@hugesb/dsh-stream-agent 0.0.0-stage → 0.3.2

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 (161) hide show
  1. package/CHANGELOG.md +622 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +202 -0
  4. package/README.en.md +349 -0
  5. package/README.md +300 -3
  6. package/cordis.patch.yml +77 -0
  7. package/dist/entry/action-gate.js +206 -0
  8. package/dist/entry/adapter-kit.js +192 -0
  9. package/dist/entry/context-render.js +119 -0
  10. package/dist/entry/control-bar-cli.js +289 -0
  11. package/dist/entry/control-bar.js +123 -0
  12. package/dist/entry/control-session.js +115 -0
  13. package/dist/entry/control-state.js +125 -0
  14. package/dist/entry/cordis-compat.js +95 -0
  15. package/dist/entry/eval-probe.js +112 -0
  16. package/dist/entry/intent-log.js +121 -0
  17. package/dist/entry/json-persistence.js +306 -0
  18. package/dist/entry/loop.js +4163 -0
  19. package/dist/entry/mock-provider.js +549 -0
  20. package/dist/entry/obs-broker.js +178 -0
  21. package/dist/entry/ptc-bridge.js +405 -0
  22. package/dist/entry/state-handle.js +217 -0
  23. package/dist/entry/takeover-registry.js +60 -0
  24. package/dist/kernel/control-bar.js +559 -0
  25. package/dist/kernel/final.js +62 -0
  26. package/dist/kernel/gate.js +464 -0
  27. package/dist/kernel/modes.js +253 -0
  28. package/dist/kernel/obs.js +517 -0
  29. package/dist/kernel/parser.js +1081 -0
  30. package/dist/kernel/render.js +466 -0
  31. package/dist/kernel/state.js +416 -0
  32. package/dist/version.js +9 -0
  33. package/docs/TEST-PROPOSITIONS.md +139 -0
  34. package/docs/adr-001-segment-boundary.md +61 -0
  35. package/docs/architecture.md +104 -0
  36. package/docs/desktop-ui-feasibility.md +277 -0
  37. package/docs/disabled-lines-audit.md +53 -0
  38. package/docs/limitations.md +181 -0
  39. package/docs/protocol.md +99 -0
  40. package/docs/v0.4.0-plan.md +50 -0
  41. package/eval/METRICS.md +128 -0
  42. package/eval/RESULTS.md +246 -0
  43. package/eval/tasks/fixtures/big-report.md +298 -0
  44. package/eval/tasks/fixtures/build-manifest.txt +5 -0
  45. package/eval/tasks/fixtures/deploy.yaml +4 -0
  46. package/eval/tasks/fixtures/error.log +200 -0
  47. package/eval/tasks/fixtures/features.yaml +4 -0
  48. package/eval/tasks/fixtures/pipeline.yaml +4 -0
  49. package/eval/tasks/fixtures/sales-q1.csv +61 -0
  50. package/eval/tasks/fixtures/settings.yaml +4 -0
  51. package/eval/tasks/fixtures/users-roster.json +304 -0
  52. package/eval/tasks/fixtures/users-scores.json +20 -0
  53. package/eval/tasks/gen-fixtures.cjs +80 -0
  54. package/eval/tasks/tasks.json +150 -0
  55. package/eval/tools/f6-kill-drill.cjs +176 -0
  56. package/eval/tools/f6-kill-drill.worker.cjs +131 -0
  57. package/eval/tools/gen-results.cjs +191 -0
  58. package/eval/tools/machine-test.cjs +200 -0
  59. package/eval/tools/manual-code-scenarios.md +59 -0
  60. package/eval/tools/replay-check.cjs +311 -0
  61. package/eval/tools/runner.cjs +219 -0
  62. package/eval/tools/session-log.cjs +106 -0
  63. package/eval/tools/summarize.cjs +185 -0
  64. package/eval/tools/t3-cells.cjs +173 -0
  65. package/package.json +73 -6
  66. package/patches/adapters-smoke.yml +41 -0
  67. package/patches/eval-account.yml +36 -0
  68. package/patches/eval-baseline.yml +33 -0
  69. package/patches/eval-stream-code-off.yml +46 -0
  70. package/patches/eval-stream-code-on.yml +47 -0
  71. package/patches/eval-stream.yml +54 -0
  72. package/patches/takeover.yml +42 -0
  73. package/patches/test-preset.yml +23 -0
  74. package/preset/stream/cordis.patch.yml +39 -0
  75. package/preset/stream/package.json +13 -0
  76. package/preset.yml +56 -0
  77. package/profiles/stream/README.md +66 -0
  78. package/profiles/stream/cordis.patch.yml +12 -0
  79. package/profiles/stream/package.json +17 -0
  80. package/profiles/stream-headless/package.json +16 -0
  81. package/scripts/build.mjs +103 -0
  82. package/scripts/check-consistency.mjs +146 -0
  83. package/scripts/gate.mjs +138 -0
  84. package/scripts/install-check.mjs +116 -0
  85. package/scripts/install-cycle.mjs +88 -0
  86. package/scripts/release.mjs +428 -0
  87. package/scripts/repair-session-logs.mjs +498 -0
  88. package/src/entry/action-gate.ts +206 -0
  89. package/src/entry/adapter-kit.ts +192 -0
  90. package/src/entry/context-render.ts +119 -0
  91. package/src/entry/control-bar-cli.ts +289 -0
  92. package/src/entry/control-bar.ts +123 -0
  93. package/src/entry/control-session.ts +115 -0
  94. package/src/entry/control-state.ts +125 -0
  95. package/src/entry/cordis-compat.ts +95 -0
  96. package/src/entry/eval-probe.ts +112 -0
  97. package/src/entry/intent-log.ts +121 -0
  98. package/src/entry/json-persistence.ts +306 -0
  99. package/src/entry/loop.ts +4163 -0
  100. package/src/entry/mock-provider.ts +549 -0
  101. package/src/entry/obs-broker.ts +178 -0
  102. package/src/entry/ptc-bridge.ts +405 -0
  103. package/src/entry/state-handle.ts +217 -0
  104. package/src/entry/takeover-registry.ts +60 -0
  105. package/src/kernel/control-bar.ts +559 -0
  106. package/src/kernel/final.ts +62 -0
  107. package/src/kernel/gate.ts +464 -0
  108. package/src/kernel/modes.ts +253 -0
  109. package/src/kernel/obs.ts +517 -0
  110. package/src/kernel/parser.ts +1081 -0
  111. package/src/kernel/render.ts +466 -0
  112. package/src/kernel/state.ts +416 -0
  113. package/src/version.ts +9 -0
  114. package/test/activation.test.ts +187 -0
  115. package/test/adapters.test.ts +676 -0
  116. package/test/control-bar.test.ts +486 -0
  117. package/test/desktop-ui.test.ts +359 -0
  118. package/test/eval-probe.test.ts +139 -0
  119. package/test/f5-plan.test.ts +221 -0
  120. package/test/f6-intent.test.ts +168 -0
  121. package/test/f7-segment.test.ts +190 -0
  122. package/test/fix-limits.test.ts +599 -0
  123. package/test/gate.test.ts +380 -0
  124. package/test/helpers/stub-loop.ts +240 -0
  125. package/test/host-conformance.test.ts +418 -0
  126. package/test/kernel/obs.test.ts +329 -0
  127. package/test/kernel/parser.test.ts +451 -0
  128. package/test/loop.test.ts +1393 -0
  129. package/test/mock-provider.test.ts +386 -0
  130. package/test/ptc-bridge.test.ts +356 -0
  131. package/test/render.test.ts +418 -0
  132. package/test/s2-install-check.test.ts +46 -0
  133. package/test/scenarios/3-file-basic.json +13 -0
  134. package/test/scenarios/5-file-basic.json +22 -0
  135. package/test/scenarios/burn-more.json +9 -0
  136. package/test/scenarios/degraded-final.json +10 -0
  137. package/test/scenarios/fault-abort-xml.json +11 -0
  138. package/test/scenarios/fault-malformed-command.json +12 -0
  139. package/test/scenarios/fault-midstream-abort.json +11 -0
  140. package/test/scenarios/fault-saturating-output.json +9 -0
  141. package/test/scenarios/fault-timeout.json +9 -0
  142. package/test/scenarios/peek-first.json +11 -0
  143. package/test/scenarios/peek-second.json +11 -0
  144. package/test/scenarios/peek-third.json +10 -0
  145. package/test/scenarios/recover-final.json +10 -0
  146. package/test/scenarios/reroute-first.json +17 -0
  147. package/test/scenarios/reroute-second.json +16 -0
  148. package/test/scenarios/starvation-final.json +10 -0
  149. package/test/scenarios/starvation-promote.json +11 -0
  150. package/test/scenarios/wait-tools-continue.json +10 -0
  151. package/test/scenarios/wait-tools-xml.json +22 -0
  152. package/test/scenarios/wait-tools.json +15 -0
  153. package/test/session-format.test.ts +234 -0
  154. package/test/state.test.ts +335 -0
  155. package/test/stream-v02.test.ts +264 -0
  156. package/test/v031-display.test.ts +333 -0
  157. package/test/v032-conflict.test.ts +191 -0
  158. package/test/v032-truncation.test.ts +291 -0
  159. package/ui/client.js +576 -0
  160. package/ui/index.js +282 -0
  161. package/ui/package.json +26 -0
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "reroute-second",
3
+ "match": { "promptIncludes": "tf-stream:error" },
4
+ "chunking": { "charsPerChunk": 0, "delayMs": 0 },
5
+ "steps": [
6
+ { "type": "text", "text": "收到失败报告,改道写 fixed.txt。\n" },
7
+ {
8
+ "type": "commands",
9
+ "commands": ["<tf-write path=\"fixed.txt\" id=\"wx\">FIXED</tf-write>"]
10
+ },
11
+ { "type": "waitTools", "count": 3, "timeoutMs": 5000 },
12
+ { "type": "text", "text": "完成。\n" },
13
+ { "type": "commands", "commands": ["<tf-final id=\"f2\" summary=\"改道成功\"/>"] },
14
+ { "type": "finish", "reason": "stop" }
15
+ ]
16
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "starvation-final",
3
+ "match": { "promptIncludes": "starvation-promoted" },
4
+ "chunking": { "charsPerChunk": 0, "delayMs": 0 },
5
+ "steps": [
6
+ { "type": "text", "text": "收到升格骨架,任务其实已完成。\n" },
7
+ { "type": "commands", "commands": ["<tf-final id=\"f1\" summary=\"文件已写,收尾\"/>"] },
8
+ { "type": "finish", "reason": "stop" }
9
+ ]
10
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "starvation-promote",
3
+ "match": { "promptIncludes": "请写一个文件然后停下" },
4
+ "chunking": { "charsPerChunk": 0, "delayMs": 0 },
5
+ "steps": [
6
+ { "type": "text", "text": "任务:写一个文件。\n" },
7
+ { "type": "commands", "commands": ["<tf-write path=\"only.txt\" id=\"w1\">独苗内容</tf-write>"] },
8
+ { "type": "waitTools", "count": 1, "timeoutMs": 5000 },
9
+ { "type": "finish", "reason": "stop" }
10
+ ]
11
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "wait-tools-continue",
3
+ "match": { "promptIncludes": "tf-stream:observation" },
4
+ "chunking": { "charsPerChunk": 0, "delayMs": 0 },
5
+ "steps": [
6
+ { "type": "text", "text": "骨架收到,任务已按计划完成。\n" },
7
+ { "type": "commands", "commands": ["<tf-final id=\"fc\" summary=\"两写一读完成(骨架确认)\"/>"] },
8
+ { "type": "finish", "reason": "stop" }
9
+ ]
10
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "name": "wait-tools-xml",
3
+ "match": { "promptIncludes": "先写两个文件再读回来" },
4
+ "chunking": { "charsPerChunk": 5, "delayMs": 0 },
5
+ "steps": [
6
+ { "type": "text", "text": "分两批:先写 a、b,等结果回来再读 a。\n" },
7
+ {
8
+ "type": "commands",
9
+ "commands": [
10
+ "<tf-write path=\"a.txt\" id=\"wa\">内容A</tf-write>",
11
+ "<tf-write path=\"b.txt\" id=\"wb\">内容B</tf-write>"
12
+ ]
13
+ },
14
+ { "type": "waitTools", "count": 2, "timeoutMs": 5000 },
15
+ { "type": "text", "text": "前两个文件已写。\n" },
16
+ { "type": "commands", "commands": ["<tf-read path=\"a.txt\" id=\"ra\" depends_on=\"wa,wb\"/>"] },
17
+ { "type": "waitTools", "count": 3, "timeoutMs": 5000 },
18
+ { "type": "text", "text": "读回确认,收尾。\n" },
19
+ { "type": "commands", "commands": ["<tf-final id=\"f1\" summary=\"两写一读完成\"/>"] },
20
+ { "type": "finish", "reason": "stop" }
21
+ ]
22
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "wait-tools",
3
+ "match": { "promptIncludes": "先写两个文件再读回来" },
4
+ "chunking": { "charsPerChunk": 6, "delayMs": 0 },
5
+ "steps": [
6
+ { "type": "text", "text": "分两批:先写 a、b,等结果回来再读 a。\n" },
7
+ { "type": "commands", "commands": ["tf-write a.txt \"内容A\"", "tf-write b.txt \"内容B\""] },
8
+ { "type": "waitTools", "count": 2, "timeoutMs": 5000 },
9
+ { "type": "text", "text": "前两个文件已写。\n" },
10
+ { "type": "commands", "commands": ["tf-read a.txt", "tf-final"] },
11
+ { "type": "waitTools", "count": 3, "timeoutMs": 5000 },
12
+ { "type": "text", "text": "读回确认,收尾。\n" },
13
+ { "type": "finish", "reason": "stop" }
14
+ ]
15
+ }
@@ -0,0 +1,234 @@
1
+ // test/session-format.test.ts —— v0.3.0:会话日志的 v4 工具生命周期回归
2
+ //
3
+ // 背景(真机事故):宿主的 v4 会话格式要求每个 tool/call 都能在同一 turn/step 的
4
+ // assistant/message 里找到同名同参的 tool-call 块,并且 step/end 时不得留下未解调用。
5
+ // 插件在 0.3.0 及更早版本里直接调 ctx.tools.execute(宿主管线负责落 tool/call +
6
+ // tool/result),却从未写过带 tool-call 块的 assistant/message → 读取时抛
7
+ // `tool/call <id> has no advertised tool lifecycle`,整条会话被判 corrupt,
8
+ // 桌面端表现为"历史加载失败"。
9
+ //
10
+ // 本测试用一个"宿主同款"的假工具管线(start → tool/call;commit → tool/result),
11
+ // 断言驱动器写出的会话事件满足生命周期约束。宿主的真实校验器在
12
+ // dsh-session-format-v3-to-v4;插件仓库不依赖宿主包,这里按同一规则本地复核。
13
+
14
+ import { describe, it } from 'node:test';
15
+ import assert from 'node:assert/strict';
16
+ import { readFileSync } from 'node:fs';
17
+ import { join } from 'node:path';
18
+
19
+ import { SingleStreamDriver, normalizeStreamShim, createSessionEventWriter } from '../src/entry/loop.ts';
20
+ import type { ToolBatchInputLike, ToolBatchResultLike } from '../src/entry/loop.ts';
21
+ import { createMockModel } from '../src/entry/mock-provider.ts';
22
+ import type { MockModel, Scenario } from '../src/entry/mock-provider.ts';
23
+
24
+ interface FakeEvent {
25
+ type: string;
26
+ seq: number;
27
+ time: number;
28
+ data: Record<string, unknown>;
29
+ surfaceOp?: string;
30
+ sourceEventSeqs?: number[];
31
+ }
32
+
33
+ interface FakeSession {
34
+ id: string;
35
+ readonly seq: number;
36
+ events: FakeEvent[];
37
+ append(type: string, data: unknown, opts?: { surfaceOp?: string; sourceEventSeqs?: number[] }): FakeEvent;
38
+ snapshotEvents(from?: number): FakeEvent[];
39
+ }
40
+
41
+ function createFakeSession(): FakeSession {
42
+ const events: FakeEvent[] = [];
43
+ let seq = 0;
44
+ return {
45
+ id: 'session-format-fixture',
46
+ get seq() {
47
+ return seq;
48
+ },
49
+ events,
50
+ append(type, data, opts) {
51
+ const event: FakeEvent = { type, seq: seq++, time: Date.now(), data: data as Record<string, unknown> };
52
+ if (opts?.surfaceOp !== undefined) event.surfaceOp = opts.surfaceOp;
53
+ if (opts?.sourceEventSeqs !== undefined) event.sourceEventSeqs = opts.sourceEventSeqs;
54
+ events.push(event);
55
+ return event;
56
+ },
57
+ snapshotEvents(from = 0) {
58
+ return events.slice(from);
59
+ },
60
+ };
61
+ }
62
+
63
+ function loadScenario(name: string): Scenario {
64
+ return JSON.parse(readFileSync(join(import.meta.dirname, 'scenarios', name), 'utf8')) as Scenario;
65
+ }
66
+
67
+ /** 宿主同款工具管线(dsh-tools/lib/pipeline.js:BatchSettlement):未落 result 时绝不返回。 */
68
+ function createHostLikeTools(session: FakeSession, options: { throwBeforeDispatch?: boolean } = {}) {
69
+ return async (input: ToolBatchInputLike): Promise<ToolBatchResultLike> => {
70
+ if (options.throwBeforeDispatch === true) throw new Error('host tool pipeline exploded before dispatch');
71
+ const results = [];
72
+ for (const call of input.calls) {
73
+ const content = [{ type: 'text' as const, text: `ok:${call.name}` }];
74
+ const callSeq = session.append('tool/call', {
75
+ turn: input.log?.turn,
76
+ step: input.log?.step,
77
+ callId: call.id,
78
+ name: call.name,
79
+ arguments: call.arguments,
80
+ }).seq;
81
+ session.append('tool/result', {
82
+ turn: input.log?.turn,
83
+ step: input.log?.step,
84
+ message: {
85
+ id: `tool-result-${call.id}`,
86
+ role: 'tool',
87
+ source: { kind: 'tool', callId: call.id },
88
+ toolCallId: call.id,
89
+ content,
90
+ },
91
+ }, { surfaceOp: 'append', sourceEventSeqs: [callSeq] });
92
+ results.push({ callId: call.id, result: { content, isError: false } });
93
+ }
94
+ return { results };
95
+ };
96
+ }
97
+
98
+ function createDriver(session: FakeSession, model: MockModel, tools: (input: ToolBatchInputLike) => Promise<ToolBatchResultLike>) {
99
+ return new SingleStreamDriver({
100
+ stream: (options) => normalizeStreamShim(model.adapter.stream({
101
+ provider: options.provider,
102
+ model: options.model,
103
+ messages: options.messages,
104
+ signal: options.signal,
105
+ })),
106
+ executeTools: tools,
107
+ events: createSessionEventWriter(session),
108
+ onToolSettled: () => model.notifyToolResult(),
109
+ }, { provider: 'mock', model: 'mock-scenario', streamIdleTimeoutMs: 30_000 });
110
+ }
111
+
112
+ /**
113
+ * 本地复核 v4 工具生命周期(与 dsh-session-format-v3-to-v4 的 tool()/closeTools 同规则):
114
+ * ① assistant/message 的 tool-call 块登记 pending(id 不得重复);
115
+ * ② tool/call 必须匹配 pending(同 name、同 arguments 字符串);
116
+ * ③ tool/result 必须闭合 pending;
117
+ * ④ step/end 前不得有未闭合调用;
118
+ * ⑤ assistant/message 必须落在打开的 turn+step 内(不允许 step/end 之后写)。
119
+ */
120
+ function assertToolLifecycle(events: readonly FakeEvent[]): void {
121
+ const pending = new Map<string, { name: unknown; arguments: unknown; started: boolean }>();
122
+ let turn: number | null = null;
123
+ let step: number | null = null;
124
+ for (const event of events) {
125
+ const data = event.data as { turn?: number; step?: number };
126
+ if (event.type === 'turn/start') {
127
+ turn = data.turn ?? null;
128
+ step = null;
129
+ pending.clear();
130
+ continue;
131
+ }
132
+ if (event.type === 'step/start') {
133
+ assert.equal(data.turn, turn, 'step/start 必须属于当前 turn');
134
+ step = data.step ?? null;
135
+ continue;
136
+ }
137
+ if (event.type === 'step/end') {
138
+ assert.equal(data.turn, turn, 'step/end 必须属于当前 turn');
139
+ assert.equal(data.step, step, 'step/end 必须闭合当前 step');
140
+ assert.equal(pending.size, 0, `step/end 不得留下未解工具调用(剩余 ${[...pending.keys()].join(',')})`);
141
+ step = null;
142
+ continue;
143
+ }
144
+ if (event.type === 'turn/end') {
145
+ turn = null;
146
+ step = null;
147
+ continue;
148
+ }
149
+ if (event.type === 'assistant/message') {
150
+ assert.equal(data.turn, turn, `${event.type}#${event.seq} 必须属于当前 turn`);
151
+ assert.equal(data.step, step, `${event.type}#${event.seq} 必须落在打开的 step 内(step/end 之后不得再写)`);
152
+ const message = (event.data as { message?: { content?: Array<{ type?: string; id?: string; name?: unknown; arguments?: unknown }> } }).message;
153
+ for (const block of message?.content ?? []) {
154
+ if (block.type !== 'tool-call') continue;
155
+ const id = String(block.id);
156
+ assert.equal(pending.has(id), false, `assistant/message 不得重复广告 tool-call ${id}`);
157
+ pending.set(id, { name: block.name, arguments: block.arguments, started: false });
158
+ }
159
+ continue;
160
+ }
161
+ if (event.type === 'tool/call') {
162
+ const callId = String((event.data as { callId?: unknown }).callId);
163
+ const entry = pending.get(callId);
164
+ assert.notEqual(entry, undefined, `tool/call ${callId} 没有同步骤的 assistant/message 广告(v4 corrupt)`);
165
+ assert.equal((event.data as { name?: unknown }).name, entry!.name, `tool/call ${callId} 的 name 必须与广告一致`);
166
+ assert.equal((event.data as { arguments?: unknown }).arguments, entry!.arguments, `tool/call ${callId} 的 arguments 必须与广告逐字节一致`);
167
+ entry!.started = true;
168
+ continue;
169
+ }
170
+ if (event.type === 'tool/result') {
171
+ const callId = String((event.data as { message?: { toolCallId?: unknown } }).message?.toolCallId);
172
+ const entry = pending.get(callId);
173
+ assert.notEqual(entry, undefined, `tool/result ${callId} 没有对应的广告/调用`);
174
+ if (!entry!.started) {
175
+ // 未开始的调用只接受宿主 TOOL_NOT_STARTED 修复形状
176
+ const message = (event.data as { message?: { id?: string; isError?: boolean } }).message;
177
+ const error = (event.data as { error?: { name?: string; code?: string } }).error;
178
+ assert.ok(String(message?.id).startsWith(`interrupted-tool-result-${callId}-`), `未开始调用的 result 必须是 TOOL_NOT_STARTED 修复形状(id 前缀)`);
179
+ assert.equal(message?.isError, true);
180
+ assert.equal(error?.name, 'ToolNotStartedError');
181
+ assert.equal(error?.code, 'TOOL_NOT_STARTED');
182
+ }
183
+ pending.delete(callId);
184
+ }
185
+ }
186
+ }
187
+
188
+ describe('S. 会话日志 v4 工具生命周期(v0.3.0 回归)', () => {
189
+ it('S1. 正常回合:每个 tool/call 前都有同步骤广告,且 step/end 前全部闭合', async () => {
190
+ const session = createFakeSession();
191
+ const model = createMockModel({ scenarios: [loadScenario('5-file-basic.json')], provider: 'mock' });
192
+ const driver = createDriver(session, model, createHostLikeTools(session));
193
+ driver.pushUserTask('请写五个文件:f1 到 f5。');
194
+ const reason = await driver.runTurn();
195
+ assert.equal(reason.kind, 'completed');
196
+ assertToolLifecycle(session.events);
197
+ const calls = session.events.filter((e) => e.type === 'tool/call');
198
+ assert.equal(calls.length, 5, '五个 tf-write 都应落到 tool/call');
199
+ const ads = session.events.filter((e) => e.type === 'assistant/message'
200
+ && (e.data as { message?: { content?: Array<{ type?: string }> } }).message?.content?.some((b) => b.type === 'tool-call'));
201
+ assert.equal(ads.length, 5, '每个 tool/call 前应有一条只含 tool-call 块的 assistant/message');
202
+ for (const call of calls) {
203
+ const ad = ads.find((a) => a.seq < call.seq);
204
+ assert.notEqual(ad, undefined, `tool/call#${call.seq} 之前必须有广告`);
205
+ }
206
+ });
207
+
208
+ it('S2. 派发前异常:广告被 TOOL_NOT_STARTED 修复闭合,日志仍满足生命周期', async () => {
209
+ const session = createFakeSession();
210
+ const model = createMockModel({ scenarios: [loadScenario('5-file-basic.json')], provider: 'mock' });
211
+ const driver = createDriver(session, model, createHostLikeTools(session, { throwBeforeDispatch: true }));
212
+ driver.pushUserTask('请写五个文件:f1 到 f5。');
213
+ await driver.runTurn();
214
+ assertToolLifecycle(session.events);
215
+ const ads = session.events.filter((e) => e.type === 'assistant/message'
216
+ && (e.data as { message?: { content?: Array<{ type?: string }> } }).message?.content?.some((b) => b.type === 'tool-call'));
217
+ const repairs = session.events.filter((e) => e.type === 'tool/result');
218
+ assert.ok(ads.length > 0, '至少有一个调用被广告后再派发失败');
219
+ assert.equal(repairs.length, ads.length, '每个广告都应在同步骤内被修复结果闭合');
220
+ });
221
+
222
+ it('S3. final 答案消息必须写在 step/end 之前(v4 要求打开的 turn+step)', async () => {
223
+ const session = createFakeSession();
224
+ const model = createMockModel({ scenarios: [loadScenario('5-file-basic.json')], provider: 'mock' });
225
+ const driver = createDriver(session, model, createHostLikeTools(session));
226
+ driver.pushUserTask('请写五个文件:f1 到 f5。');
227
+ const reason = await driver.runTurn();
228
+ assert.equal(reason.kind, 'completed');
229
+ assertToolLifecycle(session.events);
230
+ const lastAssistant = session.events.filter((e) => e.type === 'assistant/message').at(-1)!;
231
+ const lastStepEnd = session.events.filter((e) => e.type === 'step/end').at(-1)!;
232
+ assert.ok(lastAssistant.seq < lastStepEnd.seq, 'final answer 必须落在最后一个 step/end 之前');
233
+ });
234
+ });
@@ -0,0 +1,335 @@
1
+ // kernel/state.ts 单测(分派 02 验收)
2
+ // 运行:node --test test/ (Node ≥24 原生 TS type-stripping,零依赖)
3
+
4
+ import { test } from 'node:test';
5
+ import assert from 'node:assert/strict';
6
+ import {
7
+ StateStore,
8
+ MemoryBlobSink,
9
+ InvalidStateWriteError,
10
+ UnknownHandleError,
11
+ CycleError,
12
+ formatHandle,
13
+ parseHandle,
14
+ type BlobSink,
15
+ type StateHandle,
16
+ } from '../src/kernel/state.ts';
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // I2 不变量(验收:至少 3 个负例)
20
+ // ---------------------------------------------------------------------------
21
+
22
+ test('I2 负例 1:derived 写入不填 derivedFrom 必须抛 InvalidStateWriteError', () => {
23
+ const store = new StateStore();
24
+ assert.throws(
25
+ () => store.set('n1', 'v', { confidence: 'derived' }),
26
+ (e: unknown) => e instanceof InvalidStateWriteError && /I2 violation/.test(e.message),
27
+ );
28
+ });
29
+
30
+ test('I2 负例 2:derived 写入 derivedFrom 为空数组必须抛错(不许静默修正)', () => {
31
+ const store = new StateStore();
32
+ assert.throws(
33
+ () => store.set('n2', 'v', { confidence: 'derived', derivedFrom: [] }),
34
+ InvalidStateWriteError,
35
+ );
36
+ });
37
+
38
+ test('I2 负例 3:stated 写入携带 derivedFrom 必须抛错', () => {
39
+ const store = new StateStore();
40
+ assert.throws(
41
+ () => store.set('n3', 'v', { confidence: 'stated', derivedFrom: ['src'] }),
42
+ InvalidStateWriteError,
43
+ );
44
+ });
45
+
46
+ test('I2 负例 4:derivedFrom 含空字符串条目必须抛错', () => {
47
+ const store = new StateStore();
48
+ assert.throws(
49
+ () => store.set('n4', 'v', { confidence: 'derived', derivedFrom: ['ok', ''] }),
50
+ InvalidStateWriteError,
51
+ );
52
+ });
53
+
54
+ test('I2 正例:stated(缺省)与 derived(带来源)都合法,节点只读', () => {
55
+ const store = new StateStore();
56
+ const a = store.set('a', 1);
57
+ assert.equal(a.confidence, 'stated');
58
+ assert.equal(a.derivedFrom, undefined);
59
+ const b = store.set('b', 2, { confidence: 'derived', derivedFrom: ['a'] });
60
+ assert.deepEqual(b.derivedFrom, ['a']);
61
+ assert.throws(() => {
62
+ (b as { confidence: string }).confidence = 'stated';
63
+ });
64
+ });
65
+
66
+ test('I2 附带不变量:同一 id 重复写入抛错(节点不可变)', () => {
67
+ const store = new StateStore();
68
+ store.set('dup', 1);
69
+ assert.throws(() => store.set('dup', 2), InvalidStateWriteError);
70
+ });
71
+
72
+ // ---------------------------------------------------------------------------
73
+ // trace 来源链(验收:三级 derived 链,断言顺序与去重;含环检测)
74
+ // ---------------------------------------------------------------------------
75
+
76
+ test('trace:三级 derived 链返回完整来源(顺序:自身 → 逐级向上)', () => {
77
+ const store = new StateStore();
78
+ store.set('root', 'r'); // stated
79
+ store.set('l1', 'a', { confidence: 'derived', derivedFrom: ['root'] });
80
+ store.set('l2', 'b', { confidence: 'derived', derivedFrom: ['l1'] });
81
+ store.set('l3', 'c', { confidence: 'derived', derivedFrom: ['l2'] });
82
+
83
+ const chain = store.trace('l3');
84
+ assert.deepEqual(
85
+ chain.map((n) => n.id),
86
+ ['l3', 'l2', 'l1', 'root'],
87
+ );
88
+ assert.equal(chain[chain.length - 1].confidence, 'stated');
89
+ });
90
+
91
+ test('trace:菱形依赖去重(两个父节点共享同一祖先,祖先只出现一次)', () => {
92
+ const store = new StateStore();
93
+ store.set('r', 0);
94
+ store.set('x', 1, { confidence: 'derived', derivedFrom: ['r'] });
95
+ store.set('y', 2, { confidence: 'derived', derivedFrom: ['r'] });
96
+ store.set('top', 3, { confidence: 'derived', derivedFrom: ['x', 'y'] });
97
+
98
+ const chain = store.trace('top');
99
+ assert.deepEqual(
100
+ chain.map((n) => n.id),
101
+ ['top', 'x', 'r', 'y'],
102
+ );
103
+ const ids = chain.map((n) => n.id);
104
+ assert.equal(new Set(ids).size, ids.length, '必须无重复节点');
105
+ });
106
+
107
+ test('trace:环检测抛 CycleError(前向引用构造 A→B→A)', () => {
108
+ const store = new StateStore();
109
+ // 前向引用:写入时引用尚未存在的节点,环在 trace 展开期被检测
110
+ store.set('a', 1, { confidence: 'derived', derivedFrom: ['b'] });
111
+ store.set('b', 2, { confidence: 'derived', derivedFrom: ['a'] });
112
+ assert.throws(() => store.trace('a'), CycleError);
113
+ assert.throws(() => store.trace('b'), CycleError);
114
+ });
115
+
116
+ test('trace:未知节点抛 UnknownHandleError;来源节点缺失也抛 UnknownHandleError', () => {
117
+ const store = new StateStore();
118
+ assert.throws(() => store.trace('ghost'), UnknownHandleError);
119
+ store.set('orphan', 1, { confidence: 'derived', derivedFrom: ['ghost'] });
120
+ assert.throws(() => store.trace('orphan'), UnknownHandleError);
121
+ });
122
+
123
+ // ---------------------------------------------------------------------------
124
+ // 内容寻址幂等性(验收:同一内容写两次 handle 深比较相等)
125
+ // ---------------------------------------------------------------------------
126
+
127
+ test('同一内容写两次返回的 handle 深比较相等(blob 句柄)', () => {
128
+ const store = new StateStore();
129
+ const h1 = store.put('hello world');
130
+ const h2 = store.put('hello world');
131
+ assert.deepEqual(h1, h2);
132
+ assert.equal(formatHandle(h1), formatHandle(h2));
133
+ assert.match(formatHandle(h1), /^blob:[0-9a-f]{8}@v1$/);
134
+ assert.equal(h1.version, 1);
135
+ });
136
+
137
+ test('同一内容写两次返回的 handle 深比较相等(file 句柄)', () => {
138
+ const store = new StateStore();
139
+ const h1 = store.put('file content', { kind: 'file', path: 'src/app.ts' });
140
+ const h2 = store.put('file content', { kind: 'file', path: 'src/app.ts' });
141
+ assert.deepEqual(h1, h2);
142
+ assert.equal(formatHandle(h1), 'file:src/app.ts@v1');
143
+ });
144
+
145
+ test('同路径不同内容版本递增;重写旧内容版本号复用', () => {
146
+ const store = new StateStore();
147
+ const v1 = store.put('A', { kind: 'file', path: 'f.txt' });
148
+ const v2 = store.put('B', { kind: 'file', path: 'f.txt' });
149
+ assert.equal(v2.version, 2);
150
+ assert.notEqual(v1.hash, v2.hash);
151
+ const v1again = store.put('A', { kind: 'file', path: 'f.txt' });
152
+ assert.deepEqual(v1again, v1, '旧内容重写必须复用 v1');
153
+ const v3 = store.put('C', { kind: 'file', path: 'f.txt' });
154
+ assert.equal(v3.version, 3, '新内容接续最大版本号');
155
+ });
156
+
157
+ test('obs 句柄格式 obs:<tool>:<callId>@v<n>;file 缺 path / obs 缺 tool+callId 抛错', () => {
158
+ const store = new StateStore();
159
+ const h = store.put('stdout text', { kind: 'obs', tool: 'tf-bash', callId: 'call-7' });
160
+ assert.equal(formatHandle(h), 'obs:tf-bash:call-7@v1');
161
+ assert.deepEqual(store.put('stdout text', { kind: 'obs', tool: 'tf-bash', callId: 'call-7' }), h);
162
+ assert.throws(() => store.put('x', { kind: 'file' }), InvalidStateWriteError);
163
+ assert.throws(() => store.put('x', { kind: 'obs', tool: 't' }), InvalidStateWriteError);
164
+ });
165
+
166
+ test('get:字符串写入还原 string,字节写入还原 Uint8Array', () => {
167
+ const store = new StateStore();
168
+ const hs = store.put('中文文本');
169
+ assert.equal(store.get(hs), '中文文本');
170
+ const bytes = new Uint8Array([1, 2, 3, 0xff]);
171
+ const hb = store.put(bytes);
172
+ assert.deepEqual(store.get(hb), bytes);
173
+ });
174
+
175
+ test('get:伪造/版本不符/未知 kind 句柄抛 UnknownHandleError', () => {
176
+ const store = new StateStore();
177
+ const h = store.put('data', { kind: 'file', path: 'a.txt' });
178
+ assert.throws(
179
+ () => store.get({ ...h, version: 9 }),
180
+ (e: unknown) => e instanceof UnknownHandleError && /actual version/.test(e.message),
181
+ );
182
+ assert.throws(
183
+ () => store.get({ kind: 'weird' as never, path: 'a.txt', version: 1, hash: h.hash }),
184
+ UnknownHandleError,
185
+ );
186
+ assert.throws(() => store.get(null as never), UnknownHandleError);
187
+ });
188
+
189
+ test('handles:句柄目录按创建顺序返回且去重', () => {
190
+ const store = new StateStore();
191
+ const h1 = store.put('one', { kind: 'file', path: '1.txt' });
192
+ const h2 = store.put('blob-two');
193
+ store.put('one', { kind: 'file', path: '1.txt' }); // 重复,不应新增目录项
194
+ const all = store.handles();
195
+ assert.deepEqual(all.map(formatHandle), [formatHandle(h1), formatHandle(h2)]);
196
+ });
197
+
198
+ test('parseHandle:合法句柄往返解析;非法格式抛 UnknownHandleError', () => {
199
+ const h = parseHandle('file:src/app.ts@v3');
200
+ assert.equal(h.kind, 'file');
201
+ assert.equal(h.path, 'src/app.ts');
202
+ assert.equal(h.version, 3);
203
+ assert.equal(parseHandle('obs:tf-read:call-1@v2').kind, 'obs');
204
+ assert.equal(parseHandle('blob:1a2b3c4d@v1').path, '1a2b3c4d');
205
+ for (const bad of ['file:x@v0', 'file:x', 'file:@v1', 'weird:x@v1', 'blob:xyz@v1', 'file:x@vX']) {
206
+ assert.throws(() => parseHandle(bad), UnknownHandleError, `应拒绝: ${bad}`);
207
+ }
208
+ });
209
+
210
+ // ---------------------------------------------------------------------------
211
+ // diff
212
+ // ---------------------------------------------------------------------------
213
+
214
+ test('diff:内容一致返回空串', () => {
215
+ const store = new StateStore();
216
+ const a = store.put('same\nlines', { kind: 'file', path: 'x.ts' });
217
+ const b = store.put('same\nlines', { kind: 'file', path: 'x.ts' });
218
+ assert.equal(store.diff(a, b), '');
219
+ });
220
+
221
+ test('diff:混合增删改输出 unified 风格差异(无上下文行)', () => {
222
+ const store = new StateStore();
223
+ const from = store.put('a\nb\nc\nd\ne', { kind: 'file', path: 'f' });
224
+ const to = store.put('a\nX\nc\nd\ne\nf\ng', { kind: 'file', path: 'f' });
225
+ const text = store.diff(from, to);
226
+ assert.equal(text, [
227
+ `--- ${formatHandle(from)}`,
228
+ `+++ ${formatHandle(to)}`,
229
+ '@@ -2,1 +2,1 @@',
230
+ '-b',
231
+ '+X',
232
+ '@@ -5,0 +6,2 @@',
233
+ '+f',
234
+ '+g',
235
+ ].join('\n'));
236
+ });
237
+
238
+ test('diff:纯删除(count=0 用变更点前一行约定)与句柄头部还原内容', () => {
239
+ const store = new StateStore();
240
+ const from = store.put('keep\ndrop1\ndrop2\nkeep2', { kind: 'file', path: 'f' });
241
+ const to = store.put('keep\nkeep2', { kind: 'file', path: 'f' });
242
+ const text = store.diff(from, to);
243
+ assert.ok(text.includes('@@ -2,2 +1,0 @@'), text);
244
+ assert.ok(text.includes('-drop1') && text.includes('-drop2'), text);
245
+ // diff 结果可由句柄重新取回原文
246
+ assert.equal(store.get(from), 'keep\ndrop1\ndrop2\nkeep2');
247
+ });
248
+
249
+ test('diff:尾部纯删除(from 比 to 多出结尾行)', () => {
250
+ const store = new StateStore();
251
+ const from = store.put('head\nextra1\nextra2', { kind: 'file', path: 'f' });
252
+ const to = store.put('head', { kind: 'file', path: 'f' });
253
+ const text = store.diff(from, to);
254
+ assert.equal(text, [
255
+ `--- ${formatHandle(from)}`,
256
+ `+++ ${formatHandle(to)}`,
257
+ '@@ -2,2 +1,0 @@',
258
+ '-extra1',
259
+ '-extra2',
260
+ ].join('\n'));
261
+ });
262
+
263
+ // ---------------------------------------------------------------------------
264
+ // BlobSink 注入与错误传播
265
+ // ---------------------------------------------------------------------------
266
+
267
+ test('自定义 BlobSink 被用于读写(依赖注入走构造参数)', () => {
268
+ const writes: string[] = [];
269
+ const backing = new Map<string, Uint8Array>();
270
+ const sink: BlobSink = {
271
+ write(key, data) {
272
+ writes.push(key);
273
+ backing.set(key, data);
274
+ },
275
+ read(key) {
276
+ return backing.get(key);
277
+ },
278
+ };
279
+ const store = new StateStore(sink);
280
+ const h = store.put('sink test');
281
+ assert.deepEqual(writes, [h.hash]);
282
+ assert.equal(store.get(h), 'sink test');
283
+ });
284
+
285
+ test('sink 数据丢失时 get 抛 UnknownHandleError(BlobSink 是唯一 IO 出口)', () => {
286
+ const store = new StateStore({
287
+ write: () => {},
288
+ read: () => undefined,
289
+ });
290
+ const h = store.put('lost');
291
+ assert.throws(
292
+ () => store.get(h),
293
+ (e: unknown) => e instanceof UnknownHandleError && /blob missing/.test(e.message),
294
+ );
295
+ });
296
+
297
+ test('MemoryBlobSink 基本语义:写入可读回,未写键返回 undefined', () => {
298
+ const sink = new MemoryBlobSink();
299
+ const data = new Uint8Array([9, 8, 7]);
300
+ sink.write('k', data);
301
+ assert.deepEqual(sink.read('k'), data);
302
+ assert.equal(sink.read('missing'), undefined);
303
+ });
304
+
305
+ // ---------------------------------------------------------------------------
306
+ // sha256 正确性抽查
307
+ // ---------------------------------------------------------------------------
308
+
309
+ test('hash 是内容 sha256 hex(与已知向量比对)', () => {
310
+ const store = new StateStore();
311
+ const h = store.put('hello');
312
+ // sha256("hello") = 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
313
+ assert.equal(h.hash, '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824');
314
+ const hb = store.put(new Uint8Array([0xfc]));
315
+ // blob 句柄的 path 就是 hash 前 8 位(内容寻址一致性)
316
+ assert.equal(hb.path, hb.hash.slice(0, 8));
317
+ assert.equal(hb.kind, 'blob');
318
+ });
319
+
320
+ // ---------------------------------------------------------------------------
321
+ // 句柄类型完整性(供 06/07 适配层引用的形状断言)
322
+ // ---------------------------------------------------------------------------
323
+
324
+ test('StateHandle / StateNode 形状符合分派 02 接口设计', () => {
325
+ const store = new StateStore();
326
+ const handle: StateHandle = store.put('x', { kind: 'file', path: 'p' });
327
+ assert.equal(new Set(['file', 'blob', 'obs']).has(handle.kind), true);
328
+ assert.equal(typeof handle.version, 'number');
329
+ assert.equal(typeof handle.hash, 'string');
330
+
331
+ const node = store.set('shape', { any: 'value' }, { confidence: 'derived', derivedFrom: ['a'] });
332
+ void node; // derivedFrom 前向引用合法('a' 尚未写入),见 trace 负例
333
+ assert.equal(typeof node.createdAt, 'number');
334
+ assert.deepEqual(node.derivedFrom, ['a']);
335
+ });