@jjh32456/longlive 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (331) hide show
  1. package/CHANGELOG.md +235 -0
  2. package/LICENSE +21 -0
  3. package/QUICKSTART.md +362 -0
  4. package/README.en.md +64 -0
  5. package/README.md +256 -2
  6. package/SPEC.md +211 -0
  7. package/build-info.json +1665 -0
  8. package/cordis.patch.yml +208 -0
  9. package/docs/A1-MIGRATION.md +75 -0
  10. package/docs/ANSWER-GUARD.md +92 -0
  11. package/docs/ARCHITECTURE.md +128 -0
  12. package/docs/AUTO-RECALL-WIRING.md +115 -0
  13. package/docs/AUTO-RECALL.md +237 -0
  14. package/docs/CONCEPTS.md +143 -0
  15. package/docs/CONFIG.md +839 -0
  16. package/docs/ERRORS.md +271 -0
  17. package/docs/FAQ.md +186 -0
  18. package/docs/FEATURES.md +579 -0
  19. package/docs/INDEX-FRESHNESS.md +21 -0
  20. package/docs/METRICS.md +244 -0
  21. package/docs/MIGRATION-1.6.0.md +220 -0
  22. package/docs/OPERATIONS.md +439 -0
  23. package/docs/PANEL-INTEGRATION.md +190 -0
  24. package/docs/PRIVACY.md +88 -0
  25. package/docs/QUICKSTART.md +155 -0
  26. package/docs/RAW-INDEX-POLICY.md +7 -0
  27. package/docs/README.en.md +48 -0
  28. package/docs/RESIDENT-WATCHER.md +90 -0
  29. package/docs/SESSION-WATCH.md +214 -0
  30. package/docs/TOOLS.md +184 -0
  31. package/docs/TROUBLESHOOTING.md +329 -0
  32. package/icon.svg +11 -0
  33. package/lib/client.js +436 -0
  34. package/locale/en.json +6 -0
  35. package/locale/zh.json +6 -0
  36. package/package.json +163 -4
  37. package/runbook.md +343 -0
  38. package/scripts/archive-digest-build.mjs +668 -0
  39. package/scripts/auto-truncate-run.ps1 +752 -0
  40. package/scripts/backfill-auto-cards.mjs +98 -0
  41. package/scripts/edges-build.mjs +1003 -0
  42. package/scripts/index-maintain.mjs +39 -0
  43. package/scripts/index-reconcile.mjs +49 -0
  44. package/scripts/index-status.mjs +28 -0
  45. package/scripts/install-resident-watcher.ps1 +15 -0
  46. package/scripts/install-session-watch.ps1 +332 -0
  47. package/scripts/install-surgery-task.ps1 +174 -0
  48. package/scripts/lib/auto-truncate-run.ps1 +512 -0
  49. package/scripts/lib/session-watch-fixture.mjs +207 -0
  50. package/scripts/longlive-doctor.mjs +578 -0
  51. package/scripts/metrics-read.mjs +79 -0
  52. package/scripts/metrics-sample.mjs +215 -0
  53. package/scripts/migrate-180.mjs +163 -0
  54. package/scripts/migrate-200.mjs +8 -0
  55. package/scripts/migrate-a1-legacy.mjs +62 -0
  56. package/scripts/migrate-lifecycle.mjs +157 -0
  57. package/scripts/pack.mjs +392 -0
  58. package/scripts/recall-index-build.mjs +128 -0
  59. package/scripts/recall-links-build.mjs +420 -0
  60. package/scripts/rescore-cards.mjs +36 -0
  61. package/scripts/resident-watcher-status.ps1 +15 -0
  62. package/scripts/resident-watcher.ps1 +643 -0
  63. package/scripts/session-watch-drill.mjs +553 -0
  64. package/scripts/session-watch-status.ps1 +146 -0
  65. package/scripts/session-watch.mjs +1367 -0
  66. package/scripts/surgery-inspect.mjs +122 -0
  67. package/scripts/surgery-run.cmd +34 -0
  68. package/scripts/truncate-cli.mjs +279 -0
  69. package/scripts/unattended-surgery.ps1 +1019 -0
  70. package/scripts/uninstall-resident-watcher.ps1 +15 -0
  71. package/scripts/uninstall-session-watch.ps1 +192 -0
  72. package/scripts/verify-card-anchors.mjs +138 -0
  73. package/scripts/watch-loop.ps1 +916 -0
  74. package/src/actions/audit.js +125 -0
  75. package/src/actions/evidence.js +122 -0
  76. package/src/actions/fs.js +162 -0
  77. package/src/activity/index.js +873 -0
  78. package/src/activity/model.js +351 -0
  79. package/src/activity/store.js +786 -0
  80. package/src/activity/summary.js +180 -0
  81. package/src/activity/thinking.js +191 -0
  82. package/src/adapters/constants.js +11 -0
  83. package/src/adapters/engram/data/aliases.json +51 -0
  84. package/src/adapters/engram/data/policy.json +8 -0
  85. package/src/adapters/engram/data/routing-rules.json +546 -0
  86. package/src/adapters/engram/index.js +278 -0
  87. package/src/adapters/registry.js +315 -0
  88. package/src/answer/audit.js +238 -0
  89. package/src/answer/claim-guard.mjs +234 -0
  90. package/src/answer/evidence.js +30 -0
  91. package/src/answer/guard.js +1370 -0
  92. package/src/answer/index.js +1086 -0
  93. package/src/answer/query.js +111 -0
  94. package/src/answer/second-hop.mjs +101 -0
  95. package/src/auto-truncate-status.js +164 -0
  96. package/src/auto-truncate.js +1181 -0
  97. package/src/autoprocedure/candidate.js +342 -0
  98. package/src/autoprocedure/config.js +122 -0
  99. package/src/autoprocedure/evidence.js +345 -0
  100. package/src/autoprocedure/index.js +83 -0
  101. package/src/autoprocedure/ledger.js +329 -0
  102. package/src/autoprocedure/lint.js +232 -0
  103. package/src/autoprocedure/llm.js +409 -0
  104. package/src/autoprocedure/locks.js +102 -0
  105. package/src/autoprocedure/paths.js +39 -0
  106. package/src/autoprocedure/privacy.js +87 -0
  107. package/src/autoprocedure/rules.js +288 -0
  108. package/src/autoprocedure/runtime.js +718 -0
  109. package/src/autoprocedure/session-reader.js +328 -0
  110. package/src/backup.js +310 -0
  111. package/src/bus/bus.mjs +1446 -0
  112. package/src/codec.js +269 -0
  113. package/src/compaction/cut-engine.js +44 -0
  114. package/src/compaction/engine-core.js +1237 -0
  115. package/src/compaction/entry.js +228 -0
  116. package/src/compaction.js +230 -0
  117. package/src/conclusion.js +366 -0
  118. package/src/config.js +835 -0
  119. package/src/d6/runtime.js +517 -0
  120. package/src/d6/surface.js +181 -0
  121. package/src/deps.js +189 -0
  122. package/src/engine-status.js +141 -0
  123. package/src/features.js +1035 -0
  124. package/src/handoff/index.js +1077 -0
  125. package/src/handoff/model.js +1058 -0
  126. package/src/handoff/store.js +1233 -0
  127. package/src/heartbeat.js +385 -0
  128. package/src/home.js +16 -0
  129. package/src/host-version.js +280 -0
  130. package/src/hot-truncate-diag.js +98 -0
  131. package/src/identity/card-marker.js +281 -0
  132. package/src/identity/handover.js +845 -0
  133. package/src/identity/index.js +337 -0
  134. package/src/identity/inject-position.js +133 -0
  135. package/src/identity/writeback.js +344 -0
  136. package/src/identity.js +118 -0
  137. package/src/index.js +647 -0
  138. package/src/lifecycle/gap-clocks.js +364 -0
  139. package/src/lifecycle/index.js +269 -0
  140. package/src/lifecycle/proactive.js +1426 -0
  141. package/src/live-target.js +212 -0
  142. package/src/live.js +1603 -0
  143. package/src/log-rotation.js +153 -0
  144. package/src/memory/a1-migration.js +190 -0
  145. package/src/memory/activity-capture.js +229 -0
  146. package/src/memory/anchor-fallback.js +116 -0
  147. package/src/memory/anchors.js +194 -0
  148. package/src/memory/archive-cold-state.mjs +794 -0
  149. package/src/memory/archive-staging.mjs +305 -0
  150. package/src/memory/archive.mjs +415 -0
  151. package/src/memory/audit-records.js +222 -0
  152. package/src/memory/auto-cards.js +441 -0
  153. package/src/memory/capture-host.js +297 -0
  154. package/src/memory/capture.js +496 -0
  155. package/src/memory/card-anchors.js +203 -0
  156. package/src/memory/card-priority.js +110 -0
  157. package/src/memory/cards.js +425 -0
  158. package/src/memory/catchup.mjs +534 -0
  159. package/src/memory/conclusion-distill.js +381 -0
  160. package/src/memory/conclusion-drafts.js +243 -0
  161. package/src/memory/conflicts.js +1060 -0
  162. package/src/memory/consolidate.js +834 -0
  163. package/src/memory/decay.js +311 -0
  164. package/src/memory/distill.js +485 -0
  165. package/src/memory/event-index.js +1826 -0
  166. package/src/memory/evidence-chain.js +295 -0
  167. package/src/memory/evidence.js +213 -0
  168. package/src/memory/filter-runner.js +555 -0
  169. package/src/memory/filter.js +1035 -0
  170. package/src/memory/forget-v2.js +680 -0
  171. package/src/memory/forget.js +531 -0
  172. package/src/memory/frames-activation.js +249 -0
  173. package/src/memory/frontmatter.js +454 -0
  174. package/src/memory/fts-query.js +342 -0
  175. package/src/memory/governance.js +604 -0
  176. package/src/memory/index-freshness.js +234 -0
  177. package/src/memory/index.js +435 -0
  178. package/src/memory/l2-gate.js +169 -0
  179. package/src/memory/land.mjs +743 -0
  180. package/src/memory/lifecycle.js +235 -0
  181. package/src/memory/lock.js +121 -0
  182. package/src/memory/maintenance.js +1149 -0
  183. package/src/memory/manifest.js +245 -0
  184. package/src/memory/memory-health.mjs +607 -0
  185. package/src/memory/migrate-200.js +1681 -0
  186. package/src/memory/migrate-lifecycle.js +1808 -0
  187. package/src/memory/migrate.js +139 -0
  188. package/src/memory/paths.js +229 -0
  189. package/src/memory/procedure-candidate.mjs +377 -0
  190. package/src/memory/procedure.js +982 -0
  191. package/src/memory/prospective-memory.mjs +362 -0
  192. package/src/memory/provenance.js +119 -0
  193. package/src/memory/recall-feedback.mjs +406 -0
  194. package/src/memory/recall-v2.js +218 -0
  195. package/src/memory/recall.js +357 -0
  196. package/src/memory/reconcile.js +265 -0
  197. package/src/memory/records.js +433 -0
  198. package/src/memory/reinforce.js +281 -0
  199. package/src/memory/retention.js +162 -0
  200. package/src/memory/review.js +124 -0
  201. package/src/memory/state.js +279 -0
  202. package/src/memory/tiers.js +168 -0
  203. package/src/memory/topic-phrases.js +73 -0
  204. package/src/memory/trust.js +97 -0
  205. package/src/memory/turn-budget.mjs +290 -0
  206. package/src/memory/version-chain.js +264 -0
  207. package/src/memory/wake-bridge.mjs +2999 -0
  208. package/src/memory/wal.js +137 -0
  209. package/src/memory/working-frame.js +779 -0
  210. package/src/metrics/classify.mjs +191 -0
  211. package/src/metrics/estimate.mjs +108 -0
  212. package/src/metrics/index.mjs +204 -0
  213. package/src/metrics/measure.mjs +462 -0
  214. package/src/metrics/prestep-latency.mjs +307 -0
  215. package/src/metrics/store.mjs +264 -0
  216. package/src/original.js +294 -0
  217. package/src/policy/threshold-policy.js +224 -0
  218. package/src/policy-profile.js +463 -0
  219. package/src/recall/anaphora.mjs +87 -0
  220. package/src/recall/archive-config.mjs +130 -0
  221. package/src/recall/archive-fallback.mjs +390 -0
  222. package/src/recall/archive-search.mjs +428 -0
  223. package/src/recall/archive-state.mjs +588 -0
  224. package/src/recall/brain.mjs +501 -0
  225. package/src/recall/cards.mjs +202 -0
  226. package/src/recall/current-line.mjs +110 -0
  227. package/src/recall/edges.js +398 -0
  228. package/src/recall/embedding.mjs +698 -0
  229. package/src/recall/entities.mjs +112 -0
  230. package/src/recall/explain.mjs +443 -0
  231. package/src/recall/force-policy.mjs +138 -0
  232. package/src/recall/gate-log.mjs +280 -0
  233. package/src/recall/gate-metrics.mjs +191 -0
  234. package/src/recall/index.js +1337 -0
  235. package/src/recall/inject-order.mjs +279 -0
  236. package/src/recall/link-recall.mjs +183 -0
  237. package/src/recall/links.mjs +696 -0
  238. package/src/recall/privacy.mjs +208 -0
  239. package/src/recall/recall-core.mjs +810 -0
  240. package/src/recall/shared-visibility.js +302 -0
  241. package/src/recall/time-normalizer.mjs +196 -0
  242. package/src/recall/turn-budget-inject.mjs +154 -0
  243. package/src/retention/cold-gate.mjs +146 -0
  244. package/src/retention/config.js +163 -0
  245. package/src/retention/index.js +801 -0
  246. package/src/role/activation.js +191 -0
  247. package/src/role/attention.js +318 -0
  248. package/src/role/base.js +36 -0
  249. package/src/role/channels.js +423 -0
  250. package/src/role/index.js +425 -0
  251. package/src/role/interfaces.js +115 -0
  252. package/src/role/personality.js +370 -0
  253. package/src/role/readers.js +151 -0
  254. package/src/role/relationships.js +477 -0
  255. package/src/role/store.js +202 -0
  256. package/src/role/writeprotect.js +373 -0
  257. package/src/router/aliases.json +182 -0
  258. package/src/router/background/agent-runner.mjs +239 -0
  259. package/src/router/background/anchor.mjs +323 -0
  260. package/src/router/background/audit.mjs +337 -0
  261. package/src/router/background/budget-ledger.mjs +648 -0
  262. package/src/router/background/host-sim.mjs +451 -0
  263. package/src/router/background/index.mjs +81 -0
  264. package/src/router/background/memory.mjs +63 -0
  265. package/src/router/background/mock-llm.mjs +203 -0
  266. package/src/router/background/queue.mjs +224 -0
  267. package/src/router/background/retry.mjs +255 -0
  268. package/src/router/background/router.mjs +1459 -0
  269. package/src/router/background/stream.mjs +276 -0
  270. package/src/router/background/tool-policy.mjs +255 -0
  271. package/src/router/design-headings.json +221 -0
  272. package/src/router/face/config.mjs +155 -0
  273. package/src/router/face/context.mjs +284 -0
  274. package/src/router/face/face.mjs +466 -0
  275. package/src/router/face/identity.mjs +130 -0
  276. package/src/router/face/index.mjs +65 -0
  277. package/src/router/face/journal.mjs +119 -0
  278. package/src/router/face/llm.mjs +252 -0
  279. package/src/router/face/outbox.mjs +153 -0
  280. package/src/router/face/paths.mjs +54 -0
  281. package/src/router/judge.mjs +987 -0
  282. package/src/router/policies/generic.json +131 -0
  283. package/src/router/route.js +1766 -0
  284. package/src/router/router.mjs +535 -0
  285. package/src/router/routing-rules.json +816 -0
  286. package/src/router/run-sim.mjs +530 -0
  287. package/src/router/runtime.js +569 -0
  288. package/src/router/service/apply.mjs +1218 -0
  289. package/src/router/service/board.mjs +712 -0
  290. package/src/router/service/caller.mjs +131 -0
  291. package/src/router/service/config.mjs +361 -0
  292. package/src/router/service/context.mjs +314 -0
  293. package/src/router/service/hint.mjs +668 -0
  294. package/src/router/service/lease.mjs +494 -0
  295. package/src/router/service/live.mjs +251 -0
  296. package/src/router/service/lock.mjs +550 -0
  297. package/src/router/service/merge.mjs +255 -0
  298. package/src/router/service/model-resolve.mjs +350 -0
  299. package/src/router/service/paths.mjs +168 -0
  300. package/src/router/service/proposals.mjs +1461 -0
  301. package/src/router/service/queue.mjs +477 -0
  302. package/src/router/service/reconcile.mjs +271 -0
  303. package/src/router/service/service.mjs +2998 -0
  304. package/src/router/service/sources.mjs +352 -0
  305. package/src/router/service/status.mjs +520 -0
  306. package/src/router/service/store.mjs +476 -0
  307. package/src/router/service/ticklock.mjs +239 -0
  308. package/src/router/service/tokens.mjs +95 -0
  309. package/src/router/service/tools.mjs +248 -0
  310. package/src/router/service/wake.mjs +544 -0
  311. package/src/router/service/wal.mjs +685 -0
  312. package/src/router/shadow.mjs +821 -0
  313. package/src/surgery-recovery.js +1909 -0
  314. package/src/tool-output.js +485 -0
  315. package/src/tools.js +3262 -0
  316. package/src/truncate-visible.js +2416 -0
  317. package/src/truncate.js +999 -0
  318. package/src/ui/actions.js +1312 -0
  319. package/src/ui/flags.js +259 -0
  320. package/src/ui/panel-api.js +371 -0
  321. package/src/ui/panel-auth.js +251 -0
  322. package/src/ui/panel-integrity.js +243 -0
  323. package/src/ui/routes-readonly.js +759 -0
  324. package/src/ui/routes.js +284 -0
  325. package/src/util/append-store.js +368 -0
  326. package/src/util/local-day.js +30 -0
  327. package/src/util/redact.js +227 -0
  328. package/src/util/stale-locks.js +148 -0
  329. package/src/version.js +99 -0
  330. package/test/fixtures/pre-step-container.mjs +100 -0
  331. package/test/p1_probe.mjs +97 -0
