@yourstandby/fabric 0.0.0-stage → 0.1.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.
@@ -0,0 +1,167 @@
1
+ /**
2
+ * B 侧执行器适配:把 Fabric 的远程任务接到一次性子会话(spawnSubagent)上。
3
+ *
4
+ * 为什么用子会话而不是唤醒常驻舰队 Agent:
5
+ * 远程任务天然是一次性的(跑完回传结论 + diff 就结束),子会话用完即回收,
6
+ * 并且它的 SessionManager 是 inMemory(不落盘、不与本地会话混在一起)。
7
+ *
8
+ * 权限两条硬约束在这里落地:
9
+ * 1. 工具集只来自档位表(FABRIC_TOOLS_BY_GRANT),对端无法申请额外工具;
10
+ * 2. 工作目录必须由 prepareWorkspace 提供(独立 worktree),绝不直接用本机
11
+ * 用户当前工作区 —— 否则远端任务会搅乱本机正在改的文件。
12
+ */
13
+ import { mkdirSync } from "node:fs";
14
+ import { join } from "node:path";
15
+ import {
16
+ FABRIC_TOOLS_BY_GRANT,
17
+ progressNote,
18
+ type FabricGrant,
19
+ type FabricProgressNote,
20
+ } from "../../../contract/domains/fabric.ts";
21
+ import type { FabricRemoteRunner } from "./dispatcher.ts";
22
+
23
+ export interface FabricSpawnInput {
24
+ name: string;
25
+ task: string;
26
+ cwd: string;
27
+ tools: string[];
28
+ signal: AbortSignal;
29
+ /** 执行器的真实进度(结构化 code + 参数 + 兜底文案),一路透传给发起方。 */
30
+ onProgress: (note: FabricProgressNote) => void;
31
+ }
32
+
33
+ export interface FabricSpawnResult {
34
+ ok: boolean;
35
+ text: string;
36
+ error?: string;
37
+ }
38
+
39
+ export interface FabricWorkspace {
40
+ cwd: string;
41
+ /** 收集改动(worktree 才有):回传成 diff 产物,发起方据此决定合不合。 */
42
+ diff?: () => Promise<Buffer | null>;
43
+ cleanup?: () => Promise<void>;
44
+ }
45
+
46
+ export interface FabricRunnerOptions {
47
+ /** 默认实现走 spawnSubagent;测试注入假实现。 */
48
+ spawn?: (input: FabricSpawnInput) => Promise<FabricSpawnResult>;
49
+ /**
50
+ * 为远程任务准备隔离工作目录(独立 worktree)。不给就拒绝执行——
51
+ * 「在别人正在改的目录里跑远程任务」是这套机制里最贵的错误。
52
+ */
53
+ prepareWorkspace?: (input: { taskId: string; hint: string }) => Promise<FabricWorkspace>;
54
+ /** 回传摘要的字符上限:进 A 的上下文,必须短。 */
55
+ summaryChars?: number;
56
+ log?: (message: string) => void;
57
+ }
58
+
59
+ /** 摘要截断:远程结论是要进对方上下文的,默认 800 字符 ≈ 200 token 上下。 */
60
+ export const FABRIC_SUMMARY_CHARS = 800;
61
+
62
+ export function clampSummary(text: string, limit = FABRIC_SUMMARY_CHARS): string {
63
+ const normalized = text.replace(/\r\n/g, "\n").trim();
64
+ if (normalized.length <= limit) return normalized;
65
+ return `${normalized.slice(0, limit - 1)}…`;
66
+ }
67
+
68
+ /** 从子会话输出里提取「改了哪些文件」:只认相对路径,避免泄露本机绝对路径。 */
69
+ export function extractFiles(text: string, limit = 50): string[] {
70
+ const files = new Set<string>();
71
+ // 只切 ASCII 路径字符:中文标点(,:)自动成为分隔符,不会把前后文粘进来。
72
+ const token = /[A-Za-z0-9_.@\-]+(?:\/[A-Za-z0-9_.@\-]+)+\.[A-Za-z0-9]{1,8}/g;
73
+ for (const match of text.matchAll(token)) {
74
+ const candidate = match[0].replace(/^\.\//, "");
75
+ if (candidate.startsWith("/") || candidate.includes("..")) continue;
76
+ files.add(candidate);
77
+ if (files.size >= limit) break;
78
+ }
79
+ return [...files];
80
+ }
81
+
82
+ export function createSubagentRunner(
83
+ agentDir: string,
84
+ options: FabricRunnerOptions = {},
85
+ ): FabricRemoteRunner {
86
+ const limit = options.summaryChars ?? FABRIC_SUMMARY_CHARS;
87
+ return {
88
+ async run(input) {
89
+ const tools = [...FABRIC_TOOLS_BY_GRANT[input.grant]];
90
+ const prepare = options.prepareWorkspace;
91
+ if (!prepare) {
92
+ throw new Error("E_UNSUPPORTED: no workspace provider (remote task would run in the local cwd)");
93
+ }
94
+ const workspace = await prepare({ taskId: input.taskId, hint: input.workspaceHint });
95
+ input.onProgress(progressNote("workspace_ready", undefined, "已在隔离工作区就绪"));
96
+ try {
97
+ const task = [
98
+ input.prompt,
99
+ "",
100
+ "---",
101
+ "远程派活说明:上面的任务来自另一台已配对机器,请在当前隔离工作区内完成;",
102
+ "结束时用不超过 8 行说明:做了什么、改了哪些文件、有没有风险。",
103
+ ].join("\n");
104
+ const spawn = options.spawn ?? defaultSpawn();
105
+ input.onProgress(progressNote("session_started", undefined, "子会话开始执行"));
106
+ const result = await spawn({
107
+ name: `fabric-${input.taskId.slice(0, 8)}`,
108
+ task,
109
+ cwd: workspace.cwd,
110
+ tools,
111
+ signal: input.signal,
112
+ onProgress: input.onProgress,
113
+ });
114
+ if (!result.ok) {
115
+ throw new Error(result.error || "remote session failed");
116
+ }
117
+ input.onProgress(progressNote("collecting", undefined, "正在收集改动与结论"));
118
+ // 先取 diff 再清理工作区(cleanup 会删掉 worktree)。
119
+ const diff = workspace.diff ? await workspace.diff().catch(() => null) : null;
120
+ return {
121
+ summary: clampSummary(result.text, limit),
122
+ files: extractFiles(result.text),
123
+ exitCode: 0,
124
+ result: Buffer.from(result.text, "utf8"),
125
+ diff,
126
+ };
127
+ } finally {
128
+ await workspace.cleanup?.().catch(() => undefined);
129
+ }
130
+ },
131
+ };
132
+ }
133
+
134
+ /** 默认执行器:动态 import,避免 fabric 模块把 Pi SDK 拖进任何冷启动路径。 */
135
+ function defaultSpawn() {
136
+ return async (input: FabricSpawnInput): Promise<FabricSpawnResult> => {
137
+ const { spawnSubagent } = await import("../../../agent-host/subagents.ts");
138
+ const result = await spawnSubagent({
139
+ name: input.name,
140
+ task: input.task,
141
+ cwd: input.cwd,
142
+ parentSessionId: `fabric-${input.name}`,
143
+ tools: input.tools,
144
+ signal: input.signal,
145
+ // 子会话的真实事件(第几轮 / 正在跑哪个工具)直接透传成远端进度。
146
+ // 子会话的 code 是字符串;fabric 侧只认白名单内的代码,未知的当兜底文案。
147
+ onProgress: (note) =>
148
+ input.onProgress({
149
+ code: note.code as FabricProgressNote["code"],
150
+ ...(note.params ? { params: note.params } : {}),
151
+ text: note.text,
152
+ }),
153
+ });
154
+ return { ok: result.ok, text: result.text, error: result.error };
155
+ };
156
+ }
157
+
158
+ /** 兜底工作区:<agentDir>/fabric/worktrees/<taskId>,只保证“不在用户工作区里”。 */
159
+ export function createScratchWorkspaceProvider(agentDir: string) {
160
+ return async (input: { taskId: string; hint: string }): Promise<FabricWorkspace> => {
161
+ const cwd = join(agentDir, "fabric", "worktrees", input.taskId);
162
+ mkdirSync(cwd, { recursive: true });
163
+ return { cwd };
164
+ };
165
+ }
166
+
167
+ export type { FabricGrant };
@@ -0,0 +1,74 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import {
4
+ PEER_MAX_QUEUE,
5
+ REMOTE_MIN_ESTIMATE_MS,
6
+ choosePeer,
7
+ describeChoice,
8
+ scorePeer,
9
+ } from "./dispatch.ts";
10
+
11
+ function peer(overrides: Record<string, unknown> = {}) {
12
+ return {
13
+ nodeId: "0123456789abcdef",
14
+ name: "机-A",
15
+ online: true,
16
+ hbAgeMs: 500,
17
+ queueDepth: 0,
18
+ labels: ["build"],
19
+ grants: "workspace-rw+bash" as const,
20
+ cpuLoad: 0.1,
21
+ historyP50Ms: 120_000,
22
+ ...overrides,
23
+ };
24
+ }
25
+
26
+ const need = { labels: ["build"], estimatedMs: REMOTE_MIN_ESTIMATE_MS };
27
+
28
+ test("打分:队列最贵,负载次之,历史耗时再次", () => {
29
+ const idle = peer({ queueDepth: 0, cpuLoad: 0.9, historyP50Ms: 900_000 });
30
+ const busy = peer({ queueDepth: PEER_MAX_QUEUE, cpuLoad: 0.01, historyP50Ms: 60_000 });
31
+ assert.ok(scorePeer(idle) < scorePeer(busy));
32
+ const slowCpu = peer({ cpuLoad: 0.8, historyP50Ms: 60_000 });
33
+ const fastCpu = peer({ cpuLoad: 0.1, historyP50Ms: 60_000 });
34
+ assert.ok(scorePeer(fastCpu) < scorePeer(slowCpu));
35
+ const veteran = peer({ cpuLoad: 0.1, historyP50Ms: 60_000 });
36
+ const rookie = peer({ cpuLoad: 0.1, historyP50Ms: null });
37
+ assert.ok(scorePeer(veteran) < scorePeer(rookie));
38
+ });
39
+
40
+ test("没上报负载按中性算,不会被当成最闲也不会被罚死", () => {
41
+ const unknown = scorePeer(peer({ cpuLoad: null }));
42
+ const neutral = scorePeer(peer({ cpuLoad: 0.5 }));
43
+ assert.equal(unknown, neutral);
44
+ });
45
+
46
+ test("队列没超过上限仍然可派;超了才报忙", () => {
47
+ const withinLimit = choosePeer([peer({ queueDepth: PEER_MAX_QUEUE })], need);
48
+ assert.equal(withinLimit.ok, true);
49
+ const overLimit = choosePeer([peer({ queueDepth: PEER_MAX_QUEUE + 1 })], need);
50
+ assert.equal(overLimit.ok === false && overLimit.code, "E_PEER_BUSY");
51
+ });
52
+
53
+ test("钉住的机器直接选中,哪怕它更忙、更慢", () => {
54
+ const pinned = peer({ nodeId: "aaaaaaaaaaaaaaaa", name: "钉住的", queueDepth: PEER_MAX_QUEUE, cpuLoad: 0.95 });
55
+ const better = peer({ nodeId: "bbbbbbbbbbbbbbbb", name: "更闲的", queueDepth: 0 });
56
+ const decision = choosePeer([pinned, better], { ...need, pin: "aaaaaaaaaaaaaaaa" });
57
+ assert.equal(decision.ok, true);
58
+ assert.equal(decision.ok === true && decision.peerId, "aaaaaaaaaaaaaaaa");
59
+ });
60
+
61
+ test("钉住的机器不可用(离线/缺标签)时回落到打分,不硬失败", () => {
62
+ const offline = peer({ nodeId: "aaaaaaaaaaaaaaaa", online: false });
63
+ const better = peer({ nodeId: "bbbbbbbbbbbbbbbb", name: "更闲的" });
64
+ const decision = choosePeer([offline, better], { ...need, pin: "aaaaaaaaaaaaaaaa" });
65
+ assert.equal(decision.ok, true);
66
+ assert.equal(decision.ok === true && decision.peerId, "bbbbbbbbbbbbbbbb");
67
+ });
68
+
69
+ test("理由是人话,带队列与负载", () => {
70
+ const reason = describeChoice(peer({ name: "机-B", queueDepth: 1, cpuLoad: 0.25 }), 123);
71
+ assert.match(reason, /机-B/);
72
+ assert.match(reason, /队列 1/);
73
+ assert.match(reason, /负载 25%/);
74
+ });
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Fabric TCP 监听:把「另一台机器」当作一个新的字节流来源,协议不变。
3
+ *
4
+ * 只监听显式传入的 host(默认 0.0.0.0,跨机必需);未配对的 nodeId 一律在握手阶段拒绝,
5
+ * 不会走到任何方法分发。
6
+ */
7
+ import { createServer, type Server } from "node:net";
8
+ import { FABRIC_DEFAULT_PORT } from "../../../contract/domains/fabric.ts";
9
+ import {
10
+ acceptFabricLink,
11
+ type FabricCaller,
12
+ type FabricLink,
13
+ type PairRequestInfo,
14
+ } from "./transport.ts";
15
+ import type { FabricIdentity } from "./pairing.ts";
16
+
17
+ export interface FabricListenerOptions {
18
+ identity: FabricIdentity;
19
+ isPaired: (nodeId: string) => boolean;
20
+ onCall: (method: string, params: Record<string, unknown>, caller: FabricCaller) => Promise<unknown>;
21
+ host?: string;
22
+ port?: number;
23
+ appVersion?: string;
24
+ log?: (message: string) => void;
25
+ /** 未配对对端的配对请求入口;给了它才允许受限会话(只收 pair.request)。 */
26
+ onPairRequest?: (info: PairRequestInfo) => Promise<unknown>;
27
+ /** 受限会话上额外放行的方法(目前只有 peer.status)。 */
28
+ onRestrictedCall?: (
29
+ method: string,
30
+ params: Record<string, unknown>,
31
+ caller: FabricCaller,
32
+ ) => Promise<unknown>;
33
+ /** 连接建立/关闭时通知上层(用于维护「在线机器」列表与负载)。 */
34
+ onLink?: (link: FabricLink) => void;
35
+ onLinkClosed?: (nodeId: string) => void;
36
+ }
37
+
38
+ export interface FabricListener {
39
+ port: number;
40
+ host: string;
41
+ close(): Promise<void>;
42
+ peers(): string[];
43
+ /** 把事件推给某台机器的入站连接;没连上就返回 false(调用方按「等对账」处理)。 */
44
+ publish(nodeId: string, frame: Record<string, unknown>): boolean;
45
+ }
46
+
47
+ export async function startFabricListener(options: FabricListenerOptions): Promise<FabricListener> {
48
+ const host = options.host ?? "0.0.0.0";
49
+ const port = options.port ?? FABRIC_DEFAULT_PORT;
50
+ const links = new Map<string, FabricLink>();
51
+ const server: Server = createServer((socket) => {
52
+ socket.setNoDelay(true);
53
+ void acceptFabricLink({
54
+ socket,
55
+ identity: options.identity,
56
+ isPaired: options.isPaired,
57
+ onPairRequest: options.onPairRequest,
58
+ onRestrictedCall: options.onRestrictedCall,
59
+ onCall: options.onCall,
60
+ appVersion: options.appVersion,
61
+ log: options.log,
62
+ })
63
+ .then((link) => {
64
+ links.set(link.nodeId, link);
65
+ options.onLink?.(link);
66
+ options.log?.(`fabric inbound link up: ${link.nodeId} (${link.features.join(",")})`);
67
+ })
68
+ .catch((error: unknown) => {
69
+ options.log?.(
70
+ `fabric inbound handshake rejected: ${error instanceof Error ? error.message : String(error)}`,
71
+ );
72
+ });
73
+ });
74
+ await new Promise<void>((resolve, reject) => {
75
+ server.once("error", reject);
76
+ server.listen(port, host, () => {
77
+ server.removeListener("error", reject);
78
+ resolve();
79
+ });
80
+ });
81
+ const address = server.address();
82
+ const actualPort = typeof address === "object" && address ? address.port : port;
83
+ return {
84
+ port: actualPort,
85
+ host,
86
+ peers: () => [...links.keys()],
87
+ publish(nodeId, frame) {
88
+ const link = links.get(nodeId);
89
+ if (!link || !link.connected) return false;
90
+ // 帧类型与事件类型必须分两层:展开会把 type 覆盖成 task_done,接收端就不再认它是事件。
91
+ link.send({ type: "event", event: frame });
92
+ return true;
93
+ },
94
+ close: () =>
95
+ new Promise<void>((resolve) => {
96
+ for (const link of links.values()) link.close();
97
+ links.clear();
98
+ server.close(() => resolve());
99
+ }),
100
+ };
101
+ }
@@ -0,0 +1,279 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { mkdtempSync, rmSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { FabricService } from "./fabric-service.ts";
7
+ import { getPeer } from "./peer-store.ts";
8
+
9
+ function tempDir(): { dir: string; cleanup: () => void } {
10
+ const dir = mkdtempSync(join(tmpdir(), "pi-fabric-service-"));
11
+ return { dir, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
12
+ }
13
+
14
+ function pairWith(target: FabricService, peer: FabricService, name: string) {
15
+ return target.pair({
16
+ nodeId: peer.nodeId,
17
+ publicKey: peer.identity.publicKey,
18
+ name,
19
+ address: "127.0.0.1",
20
+ port: peer.port,
21
+ grants: "workspace-rw+bash",
22
+ });
23
+ }
24
+
25
+ test("对端回传的 patch 要能拉回来:fetchDiff 先本地后对端,且落库后 diffFor 可读", async () => {
26
+ const a = tempDir();
27
+ const b = tempDir();
28
+ const patch = Buffer.from("diff --git a/changed.txt b/changed.txt\n+hello\n", "utf8");
29
+ const svcA = new FabricService({ agentDir: a.dir, host: "127.0.0.1", port: 0, ctx: `diff-${process.pid}-a` });
30
+ const svcB = new FabricService({
31
+ agentDir: b.dir,
32
+ host: "127.0.0.1",
33
+ port: 0,
34
+ ctx: `diff-${process.pid}-b`,
35
+ runner: {
36
+ async run() {
37
+ return {
38
+ summary: "改好了 changed.txt",
39
+ files: ["changed.txt"],
40
+ exitCode: 0,
41
+ result: Buffer.from("ok"),
42
+ diff: patch,
43
+ };
44
+ },
45
+ },
46
+ });
47
+ await svcA.start();
48
+ await svcB.start();
49
+ try {
50
+ pairWith(svcB, svcA, "A");
51
+ pairWith(svcA, svcB, "B");
52
+ const submitted = await svcA.dispatch({ prompt: "改一下 changed.txt", estimatedMs: 120_000, deadlineClass: "build" });
53
+ assert.equal(submitted.ok, true);
54
+ if (!submitted.ok) return;
55
+ const taskId = submitted.taskId;
56
+ // 对端跑完 -> 本机对账拿回 done(推送可能还没到,reconcile 是权威路径)。
57
+ await waitFor(() => svcB.inbound.get(taskId)?.state === "done", 5_000);
58
+ await svcA.reconcile();
59
+ // 关键点:patch 是对端产物,本机原先没有;不拉一次就只有 null。
60
+ const diff = await svcA.fetchDiff(taskId);
61
+ assert.ok(diff, "应该能取到对端回传的 patch");
62
+ assert.match(diff?.text ?? "", /changed\.txt/);
63
+ } finally {
64
+ await svcA.stop();
65
+ await svcB.stop();
66
+ a.cleanup();
67
+ b.cleanup();
68
+ }
69
+ });
70
+
71
+ test("急停:停发现、断全部连接、每台机器档位降回 read-only", async () => {
72
+ const a = tempDir();
73
+ const b = tempDir();
74
+ const svcA = new FabricService({ agentDir: a.dir, host: "127.0.0.1", port: 0, ctx: `panic-${process.pid}-a` });
75
+ const svcB = new FabricService({ agentDir: b.dir, host: "127.0.0.1", port: 0, ctx: `panic-${process.pid}-b` });
76
+ await svcA.start();
77
+ await svcB.start();
78
+ try {
79
+ pairWith(svcB, svcA, "A");
80
+ assert.equal(getPeer(b.dir, svcA.nodeId)?.grants, "workspace-rw+bash");
81
+ svcB.setDiscoverable(true);
82
+ const result = svcB.panic();
83
+ assert.equal(result.peers, 1);
84
+ // 降档必须落盘:只在内存里改,下一次重启就等于什么都没发生。
85
+ assert.equal(getPeer(b.dir, svcA.nodeId)?.grants, "read-only");
86
+ assert.equal(svcB.isDiscoverable(), false);
87
+ } finally {
88
+ await svcA.stop();
89
+ await svcB.stop();
90
+ a.cleanup();
91
+ b.cleanup();
92
+ }
93
+ });
94
+
95
+ test("两台机器:配对 -> 自动发现空闲机器 -> 派活 -> 结果回流", async () => {
96
+ const a = tempDir();
97
+ const b = tempDir();
98
+ const seen: string[] = [];
99
+ const svcA = new FabricService({
100
+ agentDir: a.dir,
101
+ host: "127.0.0.1",
102
+ port: 0,
103
+ ctx: `ctx-${process.pid}-a`,
104
+ });
105
+ const svcB = new FabricService({
106
+ agentDir: b.dir,
107
+ host: "127.0.0.1",
108
+ port: 0,
109
+ ctx: `ctx-${process.pid}-b`,
110
+ labels: () => ["build"],
111
+ runner: {
112
+ async run(input) {
113
+ seen.push(input.prompt);
114
+ return { summary: "build ok", files: ["out/app.js"], exitCode: 0, result: Buffer.from("artifact") };
115
+ },
116
+ },
117
+ });
118
+ try {
119
+ await svcA.start();
120
+ await svcB.start();
121
+
122
+ const pairA = pairWith(svcA, svcB, "机-B");
123
+ const pairB = pairWith(svcB, svcA, "机-A");
124
+ assert.equal(pairA.ok, true);
125
+ assert.equal(pairB.ok, true);
126
+ // 两端算出的 SAS 必须一致,否则用户看到两个不同的数字
127
+ assert.equal(pairA.ok === true && pairA.ok ? pairA.sas : "", pairB.ok === true && pairB.ok ? pairB.sas : "");
128
+
129
+ const dispatched = await svcA.dispatch({
130
+ prompt: "在这台机器上跑完整构建",
131
+ labels: ["build"],
132
+ estimatedMs: 300_000,
133
+ deadlineClass: "build",
134
+ input: Buffer.from("上下文"),
135
+ workspaceHint: "yourstandby",
136
+ });
137
+ assert.equal(dispatched.ok, true);
138
+ if (!dispatched.ok) return;
139
+ assert.equal(dispatched.peerId, svcB.nodeId);
140
+
141
+ await waitFor(() => svcB.inbound.get(dispatched.taskId)?.state === "done", 5_000);
142
+ assert.deepEqual(seen, ["在这台机器上跑完整构建"]);
143
+
144
+ const reconciled = await svcA.reconcile();
145
+ assert.deepEqual(reconciled.done, [dispatched.taskId]);
146
+ const record = svcA.outbound.get(dispatched.taskId);
147
+ assert.equal(record?.state, "done");
148
+ assert.equal(record?.summary, "build ok");
149
+ assert.deepEqual(record?.files, ["out/app.js"]);
150
+ assert.ok(record?.resultRef);
151
+ assert.equal(svcA.artifacts.read(record!.resultRef!).toString(), "artifact");
152
+
153
+ const rows = svcA.peerRows();
154
+ assert.equal(rows.length, 1);
155
+ assert.equal(rows[0].online, true);
156
+ assert.deepEqual(rows[0].labels, ["build"]);
157
+ assert.equal(rows[0].queueDepth, 0);
158
+ } finally {
159
+ await svcA.stop();
160
+ await svcB.stop();
161
+ a.cleanup();
162
+ b.cleanup();
163
+ }
164
+ });
165
+
166
+ test("没配对的机器:派活直接说「还没有已配对机器」,不会打洞连过去", async () => {
167
+ const a = tempDir();
168
+ const b = tempDir();
169
+ const svcA = new FabricService({ agentDir: a.dir, host: "127.0.0.1", port: 0, ctx: `x-${process.pid}` });
170
+ const svcB = new FabricService({ agentDir: b.dir, host: "127.0.0.1", port: 0, ctx: `y-${process.pid}` });
171
+ try {
172
+ await svcA.start();
173
+ await svcB.start();
174
+ const result = await svcA.dispatch({ prompt: "干活", estimatedMs: 120_000, deadlineClass: "build" });
175
+ assert.equal(result.ok, false);
176
+ assert.equal(result.ok === false && result.code, "E_NO_PEERS");
177
+ assert.equal(svcB.snapshot().peers.length, 0);
178
+ } finally {
179
+ await svcA.stop();
180
+ await svcB.stop();
181
+ a.cleanup();
182
+ b.cleanup();
183
+ }
184
+ });
185
+
186
+ test("配对 SAS 不符就拒绝,且不写任何 peer 记录", async () => {
187
+ const a = tempDir();
188
+ const b = tempDir();
189
+ const svcA = new FabricService({ agentDir: a.dir, host: "127.0.0.1", port: 0, ctx: `s-${process.pid}` });
190
+ const svcB = new FabricService({ agentDir: b.dir, host: "127.0.0.1", port: 0, ctx: `t-${process.pid}` });
191
+ try {
192
+ await svcA.start();
193
+ await svcB.start();
194
+ // 先正常配一次拿到真实 SAS(点击确认、不比码也能成),再解绑,用错的码重试。
195
+ const ok = pairWith(svcA, svcB, "机-B");
196
+ assert.equal(ok.ok, true);
197
+ const realSas = ok.ok ? ok.sas : "";
198
+ assert.match(realSas, /^\d{6}$/);
199
+ svcA.unpair(svcB.nodeId);
200
+ const flipped = realSas.slice(0, 5) + String((Number(realSas[5]) + 1) % 10);
201
+ const bad = svcA.pair({
202
+ nodeId: svcB.nodeId,
203
+ publicKey: svcB.identity.publicKey,
204
+ name: "机-B",
205
+ address: "127.0.0.1",
206
+ port: svcB.port,
207
+ grants: "read-only",
208
+ sas: flipped,
209
+ });
210
+ assert.equal(bad.ok, false);
211
+ assert.equal(bad.ok === false && (bad.code === "E_PAIR_SAS_MISMATCH" || bad.code === "E_PAIR_LOCKED"), true);
212
+ assert.equal(svcA.snapshot().peers.length, 0);
213
+ assert.equal(svcA.pendingSas(), null);
214
+ } finally {
215
+ await svcA.stop();
216
+ await svcB.stop();
217
+ a.cleanup();
218
+ b.cleanup();
219
+ }
220
+ });
221
+
222
+ test("sweep 清理不碰正在用的产物与未终态任务", async () => {
223
+ const a = tempDir();
224
+ const svc = new FabricService({ agentDir: a.dir, host: "127.0.0.1", port: 0, ctx: `w-${process.pid}` });
225
+ try {
226
+ const ref = svc.artifacts.put(Buffer.from("keep me"), "input");
227
+ svc.outbound.create({
228
+ taskId: "aaaaaaaaaaaaaaaa",
229
+ peerId: "0123456789abcdef",
230
+ deadlineClass: "long",
231
+ inputRef: ref,
232
+ now: Date.now(),
233
+ });
234
+ const day = 24 * 60 * 60 * 1000;
235
+ const swept = svc.sweep(Date.now() + 2 * day);
236
+ assert.equal(swept.artifacts, 0);
237
+ assert.equal(svc.artifacts.has(ref.sha256), true);
238
+ assert.equal(swept.tasks, 0);
239
+ } finally {
240
+ a.cleanup();
241
+ }
242
+ });
243
+
244
+ async function waitFor(predicate: () => boolean, timeoutMs: number): Promise<void> {
245
+ const startedAt = Date.now();
246
+ while (!predicate()) {
247
+ if (Date.now() - startedAt > timeoutMs) throw new Error("condition not met in time");
248
+ await new Promise((resolve) => setTimeout(resolve, 20));
249
+ }
250
+ }
251
+
252
+ test("diffFor:有 diffRef 就返回文本,超上限截断并标记;没有就返回 null", async () => {
253
+ const dir = mkdtempSync(join(tmpdir(), "pi-fabric-diff-"));
254
+ const svc = new FabricService({ agentDir: dir, host: "127.0.0.1", port: 0, ctx: `df-${process.pid}` });
255
+ try {
256
+ const patch = Buffer.from("diff --git a/x b/x\n+hello\n", "utf8");
257
+ const diffRef = svc.artifacts.put(patch, "diff");
258
+ svc.outbound.create({
259
+ taskId: "aaaaaaaaaaaaaaaa",
260
+ peerId: "0123456789abcdef",
261
+ deadlineClass: "build",
262
+ now: Date.now(),
263
+ });
264
+ svc.outbound.update("aaaaaaaaaaaaaaaa", { state: "done", diffRef, files: ["x"] });
265
+ const preview = svc.diffFor("aaaaaaaaaaaaaaaa");
266
+ assert.equal(preview?.text, patch.toString("utf8"));
267
+ assert.equal(preview?.truncated, false);
268
+ assert.deepEqual(preview?.files, ["x"]);
269
+
270
+ const small = svc.diffFor("aaaaaaaaaaaaaaaa", 10);
271
+ assert.equal(small?.truncated, true);
272
+ assert.equal(small?.bytes, patch.length);
273
+
274
+ assert.equal(svc.diffFor("bbbbbbbbbbbbbbbb"), null);
275
+ } finally {
276
+ rmSync(dir, { recursive: true, force: true });
277
+ }
278
+ });
279
+