@jjh32456/dsh-longlive 1.6.7 → 1.8.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 (289) hide show
  1. package/CHANGELOG.md +70 -1508
  2. package/LICENSE +1 -1
  3. package/QUICKSTART.md +34 -13
  4. package/README.en.md +18 -7
  5. package/README.md +34 -9
  6. package/SPEC.md +5 -5
  7. package/cordis.patch.yml +23 -9
  8. package/docs/ANSWER-GUARD.md +92 -0
  9. package/docs/ARCHITECTURE.md +4 -3
  10. package/docs/AUTO-RECALL-WIRING.md +1 -1
  11. package/docs/AUTO-RECALL.md +15 -9
  12. package/docs/CONFIG.md +168 -35
  13. package/docs/ERRORS.md +17 -5
  14. package/docs/FAQ.md +7 -7
  15. package/docs/FEATURES.md +96 -28
  16. package/docs/MIGRATION-1.6.0.md +2 -2
  17. package/docs/OPERATIONS.md +6 -6
  18. package/docs/PANEL-INTEGRATION.md +6 -0
  19. package/docs/PRIVACY.md +88 -0
  20. package/docs/QUICKSTART.md +5 -5
  21. package/docs/README.en.md +4 -2
  22. package/docs/RESIDENT-WATCHER.md +1 -1
  23. package/docs/SESSION-WATCH.md +6 -6
  24. package/docs/TROUBLESHOOTING.md +4 -4
  25. package/package.json +47 -117
  26. package/runbook.md +2 -2
  27. package/scripts/backfill-auto-cards.mjs +98 -0
  28. package/scripts/install-surgery-task.ps1 +5 -2
  29. package/scripts/lib/session-watch-fixture.mjs +1 -1
  30. package/scripts/longlive-doctor.mjs +6 -0
  31. package/scripts/migrate-180.mjs +163 -0
  32. package/scripts/recall-index-build.mjs +128 -0
  33. package/scripts/session-watch-drill.mjs +1 -1
  34. package/scripts/surgery-run.cmd +1 -1
  35. package/scripts/unattended-surgery.ps1 +5 -2
  36. package/scripts/verify-card-anchors.mjs +138 -0
  37. package/src/actions/audit.js +125 -0
  38. package/src/actions/evidence.js +122 -0
  39. package/src/actions/fs.js +162 -0
  40. package/src/activity/index.js +760 -0
  41. package/src/activity/model.js +351 -0
  42. package/src/activity/store.js +644 -0
  43. package/src/activity/thinking.js +176 -0
  44. package/src/adapters/constants.js +11 -0
  45. package/src/adapters/engram/data/aliases.json +51 -0
  46. package/src/adapters/engram/data/policy.json +8 -0
  47. package/src/adapters/engram/data/routing-rules.json +546 -0
  48. package/src/adapters/engram/index.js +235 -0
  49. package/src/adapters/registry.js +315 -0
  50. package/src/answer/audit.js +193 -0
  51. package/src/answer/evidence.js +30 -0
  52. package/src/answer/guard.js +1370 -0
  53. package/src/answer/index.js +1067 -0
  54. package/src/answer/query.js +111 -0
  55. package/src/answer/second-hop.mjs +101 -0
  56. package/src/auto-truncate.js +1 -1
  57. package/src/config.js +171 -47
  58. package/src/deps.js +6 -4
  59. package/src/features.js +182 -6
  60. package/src/heartbeat.js +156 -23
  61. package/src/identity/handover.js +52 -1
  62. package/src/identity/index.js +13 -5
  63. package/src/identity/inject-position.js +2 -2
  64. package/src/index.js +97 -7
  65. package/src/lifecycle/gap-clocks.js +328 -0
  66. package/src/lifecycle/index.js +269 -0
  67. package/src/live.js +22 -2
  68. package/src/memory/activity-capture.js +229 -0
  69. package/src/memory/anchors.js +194 -0
  70. package/src/memory/audit-records.js +222 -0
  71. package/src/memory/auto-cards.js +401 -0
  72. package/src/memory/capture.js +442 -0
  73. package/src/memory/card-anchors.js +203 -0
  74. package/src/memory/conflicts.js +106 -0
  75. package/src/memory/decay.js +311 -0
  76. package/src/memory/distill.js +471 -0
  77. package/src/memory/event-index.js +917 -0
  78. package/src/memory/evidence-chain.js +295 -0
  79. package/src/memory/evidence.js +145 -0
  80. package/src/memory/filter-runner.js +1 -1
  81. package/src/memory/filter.js +5 -1
  82. package/src/memory/forget-v2.js +410 -0
  83. package/src/memory/forget.js +71 -0
  84. package/src/memory/frames-activation.js +247 -0
  85. package/src/memory/fts-query.js +174 -0
  86. package/src/memory/governance.js +604 -0
  87. package/src/memory/index.js +1 -0
  88. package/src/memory/l2-gate.js +169 -0
  89. package/src/memory/lock.js +121 -0
  90. package/src/memory/migrate.js +139 -0
  91. package/src/memory/recall-v2.js +223 -0
  92. package/src/memory/recall.js +65 -2
  93. package/src/memory/records.js +425 -0
  94. package/src/memory/retention.js +128 -0
  95. package/src/memory/review.js +124 -0
  96. package/src/memory/trust.js +88 -0
  97. package/src/memory/version-chain.js +264 -0
  98. package/src/memory/wal.js +137 -0
  99. package/src/memory/working-frame.js +516 -0
  100. package/src/metrics/classify.mjs +5 -3
  101. package/src/metrics/index.mjs +21 -1
  102. package/src/metrics/prestep-latency.mjs +300 -0
  103. package/src/metrics/store.mjs +25 -0
  104. package/src/policy-profile.js +18 -3
  105. package/src/recall/anaphora.mjs +87 -0
  106. package/src/recall/cards.mjs +7 -0
  107. package/src/recall/embedding.mjs +8 -8
  108. package/src/recall/entities.mjs +112 -0
  109. package/src/recall/index.js +235 -19
  110. package/src/recall/inject-order.mjs +10 -8
  111. package/src/recall/privacy.mjs +105 -16
  112. package/src/recall/recall-core.mjs +116 -10
  113. package/src/recall/shared-visibility.js +302 -0
  114. package/src/recall/time-normalizer.mjs +196 -0
  115. package/src/role/activation.js +191 -0
  116. package/src/role/attention.js +318 -0
  117. package/src/role/base.js +36 -0
  118. package/src/role/channels.js +423 -0
  119. package/src/role/index.js +425 -0
  120. package/src/role/interfaces.js +115 -0
  121. package/src/role/personality.js +370 -0
  122. package/src/role/readers.js +151 -0
  123. package/src/role/relationships.js +477 -0
  124. package/src/role/store.js +202 -0
  125. package/src/role/writeprotect.js +373 -0
  126. package/src/router/aliases.json +176 -25
  127. package/src/router/background/agent-runner.mjs +1 -1
  128. package/src/router/background/anchor.mjs +1 -1
  129. package/src/router/background/audit.mjs +2 -2
  130. package/src/router/background/budget-ledger.mjs +2 -2
  131. package/src/router/background/host-sim.mjs +1 -1
  132. package/src/router/background/memory.mjs +4 -4
  133. package/src/router/background/queue.mjs +1 -1
  134. package/src/router/background/retry.mjs +1 -1
  135. package/src/router/background/router.mjs +1 -1
  136. package/src/router/background/stream.mjs +1 -1
  137. package/src/router/background/tool-policy.mjs +1 -1
  138. package/src/router/design-headings.json +5 -5
  139. package/src/router/face/config.mjs +1 -1
  140. package/src/router/face/identity.mjs +3 -3
  141. package/src/router/judge.mjs +8 -7
  142. package/src/router/policies/generic.json +21 -4
  143. package/src/router/route.js +109 -22
  144. package/src/router/router.mjs +10 -6
  145. package/src/router/routing-rules.json +260 -445
  146. package/src/router/run-sim.mjs +8 -8
  147. package/src/router/runtime.js +23 -12
  148. package/src/router/service/board.mjs +95 -15
  149. package/src/router/service/config.mjs +5 -5
  150. package/src/router/service/context.mjs +1 -1
  151. package/src/router/service/hint.mjs +14 -0
  152. package/src/router/service/queue.mjs +1 -1
  153. package/src/router/service/service.mjs +27 -11
  154. package/src/router/shadow.mjs +4 -3
  155. package/src/surgery-recovery.js +2 -2
  156. package/src/tool-output.js +2 -2
  157. package/src/tools.js +39 -7
  158. package/src/truncate-visible.js +2 -2
  159. package/src/ui/actions.js +1312 -0
  160. package/src/ui/panel-api.js +367 -0
  161. package/src/ui/panel-auth.js +251 -0
  162. package/src/ui/panel-integrity.js +243 -0
  163. package/src/ui/routes-readonly.js +695 -0
  164. package/src/ui/routes.js +3 -0
  165. package/docs/DEV.md +0 -279
  166. package/docs/PRESENCE-BUS-WIRING.md +0 -491
  167. package/docs/PRESENCE-BUS.md +0 -694
  168. package/docs/SURGERY.md +0 -186
  169. package/scripts/mark-core-cards.mjs +0 -289
  170. package/scripts/pack.mjs +0 -392
  171. package/scripts/router-proposals.mjs +0 -386
  172. package/src/router/fixtures/M1.json +0 -16
  173. package/src/router/fixtures/M2.json +0 -16
  174. package/src/router/fixtures/M3.json +0 -20
  175. package/src/router/fixtures/M4.json +0 -20
  176. package/src/router/fixtures/M5.json +0 -45
  177. package/src/router/fixtures/M6.json +0 -53
  178. package/src/router/fixtures/M7.json +0 -46
  179. package/src/router/fixtures/S1.json +0 -20
  180. package/src/router/fixtures/S2.json +0 -23
  181. package/src/router/fixtures/S3.json +0 -20
  182. package/src/router/fixtures/S4.json +0 -34
  183. package/src/router/fixtures/S5.json +0 -43
  184. package/src/router/fixtures/S6.json +0 -47
  185. package/src/router/fixtures/T1.json +0 -23
  186. package/src/router/fixtures/T2.json +0 -16
  187. package/src/router/fixtures/T3.json +0 -19
  188. package/src/router/fixtures/T4.json +0 -16
  189. package/src/router/fixtures/X1.json +0 -17
  190. package/src/router/fixtures/X2.json +0 -20
  191. package/src/router/gen-design-headings.mjs +0 -107
  192. package/src/router/policies/owner-rulings-2026-11-03.json +0 -62
  193. package/test/auto-recall.test.mjs +0 -474
  194. package/test/auto-truncate.test.mjs +0 -931
  195. package/test/autobind.test.mjs +0 -385
  196. package/test/bus.test.mjs +0 -1572
  197. package/test/cli-guard.test.mjs +0 -198
  198. package/test/conclusion.test.mjs +0 -408
  199. package/test/config-schema.test.mjs +0 -204
  200. package/test/d6-output.test.mjs +0 -194
  201. package/test/d6.test.mjs +0 -395
  202. package/test/deps.test.mjs +0 -342
  203. package/test/doctor-setup.test.mjs +0 -297
  204. package/test/embedding-recall.test.mjs +0 -347
  205. package/test/feature-flags.test.mjs +0 -568
  206. package/test/filter-shadow.test.mjs +0 -170
  207. package/test/fixtures/baseline-0.8.0-registration.json +0 -556
  208. package/test/fixtures/d6-header-tools.json +0 -1
  209. package/test/fixtures/lock-child.mjs +0 -67
  210. package/test/fixtures/pre-step-container.mjs +0 -100
  211. package/test/fixtures/privacy-memory/topics/pii-unmarked.md +0 -9
  212. package/test/fixtures/privacy-memory/topics/secret-local-only.md +0 -11
  213. package/test/fixtures/profile-session-longlive-config.json +0 -20
  214. package/test/fixtures/proposal-cas-child.mjs +0 -66
  215. package/test/host-engine-status.test.mjs +0 -307
  216. package/test/hot-truncate.test.mjs +0 -1349
  217. package/test/identity-card-marker.test.mjs +0 -307
  218. package/test/identity-router/run.mjs +0 -721
  219. package/test/integration-pre-step.test.mjs +0 -553
  220. package/test/live.test.mjs +0 -1020
  221. package/test/maintenance-schedule.test.mjs +0 -538
  222. package/test/memory.test.mjs +0 -2828
  223. package/test/metrics.test.mjs +0 -478
  224. package/test/orchestrator.test.mjs +0 -266
  225. package/test/p1_probe.mjs +0 -97
  226. package/test/packaging.test.mjs +0 -182
  227. package/test/portability.test.mjs +0 -343
  228. package/test/rc4-regressions.test.mjs +0 -562
  229. package/test/rc5-regressions.test.mjs +0 -197
  230. package/test/rc6-chinese.test.mjs +0 -394
  231. package/test/router-1100/apply-off.test.mjs +0 -175
  232. package/test/router-1100/budget-reconcile.test.mjs +0 -215
  233. package/test/router-1100/config-context.test.mjs +0 -211
  234. package/test/router-1100/helpers.mjs +0 -129
  235. package/test/router-1100/hint-envelope.test.mjs +0 -150
  236. package/test/router-1100/lock-crossproc.test.mjs +0 -206
  237. package/test/router-1100/proposal-cas-crossproc.test.mjs +0 -184
  238. package/test/router-1100/router-apply.test.mjs +0 -372
  239. package/test/router-1100/router-fixb.test.mjs +0 -602
  240. package/test/router-1100/router-proposals.test.mjs +0 -405
  241. package/test/router-1100/router-queue-lease-wal.test.mjs +0 -355
  242. package/test/router-1100/router-security-cr.test.mjs +0 -333
  243. package/test/router-1100/service-lifecycle.test.mjs +0 -220
  244. package/test/router-1100/tools-contract.test.mjs +0 -164
  245. package/test/router-1100/turn-reflect-tick.test.mjs +0 -89
  246. package/test/router-1100/v6-contract.test.mjs +0 -158
  247. package/test/router-1100/v6b-contract.test.mjs +0 -293
  248. package/test/router-1100/v6c-contract.test.mjs +0 -249
  249. package/test/router-1100/wal-rotation.test.mjs +0 -375
  250. package/test/router-1100/wp1-config.test.mjs +0 -170
  251. package/test/router-1100/wp1-default-off.test.mjs +0 -77
  252. package/test/router-1100/wp1-model-status.test.mjs +0 -90
  253. package/test/router-1100/wp1-status.test.mjs +0 -220
  254. package/test/router-1100/wp1-tools.test.mjs +0 -146
  255. package/test/router-1100/wp5-cli.test.mjs +0 -240
  256. package/test/router-1100/wp5-model-auto.test.mjs +0 -418
  257. package/test/router-1100/wp6-merge.test.mjs +0 -386
  258. package/test/router-1100/wp6-wake.test.mjs +0 -502
  259. package/test/router-background/audit.test.mjs +0 -37
  260. package/test/router-background/budget-ledger.test.mjs +0 -330
  261. package/test/router-background/cross-process.test.mjs +0 -222
  262. package/test/router-background/fixtures/cross-child.mjs +0 -85
  263. package/test/router-background/fixtures/real-shapes.mjs +0 -239
  264. package/test/router-background/router.test.mjs +0 -1044
  265. package/test/router-background/stream-retry.test.mjs +0 -358
  266. package/test/router-background/tool-agent.test.mjs +0 -384
  267. package/test/router-face/bridge.test.mjs +0 -169
  268. package/test/router-face/face.test.mjs +0 -316
  269. package/test/router-failclosed.test.mjs +0 -466
  270. package/test/router-identity.test.mjs +0 -384
  271. package/test/router-l1-l2.contract.test.mjs +0 -1075
  272. package/test/router-memory-tools.test.mjs +0 -262
  273. package/test/router-policy.test.mjs +0 -225
  274. package/test/router-runtime.test.mjs +0 -438
  275. package/test/router-shadow.test.mjs +0 -287
  276. package/test/router.test.mjs +0 -903
  277. package/test/run-rc.mjs +0 -299
  278. package/test/run.mjs +0 -2469
  279. package/test/safety-defaults.test.mjs +0 -179
  280. package/test/seeded-load.test.mjs +0 -436
  281. package/test/session-original.test.mjs +0 -338
  282. package/test/surgery-recovery.test.mjs +0 -936
  283. package/test/t7_drive.mjs +0 -151
  284. package/test/tool-output.test.mjs +0 -393
  285. package/test/tool-schema.test.mjs +0 -177
  286. package/test/tools_contract.test.mjs +0 -716
  287. package/test/truncate-visible.test.mjs +0 -1150
  288. package/test/ui-flags.test.mjs +0 -477
  289. package/test/v4-hardening.test.mjs +0 -427
