@yourstandby/fabric 0.0.0-stage → 0.1.0

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,118 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { buildPeerRows, buildTaskRows, formatRelative, summarize } from "./fabric-view.ts";
4
+ import type { FabricPeer } from "../../../contract/domains/fabric.ts";
5
+ import type { TaskRecord } from "./dispatch.ts";
6
+
7
+ const NOW = 1_700_000_000_000;
8
+
9
+ function peer(overrides: Partial<FabricPeer> = {}): FabricPeer {
10
+ return {
11
+ nodeId: "0123456789abcdef",
12
+ name: "机-B",
13
+ address: "192.168.1.20",
14
+ port: 7788,
15
+ grants: "workspace-rw+bash",
16
+ features: ["fabric.task.v1"],
17
+ appVersion: "0.12.5",
18
+ pairedAt: NOW - 60_000,
19
+ createdAt: NOW - 60_000,
20
+ updatedAt: NOW - 60_000,
21
+ lastSeenAt: NOW - 120_000,
22
+ ...overrides,
23
+ };
24
+ }
25
+
26
+ function task(overrides: Partial<TaskRecord> = {}): TaskRecord {
27
+ return {
28
+ taskId: "aaaaaaaaaaaaaaaa",
29
+ direction: "outbound",
30
+ peerId: "0123456789abcdef",
31
+ state: "running",
32
+ deadlineClass: "build",
33
+ deadlineAt: NOW + 600_000,
34
+ createdAt: NOW - 60_000,
35
+ updatedAt: NOW - 30_000,
36
+ startedAt: NOW - 50_000,
37
+ finishedAt: null,
38
+ inputRef: null,
39
+ resultRef: null,
40
+ diffRef: null,
41
+ workspaceHint: "",
42
+ summary: "",
43
+ progress: "",
44
+ progressCode: "",
45
+ progressParams: null,
46
+ progressAt: null,
47
+ files: [],
48
+ exitCode: null,
49
+ error: null,
50
+ pid: null,
51
+ ...overrides,
52
+ };
53
+ }
54
+
55
+ test("在线判定用 5s 心跳阈值,和选机规则保持一致", () => {
56
+ const rows = buildPeerRows(
57
+ [peer()],
58
+ [{ nodeId: "0123456789abcdef", online: true, queueDepth: 0, hbAgeMs: 4_999, labels: ["build"] }],
59
+ NOW,
60
+ );
61
+ assert.equal(rows[0].online, true);
62
+ const stale = buildPeerRows(
63
+ [peer()],
64
+ [{ nodeId: "0123456789abcdef", online: true, queueDepth: 0, hbAgeMs: 5_001, labels: [] }],
65
+ NOW,
66
+ );
67
+ assert.equal(stale[0].online, false);
68
+ const missing = buildPeerRows([peer()], [], NOW);
69
+ assert.equal(missing[0].online, false);
70
+ assert.equal(missing[0].queueDepth, null);
71
+ });
72
+
73
+ test("档位给到人话说法,未知档位降为只读", () => {
74
+ const rows = buildPeerRows([peer({ grants: "unknown" as never })], [], NOW);
75
+ assert.equal(rows[0].grants, "read-only");
76
+ assert.equal(rows[0].grantsLabel, "只读");
77
+ assert.equal(rows[0].endpoint, "192.168.1.20:7788");
78
+ assert.equal(rows[0].shortId, "012345");
79
+ });
80
+
81
+ test("任务行:剩余时间、超时标记、终态不再倒计时", () => {
82
+ const rows = buildTaskRows([task()], NOW);
83
+ assert.equal(rows[0].remainingMs, 600_000);
84
+ assert.equal(rows[0].overdue, false);
85
+ assert.equal(rows[0].stateLabel, "执行中");
86
+
87
+ const overdue = buildTaskRows([task({ deadlineAt: NOW - 1 })], NOW);
88
+ assert.equal(overdue[0].overdue, true);
89
+ assert.equal(overdue[0].remainingMs, 0);
90
+
91
+ const done = buildTaskRows([task({ state: "done", finishedAt: NOW - 1 })], NOW);
92
+ assert.equal(done[0].remainingMs, null);
93
+ assert.equal(done[0].overdue, false);
94
+ assert.equal(done[0].stateLabel, "已完成");
95
+ });
96
+
97
+ test("相对时间:秒/分/时/天,从未见过显示 —", () => {
98
+ assert.equal(formatRelative(null, NOW), "—");
99
+ assert.equal(formatRelative(NOW - 3_000, NOW), "3 秒前");
100
+ assert.equal(formatRelative(NOW - 5 * 60_000, NOW), "5 分钟前");
101
+ assert.equal(formatRelative(NOW - 3 * 3_600_000, NOW), "3 小时前");
102
+ assert.equal(formatRelative(NOW - 2 * 86_400_000, NOW), "2 天前");
103
+ assert.equal(formatRelative(NOW + 5_000, NOW), "刚刚");
104
+ });
105
+
106
+ test("汇总:在线数、在跑数、需要人管的数", () => {
107
+ const peerRows = buildPeerRows(
108
+ [peer(), peer({ nodeId: "fedcba9876543210", name: "机-C" })],
109
+ [{ nodeId: "0123456789abcdef", online: true, queueDepth: 0, hbAgeMs: 100, labels: [] }],
110
+ NOW,
111
+ );
112
+ const taskRows = buildTaskRows(
113
+ [task(), task({ taskId: "bbbbbbbbbbbbbbbb", state: "failed" }), task({ taskId: "cccccccccccccccc", deadlineAt: NOW - 5 })],
114
+ NOW,
115
+ );
116
+ // running 把「已接收 + 执行中」都算上:面板上它们都还在跑;第三个超时任务也仍在 running 态。
117
+ assert.deepEqual(summarize(peerRows, taskRows), { peers: 2, online: 1, running: 2, needsAttention: 2 });
118
+ });
@@ -0,0 +1,182 @@
1
+ /**
2
+ * 机器面板的视图模型:把 snapshot 变成「一行一台机器 + 一个任务列表」。
3
+ *
4
+ * 单独放一层是因为 UI 只管画:在线判定、档位措辞、时间格式、超时标记都在这里定死,
5
+ * 面板组件里不再出现业务判断(那些判断一旦漂移,同一台机器会在两处显示不同状态)。
6
+ */
7
+ import {
8
+ FABRIC_DEADLINE_MS,
9
+ FABRIC_GRANTS,
10
+ type FabricGrant,
11
+ type FabricPeer,
12
+ } from "../../../contract/domains/fabric.ts";
13
+ import { isTerminalState, type TaskRecord } from "./dispatch.ts";
14
+ import type { PeerLoad } from "./dispatcher.ts";
15
+
16
+ /** 心跳超过这个年龄就显示「离线」:与选机规则 PEER_ONLINE_HB_MS 保持一致。 */
17
+ export const PEER_STALE_MS = 5_000;
18
+
19
+ export interface FabricPeerRowView {
20
+ nodeId: string;
21
+ /** 显示用短 id:前 6 位,够区分又不会把面板撑破。 */
22
+ shortId: string;
23
+ name: string;
24
+ address: string;
25
+ port: number;
26
+ endpoint: string;
27
+ grants: FabricGrant;
28
+ /** 档位的人话说法(面板直接展示,不需要 UI 再翻译)。 */
29
+ grantsLabel: string;
30
+ labels: string[];
31
+ appVersion: string;
32
+ online: boolean;
33
+ queueDepth: number | null;
34
+ /** 上次见到它的相对时间,例如 "3 分钟前";从未见过是 "—"。 */
35
+ lastSeen: string;
36
+ }
37
+
38
+ export interface FabricTaskRowView {
39
+ taskId: string;
40
+ peerId: string;
41
+ shortPeerId: string;
42
+ state: TaskRecord["state"];
43
+ stateLabel: string;
44
+ deadlineClass: TaskRecord["deadlineClass"];
45
+ deadlineLabel: string;
46
+ /** 剩余时间(ms);已终态为 null。 */
47
+ remainingMs: number | null;
48
+ /** 已经超过 deadline 但还没对账:面板要显示「等对账」而不是「失败」。 */
49
+ overdue: boolean;
50
+ summary: string;
51
+ /** running 期间的最近进度(终态后保留最后一次)。 */
52
+ progress: string;
53
+ /** 结构化代码与参数:面板按自己的语言渲染。 */
54
+ progressCode: string;
55
+ progressParams: Record<string, string | number> | null;
56
+ progressLabel: string;
57
+ files: string[];
58
+ updatedAt: number;
59
+ updatedLabel: string;
60
+ }
61
+
62
+ const GRANT_LABELS: Record<FabricGrant, string> = {
63
+ "read-only": "只读",
64
+ "workspace-rw": "可读写工作区",
65
+ "workspace-rw+bash": "可读写 + 执行命令",
66
+ };
67
+
68
+ const STATE_LABELS: Record<TaskRecord["state"], string> = {
69
+ submitted: "已投递",
70
+ accepted: "对方已接收",
71
+ running: "执行中",
72
+ done: "已完成",
73
+ failed: "失败",
74
+ lost: "失联(等对账)",
75
+ cancelled: "已取消",
76
+ };
77
+
78
+ const DEADLINE_LABELS: Record<TaskRecord["deadlineClass"], string> = {
79
+ quick: "短任务",
80
+ build: "构建类",
81
+ long: "长任务",
82
+ };
83
+
84
+ export function formatRelative(then: number | null, now: number): string {
85
+ if (then === null) return "—";
86
+ const delta = now - then;
87
+ if (delta < 0) return "刚刚";
88
+ if (delta < 60_000) return `${Math.max(1, Math.round(delta / 1000))} 秒前`;
89
+ if (delta < 3_600_000) return `${Math.round(delta / 60_000)} 分钟前`;
90
+ if (delta < 86_400_000) return `${Math.round(delta / 3_600_000)} 小时前`;
91
+ return `${Math.round(delta / 86_400_000)} 天前`;
92
+ }
93
+
94
+ export function sanitizeGrantForView(raw: unknown): FabricGrant {
95
+ return typeof raw === "string" && (FABRIC_GRANTS as readonly string[]).includes(raw)
96
+ ? (raw as FabricGrant)
97
+ : "read-only";
98
+ }
99
+
100
+ export function buildPeerRows(
101
+ peers: readonly FabricPeer[],
102
+ loads: readonly PeerLoad[],
103
+ now = Date.now(),
104
+ ): FabricPeerRowView[] {
105
+ const byId = new Map(loads.map((load) => [load.nodeId, load]));
106
+ return peers
107
+ .slice()
108
+ .sort((a, b) => a.name.localeCompare(b.name))
109
+ .map((peer) => {
110
+ const load = byId.get(peer.nodeId);
111
+ const fresh =
112
+ load?.online === true && load.hbAgeMs !== null && load.hbAgeMs <= PEER_STALE_MS;
113
+ const grants = sanitizeGrantForView(peer.grants);
114
+ return {
115
+ nodeId: peer.nodeId,
116
+ shortId: peer.nodeId.slice(0, 6),
117
+ name: peer.name,
118
+ address: peer.address,
119
+ port: peer.port,
120
+ endpoint: `${peer.address}:${peer.port}`,
121
+ grants,
122
+ grantsLabel: GRANT_LABELS[grants],
123
+ labels: [...(load?.labels ?? [])],
124
+ appVersion: peer.appVersion,
125
+ online: fresh,
126
+ queueDepth: load?.queueDepth ?? null,
127
+ lastSeen: formatRelative(peer.lastSeenAt, now),
128
+ };
129
+ });
130
+ }
131
+
132
+ export function buildTaskRows(tasks: readonly TaskRecord[], now = Date.now()): FabricTaskRowView[] {
133
+ return tasks
134
+ .slice()
135
+ .sort((a, b) => b.updatedAt - a.updatedAt)
136
+ .map((task) => {
137
+ const terminal = isTerminalState(task.state);
138
+ const remainingMs = terminal ? null : Math.max(0, task.deadlineAt - now);
139
+ return {
140
+ taskId: task.taskId,
141
+ peerId: task.peerId,
142
+ shortPeerId: task.peerId.slice(0, 6),
143
+ state: task.state,
144
+ stateLabel: STATE_LABELS[task.state] ?? task.state,
145
+ deadlineClass: task.deadlineClass,
146
+ deadlineLabel: DEADLINE_LABELS[task.deadlineClass] ?? task.deadlineClass,
147
+ remainingMs,
148
+ overdue: !terminal && now > task.deadlineAt,
149
+ summary: task.summary,
150
+ progress: task.progress,
151
+ progressCode: task.progressCode,
152
+ progressParams: task.progressParams,
153
+ progressLabel:
154
+ task.progress && !terminal && task.progressAt !== null
155
+ ? `${task.progress} · ${formatRelative(task.progressAt, now)}`
156
+ : task.progress,
157
+ files: [...task.files],
158
+ updatedAt: task.updatedAt,
159
+ updatedLabel: formatRelative(task.updatedAt, now),
160
+ };
161
+ });
162
+ }
163
+
164
+ /** 面板顶部的汇总:在线几台、跑着几个、失败的要不要人管。 */
165
+ export function summarize(
166
+ peerRows: readonly FabricPeerRowView[],
167
+ taskRows: readonly FabricTaskRowView[],
168
+ ): { online: number; peers: number; running: number; needsAttention: number } {
169
+ return {
170
+ peers: peerRows.length,
171
+ online: peerRows.filter((row) => row.online).length,
172
+ running: taskRows.filter((row) => row.state === "running" || row.state === "accepted").length,
173
+ needsAttention: taskRows.filter((row) => row.state === "failed" || row.overdue).length,
174
+ };
175
+ }
176
+
177
+ export function deadlineSummary(): { className: TaskRecord["deadlineClass"]; ms: number }[] {
178
+ return (Object.keys(FABRIC_DEADLINE_MS) as TaskRecord["deadlineClass"][]).map((className) => ({
179
+ className,
180
+ ms: FABRIC_DEADLINE_MS[className],
181
+ }));
182
+ }
@@ -0,0 +1,139 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { execFileSync } from "node:child_process";
4
+ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { basename, join } from "node:path";
7
+ import {
8
+ cleanGitEnv,
9
+ createGitWorktreeProvider,
10
+ describeWorkspace,
11
+ ensureRepoForUrl,
12
+ isGitUrl,
13
+ repoCachePath,
14
+ resolveRepoRoot,
15
+ } from "./fabric-worktree.ts";
16
+ import { createSubagentRunner } from "./fabric-runner.ts";
17
+
18
+ function initRepo(): string {
19
+ const repo = mkdtempSync(join(tmpdir(), "pi-fabric-repo-"));
20
+ execFileSync("git", ["init", "-q", repo], { windowsHide: true, env: cleanGitEnv() });
21
+ execFileSync("git", ["-C", repo, "config", "user.email", "t@example.com"], { windowsHide: true, env: cleanGitEnv() });
22
+ execFileSync("git", ["-C", repo, "config", "user.name", "t"], { windowsHide: true, env: cleanGitEnv() });
23
+ writeFileSync(join(repo, "a.txt"), "one\n", "utf8");
24
+ execFileSync("git", ["-C", repo, "add", "-A"], { windowsHide: true, env: cleanGitEnv() });
25
+ execFileSync("git", ["-C", repo, "commit", "-qm", "init"], { windowsHide: true, env: cleanGitEnv() });
26
+ return repo;
27
+ }
28
+
29
+ test("不是 git 仓库时退回普通目录,不阻断任务", async () => {
30
+ const agentDir = mkdtempSync(join(tmpdir(), "pi-fabric-wt-"));
31
+ try {
32
+ const provider = createGitWorktreeProvider(agentDir);
33
+ const workspace = await provider({ taskId: "aaaaaaaaaaaaaaaa", hint: join(agentDir, "nope") });
34
+ assert.ok(workspace.cwd.includes("aaaaaaaaaaaaaaaa"));
35
+ assert.equal(workspace.diff, undefined);
36
+ await workspace.cleanup?.();
37
+ } finally {
38
+ rmSync(agentDir, { recursive: true, force: true });
39
+ }
40
+ });
41
+
42
+ test("git 仓库:在 worktree 里跑,diff 含改动,清理后目录消失", async () => {
43
+ const repo = initRepo();
44
+ const agentDir = mkdtempSync(join(tmpdir(), "pi-fabric-wt-"));
45
+ try {
46
+ const root = await resolveRepoRoot(repo);
47
+ assert.ok(root && root.toLowerCase().endsWith(basename(repo).toLowerCase()));
48
+ const provider = createGitWorktreeProvider(agentDir);
49
+ const workspace = await provider({ taskId: "bbbbbbbbbbbbbbbb", hint: repo });
50
+ const runner = createSubagentRunner(agentDir, {
51
+ prepareWorkspace: async () => workspace,
52
+ spawn: async (input) => {
53
+ writeFileSync(join(input.cwd, "a.txt"), "one\ntwo\n", "utf8");
54
+ writeFileSync(join(input.cwd, "b.txt"), "brand new\n", "utf8");
55
+ return { ok: true, text: "改好了 a.txt 与 b.txt" };
56
+ },
57
+ });
58
+ const result = await runner.run({
59
+ taskId: "bbbbbbbbbbbbbbbb",
60
+ prompt: "改点东西",
61
+ workspaceHint: repo,
62
+ grant: "workspace-rw",
63
+ tools: [],
64
+ input: null,
65
+ signal: new AbortController().signal,
66
+ onProgress: () => undefined,
67
+ });
68
+ const diff = result.diff?.toString("utf8") ?? "";
69
+ assert.match(diff, /a\.txt/);
70
+ assert.match(diff, /b\.txt/);
71
+ assert.match(diff, /\+two/);
72
+ // 清理之后:worktree 目录不该留下,仓库登记也应该清空
73
+ assert.equal(existsSync(workspace.cwd), false);
74
+ const worktrees = execFileSync("git", ["-C", repo, "worktree", "list", "--porcelain"], {
75
+ encoding: "utf8",
76
+ windowsHide: true,
77
+ });
78
+ assert.equal(worktrees.includes("bbbbbbbbbbbbbbbb"), false);
79
+ // 本机仓库的 HEAD 未被改动
80
+ assert.equal(existsSync(join(repo, "b.txt")), false);
81
+ mkdirSync(join(repo, "keep"), { recursive: true });
82
+ } finally {
83
+ rmSync(repo, { recursive: true, force: true });
84
+ rmSync(agentDir, { recursive: true, force: true });
85
+ }
86
+ });
87
+
88
+ test("describeWorkspace:有 origin 用远端 URL,没有就退回仓库根路径", async () => {
89
+ const repo = initRepo();
90
+ const bare = mkdtempSync(join(tmpdir(), "pi-fabric-origin-"));
91
+ try {
92
+ const described = await describeWorkspace(repo);
93
+ assert.equal(described.toLowerCase().endsWith(basename(repo).toLowerCase()), true);
94
+ execFileSync("git", ["init", "-q", "--bare", bare], { windowsHide: true, env: cleanGitEnv() });
95
+ execFileSync("git", ["-C", repo, "remote", "add", "origin", bare], { windowsHide: true, env: cleanGitEnv() });
96
+ assert.equal(await describeWorkspace(repo), bare);
97
+ assert.equal(isGitUrl("git@github.com:a/b.git"), true);
98
+ assert.equal(isGitUrl("https://example.com/a/b.git"), true);
99
+ assert.equal(isGitUrl("C:/work/repo"), false);
100
+ } finally {
101
+ rmSync(repo, { recursive: true, force: true });
102
+ rmSync(bare, { recursive: true, force: true });
103
+ }
104
+ });
105
+
106
+ test("ensureRepoForUrl:没有缓存就克隆,之后复用同一份(不重复克隆)", async () => {
107
+ const origin = initRepo();
108
+ const agentDir = mkdtempSync(join(tmpdir(), "pi-fabric-cache-"));
109
+ try {
110
+ const first = await ensureRepoForUrl(agentDir, origin);
111
+ assert.ok(first && existsSync(join(first, "HEAD")), "应该克隆出 bare 仓库");
112
+ const second = await ensureRepoForUrl(agentDir, origin);
113
+ assert.equal(second, first);
114
+ assert.equal(repoCachePath(agentDir, origin), first);
115
+ // 坏 URL 不抛,返回 null(调用方退回普通目录)
116
+ assert.equal(await ensureRepoForUrl(agentDir, join(agentDir, "nope"), { timeoutMs: 5_000 }), null);
117
+ } finally {
118
+ rmSync(origin, { recursive: true, force: true });
119
+ rmSync(agentDir, { recursive: true, force: true });
120
+ }
121
+ });
122
+
123
+ test("URL 形式的 hint 会经由缓存克隆建出 worktree", async () => {
124
+ const origin = initRepo();
125
+ const agentDir = mkdtempSync(join(tmpdir(), "pi-fabric-wt-url-"));
126
+ try {
127
+ const provider = createGitWorktreeProvider(agentDir);
128
+ const workspace = await provider({ taskId: "dddddddddddddddd", hint: origin });
129
+ assert.ok(existsSync(join(workspace.cwd, "a.txt")), "worktree 里应该有仓库文件");
130
+ const diff = workspace.diff ? await workspace.diff() : null;
131
+ assert.equal(diff, null);
132
+ await workspace.cleanup?.();
133
+ assert.equal(existsSync(workspace.cwd), false);
134
+ } finally {
135
+ rmSync(origin, { recursive: true, force: true });
136
+ rmSync(agentDir, { recursive: true, force: true });
137
+ }
138
+ });
139
+
@@ -0,0 +1,232 @@
1
+ /**
2
+ * 远程任务的隔离工作区:git worktree。
3
+ *
4
+ * 为什么必须是 worktree 而不是「随便一个目录」:
5
+ * 远端任务要改代码、还要把改动回传成 diff。用 worktree 才能拿到「相对 HEAD 的差异」,
6
+ * 而且不会碰本机用户正在改的那份工作区(Q9 的硬约束)。
7
+ *
8
+ * 找不到仓库时退回普通空目录(任务照样能跑,只是没有 diff),绝不阻断。
9
+ */
10
+ import { execFile } from "node:child_process";
11
+ import { createHash } from "node:crypto";
12
+ import { existsSync, mkdirSync, realpathSync, rmSync } from "node:fs";
13
+ import { dirname, join, resolve } from "node:path";
14
+ import { promisify } from "node:util";
15
+ import type { FabricWorkspace } from "./fabric-runner.ts";
16
+
17
+ const execFileAsync = promisify(execFile);
18
+
19
+ export interface GitWorktreeProviderOptions {
20
+ /** git 可执行文件(测试里可注入)。 */
21
+ git?: string;
22
+ /** 起点提交,默认 HEAD。 */
23
+ baseRef?: string;
24
+ /** git 操作超时,毫秒。 */
25
+ timeoutMs?: number;
26
+ log?: (message: string) => void;
27
+ }
28
+
29
+ /**
30
+ * 会被父进程(git hook / IDE / Host 由钩子拉起时)注入的变量:
31
+ * 一旦继承,子进程的 git 会指向**另一个仓库**,实测后果是 worktree add 报
32
+ * "Unable to create .../index.lock: No such file or directory"(verify 的 pre-commit 钩子里必现)。
33
+ * 所以这里显式清掉,让 git 只按 -C 给的目标仓库工作。
34
+ */
35
+ const GIT_ENV_KEYS = [
36
+ "GIT_DIR",
37
+ "GIT_INDEX_FILE",
38
+ "GIT_WORK_TREE",
39
+ "GIT_OBJECT_DIRECTORY",
40
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",
41
+ "GIT_COMMON_DIR",
42
+ "GIT_NAMESPACE",
43
+ "GIT_PREFIX",
44
+ ] as const;
45
+
46
+ export function cleanGitEnv(): NodeJS.ProcessEnv {
47
+ const env: NodeJS.ProcessEnv = { ...process.env };
48
+ for (const key of GIT_ENV_KEYS) delete env[key];
49
+ return env;
50
+ }
51
+
52
+ async function git(gitBin: string, args: string[], timeoutMs: number): Promise<string> {
53
+ const { stdout } = await execFileAsync(gitBin, args, {
54
+ timeout: timeoutMs,
55
+ maxBuffer: 32 * 1024 * 1024,
56
+ windowsHide: true,
57
+ env: cleanGitEnv(),
58
+ });
59
+ return String(stdout);
60
+ }
61
+
62
+
63
+ /**
64
+ * 仓库远端 URL 的识别与本地缓存克隆。
65
+ *
66
+ * 为什么需要它:跨机派活时 A 把自己本机的仓库路径当 hint 带过去,B 上根本没有那个路径
67
+ * (同构路径假设只在两台机器目录结构完全一样时成立)。改成「传远端 URL,B 按 URL 找
68
+ * 本地缓存克隆,没有就克隆一份」,这条路在任何两台机器上都成立。
69
+ */
70
+ const GIT_URL_RE = /^(?:https?:\/\/|git@|ssh:\/\/|git:\/\/)/i;
71
+
72
+ export function isGitUrl(value: string): boolean {
73
+ return GIT_URL_RE.test(value.trim());
74
+ }
75
+
76
+ /** 缓存目录:<agentDir>/fabric/repos/<url 哈希>,与产物库同级,跨版本不丢。 */
77
+ export function repoCachePath(agentDir: string, url: string): string {
78
+ const hash = createHash("sha1").update(url.trim()).digest("hex").slice(0, 16);
79
+ return join(agentDir, "fabric", "repos", hash);
80
+ }
81
+
82
+ /**
83
+ * 把「本机 cwd」翻译成对端能理解的仓库标识:
84
+ * 有 origin 就用远端 URL(最通用),没有就退回本地路径(同机/同构路径仍可用)。
85
+ */
86
+ export async function describeWorkspace(
87
+ cwd: string,
88
+ options: GitWorktreeProviderOptions = {},
89
+ ): Promise<string> {
90
+ if (!cwd) return "";
91
+ const gitBin = options.git ?? "git";
92
+ const timeoutMs = options.timeoutMs ?? 10_000;
93
+ const root = await resolveRepoRoot(cwd, options);
94
+ if (!root) return cwd;
95
+ try {
96
+ const url = (
97
+ await git(gitBin, ["-C", root, "remote", "get-url", "origin"], timeoutMs)
98
+ ).trim();
99
+ return url || root;
100
+ } catch {
101
+ return root;
102
+ }
103
+ }
104
+
105
+ /** 有缓存就用缓存;否则浅克隆一份(--bare 只为出 worktree,不要工作区)。 */
106
+ export async function ensureRepoForUrl(
107
+ agentDir: string,
108
+ url: string,
109
+ options: GitWorktreeProviderOptions = {},
110
+ ): Promise<string | null> {
111
+ const gitBin = options.git ?? "git";
112
+ const timeoutMs = options.timeoutMs ?? 120_000;
113
+ const cacheDir = repoCachePath(agentDir, url);
114
+ if (existsSync(join(cacheDir, "HEAD"))) return cacheDir;
115
+ mkdirSync(dirname(cacheDir), { recursive: true });
116
+ try {
117
+ await git(
118
+ gitBin,
119
+ ["clone", "--bare", "--filter=blob:none", url, cacheDir],
120
+ timeoutMs,
121
+ );
122
+ return cacheDir;
123
+ } catch (error) {
124
+ options.log?.(
125
+ `fabric repo clone failed for ${url}: ${error instanceof Error ? error.message : String(error)}`,
126
+ );
127
+ return null;
128
+ }
129
+ }
130
+
131
+ /** 从 hint(仓库路径 / 子目录)解析出仓库根;不是 git 仓库返回 null。 */
132
+ export async function resolveRepoRoot(
133
+ hint: string,
134
+ options: GitWorktreeProviderOptions = {},
135
+ ): Promise<string | null> {
136
+ const gitBin = options.git ?? "git";
137
+ const timeoutMs = options.timeoutMs ?? 10_000;
138
+ if (!hint) return null;
139
+ try {
140
+ const root = (await git(gitBin, ["-C", hint, "rev-parse", "--show-toplevel"], timeoutMs)).trim();
141
+ return root || null;
142
+ } catch {
143
+ return null;
144
+ }
145
+ }
146
+
147
+ /**
148
+ * 每台机器的工作区准备器。
149
+ *
150
+ * 清理是硬要求:worktree 不删会一直占着分支与磁盘(一次远程任务一个分支)。
151
+ */
152
+ export function createGitWorktreeProvider(
153
+ agentDir: string,
154
+ options: GitWorktreeProviderOptions = {},
155
+ ) {
156
+ const gitBin = options.git ?? "git";
157
+ const baseRef = options.baseRef ?? "HEAD";
158
+ const timeoutMs = options.timeoutMs ?? 60_000;
159
+
160
+ // 先规范化到真实长路径:Windows 上 8.3 短路径(LUOWEI~1)与长路径混用时,
161
+ // git 会找不到刚建好的 .git 目录(实测 "Unable to create .../index.lock")。
162
+ const baseDir = (() => {
163
+ const dir = resolve(agentDir, "fabric", "worktrees");
164
+ mkdirSync(dir, { recursive: true });
165
+ try {
166
+ return realpathSync.native(dir);
167
+ } catch {
168
+ return dir;
169
+ }
170
+ })();
171
+
172
+ return async (input: { taskId: string; hint: string }): Promise<FabricWorkspace> => {
173
+ const cwd = join(baseDir, input.taskId);
174
+ // hint 可能是本机路径,也可能是仓库远端 URL(跨机的正常情况)。
175
+ const local = await resolveRepoRoot(input.hint, options);
176
+ const repo = local ?? (isGitUrl(input.hint) ? await ensureRepoForUrl(agentDir, input.hint, options) : null);
177
+ if (!repo) {
178
+ mkdirSync(cwd, { recursive: true });
179
+ options.log?.(`fabric worktree: ${input.hint || "(no hint)"} 不是 git 仓库,退回普通目录`);
180
+ return { cwd };
181
+ }
182
+ rmSync(cwd, { recursive: true, force: true });
183
+ // 不预先创建目录:交给 git 自己建(预建空目录在短路径下会踩上面的坑)。
184
+ // --detach:不建分支。分支模式下 git 需要先写 worktree 私有 admin 区的 index,
185
+ // 在 Windows + 并行测试时偶发 "Unable to create .git/index.lock"(实测 ctor 未就绪);
186
+ // detached worktree 完全跳过这一步,且关掉分支就不用管清理时删分支。
187
+ const addWorktree = () =>
188
+ git(gitBin, ["-C", repo, "worktree", "add", "--detach", cwd, baseRef], timeoutMs);
189
+ try {
190
+ await addWorktree();
191
+ } catch (error) {
192
+ /**
193
+ * Windows 上偶尔会留下「admin 里登记了、目录没建全」的半成品(实测报
194
+ * index.lock 不存在)。先 prune 清掉死登记再重试一次,比直接失败合理:
195
+ * 这个调用在远端任务的开头,失败就等于这次远程干活白派。
196
+ */
197
+ options.log?.(
198
+ `fabric worktree add failed, pruning and retrying: ${
199
+ error instanceof Error ? error.message : String(error)
200
+ }`,
201
+ );
202
+ rmSync(cwd, { recursive: true, force: true });
203
+ await git(gitBin, ["-C", repo, "worktree", "prune"], timeoutMs).catch(() => "");
204
+ await addWorktree();
205
+ }
206
+ return {
207
+ cwd,
208
+ /** 相对 HEAD 的完整差异(含未跟踪文件),二进制安全。 */
209
+ diff: async () => {
210
+ await git(gitBin, ["-C", cwd, "add", "-A"], timeoutMs);
211
+ const text = await git(
212
+ gitBin,
213
+ ["-C", cwd, "diff", "--cached", "--binary", "--no-color", "--no-ext-diff", baseRef],
214
+ timeoutMs,
215
+ );
216
+ return text ? Buffer.from(text, "utf8") : null;
217
+ },
218
+ cleanup: async () => {
219
+ try {
220
+ await git(gitBin, ["-C", repo, "worktree", "remove", "--force", cwd], timeoutMs);
221
+ } catch (error) {
222
+ options.log?.(
223
+ `fabric worktree remove failed: ${error instanceof Error ? error.message : String(error)}`,
224
+ );
225
+ }
226
+ // remove 失败也要把登记清掉,否则下次同 taskId 重跑会撞死登记。
227
+ await git(gitBin, ["-C", repo, "worktree", "prune"], timeoutMs).catch(() => "");
228
+ rmSync(cwd, { recursive: true, force: true });
229
+ },
230
+ };
231
+ };
232
+ }