@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.
- package/CHANGELOG.md +497 -0
- package/CONTRIBUTING.md +72 -0
- package/LICENSE +202 -0
- package/README.en.md +349 -0
- package/README.md +300 -3
- package/cordis.patch.yml +77 -0
- package/dist/entry/action-gate.js +206 -0
- package/dist/entry/adapter-kit.js +192 -0
- package/dist/entry/context-render.js +119 -0
- package/dist/entry/control-bar-cli.js +289 -0
- package/dist/entry/control-bar.js +123 -0
- package/dist/entry/control-session.js +115 -0
- package/dist/entry/control-state.js +125 -0
- package/dist/entry/cordis-compat.js +95 -0
- package/dist/entry/eval-probe.js +112 -0
- package/dist/entry/intent-log.js +121 -0
- package/dist/entry/json-persistence.js +306 -0
- package/dist/entry/loop.js +3852 -0
- package/dist/entry/mock-provider.js +536 -0
- package/dist/entry/obs-broker.js +178 -0
- package/dist/entry/ptc-bridge.js +405 -0
- package/dist/entry/state-handle.js +217 -0
- package/dist/entry/takeover-registry.js +60 -0
- package/dist/kernel/control-bar.js +559 -0
- package/dist/kernel/final.js +62 -0
- package/dist/kernel/gate.js +464 -0
- package/dist/kernel/modes.js +253 -0
- package/dist/kernel/obs.js +517 -0
- package/dist/kernel/parser.js +632 -0
- package/dist/kernel/render.js +444 -0
- package/dist/kernel/state.js +416 -0
- package/dist/version.js +9 -0
- package/docs/TEST-PROPOSITIONS.md +139 -0
- package/docs/adr-001-segment-boundary.md +61 -0
- package/docs/architecture.md +104 -0
- package/docs/desktop-ui-feasibility.md +277 -0
- package/docs/disabled-lines-audit.md +53 -0
- package/docs/limitations.md +181 -0
- package/docs/protocol.md +99 -0
- package/docs/v0.4.0-plan.md +50 -0
- package/eval/METRICS.md +128 -0
- package/eval/RESULTS.md +246 -0
- package/eval/tasks/fixtures/big-report.md +298 -0
- package/eval/tasks/fixtures/build-manifest.txt +5 -0
- package/eval/tasks/fixtures/deploy.yaml +4 -0
- package/eval/tasks/fixtures/error.log +200 -0
- package/eval/tasks/fixtures/features.yaml +4 -0
- package/eval/tasks/fixtures/pipeline.yaml +4 -0
- package/eval/tasks/fixtures/sales-q1.csv +61 -0
- package/eval/tasks/fixtures/settings.yaml +4 -0
- package/eval/tasks/fixtures/users-roster.json +304 -0
- package/eval/tasks/fixtures/users-scores.json +20 -0
- package/eval/tasks/gen-fixtures.cjs +80 -0
- package/eval/tasks/tasks.json +150 -0
- package/eval/tools/f6-kill-drill.cjs +176 -0
- package/eval/tools/f6-kill-drill.worker.cjs +131 -0
- package/eval/tools/gen-results.cjs +191 -0
- package/eval/tools/machine-test.cjs +200 -0
- package/eval/tools/manual-code-scenarios.md +59 -0
- package/eval/tools/replay-check.cjs +311 -0
- package/eval/tools/runner.cjs +219 -0
- package/eval/tools/session-log.cjs +106 -0
- package/eval/tools/summarize.cjs +185 -0
- package/eval/tools/t3-cells.cjs +173 -0
- package/package.json +73 -6
- package/patches/adapters-smoke.yml +41 -0
- package/patches/eval-account.yml +36 -0
- package/patches/eval-baseline.yml +33 -0
- package/patches/eval-stream-code-off.yml +46 -0
- package/patches/eval-stream-code-on.yml +47 -0
- package/patches/eval-stream.yml +54 -0
- package/patches/takeover.yml +42 -0
- package/patches/test-preset.yml +23 -0
- package/preset/stream/cordis.patch.yml +39 -0
- package/preset/stream/package.json +13 -0
- package/preset.yml +56 -0
- package/profiles/stream/README.md +66 -0
- package/profiles/stream/cordis.patch.yml +12 -0
- package/profiles/stream/package.json +17 -0
- package/profiles/stream-headless/package.json +16 -0
- package/scripts/build.mjs +103 -0
- package/scripts/check-consistency.mjs +146 -0
- package/scripts/gate.mjs +138 -0
- package/scripts/install-check.mjs +116 -0
- package/scripts/install-cycle.mjs +88 -0
- package/scripts/release.mjs +415 -0
- package/scripts/repair-session-logs.mjs +403 -0
- package/src/entry/action-gate.ts +206 -0
- package/src/entry/adapter-kit.ts +192 -0
- package/src/entry/context-render.ts +119 -0
- package/src/entry/control-bar-cli.ts +289 -0
- package/src/entry/control-bar.ts +123 -0
- package/src/entry/control-session.ts +115 -0
- package/src/entry/control-state.ts +125 -0
- package/src/entry/cordis-compat.ts +95 -0
- package/src/entry/eval-probe.ts +112 -0
- package/src/entry/intent-log.ts +121 -0
- package/src/entry/json-persistence.ts +306 -0
- package/src/entry/loop.ts +3852 -0
- package/src/entry/mock-provider.ts +536 -0
- package/src/entry/obs-broker.ts +178 -0
- package/src/entry/ptc-bridge.ts +405 -0
- package/src/entry/state-handle.ts +217 -0
- package/src/entry/takeover-registry.ts +60 -0
- package/src/kernel/control-bar.ts +559 -0
- package/src/kernel/final.ts +62 -0
- package/src/kernel/gate.ts +464 -0
- package/src/kernel/modes.ts +253 -0
- package/src/kernel/obs.ts +517 -0
- package/src/kernel/parser.ts +632 -0
- package/src/kernel/render.ts +444 -0
- package/src/kernel/state.ts +416 -0
- package/src/version.ts +9 -0
- package/test/activation.test.ts +187 -0
- package/test/adapters.test.ts +676 -0
- package/test/control-bar.test.ts +486 -0
- package/test/desktop-ui.test.ts +359 -0
- package/test/eval-probe.test.ts +139 -0
- package/test/f5-plan.test.ts +221 -0
- package/test/f6-intent.test.ts +168 -0
- package/test/f7-segment.test.ts +190 -0
- package/test/fix-limits.test.ts +599 -0
- package/test/gate.test.ts +380 -0
- package/test/helpers/stub-loop.ts +240 -0
- package/test/kernel/obs.test.ts +329 -0
- package/test/kernel/parser.test.ts +450 -0
- package/test/loop.test.ts +1393 -0
- package/test/mock-provider.test.ts +386 -0
- package/test/ptc-bridge.test.ts +356 -0
- package/test/render.test.ts +418 -0
- package/test/s2-install-check.test.ts +46 -0
- package/test/scenarios/3-file-basic.json +13 -0
- package/test/scenarios/5-file-basic.json +22 -0
- package/test/scenarios/burn-more.json +9 -0
- package/test/scenarios/degraded-final.json +10 -0
- package/test/scenarios/fault-abort-xml.json +11 -0
- package/test/scenarios/fault-malformed-command.json +12 -0
- package/test/scenarios/fault-midstream-abort.json +11 -0
- package/test/scenarios/fault-saturating-output.json +9 -0
- package/test/scenarios/fault-timeout.json +9 -0
- package/test/scenarios/peek-first.json +11 -0
- package/test/scenarios/peek-second.json +11 -0
- package/test/scenarios/peek-third.json +10 -0
- package/test/scenarios/recover-final.json +10 -0
- package/test/scenarios/reroute-first.json +17 -0
- package/test/scenarios/reroute-second.json +16 -0
- package/test/scenarios/starvation-final.json +10 -0
- package/test/scenarios/starvation-promote.json +11 -0
- package/test/scenarios/wait-tools-continue.json +10 -0
- package/test/scenarios/wait-tools-xml.json +22 -0
- package/test/scenarios/wait-tools.json +15 -0
- package/test/session-format.test.ts +234 -0
- package/test/state.test.ts +335 -0
- package/test/stream-v02.test.ts +264 -0
- package/test/v031-display.test.ts +333 -0
- package/ui/client.js +576 -0
- package/ui/index.js +282 -0
- package/ui/package.json +26 -0
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
// kernel/state.ts —— 内容寻址状态树与句柄(M1,分派 02)
|
|
2
|
+
//
|
|
3
|
+
// 内核层纪律:零框架依赖(不 import 任何 @deepseek-ai/*);
|
|
4
|
+
// 除 node:crypto 哈希计算外无任何副作用(无 fs、无网络、无 console)——
|
|
5
|
+
// BlobSink 是唯一 IO 出口,依赖注入全走构造参数。
|
|
6
|
+
//
|
|
7
|
+
// 不变量 I2(强制溯源,违反即抛错,绝不静默修正):
|
|
8
|
+
// confidence="derived" 必须带非空 derivedFrom;
|
|
9
|
+
// confidence="stated" 必须不带 derivedFrom。
|
|
10
|
+
|
|
11
|
+
import { createHash } from 'node:crypto';
|
|
12
|
+
|
|
13
|
+
// ---------------------------------------------------------------------------
|
|
14
|
+
// 类型
|
|
15
|
+
// ---------------------------------------------------------------------------
|
|
16
|
+
|
|
17
|
+
export type HandleKind = 'file' | 'blob' | 'obs';
|
|
18
|
+
|
|
19
|
+
/** 句柄:内容寻址 + 版本。形如 file:src/app.ts@v3 / obs:tool:callId@v3 / blob:1a2b3c4d@v1 */
|
|
20
|
+
export interface StateHandle {
|
|
21
|
+
readonly kind: HandleKind;
|
|
22
|
+
readonly path: string;
|
|
23
|
+
readonly version: number;
|
|
24
|
+
readonly hash: string; // sha256 hex
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** 状态节点:强制溯源(不变量 I2) */
|
|
28
|
+
export interface StateNode {
|
|
29
|
+
readonly id: string;
|
|
30
|
+
readonly value: unknown;
|
|
31
|
+
readonly derivedFrom?: readonly string[]; // 来源节点 id 列表
|
|
32
|
+
readonly confidence: 'stated' | 'derived'; // stated 必须无 derivedFrom;derived 必须有
|
|
33
|
+
readonly createdAt: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* BlobSink:内核唯一的 IO 出口。默认内存实现;
|
|
38
|
+
* localStorage / 文件实现在适配层(07 号分派)接到 DSH storage 服务。
|
|
39
|
+
*/
|
|
40
|
+
export interface BlobSink {
|
|
41
|
+
write(key: string, data: Uint8Array): void;
|
|
42
|
+
read(key: string): Uint8Array | undefined;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface PutRef {
|
|
46
|
+
kind?: HandleKind; // 缺省 'blob'(path 自动取 hash 前 8 位)
|
|
47
|
+
path?: string; // kind='file' 必填
|
|
48
|
+
tool?: string; // kind='obs' 必填
|
|
49
|
+
callId?: string; // kind='obs' 必填
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface SetOpts {
|
|
53
|
+
derivedFrom?: readonly string[];
|
|
54
|
+
confidence?: 'stated' | 'derived';
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// ---------------------------------------------------------------------------
|
|
58
|
+
// 错误类型
|
|
59
|
+
// ---------------------------------------------------------------------------
|
|
60
|
+
|
|
61
|
+
export class InvalidStateWriteError extends Error {
|
|
62
|
+
constructor(message: string) {
|
|
63
|
+
super(message);
|
|
64
|
+
this.name = 'InvalidStateWriteError';
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export class UnknownHandleError extends Error {
|
|
69
|
+
constructor(message: string) {
|
|
70
|
+
super(message);
|
|
71
|
+
this.name = 'UnknownHandleError';
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export class CycleError extends Error {
|
|
76
|
+
constructor(message: string) {
|
|
77
|
+
super(message);
|
|
78
|
+
this.name = 'CycleError';
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// ---------------------------------------------------------------------------
|
|
83
|
+
// 默认内存 BlobSink
|
|
84
|
+
// ---------------------------------------------------------------------------
|
|
85
|
+
|
|
86
|
+
export class MemoryBlobSink implements BlobSink {
|
|
87
|
+
private readonly blobs = new Map<string, Uint8Array>();
|
|
88
|
+
|
|
89
|
+
write(key: string, data: Uint8Array): void {
|
|
90
|
+
this.blobs.set(key, data);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
read(key: string): Uint8Array | undefined {
|
|
94
|
+
return this.blobs.get(key);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ---------------------------------------------------------------------------
|
|
99
|
+
// 句柄格式化 / 解析
|
|
100
|
+
// ---------------------------------------------------------------------------
|
|
101
|
+
|
|
102
|
+
export function formatHandle(handle: StateHandle): string {
|
|
103
|
+
return `${handle.kind}:${handle.path}@v${handle.version}`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 解析句柄字符串;格式非法抛 UnknownHandleError。 */
|
|
107
|
+
export function parseHandle(text: string): StateHandle {
|
|
108
|
+
const at = text.lastIndexOf('@v');
|
|
109
|
+
if (at <= 0) throw new UnknownHandleError(`malformed handle: "${text}"`);
|
|
110
|
+
const prefix = text.slice(0, at);
|
|
111
|
+
const version = Number(text.slice(at + 2));
|
|
112
|
+
if (!Number.isInteger(version) || version < 1) {
|
|
113
|
+
throw new UnknownHandleError(`malformed handle version: "${text}"`);
|
|
114
|
+
}
|
|
115
|
+
const colon = prefix.indexOf(':');
|
|
116
|
+
if (colon < 0) throw new UnknownHandleError(`malformed handle: "${text}"`);
|
|
117
|
+
const kind = prefix.slice(0, colon) as HandleKind;
|
|
118
|
+
const path = prefix.slice(colon + 1);
|
|
119
|
+
if (!path) throw new UnknownHandleError(`malformed handle: "${text}"`);
|
|
120
|
+
if (kind !== 'file' && kind !== 'blob' && kind !== 'obs') {
|
|
121
|
+
throw new UnknownHandleError(`unknown handle kind: "${text}"`);
|
|
122
|
+
}
|
|
123
|
+
// blob 句柄 path 必须是 8 位 hash 前缀(写入时由 put 保证)
|
|
124
|
+
if (kind === 'blob' && !/^[0-9a-f]{8}$/.test(path)) {
|
|
125
|
+
throw new UnknownHandleError(`malformed blob handle: "${text}"`);
|
|
126
|
+
}
|
|
127
|
+
return { kind, path, version, hash: '' };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// ---------------------------------------------------------------------------
|
|
131
|
+
// StateStore
|
|
132
|
+
// ---------------------------------------------------------------------------
|
|
133
|
+
|
|
134
|
+
export class StateStore {
|
|
135
|
+
private readonly sink: BlobSink;
|
|
136
|
+
private readonly textEncoder = new TextEncoder();
|
|
137
|
+
private readonly textDecoder = new TextDecoder();
|
|
138
|
+
|
|
139
|
+
/** 每个 `${kind}:${path}` 键下:hash → 版本号(同一内容复用同一版本) */
|
|
140
|
+
private readonly versionByHash = new Map<string, Map<string, number>>();
|
|
141
|
+
/** 每个 `${kind}:${path}` 键下的下一个版本号 */
|
|
142
|
+
private readonly nextVersion = new Map<string, number>();
|
|
143
|
+
/** 哪些 hash 是以字符串写入的(get 时还原为 string) */
|
|
144
|
+
private readonly textHashes = new Set<string>();
|
|
145
|
+
private readonly nodes = new Map<string, StateNode>();
|
|
146
|
+
/** 句柄目录:按创建顺序去重 */
|
|
147
|
+
private readonly catalog = new Map<string, StateHandle>();
|
|
148
|
+
|
|
149
|
+
constructor(sink?: BlobSink) {
|
|
150
|
+
this.sink = sink ?? new MemoryBlobSink();
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* 内容寻址写。同一内容重复写入得到同一版本(sha256 相同 → 版本号复用)。
|
|
155
|
+
* ref 缺省写 blob(path = hash 前 8 位);file / obs 见 PutRef。
|
|
156
|
+
*/
|
|
157
|
+
put(content: Uint8Array | string, ref?: PutRef): StateHandle {
|
|
158
|
+
const bytes = typeof content === 'string' ? this.textEncoder.encode(content) : content;
|
|
159
|
+
const hash = sha256Hex(bytes);
|
|
160
|
+
const kind = ref?.kind ?? 'blob';
|
|
161
|
+
|
|
162
|
+
let path: string;
|
|
163
|
+
if (kind === 'file') {
|
|
164
|
+
if (!ref?.path) {
|
|
165
|
+
throw new InvalidStateWriteError('put() with kind="file" requires ref.path');
|
|
166
|
+
}
|
|
167
|
+
path = ref.path;
|
|
168
|
+
} else if (kind === 'obs') {
|
|
169
|
+
if (!ref?.tool || !ref?.callId) {
|
|
170
|
+
throw new InvalidStateWriteError('put() with kind="obs" requires ref.tool and ref.callId');
|
|
171
|
+
}
|
|
172
|
+
path = `${ref.tool}:${ref.callId}`;
|
|
173
|
+
} else {
|
|
174
|
+
path = hash.slice(0, 8);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const key = `${kind}:${path}`;
|
|
178
|
+
let byHash = this.versionByHash.get(key);
|
|
179
|
+
if (!byHash) {
|
|
180
|
+
byHash = new Map();
|
|
181
|
+
this.versionByHash.set(key, byHash);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
let version = byHash.get(hash);
|
|
185
|
+
if (version === undefined) {
|
|
186
|
+
version = this.nextVersion.get(key) ?? 1;
|
|
187
|
+
this.nextVersion.set(key, version + 1);
|
|
188
|
+
byHash.set(hash, version);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// 内容寻址存储:同一 hash 只存一份,天然去重
|
|
192
|
+
this.sink.write(hash, bytes);
|
|
193
|
+
if (typeof content === 'string') this.textHashes.add(hash);
|
|
194
|
+
|
|
195
|
+
const handle: StateHandle = { kind, path, version, hash };
|
|
196
|
+
this.catalog.set(formatHandle(handle), handle);
|
|
197
|
+
return handle;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** 取回句柄对应的全文。句柄不存在 / 版本不符 / blob 丢失 → UnknownHandleError。 */
|
|
201
|
+
get(handle: StateHandle): Uint8Array | string {
|
|
202
|
+
this.assertKnownHandle(handle);
|
|
203
|
+
const data = this.sink.read(handle.hash);
|
|
204
|
+
if (!data) {
|
|
205
|
+
throw new UnknownHandleError(`blob missing for handle: ${formatHandle(handle)}`);
|
|
206
|
+
}
|
|
207
|
+
return this.textHashes.has(handle.hash) ? this.textDecoder.decode(data) : data;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* 写状态节点(不变量 I2)。节点不可变:同一 id 重复写入抛错。
|
|
212
|
+
* derivedFrom 允许前向引用(引用尚未写入的节点)——环不在写入期阻止,
|
|
213
|
+
* 而是在 trace() 展开时检测(否则环根本无法构造出来测试)。
|
|
214
|
+
*/
|
|
215
|
+
set(id: string, value: unknown, opts: SetOpts = {}): StateNode {
|
|
216
|
+
if (this.nodes.has(id)) {
|
|
217
|
+
throw new InvalidStateWriteError(`state node already exists: "${id}"`);
|
|
218
|
+
}
|
|
219
|
+
const confidence = opts.confidence ?? 'stated';
|
|
220
|
+
const { derivedFrom } = opts;
|
|
221
|
+
|
|
222
|
+
if (confidence === 'derived') {
|
|
223
|
+
if (!derivedFrom || derivedFrom.length === 0) {
|
|
224
|
+
throw new InvalidStateWriteError(
|
|
225
|
+
`I2 violation: node "${id}" is derived but has no derivedFrom`,
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
} else if (derivedFrom !== undefined) {
|
|
229
|
+
throw new InvalidStateWriteError(
|
|
230
|
+
`I2 violation: node "${id}" is stated but carries derivedFrom`,
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
if (derivedFrom) {
|
|
234
|
+
for (const src of derivedFrom) {
|
|
235
|
+
if (typeof src !== 'string' || src.length === 0) {
|
|
236
|
+
throw new InvalidStateWriteError(`I2 violation: node "${id}" has empty derivedFrom entry`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const node: StateNode = Object.freeze({
|
|
242
|
+
id,
|
|
243
|
+
value,
|
|
244
|
+
...(derivedFrom ? { derivedFrom: [...derivedFrom] } : {}),
|
|
245
|
+
confidence,
|
|
246
|
+
createdAt: Date.now(),
|
|
247
|
+
});
|
|
248
|
+
this.nodes.set(id, node);
|
|
249
|
+
return node;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* 完整来源链:从节点出发递归展开 derivedFrom(含节点自身,先序 DFS),
|
|
254
|
+
* 去重;展开路径上出现环抛 CycleError,来源缺失抛 UnknownHandleError。
|
|
255
|
+
*/
|
|
256
|
+
trace(id: string): StateNode[] {
|
|
257
|
+
const start = this.nodes.get(id);
|
|
258
|
+
if (!start) throw new UnknownHandleError(`unknown state node: "${id}"`);
|
|
259
|
+
|
|
260
|
+
const chain: StateNode[] = [];
|
|
261
|
+
const seen = new Set<string>();
|
|
262
|
+
const inStack = new Set<string>();
|
|
263
|
+
|
|
264
|
+
const visit = (node: StateNode): void => {
|
|
265
|
+
if (inStack.has(node.id)) {
|
|
266
|
+
throw new CycleError(`provenance cycle detected at node "${node.id}"`);
|
|
267
|
+
}
|
|
268
|
+
if (seen.has(node.id)) return; // 菱形依赖去重
|
|
269
|
+
seen.add(node.id);
|
|
270
|
+
inStack.add(node.id);
|
|
271
|
+
chain.push(node);
|
|
272
|
+
for (const src of node.derivedFrom ?? []) {
|
|
273
|
+
const parent = this.nodes.get(src);
|
|
274
|
+
if (!parent) {
|
|
275
|
+
throw new UnknownHandleError(
|
|
276
|
+
`provenance node "${src}" (referenced by "${node.id}") does not exist`,
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
visit(parent);
|
|
280
|
+
}
|
|
281
|
+
inStack.delete(node.id);
|
|
282
|
+
};
|
|
283
|
+
|
|
284
|
+
visit(start);
|
|
285
|
+
return chain;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** 两个句柄内容的逐行差异(unified 风格,无上下文行)。内容一致返回空串。 */
|
|
289
|
+
diff(fromHandle: StateHandle, toHandle: StateHandle): string {
|
|
290
|
+
const from = this.get(fromHandle);
|
|
291
|
+
const to = this.get(toHandle);
|
|
292
|
+
const a = splitLines(asText(from));
|
|
293
|
+
const b = splitLines(asText(to));
|
|
294
|
+
if (arraysEqual(a, b)) return '';
|
|
295
|
+
|
|
296
|
+
const ops = diffOps(a, b);
|
|
297
|
+
const out: string[] = [`--- ${formatHandle(fromHandle)}`, `+++ ${formatHandle(toHandle)}`];
|
|
298
|
+
|
|
299
|
+
let i = 0;
|
|
300
|
+
while (i < ops.length) {
|
|
301
|
+
if (ops[i].type === 'equal') {
|
|
302
|
+
i += 1; // 无上下文行格式:equal 直接跳过
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
// 收集一个连续变更块(-/+ 混合,直到遇到 equal)
|
|
306
|
+
const aStart = ops[i].aLine;
|
|
307
|
+
const bStart = ops[i].bLine;
|
|
308
|
+
let aLen = 0;
|
|
309
|
+
let bLen = 0;
|
|
310
|
+
const body: string[] = [];
|
|
311
|
+
while (i < ops.length && ops[i].type !== 'equal') {
|
|
312
|
+
const op = ops[i];
|
|
313
|
+
if (op.type === 'delete') {
|
|
314
|
+
body.push(`-${op.text}`);
|
|
315
|
+
aLen += 1;
|
|
316
|
+
} else {
|
|
317
|
+
body.push(`+${op.text}`);
|
|
318
|
+
bLen += 1;
|
|
319
|
+
}
|
|
320
|
+
i += 1;
|
|
321
|
+
}
|
|
322
|
+
// count=0 时起始行取变更点前一行(GNU unified diff 约定)
|
|
323
|
+
const aHead = aLen > 0 ? `${aStart},${aLen}` : `${aStart - 1},0`;
|
|
324
|
+
const bHead = bLen > 0 ? `${bStart},${bLen}` : `${bStart - 1},0`;
|
|
325
|
+
out.push(`@@ -${aHead} +${bHead} @@`);
|
|
326
|
+
out.push(...body);
|
|
327
|
+
}
|
|
328
|
+
return out.join('\n');
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** 当前句柄目录(按首次创建顺序,已去重)。 */
|
|
332
|
+
handles(): StateHandle[] {
|
|
333
|
+
return [...this.catalog.values()];
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
private assertKnownHandle(handle: StateHandle): void {
|
|
337
|
+
if (!handle || typeof handle !== 'object') {
|
|
338
|
+
throw new UnknownHandleError('not a handle');
|
|
339
|
+
}
|
|
340
|
+
if (handle.kind !== 'file' && handle.kind !== 'blob' && handle.kind !== 'obs') {
|
|
341
|
+
throw new UnknownHandleError(`unknown handle kind: ${String(handle.kind)}`);
|
|
342
|
+
}
|
|
343
|
+
const byHash = this.versionByHash.get(`${handle.kind}:${handle.path}`);
|
|
344
|
+
const version = byHash?.get(handle.hash);
|
|
345
|
+
if (version !== handle.version) {
|
|
346
|
+
throw new UnknownHandleError(
|
|
347
|
+
`unknown handle: ${formatHandle(handle)}` +
|
|
348
|
+
(version !== undefined ? ` (actual version v${version})` : ''),
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// ---------------------------------------------------------------------------
|
|
355
|
+
// 内部工具(纯函数)
|
|
356
|
+
// ---------------------------------------------------------------------------
|
|
357
|
+
|
|
358
|
+
function sha256Hex(data: Uint8Array): string {
|
|
359
|
+
return createHash('sha256').update(data).digest('hex');
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function asText(content: Uint8Array | string): string {
|
|
363
|
+
return typeof content === 'string' ? content : new TextDecoder().decode(content);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function splitLines(text: string): string[] {
|
|
367
|
+
return text.split(/\r\n|\r|\n/);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function arraysEqual(a: string[], b: string[]): boolean {
|
|
371
|
+
return a.length === b.length && a.every((line, i) => line === b[i]);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
type DiffOp =
|
|
375
|
+
| { type: 'equal'; aLine: number; bLine: number; text: string }
|
|
376
|
+
| { type: 'delete'; aLine: number; bLine: number; text: string }
|
|
377
|
+
| { type: 'insert'; aLine: number; bLine: number; text: string };
|
|
378
|
+
|
|
379
|
+
/** 经典 LCS 逐行 diff(O(n·m),内核数据量下足够),输出带行号的 op 序列。 */
|
|
380
|
+
function diffOps(a: string[], b: string[]): DiffOp[] {
|
|
381
|
+
const n = a.length;
|
|
382
|
+
const m = b.length;
|
|
383
|
+
// lcs[i][j] = a[i..] 与 b[j..] 的 LCS 长度
|
|
384
|
+
const lcs: number[][] = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(0));
|
|
385
|
+
for (let i = n - 1; i >= 0; i -= 1) {
|
|
386
|
+
for (let j = m - 1; j >= 0; j -= 1) {
|
|
387
|
+
lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
const ops: DiffOp[] = [];
|
|
392
|
+
let i = 0;
|
|
393
|
+
let j = 0;
|
|
394
|
+
while (i < n && j < m) {
|
|
395
|
+
if (a[i] === b[j]) {
|
|
396
|
+
ops.push({ type: 'equal', aLine: i + 1, bLine: j + 1, text: a[i] });
|
|
397
|
+
i += 1;
|
|
398
|
+
j += 1;
|
|
399
|
+
} else if (lcs[i + 1][j] >= lcs[i][j + 1]) {
|
|
400
|
+
ops.push({ type: 'delete', aLine: i + 1, bLine: j + 1, text: a[i] });
|
|
401
|
+
i += 1;
|
|
402
|
+
} else {
|
|
403
|
+
ops.push({ type: 'insert', aLine: i + 1, bLine: j + 1, text: b[j] });
|
|
404
|
+
j += 1;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
while (i < n) {
|
|
408
|
+
ops.push({ type: 'delete', aLine: i + 1, bLine: m + 1, text: a[i] });
|
|
409
|
+
i += 1;
|
|
410
|
+
}
|
|
411
|
+
while (j < m) {
|
|
412
|
+
ops.push({ type: 'insert', aLine: n + 1, bLine: j + 1, text: b[j] });
|
|
413
|
+
j += 1;
|
|
414
|
+
}
|
|
415
|
+
return ops;
|
|
416
|
+
}
|
package/src/version.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// version.ts —— 单一版本常量(package.json 必须与它一致,test/control-bar.test.ts 会断言)
|
|
2
|
+
//
|
|
3
|
+
// 为什么单独一个文件:控制栏在 stderr 与 --json 里都要报版本,而 kernel 不读 package.json
|
|
4
|
+
// (内核零 IO 纪律),entry 也不该各自硬编码字符串。
|
|
5
|
+
|
|
6
|
+
export const VERSION = '0.3.1';
|
|
7
|
+
|
|
8
|
+
/** 版本来源:npm 源未上线时引导用户用本地路径安装的提示会用到。 */
|
|
9
|
+
export const PACKAGE_NAME = '@hugesb/dsh-stream-agent';
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// test/activation.test.ts —— v0.2.1 装载期回归(事故:桌面端 "1 entry did not activate stream-agent")
|
|
2
|
+
//
|
|
3
|
+
// 现场两行报错:
|
|
4
|
+
// dsh: warning: 1 entry did not activate stream-agent
|
|
5
|
+
// Error: cannot get property "ptcRuntime" without inject
|
|
6
|
+
//
|
|
7
|
+
// 两个独立缺陷,本文件分别钉住:
|
|
8
|
+
// 缺陷 1|可选服务裸读:Cordis 4.x 的 ctx 是 Proxy,未 inject 的属性读取直接抛错。
|
|
9
|
+
// 这里用 strictCtx 复刻该行为(未声明的属性读取抛同款错误)。
|
|
10
|
+
// 缺陷 2|返回值契约:函数式插件的返回值被当作 effect 收集,普通对象 = Invalid effect。
|
|
11
|
+
// 这里断言每个 entry 的返回值可调用。
|
|
12
|
+
//
|
|
13
|
+
// 断言口径:apply() 在"严格 ctx(会抛 inject 错)+ 无 ptcRuntime"下必须装载成功,
|
|
14
|
+
// 且不得因为可选服务缺失而抛错——这是 v0.2.0 完全不可用的直接原因。
|
|
15
|
+
|
|
16
|
+
import test from 'node:test';
|
|
17
|
+
import assert from 'node:assert/strict';
|
|
18
|
+
import { readFileSync } from 'node:fs';
|
|
19
|
+
import { mkdtempSync } from 'node:fs';
|
|
20
|
+
import { tmpdir } from 'node:os';
|
|
21
|
+
import { join } from 'node:path';
|
|
22
|
+
|
|
23
|
+
import applyLoop from '../src/entry/loop.ts';
|
|
24
|
+
import applyStateHandle from '../src/entry/state-handle.ts';
|
|
25
|
+
import applyObsBroker from '../src/entry/obs-broker.ts';
|
|
26
|
+
import applyActionGate from '../src/entry/action-gate.ts';
|
|
27
|
+
import applyContextRender from '../src/entry/context-render.ts';
|
|
28
|
+
import applyControlBar from '../src/entry/control-bar.ts';
|
|
29
|
+
import { asPluginEffect, getService } from '../src/entry/cordis-compat.ts';
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 复刻 Cordis 4.x 的 context proxy:
|
|
33
|
+
* · 方法面(get/provide/on/effect)直接可读;
|
|
34
|
+
* · 服务只能通过 ctx.get(name) 取(无 inject 要求);
|
|
35
|
+
* · **未声明注入**的属性读取一律抛 `cannot get property "X" without inject`。
|
|
36
|
+
*/
|
|
37
|
+
function strictCtx(services: Record<string, unknown>, injected: readonly string[] = []): Record<string, unknown> {
|
|
38
|
+
const base: Record<string, unknown> = {
|
|
39
|
+
get(name: string): unknown {
|
|
40
|
+
return services[name];
|
|
41
|
+
},
|
|
42
|
+
provide(): void {},
|
|
43
|
+
on(): void {},
|
|
44
|
+
effect(): void {},
|
|
45
|
+
};
|
|
46
|
+
return new Proxy(base, {
|
|
47
|
+
get(target, prop, receiver) {
|
|
48
|
+
if (typeof prop === 'symbol') return Reflect.get(target, prop, receiver);
|
|
49
|
+
if (Reflect.has(target, prop)) return Reflect.get(target, prop, receiver);
|
|
50
|
+
if (injected.includes(prop) && services[prop] !== undefined) return services[prop];
|
|
51
|
+
throw new Error(`cannot get property "${prop}" without inject`);
|
|
52
|
+
},
|
|
53
|
+
has(target, prop) {
|
|
54
|
+
if (Reflect.has(target, prop)) return true;
|
|
55
|
+
return injected.includes(String(prop)) && services[String(prop)] !== undefined;
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function makeServices(): { services: Record<string, unknown>; factory: () => unknown } {
|
|
61
|
+
let registered: unknown = null;
|
|
62
|
+
return {
|
|
63
|
+
services: {
|
|
64
|
+
llm: { stream: () => (async function* () {})() },
|
|
65
|
+
tools: { execute: async () => ({ results: [] }), guard: () => () => {} },
|
|
66
|
+
agents: {
|
|
67
|
+
setFactory: (factory: unknown) => {
|
|
68
|
+
registered = factory;
|
|
69
|
+
return () => { registered = null; };
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
sessions: { prepare: async () => ({}) },
|
|
73
|
+
logger: { warn: () => {}, error: () => {} },
|
|
74
|
+
storage: {
|
|
75
|
+
backend: {
|
|
76
|
+
get: () => ({
|
|
77
|
+
kv: {
|
|
78
|
+
open: async () => ({
|
|
79
|
+
loadAll: async () => ({ tables: {}, global: null }),
|
|
80
|
+
putRecord: async () => {},
|
|
81
|
+
close: async () => {},
|
|
82
|
+
}),
|
|
83
|
+
},
|
|
84
|
+
}),
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
factory: () => registered,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
test('strictCtx 复刻了 Cordis 的 inject 守卫(负向对照)', () => {
|
|
93
|
+
const ctx = strictCtx({}, []);
|
|
94
|
+
assert.throws(() => (ctx as Record<string, unknown>)['ptcRuntime'], /cannot get property "ptcRuntime" without inject/);
|
|
95
|
+
assert.equal(ctx.get('ptcRuntime'), undefined, 'ctx.get 不要求 inject,缺失时返回 undefined');
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test('getService:可选服务缺失 / 守卫抛错 / 桩对象属性三条路径都降级为 undefined', () => {
|
|
99
|
+
const strict = strictCtx({ llm: { stream: () => {} } }, []);
|
|
100
|
+
assert.equal(getService(strict, 'ptcRuntime'), undefined);
|
|
101
|
+
assert.notEqual(getService(strict, 'llm'), undefined, 'ctx.get 命中的服务必须返回');
|
|
102
|
+
|
|
103
|
+
// 非 Cordis 测试桩:服务直接挂在 ctx 上(历史用法),属性回退仍要能用
|
|
104
|
+
const stub = { llm: { stream: () => {} } };
|
|
105
|
+
assert.notEqual(getService(stub, 'llm'), undefined);
|
|
106
|
+
|
|
107
|
+
// 极端桩:get 自己抛错 → 仍然不能冒泡
|
|
108
|
+
const broken = { get() { throw new Error('boom'); } };
|
|
109
|
+
assert.equal(getService(broken, 'anything'), undefined);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test('缺陷 1 回归:无 ptcRuntime 时 loop entry 必须装载成功(不再裸读属性)', () => {
|
|
113
|
+
const { services, factory } = makeServices();
|
|
114
|
+
const ctx = strictCtx(services, ['llm', 'tools', 'agents', 'sessions']);
|
|
115
|
+
const handle = applyLoop(ctx as never, { announceTakeover: false, maxParallelToolCalls: 3, maxReentries: 8, streamIdleTimeoutMs: 30000 });
|
|
116
|
+
assert.notEqual(handle, undefined);
|
|
117
|
+
assert.notEqual(factory(), null, 'setFactory 必须被调用(接管才算成立)');
|
|
118
|
+
assert.equal(typeof handle, 'function', '缺陷 2:返回值必须是可调用 disposer');
|
|
119
|
+
handle();
|
|
120
|
+
assert.equal(factory(), null, 'disposer 必须卸载 factory');
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test('缺陷 1 回归:ptcRuntime / sessionProjections / loader / agentDefaultModel 全部缺失也不抛错', () => {
|
|
124
|
+
const { services } = makeServices();
|
|
125
|
+
const ctx = strictCtx(services, ['llm', 'tools', 'agents', 'sessions']);
|
|
126
|
+
assert.doesNotThrow(() => {
|
|
127
|
+
const handle = applyLoop(ctx as never, {});
|
|
128
|
+
assert.equal(typeof handle, 'function');
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test('缺陷 1 回归:ptcRuntime 形状不符只告警、不阻断(tf-code 通道关闭)', () => {
|
|
133
|
+
const { services } = makeServices();
|
|
134
|
+
services['ptcRuntime'] = { notARuntime: true };
|
|
135
|
+
const warnings: string[] = [];
|
|
136
|
+
services['logger'] = { warn: (m: string) => warnings.push(m), error: () => {} };
|
|
137
|
+
const ctx = strictCtx(services, ['llm', 'tools', 'agents', 'sessions']);
|
|
138
|
+
assert.doesNotThrow(() => applyLoop(ctx as never, {}));
|
|
139
|
+
assert.ok(warnings.some((w) => w.includes('ptcRuntime')), '形状不符必须告警,不静默');
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
test('缺陷 2 回归:五个 entry 的返回值都是 Cordis 合法 effect(function / null)', () => {
|
|
143
|
+
const stateDir = mkdtempSync(join(tmpdir(), 'tf-activation-'));
|
|
144
|
+
const { services } = makeServices();
|
|
145
|
+
const handles: unknown[] = [
|
|
146
|
+
applyStateHandle(strictCtx(services, ['storage']) as never, { unit: 'tfAgentState', stateDir, announce: false }),
|
|
147
|
+
applyObsBroker(strictCtx(services, ['tools']) as never, { announce: false }),
|
|
148
|
+
applyActionGate(strictCtx(services, ['tools', 'storage']) as never, { announce: false }),
|
|
149
|
+
applyContextRender(strictCtx(services, []) as never, { announce: false }),
|
|
150
|
+
applyControlBar(strictCtx(services, []) as never, { announce: false, stateDir }),
|
|
151
|
+
];
|
|
152
|
+
for (const handle of handles) {
|
|
153
|
+
assert.equal(typeof handle, 'function', `entry 返回值必须是函数(实际 ${typeof handle})`);
|
|
154
|
+
assert.doesNotThrow(() => (handle as () => void)());
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
test('asPluginEffect:句柄属性照旧可读,调用即执行 dispose', () => {
|
|
159
|
+
let disposed = 0;
|
|
160
|
+
const handle = asPluginEffect({ service: 'x', dispose: () => { disposed += 1; } });
|
|
161
|
+
assert.equal(typeof handle, 'function');
|
|
162
|
+
assert.equal(handle.service, 'x');
|
|
163
|
+
handle();
|
|
164
|
+
assert.equal(disposed, 1);
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
test('asPluginEffect:没有 dispose 字段时调用不抛错', () => {
|
|
168
|
+
const handle = asPluginEffect({ value: 1 });
|
|
169
|
+
assert.equal(handle.value, 1);
|
|
170
|
+
assert.doesNotThrow(() => handle());
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
test('loop entry 兼容老式测试桩(服务直接挂在 ctx 上)', () => {
|
|
174
|
+
const { services, factory } = makeServices();
|
|
175
|
+
// 老桩:没有 get 方法,服务是普通属性
|
|
176
|
+
const plain = { llm: services['llm'], tools: services['tools'], agents: services['agents'] };
|
|
177
|
+
const handle = applyLoop(plain as never, {});
|
|
178
|
+
assert.equal(typeof handle, 'function');
|
|
179
|
+
assert.notEqual(factory(), null);
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
test('版本常量与 package.json 一致(发版口径唯一)', () => {
|
|
183
|
+
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string; bin?: Record<string, string> };
|
|
184
|
+
const source = readFileSync(new URL('../src/version.ts', import.meta.url), 'utf8');
|
|
185
|
+
assert.match(source, new RegExp(`VERSION = '${pkg.version.replace(/\./g, '\\.')}'`), 'src/version.ts 必须与 package.json 同版本');
|
|
186
|
+
assert.ok(pkg.bin?.['dsh-stream-agent'] !== undefined, 'package.json 必须暴露 dsh-stream-agent 命令');
|
|
187
|
+
});
|