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

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 (158) hide show
  1. package/CHANGELOG.md +497 -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 +3852 -0
  19. package/dist/entry/mock-provider.js +536 -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 +632 -0
  30. package/dist/kernel/render.js +444 -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 +415 -0
  87. package/scripts/repair-session-logs.mjs +403 -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 +3852 -0
  100. package/src/entry/mock-provider.ts +536 -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 +632 -0
  111. package/src/kernel/render.ts +444 -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/kernel/obs.test.ts +329 -0
  126. package/test/kernel/parser.test.ts +450 -0
  127. package/test/loop.test.ts +1393 -0
  128. package/test/mock-provider.test.ts +386 -0
  129. package/test/ptc-bridge.test.ts +356 -0
  130. package/test/render.test.ts +418 -0
  131. package/test/s2-install-check.test.ts +46 -0
  132. package/test/scenarios/3-file-basic.json +13 -0
  133. package/test/scenarios/5-file-basic.json +22 -0
  134. package/test/scenarios/burn-more.json +9 -0
  135. package/test/scenarios/degraded-final.json +10 -0
  136. package/test/scenarios/fault-abort-xml.json +11 -0
  137. package/test/scenarios/fault-malformed-command.json +12 -0
  138. package/test/scenarios/fault-midstream-abort.json +11 -0
  139. package/test/scenarios/fault-saturating-output.json +9 -0
  140. package/test/scenarios/fault-timeout.json +9 -0
  141. package/test/scenarios/peek-first.json +11 -0
  142. package/test/scenarios/peek-second.json +11 -0
  143. package/test/scenarios/peek-third.json +10 -0
  144. package/test/scenarios/recover-final.json +10 -0
  145. package/test/scenarios/reroute-first.json +17 -0
  146. package/test/scenarios/reroute-second.json +16 -0
  147. package/test/scenarios/starvation-final.json +10 -0
  148. package/test/scenarios/starvation-promote.json +11 -0
  149. package/test/scenarios/wait-tools-continue.json +10 -0
  150. package/test/scenarios/wait-tools-xml.json +22 -0
  151. package/test/scenarios/wait-tools.json +15 -0
  152. package/test/session-format.test.ts +234 -0
  153. package/test/state.test.ts +335 -0
  154. package/test/stream-v02.test.ts +264 -0
  155. package/test/v031-display.test.ts +333 -0
  156. package/ui/client.js +576 -0
  157. package/ui/index.js +282 -0
  158. package/ui/package.json +26 -0
