@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,599 @@
1
+ // test/fix-limits.test.ts —— 四个已知限制的修复验收(README 已知限制 1–4 对应 docs/limitations.md 1/3/5/7)
2
+ //
3
+ // 修复 1(写批任务 token 偏重):自写回验 receipt —— tf-read 命中本任务 tf-write 已写过的
4
+ // 路径时只注入回执(行数 + 内容指纹),不再回灌全文;外部文件的完整反馈保持不变。
5
+ // 修复 2(steer 语义偏离):运行中回合的 steer 注入下一请求(追加区 [tf-stream:steer]),
6
+ // 对齐内建"注入运行中回合的下一步";空闲时保持"插队队首、新回合任务"语义。
7
+ // 修复 3(持久化依赖宿主 storage):宿主缺 sessionPersistence → 本地 JSONL 会话持久化;
8
+ // state-handle 宿主缺 storage backend → 本地文件 KvUnit(A4 在 adapters.test.ts)。
9
+ // 修复 4(bundle 形态 plugin record 降级):宿主模块不可达 → 本地文件台账(可重放),
10
+ // resume 时 final 答案回灌驱动器(rehydrateRecords)。
11
+
12
+ import { describe, it, beforeEach } from 'node:test';
13
+ import assert from 'node:assert/strict';
14
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
15
+ import { tmpdir } from 'node:os';
16
+ import { join } from 'node:path';
17
+ import { randomUUID } from 'node:crypto';
18
+
19
+ import {
20
+ SingleStreamDriver,
21
+ StreamLoopAgent,
22
+ createStreamAgentFactory,
23
+ attachSessionLedger,
24
+ createSessionEventWriter,
25
+ normalizeStreamShim,
26
+ } from '../src/entry/loop.ts';
27
+ import type { DriverPorts, StreamRequestOptions, ToolBatchInputLike, ToolBatchResultLike, StreamDriverConfig } from '../src/entry/loop.ts';
28
+ import { createMockModel } from '../src/entry/mock-provider.ts';
29
+ import type { MockModel, Scenario } from '../src/entry/mock-provider.ts';
30
+ import { JsonFileKvUnit, appendLedgerRecord, createJsonlPersistence, loadLedgerRecords, withEventCapture } from '../src/entry/json-persistence.ts';
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // 测试设施(与 loop.test.ts 同款最小装配)
34
+ // ---------------------------------------------------------------------------
35
+
36
+ function loadScenario(name: string): Scenario {
37
+ return JSON.parse(readFileSync(join(import.meta.dirname, 'scenarios', name), 'utf8')) as unknown as Scenario;
38
+ }
39
+
40
+ function createSandboxExecutor(sandboxDir: string) {
41
+ return async (input: ToolBatchInputLike): Promise<ToolBatchResultLike> => {
42
+ const results: ToolBatchResultLike['results'] = [];
43
+ for (const call of input.calls) {
44
+ const args = JSON.parse(call.arguments) as Record<string, unknown>;
45
+ try {
46
+ if (call.name === 'write') {
47
+ const filePath = String(args['file_path'] ?? '');
48
+ writeFileSync(join(sandboxDir, filePath), String(args['content'] ?? ''), 'utf8');
49
+ results.push({ callId: call.id, result: { content: [{ type: 'text', text: `written ${filePath}` }], isError: false } });
50
+ } else if (call.name === 'read') {
51
+ const content = readFileSync(join(sandboxDir, String(args['file_path'] ?? '')), 'utf8');
52
+ results.push({ callId: call.id, result: { content: [{ type: 'text', text: content }], isError: false } });
53
+ } else {
54
+ results.push({ callId: call.id, result: { content: [{ type: 'text', text: `unknown tool: ${call.name}` }], isError: true } });
55
+ }
56
+ } catch (error) {
57
+ results.push({ callId: call.id, result: { content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }], isError: true } });
58
+ }
59
+ }
60
+ return { results, additionalContexts: [], concluded: false };
61
+ };
62
+ }
63
+
64
+ interface Harness {
65
+ driver: SingleStreamDriver;
66
+ model: MockModel;
67
+ wireRequests: Array<StreamRequestOptions & { contentTexts: string[] }>;
68
+ sandboxDir: string;
69
+ cleanup: () => void;
70
+ }
71
+
72
+ function makeHarness(opts: {
73
+ task: string;
74
+ scenarios: Scenario[];
75
+ seed?: Record<string, string>;
76
+ config?: Partial<StreamDriverConfig>;
77
+ onFirstSettle?: (driver: SingleStreamDriver) => void;
78
+ }): Harness {
79
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-fix-'));
80
+ for (const [name, content] of Object.entries(opts.seed ?? {})) writeFileSync(join(sandboxDir, name), content, 'utf8');
81
+ const model = createMockModel({ scenarios: opts.scenarios, provider: 'mock' });
82
+ const wireRequests: Array<StreamRequestOptions & { contentTexts: string[] }> = [];
83
+ let settled = false;
84
+ let driverRef: SingleStreamDriver | undefined;
85
+ const ports: DriverPorts = {
86
+ stream: (options) => {
87
+ wireRequests.push({ ...options, contentTexts: options.messages.map((m) => m.content.map((b) => b.text ?? '').join('\n')) });
88
+ return normalizeStreamShim(model.adapter.stream({ provider: options.provider, model: options.model, messages: options.messages, signal: options.signal }));
89
+ },
90
+ executeTools: createSandboxExecutor(sandboxDir),
91
+ onToolSettled: () => {
92
+ model.notifyToolResult();
93
+ if (!settled && opts.onFirstSettle !== undefined && driverRef !== undefined) {
94
+ settled = true;
95
+ opts.onFirstSettle(driverRef);
96
+ }
97
+ },
98
+ };
99
+ const config: StreamDriverConfig = { provider: 'mock', model: 'mock-scenario', streamIdleTimeoutMs: 30_000, ...opts.config };
100
+ const driver = new SingleStreamDriver(ports, config);
101
+ driverRef = driver;
102
+ driver.pushUserTask(opts.task);
103
+ return { driver, model, wireRequests, sandboxDir, cleanup: () => rmSync(sandboxDir, { recursive: true, force: true }) };
104
+ }
105
+
106
+ function lastReasonOf(driver: SingleStreamDriver): string {
107
+ const ends = driver.snapshot().records.filter((r) => r.kind === 'turn-end');
108
+ const last = ends[ends.length - 1];
109
+ assert.ok(last !== undefined && last.kind === 'turn-end', '必须有 turn-end 记录');
110
+ return last.reason.kind;
111
+ }
112
+
113
+ const tick = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 5));
114
+
115
+ // ---------------------------------------------------------------------------
116
+ // 修复 1:自写回验 receipt
117
+ // ---------------------------------------------------------------------------
118
+
119
+ describe('修复限制 1:自写回验 receipt(写批任务 token 偏重)', () => {
120
+ let harness: Harness | undefined;
121
+ beforeEach(() => {
122
+ harness?.cleanup();
123
+ harness = undefined;
124
+ });
125
+
126
+ const writeReadScenario: Scenario = {
127
+ name: 'write-then-read',
128
+ match: { promptIncludes: '回验演练' },
129
+ chunking: { charsPerChunk: 0, delayMs: 0 },
130
+ steps: [
131
+ { type: 'text', text: '写完读回确认。\n' },
132
+ { type: 'commands', commands: ['<tf-write path="a.txt" id="w1">内容A-独一无二-42</tf-write>', '<tf-read path="a.txt" id="r1"/>', '<tf-final id="f1" summary="done"/>'] },
133
+ { type: 'waitTools', count: 2, timeoutMs: 5000 },
134
+ { type: 'finish', reason: 'stop' },
135
+ ],
136
+ };
137
+
138
+ it('R1. 写后读同路径 → receipt 回执(不回灌全文),任务收敛', async () => {
139
+ harness = makeHarness({ task: '回验演练:写 a.txt 再读回。', scenarios: [writeReadScenario] });
140
+ try {
141
+ const reason = await harness.driver.runTurn();
142
+ assert.equal(reason.kind, 'completed');
143
+ assert.ok(existsSync(join(harness.sandboxDir, 'a.txt')));
144
+ const req1 = harness.wireRequests[0]!;
145
+ const req2 = harness.wireRequests[1]!;
146
+ assert.ok(!req1.contentTexts.some((t) => t.includes('[tf-stream:receipt handle=')), '请求 1 不应有 receipt');
147
+ const receipt = req2.contentTexts.find((t) => t.includes('[tf-stream:receipt handle=') && t.includes('path=a.txt'));
148
+ assert.ok(receipt !== undefined, `请求 2 应注入 receipt:\n${req2.contentTexts.join('\n---\n').slice(0, 1200)}`);
149
+ assert.ok(/sha256=[0-9a-f]{16}/.test(receipt), 'receipt 应带内容指纹');
150
+ assert.ok(receipt.includes('lines='), 'receipt 应带行数');
151
+ assert.ok(!receipt.includes('内容A-独一无二-42'), 'receipt 不得回灌自写文件全文');
152
+ // 完整反馈块也不该出现
153
+ assert.ok(!req2.contentTexts.some((t) => t.includes('内容A-独一无二-42')), '自写文件全文不得进任何注入块');
154
+ } finally {
155
+ harness.cleanup();
156
+ }
157
+ });
158
+
159
+ it('R2. config selfReadFeedback=full → 恢复 v0.1 完整反馈行为', async () => {
160
+ harness = makeHarness({ task: '回验演练:写 a.txt 再读回。', scenarios: [writeReadScenario], config: { selfReadFeedback: 'full' } });
161
+ try {
162
+ const reason = await harness.driver.runTurn();
163
+ assert.equal(reason.kind, 'completed');
164
+ const req2 = harness.wireRequests[1]!;
165
+ assert.ok(req2.contentTexts.some((t) => t.includes('内容A-独一无二-42')), 'full 模式应回灌全文');
166
+ assert.ok(!req2.contentTexts.some((t) => t.includes('[tf-stream:receipt handle=')), 'full 模式不应有 receipt');
167
+ } finally {
168
+ harness.cleanup();
169
+ }
170
+ });
171
+
172
+ it('R3. 读外部文件(非本任务写入)→ 完整反馈保持不变', async () => {
173
+ harness = makeHarness({
174
+ task: '回验演练:读已有的 big.txt。',
175
+ scenarios: [
176
+ {
177
+ name: 'read-foreign',
178
+ match: { promptIncludes: '回验演练' },
179
+ chunking: { charsPerChunk: 0, delayMs: 0 },
180
+ steps: [
181
+ { type: 'text', text: '读外部文件。\n' },
182
+ { type: 'commands', commands: ['<tf-read path="big.txt" id="r1"/>', '<tf-final id="f1" summary="answer-FOREIGN-LINE-2"/>'] },
183
+ { type: 'waitTools', count: 1, timeoutMs: 5000 },
184
+ { type: 'finish', reason: 'stop' },
185
+ ],
186
+ },
187
+ ],
188
+ seed: { 'big.txt': 'FOREIGN-LINE-1\nFOREIGN-LINE-2\nFOREIGN-LINE-3\n' },
189
+ });
190
+ try {
191
+ const reason = await harness.driver.runTurn();
192
+ assert.equal(reason.kind, 'completed');
193
+ const req2 = harness.wireRequests[1]!;
194
+ assert.ok(req2.contentTexts.some((t) => t.includes('FOREIGN-LINE-2')), '外部文件应完整反馈');
195
+ assert.ok(!req2.contentTexts.some((t) => t.includes('[tf-stream:receipt handle=')), '外部文件不应走 receipt');
196
+ } finally {
197
+ harness.cleanup();
198
+ }
199
+ });
200
+ });
201
+
202
+ // ---------------------------------------------------------------------------
203
+ // 修复 2:steer 运行中回合注入
204
+ // ---------------------------------------------------------------------------
205
+
206
+ describe('修复限制 2:steer 注入运行中回合的下一步', () => {
207
+ let harness: Harness | undefined;
208
+ beforeEach(() => {
209
+ harness?.cleanup();
210
+ harness = undefined;
211
+ });
212
+
213
+ it('S1. driver 级:运行中 pushSteer → 下一请求含 [tf-stream:steer] 用户块,插话被看到后才收敛', async () => {
214
+ harness = makeHarness({
215
+ task: 'steer演练:读一个不存在的文件。',
216
+ scenarios: [
217
+ {
218
+ name: 'steered-continue',
219
+ match: { promptIncludes: 'tf-stream:steer' },
220
+ chunking: { charsPerChunk: 0, delayMs: 0 },
221
+ steps: [
222
+ { type: 'text', text: '收到插话,按新指令收尾。\n' },
223
+ { type: 'commands', commands: ['<tf-final id="f2" summary="steered-done"/>'] },
224
+ { type: 'finish', reason: 'stop' },
225
+ ],
226
+ },
227
+ {
228
+ name: 'steer-base',
229
+ match: { promptIncludes: 'steer演练' },
230
+ chunking: { charsPerChunk: 0, delayMs: 0 },
231
+ steps: [
232
+ { type: 'text', text: '先读 missing.txt。\n' },
233
+ { type: 'commands', commands: ['<tf-read path="missing.txt" id="r1"/>', '<tf-final id="f1" summary="premature"/>'] },
234
+ { type: 'waitTools', count: 1, timeoutMs: 5000 },
235
+ { type: 'finish', reason: 'stop' },
236
+ ],
237
+ },
238
+ ],
239
+ // 工具落定即插话:时序确定(命令在途时 steer 到达,必须等下一请求才能被看到)
240
+ onFirstSettle: (driver) => driver.pushSteer('请立刻改为读 other.txt 并收尾。', { role: 'user', source: 'steer-test' }),
241
+ });
242
+ try {
243
+ const reason = await harness.driver.runTurn();
244
+ assert.equal(reason.kind, 'completed');
245
+ // 插话必须出现在某个请求的装配历史里(追加区,单调不破)
246
+ const steerReq = harness.wireRequests.find((r) => r.contentTexts.some((t) => t.includes('[tf-stream:steer]') && t.includes('请立刻改为读 other.txt')));
247
+ assert.ok(steerReq !== undefined, `steer 必须注入下一请求:\n${harness.wireRequests.map((r) => r.contentTexts.join('|')).join('\n---\n').slice(0, 2000)}`);
248
+ // 收敛答案 = 插话后剧本的 final(last-wins)
249
+ const finals = harness.driver.snapshot().records.filter((r) => r.kind === 'final');
250
+ const last = finals[finals.length - 1] as { summary?: string };
251
+ assert.equal(last.summary, 'steered-done');
252
+ // 前缀单调:含 steer 的请求必须包含其前所有请求的稳定段(追加式增长)
253
+ for (let i = 1; i < harness.wireRequests.length; i += 1) {
254
+ const prev = harness.wireRequests[i - 1]!;
255
+ const cur = harness.wireRequests[i]!;
256
+ assert.ok(cur.contentTexts.length >= prev.contentTexts.length, '请求只能追加不能收缩');
257
+ for (let j = 0; j < prev.contentTexts.length; j += 1) {
258
+ assert.equal(cur.contentTexts[j], prev.contentTexts[j], `第 ${i} 请求第 ${j} 条消息必须逐字节稳定`);
259
+ }
260
+ }
261
+ } finally {
262
+ harness.cleanup();
263
+ }
264
+ });
265
+
266
+ it('S2. agent 级:运行中 steer → inbox.nextStep 如实暴露、消费后清空;空闲 steer → 新回合任务', async () => {
267
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-fix-agent-'));
268
+ const { ctx } = createFakeHostLite();
269
+ const model = createMockModel({
270
+ scenarios: [
271
+ // 顺序敏感:'空闲插话' 更具体,排在 'tf-stream:steer' 之前(历史里两个标记可能同时出现)
272
+ {
273
+ name: 'agent-idle-steer',
274
+ match: { promptIncludes: '空闲插话' },
275
+ chunking: { charsPerChunk: 0, delayMs: 0 },
276
+ steps: [
277
+ { type: 'text', text: '空闲插话当新任务。\n' },
278
+ { type: 'commands', commands: ['<tf-final id="f3" summary="idle-steer-done"/>'] },
279
+ { type: 'finish', reason: 'stop' },
280
+ ],
281
+ },
282
+ {
283
+ name: 'agent-steered',
284
+ match: { promptIncludes: 'tf-stream:steer' },
285
+ chunking: { charsPerChunk: 0, delayMs: 0 },
286
+ steps: [
287
+ { type: 'text', text: '按插话收尾。\n' },
288
+ { type: 'commands', commands: ['<tf-final id="f2" summary="steered-done"/>'] },
289
+ { type: 'finish', reason: 'stop' },
290
+ ],
291
+ },
292
+ {
293
+ name: 'agent-base',
294
+ match: { promptIncludes: 'agent 演练' },
295
+ chunking: { charsPerChunk: 0, delayMs: 0 },
296
+ steps: [
297
+ { type: 'text', text: '先读 missing.txt。\n' },
298
+ { type: 'commands', commands: ['<tf-read path="missing.txt" id="r1"/>', '<tf-final id="f1" summary="premature"/>'] },
299
+ { type: 'waitTools', count: 1, timeoutMs: 5000 },
300
+ { type: 'finish', reason: 'stop' },
301
+ ],
302
+ },
303
+ ],
304
+ provider: 'mock',
305
+ });
306
+ let settled = false;
307
+ let agentRef: StreamLoopAgent | undefined;
308
+ const driver = new SingleStreamDriver(
309
+ {
310
+ stream: (options) => normalizeStreamShim(model.adapter.stream({ provider: options.provider, model: options.model, messages: options.messages, signal: options.signal })),
311
+ executeTools: createSandboxExecutor(sandboxDir),
312
+ onToolSettled: () => {
313
+ model.notifyToolResult();
314
+ // 命令在途时经 Agent.steer 插话(真实入口;时序确定:必须等下一请求才能被看到)
315
+ if (!settled && agentRef !== undefined) {
316
+ settled = true;
317
+ agentRef.steer({ role: 'user', content: [{ type: 'text', text: '运行中插话:直接收尾。' }] });
318
+ }
319
+ },
320
+ },
321
+ { provider: 'mock', model: 'mock-scenario', streamIdleTimeoutMs: 30_000 },
322
+ );
323
+ const fakeSession = { id: 'agent-steer-1', header: { id: 'agent-steer-1' }, events: [] as Array<{ type: string; data: unknown }>, append(type: string, data: unknown) { fakeSession.events.push({ type, data }); } };
324
+ const agent = new StreamLoopAgent({ id: 'agent-steer-1', session: fakeSession, driver, modelSelection: { provider: 'mock', model: 'mock-scenario' } });
325
+ agentRef = agent;
326
+
327
+ // ① 运行中 steer:插话在回合内被消费(注入下一请求),收敛答案取插话后的 final
328
+ agent.followup({ role: 'user', content: [{ type: 'text', text: 'agent 演练:读 missing.txt。' }] });
329
+ assert.equal(agent.status, 'running');
330
+ await agent.whenIdle();
331
+ assert.equal(agent.status, 'idle');
332
+ assert.equal((driver.pendingSteerMessages as unknown[]).length, 0, '插话消费后清空');
333
+ assert.equal(agent.inbox.nextStep.length, 0);
334
+ // 会话事件含两条 user/message(原任务 + steer)
335
+ const userMessages = fakeSession.events.filter((e) => e.type === 'user/message');
336
+ assert.equal(userMessages.length, 2, `应有两条 user/message,实际:${fakeSession.events.map((e) => e.type).join(',')}`);
337
+ const finals = driver.snapshot().records.filter((r) => r.kind === 'final');
338
+ assert.equal((finals[finals.length - 1] as { summary?: string }).summary, 'steered-done');
339
+
340
+ // ② 空闲 steer:插队队首当新回合任务(内建空闲语义一致);user/message 落第三条
341
+ agent.steer({ role: 'user', content: [{ type: 'text', text: '空闲插话:把这个当新任务。' }] });
342
+ await agent.whenIdle();
343
+ assert.equal((driver.snapshot().records.filter((r) => r.kind === 'final').at(-1) as { summary?: string }).summary, 'idle-steer-done');
344
+ assert.equal(fakeSession.events.filter((e) => e.type === 'user/message').length, 3);
345
+ rmSync(sandboxDir, { recursive: true, force: true });
346
+ });
347
+ });
348
+
349
+ // ---------------------------------------------------------------------------
350
+ // 修复 3:本地持久化兜底
351
+ // ---------------------------------------------------------------------------
352
+
353
+ describe('修复限制 3:本地 JSONL 会话持久化(宿主 sessionPersistence 缺位)', () => {
354
+ it('P1. JsonFileKvUnit:落盘 + 重开实例数据仍在(durable)', async () => {
355
+ const dir = mkdtempSync(join(tmpdir(), 'tf-fix-kv-'));
356
+ try {
357
+ const one = new JsonFileKvUnit(dir, 'unitA', () => {});
358
+ await one.putRecord('blobs', 'k1', { b64: 'YWJj' });
359
+ await one.putRecord('handles', 'k2', { handle: 'file:a.txt@v1' });
360
+ const all = await one.loadAll();
361
+ assert.deepEqual((all.tables['blobs'] as Record<string, unknown>)['k1'], { b64: 'YWJj' });
362
+ await one.close();
363
+ // "重启":新实例同一文件
364
+ const two = new JsonFileKvUnit(dir, 'unitA', () => {});
365
+ const all2 = await two.loadAll();
366
+ assert.deepEqual((all2.tables['handles'] as Record<string, unknown>)['k2'], { handle: 'file:a.txt@v1' });
367
+ await two.close();
368
+ } finally {
369
+ rmSync(dir, { recursive: true, force: true });
370
+ }
371
+ });
372
+
373
+ it('P2. factory E2E:无宿主 sessionPersistence → 本地 JSONL 落盘;resume 从 JSONL 冷读重建', async () => {
374
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-fix-pers-'));
375
+ const sessionsDir = mkdtempSync(join(tmpdir(), 'tf-fix-sess-'));
376
+ const sessionId = `session-${randomUUID()}`;
377
+ const warnings: string[] = [];
378
+ const warn = (m: string, d?: unknown) => warnings.push(`${m} ${String(d)}`);
379
+ try {
380
+ const model = createMockModel({ scenarios: [loadScenario('5-file-basic.json')], provider: 'mock' });
381
+ const makeFactory = () => createStreamAgentFactory({
382
+ ctx: createFakeHostLite().ctx, // 无 sessionPersistence 服务
383
+ createFallbackPersistence: (sid) => createJsonlPersistence(sessionsDir, sid, warn),
384
+ createDriver({ session }) {
385
+ return {
386
+ driver: new SingleStreamDriver(
387
+ {
388
+ stream: (o) => normalizeStreamShim(model.adapter.stream({ provider: o.provider, model: o.model, messages: o.messages, signal: o.signal })),
389
+ executeTools: createSandboxExecutor(sandboxDir),
390
+ events: createSessionEventWriter(session),
391
+ onToolSettled: () => model.notifyToolResult(),
392
+ onWarning: warn,
393
+ },
394
+ { provider: 'mock', model: 'mock-scenario', streamIdleTimeoutMs: 30_000 },
395
+ ),
396
+ };
397
+ },
398
+ });
399
+
400
+ // ① 创建 + 跑任务 + dispose
401
+ const factory = makeFactory();
402
+ const handle = await factory.createAgent(undefined, { sessionId, agentOptions: { provider: 'mock', model: 'mock-scenario' } });
403
+ handle.agent.followup({ role: 'user', content: [{ type: 'text', text: '请写五个文件 f1 到 f5。' }] });
404
+ await handle.agent.whenIdle();
405
+ assert.ok(existsSync(join(sandboxDir, 'f3.txt')), '任务应完成');
406
+ await handle.dispose();
407
+
408
+ // ② 会话事件已落 JSONL(含 user/message)
409
+ const logFile = join(sessionsDir, `${sessionId}.jsonl`);
410
+ assert.ok(existsSync(logFile), `会话 JSONL 应存在:${logFile}`);
411
+ const logText = readFileSync(logFile, 'utf8');
412
+ assert.ok(logText.includes('user/message'), 'user/message 应落 JSONL');
413
+ assert.ok(logText.includes('turn/end'), 'turn/end 应落 JSONL');
414
+
415
+ // ③ resume:从 JSONL 冷读(无宿主持久化也能跨会话),新回合继续追加同一文件
416
+ const factory2 = makeFactory();
417
+ const handle2 = await factory2.resume(undefined, { resumeSessionId: sessionId, agentOptions: { provider: 'mock', model: 'mock-scenario' } });
418
+ handle2.agent.followup({ role: 'user', content: [{ type: 'text', text: '请写五个文件 f1 到 f5(续跑)。' }] });
419
+ await handle2.agent.whenIdle();
420
+ await handle2.dispose();
421
+ const logText2 = readFileSync(logFile, 'utf8');
422
+ assert.ok(logText2.split('\n').length > logText.split('\n').length, 'resume 后事件应继续追加');
423
+ assert.ok(existsSync(join(sandboxDir, 'f3.txt')));
424
+ } finally {
425
+ rmSync(sandboxDir, { recursive: true, force: true });
426
+ rmSync(sessionsDir, { recursive: true, force: true });
427
+ }
428
+ });
429
+ });
430
+
431
+ // ---------------------------------------------------------------------------
432
+ // 修复 4:plugin record 通道降级 → 本地文件台账 + resume 重放
433
+ // ---------------------------------------------------------------------------
434
+
435
+ describe('修复限制 4:本地文件台账(bundle plugin record 通道降级)', () => {
436
+ it('L1. 宿主模块不可达 + 提供本地台账 → 记录落 JSONL(可重放),且告警不静默', async () => {
437
+ const dir = mkdtempSync(join(tmpdir(), 'tf-fix-ledger-'));
438
+ try {
439
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-fix-ledger-sb-'));
440
+ const warnings: string[] = [];
441
+ const model = createMockModel({ scenarios: [{ name: 'idle', match: { promptIncludes: '任务' }, chunking: { charsPerChunk: 0, delayMs: 0 }, steps: [{ type: 'finish', reason: 'stop' }] }], provider: 'mock' });
442
+ const driver = new SingleStreamDriver(
443
+ {
444
+ stream: (o) => normalizeStreamShim(model.adapter.stream({ provider: o.provider, model: o.model, messages: o.messages, signal: o.signal })),
445
+ executeTools: createSandboxExecutor(sandboxDir),
446
+ onToolSettled: () => model.notifyToolResult(),
447
+ },
448
+ { provider: 'mock', model: 'mock-scenario' },
449
+ );
450
+ driver.pushUserTask('任务:什么都不做,直接结束。');
451
+ const ledgerFile = join(dir, 'ledger', 'sess-1.jsonl');
452
+ // ctx 无 loader → 三级宿主解析全失败(本环境无 @deepseek-ai/dsh-session)→ 文件台账
453
+ await attachSessionLedger(
454
+ driver,
455
+ { append() {} },
456
+ (m) => warnings.push(m),
457
+ {},
458
+ { file: ledgerFile, appendRecord: (type: string, data: unknown) => appendLedgerRecord(ledgerFile, type, data) },
459
+ );
460
+ const reason = await driver.runTurn();
461
+ assert.ok(reason.kind === 'blocked' || reason.kind === 'completed');
462
+ assert.ok(existsSync(ledgerFile), '台账 JSONL 应存在');
463
+ const { records, skipped } = loadLedgerRecords(ledgerFile);
464
+ assert.equal(skipped, 0);
465
+ assert.ok(records.some((r) => r.type === 'plugin:tf-agent/step'), 'turn-end 台账应落盘');
466
+ assert.equal(driver.snapshot().records.length > 0, true);
467
+ assert.ok(warnings.some((w) => w.includes('台账')), '降级必须告警');
468
+ rmSync(sandboxDir, { recursive: true, force: true });
469
+ } finally {
470
+ rmSync(dir, { recursive: true, force: true });
471
+ }
472
+ });
473
+
474
+ it('L2. rehydrateRecords:final 答案回灌(last-wins 候选),命令记录跳过不占 id', () => {
475
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-fix-rehy-'));
476
+ const model = createMockModel({ scenarios: [{ name: 'dummy', steps: [{ type: 'finish', reason: 'stop' }] }], provider: 'mock' });
477
+ const driver = new SingleStreamDriver(
478
+ {
479
+ stream: (o) => normalizeStreamShim(model.adapter.stream({ provider: o.provider, model: o.model, messages: o.messages, signal: o.signal })),
480
+ executeTools: createSandboxExecutor(sandboxDir),
481
+ },
482
+ { provider: 'mock', model: 'mock-scenario' },
483
+ );
484
+ const replay = driver.rehydrateRecords([
485
+ { kind: 'plugin:tf-agent/final', data: { summary: 'resumed-answer-v1', cmdId: 'f1' } },
486
+ { kind: 'plugin:tf-agent/final', data: { summary: 'resumed-answer-v2', cmdId: 'f1' } },
487
+ { kind: 'plugin:tf-agent/command', data: { cmdId: 'w1', name: 'tf-write', status: 'ok' } },
488
+ { kind: 'plugin:tf-agent/fault', data: { fault: 'malformed-command' } },
489
+ ]);
490
+ assert.equal(replay.applied, 2, '两条 final 都回灌(last-wins 靠数组序)');
491
+ assert.equal(replay.skipped, 2, '命令与 fault 记录跳过');
492
+ const finals = driver.snapshot().records.filter((r) => r.kind === 'final').map((r) => (r as { summary?: string }).summary);
493
+ assert.deepEqual(finals, ['resumed-answer-v1', 'resumed-answer-v2']);
494
+ // 命令 id 未被占用:w1 可正常登记(不因回放被"换新 id"拒绝)
495
+ void sandboxDir;
496
+ rmSync(sandboxDir, { recursive: true, force: true });
497
+ });
498
+
499
+ it('L3. resume 全链路:上一会话的 final 答案从文件台账回灌新驱动器', async () => {
500
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-fix-resume-'));
501
+ const sessionsDir = mkdtempSync(join(tmpdir(), 'tf-fix-resume-sess-'));
502
+ const ledgerDir = mkdtempSync(join(tmpdir(), 'tf-fix-resume-led-'));
503
+ const sessionId = `session-${randomUUID()}`;
504
+ try {
505
+ const { ctx } = createFakeHostLite();
506
+ const model = createMockModel({ scenarios: [loadScenario('5-file-basic.json')], provider: 'mock' });
507
+ const makeFactory = () => createStreamAgentFactory({
508
+ ctx,
509
+ createFallbackPersistence: (sid) => createJsonlPersistence(sessionsDir, sid, () => {}),
510
+ fallbackLedger: (sid) => {
511
+ const file = join(ledgerDir, `${sid}.jsonl`);
512
+ return {
513
+ file,
514
+ appendRecord: (type: string, data: unknown) => import('../src/entry/json-persistence.ts').then((m) => m.appendLedgerRecord(file, type, data)),
515
+ };
516
+ },
517
+ createDriver() {
518
+ return {
519
+ driver: new SingleStreamDriver(
520
+ {
521
+ stream: (o) => normalizeStreamShim(model.adapter.stream({ provider: o.provider, model: o.model, messages: o.messages, signal: o.signal })),
522
+ executeTools: createSandboxExecutor(sandboxDir),
523
+ onToolSettled: () => model.notifyToolResult(),
524
+ },
525
+ { provider: 'mock', model: 'mock-scenario', streamIdleTimeoutMs: 30_000 },
526
+ ),
527
+ };
528
+ },
529
+ });
530
+ const handle = await makeFactory().createAgent(undefined, { sessionId, agentOptions: { provider: 'mock', model: 'mock-scenario' } });
531
+ handle.agent.followup({ role: 'user', content: [{ type: 'text', text: '请写五个文件 f1 到 f5。' }] });
532
+ await handle.agent.whenIdle();
533
+ await handle.dispose();
534
+
535
+ const resumed = await makeFactory().resume(undefined, { resumeSessionId: sessionId, agentOptions: { provider: 'mock', model: 'mock-scenario' } });
536
+ // 通过 ledger 文件直接验证重放源存在(rehydrateRecords 的单测在 L2)
537
+ const ledgerFile = join(ledgerDir, `${sessionId}.jsonl`);
538
+ const { records } = loadLedgerRecords(ledgerFile);
539
+ assert.ok(records.some((r) => r.type === 'plugin:tf-agent/final'), 'final 记录应已在文件台账');
540
+ assert.ok(records.some((r) => r.type === 'plugin:tf-agent/command'), 'command 记录应已在文件台账');
541
+ await resumed.dispose();
542
+ } finally {
543
+ rmSync(sandboxDir, { recursive: true, force: true });
544
+ rmSync(sessionsDir, { recursive: true, force: true });
545
+ rmSync(ledgerDir, { recursive: true, force: true });
546
+ }
547
+ });
548
+ });
549
+
550
+ // ---------------------------------------------------------------------------
551
+ // withEventCapture(修复 3 的事件镜像面)
552
+ // ---------------------------------------------------------------------------
553
+
554
+ describe('withEventCapture', () => {
555
+ it('append 代理:事件镜像进 sink,返回值与原型链方法透传不变', () => {
556
+ const captured: unknown[][] = [];
557
+ const base = {
558
+ id: 's1',
559
+ header: { id: 's1' },
560
+ append(type: string, data: unknown) {
561
+ return { seq: (this as unknown as { n: number }).n++, type, data };
562
+ },
563
+ n: 0,
564
+ snapshotEvents(offset: number) {
565
+ return offset === 0 ? ['e1'] : [];
566
+ },
567
+ };
568
+ const wrapped = withEventCapture(base, { appendEvents: (events) => captured.push([...events]) }, () => {}) as typeof base;
569
+ const appended = wrapped.append('user/message', { text: 'hi' });
570
+ assert.deepEqual(captured[0]?.[0], { type: 'user/message', data: { text: 'hi' }, seq: 0 }, '事件镜像含 seq/type/data');
571
+ assert.equal(appended?.seq, 0, '返回值透传');
572
+ assert.equal(wrapped.snapshotEvents(0)[0], 'e1', '原型链方法透传');
573
+ assert.equal(wrapped.header.id, 's1');
574
+ });
575
+ });
576
+
577
+ // ---------------------------------------------------------------------------
578
+ // 最小 fake host(无 sessionPersistence / 无 loader / 无 storage)
579
+ // ---------------------------------------------------------------------------
580
+
581
+ function createFakeHostLite() {
582
+ const sessions = {
583
+ prepare(id: string) {
584
+ const session = { id, header: { id }, events: [] as unknown[], append(type: string, data: unknown) { session.events.push({ type, data }); } };
585
+ return { session, [Symbol.dispose]() {} };
586
+ },
587
+ enter() {
588
+ return () => {};
589
+ },
590
+ announce() {},
591
+ };
592
+ const agents = {
593
+ enter() {
594
+ return () => {};
595
+ },
596
+ async announce() {},
597
+ };
598
+ return { ctx: { sessions, agents, get: () => undefined } };
599
+ }