@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,221 @@
1
+ // test/f5-plan.test.ts —— F5 计划与验收(0.4.0 规划内容随 0.3.0 实施)
2
+ //
3
+ // 覆盖:
4
+ // - parser:tf-plan body 命令;accepts 公共属性在 tf-write/tf-bash 上合法
5
+ // - parsePlanItems:`- [id] 描述` 行解析、去重、忽略非验收行
6
+ // - 驱动器 E2E:tf-plan 全量注入一次 → accepts 回执差分 → 未验证验收项拦截过早 tf-final
7
+ // → 全部验证后收敛;请求里只注差分(后续请求不再重复全量计划)
8
+ // - enablePlan: false → tf-plan 结构化失败(回退点),tf-final 不做验收拦截
9
+ // - 自述不算证据:没有命令回执的验收项永远 open
10
+
11
+ import { describe, it } from 'node:test';
12
+ import assert from 'node:assert/strict';
13
+ import { mkdtempSync, rmSync } from 'node:fs';
14
+ import { tmpdir } from 'node:os';
15
+ import { join } from 'node:path';
16
+
17
+ import { SingleStreamDriver, normalizeStreamShim, parsePlanItems } from '../src/entry/loop.ts';
18
+ import type { DriverPorts, StreamRequestOptions, ToolBatchInputLike, ToolBatchResultLike, StreamDriverConfig } from '../src/entry/loop.ts';
19
+ import { TfStreamParser } from '../src/kernel/parser.ts';
20
+ import { createMockModel } from '../src/entry/mock-provider.ts';
21
+ import type { MockModel, Scenario } from '../src/entry/mock-provider.ts';
22
+
23
+ // ---------------------------------------------------------------------------
24
+ // 测试设施
25
+ // ---------------------------------------------------------------------------
26
+
27
+ function createSandboxExecutor(): (input: ToolBatchInputLike) => Promise<ToolBatchResultLike> {
28
+ return async (input) => ({
29
+ results: input.calls.map((c) => ({ callId: c.id, result: { content: [{ type: 'text', text: `${c.name}:ok` }], isError: false } })),
30
+ });
31
+ }
32
+
33
+ interface Harness {
34
+ driver: SingleStreamDriver;
35
+ wireRequests: Array<StreamRequestOptions & { contentTexts: string[] }>;
36
+ cleanup: () => void;
37
+ }
38
+
39
+ function makeHarness(opts: { task: string; scenarios: Scenario[]; config?: Partial<StreamDriverConfig> }): Harness {
40
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-f5-'));
41
+ const model = createMockModel({ scenarios: opts.scenarios, provider: 'mock' });
42
+ const wireRequests: Array<StreamRequestOptions & { contentTexts: string[] }> = [];
43
+ const ports: DriverPorts = {
44
+ stream: (options) => {
45
+ wireRequests.push({ ...options, contentTexts: options.messages.map((m) => m.content.map((b) => b.text ?? '').join('\n')) });
46
+ return normalizeStreamShim(model.adapter.stream({ provider: options.provider, model: options.model, messages: options.messages, signal: options.signal }));
47
+ },
48
+ executeTools: createSandboxExecutor(),
49
+ onToolSettled: () => model.notifyToolResult(),
50
+ };
51
+ const config: StreamDriverConfig = { provider: 'mock', model: 'mock-scenario', streamIdleTimeoutMs: 30_000, ...opts.config };
52
+ const driver = new SingleStreamDriver(ports, config);
53
+ driver.pushUserTask(opts.task);
54
+ return { driver, wireRequests, cleanup: () => rmSync(sandboxDir, { recursive: true, force: true }) };
55
+ }
56
+
57
+ function joinTexts(h: Harness): string {
58
+ return h.wireRequests.map((r) => r.contentTexts.join('\n')).join('\n=====\n');
59
+ }
60
+
61
+ // ---------------------------------------------------------------------------
62
+
63
+ describe('F5:parser 与计划解析', () => {
64
+ it('P1. tf-plan body 命令闭合即派发;accepts 属性在 tf-write / tf-bash 上合法', () => {
65
+ const parser = new TfStreamParser();
66
+ const events = parser.feed(
67
+ '<tf-plan id="p1">\n- [a1] 生成 intro.md\n- [a2] 生成 summary.md\n</tf-plan>'
68
+ + '<tf-write path="intro.md" id="w1" accepts="a1">x</tf-write>'
69
+ + '<tf-bash cmd="ls" id="b1" accepts="a2"/>',
70
+ );
71
+ const commands = events.filter((e): e is Extract<typeof e, { type: 'command' }> => e.type === 'command').map((e) => e.command);
72
+ assert.equal(commands.length, 3, '三个命令都应闭合');
73
+ assert.equal(commands[0]!.name, 'tf-plan');
74
+ assert.equal(commands[1]!.attrs['accepts'], 'a1');
75
+ assert.equal(commands[2]!.attrs['accepts'], 'a2');
76
+ });
77
+
78
+ it('P2. parsePlanItems:解析验收项行、去重、忽略普通文本行', () => {
79
+ const items = parsePlanItems('说明文字\n- [a1] 第一项\n* [a2] 第二项\n- [a1] 重复忽略\n没有标记的行\n- [a3_1] 带下划线的 id');
80
+ assert.deepEqual(items.map((i) => i.id), ['a1', 'a2', 'a3_1']);
81
+ assert.equal(items[0]!.text, '第一项');
82
+ });
83
+ });
84
+
85
+ describe('F5:驱动器 E2E', () => {
86
+ const planTask = '计划演练:两个文件。';
87
+
88
+ it('E1. 全量计划注入一次 → accepts 回执差分 → 未验证拦截过早 final → 验证后收敛', async () => {
89
+ const h = makeHarness({
90
+ task: planTask,
91
+ scenarios: [
92
+ {
93
+ name: 'f5-premature',
94
+ match: { promptIncludes: 'tf-final 过早' },
95
+ chunking: { charsPerChunk: 0, delayMs: 0 },
96
+ steps: [
97
+ { type: 'text', text: '补齐验收项。\n' },
98
+ { type: 'commands', commands: ['<tf-write path="summary.md" id="w2" accepts="a2">s</tf-write>', '<tf-final id="f2" summary="a1: intro.md;a2: summary.md"/>'] },
99
+ { type: 'waitTools', count: 1, timeoutMs: 5000 },
100
+ { type: 'finish', reason: 'stop' },
101
+ ],
102
+ },
103
+ {
104
+ name: 'f5-first',
105
+ match: { promptIncludes: '计划演练' },
106
+ chunking: { charsPerChunk: 0, delayMs: 0 },
107
+ steps: [
108
+ { type: 'text', text: '声明计划并完成第一项。\n' },
109
+ { type: 'commands', commands: [
110
+ '<tf-plan id="p1">\n- [a1] 生成 intro.md\n- [a2] 生成 summary.md\n</tf-plan>',
111
+ '<tf-write path="intro.md" id="w1" accepts="a1">i</tf-write>',
112
+ '<tf-final id="f1" summary="占位"/>',
113
+ ] },
114
+ { type: 'waitTools', count: 1, timeoutMs: 5000 },
115
+ { type: 'finish', reason: 'stop' },
116
+ ],
117
+ },
118
+ ],
119
+ });
120
+ try {
121
+ const reason = await h.driver.runTurn();
122
+ assert.equal(reason.kind, 'completed', `应收敛:${JSON.stringify(reason)}`);
123
+
124
+ // 请求 2:全量计划一次(带 a1 已验证状态)+ 过早 final 拦截
125
+ const req2 = h.wireRequests[1]!.contentTexts.join('\n');
126
+ assert.ok(req2.includes('[tf-stream:plan v1]'), '请求 2 应注入全量计划');
127
+ assert.ok(req2.includes('- [a1] 生成 intro.md'), '计划清单应含验收项');
128
+ assert.ok(req2.includes('✓ 已验证(回执:w1'), 'a1 的验证状态与回执应在全量清单中');
129
+ assert.ok(req2.includes('[a2] 生成 summary.md(未验证)'), 'a2 应标未验证');
130
+ assert.ok(req2.includes('tf-final 过早'), '未验证的 a2 应拦截过早 final');
131
+
132
+ // 任务收敛后不再有请求 3;即使有,也不重复全量计划
133
+ const req3 = h.wireRequests[2]?.contentTexts.join('\n') ?? '';
134
+ assert.ok(!req3.includes('[tf-stream:plan v1]'), `请求 3 不得重复全量计划:${req3.slice(0, 400)}`);
135
+
136
+ // 台账:plan 与 plan-accept 各有记录
137
+ const records = h.driver.snapshot().records;
138
+ assert.ok(records.some((r) => r.kind === 'plan' && r.kind === 'plan' && r.total === 2), '应有 plan 记录');
139
+ assert.ok(records.some((r) => r.kind === 'plan-accept' && r.acceptId === 'a1'), 'a1 应有验证记录');
140
+ } finally {
141
+ h.cleanup();
142
+ }
143
+ });
144
+
145
+ it('E2. 自述不算证据:没有命令回执的验收项保持 open,final 一直被拦截', async () => {
146
+ const h = makeHarness({
147
+ task: planTask,
148
+ scenarios: [
149
+ {
150
+ name: 'f5-claim',
151
+ match: { promptIncludes: 'tf-final 过早' },
152
+ chunking: { charsPerChunk: 0, delayMs: 0 },
153
+ steps: [
154
+ { type: 'text', text: '我声称完成了。\n' },
155
+ { type: 'commands', commands: ['<tf-final id="f9" summary="全部完成(自述)"/>'] },
156
+ { type: 'finish', reason: 'stop' },
157
+ ],
158
+ },
159
+ {
160
+ name: 'f5-first',
161
+ match: { promptIncludes: '计划演练' },
162
+ chunking: { charsPerChunk: 0, delayMs: 0 },
163
+ steps: [
164
+ { type: 'text', text: '声明计划,不执行任何命令。\n' },
165
+ { type: 'commands', commands: ['<tf-plan id="p1">\n- [a1] 生成 intro.md\n</tf-plan>', '<tf-final id="f1" summary="占位"/>'] },
166
+ { type: 'finish', reason: 'stop' },
167
+ ],
168
+ },
169
+ ],
170
+ config: { maxReentries: 2 },
171
+ });
172
+ try {
173
+ const reason = await h.driver.runTurn();
174
+ // 无回执 → 验收项永远 open → 回合以 blocked(重入上限)结束,绝不 completed
175
+ assert.equal(reason.kind, 'blocked', `自述不得通过验收:${JSON.stringify(reason)}`);
176
+ const text = joinTexts(h);
177
+ assert.ok(!text.includes('✓ [a1]'), '无命令回执不得产生验证差分');
178
+ } finally {
179
+ h.cleanup();
180
+ }
181
+ });
182
+
183
+ it('E3. enablePlan: false → tf-plan 结构化失败(回退点),tf-final 不做验收拦截', async () => {
184
+ const h = makeHarness({
185
+ task: planTask,
186
+ scenarios: [
187
+ {
188
+ name: 'f5-off',
189
+ match: { promptIncludes: 'plan-disabled' },
190
+ chunking: { charsPerChunk: 0, delayMs: 0 },
191
+ steps: [
192
+ { type: 'text', text: '计划关闭,直接收尾。\n' },
193
+ { type: 'commands', commands: ['<tf-final id="f2" summary="done"/>'] },
194
+ { type: 'finish', reason: 'stop' },
195
+ ],
196
+ },
197
+ {
198
+ name: 'f5-first',
199
+ match: { promptIncludes: '计划演练' },
200
+ chunking: { charsPerChunk: 0, delayMs: 0 },
201
+ steps: [
202
+ { type: 'text', text: '尝试声明计划。\n' },
203
+ { type: 'commands', commands: ['<tf-plan id="p1">\n- [a1] 生成 intro.md\n</tf-plan>'] },
204
+ { type: 'waitTools', count: 1, timeoutMs: 5000 },
205
+ { type: 'finish', reason: 'stop' },
206
+ ],
207
+ },
208
+ ],
209
+ config: { enablePlan: false },
210
+ });
211
+ try {
212
+ const reason = await h.driver.runTurn();
213
+ assert.equal(reason.kind, 'completed');
214
+ const req2 = h.wireRequests[1]!.contentTexts.join('\n');
215
+ assert.ok(req2.includes('plan-disabled'), 'tf-plan 应结构化失败');
216
+ assert.ok(!req2.includes('[tf-stream:plan'), '关闭时不得注入任何计划块');
217
+ } finally {
218
+ h.cleanup();
219
+ }
220
+ });
221
+ });
@@ -0,0 +1,168 @@
1
+ // test/f6-intent.test.ts —— F6 恢复意图(0.4.0 规划内容随 0.3.0 实施)
2
+ //
3
+ // 覆盖:
4
+ // - intent-log 单元:fsync 追加 / 读取(坏行如实计数)/ 三态判定(未发生/已发生/不确定)
5
+ // - 驱动器 E2E:写前意图在派发前落盘、写后回执闭合;零注入(意图不进任何请求)
6
+ // - resume 停机核对:有意图无回执 → runTurn 直接 blocked 且不发任何请求
7
+ // - 失败写入也闭合意图(不算"无回执")
8
+
9
+ import { describe, it } from 'node:test';
10
+ import assert from 'node:assert/strict';
11
+ import { mkdtempSync, existsSync, readFileSync, rmSync, appendFileSync } from 'node:fs';
12
+ import { tmpdir } from 'node:os';
13
+ import { join } from 'node:path';
14
+
15
+ import { SingleStreamDriver, normalizeStreamShim } from '../src/entry/loop.ts';
16
+ import type { DriverPorts, StreamRequestOptions, ToolBatchInputLike, ToolBatchResultLike, StreamDriverConfig } from '../src/entry/loop.ts';
17
+ import {
18
+ appendIntentRecord,
19
+ intentFingerprint,
20
+ loadIntentRecords,
21
+ pendingIntents,
22
+ } from '../src/entry/intent-log.ts';
23
+ import type { IntentLogRecord } from '../src/entry/intent-log.ts';
24
+ import { createMockModel } from '../src/entry/mock-provider.ts';
25
+ import type { Scenario } from '../src/entry/mock-provider.ts';
26
+
27
+ // ---------------------------------------------------------------------------
28
+
29
+ describe('F6:intent-log 单元', () => {
30
+ it('I1. fsync 追加 + 读取 + 坏行如实计数', () => {
31
+ const dir = mkdtempSync(join(tmpdir(), 'tf-f6-'));
32
+ try {
33
+ const file = join(dir, 's1.jsonl');
34
+ appendIntentRecord(file, { type: 'intent', seq: 1, at: 't', sessionId: 's1', cmdId: 'w1', op: 'write', path: 'a.txt', fingerprint: 'f1' });
35
+ appendIntentRecord(file, { type: 'receipt', seq: 2, at: 't', intentSeq: 1, ok: true, detail: '10 chars' });
36
+ appendIntentRecord(file, { type: 'ack', seq: 3, at: 't', intentSeqs: [] });
37
+ // 模拟崩溃截断的最后一行
38
+ appendFileSync(file, '{"type":"intent","seq":4,"at":"trunc', 'utf8');
39
+ const { records, badLines } = loadIntentRecords(file);
40
+ assert.equal(records.length, 3);
41
+ assert.equal(badLines, 1);
42
+ } finally {
43
+ rmSync(dir, { recursive: true, force: true });
44
+ }
45
+ });
46
+
47
+ it('I2. 三态判定:有回执=已发生;无回执=不确定(pending);失败回执=已发生但失败;ack 闭合', () => {
48
+ const records: IntentLogRecord[] = [
49
+ { type: 'intent', seq: 1, at: 't', sessionId: 's', cmdId: 'w1', op: 'write', path: 'ok.txt', fingerprint: 'f' },
50
+ { type: 'receipt', seq: 2, at: 't', intentSeq: 1, ok: true },
51
+ { type: 'intent', seq: 3, at: 't', sessionId: 's', cmdId: 'w2', op: 'edit', path: 'hang.txt', fingerprint: 'f' },
52
+ { type: 'intent', seq: 4, at: 't', sessionId: 's', cmdId: 'w3', op: 'append', path: 'fail.txt', fingerprint: 'f' },
53
+ { type: 'receipt', seq: 5, at: 't', intentSeq: 4, ok: false, detail: 'EFAIL' },
54
+ { type: 'intent', seq: 6, at: 't', sessionId: 's', cmdId: 'w4', op: 'write', path: 'acked.txt', fingerprint: 'f' },
55
+ { type: 'ack', seq: 7, at: 't', intentSeqs: [6], note: '人工确认未写入' },
56
+ ];
57
+ const pending = pendingIntents(records);
58
+ // w2 = 不确定(pending,停机核对对象);w3 = 已发生但失败(failed,列出供参考不阻断)
59
+ assert.deepEqual(pending.map((p) => `${p.intent.cmdId}:${p.state}`), ['w2:pending', 'w3:failed']);
60
+ assert.deepEqual(pending.filter((p) => p.state === 'pending').map((p) => p.intent.cmdId), ['w2'], '停机核对只针对"有意图无回执"');
61
+ assert.ok(!pending.some((p) => p.intent.cmdId === 'w1'), '已成功的写入不是核对对象');
62
+ assert.ok(!pending.some((p) => p.intent.cmdId === 'w4'), 'ack 闭合的意图不是核对对象');
63
+ });
64
+
65
+ it('I3. intentFingerprint:确定性、16 位、内容不同指纹不同', () => {
66
+ assert.equal(intentFingerprint('abc'), intentFingerprint('abc'));
67
+ assert.equal(intentFingerprint('abc').length, 16);
68
+ assert.notEqual(intentFingerprint('abc'), intentFingerprint('abd'));
69
+ });
70
+ });
71
+
72
+ // ---------------------------------------------------------------------------
73
+ // 驱动器 E2E
74
+ // ---------------------------------------------------------------------------
75
+
76
+ interface F6Harness {
77
+ driver: SingleStreamDriver;
78
+ wireRequests: Array<StreamRequestOptions & { contentTexts: string[] }>;
79
+ intents: Array<{ cmdId: string; op: string; path: string; fingerprint: string }>;
80
+ receipts: Array<{ cmdId: string; ok: boolean; detail?: string }>;
81
+ cleanup: () => void;
82
+ }
83
+
84
+ function makeF6Harness(opts: { task: string; scenarios: Scenario[]; config?: Partial<StreamDriverConfig> }): F6Harness {
85
+ const dir = mkdtempSync(join(tmpdir(), 'tf-f6e2e-'));
86
+ const model = createMockModel({ scenarios: opts.scenarios, provider: 'mock' });
87
+ const wireRequests: Array<StreamRequestOptions & { contentTexts: string[] }> = [];
88
+ const intents: F6Harness['intents'] = [];
89
+ const receipts: F6Harness['receipts'] = [];
90
+ const ports: DriverPorts = {
91
+ stream: (options) => {
92
+ wireRequests.push({ ...options, contentTexts: options.messages.map((m) => m.content.map((b) => b.text ?? '').join('\n')) });
93
+ return normalizeStreamShim(model.adapter.stream({ provider: options.provider, model: options.model, messages: options.messages, signal: options.signal }));
94
+ },
95
+ executeTools: async (input: ToolBatchInputLike): Promise<ToolBatchResultLike> => ({
96
+ results: input.calls.map((c) => ({ callId: c.id, result: { content: [{ type: 'text', text: `${c.name}:ok` }], isError: false } })),
97
+ }),
98
+ onIntent: (intent) => intents.push({ ...intent }),
99
+ onIntentReceipt: (receipt) => receipts.push({ ...receipt }),
100
+ onToolSettled: () => model.notifyToolResult(),
101
+ };
102
+ const config: StreamDriverConfig = { provider: 'mock', model: 'mock-scenario', streamIdleTimeoutMs: 30_000, ...opts.config };
103
+ const driver = new SingleStreamDriver(ports, config);
104
+ driver.pushUserTask(opts.task);
105
+ return { driver, wireRequests, intents, receipts, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
106
+ }
107
+
108
+ describe('F6:驱动器 E2E', () => {
109
+ it('E1. 写前意图先于执行、写后回执闭合;意图零注入(不进任何请求)', async () => {
110
+ const h = makeF6Harness({
111
+ task: '意图演练:写两个文件。',
112
+ scenarios: [
113
+ {
114
+ name: 'f6-write',
115
+ match: { promptIncludes: '意图演练' },
116
+ chunking: { charsPerChunk: 0, delayMs: 0 },
117
+ steps: [
118
+ { type: 'text', text: '写文件。\n' },
119
+ { type: 'commands', commands: ['<tf-write path="a.txt" id="w1">A</tf-write>', '<tf-edit path="a.txt" id="e1">\n<<<<<<< OLD\nA\n=======\nB\n>>>>>>> NEW\n</tf-edit>', '<tf-append path="a.txt" id="a1">C</tf-append>', '<tf-read path="a.txt" id="r1"/>', '<tf-final id="f1" summary="done"/>'] },
120
+ { type: 'waitTools', count: 3, timeoutMs: 5000 },
121
+ { type: 'finish', reason: 'stop' },
122
+ ],
123
+ },
124
+ ],
125
+ });
126
+ try {
127
+ const reason = await h.driver.runTurn();
128
+ assert.equal(reason.kind, 'completed');
129
+ // 三个变更类命令各有一条写前意图 + 一条回执;tf-read 不产生意图
130
+ assert.deepEqual(h.intents.map((i) => `${i.cmdId}:${i.op}`), ['w1:write', 'e1:edit', 'a1:append']);
131
+ assert.deepEqual(h.receipts.map((r) => `${r.cmdId}:${r.ok}`), ['w1:true', 'e1:true', 'a1:true']);
132
+ // 写前意图的指纹 = 命令正文指纹(对账用)
133
+ const w1 = h.intents[0]!;
134
+ assert.equal(w1.fingerprint, intentFingerprint('A'));
135
+ // 零注入:全部请求文本里不出现意图日志的字段形态
136
+ const allText = h.wireRequests.map((r) => r.contentTexts.join('\n')).join('\n');
137
+ assert.ok(!allText.includes('"type":"intent"'), '意图记录不得进入模型上下文');
138
+ assert.ok(!allText.includes('intentFingerprint') && !allText.includes('写前意图'), '意图语义不得注入');
139
+ } finally {
140
+ h.cleanup();
141
+ }
142
+ });
143
+
144
+ it('E2. resume 停机核对:有意图无回执 → runTurn blocked 且不发任何请求(零注入)', async () => {
145
+ const h = makeF6Harness({
146
+ task: '任何任务。',
147
+ scenarios: [{
148
+ name: 'f6-halt-never-used',
149
+ match: { promptIncludes: '任何任务' },
150
+ chunking: { charsPerChunk: 0, delayMs: 0 },
151
+ steps: [{ type: 'text', text: '不该到达。\n' }, { type: 'finish', reason: 'stop' }],
152
+ }],
153
+ config: {},
154
+ });
155
+ try {
156
+ h.driver.setResumeHalt('1 条写前意图无回执(write a.txt)');
157
+ const reason = await h.driver.runTurn();
158
+ assert.equal(reason.kind, 'blocked');
159
+ assert.ok(reason.kind === 'blocked' && reason.detail!.includes('resume 停机核对'), 'blocked 详情应指明停机核对');
160
+ assert.equal(h.wireRequests.length, 0, '停机核对不得发出任何请求');
161
+ // 清除后可正常运行
162
+ h.driver.clearResumeHalt();
163
+ assert.ok(h.driver !== undefined);
164
+ } finally {
165
+ h.cleanup();
166
+ }
167
+ });
168
+ });
@@ -0,0 +1,190 @@
1
+ // test/f7-segment.test.ts —— F7 长会话段边界(0.4.0 规划内容随 0.3.0 实施;ADR-001)
2
+ //
3
+ // 覆盖:
4
+ // - renderer 单元:dropAppendHead 整块丢弃、policyLog 记录、前缀基线重置后 preflight 不误报
5
+ // - 驱动器 E2E:长会话多回合 + 段丢弃——100+ 请求 0 前缀违规(PrefixBrokenError 不外泄)
6
+ // - 块完整性:丢弃只落在回合边界,当前回合块保留;被丢弃原文句柄化可 tf-peek 回取
7
+ // - 末/首请求体积断言:边界后首请求 ≤ 阈值 + 当前任务(≤1.5× 首请求口径的落地)
8
+
9
+ import { describe, it } from 'node:test';
10
+ import assert from 'node:assert/strict';
11
+ import { mkdtempSync, rmSync } from 'node:fs';
12
+ import { tmpdir } from 'node:os';
13
+ import { join } from 'node:path';
14
+
15
+ import { SingleStreamDriver, normalizeStreamShim } from '../src/entry/loop.ts';
16
+ import type { DriverPorts, StreamRequestOptions, ToolBatchInputLike, ToolBatchResultLike, StreamDriverConfig } from '../src/entry/loop.ts';
17
+ import { ContextRenderer, PrefixBrokenError } from '../src/kernel/render.ts';
18
+ import { createMockModel } from '../src/entry/mock-provider.ts';
19
+ import type { Scenario } from '../src/entry/mock-provider.ts';
20
+
21
+ // ---------------------------------------------------------------------------
22
+ // renderer 单元
23
+ // ---------------------------------------------------------------------------
24
+
25
+ describe('F7:renderer 段边界单元', () => {
26
+ it('R1. dropAppendHead:整块丢弃 + policyLog 记录 + 前缀基线重置', () => {
27
+ const r = new ContextRenderer({ system: 'S', protocol: 'P', toolSchemas: 'T', invariants: 'I' });
28
+ r.appendHistory({ role: 'user', content: 'task1' });
29
+ r.appendHistory({ role: 'assistant', content: 'a1' });
30
+ r.appendHistory({ role: 'user', content: 'task2' });
31
+ r.appendHistory({ role: 'assistant', content: 'a2' });
32
+ assert.equal(r.appendBlockCount, 4);
33
+ assert.ok(r.appendChars > 0);
34
+ r.render(); // 建立前缀基线
35
+ const { dropped, record } = r.dropAppendHead(2, { reason: 'test' });
36
+ assert.deepEqual(dropped, ['task1', 'a1'], '丢弃的必须是完整整块');
37
+ assert.equal(record.kind, 'segment-drop');
38
+ assert.equal(record.accepted, true);
39
+ assert.equal(r.policyLog.length, 1);
40
+ assert.equal(r.appendBlockCount, 2);
41
+ // 前缀基线已重置:下一请求与旧基线不同,但 preflight 不得误报
42
+ let threw = false;
43
+ try {
44
+ r.render();
45
+ } catch (error) {
46
+ threw = error instanceof PrefixBrokenError;
47
+ }
48
+ assert.ok(!threw, '显式段边界后 render() 不得抛前缀违规');
49
+ // 之后继续追加照常单调
50
+ r.appendHistory({ role: 'user', content: 'task3' });
51
+ r.render();
52
+ r.render();
53
+ });
54
+
55
+ it('R2. 越界丢弃收敛到块数;0 块丢弃不记录', () => {
56
+ const r = new ContextRenderer({ system: 'S', protocol: 'P', toolSchemas: 'T', invariants: 'I' });
57
+ r.appendHistory({ role: 'user', content: 'x' });
58
+ const { dropped, record } = r.dropAppendHead(99, { reason: 'over' });
59
+ assert.equal(dropped.length, 1);
60
+ assert.equal(record.droppedBlocks, 1);
61
+ const empty = r.dropAppendHead(5, { reason: 'none' });
62
+ assert.equal(empty.dropped.length, 0);
63
+ assert.equal(r.policyLog.length, 2, '0 块丢弃也如实记录(不静默)');
64
+ });
65
+ });
66
+
67
+ // ---------------------------------------------------------------------------
68
+ // 驱动器 E2E:长会话多回合 + 段丢弃
69
+ // ---------------------------------------------------------------------------
70
+
71
+ interface F7Harness {
72
+ driver: SingleStreamDriver;
73
+ wireRequests: Array<StreamRequestOptions & { contentTexts: string[] }>;
74
+ cleanup: () => void;
75
+ }
76
+
77
+ function makeF7Harness(opts: { config?: Partial<StreamDriverConfig> }): F7Harness {
78
+ const dir = mkdtempSync(join(tmpdir(), 'tf-f7-'));
79
+ const TURNS = 50;
80
+ const scenarios: Scenario[] = [];
81
+ for (let n = 1; n <= TURNS; n++) {
82
+ // 回合第 2 请求:premature-final 拦截块含 `未验证(a<n>)`(每回合唯一)——
83
+ // 完成验收项后收尾。顺序敏感:close 排在 turn 之前。
84
+ scenarios.push({
85
+ name: `f7-close${n}`,
86
+ match: { model: `mock-turn${n}`, promptIncludes: `未验证(a${n})` },
87
+ chunking: { charsPerChunk: 0, delayMs: 0 },
88
+ steps: [
89
+ { type: 'text', text: `turn${n} 验收回执。\n` },
90
+ { type: 'commands', commands: [`<tf-write path="t${n}.txt" id="w${n}b" accepts="a${n}">payload-${'x'.repeat(120)}-${n}</tf-write>`, `<tf-final id="f${n}b" summary="turn${n} done"/>`] },
91
+ { type: 'waitTools', count: 1, timeoutMs: 5000 },
92
+ { type: 'finish', reason: 'stop' },
93
+ ],
94
+ });
95
+ // 回合第 1 请求:声明计划 + 写文件 + 收尾(验收项未验证 → F5 拦截 → 第二请求)
96
+ scenarios.push({
97
+ name: `f7-turn${n}`,
98
+ match: { model: `mock-turn${n}` },
99
+ chunking: { charsPerChunk: 0, delayMs: 0 },
100
+ steps: [
101
+ { type: 'text', text: `turn${n} 开工。\n` },
102
+ { type: 'commands', commands: [
103
+ `<tf-plan id="p${n}">\n- [a${n}] 写出 t${n}.txt\n</tf-plan>`,
104
+ `<tf-write path="t${n}.txt" id="w${n}a">partial-${'x'.repeat(100)}-${n}</tf-write>`,
105
+ `<tf-final id="f${n}a" summary="占位(会被 F5 拦截)"/>`,
106
+ ] },
107
+ { type: 'waitTools', count: 1, timeoutMs: 5000 },
108
+ { type: 'finish', reason: 'stop' },
109
+ ],
110
+ });
111
+ }
112
+ const model = createMockModel({ scenarios, provider: 'mock' });
113
+ const wireRequests: Array<StreamRequestOptions & { contentTexts: string[] }> = [];
114
+ const ports: DriverPorts = {
115
+ stream: (options) => {
116
+ wireRequests.push({ ...options, contentTexts: options.messages.map((m) => m.content.map((b) => b.text ?? '').join('\n')) });
117
+ return normalizeStreamShim(model.adapter.stream({ provider: options.provider, model: options.model, messages: options.messages, signal: options.signal }));
118
+ },
119
+ executeTools: async (input: ToolBatchInputLike): Promise<ToolBatchResultLike> => ({
120
+ results: input.calls.map((c) => ({ callId: c.id, result: { content: [{ type: 'text', text: `${c.name}:ok` }], isError: false } })),
121
+ }),
122
+ onToolSettled: () => model.notifyToolResult(),
123
+ };
124
+ const config: StreamDriverConfig = { provider: 'mock', model: 'mock-scenario', streamIdleTimeoutMs: 30_000, ...opts.config };
125
+ const driver = new SingleStreamDriver(ports, config);
126
+ return { driver, wireRequests, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
127
+ }
128
+
129
+ describe('F7:驱动器 E2E(长会话 100+ 请求 0 前缀违规)', () => {
130
+ it('E1. 50 回合 × 2 请求长会话触发段丢弃:0 前缀违规、块完整、原文可回取、体积有界', async () => {
131
+ const h = makeF7Harness({ config: { segmentMaxChars: 1200 } });
132
+ try {
133
+ let totalRequests = 0;
134
+ let dropsSeen = 0;
135
+ let prefixViolations = 0;
136
+ const firstReqChars = [];
137
+ for (let n = 1; n <= 50; n++) {
138
+ // 按模型路由区分回合(历史任务文本会持久存在,不能作为剧本匹配标记)
139
+ h.driver.applySelection({ model: `mock-turn${n}` });
140
+ h.driver.pushUserTask(`turn${n} 任务:写 t${n}.txt。`);
141
+ const before = h.wireRequests.length;
142
+ const reason = await h.driver.runTurn();
143
+ assert.equal(reason.kind, 'completed', `turn${n} 应收敛:${JSON.stringify(reason)}`);
144
+ totalRequests += h.wireRequests.length - before;
145
+ firstReqChars.push(h.wireRequests[before]!.contentTexts[0]!.length);
146
+ const records = h.driver.snapshot().records;
147
+ dropsSeen = records.filter((r) => r.kind === 'fault' && r.fault === 'segment-drop').length;
148
+ prefixViolations = records.filter((r) => r.kind === 'fault' && r.fault === 'driver-error').length;
149
+ assert.equal(prefixViolations, 0, `turn${n} 后 0 次 driver-error(前缀违规会以 driver-error 呈现)`);
150
+ }
151
+ // 100 请求(50 回合 × 2):0 前缀违规
152
+ assert.ok(totalRequests >= 100, `长会话请求数应 ≥100,实际 ${totalRequests}`);
153
+ assert.equal(prefixViolations, 0, '0 次 driver-error');
154
+ assert.ok(dropsSeen >= 3, `小阈值下应多次段丢弃,实际 ${dropsSeen}`);
155
+
156
+ // 块完整性与回取:最后一次丢弃的旧段原文可按句柄取回(不摘要改写)
157
+ const records = h.driver.snapshot().records;
158
+ const segDrop = [...records].reverse().find((r) => r.kind === 'fault' && r.fault === 'segment-drop');
159
+ assert.ok(segDrop !== undefined);
160
+ const handle = segDrop.detail!.match(/obs:read:seg-t(\d+)-0@v1/);
161
+ if (handle !== null) {
162
+ const retrieved = h.driver.peekHandle(`obs:read:seg-t${handle[1]}-0@v1`);
163
+ assert.ok(retrieved !== null && retrieved.includes('turn'), `被丢弃旧段原文应可回取:${String(retrieved).slice(0, 80)}`);
164
+ }
165
+
166
+ // 体积有界:末段请求的 system 体积 ≤ 1.5 × 首回合请求 system 体积(末/首 ≤1.5× 的落地)
167
+ const first = firstReqChars[0]!;
168
+ const last = firstReqChars[firstReqChars.length - 1]!;
169
+ assert.ok(last <= Math.ceil(first * 1.5) + 200, `边界后首请求体积应 ≤1.5×(first=${first} last=${last})`);
170
+ } finally {
171
+ h.cleanup();
172
+ }
173
+ });
174
+
175
+ it('E2. segmentMaxChars=0 关闭段边界(回退点):长会话不丢弃', async () => {
176
+ const h = makeF7Harness({ config: { segmentMaxChars: 0 } });
177
+ try {
178
+ for (let n = 1; n <= 3; n++) {
179
+ h.driver.applySelection({ model: `mock-turn${n}` });
180
+ h.driver.pushUserTask(`turn${n} 任务:写 t${n}.txt。`);
181
+ const reason = await h.driver.runTurn();
182
+ assert.equal(reason.kind, 'completed');
183
+ }
184
+ const records = h.driver.snapshot().records;
185
+ assert.equal(records.filter((r) => r.kind === 'fault' && r.fault === 'segment-drop').length, 0, '关闭时不得丢弃');
186
+ } finally {
187
+ h.cleanup();
188
+ }
189
+ });
190
+ });