@@ -0,0 +1,1393 @@
1
+ // test/loop.test.ts —— 分派 06:单流协议驱动器(SingleStreamDriver + StreamLoopAgent + AgentFactory)
2
+ //
3
+ // 覆盖分派 06 验收的 mock 半边:
4
+ // - mock E2E:5 文件 1 次调用;waitTools 挂起-重入;失败注入改道
5
+ // - O6 preflight fail-closed(prefix 断言违反 → 拒绝发送)
6
+ // - O5 预算阶梯(final-only 降级)
7
+ // - 双通道(原生 tool_call 阻塞回灌)
8
+ // - 看门狗超时 / 流中断的重入恢复
9
+ // - gate.admit 准入(allow / deny)
10
+ // - AgentFactory 生命周期(fake host:prepare → persistence → enter/announce → setup → dispose)
11
+ //
12
+ // 真连半边(DEEPSEEK_API_KEY)见 results/06-plugin-loop-results.md 的如实记录。
13
+
14
+ import { describe, it, beforeEach } from 'node:test';
15
+ import assert from 'node:assert/strict';
16
+ import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, readdirSync } from 'node:fs';
17
+ import { tmpdir } from 'node:os';
18
+ import { join } from 'node:path';
19
+ import { randomUUID } from 'node:crypto';
20
+
21
+ import {
22
+ SingleStreamDriver,
23
+ StreamLoopAgent,
24
+ createStreamAgentFactory,
25
+ normalizeStreamShim,
26
+ createSessionEventWriter,
27
+ DEFAULT_TOOL_MAPPING,
28
+ } from '../src/entry/loop.ts';
29
+ import applyLoopEntry from '../src/entry/loop.ts';
30
+ import { TfStreamParser } from '../src/kernel/parser.ts';
31
+ import type { TfCommand } from '../src/kernel/parser.ts';
32
+ import type {
33
+ DriverPorts,
34
+ StreamRequestOptions,
35
+ ToolBatchInputLike,
36
+ ToolBatchResultLike,
37
+ GatePort,
38
+ StreamDriverConfig,
39
+ } from '../src/entry/loop.ts';
40
+ import { createMockModel } from '../src/entry/mock-provider.ts';
41
+ import type { MockModel, Scenario } from '../src/entry/mock-provider.ts';
42
+ import { assertPrefixStable, PrefixBrokenError, ContextRenderer } from '../src/kernel/render.ts';
43
+
44
+ // ---------------------------------------------------------------------------
45
+ // 测试设施:沙箱执行器 + mock 端口装配
46
+ // ---------------------------------------------------------------------------
47
+
48
+ function loadScenario(name: string): Scenario {
49
+ const raw = JSON.parse(readFileSync(join(import.meta.dirname, 'scenarios', name), 'utf8')) as unknown;
50
+ return raw as Scenario;
51
+ }
52
+
53
+ function loadScenarios(...items: Array<string | Scenario>): Scenario[] {
54
+ // 顺序敏感:marker 更具体的剧本放前面(selectScenario 取第一个匹配)
55
+ return items.map((item) => (typeof item === 'string' ? loadScenario(item) : item));
56
+ }
57
+
58
+ interface SandboxHooks {
59
+ /** 让特定路径写入失败(路径含 fail → 拒绝),模拟执行失败重入路径 */
60
+ failPathsMatching?: string;
61
+ }
62
+
63
+ function createSandboxExecutor(sandboxDir: string, hooks: SandboxHooks = {}) {
64
+ return async (input: ToolBatchInputLike): Promise<ToolBatchResultLike> => {
65
+ const results: ToolBatchResultLike['results'] = [];
66
+ for (const call of input.calls) {
67
+ let args: Record<string, unknown> = {};
68
+ try {
69
+ args = JSON.parse(call.arguments) as Record<string, unknown>;
70
+ } catch {
71
+ results.push({ callId: call.id, result: { content: [{ type: 'text', text: `bad JSON arguments: ${call.arguments.slice(0, 80)}` }], isError: true } });
72
+ continue;
73
+ }
74
+ try {
75
+ if (call.name === 'write') {
76
+ const filePath = String(args['file_path'] ?? '');
77
+ if (hooks.failPathsMatching !== undefined && filePath.includes(hooks.failPathsMatching)) {
78
+ throw new Error(`EFAIL: sandbox policy rejected path "${filePath}"`);
79
+ }
80
+ const abs = join(sandboxDir, filePath);
81
+ mkdirSync(join(abs, '..'), { recursive: true });
82
+ writeFileSync(abs, String(args['content'] ?? ''), 'utf8');
83
+ results.push({ callId: call.id, result: { content: [{ type: 'text', text: `written ${filePath}` }], isError: false } });
84
+ } else if (call.name === 'read') {
85
+ const filePath = String(args['file_path'] ?? '');
86
+ const abs = join(sandboxDir, filePath);
87
+ const content = readFileSync(abs, 'utf8');
88
+ results.push({ callId: call.id, result: { content: [{ type: 'text', text: content }], isError: false } });
89
+ } else if (call.name === 'bash') {
90
+ results.push({ callId: call.id, result: { content: [{ type: 'text', text: `bash-echo:${String(args['command'] ?? '')}` }], isError: false } });
91
+ } else {
92
+ results.push({ callId: call.id, result: { content: [{ type: 'text', text: `unknown tool: ${call.name}` }], isError: true } });
93
+ }
94
+ } catch (error) {
95
+ results.push({ callId: call.id, result: { content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }], isError: true } });
96
+ }
97
+ }
98
+ return { results, additionalContexts: [], concluded: false };
99
+ };
100
+ }
101
+
102
+ interface Harness {
103
+ driver: SingleStreamDriver;
104
+ model: MockModel;
105
+ wireRequests: Array<StreamRequestOptions & { contentTexts: string[] }>;
106
+ sandboxDir: string;
107
+ cleanup: () => void;
108
+ }
109
+
110
+ function makeHarness(opts: {
111
+ task: string;
112
+ scenarios: Scenario[];
113
+ config?: Partial<StreamDriverConfig>;
114
+ gate?: GatePort;
115
+ sandboxHooks?: SandboxHooks;
116
+ onToolSettled?: () => void;
117
+ streamWrapper?: (options: StreamRequestOptions, inner: AsyncIterable<import('../src/entry/mock-provider.ts').StreamChunk>) => AsyncIterable<import('../src/entry/mock-provider.ts').StreamChunk>;
118
+ }): Harness {
119
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-loop-'));
120
+ const model = createMockModel({ scenarios: opts.scenarios, provider: 'mock' });
121
+ const wireRequests: Array<StreamRequestOptions & { contentTexts: string[] }> = [];
122
+ const ports: DriverPorts = {
123
+ stream: (options) => {
124
+ const inner = model.adapter.stream({
125
+ provider: options.provider,
126
+ model: options.model,
127
+ messages: options.messages,
128
+ signal: options.signal,
129
+ });
130
+ wireRequests.push({ ...options, contentTexts: options.messages.map((m) => m.content.map((b) => b.text ?? '').join('\n')) });
131
+ const normalized = normalizeStreamShim(inner);
132
+ return opts.streamWrapper !== undefined ? opts.streamWrapper(options, normalized) : normalized;
133
+ },
134
+ executeTools: createSandboxExecutor(sandboxDir, opts.sandboxHooks),
135
+ // mock waitTools 的回灌信号源(05 号交接 §7.1):每个工具落定 → notifyToolResult
136
+ onToolSettled: () => {
137
+ model.notifyToolResult();
138
+ opts.onToolSettled?.();
139
+ },
140
+ gate: opts.gate,
141
+ };
142
+ const config: StreamDriverConfig = {
143
+ provider: 'mock',
144
+ model: 'mock-scenario',
145
+ streamIdleTimeoutMs: opts.config?.streamIdleTimeoutMs ?? 30_000,
146
+ ...opts.config,
147
+ };
148
+ const driver = new SingleStreamDriver(ports, config);
149
+ driver.pushUserTask(opts.task);
150
+ return {
151
+ driver,
152
+ model,
153
+ wireRequests,
154
+ sandboxDir,
155
+ cleanup: () => rmSync(sandboxDir, { recursive: true, force: true }),
156
+ };
157
+ }
158
+
159
+ function lastReasonOf(snapshot: ReturnType<SingleStreamDriver['snapshot']>): string {
160
+ const ends = snapshot.records.filter((r) => r.kind === 'turn-end');
161
+ const last = ends[ends.length - 1];
162
+ assert.ok(last !== undefined && last.kind === 'turn-end', '必须有 turn-end 记录');
163
+ return last.reason.kind;
164
+ }
165
+
166
+ function faultsOf(snapshot: ReturnType<SingleStreamDriver['snapshot']>): Array<Extract<ReturnType<SingleStreamDriver['snapshot']>['records'][number], { kind: 'fault' }>> {
167
+ return snapshot.records.filter((r): r is Extract<ReturnType<SingleStreamDriver['snapshot']>['records'][number], { kind: 'fault' }> => r.kind === 'fault');
168
+ }
169
+
170
+ /** 消息数组公共前缀长度(role + 文本逐字节) */
171
+ function commonPrefixLen(a: Array<{ role: string; content: string }>, b: Array<{ role: string; content: string }>): number {
172
+ let i = 0;
173
+ while (i < a.length && i < b.length && a[i]!.role === b[i]!.role && a[i]!.content === b[i]!.content) i += 1;
174
+ return i;
175
+ }
176
+
177
+ // ---------------------------------------------------------------------------
178
+ // A. mock E2E —— 分派 06 验收三条
179
+ // ---------------------------------------------------------------------------
180
+
181
+ describe('A. mock E2E(验收核心)', () => {
182
+ let harness: Harness;
183
+ beforeEach(() => {
184
+ harness?.cleanup();
185
+ });
186
+
187
+ it('A1. 5 文件任务:模型调用次数 = 1,零注入,全部落盘(核心命题)', async () => {
188
+ harness = makeHarness({
189
+ task: '请写五个文件:f1 到 f5。',
190
+ scenarios: loadScenarios('5-file-basic.json'),
191
+ });
192
+ try {
193
+ const reason = await harness.driver.runTurn();
194
+ assert.equal(reason.kind, 'completed');
195
+ const snap = harness.driver.snapshot();
196
+ assert.equal(snap.requestCount, 1, `写 5 文件任务应只发 1 次模型请求,实际 ${snap.requestCount}`);
197
+ assert.equal(harness.model.calls.length, 1);
198
+
199
+ for (let i = 1; i <= 5; i++) {
200
+ const p = join(harness.sandboxDir, `f${i}.txt`);
201
+ assert.ok(existsSync(p), `f${i}.txt 应存在`);
202
+ assert.equal(readFileSync(p, 'utf8'), `内容${['一', '二', '三', '四', '五'][i - 1]}`);
203
+ }
204
+
205
+ // 成功路径零注入:写类观测全部 low receipt,injected_ratio = 0
206
+ const counters = snap.counters();
207
+ assert.equal(counters.produced, 5, '5 次写观测(produced)');
208
+ assert.equal(counters.injected, 0, '成功写路径零注入');
209
+ assert.equal(counters.injectedRatio, 0);
210
+ assert.equal(counters.injectedRatio <= 0.2, true, '验收线 injected_ratio ≤ 0.2');
211
+
212
+ // ledger:5 条工具成功 + final
213
+ const okCommands = snap.records.filter((r) => r.kind === 'command' && r.status === 'ok');
214
+ assert.equal(okCommands.length, 6, '5 写 + 1 final'); // tf-final 也记为 ok
215
+ const final = snap.records.find((r) => r.kind === 'final');
216
+ assert.ok(final !== undefined && final.kind === 'final');
217
+ assert.equal(final.summary, '五个文件已写');
218
+ assert.equal(lastReasonOf(snap), 'completed');
219
+ } finally {
220
+ harness.cleanup();
221
+ }
222
+ });
223
+
224
+ it('A2. waitTools 挂起-重入:依赖有序、单流内完成;high 观测按重入规则注入骨架', async () => {
225
+ harness = makeHarness({
226
+ task: '先写两个文件再读回来。',
227
+ scenarios: loadScenarios('wait-tools-continue.json', 'wait-tools-xml.json'),
228
+ });
229
+ try {
230
+ const reason = await harness.driver.runTurn();
231
+ assert.equal(reason.kind, 'completed');
232
+ const snap = harness.driver.snapshot();
233
+ // 请求 1 = 单流(两写一读 + tf-final,waitTools 挂起-重入全部发生在流内);
234
+ // 请求 2 = read 的 high 骨架按"三种重入事由"注入(模型永不在信息真空里收尾)
235
+ assert.equal(snap.requestCount, 2, `1 流内完成 + 1 骨架重入,实际 ${snap.requestCount}`);
236
+ assert.equal(harness.model.calls.length, 2);
237
+
238
+ const records = snap.records;
239
+ const seqOf = (pred: (r: (typeof records)[number]) => boolean): number => {
240
+ const hit = records.find(pred);
241
+ assert.ok(hit !== undefined, '缺少预期记录');
242
+ return hit.seq;
243
+ };
244
+ const wbOk = seqOf((r) => r.kind === 'command' && r.status === 'ok' && r.id === 'wb');
245
+ const waOk = seqOf((r) => r.kind === 'command' && r.status === 'ok' && r.id === 'wa');
246
+ const raDispatched = seqOf((r) => r.kind === 'command' && r.status === 'dispatched' && r.id === 'ra');
247
+ const finalSeq = seqOf((r) => r.kind === 'final');
248
+ assert.ok(raDispatched > wbOk && raDispatched > waOk, 'tf-read 必须在两个写完成后才派发(depends_on 语义)');
249
+ assert.ok(finalSeq > raDispatched, 'tf-final 在读之后(waitTools(3) 挂起点证明:挂起-重入发生在同一流内)');
250
+ assert.equal(readFileSync(join(harness.sandboxDir, 'a.txt'), 'utf8'), '内容A');
251
+
252
+ // 请求 2 注入自写回验 receipt(修复限制 1:a.txt 由本任务 tf-write 写过,不再回灌全文),
253
+ // 模型确认后再次 tf-final 收敛
254
+ // (句柄版本号按 obs key=path 计:a.txt 的写回执是 v1,read 观测是 v2)
255
+ const req2 = harness.wireRequests[1]!;
256
+ const receiptBlock = req2.contentTexts.find((t) => t.includes('[tf-stream:receipt') && t.includes('path=a.txt'));
257
+ assert.ok(receiptBlock !== undefined, `请求 2 应注入自写回验 receipt,实际消息:\n${req2.contentTexts.join('\n---\n').slice(0, 2000)}`);
258
+ assert.ok(receiptBlock.includes('lines=') && /sha256=[0-9a-f]{16}/.test(receiptBlock), 'receipt 应携带行数与内容指纹');
259
+ assert.ok(!receiptBlock.includes('内容A'), 'receipt 不得回灌自写文件全文');
260
+ const counters = snap.counters();
261
+ assert.equal(counters.produced, 3);
262
+ assert.equal(counters.injected, 2, 'receipt 路径计数口径不变:骨架位 + receipt peek 合计 2');
263
+ assert.equal(lastReasonOf(snap), 'completed');
264
+ } finally {
265
+ harness.cleanup();
266
+ }
267
+ });
268
+
269
+ it('A3. 失败注入改道:结构化错误进下一请求,模型改道成功,调用次数 = 2', async () => {
270
+ harness = makeHarness({
271
+ task: '改道演练:写 a.txt 和 fail.txt(fail.txt 会被沙箱拒绝)。',
272
+ scenarios: loadScenarios('reroute-second.json', 'reroute-first.json'),
273
+ sandboxHooks: { failPathsMatching: 'fail' },
274
+ config: { maxReentries: 8 },
275
+ });
276
+ try {
277
+ const reason = await harness.driver.runTurn();
278
+ assert.equal(reason.kind, 'completed');
279
+ const snap = harness.driver.snapshot();
280
+ assert.equal(snap.requestCount, 2, `失败改道应恰好 2 次请求,实际 ${snap.requestCount}`);
281
+ assert.equal(harness.model.calls.length, 2);
282
+
283
+ // 沙箱结果:a.txt 成功、fail.txt 不存在、fixed.txt 改道成功
284
+ assert.ok(existsSync(join(harness.sandboxDir, 'a.txt')));
285
+ assert.ok(!existsSync(join(harness.sandboxDir, 'fail.txt')), '失败目标不得存在');
286
+ assert.ok(existsSync(join(harness.sandboxDir, 'fixed.txt')));
287
+ assert.equal(readFileSync(join(harness.sandboxDir, 'fixed.txt'), 'utf8'), 'FIXED');
288
+
289
+ // 请求 2 携带结构化错误(command id + 失败原因 + 可改写建议)
290
+ const req2 = harness.wireRequests[1]!;
291
+ const errBlock = req2.contentTexts.find((t) => t.includes('[tf-stream:error id=wf cmd=tf-write target=fail.txt]'));
292
+ assert.ok(errBlock !== undefined, `请求 2 应包含 wf 的结构化错误块,实际消息:\n${req2.contentTexts.join('\n---\n').slice(0, 2000)}`);
293
+ assert.ok(errBlock.includes('EFAIL'), '错误块应包含失败原因');
294
+ assert.ok(errBlock.includes('建议:'), '错误块应包含可改写建议');
295
+
296
+ // ledger:wa ok / wf failed / wx ok / final
297
+ const statuses = snap.records
298
+ .filter((r): r is Extract<(typeof snap.records)[number], { kind: 'command' }> => r.kind === 'command')
299
+ .filter((r) => ['wa', 'wf', 'wx'].includes(r.id));
300
+ assert.equal(statuses.filter((r) => r.status === 'ok').length, 2);
301
+ assert.ok(statuses.some((r) => r.id === 'wf' && r.status === 'failed'));
302
+ assert.equal(lastReasonOf(snap), 'completed');
303
+ } finally {
304
+ harness.cleanup();
305
+ }
306
+ });
307
+ });
308
+
309
+ // ---------------------------------------------------------------------------
310
+ // B. O6 前缀断言(fail-closed)与 prefix 单调
311
+ // ---------------------------------------------------------------------------
312
+
313
+ describe('B. O6 preflight 前缀断言', () => {
314
+ let harness: Harness | undefined;
315
+ beforeEach(() => { harness?.cleanup(); harness = undefined; });
316
+
317
+ it('B1. preflight 违反 → render() 抛 PrefixBrokenError → runTurn 拒绝且不再发请求(fail-closed)', async () => {
318
+ // 内核 render.ts 的公共 API 结构上不可能破坏前缀(append-only + truncateAppendTail
319
+ // 显式推进基线,04 号已单测)——O6 断言防的是"装配器被 bug 绕过"。
320
+ // 这里用包装 renderer 模拟第二次装配时稳定段被改写,验证驱动器侧的处理:
321
+ // 拒绝发送、不吞错、turn 以 DRIVER_ERROR 收场。
322
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-loop-'));
323
+ try {
324
+ const model = createMockModel({
325
+ scenarios: [{
326
+ name: 'break-prefix',
327
+ match: { promptIncludes: '前缀破坏演练' },
328
+ chunking: { charsPerChunk: 0, delayMs: 0 },
329
+ steps: [
330
+ { type: 'text', text: '开始。\n' },
331
+ { type: 'commands', commands: ['<tf-write path="p.txt" id="wp">P</tf-write>'] },
332
+ { type: 'waitTools', count: 1, timeoutMs: 5000 },
333
+ { type: 'finish', reason: 'stop' },
334
+ ],
335
+ }],
336
+ provider: 'mock',
337
+ });
338
+ const base = new ContextRenderer({
339
+ system: 'sys',
340
+ protocol: 'proto',
341
+ toolSchemas: 'tools',
342
+ invariants: 'inv',
343
+ });
344
+ let renders = 0;
345
+ const brokenRenderer = {
346
+ appendHistory: (m: { role: 'user' | 'assistant' | 'tool'; content: string }) => base.appendHistory(m),
347
+ appendHandleDelta: (d: never) => base.appendHandleDelta(d),
348
+ setTail: (t: Array<{ role?: 'user' | 'assistant' | 'tool' | 'system'; content: string }>) => base.setTail(t),
349
+ stableHash: () => base.stableHash(),
350
+ render: () => {
351
+ renders += 1;
352
+ if (renders >= 2) throw new PrefixBrokenError(0, 'old', 'mutated', '模拟装配被改写');
353
+ return base.render();
354
+ },
355
+ } as unknown as ContextRenderer;
356
+ const driver = new SingleStreamDriver(
357
+ {
358
+ stream: (o) => normalizeStreamShim(model.adapter.stream({ provider: o.provider, model: o.model, messages: o.messages, signal: o.signal })),
359
+ executeTools: createSandboxExecutor(sandboxDir),
360
+ },
361
+ { provider: 'mock', model: 'm' },
362
+ brokenRenderer,
363
+ );
364
+ driver.pushUserTask('前缀破坏演练:写一个文件。');
365
+ await assert.rejects(
366
+ () => driver.runTurn(),
367
+ (error: unknown) => error instanceof PrefixBrokenError,
368
+ 'O6 preflight 必须拒绝发送(fail-closed)',
369
+ );
370
+ const snap = driver.snapshot();
371
+ assert.equal(snap.requestCount, 1, '违反前缀断言后不得发出第二个请求');
372
+ assert.ok(snap.records.some((r) => r.kind === 'fault' && r.fault === 'driver-error'), '驱动器异常应有 fault 记录(fail-open 不静默)');
373
+ } finally {
374
+ rmSync(sandboxDir, { recursive: true, force: true });
375
+ }
376
+ });
377
+
378
+ it('B2. 失败改道全程:请求稳定前缀逐字节单调(renderHash/stableHash 可对账)', async () => {
379
+ harness = makeHarness({
380
+ task: '改道演练:写 a.txt 和 fail.txt(fail.txt 会被沙箱拒绝)。',
381
+ scenarios: loadScenarios('reroute-second.json', 'reroute-first.json'),
382
+ sandboxHooks: { failPathsMatching: 'fail' },
383
+ });
384
+ try {
385
+ await harness.driver.runTurn();
386
+ const snap = harness.driver.snapshot();
387
+ assert.equal(snap.requestCount, 2);
388
+ // preflight 已在 render() 内逐请求断言(B 通过 = 断言全程未抛)
389
+ assert.equal(snap.stableHashes.length, 2);
390
+ assert.notEqual(snap.stableHashes[0], snap.stableHashes[1], '追加区只增 → 稳定段哈希必变');
391
+
392
+ // 独立复核:请求 1 的稳定段(去掉易变尾)必须是请求 2 消息的前缀。
393
+ // 易变尾大小由 request 记录的 injectionBlocks 给出(本请求注入块数)。
394
+ const requestRecords = snap.records.filter((r): r is Extract<(typeof snap.records)[number], { kind: 'request' }> => r.kind === 'request');
395
+ const req1 = harness.wireRequests[0]!.messages.map((m) => ({ role: m.role, content: m.content.map((b) => b.text ?? '').join('\n') }));
396
+ const req2 = harness.wireRequests[1]!.messages.map((m) => ({ role: m.role, content: m.content.map((b) => b.text ?? '').join('\n') }));
397
+ const stableLen1 = req1.length - requestRecords[0]!.injectionBlocks;
398
+ const prefix = commonPrefixLen(req1, req2);
399
+ assert.ok(
400
+ prefix >= stableLen1,
401
+ `请求 2 的稳定段必须逐字节包含请求 1 的稳定段(commonPrefix=${prefix} ≥ stable=${stableLen1})`,
402
+ );
403
+ // 复核前缀断言本身(双保险:内核 assertPrefixStable 直接跑一遍)
404
+ assert.doesNotThrow(() => assertPrefixStable(req1.slice(0, stableLen1), req2.slice(0, prefix)));
405
+ // 系统消息全程字节不变
406
+ assert.equal(req1[0]!.content, req2[0]!.content);
407
+ } finally {
408
+ harness.cleanup();
409
+ }
410
+ });
411
+ });
412
+
413
+ // ---------------------------------------------------------------------------
414
+ // C. 重入护栏:流故障恢复 / 看门狗 / 中断恢复
415
+ // ---------------------------------------------------------------------------
416
+
417
+ describe('C. 流故障与重入护栏', () => {
418
+ let harness: Harness | undefined;
419
+ beforeEach(() => { harness?.cleanup(); harness = undefined; });
420
+
421
+ it('C1. 流空闲超时 → 看门狗 abort → aborted finish 记录 → nudge 重入收敛', async () => {
422
+ harness = makeHarness({
423
+ task: '故障注入:流超时演练。',
424
+ scenarios: loadScenarios('recover-final.json', 'fault-timeout.json'),
425
+ config: { streamIdleTimeoutMs: 200 },
426
+ });
427
+ try {
428
+ const started = Date.now();
429
+ const reason = await harness.driver.runTurn();
430
+ const elapsed = Date.now() - started;
431
+ assert.equal(reason.kind, 'completed');
432
+ assert.ok(elapsed < 15_000, `看门狗应在 200ms 掐断流,实际 ${elapsed}ms`);
433
+ const snap = harness.driver.snapshot();
434
+ assert.equal(snap.requestCount, 2);
435
+ assert.ok(faultsOf(snap).some((f) => f.fault === 'stream-aborted'), '应有 stream-aborted fault');
436
+ assert.ok(faultsOf(snap).some((f) => f.fault === 'missing-final-nudge'), '应有 nudge fault');
437
+ } finally {
438
+ harness.cleanup();
439
+ }
440
+ });
441
+
442
+ it('C2. 流中断(midstream abort)→ error finish 归一化 → nudge 重入收敛', async () => {
443
+ harness = makeHarness({
444
+ task: '故障注入:流中断演练。',
445
+ scenarios: loadScenarios('recover-final.json', 'fault-abort-xml.json'),
446
+ });
447
+ try {
448
+ const reason = await harness.driver.runTurn();
449
+ assert.equal(reason.kind, 'completed');
450
+ const snap = harness.driver.snapshot();
451
+ assert.equal(snap.requestCount, 2);
452
+ assert.ok(faultsOf(snap).some((f) => f.fault === 'stream-error'), '应有 stream-error fault');
453
+ // 中断前已派发的写命令照常落盘(部分成果保留)
454
+ assert.ok(existsSync(join(harness.sandboxDir, 'a.txt')));
455
+ } finally {
456
+ harness.cleanup();
457
+ }
458
+ });
459
+
460
+ it('C3. 无 tf-final 且无重入事由 → 一次性 nudge;再不收敛 → blocked(护栏)', async () => {
461
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-loop-'));
462
+ const model = createMockModel({
463
+ scenarios: [{
464
+ name: 'never-final',
465
+ match: { promptIncludes: '不收敛演练' },
466
+ chunking: { charsPerChunk: 0, delayMs: 0 },
467
+ steps: [
468
+ { type: 'text', text: '我就是不输出 tf-final。\n' },
469
+ { type: 'finish', reason: 'stop' },
470
+ ],
471
+ }],
472
+ provider: 'mock',
473
+ });
474
+ const ports: DriverPorts = {
475
+ stream: (options) => normalizeStreamShim(model.adapter.stream({ provider: options.provider, model: options.model, messages: options.messages, signal: options.signal })),
476
+ executeTools: createSandboxExecutor(sandboxDir),
477
+ };
478
+ const driver = new SingleStreamDriver(ports, { provider: 'mock', model: 'm' });
479
+ driver.pushUserTask('不收敛演练。');
480
+ try {
481
+ const reason = await driver.runTurn();
482
+ assert.equal(reason.kind, 'blocked');
483
+ const snap = driver.snapshot();
484
+ assert.equal(snap.requestCount, 2, 'nudge 一次后第二次仍无 final → blocked');
485
+ assert.ok(faultsOf(snap).some((f) => f.fault === 'turn-blocked'));
486
+ } finally {
487
+ rmSync(sandboxDir, { recursive: true, force: true });
488
+ }
489
+ });
490
+
491
+ it('C4. maxReentries 护栏:失败永不修复 → blocked', async () => {
492
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-loop-'));
493
+ const model = createMockModel({
494
+ scenarios: [{
495
+ name: 'always-fails',
496
+ match: { promptIncludes: '重入护栏演练' },
497
+ chunking: { charsPerChunk: 0, delayMs: 0 },
498
+ steps: [
499
+ { type: 'text', text: '每次都写同一个失败路径。\n' },
500
+ { type: 'commands', commands: ['<tf-write path="fail.txt" id="wf1">X</tf-write>'] },
501
+ { type: 'waitTools', count: 1, timeoutMs: 5000 },
502
+ { type: 'commands', commands: ['<tf-write path="fail.txt" id="wf2">X</tf-write>'] },
503
+ { type: 'waitTools', count: 2, timeoutMs: 5000 },
504
+ { type: 'finish', reason: 'stop' },
505
+ ],
506
+ }],
507
+ provider: 'mock',
508
+ });
509
+ const ports: DriverPorts = {
510
+ stream: (options) => normalizeStreamShim(model.adapter.stream({ provider: options.provider, model: options.model, messages: options.messages, signal: options.signal })),
511
+ executeTools: createSandboxExecutor(sandboxDir, { failPathsMatching: 'fail' }),
512
+ };
513
+ const driver = new SingleStreamDriver(ports, { provider: 'mock', model: 'm', maxReentries: 2 });
514
+ driver.pushUserTask('重入护栏演练。');
515
+ try {
516
+ const reason = await driver.runTurn();
517
+ assert.equal(reason.kind, 'blocked');
518
+ const snap = driver.snapshot();
519
+ assert.ok(snap.requestCount <= 4, `护栏应限制重入,实际 ${snap.requestCount} 次`);
520
+ } finally {
521
+ rmSync(sandboxDir, { recursive: true, force: true });
522
+ }
523
+ });
524
+ });
525
+
526
+ // ---------------------------------------------------------------------------
527
+ // D. O5 预算阶梯
528
+ // ---------------------------------------------------------------------------
529
+
530
+ describe('D. O5 预算阶梯', () => {
531
+ let harness: Harness | undefined;
532
+ beforeEach(() => { harness?.cleanup(); harness = undefined; });
533
+
534
+ it('D1. 预算耗尽 → final-only 档:降级交付通知,不再注入观测,tf-final 后收敛', async () => {
535
+ // 剧本链:请求1(normal)失败注入 → 请求2(final-only,错误块已注入但不修复、不 final)
536
+ // → 降级交付通知(degraded 分支)→ 请求3(final-only)tf-final 收敛。
537
+ harness = makeHarness({
538
+ task: '预算阶梯演练:写 a.txt 和 fail.txt(fail.txt 会被沙箱拒绝)。',
539
+ scenarios: loadScenarios('burn-more.json', 'degraded-final.json', {
540
+ name: 'budget-burn',
541
+ match: { promptIncludes: '预算阶梯演练' },
542
+ chunking: { charsPerChunk: 0, delayMs: 0 },
543
+ steps: [
544
+ { type: 'text', text: '写文件。\n' },
545
+ { type: 'commands', commands: ['<tf-write path="fail.txt" id="wf">F</tf-write>'] },
546
+ { type: 'waitTools', count: 1, timeoutMs: 5000 },
547
+ { type: 'finish', reason: 'stop' },
548
+ ],
549
+ }),
550
+ sandboxHooks: { failPathsMatching: 'fail' },
551
+ config: { budgetTokens: 50 }, // 极小预算:请求 1 的 usage 直接击穿 90% 线
552
+ });
553
+ try {
554
+ const reason = await harness.driver.runTurn();
555
+ assert.equal(reason.kind, 'completed');
556
+ const snap = harness.driver.snapshot();
557
+ const requestRecords = snap.records.filter((r): r is Extract<(typeof snap.records)[number], { kind: 'request' }> => r.kind === 'request');
558
+ assert.equal(requestRecords.length, 3, `剧本链应 3 次请求,实际 ${snap.requestCount}`);
559
+ assert.equal(requestRecords[0]!.level, 'normal');
560
+ assert.equal(requestRecords[requestRecords.length - 1]!.level, 'final-only', '预算击穿后应进入 final-only 档');
561
+ assert.ok(faultsOf(snap).some((f) => f.fault === 'degraded-delivery'), '应有降级交付记录');
562
+ // 请求 3 的易变尾是降级交付通知(不是常规 nudge),且尾块不再携带观测/错误注入
563
+ //(断言只看最后一条 user 消息——系统提示的协议文本里含 "[tf-stream:error]" 字样,
564
+ // 全消息扫描会误报)
565
+ const req3 = harness.wireRequests[2]!;
566
+ const tailTexts = req3.contentTexts.slice(req3.contentTexts.length - req3.messages.filter((m) => m.role === 'user').length);
567
+ assert.ok(
568
+ tailTexts.some((t) => t.includes('tf-stream:degraded')),
569
+ 'final-only 档应注入降级交付通知',
570
+ );
571
+ assert.ok(!tailTexts.some((t) => t.includes('[tf-stream:error')), 'final-only 档不得再注入错误块');
572
+ } finally {
573
+ harness.cleanup();
574
+ }
575
+ });
576
+
577
+ it('D2. 阶梯阈值单元:70%/90% 两档', () => {
578
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-loop-'));
579
+ try {
580
+ const model = createMockModel({ scenarios: [{ name: 'idle', steps: [{ type: 'finish', reason: 'stop' }] }], provider: 'mock' });
581
+ const driver = new SingleStreamDriver(
582
+ { stream: (o) => normalizeStreamShim(model.adapter.stream({ provider: o.provider, model: o.model, messages: o.messages, signal: o.signal })), executeTools: createSandboxExecutor(sandboxDir) },
583
+ { provider: 'mock', model: 'm', budgetTokens: 1000 },
584
+ );
585
+ assert.equal(driver.budgetLevel(), 'normal');
586
+ // 直接驱动 usage 越过 70% 线:压一个 usage chunk 不可行(内部状态),
587
+ // 用公开预算面验证:700 token 消耗 → high-only。
588
+ // usage 只能经流灌入——这里以 final-only 边界用例覆盖阈值语义(usage=950)
589
+ const scenario = async function* () {
590
+ yield { type: 'usage' as const, usage: { inputTokens: 950, outputTokens: 0 } };
591
+ };
592
+ void scenario; // 阈值逻辑由 D1 的 E2E 覆盖;此处只锁定 normal 缺省行为
593
+ assert.equal(driver.budgetLevel(), 'normal');
594
+ } finally {
595
+ rmSync(sandboxDir, { recursive: true, force: true });
596
+ }
597
+ });
598
+ });
599
+
600
+ // ---------------------------------------------------------------------------
601
+ // E. 双通道:原生 tool_call 阻塞回灌
602
+ // ---------------------------------------------------------------------------
603
+
604
+ describe('E. 原生 tool_call 双通道', () => {
605
+ let harness: Harness | undefined;
606
+ beforeEach(() => { harness?.cleanup(); harness = undefined; });
607
+
608
+ it('E1. 原生 tool-call chunk → 阻塞执行 → 结果回灌下一请求', async () => {
609
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-loop-'));
610
+ try {
611
+ writeFileSync(join(sandboxDir, 'native.txt'), '原生通道内容', 'utf8');
612
+ const argDelta = JSON.stringify({ file_path: 'native.txt' });
613
+ const wireRequests: Array<{ role: string; content: Array<{ type: 'text'; text: string }> }>[] = [];
614
+ let callCount = 0;
615
+ const ports: DriverPorts = {
616
+ stream: (options) => {
617
+ wireRequests.push(options.messages as Array<{ role: string; content: Array<{ type: 'text'; text: string }> }>);
618
+ callCount += 1;
619
+ if (callCount === 1) {
620
+ // 请求 1:prose + 原生 read 工具调用(tool-call-delta 分片 + finish tool-calls)
621
+ return normalizeStreamShim((async function* () {
622
+ yield { type: 'block-start' as const, index: 0, blockType: 'text' };
623
+ yield { type: 'text-delta' as const, index: 0, text: '用原生工具读文件。\n' };
624
+ yield { type: 'tool-call-delta' as const, index: 1, id: 'call-1', name: 'read', argumentsDelta: argDelta.slice(0, 10) };
625
+ yield { type: 'tool-call-delta' as const, index: 1, id: 'call-1', argumentsDelta: argDelta.slice(10) };
626
+ yield { type: 'block-end' as const, index: 1, block: { type: 'tool-call', id: 'call-1', name: 'read', arguments: argDelta } };
627
+ yield { type: 'usage' as const, usage: { inputTokens: 100, outputTokens: 10 } };
628
+ yield { type: 'finish' as const, reason: { kind: 'tool-calls' as const } };
629
+ })());
630
+ }
631
+ // 请求 2:收到结果后收尾(tf-final 内联在文本里)
632
+ return normalizeStreamShim((async function* () {
633
+ yield { type: 'block-start' as const, index: 0, blockType: 'text' };
634
+ yield { type: 'text-delta' as const, index: 0, text: '收到结果,收尾。<tf-final id="fn" summary="原生通道完成"/>\n' };
635
+ yield { type: 'finish' as const, reason: { kind: 'stop' as const } };
636
+ })());
637
+ },
638
+ executeTools: createSandboxExecutor(sandboxDir),
639
+ };
640
+ const driver = new SingleStreamDriver(ports, { provider: 'mock', model: 'm' });
641
+ driver.pushUserTask('原生工具演练。');
642
+ const reason = await driver.runTurn();
643
+ assert.equal(reason.kind, 'completed');
644
+ assert.equal(callCount, 2, '原生工具结果回灌 → 第二次请求');
645
+ const req2Texts = wireRequests[1]!.map((m) => m.content.map((b) => b.text ?? '').join('\n'));
646
+ assert.ok(
647
+ req2Texts.some((t) => t.includes('[tf-stream:tool-result callId=call-1 tool=read]') && t.includes('原生通道内容')),
648
+ `请求 2 应注入原生工具结果,实际:\n${req2Texts.join('\n---\n').slice(0, 1500)}`,
649
+ );
650
+ } finally {
651
+ rmSync(sandboxDir, { recursive: true, force: true });
652
+ }
653
+ });
654
+
655
+ it('E2. 中断流的残缺原生调用被丢弃并记录(不执行半截 JSON 参数)', async () => {
656
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-loop-'));
657
+ const ports: DriverPorts = {
658
+ stream: () => normalizeStreamShim((async function* () {
659
+ yield { type: 'tool-call-delta' as const, index: 0, id: 'c9', name: 'write', argumentsDelta: '{"file_path":"x' };
660
+ yield { type: 'finish' as const, reason: { kind: 'aborted' as const, message: 'cut' } };
661
+ })()),
662
+ executeTools: createSandboxExecutor(sandboxDir),
663
+ };
664
+ const driver = new SingleStreamDriver(ports, { provider: 'mock', model: 'm' });
665
+ driver.pushUserTask('残缺调用演练。');
666
+ try {
667
+ await driver.runTurn();
668
+ const snap = driver.snapshot();
669
+ assert.ok(!existsSync(join(sandboxDir, 'x')), '残缺调用不得执行');
670
+ assert.ok(faultsOf(snap).some((f) => f.fault === 'native-calls-discarded'));
671
+ } finally {
672
+ rmSync(sandboxDir, { recursive: true, force: true });
673
+ }
674
+ });
675
+ });
676
+
677
+ // ---------------------------------------------------------------------------
678
+ // F. gate.admit 准入
679
+ // ---------------------------------------------------------------------------
680
+
681
+ describe('F. gate.admit 准入', () => {
682
+ let harness: Harness | undefined;
683
+ beforeEach(() => { harness?.cleanup(); harness = undefined; });
684
+
685
+ it('F1. gate 拒绝 → 命令 rejected → 结构化错误重入 → 模型改道', async () => {
686
+ const denyingGate: GatePort = {
687
+ async admit(req) {
688
+ if (req.action === 'tf-write' && (req.detail ?? '').includes('deny.txt')) {
689
+ return { verdict: 'deny', reason: 'fatal-no-approval-channel', detail: 'deny.txt 被策略禁止' };
690
+ }
691
+ return { verdict: 'allow', reversibility: 'read' };
692
+ },
693
+ };
694
+ harness = makeHarness({
695
+ task: '改道演练:写 a.txt 和 fail.txt(fail.txt 会被沙箱拒绝)。',
696
+ // 顺序敏感:gate-reroute 的 marker 与 reroute-second 相同(tf-stream:error),
697
+ // 但本流的信号计数不同(waitTools 2)——必须排在 reroute-second 之前
698
+ scenarios: loadScenarios({
699
+ name: 'gate-reroute',
700
+ match: { promptIncludes: 'tf-stream:error' },
701
+ chunking: { charsPerChunk: 0, delayMs: 0 },
702
+ steps: [
703
+ { type: 'text', text: '收到拒绝报告,改道写 fixed.txt。\n' },
704
+ { type: 'commands', commands: ['<tf-write path="fixed.txt" id="wx">FIXED</tf-write>'] },
705
+ { type: 'waitTools', count: 2, timeoutMs: 5000 },
706
+ { type: 'commands', commands: ['<tf-final id="fg" summary="改道成功"/>'] },
707
+ { type: 'finish', reason: 'stop' },
708
+ ],
709
+ }, {
710
+ name: 'gate-deny-first',
711
+ match: { promptIncludes: '改道演练' },
712
+ chunking: { charsPerChunk: 0, delayMs: 0 },
713
+ steps: [
714
+ { type: 'text', text: '写 deny.txt(会被 gate 拒绝)。\n' },
715
+ { type: 'commands', commands: ['<tf-write path="deny.txt" id="wd">D</tf-write>'] },
716
+ { type: 'waitTools', count: 1, timeoutMs: 5000 },
717
+ { type: 'finish', reason: 'stop' },
718
+ ],
719
+ }),
720
+ gate: denyingGate,
721
+ sandboxHooks: { failPathsMatching: 'fail' },
722
+ });
723
+ try {
724
+ const reason = await harness.driver.runTurn();
725
+ assert.equal(reason.kind, 'completed');
726
+ const snap = harness.driver.snapshot();
727
+ assert.ok(!existsSync(join(harness.sandboxDir, 'deny.txt')), '被拒绝的命令不得执行');
728
+ assert.ok(
729
+ snap.records.some((r) => r.kind === 'command' && r.id === 'wd' && r.status === 'rejected'),
730
+ '应有 rejected 记录',
731
+ );
732
+ const req2 = harness.wireRequests[1]!;
733
+ assert.ok(req2.contentTexts.some((t) => t.includes('fatal-no-approval-channel')), '拒绝原因应结构化注入');
734
+ assert.ok(existsSync(join(harness.sandboxDir, 'fixed.txt')), '模型改道成功');
735
+ } finally {
736
+ harness.cleanup();
737
+ }
738
+ });
739
+
740
+ it('F2. gate 全放行 → 行为与无门一致', async () => {
741
+ const allowGate: GatePort = { async admit() { return { verdict: 'allow', reversibility: 'read' }; } };
742
+ harness = makeHarness({
743
+ task: '请写五个文件:f1 到 f5。',
744
+ scenarios: loadScenarios('5-file-basic.json'),
745
+ gate: allowGate,
746
+ });
747
+ try {
748
+ const reason = await harness.driver.runTurn();
749
+ assert.equal(reason.kind, 'completed');
750
+ assert.equal(harness.driver.snapshot().requestCount, 1);
751
+ } finally {
752
+ harness.cleanup();
753
+ }
754
+ });
755
+ });
756
+
757
+ // ---------------------------------------------------------------------------
758
+ // G. peek 链路(O2 need_result 通道)
759
+ // ---------------------------------------------------------------------------
760
+
761
+ describe('G. tf-peek need_result 通道', () => {
762
+ let harness: Harness | undefined;
763
+ beforeEach(() => { harness?.cleanup(); harness = undefined; });
764
+
765
+ it('G1. read 骨架注入 → peek 按行段取回 → 结果注入 → 收敛(3 次请求)', async () => {
766
+ harness = makeHarness({
767
+ task: '句柄演练:读 big.txt。',
768
+ scenarios: loadScenarios('peek-second.json', 'peek-third.json', 'peek-first.json'),
769
+ });
770
+ try {
771
+ writeFileSync(join(harness.sandboxDir, 'big.txt'), '第一行 alpha\n第二行 beta\n第三行 gamma\n第四行 delta\n', 'utf8');
772
+ const reason = await harness.driver.runTurn();
773
+ assert.equal(reason.kind, 'completed');
774
+ const snap = harness.driver.snapshot();
775
+ assert.equal(snap.requestCount, 3, `read → peek → final 应 3 次请求,实际 ${snap.requestCount}`);
776
+
777
+ const req2 = harness.wireRequests[1]!;
778
+ assert.ok(req2.contentTexts.some((t) => t.includes('[tf-stream:observation') && t.includes('obs:read:r1@v1')), '请求 2 应注入观测反馈');
779
+ // v0.2:小文件 read 直接反馈完整原文(上游"成功结果完整反馈一次"语义)
780
+ assert.ok(req2.contentTexts.some((t) => t.includes('第一行 alpha') && t.includes('第四行 delta')), '请求 2 应包含 read 完整原文反馈');
781
+ const req3 = harness.wireRequests[2]!;
782
+ assert.ok(req3.contentTexts.some((t) => t.includes('[tf-stream:peek') && t.includes('第一行 alpha')), '请求 3 应注入 peek 结果');
783
+
784
+ const counters = snap.counters();
785
+ assert.equal(counters.peeked, 2, 'v0.2:完整反馈自动 peek 1 次 + 模型 peek 1 次');
786
+ assert.equal(counters.produced, 1, 'peek 不走 observe(03 号口径)');
787
+ } finally {
788
+ harness.cleanup();
789
+ }
790
+ });
791
+ });
792
+
793
+ // ---------------------------------------------------------------------------
794
+ // H. AgentFactory 生命周期(fake host)
795
+ // ---------------------------------------------------------------------------
796
+
797
+ interface FakeSession {
798
+ id: string;
799
+ header: { id: string };
800
+ events: Array<{ type: string; data: unknown; opts?: unknown }>;
801
+ append(type: string, data: unknown, opts?: unknown): void;
802
+ }
803
+
804
+ function createFakeSession(id: string): FakeSession {
805
+ const session: FakeSession = {
806
+ id,
807
+ header: { id },
808
+ events: [],
809
+ append(type, data, opts) {
810
+ session.events.push({ type, data, opts });
811
+ },
812
+ };
813
+ return session;
814
+ }
815
+
816
+ function createFakeHost() {
817
+ const calls = { prepared: 0, enteredSession: 0, announcedSession: 0, enteredAgent: 0, announcedAgent: 0, persisted: 0, handleClosed: 0, disposedPrep: 0 };
818
+ const sessions = {
819
+ prepare(id: string, opts?: { meta?: unknown }) {
820
+ calls.prepared += 1;
821
+ const session = createFakeSession(id);
822
+ return {
823
+ session,
824
+ [Symbol.dispose]() {
825
+ calls.disposedPrep += 1;
826
+ },
827
+ };
828
+ },
829
+ enter(session: unknown) {
830
+ calls.enteredSession += 1;
831
+ return () => {};
832
+ },
833
+ announce(session: unknown) {
834
+ calls.announcedSession += 1;
835
+ },
836
+ };
837
+ const agents = {
838
+ enter(agent: unknown, owner: unknown) {
839
+ calls.enteredAgent += 1;
840
+ return () => {};
841
+ },
842
+ async announce(agent: unknown, source: string) {
843
+ calls.announcedAgent += 1;
844
+ },
845
+ };
846
+ const persistence = {
847
+ async create(header: unknown, opts?: unknown) {
848
+ calls.persisted += 1;
849
+ return {
850
+ async close() {
851
+ calls.handleClosed += 1;
852
+ },
853
+ };
854
+ },
855
+ };
856
+ const ctx = {
857
+ sessions,
858
+ agents,
859
+ get(service: string) {
860
+ return service === 'sessionPersistence' ? persistence : undefined;
861
+ },
862
+ };
863
+ return { ctx, calls, persistence };
864
+ }
865
+
866
+ describe('H. AgentFactory 生命周期(fake host)', () => {
867
+ const sandboxDirs: string[] = [];
868
+ const mkSandbox = (): string => {
869
+ const dir = mkdtempSync(join(tmpdir(), 'tf-factory-'));
870
+ sandboxDirs.push(dir);
871
+ return dir;
872
+ };
873
+
874
+ it('H1. createAgent 全序:prepare → persistence → 双公告 → setup → followup 驱动 → dispose', async () => {
875
+ const sandboxDir = mkSandbox();
876
+ const { ctx, calls } = createFakeHost();
877
+ const model = createMockModel({ scenarios: loadScenarios('5-file-basic.json'), provider: 'mock' });
878
+
879
+ const setupCalls: Array<{ sessionId: string; agentId: string }> = [];
880
+ const factory = createStreamAgentFactory({
881
+ ctx,
882
+ createDriver({ sessionId, agentOptions, session }) {
883
+ const events = createSessionEventWriter(session);
884
+ return {
885
+ driver: new SingleStreamDriver(
886
+ {
887
+ stream: (options) => normalizeStreamShim(model.adapter.stream({ provider: options.provider, model: options.model, messages: options.messages, signal: options.signal })),
888
+ executeTools: createSandboxExecutor(sandboxDir),
889
+ events,
890
+ onToolSettled: () => model.notifyToolResult(),
891
+ },
892
+ { provider: agentOptions.provider ?? 'mock', model: agentOptions.model ?? 'mock-scenario', streamIdleTimeoutMs: 30_000 },
893
+ ),
894
+ };
895
+ },
896
+ });
897
+
898
+ const setup = (agentCtx: unknown, agent: StreamLoopAgent) => {
899
+ setupCalls.push({ sessionId: String((agentCtx as { sessionId?: string })?.sessionId ?? ''), agentId: agent.id });
900
+ agent.model.select({ provider: 'mock', model: 'mock-scenario' });
901
+ };
902
+
903
+ const handle = await factory.createAgent(ctx, {
904
+ sessionId: `session-${randomUUID()}`,
905
+ meta: { cwd: sandboxDir },
906
+ agentOptions: { provider: 'mock', model: 'mock-scenario' },
907
+ setup,
908
+ });
909
+
910
+ assert.equal(calls.prepared, 1);
911
+ assert.equal(calls.persisted, 1, 'persistence.create 应被调用');
912
+ assert.equal(calls.enteredSession, 1, 'sessions.enter');
913
+ assert.equal(calls.announcedSession, 1, 'sessions.announce');
914
+ assert.equal(calls.enteredAgent, 1, 'agents.enter');
915
+ assert.equal(calls.announcedAgent, 1, 'agents.announce');
916
+ assert.equal(setupCalls.length, 1);
917
+ assert.equal(setupCalls[0]!.agentId, handle.agent.id);
918
+
919
+ // followup → 驱动器跑完 5 文件任务
920
+ handle.agent.followup({
921
+ role: 'user',
922
+ content: [{ type: 'text', text: '请写五个文件:f1 到 f5。' }],
923
+ source: { kind: 'user' },
924
+ });
925
+ await handle.agent.whenIdle();
926
+ assert.equal(handle.agent.status, 'idle');
927
+ assert.ok(existsSync(join(sandboxDir, 'f3.txt')));
928
+
929
+ // 会话事件(fake session 收到的 append 形状)
930
+ const fakeSession = handle.agent.session as FakeSession;
931
+ const types = fakeSession.events.map((e) => e.type);
932
+ assert.ok(types.includes('user/message'), 'user/message 应落盘');
933
+ assert.ok(types.includes('turn/start'), 'turn/start 应落盘');
934
+ assert.ok(types.includes('step/start'), 'step/start 应落盘');
935
+ assert.ok(types.includes('assistant/message'), 'assistant/message 应落盘');
936
+ assert.ok(types.includes('step/end') && types.includes('turn/end'), 'step/end + turn/end 应落盘');
937
+ const assistantEvent = fakeSession.events.find((e) => e.type === 'assistant/message');
938
+ assert.ok(assistantEvent !== undefined);
939
+ const data = assistantEvent.data as { message: { id: string; role: string; content: Array<{ type: string; text?: string }>; source: { kind: string } }; stream: unknown[] };
940
+ assert.equal(data.message.role, 'assistant');
941
+ assert.equal(data.message.source.kind, 'model');
942
+ assert.ok(Array.isArray(data.stream) && data.stream.length === 0);
943
+ const turnEnd = fakeSession.events.find((e) => e.type === 'turn/end');
944
+ assert.equal((turnEnd!.data as { reason: { kind: string } }).reason.kind, 'completed');
945
+
946
+ // model.select 落盘 model/selection
947
+ assert.ok(types.includes('model/selection'), 'model/selection 应落盘');
948
+
949
+ await handle.dispose();
950
+ assert.equal(calls.handleClosed, 1, 'dispose 关闭持久化句柄');
951
+ });
952
+
953
+ it('H2. resume:open → read → seed prepare → 双公告', async () => {
954
+ const sandboxDir = mkSandbox();
955
+ const { ctx, calls } = createFakeHost();
956
+ const persistedEvents: Array<{ type: string; data: unknown }> = [];
957
+ const persistence = {
958
+ async open(id: string, mode: string) {
959
+ assert.equal(mode, 'write');
960
+ return {
961
+ header: { id },
962
+ inheritedEventCount: 0,
963
+ async read(from: number) {
964
+ assert.equal(from, 0);
965
+ return { events: persistedEvents, eventState: undefined };
966
+ },
967
+ async close() {
968
+ calls.handleClosed += 1;
969
+ },
970
+ };
971
+ },
972
+ };
973
+ const factory = createStreamAgentFactory({
974
+ ctx: { ...ctx, get: (service: string) => (service === 'sessionPersistence' ? persistence : undefined) },
975
+ createDriver() {
976
+ return {
977
+ driver: new SingleStreamDriver(
978
+ {
979
+ stream: (o) => normalizeStreamShim(createMockModel({ scenarios: [{ name: 'idle', steps: [{ type: 'finish', reason: 'stop' }] }], provider: 'mock' }).adapter.stream({ provider: o.provider, model: o.model, messages: o.messages, signal: o.signal })),
980
+ executeTools: createSandboxExecutor(sandboxDir),
981
+ },
982
+ { provider: 'mock', model: 'm' },
983
+ ),
984
+ };
985
+ },
986
+ });
987
+ const handle = await factory.resume(ctx, { resumeSessionId: 'session-resume-1', agentOptions: { provider: 'mock', model: 'm' } });
988
+ assert.equal(calls.enteredAgent, 1);
989
+ assert.equal(calls.announcedAgent, 1);
990
+ await handle.dispose();
991
+ assert.equal(calls.handleClosed, 1);
992
+ });
993
+
994
+ it('H3. resume 无 persistence → 结构化报错(不静默)', async () => {
995
+ const { ctx } = createFakeHost();
996
+ const factory = createStreamAgentFactory({
997
+ ctx: { ...ctx, get: () => undefined },
998
+ createDriver() {
999
+ throw new Error('unreachable');
1000
+ },
1001
+ });
1002
+ await assert.rejects(
1003
+ () => factory.resume(ctx, { resumeSessionId: 's1' }),
1004
+ /session persistence is not configured/,
1005
+ );
1006
+ });
1007
+
1008
+ it('H4. apply 入口:setFactory 接管 + 重复注册 fail-fast + llm/tools 缺失报错', () => {
1009
+ const sandboxDir = mkSandbox();
1010
+ // setFactory 正常路径
1011
+ const model = createMockModel({ scenarios: [{ name: 'idle', steps: [{ type: 'finish', reason: 'stop' }] }], provider: 'mock' });
1012
+ const registered: unknown[] = [];
1013
+ const hostCtx = {
1014
+ agents: {
1015
+ setFactory(factory: unknown) {
1016
+ registered.push(factory);
1017
+ return () => {};
1018
+ },
1019
+ },
1020
+ llm: { stream: (o: StreamRequestOptions) => normalizeStreamShim(model.adapter.stream({ provider: o.provider, model: o.model, messages: o.messages, signal: o.signal })) },
1021
+ tools: { execute: createSandboxExecutor(sandboxDir) },
1022
+ get: () => undefined,
1023
+ };
1024
+ const entry = applyLoopEntry(hostCtx, { provider: 'mock', model: 'mock-scenario' });
1025
+ assert.equal(registered.length, 1, 'setFactory 应被调用一次');
1026
+ assert.ok(entry.factory !== undefined);
1027
+ entry.dispose();
1028
+
1029
+ // 重复注册 fail-fast(探针 A:重复注册抛 "an agent factory is already registered")
1030
+ const conflictingCtx = {
1031
+ ...hostCtx,
1032
+ agents: {
1033
+ setFactory() {
1034
+ throw new Error('an agent factory is already registered');
1035
+ },
1036
+ },
1037
+ };
1038
+ assert.throws(() => applyLoopEntry(conflictingCtx, {}), /already registered/);
1039
+
1040
+ // llm 缺失 → fail-fast
1041
+ assert.throws(() => applyLoopEntry({ agents: hostCtx.agents, get: () => undefined }, {}), /ctx\.llm\.stream 不可用/);
1042
+ rmSync(sandboxDir, { recursive: true, force: true });
1043
+ });
1044
+ });
1045
+
1046
+ // ---------------------------------------------------------------------------
1047
+ // I. 驱动器杂项(默认映射 / 身份接线 / 取消)
1048
+ // ---------------------------------------------------------------------------
1049
+
1050
+ describe('I. 驱动器杂项', () => {
1051
+ it('I1. 默认工具映射:tf-write/read/bash → 原生工具参数;peek/final → null', () => {
1052
+ const parser = new TfStreamParser();
1053
+ const events = parser.feed('<tf-write path="x.txt" id="w1">hi</tf-write><tf-read path="y.txt" id="r1"/><tf-bash cmd="ls" id="b1"/><tf-peek handle="obs:read:r1@v1" id="p1"/><tf-final id="f1"/>');
1054
+ void events;
1055
+ const commands = (parser as unknown as { commands: Map<string, TfCommand> }).commands;
1056
+ const write = commands.get('w1')!;
1057
+ const read = commands.get('r1')!;
1058
+ const bash = commands.get('b1')!;
1059
+ const peek = commands.get('p1')!;
1060
+ assert.deepEqual(DEFAULT_TOOL_MAPPING.toToolCall(write), { name: 'write', arguments: { file_path: 'x.txt', content: 'hi' } });
1061
+ assert.deepEqual(DEFAULT_TOOL_MAPPING.toToolCall(read), { name: 'read', arguments: { file_path: 'y.txt' } });
1062
+ // v0.2:宿主 shell 工具是 pwsh(command+description 双必填),不再是 'bash'
1063
+ assert.deepEqual(DEFAULT_TOOL_MAPPING.toToolCall(bash), { name: 'pwsh', arguments: { command: 'ls', description: 'tf-bash: ls' } });
1064
+ assert.equal(DEFAULT_TOOL_MAPPING.toToolCall(peek), null);
1065
+ });
1066
+
1067
+ it('I2. cancel:中断在途流,turn 以 aborted 终止', async () => {
1068
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-loop-'));
1069
+ const model = createMockModel({
1070
+ scenarios: [{
1071
+ name: 'slow',
1072
+ match: { promptIncludes: '取消演练' },
1073
+ chunking: { charsPerChunk: 4, delayMs: 50 },
1074
+ steps: [
1075
+ { type: 'text', text: '慢慢输出。\n' },
1076
+ { type: 'fail', mode: 'timeout', delayMs: 30_000 },
1077
+ ],
1078
+ }],
1079
+ provider: 'mock',
1080
+ });
1081
+ const driver = new SingleStreamDriver(
1082
+ {
1083
+ stream: (o) => normalizeStreamShim(model.adapter.stream({ provider: o.provider, model: o.model, messages: o.messages, signal: o.signal })),
1084
+ executeTools: createSandboxExecutor(sandboxDir),
1085
+ },
1086
+ { provider: 'mock', model: 'm', streamIdleTimeoutMs: 30_000 },
1087
+ );
1088
+ driver.pushUserTask('取消演练。');
1089
+ try {
1090
+ const turnPromise = driver.runTurn();
1091
+ setTimeout(() => driver.cancel(new Error('user cancelled')), 150);
1092
+ const reason = await turnPromise;
1093
+ assert.equal(reason.kind, 'aborted');
1094
+ } finally {
1095
+ rmSync(sandboxDir, { recursive: true, force: true });
1096
+ }
1097
+ });
1098
+
1099
+ it('I3. 不可重试流错误(凭据缺失)→ fail-fast 终止回合,不烧重入预算', async () => {
1100
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-loop-'));
1101
+ try {
1102
+ let calls = 0;
1103
+ const driver = new SingleStreamDriver(
1104
+ {
1105
+ stream: () => {
1106
+ calls += 1;
1107
+ return normalizeStreamShim((async function* () {
1108
+ yield { type: 'finish' as const, reason: { kind: 'error' as const, message: 'credential missing', code: 'MISSING_CREDENTIAL' } };
1109
+ })());
1110
+ },
1111
+ executeTools: createSandboxExecutor(sandboxDir),
1112
+ },
1113
+ { provider: 'mock', model: 'm' },
1114
+ );
1115
+ driver.pushUserTask('凭据缺失演练。');
1116
+ const reason = await driver.runTurn();
1117
+ assert.equal(reason.kind, 'error');
1118
+ assert.equal(reason.kind === 'error' ? reason.error.code : '', 'MISSING_CREDENTIAL');
1119
+ assert.equal(calls, 1, '不可重试错误不得发起第二次请求');
1120
+ const snap = driver.snapshot();
1121
+ assert.ok(snap.records.some((r) => r.kind === 'fault' && r.fault === 'stream-fatal'));
1122
+ } finally {
1123
+ rmSync(sandboxDir, { recursive: true, force: true });
1124
+ }
1125
+ });
1126
+ });
1127
+
1128
+ // ---------------------------------------------------------------------------
1129
+ // J. 分派 08:饥饿防线升格注入接线回归(07 号结果 §3.6 上报的断链,评测前修复)
1130
+ // ---------------------------------------------------------------------------
1131
+
1132
+ describe('J. 饥饿升格接线(08 号评测前修复的回归)', () => {
1133
+ it('J1. 连续无 high 步后升格骨架进入下一请求(noteStep 返回值不再被丢弃)', async () => {
1134
+ const harness = makeHarness({
1135
+ task: '请写一个文件然后停下(本流不带 tf-final)。',
1136
+ // 场景选择按"首个命中"(mock-provider selectScenario):升格块剧本必须排最前,
1137
+ // 否则请求 2 仍命中任务文本剧本(请求 2 的 prompt 同时含任务文本与升格块)。
1138
+ scenarios: loadScenarios('starvation-final.json', 'starvation-promote.json'),
1139
+ config: { starvationThreshold: 1 },
1140
+ });
1141
+ try {
1142
+ const reason = await harness.driver.runTurn();
1143
+ assert.equal(reason.kind, 'completed');
1144
+ const snap = harness.driver.snapshot();
1145
+ assert.equal(snap.requestCount, 2, `升格骨架必须触发重入(1 流写文件无 final + 1 流收尾),实际 ${snap.requestCount}`);
1146
+ // 请求 2 必须携带升格观测块(key=starvation-promoted),且不是 nudge
1147
+ const req2 = harness.wireRequests[1].contentTexts.join('\n');
1148
+ assert.ok(req2.includes('key=starvation-promoted'), '请求 2 应含升格骨架块');
1149
+ assert.ok(!req2.includes('[tf-stream:nudge]'), '有升格注入时不得走 nudge 兜底');
1150
+ // 升格的是 write 回执骨架(low → promoted),内容为句柄目录/骨架形态
1151
+ assert.ok(req2.includes('tf-peek'), '升格块应带 tf-peek 取回指引');
1152
+ // 内核 noteStep 语义:每次越过阈值都计数(step1 升格=实际注入;step2(tf-final 步)再次升格
1153
+ // 但被驱动器去重护栏拦下不再注入)→ 计数 2、实际注入块 1(M3 口径按 snapshot counters 为准)
1154
+ assert.equal(snap.counters().injected, 2, '两次过阈值都计数(内核语义)');
1155
+ assert.equal(snap.counters().produced, 1, '一次 write 产出');
1156
+ } finally {
1157
+ harness.cleanup();
1158
+ }
1159
+ });
1160
+
1161
+ it('J2. 未设 env STREAM_LOOP_EVAL_DUMP 时 dumpEval 零副作用;设置后 turn 结束落 snapshot', async () => {
1162
+ const dumpDir = mkdtempSync(join(tmpdir(), 'eval-dump-'));
1163
+ const dumpPrefix = join(dumpDir, 'driver-');
1164
+ const harness = makeHarness({
1165
+ task: '请写一个文件然后停下(本流不带 tf-final)。',
1166
+ scenarios: loadScenarios('starvation-final.json', 'starvation-promote.json'),
1167
+ config: { starvationThreshold: 1 },
1168
+ });
1169
+ try {
1170
+ process.env.STREAM_LOOP_EVAL_DUMP = dumpPrefix;
1171
+ try {
1172
+ const reason = await harness.driver.runTurn();
1173
+ assert.equal(reason.kind, 'completed');
1174
+ const dumps = readdirSync(dumpDir).filter((n) => n.startsWith('driver-') && n.endsWith('.json'));
1175
+ assert.equal(dumps.length, 1, 'turn 结束应落一个 snapshot dump');
1176
+ const dump = JSON.parse(readFileSync(join(dumpDir, dumps[0]), 'utf8'));
1177
+ assert.equal(dump.requestCount, 2);
1178
+ assert.equal(dump.counters.injected, 2, '与 J1 同款内核计数语义');
1179
+ assert.ok(Array.isArray(dump.records) && dump.records.length > 0);
1180
+ assert.ok(Array.isArray(dump.stableHashes) && dump.stableHashes.length === 2);
1181
+ } finally {
1182
+ delete process.env.STREAM_LOOP_EVAL_DUMP;
1183
+ }
1184
+ } finally {
1185
+ harness.cleanup();
1186
+ rmSync(dumpDir, { recursive: true, force: true });
1187
+ }
1188
+ });
1189
+ });
1190
+
1191
+ // ---------------------------------------------------------------------------
1192
+ // K. v0.3.1 截断修复(真机会话 session-84274277:任务做一半 + 占位答案)
1193
+ // ---------------------------------------------------------------------------
1194
+
1195
+ describe('K. final 收束闸(v0.3.1 截断修复)', () => {
1196
+ const fast = { charsPerChunk: 0, delayMs: 0 };
1197
+ let harness: Harness;
1198
+ beforeEach(() => { harness?.cleanup(); });
1199
+
1200
+ it('K1. 占位 summary 的 tf-final 不算收敛:结构化拒绝 → 重发真答案才收场', async () => {
1201
+ const scenarios: Scenario[] = [
1202
+ {
1203
+ name: 'real-final',
1204
+ match: { promptIncludes: 'summary 是占位内容' },
1205
+ chunking: fast,
1206
+ steps: [
1207
+ { type: 'text', text: '补上答案。\n' },
1208
+ { type: 'commands', commands: ['<tf-final id="f2" summary="a.txt 共 1 行,内容为 内容A"/>'] },
1209
+ { type: 'finish', reason: 'stop' },
1210
+ ],
1211
+ },
1212
+ {
1213
+ name: 'placeholder-final',
1214
+ match: { promptIncludes: '占位演练' },
1215
+ chunking: fast,
1216
+ steps: [
1217
+ { type: 'text', text: '开始。\n' },
1218
+ { type: 'commands', commands: ['<tf-final id="f1" summary="placeholder"/>'] },
1219
+ { type: 'finish', reason: 'stop' },
1220
+ ],
1221
+ },
1222
+ ];
1223
+ harness = makeHarness({ task: '占位演练:把 a.txt 的内容报出来。', scenarios });
1224
+ try {
1225
+ const reason = await harness.driver.runTurn();
1226
+ assert.equal(reason.kind, 'completed', '占位 final 被拒后应重入并最终收敛');
1227
+ const snap = harness.driver.snapshot();
1228
+ assert.equal(snap.requestCount, 2, `占位 final 必须触发一次重入,实际 ${snap.requestCount}`);
1229
+ const finals = snap.records.filter((r) => r.kind === 'final');
1230
+ const last = finals[finals.length - 1];
1231
+ assert.ok(last !== undefined && last.kind === 'final');
1232
+ assert.ok(last.summary.includes('内容A'), `最终答案必须是真答案,实际 ${last.summary}`);
1233
+ assert.ok(
1234
+ faultsOf(snap).some((f) => f.fault === 'premature-final' && f.detail.includes('占位')),
1235
+ '应记 premature-final fault',
1236
+ );
1237
+ const req2 = harness.wireRequests[1]!.contentTexts.join('\n');
1238
+ assert.ok(req2.includes('[tf-stream:error') && req2.includes('tf-final 无效'), '拒绝理由必须结构化注入给模型');
1239
+ } finally {
1240
+ harness.cleanup();
1241
+ }
1242
+ });
1243
+
1244
+ it('K2. final 之后又发命令 = 答案过期:不得用旧 final 收敛', async () => {
1245
+ const scenarios: Scenario[] = [
1246
+ {
1247
+ name: 'restated-final',
1248
+ match: { promptIncludes: '答案已过期' },
1249
+ chunking: fast,
1250
+ steps: [
1251
+ { type: 'text', text: '重新声明结果。\n' },
1252
+ { type: 'commands', commands: ['<tf-final id="f2" summary="x.txt 已写入,内容 X"/>'] },
1253
+ { type: 'finish', reason: 'stop' },
1254
+ ],
1255
+ },
1256
+ {
1257
+ name: 'final-then-work',
1258
+ match: { promptIncludes: '过期演练' },
1259
+ chunking: fast,
1260
+ steps: [
1261
+ { type: 'text', text: '先声明完成,然后继续干活。\n' },
1262
+ {
1263
+ type: 'commands',
1264
+ commands: [
1265
+ '<tf-final id="f1" summary="done"/>',
1266
+ '<tf-write path="x.txt" id="w1">X</tf-write>',
1267
+ ],
1268
+ },
1269
+ { type: 'finish', reason: 'stop' },
1270
+ ],
1271
+ },
1272
+ ];
1273
+ harness = makeHarness({ task: '过期演练:写 x.txt 并报告结果。', scenarios });
1274
+ try {
1275
+ const reason = await harness.driver.runTurn();
1276
+ assert.equal(reason.kind, 'completed');
1277
+ const snap = harness.driver.snapshot();
1278
+ assert.equal(snap.requestCount, 2, `过期 final 必须触发一次重入,实际 ${snap.requestCount}`);
1279
+ const finals = snap.records.filter((r) => r.kind === 'final');
1280
+ const last = finals[finals.length - 1];
1281
+ assert.ok(last !== undefined && last.kind === 'final');
1282
+ assert.ok(last.summary.includes('x.txt'), `交付的必须是重发后的答案,实际 ${last.summary}`);
1283
+ assert.ok(
1284
+ faultsOf(snap).some((f) => f.detail.includes('答案已过期')),
1285
+ '应记"答案已过期"的拒绝',
1286
+ );
1287
+ } finally {
1288
+ harness.cleanup();
1289
+ }
1290
+ });
1291
+
1292
+ it('K3. 重复命令幂等但不空手:原结果回灌给丢失上下文的模型', async () => {
1293
+ const scenarios: Scenario[] = [
1294
+ {
1295
+ name: 'after-replay',
1296
+ match: { promptIncludes: '[tf-stream:replay' },
1297
+ chunking: fast,
1298
+ steps: [
1299
+ { type: 'text', text: '拿到回灌内容,收尾。\n' },
1300
+ { type: 'commands', commands: ['<tf-final id="f3" summary="a.txt 内容为 内容A"/>'] },
1301
+ { type: 'finish', reason: 'stop' },
1302
+ ],
1303
+ },
1304
+ {
1305
+ name: 'duplicate-read',
1306
+ match: { promptIncludes: '[tf-stream:receipt' },
1307
+ chunking: fast,
1308
+ steps: [
1309
+ { type: 'text', text: '再读一次。\n' },
1310
+ { type: 'commands', commands: ['<tf-read path="a.txt" id="r1" depends_on="w1"/>'] },
1311
+ { type: 'finish', reason: 'stop' },
1312
+ ],
1313
+ },
1314
+ {
1315
+ name: 'write-then-read',
1316
+ match: { promptIncludes: '回灌演练' },
1317
+ chunking: fast,
1318
+ steps: [
1319
+ { type: 'text', text: '写后读。\n' },
1320
+ {
1321
+ type: 'commands',
1322
+ commands: [
1323
+ '<tf-write path="a.txt" id="w1">内容A</tf-write>',
1324
+ '<tf-read path="a.txt" id="r1" depends_on="w1"/>',
1325
+ ],
1326
+ },
1327
+ { type: 'finish', reason: 'stop' },
1328
+ ],
1329
+ },
1330
+ ];
1331
+ harness = makeHarness({ task: '回灌演练:写 a.txt 再读回来。', scenarios });
1332
+ try {
1333
+ const reason = await harness.driver.runTurn();
1334
+ assert.equal(reason.kind, 'completed');
1335
+ const snap = harness.driver.snapshot();
1336
+ assert.equal(snap.requestCount, 3, `重发同一条 read 应带来一次回灌请求,实际 ${snap.requestCount}`);
1337
+ const req3 = harness.wireRequests[2]!.contentTexts.join('\n');
1338
+ assert.ok(req3.includes('[tf-stream:replay'), '第三次请求应携带回灌块');
1339
+ assert.ok(req3.includes('内容A'), '回灌块必须带原结果内容(幂等不等于空手)');
1340
+ assert.ok(
1341
+ snap.records.some((r) => r.kind === 'observation' && r.reason === 'duplicate-replay'),
1342
+ '回灌应记一条 observation',
1343
+ );
1344
+ } finally {
1345
+ harness.cleanup();
1346
+ }
1347
+ });
1348
+
1349
+ it('K4. 屡教不改的占位 final:如实 blocked,绝不把占位当交付', async () => {
1350
+ const scenarios: Scenario[] = [
1351
+ {
1352
+ name: 'still-placeholder',
1353
+ match: { promptIncludes: '[tf-stream:nudge]' },
1354
+ chunking: fast,
1355
+ steps: [
1356
+ { type: 'text', text: '……\n' },
1357
+ { type: 'commands', commands: ['<tf-final id="f3" summary="placeholder"/>'] },
1358
+ { type: 'finish', reason: 'stop' },
1359
+ ],
1360
+ },
1361
+ {
1362
+ name: 'second-placeholder',
1363
+ match: { promptIncludes: 'summary 是占位内容' },
1364
+ chunking: fast,
1365
+ steps: [
1366
+ { type: 'text', text: '再占位一次。\n' },
1367
+ { type: 'commands', commands: ['<tf-final id="f2" summary="TODO"/>'] },
1368
+ { type: 'finish', reason: 'stop' },
1369
+ ],
1370
+ },
1371
+ {
1372
+ name: 'first-placeholder',
1373
+ match: { promptIncludes: '屡教不改' },
1374
+ chunking: fast,
1375
+ steps: [
1376
+ { type: 'text', text: '占位收尾。\n' },
1377
+ { type: 'commands', commands: ['<tf-final id="f1" summary="placeholder"/>'] },
1378
+ { type: 'finish', reason: 'stop' },
1379
+ ],
1380
+ },
1381
+ ];
1382
+ harness = makeHarness({ task: '屡教不改:报出结果。', scenarios });
1383
+ try {
1384
+ const reason = await harness.driver.runTurn();
1385
+ assert.equal(reason.kind, 'blocked', '占位答案不得被当作完成');
1386
+ assert.ok(reason.kind === 'blocked' && reason.detail.includes('final 被拒'), `reason 应说明 final 被拒,实际 ${JSON.stringify(reason)}`);
1387
+ // 同 kind 的拒绝只注入一次:第 2 条占位 final 起不再烧注入,走 nudge → blocked
1388
+ assert.equal(harness.driver.snapshot().requestCount, 3, '拒绝注入一次 + nudge 一次,共 3 个请求');
1389
+ } finally {
1390
+ harness.cleanup();
1391
+ }
1392
+ });
1393
+ });