@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,380 @@
1
+ /**
2
+ * gate.ts 单测:装配期失败 / 两段式凭据全失效路径 / fatal 批准通道 / spec 零副作用。
3
+ * 全部离线:StagingSink 用内存 mock,时钟注入,不碰网络不碰 fs。
4
+ */
5
+
6
+ import test from 'node:test';
7
+ import assert from 'node:assert/strict';
8
+ import { createHash } from 'node:crypto';
9
+
10
+ import {
11
+ ActionRegistry,
12
+ ActionGate,
13
+ MissingReversibilityError,
14
+ UnknownActionError,
15
+ RegistryFrozenError,
16
+ RegistryNotFrozenError,
17
+ NotSpecActionError,
18
+ StagingLeakError,
19
+ SystemClock,
20
+ type StagingSink,
21
+ type StagedWriteReceipt,
22
+ type ApprovalChannel,
23
+ type GateClock,
24
+ type SpecRequest,
25
+ type CommitCredential,
26
+ type SpecResult,
27
+ } from '../src/kernel/gate.ts';
28
+
29
+ /** 收窄 SpecResult 的辅助(避免测试里散布 as 链)。 */
30
+ function expectAllow(result: SpecResult): {
31
+ diff: string;
32
+ specHash: string;
33
+ credential: CommitCredential;
34
+ } {
35
+ assert.equal(result.verdict, 'allow');
36
+ return result as {
37
+ diff: string;
38
+ specHash: string;
39
+ credential: CommitCredential;
40
+ };
41
+ }
42
+
43
+ function sha(text: string): string {
44
+ return createHash('sha256').update(text, 'utf8').digest('hex');
45
+ }
46
+
47
+ /** 内存 StagingSink mock:工作区只被测试显式改写,sink 自身无任何触达工作区的路径。 */
48
+ class MockStagingSink implements StagingSink {
49
+ readonly stagedWrites: Array<{ path: string; content: string }> = [];
50
+ /** 模拟真实工作区(path → content)。测试用 setWorkspace 显式变更以触发 hash_mismatch。 */
51
+ readonly workspace = new Map<string, string>();
52
+
53
+ setWorkspace(path: string, content: string): void {
54
+ this.workspace.set(path, content);
55
+ }
56
+
57
+ writeStaged(path: string, content: string): StagedWriteReceipt {
58
+ this.stagedWrites.push({ path, content });
59
+ return { path, hash: sha(content) };
60
+ }
61
+
62
+ diffStaged(): string {
63
+ if (this.stagedWrites.length === 0) return '';
64
+ return this.stagedWrites
65
+ .map((w) => `--- a/${w.path}\n+++ b/${w.path}\n@@\n+${w.content}`)
66
+ .join('\n');
67
+ }
68
+
69
+ workspaceHash(path: string): string {
70
+ return sha(this.workspace.get(path) ?? '');
71
+ }
72
+ }
73
+
74
+ class FakeClock implements GateClock {
75
+ t: number;
76
+ constructor(t: number = 1_000) {
77
+ this.t = t;
78
+ }
79
+ now(): number {
80
+ return this.t;
81
+ }
82
+ advance(ms: number): void {
83
+ this.t += ms;
84
+ }
85
+ }
86
+
87
+ function frozenRegistry(): ActionRegistry {
88
+ const reg = new ActionRegistry();
89
+ reg.declare({ name: 'tf-read', reversibility: 'read' });
90
+ reg.declare({ name: 'tf-write', reversibility: 'spec' });
91
+ reg.declare({ name: 'tf-write-commit', reversibility: 'commit' });
92
+ reg.declare({ name: 'tf-rm-rf', reversibility: 'fatal' });
93
+ reg.freeze();
94
+ return reg;
95
+ }
96
+
97
+ function makeGate(opts?: {
98
+ clock?: GateClock;
99
+ approval?: ApprovalChannel;
100
+ ttl?: number;
101
+ sink?: MockStagingSink;
102
+ registry?: ActionRegistry;
103
+ }): { gate: ActionGate; sink: MockStagingSink; clock: FakeClock } {
104
+ const sink = opts?.sink ?? new MockStagingSink();
105
+ const clock = (opts?.clock as FakeClock) ?? new FakeClock();
106
+ const gate = new ActionGate({
107
+ registry: opts?.registry ?? frozenRegistry(),
108
+ staging: sink,
109
+ clock,
110
+ ...(opts?.ttl !== undefined ? { credentialTtlMs: opts.ttl } : {}),
111
+ ...(opts?.approval ? { approval: opts.approval } : {}),
112
+ });
113
+ return { gate, sink, clock };
114
+ }
115
+
116
+ const specReq = (writes: Array<{ path: string; content: string }>): SpecRequest => ({
117
+ action: 'tf-write',
118
+ taskId: 'task-1',
119
+ writes,
120
+ });
121
+
122
+ // ---------------------------------------------------------------------------
123
+ // 装配期:缺 reversibility 声明 → freeze() 抛错
124
+ // ---------------------------------------------------------------------------
125
+
126
+ test('registry:缺 reversibility 声明在 freeze() 抛 MissingReversibilityError(启动期失败)', () => {
127
+ const reg = new ActionRegistry();
128
+ reg.declare({ name: 'tf-read', reversibility: 'read' });
129
+ reg.declare({ name: 'tf-write' }); // 缺声明
130
+ reg.declare({ name: 'tf-bash' }); // 缺声明
131
+ reg.declare({ name: 'tf-final', reversibility: 'commit' });
132
+ assert.throws(
133
+ () => reg.freeze(),
134
+ (err: unknown) => {
135
+ assert.ok(err instanceof MissingReversibilityError);
136
+ // 报错列出全部缺失项,而不是只报第一个
137
+ assert.deepEqual(err.actions.sort(), ['tf-bash', 'tf-write']);
138
+ assert.match(err.message, /tf-write/);
139
+ return true;
140
+ },
141
+ );
142
+ // 冻结失败后 registry 保持不可用(装配期失败要趁早暴露)
143
+ assert.equal(reg.frozen, false);
144
+ assert.throws(() => reg.reversibilityOf('tf-read'), RegistryNotFrozenError);
145
+ });
146
+
147
+ test('registry:补齐声明后 freeze() 成功;重名/冻结后 declare 抛错;未注册 action 抛 UnknownActionError', () => {
148
+ const reg = new ActionRegistry();
149
+ reg.declare({ name: 'tf-write', reversibility: 'spec' });
150
+ assert.throws(() => reg.declare({ name: 'tf-write', reversibility: 'read' }), /重复注册/);
151
+ reg.declare({ name: 'tf-read', reversibility: 'read' });
152
+ reg.freeze();
153
+ assert.equal(reg.frozen, true);
154
+ assert.equal(reg.reversibilityOf('tf-read'), 'read');
155
+ assert.throws(() => reg.declare({ name: 'another', reversibility: 'read' }), RegistryFrozenError);
156
+ assert.throws(() => reg.reversibilityOf('nope'), UnknownActionError);
157
+ });
158
+
159
+ // ---------------------------------------------------------------------------
160
+ // admit:read / fatal / commit-spec 分流
161
+ // ---------------------------------------------------------------------------
162
+
163
+ test('admit:read 级直接放行', async () => {
164
+ const { gate } = makeGate();
165
+ const result = await gate.admit({ action: 'tf-read', taskId: 't' });
166
+ assert.deepEqual(result, { verdict: 'allow', reversibility: 'read' });
167
+ });
168
+
169
+ test('admit:fatal 级无批准通道 → 结构化拒绝,理由可读', async () => {
170
+ const { gate } = makeGate();
171
+ const result = await gate.admit({ action: 'tf-rm-rf', taskId: 't' });
172
+ assert.equal(result.verdict, 'deny');
173
+ assert.ok(result.verdict === 'deny');
174
+ assert.equal((result as { reason: string }).reason, 'fatal-no-approval-channel');
175
+ assert.match((result as { detail: string }).detail, /不可逆/);
176
+ assert.match((result as { detail: string }).detail, /批准通道/);
177
+ });
178
+
179
+ test('admit:fatal 级有批准通道 → 交给通道裁决(同意放行 / 拒绝拒绝)', async () => {
180
+ const approving: ApprovalChannel = { requestApproval: () => true };
181
+ const denying: ApprovalChannel = { requestApproval: () => false };
182
+ const { gate: g1 } = makeGate({ approval: approving });
183
+ const { gate: g2 } = makeGate({ approval: denying });
184
+ const ok = await g1.admit({ action: 'tf-rm-rf', taskId: 't' });
185
+ assert.deepEqual(ok, { verdict: 'allow', reversibility: 'fatal' });
186
+ const no = await g2.admit({ action: 'tf-rm-rf', taskId: 't' });
187
+ assert.ok(no.verdict === 'deny');
188
+ assert.equal((no as { reason: string }).reason, 'fatal-approval-denied');
189
+ });
190
+
191
+ test('admit:commit 级不允许直接准入(必须走两段式);spec 级指向 speculate', async () => {
192
+ const { gate } = makeGate();
193
+ const c = await gate.admit({ action: 'tf-write-commit', taskId: 't' });
194
+ assert.ok(c.verdict === 'deny');
195
+ assert.match((c as { reason: string }).reason, /commit-requires-credential/);
196
+ const s = await gate.admit({ action: 'tf-write', taskId: 't' });
197
+ assert.ok(s.verdict === 'deny');
198
+ assert.match((s as { reason: string }).reason, /spec-via-speculate/);
199
+ });
200
+
201
+ test('gate:未冻结 registry 上调用 → RegistryNotFrozenError(装配期失败)', () => {
202
+ const reg = new ActionRegistry();
203
+ reg.declare({ name: 'tf-read', reversibility: 'read' });
204
+ const sink = new MockStagingSink();
205
+ const gate = new ActionGate({ registry: reg, staging: sink });
206
+ assert.rejects(() => gate.admit({ action: 'tf-read' }), RegistryNotFrozenError);
207
+ });
208
+
209
+ // ---------------------------------------------------------------------------
210
+ // speculate:spec 零副作用 + 凭据签发
211
+ // ---------------------------------------------------------------------------
212
+
213
+ test('speculate:写暂存区 + 产 diff + 发凭据;真实工作区零副作用(mock 断言)', () => {
214
+ const { gate, sink, clock } = makeGate({ ttl: 5_000 });
215
+ sink.setWorkspace('src/app.ts', 'const a = 1;\n');
216
+ const before = new Map(sink.workspace);
217
+ const stagedBefore = sink.stagedWrites.length;
218
+
219
+ const result = expectAllow(
220
+ gate.speculate(specReq([{ path: 'src/app.ts', content: 'const a = 2;\n' }])),
221
+ );
222
+
223
+ // 工作区未被触碰:map 深比较不变
224
+ assert.deepEqual([...sink.workspace], [...before]);
225
+ // 写的是暂存区,不是工作区
226
+ assert.equal(sink.stagedWrites.length, stagedBefore + 1);
227
+ assert.equal(sink.stagedWrites[0].path, 'src/app.ts');
228
+ assert.equal(sink.stagedWrites[0].content, 'const a = 2;\n');
229
+ // diff 已产出
230
+ assert.match(result.diff, /const a = 2/);
231
+ // 凭据:specHash = 暂存 receipts 的确定性 sha256;expiresAt = now + ttl
232
+ const expectedSpecHash = sha(
233
+ JSON.stringify([{ path: 'src/app.ts', hash: sha('const a = 2;\n') }]),
234
+ );
235
+ assert.equal(result.specHash, expectedSpecHash);
236
+ assert.equal(result.credential.specHash, expectedSpecHash);
237
+ assert.equal(result.credential.taskId, 'task-1');
238
+ assert.equal(result.credential.expiresAt, clock.now() + 5_000);
239
+ assert.equal(result.credential.used, false);
240
+ });
241
+
242
+ test('speculate:暂存泄漏进工作区 → StagingLeakError(fail-closed,不发凭据)', () => {
243
+ // 恶意/错误 sink:writeStaged 同时改工作区
244
+ const leaky = new MockStagingSink();
245
+ const originalWrite = leaky.writeStaged.bind(leaky);
246
+ leaky.writeStaged = (path: string, content: string) => {
247
+ leaky.setWorkspace(path, content); // 违反契约
248
+ return originalWrite(path, content);
249
+ };
250
+ const { gate } = makeGate({ sink: leaky });
251
+ leaky.setWorkspace('src/app.ts', 'old');
252
+ assert.throws(
253
+ () => gate.speculate(specReq([{ path: 'src/app.ts', content: 'new' }])),
254
+ StagingLeakError,
255
+ );
256
+ });
257
+
258
+ test('speculate:非 spec 级 action 抛 NotSpecActionError;空写入结构化拒绝', () => {
259
+ const { gate } = makeGate();
260
+ assert.throws(() => gate.speculate({ ...specReq([]), action: 'tf-read', writes: [{ path: 'a', content: 'x' }] }), NotSpecActionError);
261
+ const empty = gate.speculate(specReq([]));
262
+ assert.ok(empty.verdict === 'deny');
263
+ assert.match((empty as { reason: string }).reason, /empty-spec/);
264
+ });
265
+
266
+ // ---------------------------------------------------------------------------
267
+ // commit:凭据三种失效路径全部结构化返回
268
+ // ---------------------------------------------------------------------------
269
+
270
+ test('commit:有效凭据放行一次;同一凭据二次使用 → already_used(结构化)', () => {
271
+ const { gate, sink } = makeGate();
272
+ sink.setWorkspace('src/app.ts', 'v1');
273
+ const cred = expectAllow(
274
+ gate.speculate(specReq([{ path: 'src/app.ts', content: 'v2' }])),
275
+ ).credential;
276
+
277
+ const first = gate.commit({ action: 'tf-write-commit', taskId: 'task-1', credential: cred });
278
+ assert.ok(first.verdict === 'allow');
279
+ assert.equal((first as { credentialId: string }).credentialId, cred.id);
280
+ assert.equal(cred.used, true);
281
+
282
+ const second = gate.commit({ action: 'tf-write-commit', taskId: 'task-1', credential: cred });
283
+ assert.ok(second.verdict === 'deny');
284
+ const rej = (second as { rejection: { reason: string; detail: string } }).rejection;
285
+ assert.equal(rej.reason, 'already_used');
286
+ assert.match(rej.detail, /一次性/);
287
+ });
288
+
289
+ test('commit:spec 后目标内容变化 → hash_mismatch(结构化,含路径)', () => {
290
+ const { gate, sink } = makeGate();
291
+ sink.setWorkspace('src/app.ts', 'v1');
292
+ sink.setWorkspace('src/lib.ts', 'L1');
293
+ const cred = expectAllow(
294
+ gate.speculate(
295
+ specReq([
296
+ { path: 'src/app.ts', content: 'v2' },
297
+ { path: 'src/lib.ts', content: 'L2' },
298
+ ]),
299
+ ),
300
+ ).credential;
301
+
302
+ // 另一个工程师在 spec 之后改了工作区
303
+ sink.setWorkspace('src/lib.ts', 'L1-changed-by-others');
304
+ const result = gate.commit({ action: 'tf-write-commit', taskId: 'task-1', credential: cred });
305
+ assert.ok(result.verdict === 'deny');
306
+ const rej = (result as { rejection: { reason: string; detail: string } }).rejection;
307
+ assert.equal(rej.reason, 'hash_mismatch');
308
+ assert.match(rej.detail, /src\/lib\.ts/);
309
+ assert.match(rej.detail, /spec 之后/);
310
+ // hash_mismatch 不消费凭据(未被 used),凭据仍可解释状态
311
+ assert.equal(cred.used, false);
312
+ });
313
+
314
+ test('commit:超时 → expired(结构化,含时间);used+expired 时 already_used 优先', () => {
315
+ const clock = new FakeClock(1_000);
316
+ const { gate, sink } = makeGate({ clock, ttl: 100 });
317
+ sink.setWorkspace('a.txt', '');
318
+ const cred = expectAllow(
319
+ gate.speculate(specReq([{ path: 'a.txt', content: 'x' }])),
320
+ ).credential;
321
+ assert.equal(cred.expiresAt, 1_100);
322
+
323
+ clock.advance(101);
324
+ const result = gate.commit({ action: 'tf-write-commit', taskId: 'task-1', credential: cred });
325
+ assert.ok(result.verdict === 'deny');
326
+ const rej = (result as { rejection: { reason: string; detail: string } }).rejection;
327
+ assert.equal(rej.reason, 'expired');
328
+ assert.match(rej.detail, /过期/);
329
+
330
+ // used + expired:already_used 优先于 expired(确定性校验顺序)
331
+ sink.setWorkspace('a.txt', '');
332
+ const cred2 = expectAllow(
333
+ gate.speculate(specReq([{ path: 'a.txt', content: 'y' }])),
334
+ ).credential;
335
+ cred2.used = true; // 直接标记已用(模拟消费后时钟过期)
336
+ const r2 = gate.commit({ action: 'tf-write-commit', taskId: 'task-1', credential: cred2 });
337
+ assert.ok(r2.verdict === 'deny');
338
+ assert.equal((r2 as { rejection: { reason: string } }).rejection.reason, 'already_used');
339
+ });
340
+
341
+ test('commit:未知凭据 → unknown(结构化)', () => {
342
+ const { gate } = makeGate();
343
+ const fake = {
344
+ id: 'task-x#spec#999',
345
+ specHash: sha('nothing'),
346
+ taskId: 'task-x',
347
+ expiresAt: 9_999,
348
+ used: false,
349
+ };
350
+ const result = gate.commit({ action: 'tf-write-commit', taskId: 'task-x', credential: fake });
351
+ assert.ok(result.verdict === 'deny');
352
+ const rej = (result as { rejection: { reason: string; detail: string } }).rejection;
353
+ assert.equal(rej.reason, 'unknown');
354
+ assert.match(rej.detail, /不存在/);
355
+ });
356
+
357
+ test('commit:specHash 内容正确性 —— 相同内容重复 spec 得到相同 specHash', () => {
358
+ const { gate, sink } = makeGate();
359
+ sink.setWorkspace('a.txt', '');
360
+ const s1 = expectAllow(gate.speculate(specReq([{ path: 'a.txt', content: 'same' }])));
361
+ const s2 = expectAllow(gate.speculate(specReq([{ path: 'a.txt', content: 'same' }])));
362
+ assert.equal(s1.specHash, s2.specHash);
363
+ // 两个凭据互相独立,均可各自消费一次
364
+ assert.notEqual(s1.credential.id, s2.credential.id);
365
+ const r1 = gate.commit({ action: 'tf-write-commit', taskId: 'task-1', credential: s1.credential });
366
+ const r2 = gate.commit({ action: 'tf-write-commit', taskId: 'task-1', credential: s2.credential });
367
+ assert.ok(r1.verdict === 'allow');
368
+ assert.ok(r2.verdict === 'allow');
369
+ });
370
+
371
+ // ---------------------------------------------------------------------------
372
+ // SystemClock 冒烟(真实时钟路径)
373
+ // ---------------------------------------------------------------------------
374
+
375
+ test('SystemClock:默认时钟可用(冒烟)', () => {
376
+ const clock = new SystemClock();
377
+ const t1 = clock.now();
378
+ assert.ok(Number.isFinite(t1));
379
+ assert.ok(clock.now() >= t1);
380
+ });
@@ -0,0 +1,240 @@
1
+ // test/helpers/stub-loop.ts —— 桩 loop:mock E2E 的最小单流驱动器
2
+ //
3
+ // 这是测试设施,不是 06 号正式 loop。只实现 mock-provider E2E 所需的最小路径:
4
+ // ctx.llm.stream 的替身 = normalizeStream(model.adapter.stream(options))
5
+ // 逐 delta 累积文本 → 行闭合即解析 tf-* 命令 → 直接执行(读写沙箱目录)
6
+ // → 每个工具完成调用 model.notifyToolResult()(waitTools 的回灌信号源)
7
+ // → finish chunk 终止。
8
+ //
9
+ // normalizeStream 镜像 LlmRuntime.stream 的异常归一化契约
10
+ // (dsh-llm/lib/types/types.d.ts:456:"adapter may throw … normalizes that failure
11
+ // to a terminal `error` or `aborted` finish"):适配器抛错 → 终止 error finish。
12
+ // 若适配器已先吐过 finish 再抛错(mock 的 fail-fast 语义),吞掉重复抛错。
13
+
14
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
15
+ import { join } from 'node:path';
16
+ import type { GenerateOptionsLike, MockModel, StreamChunk } from '../../src/entry/mock-provider.ts';
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // 流归一化 shim(镜像 LlmRuntime 契约)
20
+ // ---------------------------------------------------------------------------
21
+
22
+ export interface NormalizedFinish {
23
+ kind: string;
24
+ message?: string;
25
+ code?: string;
26
+ }
27
+
28
+ export function normalizeStream(
29
+ inner: AsyncIterable<StreamChunk>,
30
+ ): { stream: AsyncGenerator<StreamChunk>; finished: NormalizedFinish | null } {
31
+ const state = { finished: null as NormalizedFinish | null };
32
+ async function* run(): AsyncGenerator<StreamChunk> {
33
+ try {
34
+ for await (const chunk of inner) {
35
+ if (chunk.type === 'finish') {
36
+ state.finished = { kind: chunk.reason.kind, message: (chunk.reason as { message?: string }).message, code: (chunk.reason as { code?: string }).code };
37
+ }
38
+ yield chunk;
39
+ }
40
+ } catch (error) {
41
+ // 契约归一化:适配器异常 → 终止 error finish;已终止则吞掉重复抛错
42
+ if (state.finished === null) {
43
+ const message = error instanceof Error ? error.message : String(error);
44
+ state.finished = { kind: 'error', message, code: 'MOCK_ADAPTER_THROWN' };
45
+ yield { type: 'finish', reason: { kind: 'error', message, code: 'MOCK_ADAPTER_THROWN' } };
46
+ }
47
+ }
48
+ }
49
+ return { stream: run(), finished: state.finished === null ? state.finished : state.finished };
50
+ }
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // tf-* 行解析(桩级:真正的 parser 在 kernel/parser.ts,03 号交付)
54
+ // ---------------------------------------------------------------------------
55
+
56
+ export interface TfCommand {
57
+ kind: 'tf-write' | 'tf-read' | 'tf-peek' | 'tf-bash' | 'tf-final';
58
+ raw: string;
59
+ path?: string;
60
+ content?: string;
61
+ }
62
+
63
+ export function parseTfLine(line: string): TfCommand | { kind: 'malformed'; raw: string } | null {
64
+ const t = line.trim();
65
+ if (t.length === 0 || !t.startsWith('tf-')) return null;
66
+ const write = /^tf-write\s+(\S+)\s+"((?:[^"\\]|\\.)*)"$/.exec(t);
67
+ if (write) return { kind: 'tf-write', raw: t, path: write[1], content: write[2]!.replace(/\\(["\\])/g, '$1') };
68
+ const read = /^tf-read\s+(\S+)$/.exec(t);
69
+ if (read) return { kind: 'tf-read', raw: t, path: read[1] };
70
+ if (/^tf-final\s*$/.test(t)) return { kind: 'tf-final', raw: t };
71
+ return { kind: 'malformed', raw: t };
72
+ }
73
+
74
+ // ---------------------------------------------------------------------------
75
+ // 桩 loop
76
+ // ---------------------------------------------------------------------------
77
+
78
+ export type LedgerEntry =
79
+ | { seq: number; kind: 'tool'; cmd: string; path?: string; ok: boolean; detail?: string }
80
+ | { seq: number; kind: 'malformed-command'; line: string }
81
+ | { seq: number; kind: 'final' }
82
+ | { seq: number; kind: 'fault'; fault: string; detail?: string }
83
+ | { seq: number; kind: 'finish'; finish: NormalizedFinish };
84
+
85
+ export interface TimelineEvent {
86
+ seq: number;
87
+ what: 'tool-executed' | 'malformed-seen' | 'final-seen' | 'finish-seen' | 'budget-abort' | 'timeout-abort';
88
+ detail?: string;
89
+ }
90
+
91
+ export interface StubLoopResult {
92
+ assistantText: string;
93
+ finish: NormalizedFinish | null;
94
+ /** 事件时间线:断言"工具执行发生在流终止之前 / 挂起-重入顺序"用 */
95
+ timeline: TimelineEvent[];
96
+ ledger: LedgerEntry[];
97
+ /** 沙箱内实际写入的文件(相对路径 → 内容) */
98
+ writtenFiles: Map<string, string>;
99
+ /** 沙箱内实际读过的文件(相对路径 → 内容) */
100
+ readFiles: Map<string, string>;
101
+ modelCalls: number;
102
+ elapsedMs: number;
103
+ }
104
+
105
+ export interface StubLoopOptions {
106
+ /** 沙箱目录(tf-write / tf-read 的根) */
107
+ sandboxDir: string;
108
+ /** 整轮超时(ms):到点 abort 模拟消费方超时处理路径 */
109
+ timeoutMs?: number;
110
+ /** 输出预算(chars):超出 abort 模拟预算降级路径 */
111
+ budgetChars?: number;
112
+ /** 发给"模型"的任务文本 */
113
+ task: string;
114
+ model: MockModel;
115
+ modelId?: string;
116
+ }
117
+
118
+ export async function runStubLoop(opts: StubLoopOptions): Promise<StubLoopResult> {
119
+ const started = Date.now();
120
+ mkdirSync(opts.sandboxDir, { recursive: true });
121
+ const controller = new AbortController();
122
+ let timedOut = false;
123
+ const timeoutTimer =
124
+ opts.timeoutMs !== undefined
125
+ ? setTimeout(() => {
126
+ timedOut = true;
127
+ controller.abort();
128
+ }, opts.timeoutMs)
129
+ : undefined;
130
+
131
+ let seq = 0;
132
+ const ledger: LedgerEntry[] = [];
133
+ const timeline: TimelineEvent[] = [];
134
+ const writtenFiles = new Map<string, string>();
135
+ const readFiles = new Map<string, string>();
136
+ let text = '';
137
+ let emittedChars = 0;
138
+ let budgetAborted = false;
139
+ let finish: NormalizedFinish | null = null;
140
+
141
+ const messages: GenerateOptionsLike['messages'] = [
142
+ { role: 'user', content: [{ type: 'text', text: opts.task }] },
143
+ ];
144
+
145
+ const { stream, finished } = normalizeStream(
146
+ opts.model.adapter.stream({
147
+ provider: opts.model.provider,
148
+ model: opts.modelId ?? 'mock-scenario',
149
+ messages,
150
+ signal: controller.signal,
151
+ }),
152
+ );
153
+ void finished;
154
+
155
+ const executeTool = (cmd: TfCommand & { kind: 'tf-write' | 'tf-read' }) => {
156
+ try {
157
+ if (cmd.kind === 'tf-write') {
158
+ const abs = join(opts.sandboxDir, cmd.path!);
159
+ writeFileSync(abs, cmd.content!, 'utf8');
160
+ writtenFiles.set(cmd.path!, cmd.content!);
161
+ ledger.push({ seq: seq++, kind: 'tool', cmd: cmd.kind, path: cmd.path, ok: true, detail: `${cmd.content!.length} chars` });
162
+ } else {
163
+ const abs = join(opts.sandboxDir, cmd.path!);
164
+ const content = readFileSync(abs, 'utf8');
165
+ readFiles.set(cmd.path!, content);
166
+ ledger.push({ seq: seq++, kind: 'tool', cmd: cmd.kind, path: cmd.path, ok: true, detail: `${content.length} chars` });
167
+ }
168
+ timeline.push({ seq: seq++, what: 'tool-executed', detail: cmd.raw });
169
+ } catch (error) {
170
+ ledger.push({ seq: seq++, kind: 'tool', cmd: cmd.kind, path: cmd.path, ok: false, detail: String((error as Error).message) });
171
+ timeline.push({ seq: seq++, what: 'tool-executed', detail: `${cmd.raw} (failed)` });
172
+ }
173
+ // 工具完成信号回灌(waitTools 的挂起-重入通道)
174
+ opts.model.notifyToolResult();
175
+ };
176
+
177
+ const handleLine = (line: string) => {
178
+ const cmd = parseTfLine(line);
179
+ if (cmd === null) return;
180
+ if (cmd.kind === 'malformed') {
181
+ ledger.push({ seq: seq++, kind: 'malformed-command', line: cmd.raw });
182
+ timeline.push({ seq: seq++, what: 'malformed-seen', detail: cmd.raw });
183
+ return;
184
+ }
185
+ if (cmd.kind === 'tf-final') {
186
+ ledger.push({ seq: seq++, kind: 'final' });
187
+ timeline.push({ seq: seq++, what: 'final-seen' });
188
+ return;
189
+ }
190
+ executeTool(cmd);
191
+ };
192
+
193
+ // 行缓冲:delta 累积,按 '\n' 切分,闭合行立即派发(不等流结束)
194
+ let lineBuffer = '';
195
+ const feedText = (delta: string) => {
196
+ text += delta;
197
+ emittedChars += delta.length;
198
+ if (opts.budgetChars !== undefined && emittedChars > opts.budgetChars && !budgetAborted) {
199
+ budgetAborted = true;
200
+ ledger.push({ seq: seq++, kind: 'fault', fault: 'budget-exceeded', detail: `emitted ${emittedChars} > ${opts.budgetChars}` });
201
+ timeline.push({ seq: seq++, what: 'budget-abort', detail: `${emittedChars} chars` });
202
+ controller.abort();
203
+ }
204
+ lineBuffer += delta;
205
+ let idx: number;
206
+ while ((idx = lineBuffer.indexOf('\n')) >= 0) {
207
+ const line = lineBuffer.slice(0, idx);
208
+ lineBuffer = lineBuffer.slice(idx + 1);
209
+ handleLine(line);
210
+ }
211
+ };
212
+
213
+ try {
214
+ for await (const chunk of stream) {
215
+ if (chunk.type === 'text-delta') feedText(chunk.text);
216
+ if (chunk.type === 'finish') {
217
+ finish = { kind: chunk.reason.kind, message: (chunk.reason as { message?: string }).message, code: (chunk.reason as { code?: string }).code };
218
+ ledger.push({ seq: seq++, kind: 'finish', finish });
219
+ timeline.push({ seq: seq++, what: 'finish-seen', detail: finish.kind });
220
+ }
221
+ }
222
+ } finally {
223
+ if (timeoutTimer !== undefined) clearTimeout(timeoutTimer);
224
+ if (timedOut) {
225
+ ledger.push({ seq: seq++, kind: 'fault', fault: 'timeout', detail: `aborted after ${Date.now() - started}ms` });
226
+ timeline.push({ seq: seq++, what: 'timeout-abort' });
227
+ }
228
+ }
229
+
230
+ return {
231
+ assistantText: text,
232
+ finish,
233
+ timeline,
234
+ ledger,
235
+ writtenFiles,
236
+ readFiles,
237
+ modelCalls: opts.model.calls.length,
238
+ elapsedMs: Date.now() - started,
239
+ };
240
+ }