@tekmidian/pai 0.66.7 → 0.66.9
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/dist/{aibroker-client-BevXY1Zz.mjs → aibroker-client-BfnVwGZl.mjs} +3 -3
- package/dist/{aibroker-client-BevXY1Zz.mjs.map → aibroker-client-BfnVwGZl.mjs.map} +1 -1
- package/dist/{aibroker-client-CxTpL_u7.mjs → aibroker-client-C-O3Fflh.mjs} +1 -1
- package/dist/{auto-route-BVeAp0fl.mjs → auto-route-DoFrncW7.mjs} +3 -3
- package/dist/{auto-route-BVeAp0fl.mjs.map → auto-route-DoFrncW7.mjs.map} +1 -1
- package/dist/auto-route-UD9PySwP.mjs +7 -0
- package/dist/{chain-8hFKr23C.mjs → chain-BL4khGgy.mjs} +4 -3
- package/dist/{chain-8hFKr23C.mjs.map → chain-BL4khGgy.mjs.map} +1 -1
- package/dist/cli/index.mjs +20 -17
- package/dist/cli/index.mjs.map +1 -1
- package/dist/cli/program.mjs +19 -16
- package/dist/{config-sfaArCsl.mjs → config-DjZELvoA.mjs} +2 -2
- package/dist/{config-sfaArCsl.mjs.map → config-DjZELvoA.mjs.map} +1 -1
- package/dist/{run-env-CkAmx3lb.mjs → config-Dpe2JlbY.mjs} +5 -114
- package/dist/config-Dpe2JlbY.mjs.map +1 -0
- package/dist/{config-UWtzLpXi.mjs → config-yomayAwe.mjs} +1 -1
- package/dist/{context-handover-cache-Bb-H_mTa.mjs → context-handover-cache-5qnqzWqp.mjs} +27 -12
- package/dist/context-handover-cache-5qnqzWqp.mjs.map +1 -0
- package/dist/daemon/index.mjs +20 -16
- package/dist/daemon/index.mjs.map +1 -1
- package/dist/daemon-4VZOwUXe.mjs +23 -0
- package/dist/{daemon-CkbX-hV7.mjs → daemon-C-2mo7y_.mjs} +20 -19
- package/dist/{daemon-CkbX-hV7.mjs.map → daemon-C-2mo7y_.mjs.map} +1 -1
- package/dist/daemon-mcp/index.mjs +15 -13
- package/dist/daemon-mcp/index.mjs.map +1 -1
- package/dist/{embedding-gate-BVrr0BgS.mjs → embedding-gate-DqbKvn56.mjs} +4 -4
- package/dist/{embedding-gate-BVrr0BgS.mjs.map → embedding-gate-DqbKvn56.mjs.map} +1 -1
- package/dist/{embedding-gate-Crj8awk7.mjs → embedding-gate-SJMCPwxG.mjs} +3 -3
- package/dist/{embeddings-DFl88_y-.mjs → embeddings-BUjZMD9F.mjs} +1 -1
- package/dist/{embeddings-DFl88_y-.mjs.map → embeddings-BUjZMD9F.mjs.map} +1 -1
- package/dist/{embeddings-BuA7v4lk.mjs → embeddings-DrJ-ewfi.mjs} +1 -1
- package/dist/{env-DqTjeKoA.mjs → env-CPCNHz3i.mjs} +1 -1
- package/dist/{env-DqTjeKoA.mjs.map → env-CPCNHz3i.mjs.map} +1 -1
- package/dist/factory-DjtXElOI.mjs +9 -0
- package/dist/{factory-mNBitkL_.mjs → factory-yElzJc6f.mjs} +10 -10
- package/dist/{factory-mNBitkL_.mjs.map → factory-yElzJc6f.mjs.map} +1 -1
- package/dist/{fallback-DdC1_s2d.mjs → fallback-2yWDDYiT.mjs} +5 -4
- package/dist/{fallback-DdC1_s2d.mjs.map → fallback-2yWDDYiT.mjs.map} +1 -1
- package/dist/{helpers-CZsi_49C.mjs → helpers-B9LHRJ8R.mjs} +1 -1
- package/dist/{helpers-CZsi_49C.mjs.map → helpers-B9LHRJ8R.mjs.map} +1 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +7 -4
- package/dist/{ipc-client-BgSzY9QJ.mjs → ipc-client-DVZ_EGnu.mjs} +2 -2
- package/dist/{ipc-client-BgSzY9QJ.mjs.map → ipc-client-DVZ_EGnu.mjs.map} +1 -1
- package/dist/main-resolver-DjQsexge.mjs +8 -0
- package/dist/{main-resolver-DEXky_Km.mjs → main-resolver-Dxvn4Mv8.mjs} +7 -6
- package/dist/{main-resolver-DEXky_Km.mjs.map → main-resolver-Dxvn4Mv8.mjs.map} +1 -1
- package/dist/{pai-marker-DXVpFsYz.mjs → pai-marker-BFOlchq2.mjs} +121 -3
- package/dist/pai-marker-BFOlchq2.mjs.map +1 -0
- package/dist/{planner-DBoB5GtC.mjs → planner-CspP59ya.mjs} +13 -11
- package/dist/{planner-DBoB5GtC.mjs.map → planner-CspP59ya.mjs.map} +1 -1
- package/dist/{postgres-D-96lgE1.mjs → postgres-CCAGq1qp.mjs} +5 -5
- package/dist/{postgres-D-96lgE1.mjs.map → postgres-CCAGq1qp.mjs.map} +1 -1
- package/dist/postgres-CzkEPfAm.mjs +7 -0
- package/dist/{program-BXns_5kO.mjs → program-D_Ks5nkL.mjs} +77 -119
- package/dist/program-D_Ks5nkL.mjs.map +1 -0
- package/dist/{query-feedback-VI7Cl-Lr.mjs → query-feedback-GPeVGvIa.mjs} +2 -2
- package/dist/{query-feedback-VI7Cl-Lr.mjs.map → query-feedback-GPeVGvIa.mjs.map} +1 -1
- package/dist/{reranker-3lnggwgq.mjs → reranker-BTiOia8Y.mjs} +1 -1
- package/dist/{reranker-3lnggwgq.mjs.map → reranker-BTiOia8Y.mjs.map} +1 -1
- package/dist/{reranker-CZ2mP4cf.mjs → reranker-YwDT2n5e.mjs} +1 -1
- package/dist/{router-dfjlaOMI.mjs → router-Bk_ySIZT.mjs} +2 -2
- package/dist/{router-dfjlaOMI.mjs.map → router-Bk_ySIZT.mjs.map} +1 -1
- package/dist/router-DyiZNI6o.mjs +3 -0
- package/dist/{run-DPwQkRwh.mjs → run-BZNdpUGQ.mjs} +126 -1795
- package/dist/run-BZNdpUGQ.mjs.map +1 -0
- package/dist/run-env-Cd0Son-Y.mjs +115 -0
- package/dist/run-env-Cd0Son-Y.mjs.map +1 -0
- package/dist/{runtime-paths-BiEi_gaG.mjs → runtime-paths-DkZoxofH.mjs} +1 -1
- package/dist/{runtime-paths-BiEi_gaG.mjs.map → runtime-paths-DkZoxofH.mjs.map} +1 -1
- package/dist/{search-CNAGTiJP.mjs → search-cPDj-9fO.mjs} +2 -2
- package/dist/{search-CNAGTiJP.mjs.map → search-cPDj-9fO.mjs.map} +1 -1
- package/dist/{sources-BxXbzpAJ.mjs → sources-CvvzNZad.mjs} +1 -1
- package/dist/{sources-BxXbzpAJ.mjs.map → sources-CvvzNZad.mjs.map} +1 -1
- package/dist/{stop-words-DtxaTWU_.mjs → stop-words-LtkS-Pej.mjs} +1 -1
- package/dist/{stop-words-DtxaTWU_.mjs.map → stop-words-LtkS-Pej.mjs.map} +1 -1
- package/dist/worktree-CwMRTa0H.mjs +1578 -0
- package/dist/worktree-CwMRTa0H.mjs.map +1 -0
- package/dist/{zettelkasten-wh2Yy1nS.mjs → zettelkasten-DSIe6wpF.mjs} +4 -4
- package/dist/{zettelkasten-wh2Yy1nS.mjs.map → zettelkasten-DSIe6wpF.mjs.map} +1 -1
- package/dist/{zettelkasten-CzcPzEsL.mjs → zettelkasten-DtkAvA18.mjs} +5 -5
- package/package.json +1 -1
- package/dist/auto-route-CboBqsN3.mjs +0 -3
- package/dist/context-handover-cache-Bb-H_mTa.mjs.map +0 -1
- package/dist/daemon-BXTn2EgV.mjs +0 -19
- package/dist/factory-XrH66erA.mjs +0 -9
- package/dist/main-resolver-CobQGm2B.mjs +0 -7
- package/dist/pai-marker-DXVpFsYz.mjs.map +0 -1
- package/dist/postgres-TedJP3yF.mjs +0 -7
- package/dist/program-BXns_5kO.mjs.map +0 -1
- package/dist/router-CKn9e0fo.mjs +0 -3
- package/dist/run-DPwQkRwh.mjs.map +0 -1
- package/dist/run-env-CkAmx3lb.mjs.map +0 -1
|
@@ -0,0 +1,1578 @@
|
|
|
1
|
+
import { d as resolvePaiFile, u as paiHomePath } from "./runtime-paths-DkZoxofH.mjs";
|
|
2
|
+
import { _ as expandHome, i as DEFAULT_LOG_DIR } from "./config-Dpe2JlbY.mjs";
|
|
3
|
+
import { appendFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { platform, tmpdir } from "node:os";
|
|
5
|
+
import { dirname, isAbsolute, join, resolve, sep } from "node:path";
|
|
6
|
+
import { execFileSync } from "node:child_process";
|
|
7
|
+
|
|
8
|
+
//#region src/workers/paths.ts
|
|
9
|
+
/**
|
|
10
|
+
* paths.ts — where worker run artefacts live.
|
|
11
|
+
*
|
|
12
|
+
* Everything a run writes (event mirror, status file, pane registry, routing
|
|
13
|
+
* state, the empty MCP config) sits under one logDir so the whole tree is
|
|
14
|
+
* disposable and configurable: `workers.logDir`, default ~/.claude/logs/workers.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Absolute logDir for the given config. An explicit `logDir` in workers.yaml
|
|
18
|
+
* is honored verbatim (the user chose it). Otherwise this resolves like every
|
|
19
|
+
* other PAI_HOME file: PAI_HOME/logs/workers if it exists, else the old
|
|
20
|
+
* ~/.claude/logs/workers (with a one-time notice), else the new path.
|
|
21
|
+
*/
|
|
22
|
+
function workersLogDir(config) {
|
|
23
|
+
const expanded = expandHome(config.logDir);
|
|
24
|
+
if (config.logDir !== DEFAULT_LOG_DIR) return expanded;
|
|
25
|
+
return resolvePaiFile(paiHomePath("logs", "workers"), [expanded], "pai config migrate --logs");
|
|
26
|
+
}
|
|
27
|
+
/** The strict empty MCP config for headless runs, written on demand. */
|
|
28
|
+
function ensureNoMcpConfig(logDir) {
|
|
29
|
+
const path = noMcpConfigPath(logDir);
|
|
30
|
+
if (!existsSync(path)) {
|
|
31
|
+
mkdirSync(logDir, { recursive: true });
|
|
32
|
+
writeFileSync(path, "{ \"mcpServers\": {} }\n", "utf8");
|
|
33
|
+
}
|
|
34
|
+
return path;
|
|
35
|
+
}
|
|
36
|
+
function statusPath(logDir, id) {
|
|
37
|
+
return join(logDir, `${id}.status`);
|
|
38
|
+
}
|
|
39
|
+
function eventsPath(logDir, id) {
|
|
40
|
+
return join(logDir, `${id}.jsonl`);
|
|
41
|
+
}
|
|
42
|
+
function ledgerPath(logDir) {
|
|
43
|
+
return join(logDir, "ledger.log");
|
|
44
|
+
}
|
|
45
|
+
function routingStatePath(logDir) {
|
|
46
|
+
return join(logDir, "routing-state.json");
|
|
47
|
+
}
|
|
48
|
+
function panesDir(logDir) {
|
|
49
|
+
return join(logDir, "panes");
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The strict empty MCP config handed to headless workers. Written into the
|
|
53
|
+
* logDir on demand (never into the user's vendor config directory — this is
|
|
54
|
+
* PAI state, not vendor state).
|
|
55
|
+
*/
|
|
56
|
+
function noMcpConfigPath(logDir) {
|
|
57
|
+
return join(logDir, "no-mcp.json");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
//#endregion
|
|
61
|
+
//#region src/workers/args.ts
|
|
62
|
+
function parseRunnerArgs(argv) {
|
|
63
|
+
let prompt = null;
|
|
64
|
+
let outputFormat = "text";
|
|
65
|
+
const rest = [];
|
|
66
|
+
let headless = false;
|
|
67
|
+
let callerModel = false;
|
|
68
|
+
let callerMcpConfig = false;
|
|
69
|
+
let callerSystemPrompt = false;
|
|
70
|
+
const callerSystemPrompts = [];
|
|
71
|
+
let callerTools = false;
|
|
72
|
+
const mcp = [];
|
|
73
|
+
const allowedTools = [];
|
|
74
|
+
let i = 0;
|
|
75
|
+
while (i < argv.length) {
|
|
76
|
+
const a = argv[i];
|
|
77
|
+
if (a === "-p" || a === "--print") {
|
|
78
|
+
headless = true;
|
|
79
|
+
rest.push(a);
|
|
80
|
+
if (i + 1 < argv.length && !argv[i + 1].startsWith("-")) {
|
|
81
|
+
prompt = argv[i + 1];
|
|
82
|
+
rest.push(prompt);
|
|
83
|
+
i += 1;
|
|
84
|
+
}
|
|
85
|
+
} else if (a === "--output-format") {
|
|
86
|
+
const v = argv[i + 1];
|
|
87
|
+
if (v === "json" || v === "stream-json") outputFormat = v;
|
|
88
|
+
i += 1;
|
|
89
|
+
} else if (a.startsWith("--output-format=")) {
|
|
90
|
+
const v = a.slice(16);
|
|
91
|
+
if (v === "json" || v === "stream-json") outputFormat = v;
|
|
92
|
+
} else if (a === "--verbose") {} else if (a === "--append-system-prompt") {
|
|
93
|
+
callerSystemPrompt = true;
|
|
94
|
+
if (i + 1 < argv.length) callerSystemPrompts.push(argv[++i]);
|
|
95
|
+
} else if (a.startsWith("--append-system-prompt=")) {
|
|
96
|
+
callerSystemPrompt = true;
|
|
97
|
+
callerSystemPrompts.push(a.slice(23));
|
|
98
|
+
} else if (a === "--mcp") {
|
|
99
|
+
const v = argv[i + 1];
|
|
100
|
+
if (v !== void 0 && !v.startsWith("-")) {
|
|
101
|
+
mcp.push(v);
|
|
102
|
+
i += 1;
|
|
103
|
+
}
|
|
104
|
+
} else if (a.startsWith("--mcp=")) mcp.push(a.slice(6));
|
|
105
|
+
else if (a === "--allowedTools") {
|
|
106
|
+
rest.push(a);
|
|
107
|
+
const v = argv[i + 1];
|
|
108
|
+
if (v !== void 0 && !v.startsWith("-")) {
|
|
109
|
+
allowedTools.push(v);
|
|
110
|
+
rest.push(v);
|
|
111
|
+
i += 1;
|
|
112
|
+
}
|
|
113
|
+
} else if (a.startsWith("--allowedTools=")) {
|
|
114
|
+
allowedTools.push(a.slice(15));
|
|
115
|
+
rest.push(a);
|
|
116
|
+
} else {
|
|
117
|
+
if (a === "--model") callerModel = true;
|
|
118
|
+
if (a.startsWith("--model=")) callerModel = true;
|
|
119
|
+
if (a === "--mcp-config") callerMcpConfig = true;
|
|
120
|
+
if (a.startsWith("--mcp-config=")) callerMcpConfig = true;
|
|
121
|
+
if (a === "--tools") callerTools = true;
|
|
122
|
+
if (a.startsWith("--tools=")) callerTools = true;
|
|
123
|
+
if (prompt === null && !a.startsWith("-") && rest.length > 0 && (rest[rest.length - 1] === "-p" || rest[rest.length - 1] === "--print")) prompt = a;
|
|
124
|
+
rest.push(a);
|
|
125
|
+
}
|
|
126
|
+
i += 1;
|
|
127
|
+
}
|
|
128
|
+
return {
|
|
129
|
+
prompt,
|
|
130
|
+
outputFormat,
|
|
131
|
+
rest,
|
|
132
|
+
headless,
|
|
133
|
+
callerModel,
|
|
134
|
+
callerMcpConfig,
|
|
135
|
+
callerSystemPrompt,
|
|
136
|
+
callerSystemPrompts,
|
|
137
|
+
callerTools,
|
|
138
|
+
mcp,
|
|
139
|
+
allowedTools
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* The one --append-system-prompt flag for a spawn: claude keeps only the LAST
|
|
144
|
+
* occurrence, so every piece is joined (blank line between) into a single flag.
|
|
145
|
+
* Empty parts are dropped; no parts, no flag.
|
|
146
|
+
*/
|
|
147
|
+
function appendSystemPromptArgs(parts) {
|
|
148
|
+
const text = parts.filter((p) => p.trim()).join("\n\n");
|
|
149
|
+
return text ? ["--append-system-prompt", text] : [];
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Turn `-p "<prompt>"` into bare `-p` (same for --print): for stream-json
|
|
153
|
+
* stdin runs the prompt moves to the first user message on stdin, so the
|
|
154
|
+
* value must not stay on the command line. Only prompt values directly
|
|
155
|
+
* following the flag are touched; everything else passes through.
|
|
156
|
+
*/
|
|
157
|
+
function stripPromptValues(argv) {
|
|
158
|
+
const out = [];
|
|
159
|
+
for (let i = 0; i < argv.length; i++) {
|
|
160
|
+
const a = argv[i];
|
|
161
|
+
const isPrint = a === "-p" || a === "--print";
|
|
162
|
+
out.push(a);
|
|
163
|
+
if (isPrint && i + 1 < argv.length && !argv[i + 1].startsWith("-")) i += 1;
|
|
164
|
+
}
|
|
165
|
+
return out;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* A one-line stderr hint (never blocking) for an inline -p prompt long or
|
|
169
|
+
* multi-line enough to be a shell-quoting risk — write it to a file and pass
|
|
170
|
+
* --spec instead. null when the prompt is short/simple enough to be fine.
|
|
171
|
+
*/
|
|
172
|
+
function longInlinePromptHint(prompt) {
|
|
173
|
+
if (!prompt) return null;
|
|
174
|
+
const newlines = (prompt.match(/\n/g) ?? []).length;
|
|
175
|
+
if (prompt.length > 600 || newlines > 3) return "hint: long inline prompts break on shell quoting — write the spec to a file and use --spec <file>";
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
/** Collapse whitespace and cut to n chars with an ellipsis (label rendering). */
|
|
179
|
+
function shortText(s, n) {
|
|
180
|
+
const t = String(s ?? "").split(/\s+/).filter(Boolean).join(" ");
|
|
181
|
+
return t.length <= n ? t : t.slice(0, n - 1) + "…";
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
//#endregion
|
|
185
|
+
//#region src/workers/status.ts
|
|
186
|
+
/**
|
|
187
|
+
* status.ts — the live per-worker status file.
|
|
188
|
+
*
|
|
189
|
+
* One JSON file per run, rewritten atomically on every turn, read by `ps`,
|
|
190
|
+
* `follow`, the status line and the pane logic. Same field set the Python
|
|
191
|
+
* runner wrote, plus `provider` (routing is multi-provider now) and `session`
|
|
192
|
+
* (the AIBroker identity of the launching session, see scope.ts).
|
|
193
|
+
*/
|
|
194
|
+
/** Label a worker gets when launched with neither --label nor a prompt. */
|
|
195
|
+
const UNLABELED = "unlabeled";
|
|
196
|
+
/**
|
|
197
|
+
* Whether a status is the terminal's interactive chat pane, not a spawned
|
|
198
|
+
* task worker. `origin` is the real discriminator; the fallback catches
|
|
199
|
+
* running entries from before the flag existed (unlabeled, no turns yet).
|
|
200
|
+
* Removable once every pane runs code that writes `origin`.
|
|
201
|
+
*/
|
|
202
|
+
function isChatPane(s) {
|
|
203
|
+
return s.origin === "chat" || !s.origin && (s.label === UNLABELED || s.label === "(no prompt)") && s.turns === 0;
|
|
204
|
+
}
|
|
205
|
+
/** Context-meter percentage 0–100, null when the numbers are missing. */
|
|
206
|
+
function contextPercent(s) {
|
|
207
|
+
if (!s.contextTokens || !s.contextWindow) return null;
|
|
208
|
+
return Math.round(s.contextTokens / s.contextWindow * 100);
|
|
209
|
+
}
|
|
210
|
+
/** Compact token count: 84k, 200k, 900. */
|
|
211
|
+
function fmtContextK(n) {
|
|
212
|
+
return n >= 1e3 ? `${Math.round(n / 1e3)}k` : String(n);
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* The one context-meter label, shared by every renderer so identical
|
|
216
|
+
* numbers always render identically: `ctx 84k/200k (42%)` — used-style
|
|
217
|
+
* percent. Empty when the numbers are missing (callers drop the part).
|
|
218
|
+
*/
|
|
219
|
+
function contextLabel(s) {
|
|
220
|
+
const pct = contextPercent(s);
|
|
221
|
+
if (pct === null) return "";
|
|
222
|
+
return `ctx ${fmtContextK(s.contextTokens ?? 0)}/${fmtContextK(s.contextWindow ?? 0)} (${pct}%)`;
|
|
223
|
+
}
|
|
224
|
+
/** Timestamp format shared by status files and the ledger. */
|
|
225
|
+
function nowStamp(d = /* @__PURE__ */ new Date()) {
|
|
226
|
+
const p = (n) => String(n).padStart(2, "0");
|
|
227
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
|
228
|
+
}
|
|
229
|
+
let lastId = "";
|
|
230
|
+
let idSeq = 0;
|
|
231
|
+
function newWorkerId(d = /* @__PURE__ */ new Date(), pid = process.pid) {
|
|
232
|
+
const p = (n) => String(n).padStart(2, "0");
|
|
233
|
+
const base = `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}-${pid}`;
|
|
234
|
+
if (base === lastId) {
|
|
235
|
+
idSeq += 1;
|
|
236
|
+
return `${base}-${String(idSeq).padStart(2, "0")}`;
|
|
237
|
+
}
|
|
238
|
+
lastId = base;
|
|
239
|
+
idSeq = 0;
|
|
240
|
+
return base;
|
|
241
|
+
}
|
|
242
|
+
let tmpSeq = 0;
|
|
243
|
+
/** A temp path only this call owns — never the same string twice. */
|
|
244
|
+
function statusTmpPath(logDir, id) {
|
|
245
|
+
return `${statusPath(logDir, id)}.${process.pid}.${tmpSeq++}.tmp`;
|
|
246
|
+
}
|
|
247
|
+
const firstWrittenLabel = /* @__PURE__ */ new Map();
|
|
248
|
+
/** Write status atomically (temp + rename) and stamp `updated`. */
|
|
249
|
+
function saveStatus(logDir, status, d = /* @__PURE__ */ new Date()) {
|
|
250
|
+
status.updated = nowStamp(d);
|
|
251
|
+
const path = statusPath(logDir, status.id);
|
|
252
|
+
const baseline = firstWrittenLabel.get(status.id);
|
|
253
|
+
if (baseline === void 0) firstWrittenLabel.set(status.id, status.label);
|
|
254
|
+
const onDisk = baseline === void 0 ? void 0 : loadStatus(logDir, status.id);
|
|
255
|
+
if (onDisk) {
|
|
256
|
+
if (status.label === baseline && onDisk.label !== status.label) status.label = onDisk.label;
|
|
257
|
+
if (onDisk.controlsHeld) status.controlsHeld = true;
|
|
258
|
+
}
|
|
259
|
+
const tmp = statusTmpPath(logDir, status.id);
|
|
260
|
+
if (!existsSync(logDir)) mkdirSync(logDir, { recursive: true });
|
|
261
|
+
try {
|
|
262
|
+
writeFileSync(tmp, JSON.stringify(status), "utf8");
|
|
263
|
+
renameSync(tmp, path);
|
|
264
|
+
} catch (e) {
|
|
265
|
+
try {
|
|
266
|
+
rmSync(tmp, { force: true });
|
|
267
|
+
} catch {}
|
|
268
|
+
throw e;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Set a worker's goal (the operator's `--label`), atomically, through the
|
|
273
|
+
* same saveStatus path everything else writes with. Used by `pai worker
|
|
274
|
+
* goal` and the `--goal` option of `say`: a fresh call in a fresh process, so
|
|
275
|
+
* it always carries no baseline yet and always wins over the worker's own
|
|
276
|
+
* next periodic write (see saveStatus above).
|
|
277
|
+
*/
|
|
278
|
+
function setWorkerLabel(logDir, id, label) {
|
|
279
|
+
const status = loadStatus(logDir, id);
|
|
280
|
+
if (!status) throw new Error(`no worker named "${id}"`);
|
|
281
|
+
status.label = label;
|
|
282
|
+
saveStatus(logDir, status);
|
|
283
|
+
return status;
|
|
284
|
+
}
|
|
285
|
+
/** Load every status file in the logDir, oldest id first, skipping damage. */
|
|
286
|
+
function loadStatuses(logDir) {
|
|
287
|
+
if (!existsSync(logDir)) return [];
|
|
288
|
+
const out = [];
|
|
289
|
+
for (const name of readdirSync(logDir).sort()) {
|
|
290
|
+
if (!name.endsWith(".status")) continue;
|
|
291
|
+
try {
|
|
292
|
+
out.push(JSON.parse(readFileSync(join(logDir, name), "utf8")));
|
|
293
|
+
} catch {}
|
|
294
|
+
}
|
|
295
|
+
return out;
|
|
296
|
+
}
|
|
297
|
+
function loadStatus(logDir, id) {
|
|
298
|
+
const path = statusPath(logDir, id);
|
|
299
|
+
if (!existsSync(path)) return null;
|
|
300
|
+
try {
|
|
301
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
302
|
+
} catch {
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Wait for a worker to record its own terminal state (the run's signal
|
|
308
|
+
* handler writes killed/rc/secs). Returns that status, or null when it is
|
|
309
|
+
* still "running" after `timeoutMs` — the caller then writes the state itself.
|
|
310
|
+
*/
|
|
311
|
+
async function waitForTerminalStatus(logDir, id, timeoutMs = 2e3, stepMs = 50) {
|
|
312
|
+
const deadline = Date.now() + timeoutMs;
|
|
313
|
+
for (;;) {
|
|
314
|
+
const s = loadStatus(logDir, id);
|
|
315
|
+
if (s && s.state !== "running") return s;
|
|
316
|
+
if (Date.now() >= deadline) return null;
|
|
317
|
+
await new Promise((r) => setTimeout(r, stepMs));
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
function alive(pid) {
|
|
321
|
+
if (!pid || pid <= 0) return false;
|
|
322
|
+
try {
|
|
323
|
+
process.kill(pid, 0);
|
|
324
|
+
return true;
|
|
325
|
+
} catch {
|
|
326
|
+
return false;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Whether `status.pid` still names the process that was started as this
|
|
331
|
+
* worker, not a later, unrelated process the OS handed the same pid to after
|
|
332
|
+
* the worker exited. `alive()` alone can't tell these apart — a pid observed
|
|
333
|
+
* live on 2026-09-19 (worker 20260919-083549-90913) had been reused, and
|
|
334
|
+
* `pai worker kill` signalled the wrong, unrelated process. `ps -o lstart=`
|
|
335
|
+
* reads the running process's actual start time and compares it against the
|
|
336
|
+
* status file's own `started` stamp; a reused pid almost never starts within
|
|
337
|
+
* 120s of the original, so a wider drift means "different process".
|
|
338
|
+
*/
|
|
339
|
+
function ownsPid(status) {
|
|
340
|
+
if (status.pid <= 0 || !alive(status.pid)) return false;
|
|
341
|
+
try {
|
|
342
|
+
const out = execFileSync("ps", [
|
|
343
|
+
"-o",
|
|
344
|
+
"lstart=",
|
|
345
|
+
"-p",
|
|
346
|
+
String(status.pid)
|
|
347
|
+
], {
|
|
348
|
+
encoding: "utf8",
|
|
349
|
+
env: {
|
|
350
|
+
...process.env,
|
|
351
|
+
LC_ALL: "C"
|
|
352
|
+
}
|
|
353
|
+
}).trim();
|
|
354
|
+
const psStart = Date.parse(out);
|
|
355
|
+
const started = Date.parse(status.started.replace(" ", "T"));
|
|
356
|
+
if (Number.isNaN(psStart) || Number.isNaN(started)) return alive(status.pid);
|
|
357
|
+
return Math.abs(psStart - started) <= 12e4;
|
|
358
|
+
} catch {
|
|
359
|
+
return alive(status.pid);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
/** Whether a status is both marked "running" and still owns its recorded pid. */
|
|
363
|
+
function isLive(status) {
|
|
364
|
+
return status.state === "running" && ownsPid(status);
|
|
365
|
+
}
|
|
366
|
+
/** "42s" under 90s, "7m" above — the coarse age the table and bar show. */
|
|
367
|
+
function ageOf(ts, now = /* @__PURE__ */ new Date()) {
|
|
368
|
+
const t = Date.parse(ts.replace(" ", "T"));
|
|
369
|
+
if (Number.isNaN(t)) return "?";
|
|
370
|
+
const s = Math.max(0, Math.floor((now.getTime() - t) / 1e3));
|
|
371
|
+
return s < 90 ? `${s}s` : `${Math.floor(s / 60)}m`;
|
|
372
|
+
}
|
|
373
|
+
/** Precise elapsed time: "45s", "1m 23s", "12m 05s", "1h 02m 05s" — seconds zero-padded after a larger unit. */
|
|
374
|
+
function elapsedOf(ts, now = /* @__PURE__ */ new Date()) {
|
|
375
|
+
const t = Date.parse(ts.replace(" ", "T"));
|
|
376
|
+
if (Number.isNaN(t)) return "?";
|
|
377
|
+
const secs = Math.max(0, Math.floor((now.getTime() - t) / 1e3));
|
|
378
|
+
const hours = Math.floor(secs / 3600);
|
|
379
|
+
const mins = Math.floor(secs % 3600 / 60);
|
|
380
|
+
const sec = secs % 60;
|
|
381
|
+
if (hours > 0) return `${hours}h ${String(mins).padStart(2, "0")}m ${String(sec).padStart(2, "0")}s`;
|
|
382
|
+
if (mins > 0) return `${mins}m ${String(sec).padStart(2, "0")}s`;
|
|
383
|
+
return `${sec}s`;
|
|
384
|
+
}
|
|
385
|
+
/** Shorter sleeps are legitimate polling — not worth a supervision event. */
|
|
386
|
+
const SLEEP_FLOOR_SECS = 60;
|
|
387
|
+
const SLEEP_RE = /^\s*sleep\s+([0-9]+(?:\.[0-9]+)?)([smhd]?)\s*(?:$|[;&|])/;
|
|
388
|
+
/** s/m/h/d suffix to seconds multiplier, shared by every `sleep N<unit>` parse below. */
|
|
389
|
+
function sleepUnitMultiplier(unit) {
|
|
390
|
+
return unit === "m" ? 60 : unit === "h" ? 3600 : unit === "d" ? 86400 : 1;
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Seconds of a `sleep N` (N plain or with an s/m/h/d suffix) that stands alone
|
|
394
|
+
* or leads a compound command (`sleep 150; cat f`, `sleep 2m && tail f`,
|
|
395
|
+
* `sleep 90 || true`, `sleep 60 &`), or null when no long sleep leads: anchored
|
|
396
|
+
* to the start of the command, so a filename containing "sleep" or an
|
|
397
|
+
* `echo sleep 500` never trips it, and floored at SLEEP_FLOOR_SECS so ordinary
|
|
398
|
+
* polling stays invisible.
|
|
399
|
+
*/
|
|
400
|
+
function parseSleepSecs(command) {
|
|
401
|
+
const m = command.match(SLEEP_RE);
|
|
402
|
+
if (!m) return null;
|
|
403
|
+
const secs = Number(m[1]) * sleepUnitMultiplier(m[2]);
|
|
404
|
+
return Number.isFinite(secs) && secs >= SLEEP_FLOOR_SECS ? secs : null;
|
|
405
|
+
}
|
|
406
|
+
/** One-line description of a tool call, e.g. "Bash: npm test". */
|
|
407
|
+
function describeTool(name, inp) {
|
|
408
|
+
if (typeof inp !== "object" || inp === null) return name;
|
|
409
|
+
const i = inp;
|
|
410
|
+
const get = (k) => typeof i[k] === "string" ? i[k] : "";
|
|
411
|
+
if (name === "Bash") return `Bash: ${shortText(get("command"), 70)}`;
|
|
412
|
+
if (name === "Read" || name === "Edit" || name === "Write" || name === "MultiEdit") return `${name}: ${get("file_path").split("/").pop() ?? ""}`;
|
|
413
|
+
if (name === "Grep" || name === "Glob") return `${name}: ${shortText(get("pattern"), 50)}`;
|
|
414
|
+
if (name === "WebSearch") return `${name}: ${shortText(get("query"), 50)}`;
|
|
415
|
+
if (name === "WebFetch") return `${name}: ${shortText(get("url"), 60)}`;
|
|
416
|
+
return name;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
//#endregion
|
|
420
|
+
//#region src/workers/ledger.ts
|
|
421
|
+
/**
|
|
422
|
+
* ledger.ts — the routing ledger, one append-only log for every worker event.
|
|
423
|
+
*
|
|
424
|
+
* Line shapes (whitespace-aligned so `tail` reads as a table):
|
|
425
|
+
*
|
|
426
|
+
* 2026-09-17 12:00:00 WORKER-START id=<id> provider=<p> mode=headless model=<m> cwd=<cwd> label=<label>
|
|
427
|
+
* 2026-09-17 12:01:00 WORKER-END id=<id> provider=<p> mode=headless model=<m> rc=0 secs=60 turns=3 tools=8 label=<label>
|
|
428
|
+
* 2026-09-17 12:00:20 WORKER-REROUTE from=<a> to=<b> reason=quota
|
|
429
|
+
* 2026-09-17 12:00:00 DENIED-ANTHROPIC-AGENT cwd=<cwd> desc=<desc>
|
|
430
|
+
* 2026-09-17 12:00:00 ALLOWED-ANTHROPIC-AGENT cwd=<cwd> desc=<desc>
|
|
431
|
+
*
|
|
432
|
+
* `pai worker log` (and glm-log before it) counts these; keep the tags stable.
|
|
433
|
+
*/
|
|
434
|
+
function ledgerStamp(d = /* @__PURE__ */ new Date()) {
|
|
435
|
+
const p = (n) => String(n).padStart(2, "0");
|
|
436
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
|
437
|
+
}
|
|
438
|
+
/** Parse `2026-09-17 12:00:00 TAG key=value …` into its parts. */
|
|
439
|
+
function parseLedgerLine(line) {
|
|
440
|
+
const m = line.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (\S+)(?: (.*))?$/);
|
|
441
|
+
if (!m) return null;
|
|
442
|
+
const fields = {};
|
|
443
|
+
for (const part of (m[3] ?? "").split(" ")) {
|
|
444
|
+
if (!part) continue;
|
|
445
|
+
const eq = part.indexOf("=");
|
|
446
|
+
if (eq <= 0) continue;
|
|
447
|
+
fields[part.slice(0, eq)] = part.slice(eq + 1);
|
|
448
|
+
}
|
|
449
|
+
return {
|
|
450
|
+
stamp: m[1],
|
|
451
|
+
event: m[2],
|
|
452
|
+
fields
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
/** Append one ledger line. `kv` order is the caller's; values are flattened. */
|
|
456
|
+
function appendLedger(path, event, kv, now = /* @__PURE__ */ new Date()) {
|
|
457
|
+
const parts = [];
|
|
458
|
+
for (const [k, v] of Object.entries(kv)) {
|
|
459
|
+
if (v === void 0 || v === null) continue;
|
|
460
|
+
parts.push(`${k}=${String(v).replace(/\s+/g, " ")}`);
|
|
461
|
+
}
|
|
462
|
+
const dir = dirname(path);
|
|
463
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
464
|
+
const tail = parts.length ? " " + parts.join(" ") : "";
|
|
465
|
+
appendFileSync(path, `${ledgerStamp(now)} ${event}${tail}\n`, "utf8");
|
|
466
|
+
}
|
|
467
|
+
/** The counts `pai worker log` prints, over today's lines or the whole file. */
|
|
468
|
+
function ledgerSummary(path, scope, lastN = 15, now = /* @__PURE__ */ new Date()) {
|
|
469
|
+
if (!existsSync(path)) return null;
|
|
470
|
+
const text = readFileSync(path, "utf8");
|
|
471
|
+
const today = ledgerStamp(now).slice(0, 10);
|
|
472
|
+
const lines = text.split("\n").filter((l) => l.trim());
|
|
473
|
+
const parsed = (scope === "all" ? lines : lines.filter((l) => l.startsWith(today))).map(parseLedgerLine).filter((x) => x !== null);
|
|
474
|
+
const count = (ev) => parsed.filter((p) => p.event === ev).length;
|
|
475
|
+
const ends = parsed.filter((p) => p.event === "WORKER-END");
|
|
476
|
+
const ok = ends.filter((p) => p.fields.rc === "0").length;
|
|
477
|
+
return {
|
|
478
|
+
scope: scope === "all" ? "all time" : `today ${today}`,
|
|
479
|
+
started: count("WORKER-START"),
|
|
480
|
+
endedOk: ok,
|
|
481
|
+
endedFailed: ends.length - ok,
|
|
482
|
+
denied: count("DENIED-ANTHROPIC-AGENT"),
|
|
483
|
+
allowed: count("ALLOWED-ANTHROPIC-AGENT"),
|
|
484
|
+
reroutes: count("WORKER-REROUTE"),
|
|
485
|
+
lastLines: lines.slice(-lastN)
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
//#endregion
|
|
490
|
+
//#region src/workers/pending.ts
|
|
491
|
+
/**
|
|
492
|
+
* Pending worker results: finished workers whose worktree branch still holds
|
|
493
|
+
* work that never reached the repo (commits not in HEAD, or uncommitted
|
|
494
|
+
* files). Surfaced by `pai worker ps/pending`, the SessionStart hook, the
|
|
495
|
+
* status line and the prepublish gate so an unmerged fix cannot be forgotten.
|
|
496
|
+
*/
|
|
497
|
+
/** Stale after this long: `pai worker gc` (archive) instead of merge. */
|
|
498
|
+
const STALE_HOURS = 24;
|
|
499
|
+
function toplevel(dir) {
|
|
500
|
+
try {
|
|
501
|
+
return git(dir, ["rev-parse", "--show-toplevel"]);
|
|
502
|
+
} catch {
|
|
503
|
+
return null;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
function fmtAge(ms) {
|
|
507
|
+
const h = Math.floor(ms / 36e5);
|
|
508
|
+
return h >= 48 ? `${Math.floor(h / 24)}d` : h >= 1 ? `${h}h` : `${Math.floor(ms / 6e4)}m`;
|
|
509
|
+
}
|
|
510
|
+
/** Finished workers with unmerged work; `repoRoot` limits to one repo, else every repo. */
|
|
511
|
+
function pendingResults(logDir, repoRoot, now = Date.now()) {
|
|
512
|
+
const want = repoRoot ? toplevel(repoRoot) : null;
|
|
513
|
+
if (repoRoot && !want) return [];
|
|
514
|
+
const out = [];
|
|
515
|
+
for (const st of loadStatuses(logDir)) {
|
|
516
|
+
if (st.archived || st.merged || isLive(st)) continue;
|
|
517
|
+
if (!st.worktreeDir || !existsSync(st.worktreeDir)) continue;
|
|
518
|
+
const repo = toplevel(st.cwd);
|
|
519
|
+
if (!repo || want && repo !== want) continue;
|
|
520
|
+
let commits = 0;
|
|
521
|
+
let dirty = 0;
|
|
522
|
+
try {
|
|
523
|
+
if (st.branch) commits = git(repo, [
|
|
524
|
+
"cherry",
|
|
525
|
+
"HEAD",
|
|
526
|
+
`refs/heads/${st.branch}`
|
|
527
|
+
]).split("\n").filter((l) => l.startsWith("+")).length;
|
|
528
|
+
dirty = uncommittedPaths(st.worktreeDir).filter((p) => !/(^|\/)node_modules(\/|$)/.test(p)).length;
|
|
529
|
+
} catch {
|
|
530
|
+
continue;
|
|
531
|
+
}
|
|
532
|
+
if (!commits && !dirty) continue;
|
|
533
|
+
let ageMs = 0;
|
|
534
|
+
try {
|
|
535
|
+
ageMs = Math.max(0, now - statSync(statusPath(logDir, st.id)).mtimeMs);
|
|
536
|
+
} catch {}
|
|
537
|
+
out.push({
|
|
538
|
+
id: st.id,
|
|
539
|
+
label: st.label,
|
|
540
|
+
repo,
|
|
541
|
+
ageMs,
|
|
542
|
+
age: fmtAge(ageMs),
|
|
543
|
+
commits,
|
|
544
|
+
dirty
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
return out;
|
|
548
|
+
}
|
|
549
|
+
/** One human line per result, with the exact next command. */
|
|
550
|
+
function formatPending(results, showRepo = false) {
|
|
551
|
+
return results.map((r) => {
|
|
552
|
+
const next = r.ageMs > STALE_HOURS * 36e5 ? "pai worker gc" : `pai worker merge ${r.id}`;
|
|
553
|
+
const repo = showRepo ? ` ${r.repo}` : "";
|
|
554
|
+
return `${r.id} ${r.age} ${r.commits} commit(s), ${r.dirty} dirty ${r.label}${repo} -> ${next}`;
|
|
555
|
+
}).join("\n");
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Release gate: exit code and message for `pai worker pending --gate`.
|
|
559
|
+
* PAI_ALLOW_PENDING=1 overrides.
|
|
560
|
+
*/
|
|
561
|
+
function pendingGate(results, env = process.env) {
|
|
562
|
+
if (!results.length || env.PAI_ALLOW_PENDING === "1") return {
|
|
563
|
+
code: 0,
|
|
564
|
+
message: ""
|
|
565
|
+
};
|
|
566
|
+
return {
|
|
567
|
+
code: 1,
|
|
568
|
+
message: `${results.length} unmerged worker result(s) in this repo — merge or discard before publishing:\n${formatPending(results)}\nOverride deliberately with PAI_ALLOW_PENDING=1.`
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
/** Invalidate pending cache entries for a repo and its subdirectories. */
|
|
572
|
+
function invalidatePendingCache(logDir, repoRoot) {
|
|
573
|
+
const file = join(logDir, "pending-cache.json");
|
|
574
|
+
let cache = {};
|
|
575
|
+
try {
|
|
576
|
+
cache = JSON.parse(readFileSync(file, "utf8"));
|
|
577
|
+
} catch {
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
const resolved = repoRoot.endsWith("/") ? repoRoot : `${repoRoot}/`;
|
|
581
|
+
let changed = false;
|
|
582
|
+
for (const key of Object.keys(cache)) if (key === repoRoot || key.startsWith(resolved)) {
|
|
583
|
+
delete cache[key];
|
|
584
|
+
changed = true;
|
|
585
|
+
}
|
|
586
|
+
if (!changed) return;
|
|
587
|
+
try {
|
|
588
|
+
writeFileSync(file, JSON.stringify(cache));
|
|
589
|
+
} catch {}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
//#endregion
|
|
593
|
+
//#region src/workers/worktree.ts
|
|
594
|
+
/**
|
|
595
|
+
* worktree.ts — one git worktree per writing worker.
|
|
596
|
+
*
|
|
597
|
+
* A run whose class edits files (implement, complex, plan) and whose cwd is a
|
|
598
|
+
* git repository gets its own worktree by default: `git worktree add
|
|
599
|
+
* <logDir>/worktrees/<id> -b worker/<id>` from the current HEAD. The worker
|
|
600
|
+
* commits its own work on that branch — the no-commit rule applies to the
|
|
601
|
+
* main branch only — and the parent (or the operator) merges the result back:
|
|
602
|
+
*
|
|
603
|
+
* pai worker merge <id> git merge --no-ff worker/<id> + remove worktree + delete branch
|
|
604
|
+
* pai worker discard <id> remove worktree and branch, keep nothing
|
|
605
|
+
*
|
|
606
|
+
* `ps` marks a worker with an unmerged branch `⎇`. Draft and review run in
|
|
607
|
+
* place; `--no-worktree` opts out, `--worktree` forces one on.
|
|
608
|
+
*/
|
|
609
|
+
function worktreesDir(logDir) {
|
|
610
|
+
return join(logDir, "worktrees");
|
|
611
|
+
}
|
|
612
|
+
function worktreeBranch(id) {
|
|
613
|
+
return `worker/${id}`;
|
|
614
|
+
}
|
|
615
|
+
function worktreePath(logDir, id) {
|
|
616
|
+
return join(worktreesDir(logDir), id);
|
|
617
|
+
}
|
|
618
|
+
/** Run git in `cwd` with an optional env override, trimmed stdout, stderr on failure. */
|
|
619
|
+
function runGit(cwd, args, env, timeout = 3e4) {
|
|
620
|
+
try {
|
|
621
|
+
return execFileSync("git", [
|
|
622
|
+
"-C",
|
|
623
|
+
cwd,
|
|
624
|
+
...args
|
|
625
|
+
], {
|
|
626
|
+
encoding: "utf8",
|
|
627
|
+
timeout,
|
|
628
|
+
stdio: [
|
|
629
|
+
"ignore",
|
|
630
|
+
"pipe",
|
|
631
|
+
"pipe"
|
|
632
|
+
],
|
|
633
|
+
...env ? { env } : {}
|
|
634
|
+
}).trim();
|
|
635
|
+
} catch (e) {
|
|
636
|
+
const err = e;
|
|
637
|
+
const why = (typeof err.stderr === "string" ? err.stderr : err.stderr?.toString("utf8")) || err.message || String(e);
|
|
638
|
+
throw new Error(`git ${args.join(" ")} in ${cwd}: ${why.trim()}`);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
/** Run git in `cwd`, returning trimmed stdout; throws with stderr on failure. */
|
|
642
|
+
function git(cwd, args, timeoutMs) {
|
|
643
|
+
return runGit(cwd, args, void 0, timeoutMs);
|
|
644
|
+
}
|
|
645
|
+
/** Is `cwd` inside a git repository (a .git dir — worktrees: a .git file)? */
|
|
646
|
+
function isGitRepo(cwd) {
|
|
647
|
+
try {
|
|
648
|
+
return git(cwd, ["rev-parse", "--git-dir"]) !== "";
|
|
649
|
+
} catch {
|
|
650
|
+
return false;
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
/** Tools that can write to the checkout (Bash can, via the shell). */
|
|
654
|
+
const WRITING_TOOLS = [
|
|
655
|
+
"Edit",
|
|
656
|
+
"Write",
|
|
657
|
+
"MultiEdit",
|
|
658
|
+
"NotebookEdit",
|
|
659
|
+
"Bash"
|
|
660
|
+
];
|
|
661
|
+
/** Can a run with these --allowedTools write? No restriction at all means yes. */
|
|
662
|
+
function toolsCanWrite(allowedTools) {
|
|
663
|
+
const names = allowedTools.flatMap((e) => e.split(",")).map((s) => s.trim().replace(/\(.*$/, "")).filter(Boolean);
|
|
664
|
+
return !names.length || names.some((n) => WRITING_TOOLS.includes(n));
|
|
665
|
+
}
|
|
666
|
+
/** Should this run get a worktree? Explicit flag first, then: can it write? */
|
|
667
|
+
function worktreeWanted(flag, opts) {
|
|
668
|
+
if (flag !== void 0) return flag;
|
|
669
|
+
return toolsCanWrite(opts.allowedTools) && isGitRepo(opts.cwd);
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* Commit `cwd`'s current index + working tree (including untracked files) as
|
|
673
|
+
* a floating commit on top of HEAD, without touching the real index, working
|
|
674
|
+
* tree or HEAD: a temporary `GIT_INDEX_FILE` collects the snapshot, `git
|
|
675
|
+
* commit-tree` writes the commit object directly (it updates no ref). The
|
|
676
|
+
* caller then branches a worktree from that commit, so the worktree sees
|
|
677
|
+
* exactly what was on disk, uncommitted or not.
|
|
678
|
+
*/
|
|
679
|
+
function snapshotUncommitted(cwd, id, head) {
|
|
680
|
+
const idxDir = mkdtempSync(join(tmpdir(), "pai-worktree-idx-"));
|
|
681
|
+
const idx = join(idxDir, "index");
|
|
682
|
+
try {
|
|
683
|
+
const env = {
|
|
684
|
+
...process.env,
|
|
685
|
+
GIT_INDEX_FILE: idx
|
|
686
|
+
};
|
|
687
|
+
runGit(cwd, ["read-tree", head], env);
|
|
688
|
+
runGit(cwd, ["add", "-A"], env);
|
|
689
|
+
return runGit(cwd, [
|
|
690
|
+
"commit-tree",
|
|
691
|
+
runGit(cwd, ["write-tree"], env),
|
|
692
|
+
"-p",
|
|
693
|
+
head,
|
|
694
|
+
"-m",
|
|
695
|
+
`worker ${id}: snapshot of uncommitted checkout`
|
|
696
|
+
]);
|
|
697
|
+
} finally {
|
|
698
|
+
rmSync(idxDir, {
|
|
699
|
+
recursive: true,
|
|
700
|
+
force: true
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
/**
|
|
705
|
+
* Create the worktree and branch for `id` from `cwd`'s HEAD — or, when the
|
|
706
|
+
* checkout has uncommitted changes, from a snapshot commit of that dirty
|
|
707
|
+
* state (see `snapshotUncommitted`), so a worktree worker sees the same
|
|
708
|
+
* files the operator sees, not just what was last committed. Throws when git
|
|
709
|
+
* refuses (no commits yet, branch exists, …) — the caller decides whether to
|
|
710
|
+
* degrade to an in-place run.
|
|
711
|
+
*/
|
|
712
|
+
function addWorktree(logDir, id, cwd) {
|
|
713
|
+
const dir = worktreePath(logDir, id);
|
|
714
|
+
const branch = worktreeBranch(id);
|
|
715
|
+
const head = git(cwd, ["rev-parse", "HEAD"]);
|
|
716
|
+
const dirty = dirtyPaths(cwd).length > 0;
|
|
717
|
+
const base = dirty ? snapshotUncommitted(cwd, id, head) : head;
|
|
718
|
+
git(cwd, [
|
|
719
|
+
"worktree",
|
|
720
|
+
"add",
|
|
721
|
+
dir,
|
|
722
|
+
"-b",
|
|
723
|
+
branch,
|
|
724
|
+
base
|
|
725
|
+
]);
|
|
726
|
+
provisionDeps(logDir, id, cwd, dir);
|
|
727
|
+
return {
|
|
728
|
+
dir,
|
|
729
|
+
branch,
|
|
730
|
+
base,
|
|
731
|
+
snapshot: dirty
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
/**
|
|
735
|
+
* Give the worktree its own dependencies so the worker never has to improvise
|
|
736
|
+
* (symlinking node_modules to the main checkout, building in a /tmp copy).
|
|
737
|
+
* A real node_modules directory in the main checkout is APFS-cloned
|
|
738
|
+
* (`cp -c`, copy-on-write, near instant); elsewhere the lockfile installs it.
|
|
739
|
+
* Never a symlink. Time-boxed and best effort: a failure is logged, the run
|
|
740
|
+
* goes on.
|
|
741
|
+
*/
|
|
742
|
+
function provisionDeps(logDir, id, cwd, wtDir) {
|
|
743
|
+
const note = (n) => appendLedger(ledgerPath(logDir), "WORKER-NOTE", {
|
|
744
|
+
id,
|
|
745
|
+
note: n
|
|
746
|
+
});
|
|
747
|
+
try {
|
|
748
|
+
const main = join(git(cwd, ["rev-parse", "--show-toplevel"]), "node_modules");
|
|
749
|
+
const dest = join(wtDir, "node_modules");
|
|
750
|
+
if (!existsSync(main) || lstatSync(main).isSymbolicLink() || existsSync(dest)) return;
|
|
751
|
+
try {
|
|
752
|
+
git(wtDir, [
|
|
753
|
+
"check-ignore",
|
|
754
|
+
"-q",
|
|
755
|
+
"node_modules"
|
|
756
|
+
]);
|
|
757
|
+
} catch {
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
const t0 = Date.now();
|
|
761
|
+
const opts = {
|
|
762
|
+
cwd: wtDir,
|
|
763
|
+
stdio: "ignore",
|
|
764
|
+
timeout: 18e4
|
|
765
|
+
};
|
|
766
|
+
if (platform() === "darwin") try {
|
|
767
|
+
execFileSync("cp", [
|
|
768
|
+
"-cR",
|
|
769
|
+
main,
|
|
770
|
+
dest
|
|
771
|
+
], opts);
|
|
772
|
+
note(`node_modules cloned (apfs) in ${Date.now() - t0}ms`);
|
|
773
|
+
return;
|
|
774
|
+
} catch {
|
|
775
|
+
rmSync(dest, {
|
|
776
|
+
recursive: true,
|
|
777
|
+
force: true
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
if (existsSync(join(wtDir, "bun.lock"))) execFileSync("bun", ["install", "--frozen-lockfile"], opts);
|
|
781
|
+
else if (existsSync(join(wtDir, "package-lock.json"))) execFileSync("npm", ["ci"], opts);
|
|
782
|
+
else return;
|
|
783
|
+
note(`node_modules installed from lockfile in ${Date.now() - t0}ms`);
|
|
784
|
+
} catch (e) {
|
|
785
|
+
try {
|
|
786
|
+
note(`node_modules provisioning failed: ${e.message}`);
|
|
787
|
+
} catch {}
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
/** Commits the branch collected on top of its base. */
|
|
791
|
+
function commitsSince(dir, base) {
|
|
792
|
+
try {
|
|
793
|
+
return parseInt(git(dir, [
|
|
794
|
+
"rev-list",
|
|
795
|
+
"--count",
|
|
796
|
+
`${base}..HEAD`
|
|
797
|
+
]), 10) || 0;
|
|
798
|
+
} catch {
|
|
799
|
+
return 0;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* Record the worktree result in the status file: branch and commit count on
|
|
804
|
+
* success, the worktree cleaned up on failure. Returns the updated status.
|
|
805
|
+
*/
|
|
806
|
+
function recordWorktree(logDir, status, info, ok) {
|
|
807
|
+
const s = { ...status };
|
|
808
|
+
if (ok) {
|
|
809
|
+
s.branch = info.branch;
|
|
810
|
+
s.commits = commitsSince(info.dir, info.base);
|
|
811
|
+
s.worktreeDir = info.dir;
|
|
812
|
+
s.worktreeBase = info.base;
|
|
813
|
+
s.worktreeSnapshot = info.snapshot;
|
|
814
|
+
} else if (safeCommitsSince(info.dir, info.base) > 0) {
|
|
815
|
+
s.branch = info.branch;
|
|
816
|
+
s.commits = commitsSince(info.dir, info.base);
|
|
817
|
+
s.worktreeDir = info.dir;
|
|
818
|
+
s.worktreeBase = info.base;
|
|
819
|
+
s.worktreeSnapshot = info.snapshot;
|
|
820
|
+
} else {
|
|
821
|
+
removeWorktree(s.cwd, info.dir, true);
|
|
822
|
+
try {
|
|
823
|
+
git(s.cwd, [
|
|
824
|
+
"branch",
|
|
825
|
+
"-D",
|
|
826
|
+
info.branch
|
|
827
|
+
]);
|
|
828
|
+
} catch {}
|
|
829
|
+
s.branch = null;
|
|
830
|
+
s.worktreeDir = null;
|
|
831
|
+
s.worktreeBase = null;
|
|
832
|
+
s.commits = null;
|
|
833
|
+
s.worktreeSnapshot = null;
|
|
834
|
+
}
|
|
835
|
+
saveStatus(logDir, s);
|
|
836
|
+
invalidatePendingCache(logDir, s.cwd);
|
|
837
|
+
return s;
|
|
838
|
+
}
|
|
839
|
+
function safeCommitsSince(dir, base) {
|
|
840
|
+
try {
|
|
841
|
+
return commitsSince(dir, base);
|
|
842
|
+
} catch {
|
|
843
|
+
return 0;
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* Salvage for an exit path (run finaliser, kill signal): commit whatever the
|
|
848
|
+
* worker left uncommitted, log WORKER-SALVAGE, never throw. Bounded by
|
|
849
|
+
* `timeoutMs` per git call. Returns the committed paths.
|
|
850
|
+
*/
|
|
851
|
+
function salvageOnExit(ledger, id, label, wtDir, timeoutMs) {
|
|
852
|
+
try {
|
|
853
|
+
const { committed, skipped } = salvageUncommitted(wtDir, label, timeoutMs);
|
|
854
|
+
if (committed.length) appendLedger(ledger, "WORKER-SALVAGE", {
|
|
855
|
+
id,
|
|
856
|
+
paths: committed.join(","),
|
|
857
|
+
skipped: skipped.length
|
|
858
|
+
});
|
|
859
|
+
if (skipped.length) appendLedger(ledger, "WORKER-NOTE", {
|
|
860
|
+
id,
|
|
861
|
+
note: `salvage skipped: ${skipped.join("; ")}`
|
|
862
|
+
});
|
|
863
|
+
return committed;
|
|
864
|
+
} catch (e) {
|
|
865
|
+
try {
|
|
866
|
+
appendLedger(ledger, "WORKER-NOTE", {
|
|
867
|
+
id,
|
|
868
|
+
note: `salvage failed: ${e.message}`
|
|
869
|
+
});
|
|
870
|
+
} catch {}
|
|
871
|
+
return [];
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
/** Remove a worktree directory from git's books and the filesystem. */
|
|
875
|
+
function removeWorktree(cwd, dir, force) {
|
|
876
|
+
try {
|
|
877
|
+
git(cwd, [
|
|
878
|
+
"worktree",
|
|
879
|
+
"remove",
|
|
880
|
+
...force ? ["--force"] : [],
|
|
881
|
+
dir
|
|
882
|
+
]);
|
|
883
|
+
return;
|
|
884
|
+
} catch {}
|
|
885
|
+
if (existsSync(dir)) try {
|
|
886
|
+
rmSync(dir, {
|
|
887
|
+
recursive: true,
|
|
888
|
+
force: true
|
|
889
|
+
});
|
|
890
|
+
git(cwd, ["worktree", "prune"]);
|
|
891
|
+
} catch {}
|
|
892
|
+
}
|
|
893
|
+
/**
|
|
894
|
+
* Tracked changes (staged or not) plus untracked files — everything a
|
|
895
|
+
* `git add -A` in `wtDir` would commit. The same two calls the old patch
|
|
896
|
+
* carry used; name-only, not porcelain: a worktree-only change renders as
|
|
897
|
+
* " M path" and the shared git() helper trims that leading space away.
|
|
898
|
+
*/
|
|
899
|
+
function uncommittedPaths(wtDir, timeoutMs) {
|
|
900
|
+
const tracked = git(wtDir, [
|
|
901
|
+
"diff",
|
|
902
|
+
"--name-only",
|
|
903
|
+
"HEAD"
|
|
904
|
+
], timeoutMs).split("\n").filter(Boolean);
|
|
905
|
+
const untracked = git(wtDir, [
|
|
906
|
+
"ls-files",
|
|
907
|
+
"--others",
|
|
908
|
+
"--exclude-standard"
|
|
909
|
+
], timeoutMs).split("\n").filter(Boolean);
|
|
910
|
+
return [...tracked, ...untracked];
|
|
911
|
+
}
|
|
912
|
+
/**
|
|
913
|
+
* True when `wtDir`/`relPath` is a symlink whose target resolves outside
|
|
914
|
+
* `wtDir` — e.g. a worker's `node_modules -> <main checkout>/node_modules`
|
|
915
|
+
* convenience link. A `.gitignore` using `dir/` (directories only) does not
|
|
916
|
+
* ignore such a link, so it turns up as untracked; staging and merging it
|
|
917
|
+
* lets git replace the real directory on the other side with a symlink to
|
|
918
|
+
* itself. Never a candidate for salvage.
|
|
919
|
+
*/
|
|
920
|
+
function symlinkEscapesWorktree(wtDir, relPath) {
|
|
921
|
+
const full = join(wtDir, relPath);
|
|
922
|
+
let stat;
|
|
923
|
+
try {
|
|
924
|
+
stat = lstatSync(full);
|
|
925
|
+
} catch {
|
|
926
|
+
return false;
|
|
927
|
+
}
|
|
928
|
+
if (!stat.isSymbolicLink()) return false;
|
|
929
|
+
const target = readlinkSync(full);
|
|
930
|
+
const resolvedTarget = isAbsolute(target) ? target : resolve(dirname(full), target);
|
|
931
|
+
const realTarget = existsSync(resolvedTarget) ? realpathSync(resolvedTarget) : resolvedTarget;
|
|
932
|
+
const realWtDir = realpathSync(wtDir);
|
|
933
|
+
return realTarget !== realWtDir && !realTarget.startsWith(realWtDir + sep);
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* Commit a worktree's uncommitted changes to its branch so the merge carries
|
|
937
|
+
* them. `git merge` only moves committed work, so a worker that stopped
|
|
938
|
+
* without committing would lose its edits to `worktree remove` — exactly
|
|
939
|
+
* what happened live on 2026-09-17. Returns the salvaged paths, empty when
|
|
940
|
+
* the worktree is clean. A symlink pointing outside the worktree (see
|
|
941
|
+
* `symlinkEscapesWorktree`) is never staged; it is left on disk and reported
|
|
942
|
+
* as skipped instead. A failed commit throws with the worktree untouched:
|
|
943
|
+
* its edits are still on disk, so nothing is lost.
|
|
944
|
+
*/
|
|
945
|
+
function salvageUncommitted(wtDir, label, timeoutMs) {
|
|
946
|
+
const paths = uncommittedPaths(wtDir, timeoutMs);
|
|
947
|
+
if (!paths.length) return {
|
|
948
|
+
committed: [],
|
|
949
|
+
skipped: []
|
|
950
|
+
};
|
|
951
|
+
const skipped = [];
|
|
952
|
+
const missing = new Set(git(wtDir, ["ls-files", "--deleted"], timeoutMs).split("\n").filter(Boolean));
|
|
953
|
+
const toStage = [];
|
|
954
|
+
for (const p of paths) if (missing.has(p)) skipped.push(`${p} (missing, not committed)`);
|
|
955
|
+
else if (symlinkEscapesWorktree(wtDir, p)) skipped.push(`symlink ${p} -> ${readlinkSync(join(wtDir, p))} (points outside the worktree)`);
|
|
956
|
+
else toStage.push(p);
|
|
957
|
+
if (!toStage.length) return {
|
|
958
|
+
committed: [],
|
|
959
|
+
skipped
|
|
960
|
+
};
|
|
961
|
+
try {
|
|
962
|
+
git(wtDir, [
|
|
963
|
+
"add",
|
|
964
|
+
"--ignore-removal",
|
|
965
|
+
"--",
|
|
966
|
+
".",
|
|
967
|
+
...paths.filter((p) => !toStage.includes(p)).map((p) => `:(exclude,literal)${p}`)
|
|
968
|
+
], timeoutMs);
|
|
969
|
+
const deleted = git(wtDir, [
|
|
970
|
+
"diff",
|
|
971
|
+
"--cached",
|
|
972
|
+
"--diff-filter=D",
|
|
973
|
+
"--name-only"
|
|
974
|
+
], timeoutMs).split("\n").filter(Boolean);
|
|
975
|
+
if (deleted.length > MAX_SALVAGE_DELETES) {
|
|
976
|
+
git(wtDir, ["reset", "-q"], timeoutMs);
|
|
977
|
+
throw new Error(`salvage would delete ${deleted.length} tracked files (${deleted.slice(0, 5).join(", ")}, ...), refused`);
|
|
978
|
+
}
|
|
979
|
+
git(wtDir, [
|
|
980
|
+
"commit",
|
|
981
|
+
"-m",
|
|
982
|
+
`salvaged: ${label}`
|
|
983
|
+
], timeoutMs);
|
|
984
|
+
} catch (e) {
|
|
985
|
+
throw new Error(`cannot salvage the uncommitted changes in ${wtDir} — ${e.message}; nothing was lost: commit them there by hand, then re-run merge`);
|
|
986
|
+
}
|
|
987
|
+
return {
|
|
988
|
+
committed: toStage,
|
|
989
|
+
skipped
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
/** A salvage commit that deletes more tracked files than this is refused. */
|
|
993
|
+
const MAX_SALVAGE_DELETES = 5;
|
|
994
|
+
/**
|
|
995
|
+
* The dirty paths of a checkout, parsed from `git status --porcelain -z`:
|
|
996
|
+
* NUL-separated (a path with a newline in it cannot corrupt the parse),
|
|
997
|
+
* rename entries contribute both sides, and any quoting is stripped.
|
|
998
|
+
*/
|
|
999
|
+
function dirtyPaths(cwd) {
|
|
1000
|
+
const fields = execFileSync("git", [
|
|
1001
|
+
"-C",
|
|
1002
|
+
cwd,
|
|
1003
|
+
"status",
|
|
1004
|
+
"--porcelain",
|
|
1005
|
+
"-z"
|
|
1006
|
+
], {
|
|
1007
|
+
encoding: "utf8",
|
|
1008
|
+
timeout: 3e4,
|
|
1009
|
+
stdio: [
|
|
1010
|
+
"ignore",
|
|
1011
|
+
"pipe",
|
|
1012
|
+
"pipe"
|
|
1013
|
+
]
|
|
1014
|
+
}).split("\0");
|
|
1015
|
+
const strip = (p) => p.startsWith("\"") && p.endsWith("\"") ? p.slice(1, -1) : p;
|
|
1016
|
+
const out = [];
|
|
1017
|
+
for (let i = 0; i < fields.length; i++) {
|
|
1018
|
+
const f = fields[i];
|
|
1019
|
+
if (!f || f.length < 4 || f.charAt(2) !== " ") continue;
|
|
1020
|
+
out.push(strip(f.slice(3)));
|
|
1021
|
+
const xy = f.slice(0, 2);
|
|
1022
|
+
if (xy.includes("R") || xy.includes("C")) {
|
|
1023
|
+
const orig = fields[i + 1];
|
|
1024
|
+
if (orig && orig.charAt(2) !== " ") {
|
|
1025
|
+
out.push(strip(orig));
|
|
1026
|
+
i += 1;
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
return out;
|
|
1031
|
+
}
|
|
1032
|
+
/**
|
|
1033
|
+
* Refuse the merge when the original checkout is dirty in paths the branch
|
|
1034
|
+
* touches: the merge would overwrite those edits or fail on them, either way
|
|
1035
|
+
* leaving a half-state. No merge is made, the worktree stays.
|
|
1036
|
+
*/
|
|
1037
|
+
function assertNoDirtyOverlap(cwd, incoming, id, branch) {
|
|
1038
|
+
const dirty = new Set(dirtyPaths(cwd));
|
|
1039
|
+
const overlap = [...new Set(incoming)].filter((p) => dirty.has(p)).sort();
|
|
1040
|
+
if (!overlap.length) return;
|
|
1041
|
+
throw new Error(`worker ${id}: the checkout ${cwd} has uncommitted changes in paths ${branch} touches: ${overlap.join(", ")}. Commit or stash them in the checkout, then re-run: pai worker merge ${id}. No merge was made; the worktree was kept.`);
|
|
1042
|
+
}
|
|
1043
|
+
/**
|
|
1044
|
+
* Never remove a worktree that still holds uncommitted changes — except a
|
|
1045
|
+
* symlink escaping the worktree (see `symlinkEscapesWorktree`): it was
|
|
1046
|
+
* deliberately left uncommitted by `salvageUncommitted`, and deleting the
|
|
1047
|
+
* link itself touches nothing outside the worktree.
|
|
1048
|
+
*/
|
|
1049
|
+
function assertWorktreeClean(wtDir, id) {
|
|
1050
|
+
const leftover = uncommittedPaths(wtDir).filter((p) => !symlinkEscapesWorktree(wtDir, p));
|
|
1051
|
+
if (leftover.length) throw new Error(`worker ${id}: the worktree ${wtDir} still holds uncommitted changes (${leftover.join(", ")}) — it was NOT removed; commit or copy them by hand, then re-run merge`);
|
|
1052
|
+
}
|
|
1053
|
+
/** Blob sha of `path` at `rev` in `cwd`, or null when it does not exist there. */
|
|
1054
|
+
function blobAt(cwd, rev, path) {
|
|
1055
|
+
try {
|
|
1056
|
+
return git(cwd, [
|
|
1057
|
+
"rev-parse",
|
|
1058
|
+
"--verify",
|
|
1059
|
+
"-q",
|
|
1060
|
+
`${rev}:${path}`
|
|
1061
|
+
]);
|
|
1062
|
+
} catch {
|
|
1063
|
+
return null;
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
/** Blob sha of `path` as it sits on disk in `cwd`, or null when it is absent. */
|
|
1067
|
+
function workingBlob(cwd, path) {
|
|
1068
|
+
if (!existsSync(join(cwd, path))) return null;
|
|
1069
|
+
try {
|
|
1070
|
+
return git(cwd, [
|
|
1071
|
+
"hash-object",
|
|
1072
|
+
"--",
|
|
1073
|
+
path
|
|
1074
|
+
]);
|
|
1075
|
+
} catch {
|
|
1076
|
+
return null;
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
/**
|
|
1080
|
+
* Refuse a snapshot merge when the checkout differs from the snapshot the
|
|
1081
|
+
* worker branched from, for any path the branch touched: the operator edited
|
|
1082
|
+
* it, or it was created/deleted since — applying the branch's diff on top
|
|
1083
|
+
* would silently discard that. Absent-in-both counts as equal.
|
|
1084
|
+
*/
|
|
1085
|
+
function assertNoSnapshotDrift(cwd, snapshot, paths, id) {
|
|
1086
|
+
const drifted = paths.filter((p) => blobAt(cwd, snapshot, p) !== workingBlob(cwd, p)).sort();
|
|
1087
|
+
if (!drifted.length) return;
|
|
1088
|
+
throw new Error(`worker ${id}: the checkout ${cwd} has changed since the worktree's snapshot in paths the branch touches: ${drifted.join(", ")}. Resolve by hand, then re-run: pai worker merge ${id}. No merge was made; the worktree was kept.`);
|
|
1089
|
+
}
|
|
1090
|
+
/**
|
|
1091
|
+
* `pai worker merge <id>` for a snapshot-based worktree (see `addWorktree`):
|
|
1092
|
+
* git's own merge only moves committed history, and the snapshot commit was
|
|
1093
|
+
* never on any branch reachable from `cwd`'s HEAD, so there is nothing to
|
|
1094
|
+
* `git merge` here. Instead the worker's own changes — `git diff --binary
|
|
1095
|
+
* <snapshot> <branch>` — are applied straight onto the checkout's working
|
|
1096
|
+
* tree as uncommitted edits, exactly like the uncommitted state the worker
|
|
1097
|
+
* started from. Works even if `cwd`'s HEAD moved since the snapshot: the
|
|
1098
|
+
* diff is applied to files, not merged into a tree.
|
|
1099
|
+
*/
|
|
1100
|
+
function mergeSnapshotWorker(logDir, id, st, noCommit = false) {
|
|
1101
|
+
const snapshot = st.worktreeBase;
|
|
1102
|
+
const branch = st.branch;
|
|
1103
|
+
const worktreeDir = st.worktreeDir;
|
|
1104
|
+
const salvage = existsSync(worktreeDir) ? salvageUncommitted(worktreeDir, st.label || UNLABELED) : {
|
|
1105
|
+
committed: [],
|
|
1106
|
+
skipped: []
|
|
1107
|
+
};
|
|
1108
|
+
if ((parseInt(git(st.cwd, [
|
|
1109
|
+
"rev-list",
|
|
1110
|
+
"--count",
|
|
1111
|
+
`${snapshot}..${branch}`
|
|
1112
|
+
]), 10) || 0) <= 0) throw new Error(`worker ${id}: branch ${branch} has no commits beyond its snapshot to merge. The worktree ${worktreeDir} was NOT removed — uncommitted work there would be destroyed. Commit it yourself, or drop everything with: pai worker discard ${id}`);
|
|
1113
|
+
const changedPaths = git(st.cwd, [
|
|
1114
|
+
"diff",
|
|
1115
|
+
"--name-only",
|
|
1116
|
+
snapshot,
|
|
1117
|
+
branch
|
|
1118
|
+
]).split("\n").filter(Boolean);
|
|
1119
|
+
assertNoSnapshotDrift(st.cwd, snapshot, changedPaths, id);
|
|
1120
|
+
const diff = execFileSync("git", [
|
|
1121
|
+
"-C",
|
|
1122
|
+
st.cwd,
|
|
1123
|
+
"diff",
|
|
1124
|
+
"--binary",
|
|
1125
|
+
snapshot,
|
|
1126
|
+
branch
|
|
1127
|
+
], {
|
|
1128
|
+
encoding: "utf8",
|
|
1129
|
+
timeout: 3e4,
|
|
1130
|
+
maxBuffer: 64 * 1024 * 1024
|
|
1131
|
+
});
|
|
1132
|
+
if (diff.trim()) try {
|
|
1133
|
+
execFileSync("git", [
|
|
1134
|
+
"-C",
|
|
1135
|
+
st.cwd,
|
|
1136
|
+
"apply",
|
|
1137
|
+
"--binary"
|
|
1138
|
+
], {
|
|
1139
|
+
input: diff,
|
|
1140
|
+
encoding: "utf8",
|
|
1141
|
+
timeout: 3e4,
|
|
1142
|
+
stdio: [
|
|
1143
|
+
"pipe",
|
|
1144
|
+
"pipe",
|
|
1145
|
+
"pipe"
|
|
1146
|
+
]
|
|
1147
|
+
});
|
|
1148
|
+
} catch (e) {
|
|
1149
|
+
const err = e;
|
|
1150
|
+
const why = (typeof err.stderr === "string" ? err.stderr : err.stderr?.toString("utf8")) || err.message || String(e);
|
|
1151
|
+
throw new Error(`worker ${id}: git refused to apply ${branch}'s changes to ${st.cwd} — ${why.trim()}. The worktree ${worktreeDir} was kept: resolve by hand, then re-run merge`);
|
|
1152
|
+
}
|
|
1153
|
+
if (noCommit) return noCommitNextSteps(id, branch, worktreeDir, changedPaths);
|
|
1154
|
+
removeWorktree(st.cwd, worktreeDir, true);
|
|
1155
|
+
try {
|
|
1156
|
+
git(st.cwd, [
|
|
1157
|
+
"branch",
|
|
1158
|
+
"-D",
|
|
1159
|
+
branch
|
|
1160
|
+
]);
|
|
1161
|
+
} catch {}
|
|
1162
|
+
saveStatus(logDir, {
|
|
1163
|
+
...st,
|
|
1164
|
+
merged: true
|
|
1165
|
+
});
|
|
1166
|
+
const base = `applied worker ${id}'s changes (branch ${branch}) to ${st.cwd} as uncommitted changes: ${changedPaths.join(", ")} (worktree removed, branch deleted)`;
|
|
1167
|
+
const notes = [];
|
|
1168
|
+
if (salvage.committed.length) notes.push(`salvaged ${salvage.committed.length} uncommitted change(s) onto the branch first: ${salvage.committed.join(", ")}`);
|
|
1169
|
+
if (salvage.skipped.length) notes.push(`skipped ${salvage.skipped.join(", ")}`);
|
|
1170
|
+
return notes.length ? `${base}; ${notes.join("; ")}` : base;
|
|
1171
|
+
}
|
|
1172
|
+
function noCommitNextSteps(id, branch, worktreeDir, paths) {
|
|
1173
|
+
return `applied worker ${id}'s changes (branch ${branch}) to the checkout as uncommitted changes: ${paths.join(", ")}. Branch and worktree ${worktreeDir} were kept. Next: review (git diff), commit, then run: pai worker gc`;
|
|
1174
|
+
}
|
|
1175
|
+
/**
|
|
1176
|
+
* `merge --no-commit`: apply base..branch to the checkout with a 3-way
|
|
1177
|
+
* `git apply`, leaving the result uncommitted. On conflict the tree is left
|
|
1178
|
+
* as is (markers + unmerged index entries) and the conflicted paths are listed.
|
|
1179
|
+
*/
|
|
1180
|
+
function applyNoCommit(cwd, id, branch, worktreeDir, base, paths) {
|
|
1181
|
+
const diff = execFileSync("git", [
|
|
1182
|
+
"-C",
|
|
1183
|
+
cwd,
|
|
1184
|
+
"diff",
|
|
1185
|
+
"--binary",
|
|
1186
|
+
`${base}..${branch}`
|
|
1187
|
+
], {
|
|
1188
|
+
encoding: "buffer",
|
|
1189
|
+
timeout: 3e4,
|
|
1190
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
1191
|
+
env: {
|
|
1192
|
+
...process.env,
|
|
1193
|
+
LC_ALL: "C"
|
|
1194
|
+
}
|
|
1195
|
+
});
|
|
1196
|
+
try {
|
|
1197
|
+
execFileSync("git", [
|
|
1198
|
+
"-C",
|
|
1199
|
+
cwd,
|
|
1200
|
+
"apply",
|
|
1201
|
+
"--3way",
|
|
1202
|
+
"--binary"
|
|
1203
|
+
], {
|
|
1204
|
+
input: diff,
|
|
1205
|
+
timeout: 3e4,
|
|
1206
|
+
stdio: [
|
|
1207
|
+
"pipe",
|
|
1208
|
+
"pipe",
|
|
1209
|
+
"pipe"
|
|
1210
|
+
],
|
|
1211
|
+
env: {
|
|
1212
|
+
...process.env,
|
|
1213
|
+
LC_ALL: "C"
|
|
1214
|
+
}
|
|
1215
|
+
});
|
|
1216
|
+
} catch (e) {
|
|
1217
|
+
const conflicted = git(cwd, [
|
|
1218
|
+
"diff",
|
|
1219
|
+
"--name-only",
|
|
1220
|
+
"--diff-filter=U"
|
|
1221
|
+
]).split("\n").filter(Boolean);
|
|
1222
|
+
const err = e;
|
|
1223
|
+
const why = ((typeof err.stderr === "string" ? err.stderr : err.stderr?.toString("utf8")) || err.message || "").trim();
|
|
1224
|
+
throw new Error(conflicted.length ? `worker ${id}: applying ${branch} conflicted in ${conflicted.join(", ")}. The tree was left for you: resolve those paths, review, commit; branch and worktree ${worktreeDir} were kept` : `worker ${id}: git refused to apply ${branch} to ${cwd} — ${why}. Nothing was changed; branch and worktree were kept`);
|
|
1225
|
+
}
|
|
1226
|
+
return noCommitNextSteps(id, branch, worktreeDir, paths);
|
|
1227
|
+
}
|
|
1228
|
+
/**
|
|
1229
|
+
* `pai worker verify <id>`: for every file the worker's branch (or its
|
|
1230
|
+
* refs/pai-archive/<id> archive once the branch is gone) changed since its
|
|
1231
|
+
* base, compare bytes with the working tree or `--against <ref>`.
|
|
1232
|
+
* identical = the target already holds the worker's version (a worker delete
|
|
1233
|
+
* counts as identical when the target lacks the file too); differs = other
|
|
1234
|
+
* bytes; missing = the worker's file is absent in the target; deleted = the
|
|
1235
|
+
* worker deleted it but the target still has it. ok = every file identical.
|
|
1236
|
+
*/
|
|
1237
|
+
function verifyWorker(logDir, id, opts = {}) {
|
|
1238
|
+
const st = loadStatus(logDir, id);
|
|
1239
|
+
if (!st) throw new Error(`no worker named "${id}"`);
|
|
1240
|
+
const env = {
|
|
1241
|
+
...process.env,
|
|
1242
|
+
LC_ALL: "C"
|
|
1243
|
+
};
|
|
1244
|
+
const bytes = (args) => {
|
|
1245
|
+
try {
|
|
1246
|
+
return execFileSync("git", [
|
|
1247
|
+
"-C",
|
|
1248
|
+
st.cwd,
|
|
1249
|
+
...args
|
|
1250
|
+
], {
|
|
1251
|
+
env,
|
|
1252
|
+
timeout: 3e4,
|
|
1253
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
1254
|
+
stdio: [
|
|
1255
|
+
"ignore",
|
|
1256
|
+
"pipe",
|
|
1257
|
+
"pipe"
|
|
1258
|
+
]
|
|
1259
|
+
});
|
|
1260
|
+
} catch {
|
|
1261
|
+
return null;
|
|
1262
|
+
}
|
|
1263
|
+
};
|
|
1264
|
+
const has = (ref) => bytes([
|
|
1265
|
+
"rev-parse",
|
|
1266
|
+
"--verify",
|
|
1267
|
+
"-q",
|
|
1268
|
+
`${ref}^{commit}`
|
|
1269
|
+
]) !== null;
|
|
1270
|
+
const ref = [`refs/heads/${worktreeBranch(id)}`, `refs/pai-archive/${id}`].find(has);
|
|
1271
|
+
if (!ref) throw new Error(`worker ${id}: neither ${worktreeBranch(id)} nor refs/pai-archive/${id} exists in ${st.cwd}`);
|
|
1272
|
+
const base = st.worktreeSnapshot && st.worktreeBase ? st.worktreeBase : git(st.cwd, [
|
|
1273
|
+
"merge-base",
|
|
1274
|
+
"HEAD",
|
|
1275
|
+
ref
|
|
1276
|
+
]);
|
|
1277
|
+
const list = (bytes([
|
|
1278
|
+
"diff",
|
|
1279
|
+
"--name-status",
|
|
1280
|
+
"--no-renames",
|
|
1281
|
+
"-z",
|
|
1282
|
+
`${base}..${ref}`
|
|
1283
|
+
]) ?? Buffer.alloc(0)).toString("utf8").split("\0").filter(Boolean);
|
|
1284
|
+
const files = [];
|
|
1285
|
+
for (let i = 0; i + 1 < list.length; i += 2) {
|
|
1286
|
+
const path = list[i + 1];
|
|
1287
|
+
const deleted = list[i] === "D";
|
|
1288
|
+
const target = opts.against ? bytes(["show", `${opts.against}:${path}`]) : existsSync(join(st.cwd, path)) ? readFileSync(join(st.cwd, path)) : null;
|
|
1289
|
+
let state;
|
|
1290
|
+
if (deleted) state = target ? "deleted" : "identical";
|
|
1291
|
+
else {
|
|
1292
|
+
const mine = bytes(["show", `${ref}:${path}`]);
|
|
1293
|
+
state = !target ? "missing" : mine && mine.equals(target) ? "identical" : "differs";
|
|
1294
|
+
}
|
|
1295
|
+
files.push({
|
|
1296
|
+
path,
|
|
1297
|
+
state
|
|
1298
|
+
});
|
|
1299
|
+
}
|
|
1300
|
+
return {
|
|
1301
|
+
id,
|
|
1302
|
+
ref,
|
|
1303
|
+
base,
|
|
1304
|
+
against: opts.against ?? "working tree",
|
|
1305
|
+
files,
|
|
1306
|
+
ok: files.every((f) => f.state === "identical")
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
/**
|
|
1310
|
+
* `pai worker merge <id>`: salvage whatever the worker left uncommitted onto
|
|
1311
|
+
* its branch, refuse when the original checkout is dirty in paths the branch
|
|
1312
|
+
* touches, merge with --no-ff (the merge commit names the worker), then
|
|
1313
|
+
* remove the worktree and delete the branch; the status gains `merged: true`.
|
|
1314
|
+
* A branch with nothing to merge is refused loudly — after salvage that
|
|
1315
|
+
* genuinely means it holds nothing, and reporting success there would
|
|
1316
|
+
* destroy the worktree for no gain.
|
|
1317
|
+
*/
|
|
1318
|
+
function mergeWorker(logDir, id, opts = {}) {
|
|
1319
|
+
const st = mustHaveBranch(logDir, id);
|
|
1320
|
+
if (st.merged) return `worker ${id}: branch ${st.branch} already merged`;
|
|
1321
|
+
if (st.worktreeSnapshot) return mergeSnapshotWorker(logDir, id, st, opts.noCommit);
|
|
1322
|
+
const salvage = existsSync(st.worktreeDir) ? salvageUncommitted(st.worktreeDir, st.label || UNLABELED) : {
|
|
1323
|
+
committed: [],
|
|
1324
|
+
skipped: []
|
|
1325
|
+
};
|
|
1326
|
+
if ((parseInt(git(st.cwd, [
|
|
1327
|
+
"rev-list",
|
|
1328
|
+
"--count",
|
|
1329
|
+
`HEAD..${st.branch}`
|
|
1330
|
+
]), 10) || 0) <= 0) throw new Error(`worker ${id}: branch ${st.branch} has no commits to merge. The worktree ${st.worktreeDir} was NOT removed — uncommitted work there would be destroyed. Commit it yourself, or drop everything with: pai worker discard ${id}`);
|
|
1331
|
+
const mergeBase = git(st.cwd, [
|
|
1332
|
+
"merge-base",
|
|
1333
|
+
"HEAD",
|
|
1334
|
+
st.branch
|
|
1335
|
+
]);
|
|
1336
|
+
const incomingPaths = git(st.cwd, [
|
|
1337
|
+
"diff",
|
|
1338
|
+
"--name-only",
|
|
1339
|
+
mergeBase,
|
|
1340
|
+
st.branch
|
|
1341
|
+
]).split("\n").filter(Boolean);
|
|
1342
|
+
assertNoDirtyOverlap(st.cwd, incomingPaths, id, st.branch);
|
|
1343
|
+
if (opts.noCommit) return applyNoCommit(st.cwd, id, st.branch, st.worktreeDir, mergeBase, incomingPaths);
|
|
1344
|
+
try {
|
|
1345
|
+
git(st.cwd, [
|
|
1346
|
+
"merge",
|
|
1347
|
+
"--no-ff",
|
|
1348
|
+
st.branch,
|
|
1349
|
+
"-m",
|
|
1350
|
+
`merge worker ${id} (${st.label})`
|
|
1351
|
+
]);
|
|
1352
|
+
} catch (e) {
|
|
1353
|
+
throw new Error(`worker ${id}: git refused the merge of ${st.branch} — ${e.message}. The worktree ${st.worktreeDir} was kept: resolve the conflict, then re-run merge`);
|
|
1354
|
+
}
|
|
1355
|
+
if (existsSync(st.worktreeDir)) assertWorktreeClean(st.worktreeDir, id);
|
|
1356
|
+
removeWorktree(st.cwd, st.worktreeDir, true);
|
|
1357
|
+
let branchGone = true;
|
|
1358
|
+
try {
|
|
1359
|
+
git(st.cwd, [
|
|
1360
|
+
"branch",
|
|
1361
|
+
"-d",
|
|
1362
|
+
st.branch
|
|
1363
|
+
]);
|
|
1364
|
+
} catch {
|
|
1365
|
+
branchGone = false;
|
|
1366
|
+
}
|
|
1367
|
+
saveStatus(logDir, {
|
|
1368
|
+
...st,
|
|
1369
|
+
merged: true
|
|
1370
|
+
});
|
|
1371
|
+
invalidatePendingCache(logDir, st.cwd);
|
|
1372
|
+
const base = `merged ${st.branch} into ${st.cwd} (worktree removed${branchGone ? ", branch deleted" : "; branch kept: git refused -d"})`;
|
|
1373
|
+
const notes = [];
|
|
1374
|
+
if (salvage.committed.length) notes.push(`salvaged ${salvage.committed.length} uncommitted change(s): ${salvage.committed.join(", ")}`);
|
|
1375
|
+
if (salvage.skipped.length) notes.push(`skipped ${salvage.skipped.join(", ")}`);
|
|
1376
|
+
return notes.length ? `${base}; ${notes.join("; ")}` : base;
|
|
1377
|
+
}
|
|
1378
|
+
/** `pai worker discard <id>`: drop worktree and branch, keep nothing. */
|
|
1379
|
+
function discardWorker(logDir, id) {
|
|
1380
|
+
const st = mustHaveBranch(logDir, id);
|
|
1381
|
+
removeWorktree(st.cwd, st.worktreeDir, true);
|
|
1382
|
+
let branchGone = false;
|
|
1383
|
+
try {
|
|
1384
|
+
git(st.cwd, [
|
|
1385
|
+
"branch",
|
|
1386
|
+
"-D",
|
|
1387
|
+
st.branch
|
|
1388
|
+
]);
|
|
1389
|
+
branchGone = true;
|
|
1390
|
+
} catch {
|
|
1391
|
+
branchGone = false;
|
|
1392
|
+
}
|
|
1393
|
+
saveStatus(logDir, {
|
|
1394
|
+
...st,
|
|
1395
|
+
branch: null,
|
|
1396
|
+
worktreeDir: null,
|
|
1397
|
+
worktreeBase: null,
|
|
1398
|
+
worktreeSnapshot: null,
|
|
1399
|
+
commits: null,
|
|
1400
|
+
merged: false
|
|
1401
|
+
});
|
|
1402
|
+
invalidatePendingCache(logDir, st.cwd);
|
|
1403
|
+
return `discarded worker ${id}: worktree removed${branchGone ? `, branch ${st.branch} deleted` : ""}`;
|
|
1404
|
+
}
|
|
1405
|
+
function mustHaveBranch(logDir, id) {
|
|
1406
|
+
const st = loadStatus(logDir, id);
|
|
1407
|
+
if (!st) throw new Error(`no worker named "${id}"`);
|
|
1408
|
+
if (!st.branch || !st.worktreeDir) throw new Error(`worker ${id} has no worktree branch to ${st.branch ? "clean up" : "merge"} — it ran in place or its branch was already handled`);
|
|
1409
|
+
return st;
|
|
1410
|
+
}
|
|
1411
|
+
/**
|
|
1412
|
+
* The paragraph a worktree run's system prompt gains: it may commit on its
|
|
1413
|
+
* own branch (the no-commit rule holds for the main branch only), it must not
|
|
1414
|
+
* merge or push itself, and the parent or operator merges.
|
|
1415
|
+
*/
|
|
1416
|
+
function worktreeSystemPrompt(id, branch, dir, snapshot = false) {
|
|
1417
|
+
return [
|
|
1418
|
+
"You are running in your own git worktree:",
|
|
1419
|
+
` ${dir} on branch ${branch} (worker id ${id}).`,
|
|
1420
|
+
"Commit your work on that branch as you go (git add / git commit) — committing here is expected;",
|
|
1421
|
+
"the no-commit rule applies to the main branch only, and this is not it.",
|
|
1422
|
+
"Do not merge, rebase or push; the operator merges your branch back with `pai worker merge`.",
|
|
1423
|
+
"Use ONLY relative paths inside the worktree, never absolute worktree paths — absolute paths break after merge and leak machine layout.",
|
|
1424
|
+
...snapshot ? ["This worktree was branched from a snapshot that includes files the parent checkout had uncommitted at spawn time — not just its last commit."] : []
|
|
1425
|
+
].join("\n");
|
|
1426
|
+
}
|
|
1427
|
+
/**
|
|
1428
|
+
* For headless runs WITHOUT a worktree: the worker shares the operator's
|
|
1429
|
+
* checkout with other in-flight workers, so a hook blocks git stash (except
|
|
1430
|
+
* list/show), reset, clean, checkout/restore of paths, switch, rebase and
|
|
1431
|
+
* merge — take baselines from measurements before editing, not from stash.
|
|
1432
|
+
*/
|
|
1433
|
+
function inPlaceSystemPrompt() {
|
|
1434
|
+
return [
|
|
1435
|
+
"You are running in the operator's shared git checkout, alongside other workers editing it at the same time.",
|
|
1436
|
+
"A hook blocks git stash (except list/show), reset, clean, checkout/restore of files, switch, rebase and merge — take baselines from measurements taken before you edit, not from stashing.",
|
|
1437
|
+
"Read-only git (status, diff, log, show, stash list) is fine."
|
|
1438
|
+
].join("\n");
|
|
1439
|
+
}
|
|
1440
|
+
const GC_STAMP = "gc-last";
|
|
1441
|
+
/**
|
|
1442
|
+
* Archive worktrees of finished workers older than `olderThanHours` and
|
|
1443
|
+
* status-less orphan directories: uncommitted state is salvaged onto the
|
|
1444
|
+
* branch, the branch is x, the worktree is
|
|
1445
|
+
* removed. Nothing is deleted without a salvage first; a failed salvage skips
|
|
1446
|
+
* that worktree. Running workers are never touched. `dryRun` reports only.
|
|
1447
|
+
*/
|
|
1448
|
+
function gcWorktrees(logDir, olderThanHours = 24, dryRun = false, now = Date.now()) {
|
|
1449
|
+
const cutoff = now - olderThanHours * 36e5;
|
|
1450
|
+
const out = [];
|
|
1451
|
+
const root = worktreesDir(logDir);
|
|
1452
|
+
const known = /* @__PURE__ */ new Set();
|
|
1453
|
+
const archive = (id, dir, st) => {
|
|
1454
|
+
const target = `refs/pai-archive/${id}`;
|
|
1455
|
+
if (dryRun) return void out.push({
|
|
1456
|
+
id,
|
|
1457
|
+
archive: target
|
|
1458
|
+
});
|
|
1459
|
+
try {
|
|
1460
|
+
let repo;
|
|
1461
|
+
try {
|
|
1462
|
+
const raw = git(dir, ["rev-parse", "--git-common-dir"]);
|
|
1463
|
+
repo = isAbsolute(raw) ? raw : resolve(dir, raw);
|
|
1464
|
+
} catch {
|
|
1465
|
+
throw new Error("not a git worktree");
|
|
1466
|
+
}
|
|
1467
|
+
const label = `archive: leftover state of worker ${id}`;
|
|
1468
|
+
if (uncommittedPaths(dir).length) {
|
|
1469
|
+
const res = salvageUncommitted(dir, label);
|
|
1470
|
+
if (res.committed.length) git(dir, [
|
|
1471
|
+
"commit",
|
|
1472
|
+
"--amend",
|
|
1473
|
+
"-q",
|
|
1474
|
+
"-m",
|
|
1475
|
+
label
|
|
1476
|
+
]);
|
|
1477
|
+
if (res.skipped.length && uncommittedPaths(dir).some((p) => !symlinkEscapesWorktree(dir, p))) throw new Error("uncommitted paths remain");
|
|
1478
|
+
}
|
|
1479
|
+
const src = worktreeBranch(id);
|
|
1480
|
+
let hasBranch = true;
|
|
1481
|
+
try {
|
|
1482
|
+
git(repo, [
|
|
1483
|
+
"rev-parse",
|
|
1484
|
+
"--verify",
|
|
1485
|
+
"-q",
|
|
1486
|
+
`refs/heads/${src}`
|
|
1487
|
+
]);
|
|
1488
|
+
} catch {
|
|
1489
|
+
hasBranch = false;
|
|
1490
|
+
}
|
|
1491
|
+
const tip = git(dir, ["rev-parse", "HEAD"]);
|
|
1492
|
+
if (hasBranch) git(repo, [
|
|
1493
|
+
"merge-base",
|
|
1494
|
+
"--is-ancestor",
|
|
1495
|
+
`refs/heads/${src}`,
|
|
1496
|
+
tip
|
|
1497
|
+
]);
|
|
1498
|
+
git(repo, [
|
|
1499
|
+
"update-ref",
|
|
1500
|
+
target,
|
|
1501
|
+
tip
|
|
1502
|
+
]);
|
|
1503
|
+
git(repo, [
|
|
1504
|
+
"worktree",
|
|
1505
|
+
"remove",
|
|
1506
|
+
"--force",
|
|
1507
|
+
dir
|
|
1508
|
+
]);
|
|
1509
|
+
if (hasBranch) git(repo, [
|
|
1510
|
+
"branch",
|
|
1511
|
+
"-D",
|
|
1512
|
+
src
|
|
1513
|
+
]);
|
|
1514
|
+
if (st) saveStatus(logDir, {
|
|
1515
|
+
...st,
|
|
1516
|
+
branch: null,
|
|
1517
|
+
worktreeDir: null,
|
|
1518
|
+
archived: target
|
|
1519
|
+
});
|
|
1520
|
+
appendLedger(ledgerPath(logDir), "WORKER-GC", {
|
|
1521
|
+
id,
|
|
1522
|
+
archive: target
|
|
1523
|
+
});
|
|
1524
|
+
out.push({
|
|
1525
|
+
id,
|
|
1526
|
+
archive: target
|
|
1527
|
+
});
|
|
1528
|
+
} catch (e) {
|
|
1529
|
+
out.push({
|
|
1530
|
+
id,
|
|
1531
|
+
skipped: e.message.split("\n")[0]
|
|
1532
|
+
});
|
|
1533
|
+
}
|
|
1534
|
+
};
|
|
1535
|
+
for (const st of loadStatuses(logDir)) {
|
|
1536
|
+
known.add(st.id);
|
|
1537
|
+
if (!st.worktreeDir || !existsSync(st.worktreeDir) || isLive(st)) continue;
|
|
1538
|
+
let end = 0;
|
|
1539
|
+
try {
|
|
1540
|
+
end = statSync(statusPath(logDir, st.id)).mtimeMs;
|
|
1541
|
+
} catch {
|
|
1542
|
+
continue;
|
|
1543
|
+
}
|
|
1544
|
+
if (end > cutoff) continue;
|
|
1545
|
+
archive(st.id, st.worktreeDir, st);
|
|
1546
|
+
}
|
|
1547
|
+
if (existsSync(root)) for (const ent of readdirSync(root, { withFileTypes: true })) {
|
|
1548
|
+
if (!ent.isDirectory() || known.has(ent.name) || existsSync(statusPath(logDir, ent.name))) continue;
|
|
1549
|
+
const dir = join(root, ent.name);
|
|
1550
|
+
try {
|
|
1551
|
+
if (statSync(dir).mtimeMs > cutoff) continue;
|
|
1552
|
+
} catch {
|
|
1553
|
+
continue;
|
|
1554
|
+
}
|
|
1555
|
+
archive(ent.name, dir, null);
|
|
1556
|
+
}
|
|
1557
|
+
if (!dryRun) for (const repo of new Set(loadStatuses(logDir).map((s) => s.cwd))) {
|
|
1558
|
+
try {
|
|
1559
|
+
git(repo, ["worktree", "prune"]);
|
|
1560
|
+
} catch {}
|
|
1561
|
+
invalidatePendingCache(logDir, repo);
|
|
1562
|
+
}
|
|
1563
|
+
return out;
|
|
1564
|
+
}
|
|
1565
|
+
/** Run `gcWorktrees` at most once per `everyMin` minutes (stamp file in the logDir). */
|
|
1566
|
+
function gcWorktreesThrottled(logDir, everyMin = 60, now = Date.now()) {
|
|
1567
|
+
const stamp = join(logDir, GC_STAMP);
|
|
1568
|
+
try {
|
|
1569
|
+
if (now - statSync(stamp).mtimeMs < everyMin * 6e4) return null;
|
|
1570
|
+
} catch {}
|
|
1571
|
+
mkdirSync(logDir, { recursive: true });
|
|
1572
|
+
writeFileSync(stamp, String(now), "utf8");
|
|
1573
|
+
return gcWorktrees(logDir, 24, false, now);
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
//#endregion
|
|
1577
|
+
export { newWorkerId as A, shortText as B, contextPercent as C, isLive as D, isChatPane as E, setWorkerLabel as F, panesDir as G, ensureNoMcpConfig as H, waitForTerminalStatus as I, routingStatePath as K, appendSystemPromptArgs as L, ownsPid as M, parseSleepSecs as N, loadStatus as O, saveStatus as P, longInlinePromptHint as R, contextLabel as S, elapsedOf as T, eventsPath as U, stripPromptValues as V, ledgerPath as W, appendLedger as _, git as a, ageOf as b, recordWorktree as c, worktreeSystemPrompt as d, worktreeWanted as f, pendingResults as g, pendingGate as h, gcWorktreesThrottled as i, nowStamp as j, loadStatuses as k, salvageOnExit as l, formatPending as m, discardWorker as n, inPlaceSystemPrompt as o, worktreesDir as p, workersLogDir as q, gcWorktrees as r, mergeWorker as s, addWorktree as t, verifyWorker as u, ledgerSummary as v, describeTool as w, alive as x, UNLABELED as y, parseRunnerArgs as z };
|
|
1578
|
+
//# sourceMappingURL=worktree-CwMRTa0H.mjs.map
|