@@ -0,0 +1,2998 @@
1
+ // RouterService —— dsh-longlive 1.1.0 的插件内后台服务(DESIGN §2)。
2
+ //
3
+ // 生命周期:
4
+ // apply() 里 createRouterService() 只保存 config(不碰 fs);
5
+ // start() 才抢实例锁、建 vault、校验审计/账本/锚、写 status,然后进入 running。
6
+ //
7
+ // 这是第 1 阶段:模型调用只走 ctx.llm.stream 的接口,测试用 MockLlm。没有可用
8
+ // provider 时明确进入 blocked(E_NO_PROVIDER),并如实写 status/审计,不假装在跑。
9
+ //
10
+ // 能力边界(必须与 REPORT 一致):
11
+ // audit/ledger/anchor 都在同一个用户可写 vault 里。校验能发现崩溃残留、半行、
12
+ // 误删、回滚和代码 bug,但同一用户蓄意重写三者无法防御;这不是安全边界。
13
+
14
+ import crypto from 'node:crypto';
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+
18
+ import { AnchorLog, readAnchor, verifyAnchor } from '../background/anchor.mjs';
19
+ import { AuditLog, readAudit } from '../background/audit.mjs';
20
+ import { BudgetLedger } from '../background/budget-ledger.mjs';
21
+ import { TaskQueue } from '../background/queue.mjs';
22
+ import { buildMessages, consumeStream } from '../background/stream.mjs';
23
+ import { computeBackoff } from '../background/retry.mjs';
24
+ import { parseAction } from '../background/router.mjs';
25
+ import { assembleContext } from './context.mjs';
26
+ import { normalizeRouterConfig } from './config.mjs';
27
+ import { InstanceLock, LOCK_RENEW_MS, STANDBY_RETRY_MS } from './lock.mjs';
28
+ import { dayKey, reconcileRuns, scanDayUsage, verifyRunAnchors } from './reconcile.mjs';
29
+ import { loadContextSources } from './sources.mjs';
30
+ import { buildStatus, KNOWN_WARNING_CODES, writeStatus } from './status.mjs';
31
+ import { createBoardBuilder, listSessionMetadata } from './board.mjs';
32
+ import { createHintInjector } from './hint.mjs';
33
+ import { createLiveWriter, scanLiveRows, sessionIdOf, stateForTurnEnd } from './live.mjs';
34
+ import { liveSweep, liveHealth } from '../../live.js';
35
+ import { createProposalEngine } from './proposals.mjs';
36
+ import { createApplier } from './apply.mjs';
37
+ import { clampLeaseTtl, computeMaxHoldMs, createWriterLease } from './lease.mjs';
38
+ import { createQueueManager } from './queue.mjs';
39
+ import { createTickLock } from './ticklock.mjs';
40
+ import { createWakeChannel } from './wake.mjs';
41
+ import { createWal } from './wal.mjs';
42
+ import { isSubagentCaller, sessionIdOfCaller } from './caller.mjs';
43
+ import {
44
+ MODEL_AUTO_PICKED_LIST_ORDER,
45
+ REASONING_EFFORT_UNSUPPORTED,
46
+ mapProviderFailure,
47
+ resolveModelTarget,
48
+ } from './model-resolve.mjs';
49
+ import { routerPaths } from './paths.mjs';
50
+ import { estimateTokens } from './tokens.mjs';
51
+
52
+ // D-CR5: a subagent session may ask at most 3 questions per rolling hour. The
53
+ // main session keeps its own (unlimited by this limiter) design quota.
54
+ const SUBAGENT_ASKS_PER_HOUR = 3;
55
+ const ASK_RATE_WINDOW_MS = 60 * 60 * 1000;
56
+
57
+ const HARD_BLOCK_CODES = new Set([
58
+ 'E_LEDGER_TAMPERED',
59
+ 'E_ANCHOR_MISSING',
60
+ 'E_VAULT_LOST',
61
+ 'E_AUDIT_WRITE',
62
+ 'E_LEDGER_WRITE',
63
+ 'E_CONTEXT_OVER_BUDGET',
64
+ ]);
65
+
66
+ const ALLOWED_ACTIONS = new Set(['note', 'report', 'noop']);
67
+
68
+ function sleep(ms) {
69
+ return new Promise((resolve) => setTimeout(resolve, ms));
70
+ }
71
+
72
+ function makeRunId(now = new Date()) {
73
+ const pad = (value) => String(value).padStart(2, '0');
74
+ const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-`
75
+ + `${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
76
+ return `run-${stamp}-${Math.random().toString(36).slice(2, 8)}`;
77
+ }
78
+
79
+ function errorMessage(error) {
80
+ if (typeof error === 'string') return error;
81
+ return error?.message ?? error?.code ?? String(error);
82
+ }
83
+
84
+ function sha256Text(text) {
85
+ return crypto.createHash('sha256').update(String(text ?? ''), 'utf8').digest('hex');
86
+ }
87
+
88
+ function clampLimit(value, min, max, fallback) {
89
+ const n = Number(value);
90
+ if (!Number.isInteger(n) || n < min) return fallback;
91
+ return Math.min(n, max);
92
+ }
93
+
94
+ /**
95
+ * 只保存 config;不读文件、不建目录、不注册钩子。默认关闭时 apply 调用它也不会产生副作用。
96
+ * @param {object} ctx
97
+ * @param {object} config
98
+ * @param {object} [deps] 测试注入:llm/queue/audit/anchor/ledger/now/runId/installTimers 等
99
+ */
100
+ export function createRouterService(ctx, config, deps = {}) {
101
+ // Test hooks are a build seam, never a configuration switch: a production
102
+ // build must not accept routerTestHooks at all (index.js asserts this).
103
+ const hooks = deps.testHooks
104
+ ?? (process.env.LONGLIVE_ROUTER_TEST === '1' ? config?.routerTestHooks : undefined);
105
+ const raw = config && typeof config === 'object' ? config : {};
106
+ // D-WP5-3: reasoningEffort is intentionally NOT a config key in 1.1.0
107
+ // (50-key ledger). Future hosts/lead may pass it through deps.
108
+ const explicitReasoningEffort = typeof deps.reasoningEffort === 'string' && deps.reasoningEffort.trim() !== ''
109
+ ? deps.reasoningEffort.trim()
110
+ : (typeof raw.reasoningEffort === 'string' && raw.reasoningEffort.trim() !== ''
111
+ ? raw.reasoningEffort.trim()
112
+ : null);
113
+ const normalized = normalizeRouterConfig(config);
114
+ const nextDeps = { ...deps, explicitReasoningEffort };
115
+ return new RouterService(ctx, normalized, hooks ? { ...nextDeps, testHooks: hooks } : nextDeps);
116
+ }
117
+
118
+ export class RouterService {
119
+ constructor(ctx, config, deps = {}) {
120
+ this.ctx = ctx ?? {};
121
+ this.config = config && typeof config === 'object' ? config : normalizeRouterConfig({});
122
+ this.deps = deps ?? {};
123
+ this.runId = this.deps.runId ?? makeRunId(this.#now());
124
+ this.startedAt = this.#iso();
125
+ this.since = this.startedAt;
126
+
127
+ this.panelState = 'stopped';
128
+ this.substate = 'idle';
129
+ this.reason = 'constructed';
130
+ this.started = false;
131
+ this.disposed = false;
132
+ this.busy = false;
133
+ this.inflight = null;
134
+ this.stopPromise = null;
135
+ this.stopRequested = false;
136
+
137
+ this.llm = null;
138
+ this.queue = null;
139
+ this.ledger = null;
140
+ this.audit = null;
141
+ this.anchor = null;
142
+ this.lock = null;
143
+ this.vaultDir = null;
144
+ this.runDir = null;
145
+ this.outboxDir = null;
146
+ this.stability = this.deps.stability ?? { enabled: true, waitMs: 50, retries: 3 };
147
+
148
+ this.seen = new Set();
149
+ this.dayUsage = null;
150
+ this.lastTickAt = null;
151
+ this.nextTickAt = null;
152
+ this.heartbeatAt = this.startedAt;
153
+ this.lastError = null;
154
+ this.lastReport = null;
155
+ this.reports = [];
156
+ this.ticks = 0;
157
+ this.processed = 0;
158
+ this.denied = 0;
159
+ this.lastIdleAt = 0;
160
+ this.consecutiveErrors = 0;
161
+ this.auditCount = 0;
162
+ this.agentMode = this.config.allowAgent === true;
163
+ this.warnings = [];
164
+ this.warnedUnknown = new Set();
165
+ this.providerInfo = {
166
+ configured: typeof this.config.provider === 'string' && this.config.provider.trim() !== '',
167
+ missing: !(typeof this.config.provider === 'string' && this.config.provider.trim() !== ''),
168
+ };
169
+ this.modelInfo = this.#initialModelInfo();
170
+ // WP5 (D-WP5-1..6): effective provider/model are resolved at start/first
171
+ // call, never guessed. providerExplicit survives normalizeRouterConfig so a
172
+ // defaulted provider is not mistaken for an explicit one.
173
+ this.effectiveProvider = this.config.provider;
174
+ this.providerSource = this.config.providerExplicit === true ? 'explicit' : 'default';
175
+ this.modelSource = this.modelInfo.auto ? null : 'explicit';
176
+ this.reasoningEffort = null;
177
+ this.explicitReasoningEffort = this.deps.explicitReasoningEffort ?? null;
178
+ this.providerCandidates = null;
179
+ this.providerWait = { attempts: 0, lastError: null, nextRetryAt: null };
180
+ this.pendingAudits = [];
181
+ this.providerListenerInstalled = false;
182
+ this.providerRetryTimer = null;
183
+ this.autoResolveTimer = null;
184
+ this.boardInfo = null;
185
+ this.proposalsInfo = null;
186
+ this.proposalEngine = null;
187
+ this.wakeInfo = null;
188
+ this.leaseInfo = null;
189
+ this.walInfo = null;
190
+
191
+ // WP2 · L1/L2(DESIGN §2.1/§2.2)。构造只记录字段;路径/监听/文件写入
192
+ // 全部推迟到 start() 之后,默认关闭时这里一个目录都不会建。
193
+ this.paths = null;
194
+ this.liveWriter = null;
195
+ this.boardBuilder = null;
196
+ this.injector = null;
197
+ this.boardSnapshot = null;
198
+ this.liveCreatedEventVia = null;
199
+ this.liveTurnEndEventVia = null;
200
+ this.liveInfo = {
201
+ rows: 0,
202
+ maxRows: Number.isInteger(this.config.liveRowsMax) ? this.config.liveRowsMax : 128,
203
+ unknown: 0,
204
+ corrupt: 0,
205
+ saturated: false,
206
+ createdEventVia: null,
207
+ turnEndEventVia: null,
208
+ };
209
+ this.sharedInfo = {
210
+ hintTokensLast: 0,
211
+ injectedTurns: 0,
212
+ injectedTokensToday: 0,
213
+ skipped: 0,
214
+ readyProposals: 0,
215
+ lastInjectAt: null,
216
+ lastInjectSha256: null,
217
+ liveRows: 0,
218
+ unknownSessions: 0,
219
+ };
220
+ // Test-only seam: only ever supplied by deps in tests (see createRouterService).
221
+ this.testHooks = this.deps.testHooks ?? null;
222
+
223
+ this.timers = new Set();
224
+ this.listenerDisposers = [];
225
+ this.tickTimer = null;
226
+ this.heartbeatTimer = null;
227
+ this.stopFileTimer = null;
228
+ this.firstTickTimer = null;
229
+ this.reflectTimer = null;
230
+ this.standbyTimer = null;
231
+ this.lastTurnReflectAt = 0;
232
+ this.abortController = null;
233
+ }
234
+
235
+ #now() {
236
+ const value = typeof this.deps.now === 'function' ? this.deps.now() : new Date();
237
+ const date = value instanceof Date ? value : new Date(value);
238
+ return Number.isFinite(date.getTime()) ? date : new Date();
239
+ }
240
+
241
+ #iso() {
242
+ return this.#now().toISOString();
243
+ }
244
+
245
+ #initialModelInfo() {
246
+ const model = this.config.model;
247
+ const auto = model === 'auto';
248
+ return {
249
+ auto,
250
+ resolved: !auto && typeof model === 'string' && model.trim() !== '' ? model : null,
251
+ resolvedAt: auto ? null : this.#iso(),
252
+ };
253
+ }
254
+
255
+ #markProviderMissing(missing = true) {
256
+ this.providerInfo = {
257
+ configured: !missing && typeof this.config.provider === 'string' && this.config.provider.trim() !== '',
258
+ missing,
259
+ };
260
+ }
261
+
262
+ #addWarning(code) {
263
+ const text = String(code ?? '').trim();
264
+ if (!text) return;
265
+ if (!this.warnings.includes(text)) this.warnings.push(text);
266
+ }
267
+
268
+ /**
269
+ * F-05: when routerAllowMissingAnchor lets the run start, the relaxation must
270
+ * be visible — a warning plus an `anchor.*` audit row, never a silent pass.
271
+ */
272
+ #auditAllowedMissingAnchors(anchors) {
273
+ const results = Array.isArray(anchors?.results) ? anchors.results : [];
274
+ const allowed = results.filter((item) => item && item.ok === true && item.anchored === false);
275
+ if (allowed.length === 0) return;
276
+ this.#addWarning('ANCHOR_MISSING_ALLOWED');
277
+ try {
278
+ this.#auditSafe('anchor.missing.allowed', {
279
+ count: allowed.length,
280
+ run_ids: allowed.map((item) => item.runId).filter(Boolean).slice(0, 20),
281
+ reason: 'routerAllowMissingAnchor',
282
+ });
283
+ } catch { /* auditing is best-effort here; the warning still stands */ }
284
+ }
285
+
286
+ #auditUnknownWarnings(warnings) {
287
+ if (!this.audit) return;
288
+ for (const code of Array.isArray(warnings) ? warnings : []) {
289
+ if (KNOWN_WARNING_CODES.includes(code)) continue;
290
+ if (this.warnedUnknown.has(code)) continue;
291
+ this.warnedUnknown.add(code);
292
+ try {
293
+ this.#audit('warn.unknown', { code: String(code).slice(0, 64) });
294
+ } catch { /* 审计失败由调用方 fail-closed,不在这里递归 */ }
295
+ }
296
+ }
297
+
298
+ #log(level, message, extra) {
299
+ try {
300
+ const logger = this.deps.logger ?? (typeof this.ctx.logger === 'function' ? this.ctx.logger() : null);
301
+ const fn = logger?.[level];
302
+ if (typeof fn === 'function') fn.call(logger, `[longlive.router] ${message}`, extra);
303
+ } catch {
304
+ /* 日志失败不影响服务 */
305
+ }
306
+ }
307
+
308
+ #timer(fn, ms) {
309
+ const handle = setTimeout(() => {
310
+ this.timers.delete(handle);
311
+ if (this.disposed) return;
312
+ try { fn(); } catch (error) { this.#failSafe(error); }
313
+ }, Math.max(0, ms));
314
+ if (typeof handle.unref === 'function') handle.unref();
315
+ this.timers.add(handle);
316
+ return handle;
317
+ }
318
+
319
+ #interval(fn, ms) {
320
+ const handle = setInterval(() => {
321
+ if (this.disposed) return;
322
+ try { fn(); } catch (error) { this.#failSafe(error); }
323
+ }, Math.max(1, ms));
324
+ if (typeof handle.unref === 'function') handle.unref();
325
+ this.timers.add(handle);
326
+ return handle;
327
+ }
328
+
329
+ #clearTimer(handle) {
330
+ if (handle === null || handle === undefined) return;
331
+ clearTimeout(handle);
332
+ this.timers.delete(handle);
333
+ }
334
+
335
+ #clearTimers() {
336
+ for (const handle of this.timers) {
337
+ try { clearTimeout(handle); } catch { /* ignore */ }
338
+ }
339
+ this.timers.clear();
340
+ this.tickTimer = null;
341
+ this.heartbeatTimer = null;
342
+ this.stopFileTimer = null;
343
+ this.firstTickTimer = null;
344
+ this.reflectTimer = null;
345
+ this.standbyTimer = null;
346
+ this.providerRetryTimer = null;
347
+ this.autoResolveTimer = null;
348
+ }
349
+
350
+ #result(extra = {}) {
351
+ let budget = null;
352
+ try { budget = this.ledger?.snapshot() ?? null; } catch { budget = null; }
353
+ return {
354
+ ok: this.panelState === 'running' || this.panelState === 'standby',
355
+ state: this.panelState,
356
+ substate: this.substate,
357
+ reason: this.reason,
358
+ runId: this.runId,
359
+ provider: this.config.provider,
360
+ model: this.config.model,
361
+ busy: this.busy,
362
+ ticks: this.ticks,
363
+ processed: this.processed,
364
+ denied: this.denied,
365
+ lastError: this.lastError,
366
+ lastReport: this.lastReport,
367
+ today: this.dayUsage,
368
+ budget: budget ? {
369
+ used: budget.used,
370
+ reserved: budget.reserved,
371
+ maxTokens: budget.maxTokens,
372
+ remaining: budget.remaining,
373
+ } : null,
374
+ ...extra,
375
+ };
376
+ }
377
+
378
+ #setState(next, reason) {
379
+ const from = this.panelState;
380
+ this.panelState = next;
381
+ this.reason = reason ?? next;
382
+ this.since = this.#iso();
383
+ if (from !== next && next !== 'standby' && this.audit) {
384
+ try { this.#audit('state.change', { from, to: next, reason: this.reason }); } catch { /* 由调用方 fail-closed */ }
385
+ }
386
+ }
387
+
388
+ #emit(kind, data = {}) {
389
+ if (!this.audit) {
390
+ const error = new Error('audit is not open');
391
+ error.code = 'E_AUDIT_WRITE';
392
+ throw error;
393
+ }
394
+ try {
395
+ const record = this.audit.append(kind, { run_id: this.runId, ...data });
396
+ this.auditCount += 1;
397
+ if (this.auditCount % 100 === 0) this.#sealAnchor();
398
+ return record;
399
+ } catch (cause) {
400
+ const error = new Error(`audit append failed: ${errorMessage(cause)}`);
401
+ error.code = 'E_AUDIT_WRITE';
402
+ error.cause = cause;
403
+ throw error;
404
+ }
405
+ }
406
+
407
+ #audit(kind, data = {}) {
408
+ return this.#emit(kind, data);
409
+ }
410
+
411
+ /** A skipped concurrent tick is evidence, not silence (H-01). */
412
+ #auditTickBusy(source, info = {}) {
413
+ try {
414
+ this.#audit('tick.busy', {
415
+ source,
416
+ tier: info.tier === 'reflect' ? 'reflect' : 'full',
417
+ reason: info.reason ?? null,
418
+ code: info.code ?? 'E_BUSY',
419
+ lock_reason: info.lockReason ?? null,
420
+ state: this.panelState,
421
+ });
422
+ } catch { /* never turn a skip into a crash */ }
423
+ }
424
+
425
+ #sealAnchor() {
426
+ if (!this.audit || !this.ledger || !this.anchor) return { ok: false, reason: 'not_ready' };
427
+ try {
428
+ const snap = this.ledger.snapshot();
429
+ // `AuditLog.seq` 是「下一条」要写的序号(append 里 seq++),锚必须指向
430
+ // 已经落盘的最后一条,否则重启时 recordAt(seq) 为空 → audit_prefix_mismatch
431
+ // → E_LEDGER_TAMPERED(P0 回归,F-03 之外的锚 off-by-one)。
432
+ const auditSeq = Number.isInteger(this.audit.seq) ? Math.max(0, this.audit.seq - 1) : 0;
433
+ const result = this.anchor.seal({
434
+ ledger: {
435
+ seq: snap.seq,
436
+ lastHash: snap.lastHash,
437
+ used: snap.used,
438
+ reserved: snap.reserved,
439
+ },
440
+ audit: {
441
+ file: this.audit.file ? path.basename(this.audit.file) : null,
442
+ seq: auditSeq,
443
+ lastHash: this.audit.lastHash ?? null,
444
+ settledUsed: snap.used,
445
+ records: auditSeq,
446
+ },
447
+ });
448
+ return result;
449
+ } catch (error) {
450
+ // DESIGN §7.3:锚写失败只告警,不阻塞 tick。
451
+ this.#log('warn', `anchor seal failed: ${errorMessage(error)}`);
452
+ return { ok: false, reason: error?.code ?? 'E_ANCHOR_WRITE' };
453
+ }
454
+ }
455
+
456
+ /**
457
+ * E-06 / G-02 / G-03:回收本 run + 所有历史 run 的崩溃遗留预留。
458
+ * 账本是按 run 分目录的,重启后新 service 只持有新 run 的账本;不扫旧 run
459
+ * 就永远释放不了子进程 reserve 后被 SIGKILL 留下的额度。
460
+ * @returns {Array<{run_id:string,scope:string,released:number,freed_tokens:number,items:Array}>}
461
+ */
462
+ #reclaimRunLedgers() {
463
+ const results = [];
464
+ const current = this.ledger.reclaimDead();
465
+ results.push({
466
+ run_id: this.runId,
467
+ scope: 'current',
468
+ released: current.released,
469
+ freed_tokens: current.freedTokens,
470
+ items: current.items,
471
+ });
472
+ const runsDir = path.join(this.vaultDir, 'runs');
473
+ let entries = [];
474
+ try { entries = fs.readdirSync(runsDir, { withFileTypes: true }); } catch { entries = []; }
475
+ for (const entry of entries) {
476
+ if (!entry.isDirectory() || entry.name === this.runId || entry.name.startsWith('.')) continue;
477
+ const file = path.join(runsDir, entry.name, 'budget.ledger.jsonl');
478
+ if (!fs.existsSync(file)) continue;
479
+ try {
480
+ const ledger = new BudgetLedger({ file, runId: entry.name, now: () => this.#iso() });
481
+ const result = ledger.reclaimDead();
482
+ if (result.released > 0) {
483
+ results.push({
484
+ run_id: entry.name,
485
+ scope: 'previous_run',
486
+ released: result.released,
487
+ freed_tokens: result.freedTokens,
488
+ items: result.items,
489
+ });
490
+ }
491
+ } catch (error) {
492
+ this.#log('warn', `reclaim of previous run ${entry.name} failed: ${errorMessage(error)}`);
493
+ }
494
+ }
495
+ return results;
496
+ }
497
+
498
+ /** 把 #reclaimRunLedgers 的结果写成一条 budget.reclaim 审计(无回收时不写)。 */
499
+ #auditBudgetReclaim(origin, results) {
500
+ const rows = Array.isArray(results) ? results.filter((row) => row.released > 0) : [];
501
+ if (rows.length === 0) return;
502
+ try {
503
+ this.#audit('budget.reclaim', {
504
+ origin,
505
+ released: rows.reduce((sum, row) => sum + row.released, 0),
506
+ freed_tokens: rows.reduce((sum, row) => sum + row.freed_tokens, 0),
507
+ charged: 0,
508
+ runs: rows,
509
+ items: rows.flatMap((row) => row.items ?? []).slice(0, 10),
510
+ });
511
+ } catch (error) {
512
+ // 回收已经落账;审计失败不能反过来把预算锁死。
513
+ this.#log('warn', `budget.reclaim audit failed: ${errorMessage(error)}`);
514
+ }
515
+ }
516
+
517
+ #statusSnapshot() {
518
+ const now = this.#iso();
519
+ let tickQueue = { pending: 0, invalid: 0, oldestAgeMs: 0 };
520
+ try {
521
+ if (this.queue) {
522
+ const view = this.queue.pending(this.seen);
523
+ tickQueue = {
524
+ pending: view.tasks.length,
525
+ invalid: view.invalid.length,
526
+ oldestAgeMs: this.#oldestAge(view.tasks),
527
+ };
528
+ }
529
+ } catch { /* status 是只读快照,失败不影响服务 */ }
530
+ let run = { usedTokens: 0, capTokens: this.config.maxTokensPerRun };
531
+ try {
532
+ const snap = this.ledger?.snapshot();
533
+ if (snap) {
534
+ run = {
535
+ usedTokens: snap.used,
536
+ capTokens: Number.isFinite(snap.maxTokens) ? snap.maxTokens : this.config.maxTokensPerRun,
537
+ };
538
+ }
539
+ } catch { /* ignore */ }
540
+ const day = this.dayUsage ?? {
541
+ day: dayKey(this.#now()),
542
+ usedTokens: 0,
543
+ reservedTokens: 0,
544
+ capTokens: this.config.maxTokensPerDay,
545
+ };
546
+ // WP3 提供提案投影;WP4 提供队列/租约/WAL 的实测快照,二者只读。
547
+ let l3 = null;
548
+ try { l3 = this.applier ? this.applier.status() : null; } catch { /* status 只读,失败降级 */ }
549
+ const proposalsBase = this.proposalEngine
550
+ ? this.proposalEngine.status()
551
+ : (this.proposalsInfo ?? {});
552
+ const proposals = l3
553
+ ? {
554
+ ...proposalsBase,
555
+ doneToday: l3.proposals.doneToday,
556
+ conflicts: l3.proposals.conflicts,
557
+ superseded: l3.proposals.superseded,
558
+ counts: l3.proposals.counts,
559
+ }
560
+ : proposalsBase;
561
+ const proposalCounts = proposals.counts ?? {};
562
+ const queue = {
563
+ pending: proposalCounts.pending ?? 0,
564
+ queued: proposalCounts.queued ?? 0,
565
+ applying: proposalCounts.applying ?? 0,
566
+ blockedOnUser: proposalCounts.blockedOnUser ?? 0,
567
+ expired: proposalCounts.expired ?? 0,
568
+ };
569
+ const board = this.boardSnapshot?.board ?? this.boardInfo ?? {};
570
+ const lease = l3?.lease ?? this.leaseInfo ?? {};
571
+ const wal = l3?.wal ?? this.walInfo ?? {};
572
+ let wakeStatus = this.wakeInfo ?? {};
573
+ try { wakeStatus = this.wakeChannel?.status?.() ?? wakeStatus; } catch { /* 只读降级 */ }
574
+ const wake = {
575
+ enabled: this.config.wakeEnabled === true,
576
+ ...wakeStatus,
577
+ };
578
+ return buildStatus({
579
+ now,
580
+ state: this.panelState,
581
+ reason: this.reason,
582
+ since: this.since,
583
+ runId: this.runId,
584
+ provider: this.providerInfo,
585
+ model: this.modelInfo,
586
+ autonomy: this.config.autonomy,
587
+ agentMode: this.agentMode,
588
+ lastTickAt: this.lastTickAt,
589
+ nextTickAt: this.nextTickAt,
590
+ heartbeatAt: now,
591
+ today: {
592
+ day: day.day,
593
+ usedTokens: day.usedTokens,
594
+ reservedTokens: day.reservedTokens,
595
+ capTokens: this.config.maxTokensPerDay,
596
+ },
597
+ run,
598
+ tickQueue,
599
+ queueStatus: queue,
600
+ liveMaxRows: this.config.liveRowsMax,
601
+ live: {
602
+ ...this.liveInfo,
603
+ createdEventVia: this.liveCreatedEventVia,
604
+ turnEndEventVia: this.liveTurnEndEventVia,
605
+ },
606
+ board: {
607
+ ...board,
608
+ pulse: {
609
+ ...(board.pulse ?? {}),
610
+ active: board.activeSessions ?? 0,
611
+ // R4.2: same projection as board.json — never a second, hardcoded
612
+ // number. Before this, status.json said 0 while board.json said 34.
613
+ running: board.pulse?.running ?? 0,
614
+ // R4.7: blocked is the same pulse field as the board's — never the
615
+ // Router's own panelState wearing the same name with another value.
616
+ // Router state is already reported as status.state.
617
+ blocked: board.pulse?.blocked ?? 0,
618
+ unknownSessions: board.unknownSessions ?? 0,
619
+ queuedProposals: proposals.queue?.depth ?? 0,
620
+ approvedProposals: proposalCounts.queued ?? 0,
621
+ blockedOnUser: queue.blockedOnUser,
622
+ readyProposals: Number(wakeStatus.readyCount ?? 0),
623
+ lastApplyAt: board.lastApplyAt ?? null,
624
+ lease: lease.active === true
625
+ ? { holder: lease.holder ?? null, since: lease.since ?? null, expiresAt: lease.expiresAt ?? null }
626
+ : null,
627
+ },
628
+ },
629
+ proposals,
630
+ lease,
631
+ wal,
632
+ shared: {
633
+ hintTokensLast: 0,
634
+ injectedTurns: 0,
635
+ injectedTokensToday: 0,
636
+ skipped: 0,
637
+ readyProposals: 0,
638
+ lastInjectAt: null,
639
+ lastInjectSha256: null,
640
+ liveRows: 0,
641
+ unknownSessions: 0,
642
+ ...(this.sharedInfo ?? {}),
643
+ },
644
+ wake,
645
+ warnings: this.warnings.slice(),
646
+ alerts: this.alerts ?? [],
647
+ lastError: this.lastError,
648
+ lastReport: this.lastReport,
649
+ files: {
650
+ vault: this.vaultDir ?? '',
651
+ board: this.paths?.boardFile ?? (this.vaultDir ? path.join(this.vaultDir, 'board.json') : ''),
652
+ audit: this.audit?.file ?? '',
653
+ ledger: this.ledger?.file ?? '',
654
+ anchor: this.anchor?.file ?? '',
655
+ outbox: this.outboxDir ?? '',
656
+ },
657
+ });
658
+ }
659
+
660
+ #writeStatus() {
661
+ if (!this.vaultDir) return { ok: false, error: 'E_NO_VAULT' };
662
+ try {
663
+ const snapshot = this.#statusSnapshot();
664
+ this.#auditUnknownWarnings(snapshot.warnings);
665
+ const file = path.join(this.vaultDir, 'status.json');
666
+ const result = writeStatus(file, snapshot);
667
+ if (!result.ok) this.#log('warn', `status write failed: ${result.error}`);
668
+ return result;
669
+ } catch (error) {
670
+ this.#log('warn', `status write failed: ${errorMessage(error)}`);
671
+ return { ok: false, error: error?.code ?? 'E_STATUS_WRITE' };
672
+ }
673
+ }
674
+
675
+ #oldestAge(tasks) {
676
+ let oldest = null;
677
+ for (const task of Array.isArray(tasks) ? tasks : []) {
678
+ const raw = task?.createdAt ?? task?.created_at;
679
+ const ts = typeof raw === 'string' ? Date.parse(raw) : (Number.isFinite(raw) ? raw : NaN);
680
+ if (!Number.isFinite(ts)) continue;
681
+ if (oldest === null || ts < oldest) oldest = ts;
682
+ }
683
+ return oldest === null ? 0 : Math.max(0, this.#now().getTime() - oldest);
684
+ }
685
+
686
+ #queueRows(tasks) {
687
+ return (Array.isArray(tasks) ? tasks : []).map((task) => {
688
+ const raw = task?.createdAt ?? task?.created_at;
689
+ const ts = typeof raw === 'string' ? Date.parse(raw) : (Number.isFinite(raw) ? raw : NaN);
690
+ return {
691
+ id: task?.id,
692
+ type: task?.type,
693
+ depth: task?.depth ?? 0,
694
+ ageMs: Number.isFinite(ts) ? Math.max(0, this.#now().getTime() - ts) : 0,
695
+ };
696
+ });
697
+ }
698
+
699
+ // WP5 (D-WP5-4): only ctx.get('llm') is a supported probe. ctx.llm may throw
700
+ // and must never be read — the host contract calls that out explicitly.
701
+ async #resolveLlm() {
702
+ this.providerListenerInstalled = this.providerListenerInstalled || false;
703
+ if (this.deps.llm !== undefined) {
704
+ this.llm = this.deps.llm;
705
+ return this.llm;
706
+ }
707
+ let llm = null;
708
+ try {
709
+ if (typeof this.ctx.get === 'function') llm = this.ctx.get('llm') ?? null;
710
+ } catch { /* 宿主没注册 llm */ }
711
+ this.llm = llm;
712
+ return llm;
713
+ }
714
+
715
+ // D-WP5-4: absence of llm is a wait state, not a terminal block. The timer is
716
+ // the safety net; `llm/adapters-updated` wakes immediately when available.
717
+ async #enterWaitingProvider(message) {
718
+ if (this.disposed) return this.#result();
719
+ this.panelState = 'waiting_provider';
720
+ this.substate = 'waiting';
721
+ this.reason = 'waiting_provider';
722
+ this.since = this.#iso();
723
+ this.lastError = null;
724
+ this.providerWait.lastError = String(message ?? 'llm service is not registered');
725
+ this.providerWait.attempts += 1;
726
+ this.#markProviderMissing(true);
727
+ this.#installProviderListener();
728
+ this.#scheduleProviderRetry();
729
+ this.providerInfo = {
730
+ ...this.providerInfo,
731
+ waitAttempts: this.providerWait.attempts,
732
+ lastError: this.providerWait.lastError,
733
+ ...(this.providerWait.nextRetryAt ? { nextRetryAt: this.providerWait.nextRetryAt } : {}),
734
+ };
735
+ this.#writeStatus();
736
+ this.#log('warn', `waiting for llm service: ${this.providerWait.lastError}`);
737
+ return this.#result();
738
+ }
739
+
740
+ #providerRetryDelayMs() {
741
+ const base = Number.isFinite(this.deps.providerRetryMs) && this.deps.providerRetryMs > 0
742
+ ? this.deps.providerRetryMs
743
+ : 30000;
744
+ const hardCap = Number.isFinite(this.deps.providerMaxRetryMs) && this.deps.providerMaxRetryMs > 0
745
+ ? Math.min(this.deps.providerMaxRetryMs, 300000)
746
+ : 300000;
747
+ const attempt = Math.max(1, this.providerWait.attempts);
748
+ return Math.min(hardCap, base * 2 ** Math.min(attempt - 1, 10));
749
+ }
750
+
751
+ #scheduleProviderRetry() {
752
+ if (this.disposed) return;
753
+ this.#clearTimer(this.providerRetryTimer);
754
+ this.providerRetryTimer = null;
755
+ const delay = this.#providerRetryDelayMs();
756
+ this.providerWait.nextRetryAt = new Date(this.#now().getTime() + delay).toISOString();
757
+ this.nextTickAt = this.providerWait.nextRetryAt;
758
+ // Tests pass installTimers:false and drive retries explicitly.
759
+ if (this.deps.installTimers === false) return;
760
+ this.providerRetryTimer = this.#timer(() => {
761
+ this.providerRetryTimer = null;
762
+ this.#runProviderRetry().catch((error) => this.#failSafe(error));
763
+ }, delay);
764
+ }
765
+
766
+ async #runProviderRetry() {
767
+ if (this.disposed) return;
768
+ const waiting = this.panelState === 'waiting_provider';
769
+ const recoverableBlock = this.panelState === 'blocked' && this.lastError?.code === 'E_NO_PROVIDER';
770
+ if (!waiting && !recoverableBlock) return;
771
+ this.panelState = 'starting';
772
+ this.substate = 'starting';
773
+ this.reason = 'provider_retry';
774
+ this.lastError = null;
775
+ this.providerInfo = {
776
+ configured: typeof this.config.provider === 'string' && this.config.provider.trim() !== '',
777
+ missing: true,
778
+ waitAttempts: this.providerWait.attempts,
779
+ ...(this.providerWait.lastError ? { lastError: this.providerWait.lastError } : {}),
780
+ };
781
+ try {
782
+ await this.#start();
783
+ } catch (error) {
784
+ await this.block(error?.code ?? 'E_START_FAILED', error);
785
+ }
786
+ }
787
+
788
+ // Public test seam: same path as the timer, without waiting for it.
789
+ async retryProviderNow() {
790
+ return this.#runProviderRetry();
791
+ }
792
+
793
+ async handleProviderAdaptersUpdated() {
794
+ if (this.disposed) return;
795
+ if (this.panelState === 'waiting_provider'
796
+ || (this.panelState === 'blocked' && this.lastError?.code === 'E_NO_PROVIDER')) {
797
+ this.#clearTimer(this.providerRetryTimer);
798
+ this.providerRetryTimer = null;
799
+ return this.#runProviderRetry();
800
+ }
801
+ if (this.panelState === 'running' && this.modelInfo?.auto === true) {
802
+ this.#scheduleAutoReResolve();
803
+ }
804
+ return undefined;
805
+ }
806
+
807
+ #installProviderListener() {
808
+ if (this.providerListenerInstalled || this.deps.installListener === false) return;
809
+ if (typeof this.ctx?.on !== 'function') return;
810
+ try {
811
+ const dispose = this.ctx.on('llm/adapters-updated', () => {
812
+ this.handleProviderAdaptersUpdated().catch((error) => this.#failSafe(error));
813
+ }, { prepend: false });
814
+ if (typeof dispose === 'function') this.listenerDisposers.push(dispose);
815
+ this.providerListenerInstalled = true;
816
+ } catch (error) {
817
+ this.#log('warn', `llm/adapters-updated listener failed: ${errorMessage(error)}`);
818
+ }
819
+ }
820
+
821
+ #scheduleAutoReResolve() {
822
+ if (this.disposed || this.autoResolveTimer) return;
823
+ const delay = 200; // host contract: 100–500ms debounce
824
+ if (this.deps.installTimers === false) return;
825
+ this.autoResolveTimer = this.#timer(() => {
826
+ this.autoResolveTimer = null;
827
+ this.#reResolveAutoModel().catch((error) => this.#failSafe(error));
828
+ }, delay);
829
+ }
830
+
831
+ async #reResolveAutoModel() {
832
+ if (this.disposed || this.panelState !== 'running' || this.modelInfo?.auto !== true) return;
833
+ const previous = this.modelInfo.resolved;
834
+ const target = await resolveModelTarget({
835
+ config: this.config,
836
+ ctx: this.ctx,
837
+ llm: this.llm,
838
+ explicitReasoningEffort: this.explicitReasoningEffort,
839
+ });
840
+ if (!target.ok) {
841
+ this.#addWarning('MODEL_AUTO_UNRESOLVED');
842
+ this.#writeStatus();
843
+ return;
844
+ }
845
+ if (!target.auto) return;
846
+ if (target.model !== previous || target.provider !== this.effectiveProvider) {
847
+ this.#applyModelTarget(target);
848
+ this.#auditSafe('model.auto_resolved', {
849
+ run_id: this.runId,
850
+ from: previous,
851
+ to: target.model,
852
+ provider: target.provider,
853
+ source: target.modelSource,
854
+ });
855
+ this.#writeStatus();
856
+ this.#log('info', `model auto re-resolved to ${target.model}`);
857
+ }
858
+ }
859
+
860
+ #applyModelTarget(target) {
861
+ this.effectiveProvider = target.provider;
862
+ this.providerSource = target.providerSource;
863
+ this.providerCandidates = Array.isArray(target.providerCandidates) ? target.providerCandidates.slice() : null;
864
+ this.modelInfo = {
865
+ auto: target.auto === true,
866
+ resolved: target.model,
867
+ resolvedAt: this.#iso(),
868
+ };
869
+ this.modelSource = target.modelSource;
870
+ this.reasoningEffort = target.reasoningEffort ?? null;
871
+ for (const code of Array.isArray(target.warnings) ? target.warnings : []) this.#addWarning(code);
872
+ if (target.unlisted === true) {
873
+ this.pendingAudits.push(['model.unlisted', {
874
+ model: target.model,
875
+ provider: target.provider,
876
+ source: 'explicit',
877
+ candidates: Array.isArray(target.candidates) ? target.candidates.slice(0, 20) : [],
878
+ }]);
879
+ }
880
+ if (target.auto === true) {
881
+ this.pendingAudits.push(['model.auto_resolved', {
882
+ model: target.model,
883
+ provider: target.provider,
884
+ source: target.modelSource,
885
+ ...(target.reasoningEffort ? { reasoning_effort: target.reasoningEffort } : {}),
886
+ }]);
887
+ }
888
+ if (target.warnings.includes(MODEL_AUTO_PICKED_LIST_ORDER)) {
889
+ this.pendingAudits.push(['model.auto_list_order', {
890
+ model: target.model,
891
+ provider: target.provider,
892
+ }]);
893
+ }
894
+ if (target.warnings.includes(REASONING_EFFORT_UNSUPPORTED)) {
895
+ this.pendingAudits.push(['model.reasoning_effort_unsupported', {
896
+ provider: target.provider,
897
+ model: target.model,
898
+ }]);
899
+ }
900
+ }
901
+
902
+ #flushPendingAudits() {
903
+ if (!this.audit || this.pendingAudits.length === 0) return;
904
+ const pending = this.pendingAudits.splice(0);
905
+ for (const [kind, data] of pending) this.#auditSafe(kind, { run_id: this.runId, ...data });
906
+ }
907
+
908
+ // Vault 目录是 status.json 的落点。provider 缺失/非法时也要先有目录,否则
909
+ // waiting_provider/blocked 写 status 会静默失败(面板看不到状态)。
910
+ #initVaultDir() {
911
+ const memoryRoot = this.config.memoryRoot ?? this.deps.memoryRoot ?? null;
912
+ const vaultDir = this.config.vaultDir
913
+ ? path.resolve(this.config.vaultDir)
914
+ : (typeof memoryRoot === 'string' && memoryRoot.trim() !== ''
915
+ ? path.join(path.resolve(memoryRoot), '.longlive', 'router')
916
+ : null);
917
+ if (!vaultDir) {
918
+ const error = new Error('router vault needs memoryRoot or routerVaultDir');
919
+ error.code = 'E_NO_MEMORY_ROOT';
920
+ throw error;
921
+ }
922
+ this.vaultDir = vaultDir;
923
+ fs.mkdirSync(vaultDir, { recursive: true });
924
+ return vaultDir;
925
+ }
926
+
927
+ #initPaths() {
928
+ const vaultDir = this.#initVaultDir();
929
+ this.runDir = path.join(vaultDir, 'runs', this.runId);
930
+ this.outboxDir = path.join(vaultDir, 'outbox');
931
+ fs.mkdirSync(this.runDir, { recursive: true });
932
+ fs.mkdirSync(this.outboxDir, { recursive: true });
933
+
934
+ const now = () => this.#iso();
935
+ this.lock = new InstanceLock({
936
+ file: path.join(vaultDir, 'router.lock'),
937
+ runId: this.runId,
938
+ leaseMs: this.deps.lockLeaseMs ?? 30000,
939
+ now: () => this.#now(),
940
+ });
941
+ this.queue = this.deps.queue ?? new TaskQueue({
942
+ file: path.join(vaultDir, 'queue.jsonl'),
943
+ maxTasks: this.deps.maxTasks ?? 200,
944
+ maxBytes: this.config.queueMaxBytes,
945
+ });
946
+ this.ledger = this.deps.ledger ?? new BudgetLedger({
947
+ file: path.join(this.runDir, 'budget.ledger.jsonl'),
948
+ runId: this.runId,
949
+ maxTokens: this.config.maxTokensPerRun,
950
+ now,
951
+ reservationLeaseMs: this.deps.reservationLeaseMs ?? 60000,
952
+ });
953
+ this.audit = this.deps.audit ?? new AuditLog({
954
+ file: path.join(vaultDir, 'audit.jsonl'),
955
+ runId: this.runId,
956
+ now,
957
+ });
958
+ this.anchor = this.deps.anchor ?? new AnchorLog({
959
+ file: this.config.anchorPath ? path.resolve(this.config.anchorPath) : path.join(this.runDir, 'anchor.jsonl'),
960
+ now,
961
+ });
962
+ this.#initL2();
963
+ }
964
+
965
+ /**
966
+ * WP2 wiring. Pure constructors: no directory is created and no listener is
967
+ * registered here; the board file only appears on the first tick/pre-step.
968
+ */
969
+ #initL2() {
970
+ const memoryRoot = this.config.memoryRoot ?? this.deps.memoryRoot ?? null;
971
+ this.paths = routerPaths({ memoryRoot, vaultDir: this.vaultDir });
972
+ try {
973
+ this.liveWriter = createLiveWriter({
974
+ memoryRoot: this.paths.liveRoot,
975
+ maxRows: this.config.liveRowsMax,
976
+ now: () => this.#now(),
977
+ audit: (kind, data) => this.#audit(kind, data),
978
+ onWarning: (code) => this.#addWarning(code),
979
+ logger: (message) => this.#log('warn', message),
980
+ });
981
+ } catch (error) {
982
+ this.liveWriter = null;
983
+ this.#log('warn', `live writer init failed: ${errorMessage(error)}`);
984
+ }
985
+ // Startup sweep: dead same-host rows (>4x ttl) move to the tombstone ledger
986
+ // before removal; stale rows stay visible in health/status.
987
+ try {
988
+ const swept = liveSweep({ autoCleanup: true }, { memoryRoot: this.paths.liveRoot, now: this.#now() });
989
+ this.liveSweepInfo = { stale: swept.stale, dead: swept.dead, removed: swept.removed.length, tombstoned: swept.tombstoned };
990
+ if (swept.removed.length > 0) this.#auditSafe('live.sweep', { removed: swept.removed.length, stale: swept.stale, dead: swept.dead });
991
+ } catch (error) {
992
+ this.liveSweepInfo = null;
993
+ this.#log('warn', `live startup sweep failed: ${errorMessage(error)}`);
994
+ }
995
+ try {
996
+ this.boardBuilder = createBoardBuilder({
997
+ memoryRoot: this.paths.liveRoot,
998
+ config: this.config,
999
+ now: () => this.#now(),
1000
+ paths: this.paths,
1001
+ });
1002
+ } catch (error) {
1003
+ this.boardBuilder = null;
1004
+ this.#log('warn', `board builder init failed: ${errorMessage(error)}`);
1005
+ }
1006
+ try {
1007
+ this.injector = createHintInjector({
1008
+ ctx: this.ctx,
1009
+ config: this.config,
1010
+ now: () => this.#now(),
1011
+ audit: (kind, data) => this.#audit(kind, data),
1012
+ onInject: (info) => this.#onInject(info),
1013
+ onSkip: () => { this.sharedInfo.skipped += 1; },
1014
+ onWarning: (code) => this.#addWarning(code),
1015
+ logger: (message) => this.#log('warn', message),
1016
+ boardProvider: () => this.#boardForInjection(),
1017
+ injectStateDir: this.paths.injectStateDir,
1018
+ // v1 bridge: shared IDENTITY.md + router-face outbox live under memoryRoot.
1019
+ memoryRoot,
1020
+ testHooks: this.testHooks,
1021
+ installListener: this.deps.installListener !== false,
1022
+ });
1023
+ } catch (error) {
1024
+ this.injector = null;
1025
+ this.#log('warn', `hint injector init failed: ${errorMessage(error)}`);
1026
+ }
1027
+ if (this.config.proposalEnabled === true) {
1028
+ try {
1029
+ this.proposalEngine = createProposalEngine({
1030
+ config: this.config,
1031
+ paths: this.paths,
1032
+ memoryRoot: this.paths.liveRoot,
1033
+ audit: (kind, data) => this.#audit(kind, data),
1034
+ now: () => this.#now(),
1035
+ logger: (message) => this.#log('warn', message),
1036
+ });
1037
+ // Read-only warm-up; the proposals directory is only created by the
1038
+ // first real propose (DESIGN §5.1 / K13 default-off contract).
1039
+ this.proposalsInfo = this.proposalEngine.status();
1040
+ // WP4: queue/lease/WAL/wake/tick-lock live beside the proposal store.
1041
+ const audit = (kind, data) => this.#audit(kind, data);
1042
+ const logger = (message) => this.#log('warn', message);
1043
+ const now = () => this.#now();
1044
+ const locksDir = path.join(this.vaultDir, 'locks');
1045
+ this.wal = createWal({
1046
+ file: this.proposalEngine.walFile,
1047
+ audit,
1048
+ logger,
1049
+ maxBytes: this.config.walMaxBytes,
1050
+ now,
1051
+ });
1052
+ this.lease = createWriterLease({
1053
+ file: path.join(locksDir, 'writer.lease.json'),
1054
+ lockDir: locksDir,
1055
+ ttlMs: clampLeaseTtl(this.config.writerLeaseMs),
1056
+ renewalsMax: this.config.leaseRenewMax,
1057
+ holder: { sessionId: 'router-service', runId: this.runId, pid: process.pid, host: 'local' },
1058
+ now,
1059
+ audit,
1060
+ });
1061
+ this.queueManager = createQueueManager({ paths: this.paths, config: this.config, wal: this.wal, audit, now });
1062
+ this.wakeChannel = createWakeChannel({ vaultDir: this.vaultDir, config: this.config, now, audit, logger });
1063
+ this.tickLock = createTickLock({
1064
+ file: path.join(this.vaultDir, 'tick.lock'),
1065
+ maxHoldMs: computeMaxHoldMs(clampLeaseTtl(this.config.writerLeaseMs), this.config.leaseRenewMax),
1066
+ now,
1067
+ audit,
1068
+ });
1069
+ this.applier = createApplier({
1070
+ paths: this.paths,
1071
+ vaultDir: this.vaultDir,
1072
+ memoryRoot: this.paths.liveRoot,
1073
+ config: this.config,
1074
+ lease: this.lease,
1075
+ wal: this.wal,
1076
+ queue: this.queueManager,
1077
+ wake: this.wakeChannel,
1078
+ audit,
1079
+ now,
1080
+ logger,
1081
+ testHooks: this.testHooks,
1082
+ caller: { kind: 'root', sessionId: 'router-service' },
1083
+ // D-CR17: apply/rollback warnings must reach status().warnings.
1084
+ onWarning: (code) => this.#addWarning(code),
1085
+ });
1086
+ this.proposalEngine.applier = this.applier;
1087
+ this.proposalEngine.wake = this.wakeChannel;
1088
+ this.proposalEngine.lease = this.lease;
1089
+ this.wakeInfo = this.wakeChannel.status();
1090
+ this.proposalsInfo = this.applier.status().proposals;
1091
+ } catch (error) {
1092
+ this.proposalEngine = null;
1093
+ this.#log('warn', `proposal engine init failed: ${errorMessage(error)}`);
1094
+ }
1095
+ }
1096
+ }
1097
+
1098
+ #auditSafe(kind, data = {}) {
1099
+ try { this.#audit(kind, data); } catch { /* L1/L2 diagnostics never block a turn */ }
1100
+ }
1101
+
1102
+ /**
1103
+ * L-03 restart rebuild. Idempotent: on a healthy vault `rebuild()` sees a
1104
+ * queue that already matches the proposal files and writes nothing.
1105
+ */
1106
+ #restoreProposalQueue() {
1107
+ if (!this.queueManager || !this.proposalEngine) return;
1108
+ try {
1109
+ const rebuilt = this.queueManager.rebuild();
1110
+ if (rebuilt.written || rebuilt.recovered.length > 0 || rebuilt.orphans.length > 0) {
1111
+ this.#auditSafe('queue.restored', {
1112
+ written: rebuilt.written === true,
1113
+ depth: rebuilt.depth ?? null,
1114
+ nonTerminal: rebuilt.nonTerminal ?? null,
1115
+ recovered: rebuilt.recovered.length,
1116
+ orphans: rebuilt.orphans.length,
1117
+ });
1118
+ }
1119
+ this.proposalsInfo = this.proposalEngine.status();
1120
+ } catch (error) {
1121
+ this.#log('warn', `proposal queue restore failed: ${errorMessage(error)}`);
1122
+ }
1123
+ }
1124
+
1125
+ async #boardForInjection() {
1126
+ try {
1127
+ await this.#refreshL2({ write: true });
1128
+ } catch (error) {
1129
+ this.#log('warn', `board refresh for injection failed: ${errorMessage(error)}`);
1130
+ }
1131
+ return this.boardSnapshot?.board ?? null;
1132
+ }
1133
+
1134
+ /**
1135
+ * Rebuild the read-only board projection from live rows + session metadata.
1136
+ * Never throws: a broken live directory degrades to LIVE_UNREADABLE and the
1137
+ * tick continues (DESIGN §2.1).
1138
+ */
1139
+ async #refreshL2({ write = true } = {}) {
1140
+ if (!this.boardBuilder || this.disposed) return null;
1141
+ try { this.boardBuilder.cleanTmp?.(); } catch { /* tmp hygiene is best-effort */ }
1142
+ let metadata = null;
1143
+ try {
1144
+ metadata = await listSessionMetadata(this.ctx);
1145
+ } catch {
1146
+ metadata = null;
1147
+ }
1148
+ let snapshot;
1149
+ try {
1150
+ snapshot = this.boardBuilder.build({
1151
+ metadata,
1152
+ saturated: this.liveWriter?.saturated === true,
1153
+ });
1154
+ } catch (error) {
1155
+ this.#log('warn', `board build failed: ${errorMessage(error)}`);
1156
+ return null;
1157
+ }
1158
+ this.boardSnapshot = snapshot;
1159
+ let liveHealthInfo = null;
1160
+ try { liveHealthInfo = liveHealth(this.paths.liveRoot, { now: this.#now() }); } catch { liveHealthInfo = null; }
1161
+ this.liveInfo = {
1162
+ ...this.liveInfo,
1163
+ rows: snapshot.live.rows,
1164
+ maxRows: snapshot.live.maxRows,
1165
+ unknown: snapshot.live.unknown,
1166
+ corrupt: snapshot.live.corrupt,
1167
+ saturated: snapshot.live.saturated,
1168
+ ...(liveHealthInfo ? {
1169
+ active: liveHealthInfo.active,
1170
+ stale: liveHealthInfo.stale,
1171
+ dead: liveHealthInfo.dead,
1172
+ tombstoned: liveHealthInfo.tombstoned,
1173
+ } : {}),
1174
+ createdEventVia: this.liveCreatedEventVia,
1175
+ turnEndEventVia: this.liveTurnEndEventVia,
1176
+ };
1177
+ const priorHintTokens = this.sharedInfo?.hintTokensLast;
1178
+ const injected = this.#aggregateInjected();
1179
+ this.sharedInfo = {
1180
+ ...this.sharedInfo,
1181
+ ...snapshot.shared,
1182
+ ...injected,
1183
+ };
1184
+ // The board projection is a disk snapshot; it must never overwrite the
1185
+ // live injection counters with its placeholder zero (M-01).
1186
+ if (!Number.isInteger(injected.hintTokensLast) && Number.isInteger(priorHintTokens)) {
1187
+ this.sharedInfo.hintTokensLast = priorHintTokens;
1188
+ }
1189
+ if (write && this.config.sharedBoard === true) {
1190
+ try {
1191
+ const written = this.boardBuilder.write(snapshot);
1192
+ if (!written.ok) {
1193
+ this.#log('warn', `board write failed: ${written.code}`);
1194
+ this.#auditSafe('write.board_failed', { code: written.code ?? null });
1195
+ }
1196
+ } catch (error) {
1197
+ this.#log('warn', `board write failed: ${errorMessage(error)}`);
1198
+ }
1199
+ }
1200
+ return snapshot;
1201
+ }
1202
+
1203
+ #aggregateInjected() {
1204
+ try {
1205
+ return this.injector?.aggregate() ?? {};
1206
+ } catch {
1207
+ return {};
1208
+ }
1209
+ }
1210
+
1211
+ /**
1212
+ * WP6 Tier B actor (DESIGN §5.13). Reached only when both
1213
+ * routerProposalEnabled and routerWakeEnabled are true, so the default-off
1214
+ * tick path performs zero wake work. Host seams are injectable through deps
1215
+ * (sessionController / createUserMessage / flushSessions / sessionLogSize /
1216
+ * wakeSessions); §6.6 #6 froze them for the mock contract.
1217
+ */
1218
+ async #runWakeTierB() {
1219
+ const deps = this.deps ?? {};
1220
+ const getService = async (key) => {
1221
+ try {
1222
+ if (typeof this.ctx?.get !== 'function') return null;
1223
+ return await this.ctx.get(key);
1224
+ } catch {
1225
+ return null;
1226
+ }
1227
+ };
1228
+
1229
+ let sessions = Array.isArray(deps.wakeSessions) ? deps.wakeSessions : null;
1230
+ if (!sessions) {
1231
+ const metadata = await listSessionMetadata(this.ctx).catch(() => null);
1232
+ if (!metadata) {
1233
+ this.#auditSafe('wake.skipped', { reason: 'metadata-unavailable' });
1234
+ return { ok: false, reason: 'metadata-unavailable' };
1235
+ }
1236
+ const metaById = new Map(metadata.map((item) => [item.sessionId, item]));
1237
+ const live = scanLiveRows({ memoryRoot: this.paths.liveRoot, now: this.#now() });
1238
+ sessions = live.entries
1239
+ .filter((entry) => entry && !entry.corrupt && typeof entry.sessionId === 'string')
1240
+ .map((entry) => {
1241
+ const meta = metaById.get(entry.sessionId) ?? null;
1242
+ return {
1243
+ sessionId: entry.sessionId,
1244
+ // Raw row state: Tier B never uses effectiveState (DESIGN §5.13).
1245
+ state: entry.state,
1246
+ origin: meta?.origin ?? null,
1247
+ parentSessionId: meta?.parentSession ?? null,
1248
+ isSubagent: meta?.origin === 'subagent',
1249
+ };
1250
+ });
1251
+ }
1252
+
1253
+ const sessionController = deps.sessionController ?? await getService('sessionController');
1254
+ const sessionsService = deps.flushSessions ? null : await getService('sessions');
1255
+ const flush = typeof deps.flushSessions === 'function'
1256
+ ? deps.flushSessions
1257
+ : (typeof sessionsService?.flush === 'function' ? (session) => sessionsService.flush(session) : null);
1258
+
1259
+ let createUserMessage = typeof deps.createUserMessage === 'function' ? deps.createUserMessage : null;
1260
+ if (!createUserMessage) {
1261
+ try {
1262
+ const llm = await import('@deepseek-ai/dsh-llm');
1263
+ if (typeof llm.createUserMessage === 'function') createUserMessage = (input) => llm.createUserMessage(input);
1264
+ } catch { /* runCycle falls back to an equivalent durable shape */ }
1265
+ }
1266
+
1267
+ let sessionLogSize = typeof deps.sessionLogSize === 'function' ? deps.sessionLogSize : null;
1268
+ if (!sessionLogSize && typeof deps.sessionLogPath === 'function') {
1269
+ sessionLogSize = (sessionId) => {
1270
+ const file = deps.sessionLogPath(sessionId);
1271
+ if (!file) return null;
1272
+ try { return fs.statSync(file).size; } catch { return null; }
1273
+ };
1274
+ }
1275
+
1276
+ const result = await this.wakeChannel.runCycle({
1277
+ sessions,
1278
+ sessionController,
1279
+ createUserMessage,
1280
+ flush,
1281
+ sessionLogSize,
1282
+ });
1283
+ if (result?.failed || result?.denied?.some((item) => item.code === 'E_WAKE_LOG_TOO_LARGE')) {
1284
+ // status.wake.lastError already carries the reason; do not flip the switch.
1285
+ this.#log('warn', `wake cycle: ${result?.reason ?? 'unknown'}`);
1286
+ }
1287
+ return result;
1288
+ }
1289
+
1290
+ #onInject(info) {
1291
+ if (!info) return;
1292
+ const tokens = Number.isInteger(info.tokens) ? info.tokens : 0;
1293
+ this.sharedInfo = {
1294
+ ...this.sharedInfo,
1295
+ hintTokensLast: tokens,
1296
+ injectedTurns: (Number.isInteger(this.sharedInfo.injectedTurns) ? this.sharedInfo.injectedTurns : 0) + 1,
1297
+ injectedTokensToday: (Number.isInteger(this.sharedInfo.injectedTokensToday) ? this.sharedInfo.injectedTokensToday : 0) + tokens,
1298
+ lastInjectAt: info.at ?? null,
1299
+ lastInjectSha256: typeof info.sha256 === 'string' ? info.sha256 : null,
1300
+ };
1301
+ }
1302
+
1303
+ #readPriorStatus() {
1304
+ if (!this.vaultDir) return null;
1305
+ try {
1306
+ return JSON.parse(fs.readFileSync(path.join(this.vaultDir, 'status.json'), 'utf8'));
1307
+ } catch {
1308
+ return null;
1309
+ }
1310
+ }
1311
+
1312
+ async #refreshDayUsage({ initial = false } = {}) {
1313
+ const today = dayKey(this.#now());
1314
+ const prior = this.#readPriorStatus();
1315
+ const priorUsed = prior && prior.today?.day === today
1316
+ ? Number(prior.today.usedTokens) || 0
1317
+ : 0;
1318
+ // 日窗口滚动:只继承同一个本地日内已经计过的用量;换日即从零开始。
1319
+ const carryUsed = this.dayUsage?.day === today ? this.dayUsage.usedTokens : 0;
1320
+ const scan = scanDayUsage({
1321
+ vaultDir: this.vaultDir,
1322
+ now: this.#now(),
1323
+ statusTodayUsed: Math.max(priorUsed, carryUsed),
1324
+ });
1325
+ if (scan.tampered) {
1326
+ this.#addWarning('E_LEDGER_TAMPERED');
1327
+ await this.block('E_LEDGER_TAMPERED', 'ledger bad line / broken hash chain');
1328
+ return false;
1329
+ }
1330
+ if (scan.clockRegression) {
1331
+ this.#addWarning('CLOCK_REGRESSION');
1332
+ try { this.#audit('clock.regression', { day: scan.day, status_used: scan.statusUsed, scanned_used: scan.scannedSettled }); } catch { /* optional */ }
1333
+ }
1334
+ this.dayUsage = {
1335
+ day: scan.day,
1336
+ usedTokens: scan.used,
1337
+ reservedTokens: scan.reserved,
1338
+ capTokens: this.config.maxTokensPerDay,
1339
+ runs: scan.runs,
1340
+ };
1341
+ return true;
1342
+ }
1343
+
1344
+ async #start() {
1345
+ // 先用最小步骤建 vault 目录:后面无论进入 waiting_provider 还是 blocked,
1346
+ // 都要能把 status.json 写出来(VM B-03/B-05、面板可见性都依赖这一点)。
1347
+ try {
1348
+ this.#initVaultDir();
1349
+ } catch (error) {
1350
+ await this.block(error?.code ?? 'E_VAULT_WRITE', errorMessage(error));
1351
+ return;
1352
+ }
1353
+
1354
+ const llm = await this.#resolveLlm();
1355
+ this.#installProviderListener();
1356
+ if (!llm || typeof llm.stream !== 'function') {
1357
+ return this.#enterWaitingProvider('no llm service is registered (ctx.get("llm") is empty)');
1358
+ }
1359
+
1360
+ // WP5 D-WP5-1/2/3/6:显式 > 宿主当前默认 > listModels 首个非 preview >
1361
+ // blocked(E_NO_PROVIDER)+candidates。解析器绝不猜版本、也绝不回退写死 id。
1362
+ const target = await resolveModelTarget({
1363
+ config: this.config,
1364
+ ctx: this.ctx,
1365
+ llm,
1366
+ explicitReasoningEffort: this.explicitReasoningEffort,
1367
+ });
1368
+ if (!target.ok) {
1369
+ this.#markProviderMissing(true);
1370
+ await this.block(target.code ?? 'E_NO_PROVIDER', target.message ?? 'no usable provider/model');
1371
+ return;
1372
+ }
1373
+ this.#applyModelTarget(target);
1374
+ this.#markProviderMissing(false);
1375
+ this.providerWait = { attempts: this.providerWait.attempts, lastError: null, nextRetryAt: null };
1376
+ this.nextTickAt = null;
1377
+
1378
+ try {
1379
+ this.#initPaths();
1380
+ } catch (error) {
1381
+ await this.block(error?.code ?? 'E_VAULT_WRITE', errorMessage(error));
1382
+ return;
1383
+ }
1384
+
1385
+ const lockResult = this.lock.acquire();
1386
+ if (!lockResult.ok) {
1387
+ this.#setState('standby', 'standby');
1388
+ this.#writeStatus();
1389
+ this.#scheduleStandbyRetry();
1390
+ return;
1391
+ }
1392
+
1393
+ let reclaimed = null;
1394
+ try {
1395
+ this.ledger.repairTail();
1396
+ this.audit.open();
1397
+ this.anchor.repairTail();
1398
+ reclaimed = this.#reclaimRunLedgers();
1399
+ } catch (error) {
1400
+ await this.block(error?.code ?? 'E_LEDGER_WRITE', errorMessage(error));
1401
+ return;
1402
+ }
1403
+
1404
+ this.#flushPendingAudits();
1405
+
1406
+ const auditRead = readAudit(this.audit.file);
1407
+ if (auditRead.tamperedLines > 0 || auditRead.badLines > 0 || auditRead.chainBreaks.length > 0) {
1408
+ this.#addWarning('E_LEDGER_TAMPERED');
1409
+ await this.block('E_LEDGER_TAMPERED', `audit chain is not clean (bad=${auditRead.badLines}, breaks=${auditRead.chainBreaks.length})`);
1410
+ return;
1411
+ }
1412
+
1413
+ // E-06/G-02/G-03:回收结果必须在审计洁净检查之后落账,避免往坏链上追加。
1414
+ this.#auditBudgetReclaim('startup', reclaimed);
1415
+
1416
+ // L-03: a restart must not inherit a stale queue view. `proposals/*.json`
1417
+ // is the source of truth; `proposals/queue.json` is a derived cache that a
1418
+ // crash between "write proposal" and "write queue" can leave behind. Build
1419
+ // it once, before the first tick, so `list`, `queue` and `status` agree the
1420
+ // moment the service is up (an approved row must never be listed as pending).
1421
+ this.#restoreProposalQueue();
1422
+
1423
+ if (lockResult.takeover) {
1424
+ try { this.#audit('lock.takeover', { previous_run: lockResult.previous?.runId ?? null }); } catch { /* start will fail below */ }
1425
+ }
1426
+
1427
+ const reconciled = reconcileRuns({
1428
+ vaultDir: this.vaultDir,
1429
+ audit: this.audit,
1430
+ auditRecords: auditRead.records,
1431
+ });
1432
+ if (!reconciled.ok) {
1433
+ this.#addWarning(reconciled.code ?? 'E_LEDGER_TAMPERED');
1434
+ await this.block(reconciled.code ?? 'E_LEDGER_TAMPERED', 'audit/ledger reconcile failed');
1435
+ return;
1436
+ }
1437
+
1438
+ const anchors = verifyRunAnchors({
1439
+ vaultDir: this.vaultDir,
1440
+ auditRecords: readAudit(this.audit.file).records,
1441
+ auditFile: this.audit.file,
1442
+ allowMissingAnchor: this.config.allowMissingAnchor,
1443
+ verifyAnchor,
1444
+ readAnchor,
1445
+ });
1446
+ if (!anchors.ok) {
1447
+ this.#addWarning(anchors.code ?? 'E_LEDGER_TAMPERED');
1448
+ await this.block(anchors.code ?? 'E_LEDGER_TAMPERED', `anchor verification failed: ${anchors.failure?.reason ?? 'unknown'}`);
1449
+ return;
1450
+ }
1451
+ this.#auditAllowedMissingAnchors(anchors);
1452
+
1453
+ const dayOk = await this.#refreshDayUsage({ initial: true });
1454
+ if (!dayOk) return;
1455
+
1456
+ try {
1457
+ this.#setState('running', 'started');
1458
+ this.#audit('router.start', {
1459
+ run_id: this.runId,
1460
+ provider: this.effectiveProvider,
1461
+ provider_source: this.providerSource,
1462
+ model: this.modelInfo.resolved ?? this.config.model,
1463
+ model_auto: this.modelInfo.auto,
1464
+ model_source: this.modelSource,
1465
+ ...(this.reasoningEffort ? { reasoning_effort: this.reasoningEffort } : {}),
1466
+ autonomy: this.config.autonomy,
1467
+ agent_mode: this.agentMode,
1468
+ budget: { run_cap: this.config.maxTokensPerRun, day_cap: this.config.maxTokensPerDay },
1469
+ });
1470
+ this.#sealAnchor();
1471
+ } catch (error) {
1472
+ await this.block(error?.code ?? 'E_AUDIT_WRITE', errorMessage(error));
1473
+ return;
1474
+ }
1475
+
1476
+ this.nextTickAt = new Date(this.#now().getTime() + (this.deps.firstTickMs ?? 3000)).toISOString();
1477
+ this.heartbeatAt = this.#iso();
1478
+ this.#installTurnListener();
1479
+ try { this.injector?.start(); } catch (error) { this.#log('warn', `agent/pre-step install failed: ${errorMessage(error)}`); }
1480
+ try { await this.#refreshL2({ write: true }); } catch (error) { this.#log('warn', `initial board refresh failed: ${errorMessage(error)}`); }
1481
+ this.#installTimers();
1482
+ this.#writeStatus();
1483
+ this.#log('info', `running (runId=${this.runId}, vault=${this.vaultDir})`);
1484
+ }
1485
+
1486
+ async start() {
1487
+ if (this.config.enabled !== true) {
1488
+ this.panelState = 'stopped';
1489
+ this.reason = 'disabled';
1490
+ this.started = false;
1491
+ return { ok: false, code: 'E_DISABLED', state: this.panelState };
1492
+ }
1493
+ if (this.started) return this.#result();
1494
+ this.started = true;
1495
+ this.panelState = 'starting';
1496
+ this.reason = 'starting';
1497
+ this.since = this.#iso();
1498
+ try {
1499
+ await this.#start();
1500
+ } catch (error) {
1501
+ await this.block(error?.code ?? 'E_START_FAILED', error);
1502
+ }
1503
+ return this.#result();
1504
+ }
1505
+
1506
+ #scheduleStandbyRetry() {
1507
+ if (this.deps.installTimers === false || this.disposed) return;
1508
+ this.standbyTimer = this.#timer(async () => {
1509
+ if (this.panelState !== 'standby' || this.disposed) return;
1510
+ const acquired = this.lock?.acquire();
1511
+ if (!acquired?.ok) {
1512
+ this.#scheduleStandbyRetry();
1513
+ return;
1514
+ }
1515
+ // 抢到了:重新走一遍账本/审计/锚校验,而不是复用 standby 之前的状态。
1516
+ this.panelState = 'starting';
1517
+ this.started = false;
1518
+ try {
1519
+ await this.#reinitializeAfterStandby();
1520
+ } catch (error) {
1521
+ await this.block(error?.code ?? 'E_START_FAILED', errorMessage(error));
1522
+ }
1523
+ }, this.deps.standbyRetryMs ?? STANDBY_RETRY_MS);
1524
+ }
1525
+
1526
+ async #reinitializeAfterStandby() {
1527
+ let reclaimed = null;
1528
+ try {
1529
+ this.ledger.repairTail();
1530
+ this.audit.open();
1531
+ this.anchor.repairTail();
1532
+ reclaimed = this.#reclaimRunLedgers();
1533
+ } catch (error) {
1534
+ await this.block(error?.code ?? 'E_LEDGER_WRITE', errorMessage(error));
1535
+ return;
1536
+ }
1537
+ const auditRead = readAudit(this.audit.file);
1538
+ if (auditRead.tamperedLines > 0 || auditRead.badLines > 0 || auditRead.chainBreaks.length > 0) {
1539
+ this.#addWarning('E_LEDGER_TAMPERED');
1540
+ await this.block('E_LEDGER_TAMPERED', 'audit chain is not clean after standby takeover');
1541
+ return;
1542
+ }
1543
+ this.#auditBudgetReclaim('standby_takeover', reclaimed);
1544
+ const reconciled = reconcileRuns({ vaultDir: this.vaultDir, audit: this.audit, auditRecords: auditRead.records });
1545
+ if (!reconciled.ok) {
1546
+ this.#addWarning(reconciled.code ?? 'E_LEDGER_TAMPERED');
1547
+ await this.block(reconciled.code ?? 'E_LEDGER_TAMPERED', 'reconcile failed after standby takeover');
1548
+ return;
1549
+ }
1550
+ const anchors = verifyRunAnchors({
1551
+ vaultDir: this.vaultDir,
1552
+ auditRecords: readAudit(this.audit.file).records,
1553
+ auditFile: this.audit.file,
1554
+ allowMissingAnchor: this.config.allowMissingAnchor,
1555
+ verifyAnchor,
1556
+ readAnchor,
1557
+ });
1558
+ if (!anchors.ok) {
1559
+ this.#addWarning(anchors.code ?? 'E_LEDGER_TAMPERED');
1560
+ await this.block(anchors.code ?? 'E_LEDGER_TAMPERED', `anchor verification failed: ${anchors.failure?.reason ?? 'unknown'}`);
1561
+ return;
1562
+ }
1563
+ this.#auditAllowedMissingAnchors(anchors);
1564
+ if (!(await this.#refreshDayUsage())) return;
1565
+ try {
1566
+ this.#setState('running', 'standby_takeover');
1567
+ this.#audit('router.start', {
1568
+ run_id: this.runId,
1569
+ provider: this.effectiveProvider,
1570
+ provider_source: this.providerSource,
1571
+ model: this.modelInfo.resolved ?? this.config.model,
1572
+ model_auto: this.modelInfo.auto,
1573
+ model_source: this.modelSource,
1574
+ ...(this.reasoningEffort ? { reasoning_effort: this.reasoningEffort } : {}),
1575
+ autonomy: this.config.autonomy,
1576
+ agent_mode: this.agentMode,
1577
+ budget: { run_cap: this.config.maxTokensPerRun, day_cap: this.config.maxTokensPerDay },
1578
+ });
1579
+ this.#sealAnchor();
1580
+ } catch (error) {
1581
+ await this.block(error?.code ?? 'E_AUDIT_WRITE', errorMessage(error));
1582
+ return;
1583
+ }
1584
+ this.nextTickAt = new Date(this.#now().getTime() + (this.deps.firstTickMs ?? 3000)).toISOString();
1585
+ this.#installTurnListener();
1586
+ this.#installTimers();
1587
+ this.#writeStatus();
1588
+ }
1589
+
1590
+ #installTurnListener() {
1591
+ if (this.deps.installListener === false) return;
1592
+ if (typeof this.ctx.on !== 'function') return;
1593
+ try {
1594
+ // R4.4: the real host emits `session/event` as TWO positional args
1595
+ // `(session, event)` (recorded DSH logs, 2026-11-06), while several
1596
+ // shipped tests drive the legacy one-arg envelope. Accept both arities:
1597
+ // two-arg -> event is arg 2 and arg 1 is the session; one-arg -> arg 1 is
1598
+ // the event (which may still carry `.session` inside).
1599
+ const listener = (...args) => {
1600
+ const twoArg = args.length >= 2 && args[1] != null;
1601
+ const event = twoArg ? args[1] : args[0];
1602
+ const session = twoArg ? args[0] : null;
1603
+ return this.handleSessionEvent(event, session);
1604
+ };
1605
+ const disposer = this.ctx.on('session/event', listener, { prepend: false });
1606
+ if (typeof disposer === 'function') this.listenerDisposers.push(disposer);
1607
+ } catch (error) {
1608
+ this.#log('warn', `session/event listener install failed: ${errorMessage(error)}`);
1609
+ }
1610
+ // Some host builds emit session/created as a direct event instead of a
1611
+ // session/event envelope. Register both and report which one actually fired
1612
+ // through status.live.createdEventVia — never silently assume.
1613
+ try {
1614
+ const created = this.ctx.on('session/created', (session) => {
1615
+ try { this.#onSessionCreated(session, 'session/created'); } catch (error) {
1616
+ this.#log('warn', `session/created heartbeat failed: ${errorMessage(error)}`);
1617
+ }
1618
+ }, { prepend: false });
1619
+ if (typeof created === 'function') this.listenerDisposers.push(created);
1620
+ } catch (error) {
1621
+ this.#log('warn', `session/created listener install failed: ${errorMessage(error)}`);
1622
+ }
1623
+ }
1624
+
1625
+ #installTimers() {
1626
+ if (this.deps.installTimers === false) return;
1627
+ if (this.firstTickTimer) this.#clearTimer(this.firstTickTimer);
1628
+ this.firstTickTimer = this.#timer(() => {
1629
+ this.firstTickTimer = null;
1630
+ this.tick({ tier: 'full', reason: 'startup' }).catch((error) => this.#failSafe(error));
1631
+ }, this.deps.firstTickMs ?? 3000);
1632
+
1633
+ if (this.tickTimer) this.#clearTimer(this.tickTimer);
1634
+ this.tickTimer = this.#interval(() => {
1635
+ if (this.panelState !== 'running') return;
1636
+ // status.nextTickAt means "the next scheduled tick" (DESIGN §6.5); the
1637
+ // periodic timer owns that slot, so refresh it before the tick runs.
1638
+ this.nextTickAt = new Date(this.#now().getTime() + this.config.tickMs).toISOString();
1639
+ this.tick({ tier: 'reflect', reason: 'timer' }).catch((error) => this.#failSafe(error));
1640
+ }, this.config.tickMs);
1641
+
1642
+ if (this.heartbeatTimer) this.#clearTimer(this.heartbeatTimer);
1643
+ this.heartbeatTimer = this.#interval(() => this.#heartbeat(), this.deps.heartbeatMs ?? LOCK_RENEW_MS);
1644
+
1645
+ if (this.config.stopFile) {
1646
+ if (this.stopFileTimer) this.#clearTimer(this.stopFileTimer);
1647
+ this.stopFileTimer = this.#interval(() => {
1648
+ if (this.#stopFileExists()) {
1649
+ this.stop('stop_file').catch((error) => this.#failSafe(error));
1650
+ }
1651
+ }, this.deps.stopFilePollMs ?? 5000);
1652
+ }
1653
+ }
1654
+
1655
+ #heartbeat() {
1656
+ if (this.panelState !== 'running' && this.panelState !== 'standby') return;
1657
+ const wasOwned = this.lock?.owned === true;
1658
+ let renewed = true;
1659
+ try { renewed = this.lock?.renew() !== false; } catch (error) { this.#log('warn', `lock renew failed: ${errorMessage(error)}`); renewed = false; }
1660
+ this.heartbeatAt = this.#iso();
1661
+ if (!renewed && wasOwned) {
1662
+ // F-01 fail-stop: another process reclaimed our lock while we were
1663
+ // paused. Continuing would write as a second live instance.
1664
+ this.#onLockLost();
1665
+ return;
1666
+ }
1667
+ this.#writeStatus();
1668
+ }
1669
+
1670
+ #onLockLost() {
1671
+ if (this.lockLost) return;
1672
+ this.lockLost = true;
1673
+ try { this.#auditSafe('lock.lost', { runId: this.runId, at: this.#iso() }); } catch { /* best effort */ }
1674
+ this.block('E_LOCK_LOST', 'writer lock was reclaimed by another instance').catch((error) => this.#failSafe(error));
1675
+ }
1676
+
1677
+ #stopFileExists() {
1678
+ if (!this.config.stopFile) return false;
1679
+ try { return fs.existsSync(this.config.stopFile); } catch { return false; }
1680
+ }
1681
+
1682
+ #sessionOfEvent(event) {
1683
+ return event?.session ?? event?.data?.session ?? event?.data ?? event;
1684
+ }
1685
+
1686
+ /** The session this Router instance belongs to, when the host exposes it. */
1687
+ #ownSessionId() {
1688
+ try {
1689
+ const direct = this.ctx?.sessionId
1690
+ ?? this.ctx?.session?.id
1691
+ ?? this.ctx?.get?.('session')?.id
1692
+ ?? this.ctx?.get?.('sessionId');
1693
+ return typeof direct === 'string' && direct.trim() ? direct.trim().toLowerCase() : null;
1694
+ } catch {
1695
+ return null;
1696
+ }
1697
+ }
1698
+
1699
+ #onSessionCreated(session, via) {
1700
+ if (this.disposed) return;
1701
+ const id = sessionIdOf(session);
1702
+ if (!id) {
1703
+ this.#auditSafe('live.row_skipped', { reason: 'bad_session_id', via });
1704
+ return;
1705
+ }
1706
+ const header = session?.header ?? session?.session?.header ?? {};
1707
+ // DESIGN §2.1: subagents are only a count; they never get a Router live row.
1708
+ if (header.origin === 'subagent') {
1709
+ this.#auditSafe('live.row_skipped', { session_id: id, via, reason: 'subagent' });
1710
+ return;
1711
+ }
1712
+ // DESIGN §2.1: Router never writes another session's row.
1713
+ const own = this.#ownSessionId();
1714
+ if (own && own !== id) {
1715
+ this.#auditSafe('live.row_skipped', { session_id: id, via, reason: 'other-session' });
1716
+ return;
1717
+ }
1718
+ const goal = typeof header.goal === 'string'
1719
+ ? header.goal
1720
+ : (typeof session?.goal === 'string' ? session.goal : undefined);
1721
+ const result = this.liveWriter?.write({
1722
+ sessionId: id,
1723
+ state: 'idle',
1724
+ goal,
1725
+ reason: 'session/created',
1726
+ via,
1727
+ turn: Number.isInteger(header.turn) ? header.turn : undefined,
1728
+ });
1729
+ if (result?.ok) {
1730
+ this.liveCreatedEventVia = via;
1731
+ this.liveInfo = { ...this.liveInfo, createdEventVia: via };
1732
+ } else {
1733
+ this.#auditSafe('live.row_skipped', { session_id: id, via, code: result?.code ?? 'NO_WRITER' });
1734
+ }
1735
+ }
1736
+
1737
+ #onTurnEnd(event, via, sessionArg = null) {
1738
+ if (this.disposed) return;
1739
+ const session = sessionArg ?? this.#sessionOfEvent(event);
1740
+ const id = sessionIdOf(session) ?? sessionIdOf(event);
1741
+ if (!id) return;
1742
+ const header = session?.header ?? {};
1743
+ if (header.origin === 'subagent') {
1744
+ this.#auditSafe('live.row_skipped', { session_id: id, via, reason: 'subagent' });
1745
+ return;
1746
+ }
1747
+ const own = this.#ownSessionId();
1748
+ if (own && own !== id) {
1749
+ this.#auditSafe('live.row_skipped', { session_id: id, via, reason: 'other-session' });
1750
+ return;
1751
+ }
1752
+ const scan = this.liveWriter?.scan();
1753
+ const ownRow = scan?.ok ? scan.entries.find((entry) => entry.sessionId === id) : null;
1754
+ const state = stateForTurnEnd(ownRow?.state);
1755
+ const rawTurn = Number.isInteger(event?.turn)
1756
+ ? event.turn
1757
+ : (Number.isInteger(event?.data?.turn) ? event.data.turn : ownRow?.turn);
1758
+ const goal = typeof event?.data?.goal === 'string'
1759
+ ? event.data.goal
1760
+ : (typeof header.goal === 'string' ? header.goal : undefined);
1761
+ const result = this.liveWriter?.write({
1762
+ sessionId: id,
1763
+ state,
1764
+ turn: Number.isInteger(rawTurn) ? rawTurn : undefined,
1765
+ goal,
1766
+ blocked_on: state === 'blocked' ? ownRow?.blocked_on : undefined,
1767
+ reason: 'turn/end',
1768
+ via,
1769
+ });
1770
+ if (result?.ok) {
1771
+ this.liveTurnEndEventVia = via;
1772
+ this.liveInfo = { ...this.liveInfo, turnEndEventVia: via };
1773
+ } else {
1774
+ this.#auditSafe('live.row_skipped', { session_id: id, via, code: result?.code ?? 'NO_WRITER' });
1775
+ }
1776
+ }
1777
+
1778
+ #handleLiveEvent(event, sessionArg = null) {
1779
+ const type = event?.type;
1780
+ if (type === 'session/created') {
1781
+ this.#onSessionCreated(sessionArg ?? this.#sessionOfEvent(event), 'session/event');
1782
+ return true;
1783
+ }
1784
+ if (type === 'turn/end') {
1785
+ this.#onTurnEnd(event, 'turn/end', sessionArg);
1786
+ return true;
1787
+ }
1788
+ if (type === 'agent/status') {
1789
+ const status = event?.data?.state ?? event?.data?.status ?? event?.status;
1790
+ if (status === 'idle') {
1791
+ this.#onTurnEnd(event, 'agent/status', sessionArg);
1792
+ return true;
1793
+ }
1794
+ }
1795
+ return false;
1796
+ }
1797
+
1798
+ /**
1799
+ * turn/end 唤醒:只认 reason.kind === 'completed',2 秒防抖 + 5 分钟合并。
1800
+ * 返回 {scheduled, coalesced?, debounced?, ignored?},方便单测。
1801
+ */
1802
+ handleSessionEvent(event, session = null) {
1803
+ // L1 heartbeat runs for every turn boundary, independent of reflectOnTurn
1804
+ // and of reason.kind (an aborted turn still ends).
1805
+ try { this.#handleLiveEvent(event, session); } catch (error) {
1806
+ this.#log('warn', `live heartbeat failed: ${errorMessage(error)}`);
1807
+ }
1808
+ const type = event?.type;
1809
+ if (type !== 'turn/end') return { scheduled: false, ignored: true, reason: 'not_turn_end' };
1810
+ if (event?.data?.reason?.kind !== 'completed') {
1811
+ return { scheduled: false, ignored: true, reason: 'not_completed' };
1812
+ }
1813
+ if (event?.data?.origin === 'router' || event?.data?.task?.origin === 'router') {
1814
+ return { scheduled: false, ignored: true, reason: 'recursive' };
1815
+ }
1816
+ if (this.config.reflectOnTurn !== true) return { scheduled: false, ignored: true, reason: 'disabled' };
1817
+ if (this.panelState !== 'running' || this.disposed) return { scheduled: false, ignored: true, reason: 'not_running' };
1818
+
1819
+ const now = this.#now().getTime();
1820
+ if (this.lastTurnReflectAt > 0 && now - this.lastTurnReflectAt < this.config.reflectCoalesceMs) {
1821
+ return { scheduled: false, coalesced: true, reason: 'coalesced' };
1822
+ }
1823
+ if (this.reflectTimer) return { scheduled: false, debounced: true, reason: 'debounced' };
1824
+
1825
+ const delayMs = this.deps.turnDebounceMs ?? 2000;
1826
+ this.reflectTimer = this.#timer(() => {
1827
+ this.reflectTimer = null;
1828
+ const current = this.#now().getTime();
1829
+ if (this.lastTurnReflectAt > 0 && current - this.lastTurnReflectAt < this.config.reflectCoalesceMs) return;
1830
+ this.lastTurnReflectAt = current;
1831
+ this.tick({ tier: 'reflect', reason: 'turn' }).catch((error) => this.#failSafe(error));
1832
+ }, delayMs);
1833
+ return { scheduled: true, delayMs };
1834
+ }
1835
+
1836
+ /**
1837
+ * 工具/内部触发。同步检查 busy 与状态,返回 {ok,accepted} 或错误码;tick 本身异步。
1838
+ */
1839
+ requestTick({ tier = 'full', reason = 'manual', manual = true, caller } = {}) {
1840
+ if (isSubagentCaller(caller)) return { ok: false, code: 'E_NOT_MAIN_SESSION' };
1841
+ if (this.disposed || this.panelState === 'stopped') return { ok: false, code: 'E_STOPPED', state: this.panelState };
1842
+ if (!this.started) return { ok: false, code: 'E_NOT_STARTED' };
1843
+ if (this.panelState === 'standby') return { ok: false, code: 'E_STANDBY', state: this.panelState };
1844
+ if (this.panelState === 'stopping') return { ok: false, code: 'E_STOPPING', state: this.panelState };
1845
+ if (this.panelState === 'blocked' && !manual) return { ok: false, code: 'E_BLOCKED', state: this.panelState };
1846
+ if (this.busy) {
1847
+ this.#auditTickBusy('request', { tier, reason, code: 'E_BUSY' });
1848
+ return { ok: false, code: 'E_BUSY', state: this.panelState };
1849
+ }
1850
+ const normalizedTier = tier === 'reflect' ? 'reflect' : 'full';
1851
+ const delayMs = this.deps.manualDelayMs ?? 2000;
1852
+ this.#timer(() => {
1853
+ this.tick({ tier: normalizedTier, reason, manual }).catch((error) => this.#failSafe(error));
1854
+ }, delayMs);
1855
+ return { ok: true, accepted: true, tier: normalizedTier, runId: this.runId, delayMs };
1856
+ }
1857
+
1858
+ async #resumeForTick() {
1859
+ const code = this.lastError?.code;
1860
+ if (HARD_BLOCK_CODES.has(code)) return false;
1861
+ if (code === 'E_NO_PROVIDER') {
1862
+ const llm = await this.#resolveLlm();
1863
+ if (!llm || typeof llm.stream !== 'function') return false;
1864
+ const target = await resolveModelTarget({
1865
+ config: this.config,
1866
+ ctx: this.ctx,
1867
+ llm,
1868
+ explicitReasoningEffort: this.explicitReasoningEffort,
1869
+ });
1870
+ if (!target.ok) return false;
1871
+ this.#applyModelTarget(target);
1872
+ this.#markProviderMissing(false);
1873
+ }
1874
+ const previous = this.panelState;
1875
+ this.panelState = 'running';
1876
+ this.reason = 'resumed';
1877
+ this.since = this.#iso();
1878
+ this.lastError = null;
1879
+ this.consecutiveErrors = 0;
1880
+ this.substate = 'idle';
1881
+ try { this.#audit('state.change', { from: previous, to: 'running', reason: 'manual_resume' }); } catch { /* status below */ }
1882
+ this.#installTimers();
1883
+ this.#writeStatus();
1884
+ return true;
1885
+ }
1886
+
1887
+ async tick({ tier = 'full', reason = 'manual', manual = false } = {}) {
1888
+ if (!this.started) return { ok: false, code: 'E_NOT_STARTED' };
1889
+ if (this.panelState === 'blocked') {
1890
+ if (!manual) return { ok: false, code: 'E_NOT_RUNNING', state: this.panelState };
1891
+ const resumed = await this.#resumeForTick();
1892
+ if (!resumed) return { ok: false, code: 'E_NOT_RUNNING', state: this.panelState, lastError: this.lastError };
1893
+ }
1894
+ if (this.panelState !== 'running') {
1895
+ return { ok: false, code: 'E_NOT_RUNNING', state: this.panelState };
1896
+ }
1897
+ if (this.busy) {
1898
+ this.#auditTickBusy('tick', { tier, reason, code: 'E_BUSY' });
1899
+ return { ok: false, code: 'E_BUSY', state: this.panelState };
1900
+ }
1901
+
1902
+ // DESIGN §3.6 (D30): one tick at a time across accidental dual instances.
1903
+ // A holder that is alive makes this round a quiet skip; an unrecoverable
1904
+ // reclaim mutex is surfaced as TICK_RECLAIM_BUSY, never waited on.
1905
+ if (this.tickLock) {
1906
+ let locked;
1907
+ try { locked = this.tickLock.tryAcquire(); } catch (error) {
1908
+ this.#log('warn', `tick lock failed: ${errorMessage(error)}`);
1909
+ locked = { ok: false, reason: 'error' };
1910
+ }
1911
+ if (!locked.ok) {
1912
+ if (locked.reason === 'reclaim-busy') this.#addWarning('TICK_RECLAIM_BUSY');
1913
+ this.#auditTickBusy('lock', { tier, reason, code: 'E_TICK_LOCKED', lockReason: locked.reason });
1914
+ return { ok: true, skipped: true, reason: locked.reason, tier: tier === 'reflect' ? 'reflect' : 'full' };
1915
+ }
1916
+ }
1917
+
1918
+ this.busy = true;
1919
+ const promise = this.#doTick({ tier: tier === 'reflect' ? 'reflect' : 'full', reason, manual });
1920
+ this.inflight = promise;
1921
+ let result;
1922
+ try {
1923
+ result = await promise;
1924
+ } catch (error) {
1925
+ result = await this.#failSafe(error);
1926
+ } finally {
1927
+ this.busy = false;
1928
+ this.inflight = null;
1929
+ try { this.tickLock?.release(); } catch { /* evidence stays; next tick reclaims */ }
1930
+ }
1931
+ return result;
1932
+ }
1933
+
1934
+ async #doTick({ tier, reason }) {
1935
+ this.lastTickAt = this.#iso();
1936
+ this.heartbeatAt = this.lastTickAt;
1937
+ this.substate = 'idle';
1938
+
1939
+ if (this.#stopFileExists()) {
1940
+ // stop() waits for this.inflight; this tick is that inflight, so clear it
1941
+ // first or the service deadlocks until disposeTimeoutMs.
1942
+ this.inflight = null;
1943
+ await this.stop('stop_file');
1944
+ return { ok: true, stopped: true, reason: 'stop_file' };
1945
+ }
1946
+
1947
+ let reclaimed = null;
1948
+ try { reclaimed = this.#reclaimRunLedgers(); } catch (error) {
1949
+ await this.block('E_LEDGER_WRITE', `reclaimDead failed: ${errorMessage(error)}`);
1950
+ return { ok: false, code: 'E_LEDGER_WRITE' };
1951
+ }
1952
+ this.#auditBudgetReclaim('tick', reclaimed);
1953
+ if (!(await this.#refreshDayUsage())) {
1954
+ return { ok: false, code: this.lastError?.code ?? 'E_LEDGER_TAMPERED' };
1955
+ }
1956
+
1957
+ let view;
1958
+ try {
1959
+ view = this.queue.pending(this.seen);
1960
+ } catch (error) {
1961
+ await this.block('E_LEDGER_WRITE', `queue read failed: ${errorMessage(error)}`);
1962
+ return { ok: false, code: 'E_LEDGER_WRITE' };
1963
+ }
1964
+ const totalLines = view.tasks.length + view.invalid.length + (view.duplicates?.length ?? 0);
1965
+ if (view.invalid.length > 0 && totalLines > 0 && view.invalid.length / totalLines > 0.1) {
1966
+ await this.block('E_QUEUE_DIRTY', `queue has ${view.invalid.length}/${totalLines} invalid lines`);
1967
+ return { ok: false, code: 'E_QUEUE_DIRTY' };
1968
+ }
1969
+
1970
+ // WP2: refresh the read-only board projection and age out inject-state.
1971
+ // Both are best-effort; a broken live/inject directory never blocks a tick.
1972
+ try { this.liveWriter?.evict({ limit: this.config.liveRowsMax }); } catch (error) {
1973
+ this.#log('warn', `live row eviction failed: ${errorMessage(error)}`);
1974
+ }
1975
+ try { await this.#refreshL2({ write: true }); } catch (error) {
1976
+ this.#log('warn', `board refresh failed: ${errorMessage(error)}`);
1977
+ }
1978
+ try { this.injector?.prune({ maxSessions: this.config.injectStateMaxSessions }); } catch (error) {
1979
+ this.#log('warn', `inject-state prune failed: ${errorMessage(error)}`);
1980
+ }
1981
+
1982
+ // WP4: queue/WAL reconciliation plus at most one apply per tick. This runs
1983
+ // under tick.lock; an apply failure is recorded on the proposal and must
1984
+ // never abort the rest of the tick (DESIGN §5.3a/§5.4).
1985
+ if (this.applier) {
1986
+ try {
1987
+ const maintenance = await this.applier.maintain({ allowApply: this.config.applyEnabled === true });
1988
+ if (maintenance?.applied) this.lastApplyAt = this.#iso();
1989
+ if (maintenance?.walBroken === true) this.#addWarning('WAL_BROKEN');
1990
+ } catch (error) {
1991
+ this.#log('warn', `apply maintenance failed: ${errorMessage(error)}`);
1992
+ }
1993
+ }
1994
+
1995
+ // WP6: Tier B wake (DESIGN §5.13). Default off; a disabled Router must not
1996
+ // read wake state, call resolveAgent or followup. Runs even when the host
1997
+ // task queue is empty, hence before the idle early-return below.
1998
+ if (this.wakeChannel && this.config.wakeEnabled === true && this.config.proposalEnabled === true) {
1999
+ try {
2000
+ await this.#runWakeTierB();
2001
+ } catch (error) {
2002
+ this.#log('warn', `wake cycle failed: ${errorMessage(error)}`);
2003
+ }
2004
+ }
2005
+
2006
+ // DESIGN §4.2: 每个 completed turn 的 reflect 是轻量整理——即使宿主任务队列
2007
+ // 为空,也要跑一次 reflect 档模型(C-02)。它不进 TaskQueue(B-06),只在
2008
+ // 本次 tick 里作为内部任务执行,审计里能看到 type=tier=reflect。
2009
+ let runTasks = view.tasks;
2010
+ if (runTasks.length === 0 && tier === 'reflect' && reason === 'turn' && this.config.reflectOnTurn === true) {
2011
+ runTasks = [{
2012
+ id: `turn-reflect-${this.runId}-${this.ticks + 1}`,
2013
+ type: 'reflect',
2014
+ question: 'turn/end reflect',
2015
+ payload: { question: 'turn/end reflect' },
2016
+ origin: 'host',
2017
+ depth: 0,
2018
+ }];
2019
+ }
2020
+
2021
+ if (runTasks.length === 0) {
2022
+ const now = this.#now().getTime();
2023
+ if (now - this.lastIdleAt >= 10 * 60 * 1000) {
2024
+ this.lastIdleAt = now;
2025
+ try { this.#audit('tick.idle', { reason }); } catch (error) {
2026
+ return this.#handleTickFailure(error);
2027
+ }
2028
+ }
2029
+ // An empty queue is not "not running": the periodic timer is still
2030
+ // armed, so nextTickAt must keep pointing at the next scheduled tick.
2031
+ this.#writeStatus();
2032
+ return { ok: true, idle: true, processed: 0, tier, reason };
2033
+ }
2034
+
2035
+ this.ticks += 1;
2036
+ try {
2037
+ this.#audit('tick.start', { tick: this.ticks, tier, reason, pending: runTasks.length });
2038
+ } catch (error) {
2039
+ return this.#handleTickFailure(error);
2040
+ }
2041
+
2042
+ let processed = 0;
2043
+ let tokensUsed = 0;
2044
+ const maxTasks = clampLimit(this.deps.maxTasksPerTick, 1, 5, 3);
2045
+ for (const task of runTasks.slice(0, maxTasks)) {
2046
+ if (this.panelState !== 'running') break;
2047
+ const result = await this.#runTask(task, { tier, queueView: view });
2048
+ processed += 1;
2049
+ tokensUsed += Number(result.tokensUsed) || 0;
2050
+ if (result.stop) break;
2051
+ }
2052
+
2053
+ try {
2054
+ this.#audit('tick.end', { tick: this.ticks, tier, processed, tokens: tokensUsed });
2055
+ } catch (error) {
2056
+ return this.#handleTickFailure(error);
2057
+ }
2058
+ if (this.ticks % 10 === 0) this.#sealAnchor();
2059
+ this.#writeStatus();
2060
+ return { ok: true, processed, tokensUsed, tier, state: this.panelState };
2061
+ }
2062
+
2063
+ async #handleTickFailure(error) {
2064
+ if (error?.code === 'E_AUDIT_WRITE') {
2065
+ this.panelState = 'stopped';
2066
+ this.reason = 'E_AUDIT_WRITE';
2067
+ this.lastError = { code: 'E_AUDIT_WRITE', at: this.#iso(), message: errorMessage(error) };
2068
+ this.#clearTimers();
2069
+ this.#writeStatus();
2070
+ return { ok: false, code: 'E_AUDIT_WRITE', state: 'stopped' };
2071
+ }
2072
+ return this.#failSafe(error);
2073
+ }
2074
+
2075
+ #accountDaySettled(reservationTokens, applied) {
2076
+ if (!this.dayUsage) return;
2077
+ this.dayUsage.reservedTokens = Math.max(0, (this.dayUsage.reservedTokens ?? 0) - (Number(reservationTokens) || 0));
2078
+ this.dayUsage.usedTokens = (this.dayUsage.usedTokens ?? 0) + Math.max(0, Number(applied) || 0);
2079
+ }
2080
+
2081
+ #accountDayReleased(reservationTokens) {
2082
+ if (!this.dayUsage) return;
2083
+ this.dayUsage.reservedTokens = Math.max(0, (this.dayUsage.reservedTokens ?? 0) - (Number(reservationTokens) || 0));
2084
+ }
2085
+
2086
+ async #runTask(task, { tier, queueView }) {
2087
+ if (task?.origin === 'router' || (Number.isInteger(task?.depth) && task.depth > 0)) {
2088
+ this.denied += 1;
2089
+ this.seen.add(task.id);
2090
+ try { this.#audit('task.denied', { task_id: task.id, type: task.type, reason: 'recursive' }); } catch (error) {
2091
+ return this.#handleTickFailure(error);
2092
+ }
2093
+ return { denied: true, tokensUsed: 0 };
2094
+ }
2095
+
2096
+ const sources = await loadContextSources({
2097
+ memoryRoot: this.config.memoryRoot ?? this.deps.memoryRoot ?? null,
2098
+ task,
2099
+ now: this.#now(),
2100
+ stability: this.stability,
2101
+ });
2102
+ sources.queue = {
2103
+ rows: this.#queueRows(queueView.tasks),
2104
+ pending: queueView.tasks.length,
2105
+ invalid: queueView.invalid.length,
2106
+ oldestAgeMs: this.#oldestAge(queueView.tasks),
2107
+ };
2108
+ let led = null;
2109
+ try { led = this.ledger.snapshot(); } catch { /* ignore */ }
2110
+ sources.ledger = {
2111
+ runUsed: led?.used ?? 0,
2112
+ runCap: this.config.maxTokensPerRun,
2113
+ dayUsed: this.dayUsage?.usedTokens ?? 0,
2114
+ dayCap: this.config.maxTokensPerDay,
2115
+ reserved: (led?.reserved ?? 0) + (this.dayUsage?.reservedTokens ?? 0),
2116
+ };
2117
+ for (const warning of sources.warnings) {
2118
+ if (String(warning).startsWith('INDEX_MISSING_FILE') || String(warning).endsWith('_UNSTABLE') || String(warning) === 'MEMORY_ROOT_MISSING') {
2119
+ try { this.#audit('llm.diagnostic', { task_id: task.id, code: warning }); } catch { /* diagnostic 不是关键路径 */ }
2120
+ }
2121
+ }
2122
+
2123
+ let context = assembleContext({
2124
+ tier,
2125
+ task,
2126
+ sources,
2127
+ forceOverBudget: this.testHooks?.forceContextOverBudget === true,
2128
+ });
2129
+ let degraded = false;
2130
+
2131
+ if (!context.ok) {
2132
+ if (tier === 'full' && context.canDegrade) {
2133
+ const reflect = assembleContext({
2134
+ tier: 'reflect',
2135
+ task,
2136
+ sources,
2137
+ degraded: true,
2138
+ forceOverBudget: this.testHooks?.forceContextOverBudget === true,
2139
+ });
2140
+ if (reflect.ok) {
2141
+ context = reflect;
2142
+ degraded = true;
2143
+ try {
2144
+ this.#audit('budget.degrade', {
2145
+ task_id: task.id,
2146
+ from: 'full',
2147
+ to: 'reflect',
2148
+ full_tokens: context.totalTokens,
2149
+ reason: 'context_over_budget',
2150
+ });
2151
+ } catch (error) { return this.#handleTickFailure(error); }
2152
+ } else {
2153
+ await this.block('E_CONTEXT_OVER_BUDGET', 'both full and reflect context exceed budget');
2154
+ return { stop: true, tokensUsed: 0 };
2155
+ }
2156
+ } else {
2157
+ await this.block('E_CONTEXT_OVER_BUDGET', 'reflect context exceeds budget');
2158
+ return { stop: true, tokensUsed: 0 };
2159
+ }
2160
+ }
2161
+
2162
+ let reservation = null;
2163
+ let reservationTokens = 0;
2164
+ let settled = false;
2165
+ const callMax = this.config.callMaxTokens;
2166
+ let contextInputTokens = context.contentTokens;
2167
+
2168
+ const reserveFor = (ctx) => {
2169
+ const needed = (ctx.contentTokens + callMax) * this.config.maxAttempts;
2170
+ const dayRemaining = Math.max(0, this.config.maxTokensPerDay
2171
+ - (this.dayUsage?.usedTokens ?? 0)
2172
+ - (this.dayUsage?.reservedTokens ?? 0));
2173
+ if (needed > dayRemaining) {
2174
+ return { needed, result: { ok: false, code: 'E_BUDGET_EXCEEDED', remaining: dayRemaining } };
2175
+ }
2176
+ try {
2177
+ const result = this.ledger.reserve({ taskId: task.id, tokens: needed, owner: this.runId, tick: this.ticks });
2178
+ if (result.ok && this.dayUsage) this.dayUsage.reservedTokens = (this.dayUsage.reservedTokens ?? 0) + needed;
2179
+ return { needed, result };
2180
+ } catch (error) {
2181
+ const code = error?.code ?? 'E_LEDGER_WRITE';
2182
+ return { needed, error: { code: code.startsWith('E_BUDGET_') ? 'E_LEDGER_WRITE' : code, message: errorMessage(error) } };
2183
+ }
2184
+ };
2185
+
2186
+ let attempt = reserveFor(context);
2187
+ if (attempt.error) {
2188
+ await this.block(attempt.error.code, attempt.error.message);
2189
+ return { stop: true, tokensUsed: 0 };
2190
+ }
2191
+ if (!attempt.result.ok) {
2192
+ if (tier === 'full') {
2193
+ const fullTokens = context.totalTokens;
2194
+ const reflect = assembleContext({
2195
+ tier: 'reflect',
2196
+ task,
2197
+ sources,
2198
+ degraded: true,
2199
+ forceOverBudget: this.testHooks?.forceContextOverBudget === true,
2200
+ });
2201
+ if (reflect.ok) {
2202
+ const second = reserveFor(reflect);
2203
+ if (second.error) {
2204
+ await this.block(second.error.code, second.error.message);
2205
+ return { stop: true, tokensUsed: 0 };
2206
+ }
2207
+ if (second.result.ok) {
2208
+ context = reflect;
2209
+ contextInputTokens = reflect.contentTokens;
2210
+ degraded = true;
2211
+ attempt = second;
2212
+ try {
2213
+ this.#audit('budget.degrade', {
2214
+ task_id: task.id,
2215
+ from: 'full',
2216
+ to: 'reflect',
2217
+ full_tokens: fullTokens,
2218
+ needed: second.needed,
2219
+ remaining: attempt.result.remaining,
2220
+ reason: 'reserve_not_fit',
2221
+ });
2222
+ } catch (error) { return this.#handleTickFailure(error); }
2223
+ }
2224
+ }
2225
+ }
2226
+ if (!attempt?.result?.ok) {
2227
+ try {
2228
+ this.#audit('budget.exceeded', {
2229
+ task_id: task.id,
2230
+ tier: context.tier,
2231
+ needed: attempt.needed ?? null,
2232
+ remaining: attempt.result?.remaining ?? null,
2233
+ });
2234
+ } catch (error) { return this.#handleTickFailure(error); }
2235
+ await this.block('E_BUDGET_EXHAUSTED', `budget reserve failed (needed=${attempt.needed ?? '?'}, remaining=${attempt.result?.remaining ?? '?'})`);
2236
+ return { stop: true, tokensUsed: 0 };
2237
+ }
2238
+ }
2239
+
2240
+ reservation = attempt.result;
2241
+ reservationTokens = attempt.needed;
2242
+ try {
2243
+ this.#audit('budget.reserve', {
2244
+ task_id: task.id,
2245
+ reservation_id: reservation.id,
2246
+ tokens: reservationTokens,
2247
+ tier: context.tier,
2248
+ });
2249
+ this.#audit('task.start', {
2250
+ task_id: task.id,
2251
+ type: task.type,
2252
+ tier: context.tier,
2253
+ input_tokens: contextInputTokens,
2254
+ reserved_tokens: reservationTokens,
2255
+ });
2256
+ } catch (error) {
2257
+ try { this.ledger.release({ id: reservation.id }); } catch { /* ignore */ }
2258
+ this.#accountDayReleased(reservationTokens);
2259
+ return this.#handleTickFailure(error);
2260
+ }
2261
+
2262
+ this.abortController = new AbortController();
2263
+ let callResult;
2264
+ try {
2265
+ callResult = await this.#callModel(context, task, { signal: this.abortController.signal });
2266
+ } catch (error) {
2267
+ callResult = {
2268
+ ok: false,
2269
+ failureCode: error?.code ?? 'E_CALL_FAILED',
2270
+ retryExhausted: true,
2271
+ usage: null,
2272
+ invalidUsage: false,
2273
+ attempts: 1,
2274
+ aborted: this.abortController.signal.aborted,
2275
+ };
2276
+ } finally {
2277
+ this.abortController = null;
2278
+ }
2279
+
2280
+ const usage = callResult.usage;
2281
+ const validUsage = usage && !callResult.invalidUsage && Number.isFinite(usage.inputTokens) && Number.isFinite(usage.outputTokens);
2282
+ const actualUsage = validUsage
2283
+ ? Math.max(0, Math.round(usage.inputTokens + usage.outputTokens + (usage.cacheReadTokens ?? 0) + (usage.cacheWriteTokens ?? 0)))
2284
+ : contextInputTokens + callMax;
2285
+ const usageEstimated = !validUsage;
2286
+
2287
+ if (callResult.aborted) {
2288
+ try { this.ledger.release({ id: reservation.id }); } catch { /* ignore */ }
2289
+ this.#accountDayReleased(reservationTokens);
2290
+ try { this.#audit('task.error', { task_id: task.id, code: 'E_ABORTED', attempt: callResult.attempts ?? 1 }); } catch { /* ignore */ }
2291
+ return { stop: true, aborted: true, tokensUsed: 0 };
2292
+ }
2293
+
2294
+ if (callResult.invalidUsage) {
2295
+ try {
2296
+ const settledResult = this.ledger.settle({ id: reservation.id, tokens: actualUsage, allowOvershoot: true });
2297
+ settled = true;
2298
+ this.#accountDaySettled(reservationTokens, settledResult.applied ?? 0);
2299
+ this.#audit('budget.settle', {
2300
+ task_id: task.id,
2301
+ reservation_id: reservation.id,
2302
+ tokens: settledResult.applied ?? 0,
2303
+ requested: actualUsage,
2304
+ usage_estimated: true,
2305
+ usage_invalid: true,
2306
+ });
2307
+ } catch { /* below */ }
2308
+ await this.block('E_USAGE_INVALID', 'llm usage is negative/NaN/non-integer');
2309
+ return { stop: true, tokensUsed: actualUsage };
2310
+ }
2311
+
2312
+ try {
2313
+ const settledResult = this.ledger.settle({ id: reservation.id, tokens: actualUsage, allowOvershoot: true });
2314
+ settled = true;
2315
+ this.#accountDaySettled(reservationTokens, settledResult.applied ?? 0);
2316
+ // A reservation is a forecast, not a billing ceiling. Account what the call
2317
+ // really cost (up to the hard run cap), surface the forecast miss, and halt
2318
+ // instead of pretending the extra tokens never happened (E-05).
2319
+ const overshoot = !settledResult.ok || actualUsage > reservationTokens;
2320
+ if (overshoot) {
2321
+ try {
2322
+ this.#audit('budget.overshoot', {
2323
+ task_id: task.id,
2324
+ reservation_id: reservation.id,
2325
+ requested: actualUsage,
2326
+ applied: settledResult.applied ?? 0,
2327
+ rejected: settledResult.rejected ?? 0,
2328
+ reserved_tokens: reservationTokens,
2329
+ });
2330
+ } catch { /* the halt below still applies */ }
2331
+ await this.#halt('E_BUDGET_OVERSHOOT', `actual usage ${actualUsage} exceeds reservation ${reservationTokens}`);
2332
+ return { stop: true, tokensUsed: actualUsage };
2333
+ }
2334
+ this.#audit('budget.settle', {
2335
+ task_id: task.id,
2336
+ reservation_id: reservation.id,
2337
+ tokens: settledResult.applied ?? actualUsage,
2338
+ requested: actualUsage,
2339
+ usage_estimated: usageEstimated,
2340
+ });
2341
+ } catch (error) {
2342
+ if (!settled) {
2343
+ try { this.ledger.release({ id: reservation.id }); } catch { /* ignore */ }
2344
+ this.#accountDayReleased(reservationTokens);
2345
+ }
2346
+ await this.block('E_LEDGER_WRITE', `ledger settle failed: ${errorMessage(error)}`);
2347
+ return { stop: true, tokensUsed: actualUsage };
2348
+ }
2349
+
2350
+ if (!callResult.ok) {
2351
+ const code = callResult.failureCode ?? 'E_CALL_FAILED';
2352
+ const hostCode = callResult.hostCode ?? code;
2353
+ this.consecutiveErrors += 1;
2354
+ try {
2355
+ this.#audit('task.error', {
2356
+ task_id: task.id,
2357
+ code: hostCode,
2358
+ router_code: code,
2359
+ attempt: callResult.attempts ?? this.config.maxAttempts,
2360
+ streak: this.consecutiveErrors,
2361
+ retry_exhausted: callResult.retryExhausted === true,
2362
+ ...(callResult.rateLimited ? { rate_limited: true } : {}),
2363
+ });
2364
+ } catch (error) {
2365
+ return this.#handleTickFailure(error);
2366
+ }
2367
+ if (callResult.fatal || callResult.terminal) {
2368
+ // D-WP5-5: terminal host failures surface as Router codes, with the
2369
+ // host code in the message for diagnosis (never credential material).
2370
+ await this.block(code, `llm provider error: ${hostCode}`);
2371
+ return { stop: true, tokensUsed: actualUsage };
2372
+ }
2373
+ this.substate = 'backoff';
2374
+ const baseDelay = computeBackoff({
2375
+ attempt: callResult.rateLimited ? 1 : this.consecutiveErrors,
2376
+ initialDelayMs: this.deps.backoffInitialMs ?? 5000,
2377
+ maxDelayMs: this.deps.backoffMaxMs ?? 300000,
2378
+ jitterRatio: 0,
2379
+ });
2380
+ const delayMs = callResult.rateLimited && Number.isFinite(callResult.retryAfterMs)
2381
+ ? Math.min(Math.max(callResult.retryAfterMs, 0), 300000)
2382
+ : baseDelay;
2383
+ this.nextTickAt = new Date(this.#now().getTime() + delayMs).toISOString();
2384
+ this.#scheduleBackoff(delayMs);
2385
+ // Rate limiting is retryable by contract: it must never become a
2386
+ // permanent E_ERROR_STREAK block (D-WP5-5).
2387
+ if (!callResult.rateLimited && this.consecutiveErrors >= this.config.maxConsecutiveErrors) {
2388
+ await this.block('E_ERROR_STREAK', `${this.consecutiveErrors} consecutive tick errors (last ${code})`);
2389
+ return { stop: true, tokensUsed: actualUsage };
2390
+ }
2391
+ this.#writeStatus();
2392
+ return { stop: true, tokensUsed: actualUsage, retryInMs: delayMs };
2393
+ }
2394
+
2395
+ this.consecutiveErrors = 0;
2396
+ this.substate = 'idle';
2397
+
2398
+ const text = typeof callResult.text === 'string' ? callResult.text : '';
2399
+ const action = parseAction(text);
2400
+ if (!action) {
2401
+ this.consecutiveErrors += 1;
2402
+ try {
2403
+ this.#audit('action.denied', { task_id: task.id, reason: 'parse', text_length: text.length, text_sha256: sha256Text(text) });
2404
+ } catch (error) {
2405
+ return this.#handleTickFailure(error);
2406
+ }
2407
+ this.seen.add(task.id);
2408
+ if (this.consecutiveErrors >= this.config.maxConsecutiveErrors) {
2409
+ await this.block('E_ERROR_STREAK', `parse failed ${this.consecutiveErrors} times`);
2410
+ }
2411
+ return { stop: true, tokensUsed: actualUsage };
2412
+ }
2413
+
2414
+ if (!ALLOWED_ACTIONS.has(action.type)) {
2415
+ this.denied += 1;
2416
+ this.seen.add(task.id);
2417
+ try {
2418
+ this.#audit('action.denied', {
2419
+ task_id: task.id,
2420
+ reason: 'not_allowed',
2421
+ action_type: String(action.type ?? ''),
2422
+ text_length: text.length,
2423
+ text_sha256: sha256Text(text),
2424
+ });
2425
+ } catch (error) {
2426
+ return this.#handleTickFailure(error);
2427
+ }
2428
+ return { stop: false, tokensUsed: actualUsage };
2429
+ }
2430
+
2431
+ try {
2432
+ this.#audit('action', {
2433
+ task_id: task.id,
2434
+ action_type: action.type,
2435
+ text_length: text.length,
2436
+ text_sha256: sha256Text(text),
2437
+ });
2438
+ } catch (error) {
2439
+ return this.#handleTickFailure(error);
2440
+ }
2441
+
2442
+ if (action.type === 'report') {
2443
+ await this.#recordReport(task, action, { degraded });
2444
+ }
2445
+
2446
+ this.seen.add(task.id);
2447
+ this.processed += 1;
2448
+ try {
2449
+ this.#audit('task.done', { task_id: task.id, action_type: action.type, tokens: actualUsage });
2450
+ } catch (error) {
2451
+ return this.#handleTickFailure(error);
2452
+ }
2453
+ this.#writeStatus();
2454
+ return { ok: true, tokensUsed: actualUsage };
2455
+ }
2456
+
2457
+ #scheduleBackoff(delayMs) {
2458
+ if (this.deps.installTimers === false || this.disposed) return;
2459
+ this.#timer(() => {
2460
+ if (this.panelState !== 'running') return;
2461
+ this.tick({ tier: 'reflect', reason: 'backoff', manual: true }).catch((error) => this.#failSafe(error));
2462
+ }, delayMs);
2463
+ }
2464
+
2465
+ async #callModel(context, task, { signal }) {
2466
+ const messages = buildMessages({
2467
+ system: context.messages?.system ?? '',
2468
+ prompt: context.messages?.prompt ?? context.userText ?? '',
2469
+ });
2470
+ let usage = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 };
2471
+ let invalidUsage = false;
2472
+ let attempts = 0;
2473
+
2474
+ const provider = this.effectiveProvider || this.config.provider;
2475
+ const resolvedModel = this.modelInfo?.resolved
2476
+ ?? (this.config.model && this.config.model !== 'auto' ? this.config.model : null);
2477
+ if (!provider || !resolvedModel || resolvedModel === 'auto') {
2478
+ // Belt and braces: never send the literal "auto" to the host.
2479
+ return {
2480
+ ok: false,
2481
+ fatal: true,
2482
+ failureCode: 'E_NO_PROVIDER',
2483
+ hostCode: 'MODEL_UNRESOLVED',
2484
+ terminal: true,
2485
+ usage,
2486
+ invalidUsage: true,
2487
+ attempts: 0,
2488
+ };
2489
+ }
2490
+
2491
+ for (let attempt = 1; attempt <= this.config.maxAttempts; attempt += 1) {
2492
+ attempts = attempt;
2493
+ let stream;
2494
+ try {
2495
+ stream = this.llm.stream({
2496
+ messages,
2497
+ task,
2498
+ signal,
2499
+ maxTokens: this.config.callMaxTokens,
2500
+ provider,
2501
+ model: resolvedModel,
2502
+ ...(this.reasoningEffort ? { reasoningEffort: this.reasoningEffort } : {}),
2503
+ });
2504
+ } catch (error) {
2505
+ const hostCode = String(error?.code ?? 'TRANSPORT');
2506
+ const mapped = mapProviderFailure(hostCode, { retryAfterMs: error?.providerRetryAfterMs });
2507
+ if (!mapped.terminal && mapped.retryable !== false
2508
+ && attempt < this.config.maxAttempts && !signal?.aborted) {
2509
+ await this.#retryWait(attempt, mapped.retryAfterMs);
2510
+ continue;
2511
+ }
2512
+ return {
2513
+ ok: false,
2514
+ failureCode: mapped.routerCode,
2515
+ hostCode,
2516
+ terminal: mapped.terminal === true,
2517
+ fatal: mapped.terminal === true,
2518
+ rateLimited: mapped.rateLimited === true,
2519
+ retryAfterMs: mapped.retryAfterMs,
2520
+ retryExhausted: true,
2521
+ usage,
2522
+ invalidUsage,
2523
+ attempts,
2524
+ aborted: signal?.aborted === true,
2525
+ };
2526
+ }
2527
+
2528
+ let result;
2529
+ try {
2530
+ result = await consumeStream(stream, { signal });
2531
+ } catch (error) {
2532
+ result = {
2533
+ ok: false,
2534
+ failure: { code: error?.code ?? 'E_STREAM_CONSUME', message: errorMessage(error) },
2535
+ aborted: signal?.aborted === true,
2536
+ usage: null,
2537
+ };
2538
+ }
2539
+
2540
+ if (result?.usage) {
2541
+ if (result.usage.invalid === true) invalidUsage = true;
2542
+ usage = {
2543
+ inputTokens: usage.inputTokens + (Number(result.usage.inputTokens) || 0),
2544
+ outputTokens: usage.outputTokens + (Number(result.usage.outputTokens) || 0),
2545
+ cacheReadTokens: usage.cacheReadTokens + (Number(result.usage.cacheReadTokens) || 0),
2546
+ cacheWriteTokens: usage.cacheWriteTokens + (Number(result.usage.cacheWriteTokens) || 0),
2547
+ };
2548
+ }
2549
+
2550
+ if (signal?.aborted || result?.aborted) {
2551
+ return { ok: false, aborted: true, failureCode: 'E_ABORTED', hostCode: 'ABORTED', usage, invalidUsage, attempts };
2552
+ }
2553
+ if (result?.ok && typeof result.text === 'string') {
2554
+ return { ok: true, text: result.text, usage, invalidUsage, attempts };
2555
+ }
2556
+
2557
+ const code = String(result?.failure?.code ?? result?.code ?? (result?.missingFinish ? 'E_STREAM_NO_FINISH' : 'EMPTY_RESPONSE'));
2558
+ const mapped = mapProviderFailure(code, {
2559
+ retryAfterMs: result?.failure?.providerRetryAfterMs,
2560
+ });
2561
+ if (mapped.aborted) {
2562
+ return { ok: false, aborted: true, failureCode: 'E_ABORTED', hostCode: code, usage, invalidUsage, attempts };
2563
+ }
2564
+ if (mapped.terminal) {
2565
+ return {
2566
+ ok: false,
2567
+ fatal: true,
2568
+ terminal: true,
2569
+ failureCode: mapped.routerCode,
2570
+ hostCode: code,
2571
+ usage,
2572
+ invalidUsage,
2573
+ attempts,
2574
+ streamFailure: result?.failure ?? null,
2575
+ };
2576
+ }
2577
+ if (attempt < this.config.maxAttempts && mapped.retryable) {
2578
+ await this.#retryWait(attempt, mapped.retryAfterMs);
2579
+ continue;
2580
+ }
2581
+ return {
2582
+ ok: false,
2583
+ retryExhausted: true,
2584
+ failureCode: mapped.routerCode,
2585
+ hostCode: code,
2586
+ rateLimited: mapped.rateLimited === true,
2587
+ retryAfterMs: mapped.retryAfterMs,
2588
+ usage,
2589
+ invalidUsage,
2590
+ attempts,
2591
+ streamFailure: result?.failure ?? null,
2592
+ };
2593
+ }
2594
+
2595
+ return { ok: false, retryExhausted: true, failureCode: 'E_RETRY_EXHAUSTED', usage, invalidUsage, attempts };
2596
+ }
2597
+
2598
+ async #retryWait(attempt, retryAfterMs) {
2599
+ if (Number.isFinite(retryAfterMs) && retryAfterMs >= 0) {
2600
+ const delayMs = Math.min(retryAfterMs, 30000);
2601
+ if (delayMs > 0) await sleep(delayMs);
2602
+ return;
2603
+ }
2604
+ await this.#retrySleep(attempt);
2605
+ }
2606
+
2607
+ async #retrySleep(attempt) {
2608
+ const delayMs = this.deps.retryDelayMs !== undefined
2609
+ ? Math.max(0, this.deps.retryDelayMs)
2610
+ : Math.min(5000 * (2 ** (attempt - 1)), 300000);
2611
+ if (delayMs > 0) await sleep(delayMs);
2612
+ }
2613
+
2614
+ async #recordReport(task, action, { degraded }) {
2615
+ const summary = String(action.summary ?? action.note ?? '').slice(0, 1200);
2616
+ const next = String(action.next ?? '').slice(0, 300);
2617
+ const waiting = String(action.waiting ?? '').slice(0, 300);
2618
+ this.lastReport = {
2619
+ at: this.#iso(),
2620
+ summary,
2621
+ next,
2622
+ waiting,
2623
+ degraded: degraded === true,
2624
+ };
2625
+ this.reports.push({ at: this.lastReport.at, summary });
2626
+ if (this.reports.length > 20) this.reports.shift();
2627
+
2628
+ if (this.config.autonomy === 'draft') {
2629
+ try {
2630
+ const stamp = this.#iso().replace(/[:.]/gu, '-');
2631
+ const file = path.join(this.outboxDir, `report-${stamp}.md`);
2632
+ const body = `# Router 报告草案\n\n- at: ${this.lastReport.at}\n- task: ${task.id}\n- degraded: ${this.lastReport.degraded}\n\n## summary\n\n${summary}\n\n## next\n\n${next}\n\n## waiting\n\n${waiting}\n`;
2633
+ fs.mkdirSync(this.outboxDir, { recursive: true });
2634
+ fs.writeFileSync(file, body, 'utf8');
2635
+ this.#audit('writeback.draft', { task_id: task.id, file: path.basename(file), bytes: Buffer.byteLength(body) });
2636
+ } catch (error) {
2637
+ this.#log('warn', `report draft write failed: ${errorMessage(error)}`);
2638
+ }
2639
+ }
2640
+ }
2641
+
2642
+ async #failSafe(error) {
2643
+ const code = String(error?.code ?? 'E_INTERNAL');
2644
+ this.lastError = { code, at: this.#iso(), message: errorMessage(error) };
2645
+ if (code === 'E_AUDIT_WRITE') {
2646
+ this.panelState = 'stopped';
2647
+ this.reason = 'E_AUDIT_WRITE';
2648
+ this.#clearTimers();
2649
+ this.#writeStatus();
2650
+ return { ok: false, code: 'E_AUDIT_WRITE', state: 'stopped' };
2651
+ }
2652
+ if (this.panelState === 'running' || this.panelState === 'starting') {
2653
+ try { this.#audit('state.change', { from: this.panelState, to: 'blocked', reason: code }); } catch { /* ignore */ }
2654
+ }
2655
+ this.panelState = 'blocked';
2656
+ this.reason = code;
2657
+ this.since = this.#iso();
2658
+ this.#clearTimers();
2659
+ this.#writeStatus();
2660
+ return { ok: false, code, state: 'blocked' };
2661
+ }
2662
+
2663
+ async block(code, errorOrMessage) {
2664
+ if (this.disposed) return this.#result();
2665
+ const message = errorMessage(errorOrMessage);
2666
+ const from = this.panelState;
2667
+ this.panelState = 'blocked';
2668
+ this.reason = String(code ?? 'E_BLOCKED');
2669
+ this.since = this.#iso();
2670
+ this.lastError = { code: this.reason, at: this.#iso(), message };
2671
+ this.#clearTimers();
2672
+ if (this.audit && from !== 'blocked') {
2673
+ try { this.#audit('state.change', { from, to: 'blocked', reason: this.reason }); } catch { /* status is best-effort */ }
2674
+ }
2675
+ if (HARD_BLOCK_CODES.has(this.reason)) {
2676
+ try { this.lock?.release(); } catch { /* ignore */ }
2677
+ }
2678
+ this.#writeStatus();
2679
+ this.#log('warn', `blocked: ${this.reason} (${message})`);
2680
+ return this.#result();
2681
+ }
2682
+
2683
+ async #halt(code, message) {
2684
+ if (this.disposed) return this.#result();
2685
+ const from = this.panelState;
2686
+ this.panelState = 'stopped';
2687
+ this.substate = 'idle';
2688
+ this.reason = String(code ?? 'E_STOPPED');
2689
+ this.since = this.#iso();
2690
+ this.lastError = { code: this.reason, at: this.#iso(), message: errorMessage(message) };
2691
+ this.nextTickAt = null;
2692
+ this.#clearTimers();
2693
+ if (this.audit && from !== 'stopped') {
2694
+ try { this.#audit('state.change', { from, to: 'stopped', reason: this.reason }); } catch { /* best effort */ }
2695
+ }
2696
+ this.#writeStatus();
2697
+ this.#log('warn', `stopped: ${this.reason} (${errorMessage(message)})`);
2698
+ return this.#result();
2699
+ }
2700
+
2701
+ async stop(reason = 'manual') {
2702
+ if (this.stopPromise) return this.stopPromise;
2703
+ if (this.disposed && this.panelState === 'stopped') return this.#result({ auditBroken: false });
2704
+ if (this.panelState === 'stopped') return this.#result({ auditBroken: false });
2705
+
2706
+ this.stopPromise = (async () => {
2707
+ this.panelState = 'stopping';
2708
+ this.reason = String(reason);
2709
+ this.since = this.#iso();
2710
+ this.stopRequested = true;
2711
+ this.#clearTimers();
2712
+ try { this.abortController?.abort(); } catch { /* ignore */ }
2713
+ let timedOut = false;
2714
+ if (this.inflight) {
2715
+ const timeoutMs = this.config.disposeTimeoutMs ?? 1000;
2716
+ const raced = await Promise.race([
2717
+ this.inflight.then(() => 'done', () => 'done'),
2718
+ sleep(timeoutMs).then(() => 'timeout'),
2719
+ ]);
2720
+ timedOut = raced === 'timeout';
2721
+ }
2722
+ if (timedOut) {
2723
+ try { this.ledger?.releaseOwner(this.runId); } catch { /* ignore */ }
2724
+ }
2725
+
2726
+ let auditBroken = false;
2727
+ try {
2728
+ this.#audit('router.stop', {
2729
+ reason: this.reason,
2730
+ timeout: timedOut,
2731
+ ticks: this.ticks,
2732
+ processed: this.processed,
2733
+ });
2734
+ } catch {
2735
+ auditBroken = true;
2736
+ }
2737
+ try { this.ledger?.releaseOwner(this.runId); } catch { /* ignore */ }
2738
+ this.#sealAnchor();
2739
+ this.panelState = 'stopped';
2740
+ this.substate = 'idle';
2741
+ this.reason = String(reason);
2742
+ this.since = this.#iso();
2743
+ this.nextTickAt = null;
2744
+ this.#writeStatus();
2745
+ try { this.lock?.release(); } catch { /* ignore */ }
2746
+ for (const dispose of this.listenerDisposers) {
2747
+ try { dispose(); } catch { /* ignore */ }
2748
+ }
2749
+ this.listenerDisposers = [];
2750
+ try { this.injector?.dispose(); } catch { /* ignore */ }
2751
+ return this.#result({ auditBroken });
2752
+ })();
2753
+
2754
+ try {
2755
+ return await this.stopPromise;
2756
+ } finally {
2757
+ this.stopPromise = null;
2758
+ }
2759
+ }
2760
+
2761
+ async dispose() {
2762
+ if (this.disposed) return this.#result({ auditBroken: false });
2763
+ this.disposed = true;
2764
+ this.#clearTimers();
2765
+ try {
2766
+ if (this.panelState !== 'stopped') await this.stop('dispose');
2767
+ else {
2768
+ for (const dispose of this.listenerDisposers) {
2769
+ try { dispose(); } catch { /* ignore */ }
2770
+ }
2771
+ this.listenerDisposers = [];
2772
+ try { this.injector?.dispose(); } catch { /* ignore */ }
2773
+ try { this.lock?.release(); } catch { /* ignore */ }
2774
+ }
2775
+ } finally {
2776
+ try { this.audit?.close(); } catch { /* ignore */ }
2777
+ }
2778
+ return this.#result({ auditBroken: false });
2779
+ }
2780
+
2781
+ status() {
2782
+ return this.#statusSnapshot();
2783
+ }
2784
+
2785
+ /**
2786
+ * WP3 tool entry: create one proposal. `options.caller` carries
2787
+ * `{sessionId,kind,turn,host}` from the host tool wrapper.
2788
+ */
2789
+ async proposeProposal(args = {}, options = {}) {
2790
+ if (!this.proposalEngine) {
2791
+ return {
2792
+ ok: false,
2793
+ code: this.config.proposalEnabled === true ? 'E_NOT_RUNNING' : 'E_PROPOSAL_DISABLED',
2794
+ message: this.config.proposalEnabled === true
2795
+ ? 'router proposal engine is only available after start()'
2796
+ : 'routerProposalEnabled is false',
2797
+ };
2798
+ }
2799
+ return this.proposalEngine.propose(args, options);
2800
+ }
2801
+
2802
+ /** WP3 tool entry: read-only list/queue/detail view. */
2803
+ proposalsView(args = {}, options = {}) {
2804
+ if (!this.proposalEngine) {
2805
+ return {
2806
+ ok: false,
2807
+ code: this.config.proposalEnabled === true ? 'E_NOT_RUNNING' : 'E_PROPOSAL_DISABLED',
2808
+ message: this.config.proposalEnabled === true
2809
+ ? 'router proposal engine is only available after start()'
2810
+ : 'routerProposalEnabled is false',
2811
+ };
2812
+ }
2813
+ return this.proposalEngine.view(args, options);
2814
+ }
2815
+
2816
+ /**
2817
+ * WP5 seam for `router_apply` and the owner CLI. The actual state machine and
2818
+ * lease/WAL writer belong to WP4b; this method only delegates when that
2819
+ * applier is installed and otherwise reports the gap honestly. It never
2820
+ * mutates a proposal file itself (that would bypass lease/WAL).
2821
+ */
2822
+ async requestApply(args = {}, options = {}) {
2823
+ if (!this.proposalEngine) {
2824
+ return {
2825
+ ok: false,
2826
+ code: this.config.proposalEnabled === true ? 'E_NOT_RUNNING' : 'E_PROPOSAL_DISABLED',
2827
+ message: this.config.proposalEnabled === true
2828
+ ? 'router proposal engine is only available after start()'
2829
+ : 'routerProposalEnabled is false',
2830
+ };
2831
+ }
2832
+ const mode = String(args?.mode ?? '');
2833
+ if (!['approve', 'reject', 'apply', 'rollback', 'cancel'].includes(mode)) {
2834
+ return { ok: false, code: 'E_BAD_MODE', message: `unknown proposal transition: ${mode}` };
2835
+ }
2836
+ const caller = options?.caller ?? { kind: 'root' };
2837
+ // D-CR2 hard gate: a subagent may only cancel its own proposal; every
2838
+ // review/apply transition is main-session/owner only. This runs before the
2839
+ // confirm check so a subagent cannot probe confirm strings either.
2840
+ if (mode !== 'cancel' && isSubagentCaller(caller)) {
2841
+ return { ok: false, code: 'E_NOT_MAIN_SESSION', message: 'subagent sessions cannot approve, reject, apply or rollback proposals' };
2842
+ }
2843
+ const engine = this.proposalEngine;
2844
+ let effectiveArgs = args;
2845
+ let id = typeof args?.id === 'string' ? args.id.trim() : '';
2846
+ // K-04: `router_apply` advertises `ticket`; resolve it here so a pending row
2847
+ // can be cancelled/rejected by ticket without an extra list round-trip.
2848
+ if (id === '' && typeof args?.ticket === 'string' && args.ticket.trim() !== ''
2849
+ && typeof engine.idForTicket === 'function') {
2850
+ const resolved = engine.idForTicket(args.ticket);
2851
+ if (!resolved) {
2852
+ return { ok: false, code: 'E_TICKET_UNKNOWN', message: `ticket ${args.ticket.trim()} was not found` };
2853
+ }
2854
+ id = resolved;
2855
+ effectiveArgs = { ...args, id: resolved };
2856
+ }
2857
+ if (mode === 'apply' && id === '') {
2858
+ // D-CR3: no id -> resolve the approved queue head first, then require the
2859
+ // matching confirm. An empty queue is E_TICKET_UNKNOWN, never a silent idle.
2860
+ const head = typeof engine.headApproved === 'function' ? engine.headApproved() : null;
2861
+ if (!head?.id) return { ok: false, code: 'E_TICKET_UNKNOWN', message: 'no approved proposal at the queue head' };
2862
+ if (args?.confirm !== head.id.slice(-6)) {
2863
+ return { ok: false, code: 'E_CONFIRM_REQUIRED', message: 'confirm must equal the last 6 characters of the proposal id' };
2864
+ }
2865
+ effectiveArgs = { ...args, id: head.id };
2866
+ } else if (['approve', 'apply', 'rollback'].includes(mode)) {
2867
+ if (id === '') return { ok: false, code: 'E_TICKET_UNKNOWN', message: 'a valid proposal id is required' };
2868
+ const expected = id.slice(-6);
2869
+ if (args?.confirm !== expected) {
2870
+ return { ok: false, code: 'E_CONFIRM_REQUIRED', message: 'confirm must equal the last 6 characters of the proposal id' };
2871
+ }
2872
+ }
2873
+ const candidates = mode === 'apply'
2874
+ ? ['requestApply', 'applyProposal']
2875
+ : [mode, `${mode}Proposal`];
2876
+ const fn = candidates.map((name) => engine[name]).find((candidate) => typeof candidate === 'function');
2877
+ if (!fn) {
2878
+ return {
2879
+ ok: false,
2880
+ code: 'E_WP4_PENDING',
2881
+ state: this.panelState,
2882
+ message: `proposal transition "${mode}" requires the WP4 queue/lease/apply writer, which is not installed in this build`,
2883
+ };
2884
+ }
2885
+ // D-CR7: a lost rev CAS is retried from a fresh read, bounded; callers that
2886
+ // keep racing get the stable E_STATE_RACE result instead of a silent overwrite.
2887
+ let last = null;
2888
+ for (let attempt = 0; attempt < 3; attempt += 1) {
2889
+ try {
2890
+ const result = await fn.call(engine, effectiveArgs, { caller });
2891
+ // N-03/L-04: status.json must reflect a proposal transition immediately
2892
+ // (the VM reads it right after apply, before the next heartbeat).
2893
+ try { this.#writeStatus(); } catch { /* status is best-effort */ }
2894
+ if (!(result && result.ok === false && result.code === 'E_STATE_RACE') || attempt === 2) return result;
2895
+ last = result;
2896
+ } catch (error) {
2897
+ if (error?.code !== 'E_STATE_RACE' || attempt === 2) throw error;
2898
+ last = error;
2899
+ }
2900
+ await new Promise((resolve) => setTimeout(resolve, 10 * (attempt + 1)));
2901
+ }
2902
+ return last;
2903
+ }
2904
+
2905
+ /** Tool-channel P0 denial audit hook (DESIGN §5.2/§5.10). */
2906
+ auditPriorityRejected(info = {}) {
2907
+ this.#auditSafe('priority.rejected', {
2908
+ id: null,
2909
+ attempted: 'P0',
2910
+ by: info.by ?? null,
2911
+ // `kind` is reserved by the audit envelope; keep the caller kind apart.
2912
+ callerKind: info.kind ?? null,
2913
+ reason: info.reason ?? 'tool-cannot-P0',
2914
+ });
2915
+ }
2916
+
2917
+ reportHistory(limit = 5) {
2918
+ const max = clampLimit(limit, 1, 10, 5);
2919
+ const recent = this.reports.slice(-max);
2920
+ return {
2921
+ lastReport: this.lastReport,
2922
+ recent,
2923
+ count: recent.length,
2924
+ };
2925
+ }
2926
+
2927
+ async ask({ question, tier = 'full', caller = null } = {}) {
2928
+ if (!this.started || this.disposed) return { ok: false, code: 'E_NOT_RUNNING', state: this.panelState };
2929
+ if (this.panelState === 'stopped' || this.panelState === 'standby') {
2930
+ return { ok: false, code: 'E_NOT_RUNNING', state: this.panelState };
2931
+ }
2932
+ const raw = typeof question === 'string' ? question.trim() : '';
2933
+ const q = Array.from(raw).slice(0, 500).join('');
2934
+ if (q === '') return { ok: false, code: 'E_INVALID_QUESTION' };
2935
+ // D-CR5: a subagent may ask at most 3 questions per rolling hour. The bucket
2936
+ // lives in memory on purpose: this is a safety valve for one service run,
2937
+ // not durable quota state (proposal quotas stay on disk).
2938
+ let askSession = null;
2939
+ let askBucket = null;
2940
+ let askNow = 0;
2941
+ if (caller && isSubagentCaller(caller)) {
2942
+ askSession = sessionIdOfCaller(caller);
2943
+ askNow = Date.now();
2944
+ if (!(this.askRate instanceof Map)) this.askRate = new Map();
2945
+ askBucket = (this.askRate.get(askSession) ?? []).filter((ts) => askNow - ts < ASK_RATE_WINDOW_MS);
2946
+ if (askBucket.length >= SUBAGENT_ASKS_PER_HOUR) {
2947
+ this.#auditSafe('ask.rejected', {
2948
+ by: askSession,
2949
+ reason: 'subagent-rate-limit',
2950
+ limit: SUBAGENT_ASKS_PER_HOUR,
2951
+ });
2952
+ return {
2953
+ ok: false,
2954
+ code: 'E_RATE_LIMITED',
2955
+ message: `subagent session exceeded ${SUBAGENT_ASKS_PER_HOUR} questions per hour`,
2956
+ limit: SUBAGENT_ASKS_PER_HOUR,
2957
+ };
2958
+ }
2959
+ this.askRate.set(askSession, askBucket);
2960
+ }
2961
+ const id = `ask-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
2962
+ let appended;
2963
+ try {
2964
+ appended = this.queue.writer.append({
2965
+ id,
2966
+ type: 'question',
2967
+ payload: { question: q },
2968
+ origin: 'tool',
2969
+ depth: 0,
2970
+ createdAt: this.#iso(),
2971
+ ...(askSession ? { sessionId: askSession, callerKind: 'subagent' } : {}),
2972
+ });
2973
+ } catch (error) {
2974
+ return { ok: false, code: error?.code ?? 'E_QUEUE_WRITE', message: errorMessage(error) };
2975
+ }
2976
+ if (!appended.ok) return appended;
2977
+ if (askBucket) askBucket.push(askNow);
2978
+ const trigger = this.requestTick({ tier, reason: 'ask', manual: true });
2979
+ return {
2980
+ ok: true,
2981
+ accepted: true,
2982
+ taskId: id,
2983
+ truncated: Array.from(raw).length > 500,
2984
+ tick: trigger.ok ? { accepted: true } : { accepted: false, code: trigger.code },
2985
+ };
2986
+ }
2987
+
2988
+ async requestStop(reason = 'tool') {
2989
+ return this.stop(reason);
2990
+ }
2991
+ }
2992
+
2993
+ /**
2994
+ * Compatibility re-export. The single source of truth is now
2995
+ * `caller.mjs` (session.header.origin first, legacy heuristic only when the
2996
+ * header is absent); keeping this named export preserves older importers.
2997
+ */
2998
+ export { isSubagentCaller } from './caller.mjs';