@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,386 @@
1
+ // mock-provider E2E 与单测(分派 05 验收)
2
+ // 运行:node --test test/ (Node ≥24 原生 TS type-stripping,零依赖,零 API 调用)
3
+
4
+ import { test } from 'node:test';
5
+ import assert from 'node:assert/strict';
6
+ import { mkdtempSync, rmSync, readFileSync } from 'node:fs';
7
+ import { tmpdir } from 'node:os';
8
+ import { join } from 'node:path';
9
+ import {
10
+ validateScenario,
11
+ createMockModel,
12
+ MockScenarioError,
13
+ type Scenario,
14
+ } from '../src/entry/mock-provider.ts';
15
+ import { runStubLoop, parseTfLine } from './helpers/stub-loop.ts';
16
+
17
+ const SCENARIO_DIR = join(import.meta.dirname, 'scenarios');
18
+ const loadScenario = (file: string): Scenario =>
19
+ validateScenario(JSON.parse(readFileSync(join(SCENARIO_DIR, file), 'utf8')), file);
20
+
21
+ function sandbox(): { dir: string; cleanup: () => void } {
22
+ const dir = mkdtempSync(join(tmpdir(), 'mock-e2e-'));
23
+ return { dir, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
24
+ }
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // 剧本 DSL 校验(fail-fast 负例)
28
+ // ---------------------------------------------------------------------------
29
+
30
+ test('DSL 负例:缺 finish 步骤抛 MockScenarioError', () => {
31
+ assert.throws(
32
+ () =>
33
+ validateScenario(
34
+ { name: 'no-finish', steps: [{ type: 'text', text: 'hi' }] },
35
+ 'inline',
36
+ ),
37
+ (e: unknown) => e instanceof MockScenarioError && /缺少 finish/.test(e.message),
38
+ );
39
+ });
40
+
41
+ test('DSL 负例:未知步骤类型与非法 waitTools.count 拒绝', () => {
42
+ assert.throws(() => validateScenario({ name: 'x', steps: [{ type: 'explode' }] }, 'inline'), MockScenarioError);
43
+ assert.throws(
44
+ () => validateScenario({ name: 'x', steps: [{ type: 'waitTools', count: 0 }, { type: 'finish' }] }, 'inline'),
45
+ (e: unknown) => /waitTools\.count/.test((e as Error).message),
46
+ );
47
+ assert.throws(
48
+ () => validateScenario({ name: 'x', steps: [{ type: 'waitTools', count: 1, timeoutMs: -5 }, { type: 'finish' }] }, 'inline'),
49
+ (e: unknown) => /waitTools\.timeoutMs/.test((e as Error).message),
50
+ );
51
+ });
52
+
53
+ test('DSL 负例:fail.mode 白名单外拒绝', () => {
54
+ assert.throws(
55
+ () => validateScenario({ name: 'x', steps: [{ type: 'fail', mode: 'nuke' }, { type: 'finish' }] }, 'inline'),
56
+ (e: unknown) => /fail\.mode/.test((e as Error).message),
57
+ );
58
+ });
59
+
60
+ test('DSL 正例:五种步骤全部通过校验且字段透传', () => {
61
+ const s = validateScenario(
62
+ {
63
+ name: 'all-steps',
64
+ chunking: { charsPerChunk: 3, delayMs: 0 },
65
+ steps: [
66
+ { type: 'text', text: 'a' },
67
+ { type: 'commands', commands: ['tf-final'] },
68
+ { type: 'waitTools', count: 1, timeoutMs: 100 },
69
+ { type: 'fail', mode: 'timeout', delayMs: 1 },
70
+ { type: 'finish', reason: 'max-tokens' },
71
+ ],
72
+ },
73
+ 'inline',
74
+ );
75
+ assert.equal(s.steps.length, 5);
76
+ assert.deepEqual(s.chunking, { charsPerChunk: 3, delayMs: 0 });
77
+ });
78
+
79
+ test('parseTfLine:合法命令 / 畸形命令 / 普通文本三分', () => {
80
+ assert.deepEqual(parseTfLine('tf-write a.txt "A"'), { kind: 'tf-write', raw: 'tf-write a.txt "A"', path: 'a.txt', content: 'A' });
81
+ assert.equal(parseTfLine('tf-read a.txt')?.kind, 'tf-read');
82
+ assert.equal(parseTfLine(' tf-final ')?.kind, 'tf-final');
83
+ assert.equal(parseTfLine('tf-frobnicate x')?.kind, 'malformed');
84
+ assert.equal(parseTfLine('tf-write 没有引号')?.kind, 'malformed');
85
+ assert.equal(parseTfLine('普通注释行'), null);
86
+ assert.equal(parseTfLine(''), null);
87
+ });
88
+
89
+ // ---------------------------------------------------------------------------
90
+ // 逐 token 粒度与流契约(硬性要求 2)
91
+ // ---------------------------------------------------------------------------
92
+
93
+ test('chunk 粒度:charsPerChunk=8 时每个 delta ≤8 字符且拼接无损', async () => {
94
+ const text = '0123456789abcdefghij';
95
+ const model = createMockModel({
96
+ scenarios: [{ name: 'g', chunking: { charsPerChunk: 8, delayMs: 0 }, steps: [{ type: 'text', text }, { type: 'finish' }] }],
97
+ });
98
+ const deltas: string[] = [];
99
+ const types: string[] = [];
100
+ for await (const c of model.adapter.stream({
101
+ provider: 'mock',
102
+ model: 'g',
103
+ messages: [{ role: 'user', content: [{ type: 'text', text: 't' }] }],
104
+ })) {
105
+ types.push(c.type);
106
+ if (c.type === 'text-delta') deltas.push(c.text);
107
+ }
108
+ assert.ok(deltas.length >= 3, '应切成多个 delta');
109
+ assert.ok(deltas.every((d) => d.length <= 8), '每个 delta ≤ 8 字符');
110
+ assert.equal(deltas.join(''), text, '拼接无损');
111
+ assert.equal(types[0], 'block-start');
112
+ assert.equal(types[types.length - 1], 'finish');
113
+ });
114
+
115
+ test('chunk 间隔:delayMs=10、3 个 chunk 时整流耗时 ≥ 20ms', async () => {
116
+ const t0 = Date.now();
117
+ const model = createMockModel({
118
+ scenarios: [{ name: 'd', chunking: { charsPerChunk: 1, delayMs: 10 }, steps: [{ type: 'text', text: 'abc' }, { type: 'finish' }] }],
119
+ });
120
+ for await (const c of model.adapter.stream({
121
+ provider: 'mock',
122
+ model: 'd',
123
+ messages: [{ role: 'user', content: [{ type: 'text', text: 't' }] }],
124
+ })) {
125
+ void c;
126
+ }
127
+ assert.ok(Date.now() - t0 >= 20, '应真实延迟(默认 20ms/chunk 模拟真实 delta 粒度)');
128
+ });
129
+
130
+ test('流契约:usage 在 finish 之前、finish 终止、block-end 携带全量文本', async () => {
131
+ const model = createMockModel({
132
+ scenarios: [{ name: 'c', steps: [{ type: 'text', text: 'hello' }, { type: 'finish' }] }],
133
+ });
134
+ const chunks: import('../src/entry/mock-provider.ts').StreamChunk[] = [];
135
+ for await (const c of model.adapter.stream({
136
+ provider: 'mock',
137
+ model: 'c',
138
+ messages: [{ role: 'user', content: [{ type: 'text', text: '1234' }] }],
139
+ })) {
140
+ chunks.push(c);
141
+ }
142
+ const usageIdx = chunks.findIndex((c) => c.type === 'usage');
143
+ const finishIdx = chunks.findIndex((c) => c.type === 'finish');
144
+ assert.ok(usageIdx >= 0 && finishIdx === chunks.length - 1 && usageIdx === finishIdx - 1, 'usage 紧邻 finish 之前');
145
+ const end = chunks.find((c) => c.type === 'block-end');
146
+ assert.equal(end && end.type === 'block-end' ? end.block.text : undefined, 'hello');
147
+ const usage = chunks[usageIdx]!;
148
+ assert.ok(usage.type === 'usage' && usage.usage.inputTokens > 0 && usage.usage.outputTokens > 0);
149
+ const finish = chunks[finishIdx]!;
150
+ assert.ok(finish.type === 'finish' && finish.reason.kind === 'stop');
151
+ });
152
+
153
+ test('剧本选择:match.model 命中优先,无 match 首个剧本兜底', async () => {
154
+ const model = createMockModel({
155
+ scenarios: [
156
+ { name: 'fallback', steps: [{ type: 'text', text: 'fallback' }, { type: 'finish' }] },
157
+ { name: 'by-model', match: { model: 'special' }, steps: [{ type: 'text', text: 'by-model' }, { type: 'finish' }] },
158
+ ],
159
+ });
160
+ const collect = async (id: string) => {
161
+ let out = '';
162
+ for await (const c of model.adapter.stream({
163
+ provider: 'mock',
164
+ model: id,
165
+ messages: [{ role: 'user', content: [{ type: 'text', text: 'x' }] }],
166
+ })) {
167
+ if (c.type === 'text-delta') out += c.text;
168
+ }
169
+ return out;
170
+ };
171
+ assert.equal(await collect('special'), 'by-model');
172
+ assert.equal(await collect('anything-else'), 'fallback');
173
+ });
174
+
175
+ // ---------------------------------------------------------------------------
176
+ // E2E:正常剧本(验收:3 文件任务写入成功,模型调用次数 = 1)
177
+ // ---------------------------------------------------------------------------
178
+
179
+ test('E2E 正常剧本:3 文件写入成功且模型调用次数 = 1(零 API)', async () => {
180
+ const { dir, cleanup } = sandbox();
181
+ try {
182
+ const model = createMockModel({ scenarios: [loadScenario('3-file-basic.json')] });
183
+ const r = await runStubLoop({ task: '请写三个文件 a.txt b.txt c.txt', model, sandboxDir: dir });
184
+ assert.equal(r.modelCalls, 1, '单流协议:整个任务 1 次模型调用');
185
+ assert.equal(r.finish?.kind, 'stop');
186
+ assert.deepEqual([...r.writtenFiles.keys()].sort(), ['a.txt', 'b.txt', 'c.txt']);
187
+ // 沙箱磁盘上真实存在且内容正确(不走内存假象)
188
+ assert.equal(readFileSync(join(dir, 'a.txt'), 'utf8'), 'A');
189
+ assert.equal(readFileSync(join(dir, 'b.txt'), 'utf8'), 'B');
190
+ assert.equal(readFileSync(join(dir, 'c.txt'), 'utf8'), 'C');
191
+ const toolRecords = r.ledger.filter((e) => e.kind === 'tool');
192
+ assert.equal(toolRecords.length, 3, 'ledger 记录 3 条工具成功');
193
+ assert.ok(toolRecords.every((e) => e.kind !== 'tool' || e.ok), '全部成功');
194
+ assert.ok(r.ledger.some((e) => e.kind === 'final'), 'tf-final 有记录');
195
+ } finally {
196
+ cleanup();
197
+ }
198
+ });
199
+
200
+ // ---------------------------------------------------------------------------
201
+ // E2E:waitTools 挂起-重入
202
+ // ---------------------------------------------------------------------------
203
+
204
+ test('E2E waitTools:流未终止时挂起等工具、回灌后续流、调用次数仍 = 1', async () => {
205
+ const { dir, cleanup } = sandbox();
206
+ try {
207
+ const model = createMockModel({ scenarios: [loadScenario('wait-tools.json')] });
208
+ const r = await runStubLoop({ task: '先写两个文件再读回来', model, sandboxDir: dir });
209
+ assert.equal(r.modelCalls, 1, '挂起-重入不产生第二次模型调用');
210
+ assert.equal(r.finish?.kind, 'stop');
211
+ // 时间线:write 工具执行发生在流 finish 之前(挂起),且 resume 文本在工具之后
212
+ const order = r.timeline.map((e) => e.what);
213
+ const firstTool = order.indexOf('tool-executed');
214
+ const finishIdx = order.indexOf('finish-seen');
215
+ assert.ok(firstTool >= 0 && finishIdx > firstTool, '工具在流终止前执行(挂起-重入)');
216
+ assert.equal(order.filter((w) => w === 'tool-executed').length, 3, '2 写 + 1 读');
217
+ assert.equal(readFileSync(join(dir, 'a.txt'), 'utf8'), '内容A');
218
+ assert.equal(readFileSync(join(dir, 'b.txt'), 'utf8'), '内容B');
219
+ assert.equal(r.readFiles.get('a.txt'), '内容A', 'tf-read 读回了写入内容');
220
+ assert.ok(r.assistantText.includes('前两个文件已写'), '回灌后剧本继续输出');
221
+ assert.ok(r.assistantText.includes('读回确认'), '第二轮 waitTools 也重入成功');
222
+ } finally {
223
+ cleanup();
224
+ }
225
+ });
226
+
227
+ // ---------------------------------------------------------------------------
228
+ // E2E:四种故障剧本(验收:对应处理路径被触发且 ledger 有记录)
229
+ // ---------------------------------------------------------------------------
230
+
231
+ test('E2E 故障 midstream_abort:流中断 → 归一化 error finish + ledger 记录', async () => {
232
+ const { dir, cleanup } = sandbox();
233
+ try {
234
+ const model = createMockModel({ scenarios: [loadScenario('fault-midstream-abort.json')] });
235
+ const r = await runStubLoop({ task: '故障注入:流中断', model, sandboxDir: dir });
236
+ assert.equal(r.finish?.kind, 'error', '桩 loop 经归一化 shim 收到终止 error finish');
237
+ assert.equal(r.finish?.code, 'MOCK_ADAPTER_THROWN');
238
+ assert.ok(r.ledger.some((e) => e.kind === 'tool' && e.ok), '中断前写入的工具仍有 ledger 记录');
239
+ assert.equal(r.ledger.at(-1)?.kind, 'finish', 'ledger 以 finish 记录收尾');
240
+ } finally {
241
+ cleanup();
242
+ }
243
+ });
244
+
245
+ test('E2E 故障 timeout:消费方超时 abort → aborted finish,快速返回', async () => {
246
+ const { dir, cleanup } = sandbox();
247
+ try {
248
+ const model = createMockModel({ scenarios: [loadScenario('fault-timeout.json')] });
249
+ const r = await runStubLoop({ task: '故障注入:流超时', model, sandboxDir: dir, timeoutMs: 200 });
250
+ assert.ok(r.elapsedMs < 5000, `应在超时后快速返回,实际 ${r.elapsedMs}ms`);
251
+ assert.equal(r.finish?.kind, 'aborted', 'mock 尊重 signal,吐 aborted finish');
252
+ const faults = r.ledger.filter((e) => e.kind === 'fault' && e.fault === 'timeout');
253
+ assert.equal(faults.length, 1, 'ledger 有 timeout 故障记录');
254
+ } finally {
255
+ cleanup();
256
+ }
257
+ });
258
+
259
+ test('E2E 故障 timeout 的 fail-fast 反面:消费方从不 abort → 适配器快速抛错而非挂死', async () => {
260
+ const model = createMockModel({
261
+ scenarios: [{ name: 'no-abort', steps: [{ type: 'fail', mode: 'timeout', delayMs: 80 }, { type: 'finish' }] }],
262
+ });
263
+ const it = model.adapter.stream({
264
+ provider: 'mock',
265
+ model: 'no-abort',
266
+ messages: [{ role: 'user', content: [{ type: 'text', text: 'x' }] }],
267
+ })[Symbol.asyncIterator]();
268
+ await it.next(); // 开始
269
+ await assert.rejects(() => it.next(), MockScenarioError, 'delayMs 耗尽仍无人 abort 时快速抛错');
270
+ });
271
+
272
+ test('E2E 故障 malformed_command:畸形行进 ledger、loop 不中断继续收尾', async () => {
273
+ const { dir, cleanup } = sandbox();
274
+ try {
275
+ const model = createMockModel({ scenarios: [loadScenario('fault-malformed-command.json')] });
276
+ const r = await runStubLoop({ task: '故障注入:畸形命令', model, sandboxDir: dir });
277
+ assert.equal(r.finish?.kind, 'stop', 'loop 对畸形命令 fail-soft,流程继续');
278
+ const malformed = r.ledger.filter((e) => e.kind === 'malformed-command');
279
+ assert.equal(malformed.length, 2, '两条畸形行各有一条 ledger 记录');
280
+ assert.deepEqual(malformed.map((e) => (e.kind === 'malformed-command' ? e.line : '')), [
281
+ 'tf-frobnicate x y z',
282
+ 'tf-write 没有引号的内容',
283
+ ]);
284
+ assert.ok(r.ledger.some((e) => e.kind === 'final'), '后续 tf-final 仍被处理');
285
+ } finally {
286
+ cleanup();
287
+ }
288
+ });
289
+
290
+ test('E2E 故障 saturating_output:预算掐断 → aborted finish + ledger 记录', async () => {
291
+ const { dir, cleanup } = sandbox();
292
+ try {
293
+ const model = createMockModel({ scenarios: [loadScenario('fault-saturating-output.json')] });
294
+ const r = await runStubLoop({ task: '故障注入:饱和输出', model, sandboxDir: dir, budgetChars: 2000 });
295
+ assert.ok(r.assistantText.length > 2000, '确实吐出了超过预算的输出');
296
+ assert.equal(r.finish?.kind, 'aborted', '预算触发 abort,mock 吐 aborted finish');
297
+ assert.ok(r.ledger.some((e) => e.kind === 'fault' && e.fault === 'budget-exceeded'), 'ledger 有预算故障记录');
298
+ } finally {
299
+ cleanup();
300
+ }
301
+ });
302
+
303
+ test('E2E waitTools fail-fast:等不到回灌信号 → MOCK_WAITTOOLS_TIMEOUT error finish', async () => {
304
+ const model = createMockModel({
305
+ scenarios: [{ name: 'stuck', steps: [{ type: 'waitTools', count: 5, timeoutMs: 100 }, { type: 'finish' }] }],
306
+ });
307
+ let finishCode: string | undefined;
308
+ for await (const c of model.adapter.stream({
309
+ provider: 'mock',
310
+ model: 'stuck',
311
+ messages: [{ role: 'user', content: [{ type: 'text', text: 'x' }] }],
312
+ })) {
313
+ if (c.type === 'finish') finishCode = (c.reason as { code?: string }).code;
314
+ }
315
+ assert.equal(finishCode, 'MOCK_WAITTOOLS_TIMEOUT', '快速失败而非挂死');
316
+ });
317
+
318
+ // ---------------------------------------------------------------------------
319
+ // entry 装配(不连真实宿主,用 duck-type 假 ctx)
320
+ // ---------------------------------------------------------------------------
321
+
322
+ test('entry apply:注册 adapter + 目录条目 + 挂 mockModel + effect 释放', async () => {
323
+ const { default: apply } = await import('../src/entry/mock-provider.ts');
324
+ const registered: { routes: string[]; count: number } = { routes: [], count: 0 };
325
+ const disposers: (() => void)[] = [];
326
+ const ctx = {
327
+ llm: {
328
+ registerAdapter(providers: string[], _adapter: unknown) {
329
+ registered.routes = providers;
330
+ const d = () => disposers.push(() => {});
331
+ disposers.push(d);
332
+ return d;
333
+ },
334
+ registerConfigurableProviders(_entries: readonly unknown[]) {
335
+ registered.count += 1;
336
+ return () => {};
337
+ },
338
+ },
339
+ effect(fn: () => () => void) {
340
+ disposers.push(fn());
341
+ },
342
+ };
343
+ const model = apply(ctx, { scenarios: [{ name: 'e', steps: [{ type: 'finish' }] }], provider: 'mock-test' });
344
+ assert.ok(model);
345
+ assert.deepEqual(registered.routes, ['mock-test']);
346
+ assert.equal(registered.count, 1, 'F10 目录条目已登记');
347
+ assert.equal((ctx as { mockModel?: unknown }).mockModel, model, 'loop 侧信号源已挂上');
348
+ for (const d of disposers.splice(0)) d();
349
+ });
350
+
351
+ test('entry apply:ctx.llm 缺失时 fail-fast 返回 undefined 并打印明确错误', async () => {
352
+ const { default: apply } = await import('../src/entry/mock-provider.ts');
353
+ const errors: string[] = [];
354
+ const orig = console.error;
355
+ console.error = (...args: unknown[]) => errors.push(args.join(' '));
356
+ try {
357
+ const r = apply({}, { scenarios: [{ name: 'noop', steps: [{ type: 'finish' }] }] });
358
+ assert.equal(r, undefined);
359
+ } finally {
360
+ console.error = orig;
361
+ }
362
+ assert.ok(errors.some((m) => /ctx\.llm 不可用/.test(m)), '错误信息明确(红线 5 反面:快速失败)');
363
+ });
364
+
365
+ // ---------------------------------------------------------------------------
366
+ // 调用记录(供 08 号重放比对)
367
+ // ---------------------------------------------------------------------------
368
+
369
+ test('calls 记录:每次 stream 留痕(chunk 序列 / 文本 / finish)', async () => {
370
+ const model = createMockModel({
371
+ scenarios: [{ name: 'rec', steps: [{ type: 'text', text: 'hi' }, { type: 'finish' }] }],
372
+ });
373
+ for await (const c of model.adapter.stream({
374
+ provider: 'mock',
375
+ model: 'rec',
376
+ messages: [{ role: 'user', content: [{ type: 'text', text: 'x' }] }],
377
+ })) {
378
+ void c;
379
+ }
380
+ assert.equal(model.calls.length, 1);
381
+ const rec = model.calls[0]!;
382
+ assert.equal(rec.scenario, 'rec');
383
+ assert.ok(rec.finished && rec.finishKind === 'stop');
384
+ assert.ok(rec.chunkTypes.includes('text-delta') && rec.chunkTypes.at(-1) === 'finish');
385
+ assert.equal(rec.emittedText, 'hi');
386
+ });