@@ -1,1044 +0,0 @@
1
- // test/router.test.mjs — Router 后台面骨架的验收测试(mustFix 重写版)
2
- //
3
- // 运行(Node 24):
4
- // node --test test/
5
- //
6
- // 覆盖:启动 / 幂等 / 预算硬上限与恢复 / 递归防护 / 崩溃隔离 / 审计格式 /
7
- // busy 互斥 / 审计写失败 / stop 中止在飞 tick / stopFile / 队列去重 / timer 清理。
8
-
9
- import test, { after } from 'node:test';
10
- import assert from 'node:assert/strict';
11
- import fs from 'node:fs';
12
- import path from 'node:path';
13
- import { fileURLToPath } from 'node:url';
14
- import { Router } from '../../src/router/background/router.mjs';
15
- import { MockLlm } from '../../src/router/background/mock-llm.mjs';
16
- import { readAudit } from '../../src/router/background/audit.mjs';
17
- import { BudgetLedger, readLedger } from '../../src/router/background/budget-ledger.mjs';
18
-
19
- const here = path.dirname(fileURLToPath(import.meta.url));
20
- const TMP = path.join(path.dirname(here), '.tmp');
21
- let caseNo = 0;
22
-
23
- function makeCase({ tasks = [], queueText = null, memory = null, llm = null, router = {} } = {}) {
24
- const dir = path.join(TMP, `case-${process.pid}-${caseNo++}`);
25
- fs.mkdirSync(dir, { recursive: true });
26
- const queuePath = path.join(dir, 'queue.jsonl');
27
- const auditPath = path.join(dir, 'audit.jsonl');
28
- const memoryPath = path.join(dir, 'memory.md');
29
-
30
- fs.writeFileSync(queuePath, queueText ?? (tasks.map((t) => JSON.stringify(t)).join('\n') + (tasks.length ? '\n' : '')));
31
- if (memory !== null) fs.writeFileSync(memoryPath, memory);
32
-
33
- return {
34
- dir, queuePath, auditPath, memoryPath,
35
- read: () => readAudit(auditPath).records,
36
- router: (overrides = {}) => new Router({
37
- queuePath,
38
- auditPath,
39
- memoryPath: memory !== null ? memoryPath : null,
40
- llm: llm ?? new MockLlm(),
41
- ...router,
42
- ...overrides,
43
- }),
44
- };
45
- }
46
-
47
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
48
-
49
- after(() => {
50
- try { fs.rmSync(TMP, { recursive: true, force: true }); } catch { /* best effort */ }
51
- });
52
-
53
- const task = (id, type = 'note', extra = {}) => ({ id, type, payload: { text: id }, ...extra });
54
-
55
- test('启动:start() 建状态、写 router.start、不预先处理任务', async () => {
56
- const c = makeCase({ tasks: [task('t1')], memory: '# 记忆\n## 卡片一\n- 事实 A\n' });
57
- const r = c.router();
58
- const started = r.start();
59
-
60
- assert.equal(started.ok, true);
61
- assert.equal(started.alreadyRunning, false);
62
- assert.equal(r.state, 'running');
63
-
64
- const recs = c.read();
65
- assert.equal(recs.length, 1);
66
- assert.equal(recs[0].kind, 'router.start');
67
- assert.equal(recs[0].seq, 1);
68
- assert.equal(recs[0].v, 1);
69
- assert.equal(recs[0].run_id, r.runId);
70
- await r.dispose();
71
- });
72
-
73
- test('幂等:重复 start() 不产生第二条 router.start,也不重置预算', async () => {
74
- const c = makeCase({ tasks: [task('t1')] });
75
- const r = c.router();
76
-
77
- assert.equal(r.start().alreadyRunning, false);
78
- const again = r.start();
79
- assert.equal(again.ok, true);
80
- assert.equal(again.alreadyRunning, true);
81
-
82
- const starts = c.read().filter((x) => x.kind === 'router.start');
83
- assert.equal(starts.length, 1);
84
- await r.dispose();
85
- });
86
-
87
- test('幂等:同一任务跨两次 tick 只处理一次', async () => {
88
- const c = makeCase({ tasks: [task('t1')] });
89
- const llm = new MockLlm();
90
- const r = c.router({ llm });
91
- r.start();
92
-
93
- const first = await r.tick();
94
- const second = await r.tick();
95
-
96
- assert.equal(first.processed, 1);
97
- assert.equal(second.processed, 0);
98
- assert.equal(llm.calls, 1);
99
- assert.equal(c.read().filter((x) => x.kind === 'action').length, 1);
100
- await r.dispose();
101
- });
102
-
103
- test('幂等:重启后从审计回放,不重复执行已处理任务', async () => {
104
- const c = makeCase({ tasks: [task('t1'), task('t2')] });
105
- const llm1 = new MockLlm();
106
- const r1 = c.router({ llm: llm1 });
107
- r1.start();
108
- await r1.tick();
109
- await r1.stop('test_done');
110
-
111
- const llm2 = new MockLlm();
112
- const r2 = c.router({ llm: llm2 });
113
- const started = r2.start();
114
- const res = await r2.tick();
115
-
116
- assert.equal(started.replayed, 2);
117
- assert.equal(res.processed, 0);
118
- assert.equal(llm2.calls, 0);
119
- await r2.dispose();
120
- });
121
-
122
- test('预算硬上限:预算 100、每次 75 时第二次调用在调度前被拒,总花费 75 不是 150', async () => {
123
- const c = makeCase({ tasks: [task('t1'), task('t2'), task('t3')] });
124
- const llm = new MockLlm({ usage: { inputTokens: 50, outputTokens: 25 } });
125
- const r = c.router({ llm, maxTokens: 100, callMaxTokens: 75, retry: { maxAttempts: 1 } });
126
- r.start();
127
-
128
- const res = await r.tick();
129
- assert.equal(res.processed, 1);
130
- assert.equal(res.stop, 'budget_exceeded');
131
- assert.equal(r.state, 'stopped');
132
- assert.equal(r.tokensUsed, 75);
133
- assert.equal(llm.calls, 1, '第二次调用必须在发出前被拒');
134
-
135
- const records = c.read();
136
- const reserves = records.filter((x) => x.kind === 'budget.reserve');
137
- assert.equal(reserves.length, 1);
138
- assert.equal(reserves[0].budgetReserved, 75);
139
- assert.ok(records.some((x) => x.kind === 'budget.exceeded'));
140
- assert.ok(records.some((x) => x.kind === 'router.stop' && x.reason === 'budget_exceeded'));
141
-
142
- const after1 = await r.tick();
143
- assert.equal(after1.ok, false);
144
- assert.equal(after1.code, 'E_NOT_RUNNING');
145
- });
146
-
147
- test('预算恢复:重启后 start() 从审计恢复已花 75,第二次 tick 不再调用模型', async () => {
148
- const c = makeCase({ tasks: [task('t1'), task('t2')] });
149
- const llm1 = new MockLlm({ usage: { inputTokens: 50, outputTokens: 25 } });
150
- const r1 = c.router({ llm: llm1, maxTokens: 100, callMaxTokens: 75, retry: { maxAttempts: 1 } });
151
- r1.start();
152
- const first = await r1.tick();
153
- assert.equal(first.processed, 1);
154
- assert.equal(r1.tokensUsed, 75);
155
- await r1.stop('done');
156
-
157
- const llm2 = new MockLlm({ usage: { inputTokens: 50, outputTokens: 25 } });
158
- const r2 = c.router({ llm: llm2, maxTokens: 100, callMaxTokens: 75, retry: { maxAttempts: 1 } });
159
- const started = r2.start();
160
- assert.equal(started.resumedTokens, 75);
161
- assert.equal(r2.tokensUsed, 75);
162
-
163
- const res = await r2.tick();
164
- assert.equal(res.stop, 'budget_exceeded');
165
- assert.equal(llm2.calls, 0);
166
- assert.equal(r2.tokensUsed, 75);
167
- await r2.dispose();
168
- });
169
-
170
- test('P0-1 预算超支:provider 返回 150 > 预留 100 → 只记 100、拒 50,E_BUDGET_OVERSHOOT 并停', async () => {
171
- const c = makeCase({ tasks: [task('t1'), task('t2')] });
172
- const llm = new MockLlm({ usage: { inputTokens: 120, outputTokens: 30 } });
173
- const r = c.router({ llm, maxTokens: 100, callMaxTokens: 100, retry: { maxAttempts: 1 } });
174
- r.start();
175
- const res = await r.tick();
176
-
177
- assert.equal(res.stop, 'budget_overshoot');
178
- assert.equal(res.code, 'E_BUDGET_OVERSHOOT');
179
- assert.equal(r.tokensUsed, 100, '硬上限是 100,不能记 150');
180
- assert.equal(r.lastError?.code, 'E_BUDGET_OVERSHOOT');
181
- assert.equal(llm.calls, 1, '超支后不得继续调用');
182
-
183
- const records = c.read();
184
- assert.ok(records.some((x) => x.kind === 'budget.overshoot'));
185
- assert.ok(records.some((x) => x.kind === 'router.stop' && x.reason === 'budget_overshoot'));
186
- const settleRec = records.find((x) => x.kind === 'budget.settle');
187
- assert.equal(settleRec.actual_tokens, 100, '只记上限内的部分');
188
- assert.equal(settleRec.requested_tokens, 150);
189
- assert.equal(settleRec.rejected_tokens, 50);
190
- await r.dispose();
191
- });
192
-
193
- test('重试预算:60+60 预留 150、预算 200 → 两次 attempt 全额入账 120(不再 clamp 到 75)', async () => {
194
- const c = makeCase({ tasks: [task('t1')] });
195
- const sixty = { inputTokens: 40, outputTokens: 20 };
196
- const llm = new MockLlm({
197
- usage: sixty,
198
- failOn: new Map([['t1', { code: 'SERVER', times: 1, usage: sixty }]]),
199
- });
200
- const r = c.router({
201
- llm,
202
- maxTokens: 200,
203
- callMaxTokens: 75,
204
- retry: { maxAttempts: 2, initialDelayMs: 1, maxDelayMs: 2 },
205
- });
206
- r.start();
207
- const res = await r.tick();
208
-
209
- assert.equal(llm.calls, 2, '必须真的发生两次 attempt');
210
- assert.equal(res.stop, false, '120 <= 150 预留,不应触发 overshoot');
211
- assert.equal(r.tokensUsed, 120, '60+60 必须全额入账,旧实现只记 75');
212
- assert.equal(r.ledger.snapshot().used, 120);
213
-
214
- const reserveRec = c.read().find((x) => x.kind === 'budget.reserve');
215
- assert.equal(reserveRec.budgetReserved, 150, '预留必须覆盖 maxAttempts × callMaxTokens');
216
- const settleRec = c.read().find((x) => x.kind === 'budget.settle');
217
- assert.equal(settleRec.actual_tokens, 120);
218
- assert.equal(settleRec.requested_tokens, 120);
219
- assert.equal(settleRec.rejected_tokens, 0);
220
- await r.dispose();
221
- });
222
-
223
- test('递归防护:origin=router / depth>0 的任务不进入模型调用', async () => {
224
- const c = makeCase({
225
- tasks: [task('r1', 'note', { origin: 'router' }), task('r2', 'note', { depth: 1 })],
226
- });
227
- const llm = new MockLlm();
228
- const r = c.router({ llm });
229
- r.start();
230
- const res = await r.tick();
231
-
232
- assert.equal(res.processed, 0);
233
- assert.equal(res.denied, 2);
234
- assert.equal(llm.calls, 0);
235
- const denied = c.read().filter((x) => x.kind === 'task.denied');
236
- assert.equal(denied.length, 2);
237
- assert.ok(denied.every((x) => x.reason === 'recursion'));
238
- await r.dispose();
239
- });
240
-
241
- test('递归防护:模型产出派生动作(spawn_router)被拒绝', async () => {
242
- const c = makeCase({ tasks: [task('t1')] });
243
- const llm = new MockLlm({ actionFor: () => ({ type: 'spawn_router' }) });
244
- const r = c.router({ llm });
245
- r.start();
246
- const res = await r.tick();
247
-
248
- assert.equal(res.processed, 0);
249
- assert.equal(res.denied, 1);
250
- const rec = c.read().find((x) => x.kind === 'action.denied');
251
- assert.equal(rec.reason, 'recursion');
252
- assert.equal(r.state, 'running');
253
- await r.dispose();
254
- });
255
-
256
- test('崩溃隔离:单任务抛错被捕获,同 tick 其它任务照常完成', async () => {
257
- const c = makeCase({ tasks: [task('t1'), task('t2')] });
258
- const llm = new MockLlm({ failOn: new Map([['t1', 'crash']]) });
259
- const r = c.router({ llm });
260
- r.start();
261
-
262
- const res = await r.tick(); // 不 reject
263
- assert.equal(res.ok, true);
264
- assert.equal(res.processed, 1);
265
- assert.equal(res.errors, 1);
266
- assert.equal(r.state, 'running');
267
-
268
- const kinds = c.read().map((x) => x.kind);
269
- assert.ok(kinds.includes('task.error'));
270
- assert.ok(kinds.includes('action'));
271
- assert.ok(c.read().some((x) => x.kind === 'task.error' && x.code === 'MOCK_CRASH'));
272
- await r.dispose();
273
- });
274
-
275
- test('熔断:连续错误达到阈值后停止', async () => {
276
- const c = makeCase({ tasks: [task('t1'), task('t2'), task('t3')] });
277
- const llm = new MockLlm({
278
- failOn: new Map([['t1', 'crash'], ['t2', 'crash'], ['t3', 'crash']]),
279
- });
280
- const r = c.router({ llm, maxConsecutiveErrors: 2 });
281
- r.start();
282
-
283
- const res = await r.tick();
284
- assert.equal(res.errors, 2);
285
- assert.equal(r.state, 'stopped');
286
- assert.equal(r.stopReason, 'error_streak');
287
- assert.equal(llm.calls, 2);
288
- });
289
-
290
- test('busy flag:并发 tick 只跑一个,另一个立即返回 E_BUSY', async () => {
291
- const c = makeCase({ tasks: [task('t1')] });
292
- const llm = new MockLlm({ delayMs: 80 });
293
- const r = c.router({ llm });
294
- r.start();
295
-
296
- const first = r.tick();
297
- await sleep(10);
298
- const second = await r.tick();
299
- assert.equal(second.ok, false);
300
- assert.equal(second.code, 'E_BUSY');
301
-
302
- const res = await first;
303
- assert.equal(res.processed, 1);
304
- assert.equal(llm.calls, 1);
305
- await r.dispose();
306
- });
307
-
308
- test('审计写失败:audit.close() 后 tick 不 reject、转 stopped 并记录', async () => {
309
- const c = makeCase({ tasks: [task('t1')] });
310
- const r = c.router();
311
- r.start();
312
- r.audit.close();
313
-
314
- let res;
315
- try {
316
- res = await r.tick();
317
- } catch (error) {
318
- assert.fail(`tick must not reject after audit close: ${error.message}`);
319
- }
320
- assert.equal(res.ok, false);
321
- assert.equal(res.code, 'E_AUDIT_WRITE');
322
- assert.equal(r.state, 'stopped');
323
- assert.equal(r.stopReason, 'audit_failed');
324
- });
325
-
326
- test('stop 先 abort:在飞 tick 被中止,stop 之后不再有新 tick', async () => {
327
- const c = makeCase({ tasks: [task('t1')] });
328
- const llm = new MockLlm({ delayMs: 300 });
329
- const r = c.router({ llm });
330
- r.start();
331
-
332
- const inflight = r.tick();
333
- await sleep(20);
334
- const stopped = await r.stop('manual');
335
- assert.equal(stopped.alreadyStopped, false);
336
- const res = await inflight;
337
-
338
- assert.equal(r.state, 'stopped');
339
- assert.equal(res.stop, 'aborted');
340
- assert.equal(llm.calls, 1);
341
-
342
- const after = await r.tick();
343
- assert.equal(after.code, 'E_NOT_RUNNING');
344
- });
345
-
346
- test('stop 幂等 + stopFile:第二次 stop 不重复写 router.stop;stopFile 触发停止', async () => {
347
- const c = makeCase({ tasks: [task('t1')] });
348
- const stopFile = path.join(c.dir, 'STOP');
349
- const r = c.router({ stopFile });
350
- r.start();
351
-
352
- const first = await r.stop('manual');
353
- const second = await r.stop('manual');
354
- assert.equal(first.alreadyStopped, false);
355
- assert.equal(second.alreadyStopped, true);
356
- assert.equal(c.read().filter((x) => x.kind === 'router.stop').length, 1);
357
-
358
- const other = c.router({ stopFile });
359
- fs.writeFileSync(stopFile, '');
360
- other.start();
361
- const res = await other.tick();
362
- assert.equal(res.stop, 'stop_file');
363
- assert.equal(other.state, 'stopped');
364
- assert.equal(c.read().filter((x) => x.kind === 'router.stop').length, 2);
365
- });
366
-
367
- test('未启动调用:tick() 返回 E_NOT_RUNNING 而不是抛错', async () => {
368
- const c = makeCase({ tasks: [task('t1')] });
369
- const r = c.router();
370
- const res = await r.tick();
371
- assert.equal(res.ok, false);
372
- assert.equal(res.code, 'E_NOT_RUNNING');
373
- });
374
-
375
- test('审计行格式:每行可解析、信封字段齐全、seq 连续、ts 为 ISO', async () => {
376
- const c = makeCase({
377
- tasks: [task('t1'), task('t2', 'report'), task('r1', 'note', { depth: 1 })],
378
- memory: '# 记忆\n## 卡片一\n- 事实 A\n',
379
- });
380
- const r = c.router({ llm: new MockLlm() });
381
- r.start();
382
- await r.tick();
383
- await r.tick();
384
- await r.stop('done');
385
-
386
- const { records, badLines } = readAudit(c.auditPath);
387
- assert.equal(badLines, 0);
388
- assert.ok(records.length >= 8);
389
-
390
- records.forEach((rec, i) => {
391
- assert.equal(rec.v, 1);
392
- assert.equal(rec.seq, i + 1, 'seq 必须从 1 开始连续');
393
- assert.equal(typeof rec.kind, 'string');
394
- assert.ok(rec.kind.length > 0);
395
- assert.equal(typeof rec.run_id, 'string');
396
- assert.equal(new Date(rec.ts).toISOString(), rec.ts, 'ts 必须是 ISO 时间');
397
- });
398
-
399
- const kinds = new Set(records.map((x) => x.kind));
400
- for (const expected of ['router.start', 'memory.read', 'action', 'task.denied', 'router.stop']) {
401
- assert.ok(kinds.has(expected), `缺少审计类型 ${expected}`);
402
- }
403
- const memRec = records.find((x) => x.kind === 'memory.read');
404
- assert.equal(memRec.facts, 2);
405
- });
406
-
407
- test('队列去重:重复 id 只跑一次,裸 append 被拒绝,writer 重复 append 返回 E_DUPLICATE', async () => {
408
- const line = JSON.stringify(task('t1'));
409
- const c = makeCase({ queueText: `${line}\n${line}\n` });
410
- const llm = new MockLlm();
411
- const r = c.router({ llm });
412
- r.start();
413
-
414
- const read = r.queue.read();
415
- assert.equal(read.tasks.length, 1);
416
- assert.equal(read.duplicates.length, 1);
417
-
418
- const res = await r.tick();
419
- assert.equal(res.processed, 1);
420
- assert.equal(llm.calls, 1);
421
-
422
- const dup = r.queue.writer.append(task('t1'));
423
- assert.equal(dup.ok, false);
424
- assert.equal(dup.code, 'E_DUPLICATE');
425
- assert.throws(() => r.queue.append(task('t2')), /trusted producer/);
426
- await r.dispose();
427
- });
428
-
429
- test('timer 清理:ctx.effect 注册的 heartbeat 在 dispose 时被取消', async () => {
430
- const c = makeCase({ tasks: [task('t1')] });
431
- let installed = 0;
432
- let disposed = 0;
433
- const ctx = {
434
- effect(fn) {
435
- installed += 1;
436
- const dispose = fn();
437
- return () => {
438
- disposed += 1;
439
- dispose();
440
- };
441
- },
442
- };
443
- const r = c.router({ ctx, heartbeatMs: 20 });
444
- r.start();
445
- assert.equal(installed, 1);
446
- await r.dispose();
447
- assert.equal(disposed, 1);
448
- });
449
-
450
- // ---------------------------------------------------------------------------
451
- // 第二轮红队 P0/P1 回归:跨实例预算、重启恢复、usage 记账、审计完整性、
452
- // 迭代器兜底、stop 降级、队列容量、heartbeat 停止。
453
- // ---------------------------------------------------------------------------
454
-
455
- function usageChunks(tokens, text = 'ok') {
456
- const inputTokens = Math.floor(tokens * 2 / 3);
457
- return [
458
- { type: 'block-start', index: 0, block: { type: 'text' } },
459
- { type: 'text-delta', index: 0, text },
460
- { type: 'usage', usage: { inputTokens, outputTokens: tokens - inputTokens, totalTokens: tokens } },
461
- { type: 'finish', reason: { kind: 'stop' } },
462
- ];
463
- }
464
-
465
- function failedChunks(tokens, code = 'SERVER') {
466
- return [
467
- { type: 'text-delta', index: 0, text: 'partial' },
468
- { type: 'usage', usage: { totalTokens: tokens } },
469
- { type: 'finish', reason: { kind: 'error', failure: { code, message: 'upstream failed' } } },
470
- ];
471
- }
472
-
473
- function scriptedLlm(scripts) {
474
- const llm = {
475
- provider: 'fixture',
476
- model: 'fixture-1',
477
- calls: 0,
478
- requests: [],
479
- async *stream(request) {
480
- llm.calls += 1;
481
- llm.requests.push(request);
482
- const index = Math.min(llm.calls - 1, scripts.length - 1);
483
- for (const chunk of scripts[index]) yield chunk;
484
- },
485
- };
486
- return llm;
487
- }
488
-
489
- test('P0-3:llm.stream 请求必须带 provider/model(真宿主 NO_ADAPTER 回归)', async () => {
490
- const c = makeCase({ tasks: [task('t1')] });
491
- const llm = scriptedLlm([usageChunks(30)]);
492
- const r = c.router({ llm, maxTokens: 100, callMaxTokens: 50, retry: { maxAttempts: 1 } });
493
- r.start();
494
- await r.tick();
495
-
496
- assert.equal(llm.requests.length, 1);
497
- assert.equal(llm.requests[0].provider, 'fixture');
498
- assert.equal(llm.requests[0].model, 'fixture-1');
499
- assert.ok(Array.isArray(llm.requests[0].messages));
500
- assert.equal(typeof llm.requests[0].maxTokens, 'number');
501
- await r.dispose();
502
-
503
- // 显式配置优先于 llm 实例上的默认值。
504
- const c2 = makeCase({ tasks: [task('t2')] });
505
- const llm2 = scriptedLlm([usageChunks(30)]);
506
- const r2 = c2.router({
507
- llm: llm2,
508
- provider: 'deepseek-official',
509
- model: 'deepseek-v4-flash',
510
- maxTokens: 100,
511
- callMaxTokens: 50,
512
- retry: { maxAttempts: 1 },
513
- });
514
- r2.start();
515
- await r2.tick();
516
- assert.equal(llm2.requests[0].provider, 'deepseek-official');
517
- assert.equal(llm2.requests[0].model, 'deepseek-v4-flash');
518
- await r2.dispose();
519
- });
520
-
521
- test('P0-3:NO_ADAPTER 写 llm.diagnostic 并停为 llm_fatal(不是静默重试)', async () => {
522
- const c = makeCase({ tasks: [task('noadapter')] });
523
- const llm = scriptedLlm([
524
- [
525
- { type: 'text-delta', index: 0, text: 'x' },
526
- { type: 'finish', reason: { kind: 'error', failure: { code: 'NO_ADAPTER', message: 'no adapter for provider' } } },
527
- ],
528
- ]);
529
- const r = c.router({ llm, maxTokens: 200, callMaxTokens: 50, retry: { maxAttempts: 3, initialDelayMs: 1 } });
530
- r.start();
531
- await r.tick();
532
-
533
- assert.equal(llm.calls, 1, 'FATAL 码不能重试');
534
- assert.equal(r.stopReason, 'llm_fatal');
535
- const diagnostic = c.read().find((rec) => rec.kind === 'llm.diagnostic');
536
- assert.ok(diagnostic, '必须把适配器缺失写进审计');
537
- assert.equal(diagnostic.code, 'NO_ADAPTER');
538
- await r.dispose();
539
- });
540
-
541
- test('P02:两个 Router 实例共享 run 目录,预算 100 时只能有一个预留 75(不得 150)', async () => {
542
- const c = makeCase({ tasks: [task('t1')] });
543
- const llm1 = scriptedLlm([usageChunks(75)]);
544
- const llm2 = scriptedLlm([usageChunks(75)]);
545
- const opts = { maxTokens: 100, callMaxTokens: 75, maxTicks: 5, retry: { maxAttempts: 1 } };
546
-
547
- // 两个进程各自写自己的审计(同一文件并发写会互相打断 hash 链),
548
- // 但共享同一本预算账本——这才是跨进程要验的东西。
549
- const r1 = c.router({ llm: llm1, ...opts, auditPath: path.join(c.dir, 'audit-1.jsonl') });
550
- const r2 = c.router({ llm: llm2, ...opts, auditPath: path.join(c.dir, 'audit-2.jsonl') });
551
- assert.equal(r1.start().ok, true);
552
- assert.equal(r2.start().ok, true);
553
-
554
- await Promise.all([r1.tick(), r2.tick()]);
555
-
556
- assert.equal(llm1.calls + llm2.calls, 1, '预算 100 只允许一次 75 的调用');
557
- assert.equal(r1.ledger.snapshot().used, 75);
558
- assert.equal(r1.ledger.snapshot().reserved, 0);
559
- const stopReasons = [r1.stopReason, r2.stopReason].filter(Boolean);
560
- assert.deepEqual(stopReasons, ['budget_exceeded']);
561
- await r1.dispose();
562
- await r2.dispose();
563
- });
564
-
565
- test('P03:重启从账本恢复全部已用(150),不是 max(75)', async () => {
566
- const c = makeCase({ tasks: [task('t1'), task('t2')] });
567
- const llm = scriptedLlm([usageChunks(75), usageChunks(75)]);
568
- const r1 = c.router({
569
- llm,
570
- maxTokens: 200,
571
- callMaxTokens: 75,
572
- maxTasksPerTick: 2,
573
- retry: { maxAttempts: 1 },
574
- });
575
- r1.start();
576
- await r1.tick();
577
- assert.equal(r1.tokensUsed, 150);
578
- await r1.dispose();
579
-
580
- const r2 = c.router({ llm: scriptedLlm([usageChunks(75)]), maxTokens: 200, callMaxTokens: 75 });
581
- const resumed = r2.start();
582
- assert.equal(resumed.ok, true);
583
- assert.equal(resumed.resumedTokens, 150, '两笔 75 必须相加恢复');
584
- assert.equal(resumed.tokensUsed, 150);
585
-
586
- // 剩余 50 连一次 75 都预留不出来 → 明确停因,不静默超支。
587
- assert.equal(r2.queue.writer.append(task('t3')).ok, true);
588
- await r2.tick();
589
- assert.equal(r2.stopReason, 'budget_exceeded');
590
- assert.equal(r2.ledger.snapshot().used, 150);
591
- await r2.dispose();
592
- });
593
-
594
- test('P06:负 usage 不得退款——拒绝记账并停机(tokensUsed 0,剩余仍是 2000)', async () => {
595
- const c = makeCase({ tasks: [task('neg')] });
596
- const llm = scriptedLlm([[
597
- { type: 'text-delta', index: 0, text: 'bad' },
598
- { type: 'usage', usage: { inputTokens: -1000, outputTokens: -1000, totalTokens: -2000 } },
599
- { type: 'finish', reason: { kind: 'stop' } },
600
- ]]);
601
- const r = c.router({ llm, maxTokens: 2000, callMaxTokens: 100, retry: { maxAttempts: 1 } });
602
- r.start();
603
- await r.tick();
604
-
605
- assert.equal(r.tokensUsed, 0, '负 usage 不能把已用降到 0 以下');
606
- assert.equal(r.ledger.snapshot().used, 0);
607
- assert.equal(r.stopReason, 'usage_invalid');
608
- assert.equal(r.state, 'stopped');
609
- assert.equal(r.lastError.code, 'E_USAGE_INVALID');
610
- const settle = c.read().find((rec) => rec.kind === 'budget.settle');
611
- assert.equal(settle.usage_valid, false);
612
- assert.equal(settle.actual_tokens, 0);
613
- await r.dispose();
614
- });
615
-
616
- test('P26:失败 attempt 的 usage 也计入——60+30 必须记 90', async () => {
617
- const c = makeCase({ tasks: [task('retry')] });
618
- const llm = scriptedLlm([
619
- failedChunks(60, 'SERVER'),
620
- usageChunks(30),
621
- ]);
622
- const r = c.router({
623
- llm,
624
- maxTokens: 1000,
625
- callMaxTokens: 100,
626
- retry: { maxAttempts: 2, initialDelayMs: 1, maxDelayMs: 2, jitterRatio: 0 },
627
- });
628
- r.start();
629
- await r.tick();
630
-
631
- assert.equal(llm.calls, 2);
632
- assert.equal(r.tokensUsed, 90, '失败那次已经计费,不能只记最后一次的 30');
633
- assert.equal(r.ledger.snapshot().used, 90);
634
- const settle = c.read().filter((rec) => rec.kind === 'budget.settle').at(-1);
635
- assert.equal(settle.actual_tokens, 90);
636
- await r.dispose();
637
- });
638
-
639
- test('F5:重试链 30 后 -20 → 只记 30、停机 usage_invalid、绝不回冲到 10', async () => {
640
- const c = makeCase({ tasks: [task('t1')] });
641
- const llm = scriptedLlm([
642
- failedChunks(30, 'SERVER'),
643
- usageChunks(-20),
644
- ]);
645
- const r = c.router({
646
- llm,
647
- maxTokens: 100,
648
- callMaxTokens: 30,
649
- retry: { maxAttempts: 2, initialDelayMs: 1, maxDelayMs: 2, jitterRatio: 0 },
650
- });
651
- r.start();
652
- const res = await r.tick();
653
-
654
- assert.equal(llm.calls, 2);
655
- assert.equal(res.stop, 'usage_invalid');
656
- assert.equal(r.tokensUsed, 30, '第一次合法花费 30 必须入账,不能被 -20 回冲成 10');
657
- assert.equal(r.ledger.snapshot().used, 30);
658
- const settle = c.read().filter((rec) => rec.kind === 'budget.settle').at(-1);
659
- assert.equal(settle.actual_tokens, 30);
660
- await r.dispose();
661
- });
662
-
663
- test('B:单次 attempt usage 40 > callMaxTokens 30(总额仍 ≤ 预留 90)→ 记 actual 40 并 fail 任务', async () => {
664
- const c = makeCase({ tasks: [task('t1')] });
665
- const llm = new MockLlm({ usage: { inputTokens: 40, outputTokens: 0 } });
666
- const r = c.router({
667
- llm,
668
- maxTokens: 200,
669
- callMaxTokens: 30,
670
- retry: { maxAttempts: 3, initialDelayMs: 1, maxDelayMs: 2 },
671
- });
672
- r.start();
673
- const res = await r.tick();
674
-
675
- assert.equal(res.stop, 'usage_overflow', '单次超 callMaxTokens 必须 fail,不能靠总额没超预留混过去');
676
- assert.equal(r.tokensUsed, 40, '按 actual 记账');
677
- assert.equal(r.ledger.snapshot().used, 40);
678
- const dead = c.read().filter((rec) => rec.kind === 'task.error' && rec.dead_letter === true);
679
- assert.equal(dead.length, 1);
680
- assert.equal(dead[0].reason, 'attempt_usage_overflow');
681
- await r.dispose();
682
- });
683
-
684
- test('P04a:没有账本且审计有坏行 → start fail-closed(E_AUDIT_CORRUPT)', async () => {
685
- const c = makeCase({ tasks: [task('t1')] });
686
- const r1 = c.router({ retry: { maxAttempts: 1 } });
687
- r1.start();
688
- await r1.tick();
689
- await r1.dispose();
690
-
691
- fs.rmSync(path.join(c.dir, 'budget.ledger.jsonl'), { force: true });
692
- fs.appendFileSync(c.auditPath, '{"v":1,"seq":999,"kind":"torn');
693
-
694
- const r2 = c.router({});
695
- const res = r2.start();
696
- assert.equal(res.ok, false);
697
- assert.equal(res.code, 'E_AUDIT_CORRUPT');
698
- assert.ok(res.badLines >= 1);
699
- assert.equal(r2.state, 'stopped');
700
- assert.equal(r2.stopReason, 'audit_corrupt');
701
- await r2.dispose();
702
- });
703
-
704
- test('P04b:审计截断但账本完整 → 从账本恢复 150,并上报 badLines', async () => {
705
- const c = makeCase({ tasks: [task('t1'), task('t2')] });
706
- const llm = scriptedLlm([usageChunks(75), usageChunks(75)]);
707
- const r1 = c.router({
708
- llm,
709
- maxTokens: 200,
710
- callMaxTokens: 75,
711
- maxTasksPerTick: 2,
712
- retry: { maxAttempts: 1 },
713
- });
714
- r1.start();
715
- await r1.tick();
716
- assert.equal(r1.tokensUsed, 150);
717
- await r1.dispose();
718
-
719
- // 尾部追加半行:旧实现会静默忽略,重新 start 只剩审计里能读出的 75。
720
- fs.appendFileSync(c.auditPath, '{"v":1,"seq":999,"kind":"torn');
721
-
722
- const r2 = c.router({ llm: scriptedLlm([usageChunks(75)]), maxTokens: 200, callMaxTokens: 75 });
723
- const res = r2.start();
724
- assert.equal(res.ok, true);
725
- assert.equal(res.resumedTokens, 150, '账本才是预算的真相来源');
726
- assert.ok(res.badLines >= 1, 'start() 必须把审计坏行数报出来');
727
- assert.equal(r2.tokensUsed, 150);
728
- const kinds = c.read().map((rec) => rec.kind);
729
- assert.ok(kinds.includes('audit.corrupt'));
730
- await r2.dispose();
731
- });
732
-
733
- test('P0-3:账本半行尾 → start() 先修尾再启动,不返回 E_BUDGET_CORRUPT', async () => {
734
- const c = makeCase({ tasks: [task('t1')] });
735
- const r1 = c.router({
736
- llm: scriptedLlm([usageChunks(75)]),
737
- maxTokens: 200,
738
- callMaxTokens: 75,
739
- retry: { maxAttempts: 1 },
740
- });
741
- r1.start();
742
- await r1.tick();
743
- assert.equal(r1.tokensUsed, 75);
744
- await r1.dispose();
745
-
746
- // 模拟崩溃:预留/结算都落盘了,最后一条只写了一半。
747
- fs.appendFileSync(path.join(c.dir, 'budget.ledger.jsonl'), '{"v":1,"seq":99,"op":"res');
748
-
749
- const r2 = c.router({
750
- llm: scriptedLlm([usageChunks(75)]),
751
- maxTokens: 200,
752
- callMaxTokens: 75,
753
- retry: { maxAttempts: 1 },
754
- });
755
- const res = r2.start();
756
- assert.equal(res.ok, true);
757
- assert.equal(res.tokensUsed, 75, '完好的 75 必须保留');
758
- assert.equal(res.reclaimed.released, 0);
759
- assert.equal(readLedger(path.join(c.dir, 'budget.ledger.jsonl')).badLines, 0, '半行必须被截掉');
760
- await r2.dispose();
761
- });
762
-
763
- test('P0-2:start() 回收死进程遗留的预留(不等到 tick)', async () => {
764
- const c = makeCase({ tasks: [task('t1')] });
765
- const ghost = new BudgetLedger({
766
- file: path.join(c.dir, 'budget.ledger.jsonl'),
767
- runId: 'run-ghost',
768
- maxTokens: 200,
769
- pid: 999999,
770
- });
771
- assert.equal(ghost.reserve({ tokens: 75, owner: 'run-ghost', leaseMs: 60000 }).ok, true);
772
-
773
- const r = c.router({
774
- llm: scriptedLlm([usageChunks(75)]),
775
- maxTokens: 200,
776
- callMaxTokens: 75,
777
- retry: { maxAttempts: 1 },
778
- });
779
- const res = r.start();
780
- assert.equal(res.ok, true);
781
- assert.equal(res.reclaimed.released, 1);
782
- assert.equal(res.tokensUsed, 0, '死预留不算花掉');
783
- assert.equal(res.resumedTokens, 0);
784
- assert.ok(res.reclaimed.freedTokens >= 75);
785
-
786
- const reclaimRec = c.read().find((rec) => rec.kind === 'budget.reclaim');
787
- assert.ok(reclaimRec, '回收动作必须进审计');
788
- assert.equal(reclaimRec.reason, 'startup');
789
-
790
- await r.tick();
791
- assert.equal(r.tokensUsed, 75);
792
- await r.stop('done');
793
- });
794
-
795
- test('P0-4:审计删掉中间整行 → start() 拒绝启动(E_LEDGER_TAMPERED)', async () => {
796
- const c = makeCase({ tasks: [task('t1'), task('t2')] });
797
- const r1 = c.router({
798
- llm: scriptedLlm([usageChunks(75), usageChunks(75)]),
799
- maxTokens: 200,
800
- callMaxTokens: 75,
801
- maxTasksPerTick: 2,
802
- retry: { maxAttempts: 1 },
803
- });
804
- r1.start();
805
- await r1.tick();
806
- await r1.dispose();
807
-
808
- const lines = fs.readFileSync(c.auditPath, 'utf8').trimEnd().split('\n');
809
- assert.ok(lines.length >= 5);
810
- lines.splice(Math.floor(lines.length / 2), 1);
811
- fs.writeFileSync(c.auditPath, `${lines.join('\n')}\n`);
812
-
813
- const r2 = c.router({});
814
- const res = r2.start();
815
- assert.equal(res.ok, false);
816
- assert.equal(res.code, 'E_LEDGER_TAMPERED');
817
- assert.ok(res.chainBreaks > 0, '删中间整行必须暴露 hash 链断裂 / seq 跳号');
818
- assert.equal(r2.state, 'stopped');
819
- assert.equal(r2.stopReason, 'ledger_tampered');
820
- await r2.dispose();
821
- });
822
-
823
- test('P0-4:账本删掉中间整行 → start() 拒绝启动(E_LEDGER_TAMPERED)', async () => {
824
- const c = makeCase({ tasks: [task('t1'), task('t2')] });
825
- const r1 = c.router({
826
- llm: scriptedLlm([usageChunks(75), usageChunks(75)]),
827
- maxTokens: 200,
828
- callMaxTokens: 75,
829
- maxTasksPerTick: 2,
830
- retry: { maxAttempts: 1 },
831
- });
832
- r1.start();
833
- await r1.tick();
834
- await r1.dispose();
835
-
836
- const ledgerPath = path.join(c.dir, 'budget.ledger.jsonl');
837
- const lines = fs.readFileSync(ledgerPath, 'utf8').trimEnd().split('\n');
838
- assert.ok(lines.length >= 4);
839
- lines.splice(Math.floor(lines.length / 2), 1);
840
- fs.writeFileSync(ledgerPath, `${lines.join('\n')}\n`);
841
-
842
- const r2 = c.router({});
843
- const res = r2.start();
844
- assert.equal(res.ok, false);
845
- assert.equal(res.code, 'E_LEDGER_TAMPERED');
846
- assert.ok(res.chainBreaks > 0);
847
- assert.equal(r2.stopReason, 'ledger_tampered');
848
- await r2.dispose();
849
- });
850
-
851
- test('P1-2:start() 在缺 provider/model 时 fail-fast E_NO_PROVIDER(不等首 tick)', async () => {
852
- const c = makeCase({ tasks: [task('t1')] });
853
- const bare = {
854
- async *stream() {
855
- yield { type: 'finish', reason: { kind: 'stop' } };
856
- },
857
- };
858
-
859
- const r1 = c.router({ llm: bare });
860
- const res1 = r1.start();
861
- assert.equal(res1.ok, false);
862
- assert.equal(res1.code, 'E_NO_PROVIDER');
863
- assert.deepEqual(res1.missing, ['provider', 'model']);
864
- assert.equal(r1.state, 'stopped');
865
- assert.equal(r1.stopReason, 'no_provider');
866
- await r1.dispose();
867
-
868
- const r2 = c.router({ llm: bare, provider: 'mock' });
869
- const res2 = r2.start();
870
- assert.equal(res2.ok, false);
871
- assert.equal(res2.code, 'E_NO_PROVIDER');
872
- assert.deepEqual(res2.missing, ['model']);
873
- await r2.dispose();
874
- });
875
-
876
- test('P10/P08:iterator.return() 永不 resolve 时 tick 仍能收敛,busy/预留都释放', async () => {
877
- const c = makeCase({ tasks: [task('hang')] });
878
- let returned = false;
879
- const llm = {
880
- provider: 'fixture',
881
- model: 'fixture-1',
882
- calls: 0,
883
- async *stream() {
884
- this.calls += 1;
885
- try {
886
- yield { type: 'text-delta', index: 0, text: 'partial' };
887
- await new Promise(() => { /* 永不 yield,也永不 return */ });
888
- } finally {
889
- returned = true;
890
- }
891
- },
892
- };
893
- const r = c.router({
894
- llm,
895
- maxTokens: 200,
896
- callMaxTokens: 50,
897
- callTimeoutMs: 5000,
898
- stopTimeoutMs: 500,
899
- retry: { maxAttempts: 1 },
900
- });
901
- r.start();
902
- const tickPromise = r.tick();
903
- await sleep(30);
904
-
905
- const started = Date.now();
906
- const stopRes = await r.stop();
907
- const stopElapsed = Date.now() - started;
908
- const tickRes = await tickPromise;
909
- const settleElapsed = Date.now() - started;
910
-
911
- assert.equal(stopRes.timedOut, false, 'stop 不能因为 return() 挂住');
912
- // 只量 stop() 本身;旧写法把 tick 收敛也算了进去,CI 抖动时会偶发 551ms。
913
- // 断言保留,放宽一个明确的调度余量(stopTimeoutMs + 150ms)。
914
- assert.ok(
915
- stopElapsed <= 500 + 150,
916
- `stop 必须在 stopTimeoutMs(500ms)附近收敛,允许 150ms 调度抖动(实测 ${stopElapsed}ms)`,
917
- );
918
- assert.ok(settleElapsed < 2000, `tick 必须在 stop 后很快收敛(实测 ${settleElapsed}ms)`);
919
- assert.equal(tickRes.ok, true);
920
- assert.equal(r.busy, false, 'busy 必须释放');
921
- assert.equal(r.reservedTokens, 0);
922
- assert.equal(r.ledger.snapshot().reserved, 0, '预留必须释放,不能泄漏 50');
923
- assert.equal(returned, false, '生成器 finally 可能来不及跑,但 tick 不能等它');
924
- await r.dispose();
925
- });
926
-
927
- test('P08:正常 abort 时消费端走到 drain 并关闭迭代器(finally 执行)', async () => {
928
- const c = makeCase({ tasks: [task('drain')] });
929
- let returned = false;
930
- let pulled = 0;
931
- const llm = {
932
- provider: 'fixture',
933
- model: 'fixture-1',
934
- async *stream() {
935
- try {
936
- while (true) {
937
- pulled += 1;
938
- yield { type: 'text-delta', index: 0, text: 'x' };
939
- }
940
- } finally {
941
- returned = true;
942
- }
943
- },
944
- };
945
- const r = c.router({
946
- llm,
947
- maxTokens: 200,
948
- callMaxTokens: 50,
949
- stopTimeoutMs: 500,
950
- retry: { maxAttempts: 1 },
951
- });
952
- r.start();
953
- const tickPromise = r.tick();
954
- await sleep(40);
955
- const stopRes = await r.stop();
956
- await tickPromise;
957
-
958
- assert.equal(stopRes.timedOut, false);
959
- assert.equal(returned, true, 'abort 之后必须真正关闭生成器');
960
- assert.ok(pulled >= 1);
961
- assert.equal(r.ledger.snapshot().reserved, 0);
962
- await r.dispose();
963
- });
964
-
965
- test('P12:stop 时 router.stop 审计写失败 → ok:false + E_AUDIT_WRITE,但状态必须 stopped', async () => {
966
- const c = makeCase({ tasks: [] });
967
- const r = c.router({});
968
- r.start();
969
- const original = r.audit.append.bind(r.audit);
970
- r.audit.append = (kind, data) => {
971
- if (kind === 'router.stop') throw new Error('disk full');
972
- return original(kind, data);
973
- };
974
-
975
- const res = await r.stop();
976
- assert.equal(res.ok, false);
977
- assert.equal(res.code, 'E_AUDIT_WRITE');
978
- assert.equal(r.state, 'stopped', '审计坏了也要落到 stopped,不能假装还在跑');
979
- assert.equal(r.auditBroken, true);
980
- await r.dispose();
981
- });
982
-
983
- test('P29:队列容量上限——第 N+1 条返回 E_QUEUE_FULL,不落盘', async () => {
984
- const c = makeCase({
985
- queueText: [1, 2, 3, 4].map((i) => JSON.stringify(task(`q${i}`))).join('\n') + '\n',
986
- });
987
- const r = c.router({ maxQueuedTasks: 3, maxQueueBytes: 1024 });
988
- const capacity = r.queue.capacity();
989
- assert.equal(capacity.count, 4);
990
- assert.equal(capacity.full, true);
991
-
992
- const before = fs.statSync(c.queuePath).size;
993
- const res = r.queue.writer.append(task('q5'));
994
- assert.equal(res.ok, false);
995
- assert.equal(res.code, 'E_QUEUE_FULL');
996
- assert.equal(fs.statSync(c.queuePath).size, before, '拒绝时不能写半行');
997
- await r.dispose();
998
- });
999
-
1000
- test('P22:dispose 之后 heartbeat 必须停止(不只是取消计时器句柄)', async () => {
1001
- const c = makeCase({ tasks: [] });
1002
- let installed = 0;
1003
- let disposed = 0;
1004
- const ctx = {
1005
- effect(fn) {
1006
- installed += 1;
1007
- const stop = fn();
1008
- return () => { disposed += 1; stop(); };
1009
- },
1010
- };
1011
- const r = c.router({ ctx, heartbeatMs: 20 });
1012
- r.start();
1013
- await sleep(70);
1014
- const beatsBefore = c.read().filter((rec) => rec.kind === 'router.heartbeat').length;
1015
- assert.ok(beatsBefore >= 2, `heartbeat 应该已经在跑(${beatsBefore})`);
1016
-
1017
- await r.dispose();
1018
- assert.equal(disposed, 1);
1019
- await sleep(60);
1020
- const beatsAfter = c.read().filter((rec) => rec.kind === 'router.heartbeat').length;
1021
- assert.equal(beatsAfter, beatsBefore, 'dispose 之后不能再产生 heartbeat');
1022
- assert.equal(installed, 1);
1023
- });
1024
-
1025
- test('M3a 真锚点:start 发现账本尾部半行 → 截断并写 budget.repair(只删 start 的 repairTail 会红)', async () => {
1026
- const c = makeCase({ tasks: [task('t1')] });
1027
- const ledgerPath = path.join(c.dir, 'budget.ledger.jsonl');
1028
- const seed = new BudgetLedger({ file: ledgerPath, runId: 'seed', maxTokens: 100 });
1029
- const seeded = seed.reserve({ taskId: 'seed', tokens: 1 });
1030
- seed.settle({ id: seeded.id, tokens: 0 });
1031
- fs.appendFileSync(ledgerPath, '{"v":1,"seq":99,"op":"settle","id":"rsv-x","tokens":30');
1032
- const r = c.router({ llm: new MockLlm(), retry: { maxAttempts: 1 } });
1033
-
1034
- const started = await r.start();
1035
- assert.equal(started.ok, true);
1036
-
1037
- const repairs = c.read().filter((rec) => rec.kind === 'budget.repair');
1038
- assert.equal(repairs.length, 1, 'start 修尾必须留下 budget.repair 审计事件');
1039
- assert.equal(repairs[0].repaired, true);
1040
- assert.equal(repairs[0].reason, 'startup_tail_repair');
1041
- assert.ok(fs.readFileSync(ledgerPath, 'utf8').endsWith('\n'), '账本必须被截到最后一条完整记录');
1042
-
1043
- await r.dispose();
1044
- });