@mycompbox/compbox-cli 1.21.9 → 1.21.10
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/.tsbuildinfo +1 -1
- package/commands/list.js +1 -1
- package/commands/list.js.map +1 -1
- package/commands/machines.d.ts +4 -0
- package/commands/machines.d.ts.map +1 -1
- package/commands/machines.js +61 -2
- package/commands/machines.js.map +1 -1
- package/commands/run.d.ts +27 -1
- package/commands/run.d.ts.map +1 -1
- package/commands/run.js +157 -36
- package/commands/run.js.map +1 -1
- package/commands/update.d.ts +19 -0
- package/commands/update.d.ts.map +1 -1
- package/commands/update.js +124 -7
- package/commands/update.js.map +1 -1
- package/commands/workspace.d.ts.map +1 -1
- package/commands/workspace.js +13 -1
- package/commands/workspace.js.map +1 -1
- package/index.js +5113 -1701
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/utils/agent-invoker.d.ts +214 -30
- package/utils/agent-invoker.d.ts.map +1 -1
- package/utils/agent-invoker.js +964 -370
- package/utils/agent-invoker.js.map +1 -1
- package/utils/brew.d.ts +10 -0
- package/utils/brew.d.ts.map +1 -1
- package/utils/brew.js +14 -0
- package/utils/brew.js.map +1 -1
- package/utils/cli-version.d.ts +3 -0
- package/utils/cli-version.d.ts.map +1 -0
- package/utils/cli-version.js +18 -0
- package/utils/cli-version.js.map +1 -0
- package/utils/cloud-preflight.d.ts +68 -0
- package/utils/cloud-preflight.d.ts.map +1 -0
- package/utils/cloud-preflight.js +287 -0
- package/utils/cloud-preflight.js.map +1 -0
- package/utils/config-store.d.ts +29 -0
- package/utils/config-store.d.ts.map +1 -1
- package/utils/config-store.js +30 -0
- package/utils/config-store.js.map +1 -1
- package/utils/install-cache.d.ts +105 -0
- package/utils/install-cache.d.ts.map +1 -0
- package/utils/install-cache.js +184 -0
- package/utils/install-cache.js.map +1 -0
- package/utils/mailbox-client.d.ts +113 -3
- package/utils/mailbox-client.d.ts.map +1 -1
- package/utils/mailbox-client.js +130 -6
- package/utils/mailbox-client.js.map +1 -1
- package/utils/merge-guard.d.ts +66 -0
- package/utils/merge-guard.d.ts.map +1 -0
- package/utils/merge-guard.js +271 -0
- package/utils/merge-guard.js.map +1 -0
- package/utils/merge-policy.d.ts +68 -0
- package/utils/merge-policy.d.ts.map +1 -0
- package/utils/merge-policy.js +129 -0
- package/utils/merge-policy.js.map +1 -0
- package/utils/progress-watcher.d.ts +53 -0
- package/utils/progress-watcher.d.ts.map +1 -0
- package/utils/progress-watcher.js +109 -0
- package/utils/progress-watcher.js.map +1 -0
- package/utils/project-checks.d.ts +72 -0
- package/utils/project-checks.d.ts.map +1 -0
- package/utils/project-checks.js +276 -0
- package/utils/project-checks.js.map +1 -0
- package/utils/run-timings.d.ts +59 -0
- package/utils/run-timings.d.ts.map +1 -0
- package/utils/run-timings.js +130 -0
- package/utils/run-timings.js.map +1 -0
- package/utils/run-workspace.d.ts +199 -2
- package/utils/run-workspace.d.ts.map +1 -1
- package/utils/run-workspace.js +896 -136
- package/utils/run-workspace.js.map +1 -1
- package/utils/self-update.d.ts +104 -0
- package/utils/self-update.d.ts.map +1 -0
- package/utils/self-update.js +391 -0
- package/utils/self-update.js.map +1 -0
- package/utils/usage-limit.d.ts +30 -0
- package/utils/usage-limit.d.ts.map +1 -0
- package/utils/usage-limit.js +186 -0
- package/utils/usage-limit.js.map +1 -0
- package/utils/wrap-up.d.ts +109 -0
- package/utils/wrap-up.d.ts.map +1 -0
- package/utils/wrap-up.js +260 -0
- package/utils/wrap-up.js.map +1 -0
package/utils/run-workspace.js
CHANGED
|
@@ -24,19 +24,22 @@
|
|
|
24
24
|
* Every git/gh/install call goes through an injectable runner so tests never
|
|
25
25
|
* touch a real repository.
|
|
26
26
|
*/
|
|
27
|
-
import { spawn } from
|
|
28
|
-
import { copyFileSync, existsSync, mkdirSync } from
|
|
29
|
-
import { basename, dirname, join } from
|
|
30
|
-
import {
|
|
31
|
-
import {
|
|
27
|
+
import { spawn } from "node:child_process";
|
|
28
|
+
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, utimesSync, writeFileSync, } from "node:fs";
|
|
29
|
+
import { basename, dirname, join } from "node:path";
|
|
30
|
+
import { formatNeedsInputText } from "@mycompbox/shared";
|
|
31
|
+
import { claudeChildEnvPath } from "./claude-runtime.js";
|
|
32
|
+
import { installPrePushGuard } from "./merge-guard.js";
|
|
33
|
+
import { DEFAULT_RUN_RETENTION_DAYS, getConfigDir, getRunRetentionMs } from "./config-store.js";
|
|
34
|
+
import { activeMarkerPath, activeMarkerProtects, detectLockfile, formatActiveMarker, orphanMarkers, parseActiveMarker, pidAlive, hashLockfile, installArgs, markerMatches, parseWorktreeList, readInstallMarker, selectStaleRuns, storeDirFor, waitingMarkerPath, writeInstallMarker, } from "./install-cache.js";
|
|
32
35
|
/** Set to "0" to keep finished runs local: no push, no pull request. */
|
|
33
|
-
export const RUN_PUSH_ENV =
|
|
36
|
+
export const RUN_PUSH_ENV = "COMPBOX_RUN_PUSH";
|
|
34
37
|
/** Install deps can take a while on a cold cache. */
|
|
35
38
|
const INSTALL_TIMEOUT_MS = 20 * 60 * 1_000;
|
|
36
39
|
const GIT_TIMEOUT_MS = 5 * 60 * 1_000;
|
|
37
40
|
export const defaultCommandRunner = (command, args, cwd) => new Promise((resolve) => {
|
|
38
|
-
let stdout =
|
|
39
|
-
let stderr =
|
|
41
|
+
let stdout = "";
|
|
42
|
+
let stderr = "";
|
|
40
43
|
let settled = false;
|
|
41
44
|
const done = (result) => {
|
|
42
45
|
if (settled)
|
|
@@ -47,70 +50,110 @@ export const defaultCommandRunner = (command, args, cwd) => new Promise((resolve
|
|
|
47
50
|
};
|
|
48
51
|
const child = spawn(command, args, {
|
|
49
52
|
cwd,
|
|
50
|
-
stdio: [
|
|
51
|
-
env: { ...process.env, PATH: claudeChildEnvPath(process.env.PATH), GIT_TERMINAL_PROMPT:
|
|
53
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
54
|
+
env: { ...process.env, PATH: claudeChildEnvPath(process.env.PATH), GIT_TERMINAL_PROMPT: "0" },
|
|
52
55
|
});
|
|
53
56
|
const timer = setTimeout(() => {
|
|
54
|
-
child.kill(
|
|
57
|
+
child.kill("SIGKILL");
|
|
55
58
|
done({ status: 1, stdout, stderr: `${command} timed out` });
|
|
56
|
-
}, command ===
|
|
57
|
-
child.stdout.on(
|
|
58
|
-
stdout += chunk.toString(
|
|
59
|
+
}, command === "git" || command === "gh" ? GIT_TIMEOUT_MS : INSTALL_TIMEOUT_MS);
|
|
60
|
+
child.stdout.on("data", (chunk) => {
|
|
61
|
+
stdout += chunk.toString("utf-8");
|
|
59
62
|
});
|
|
60
|
-
child.stderr.on(
|
|
61
|
-
stderr += chunk.toString(
|
|
63
|
+
child.stderr.on("data", (chunk) => {
|
|
64
|
+
stderr += chunk.toString("utf-8");
|
|
62
65
|
});
|
|
63
|
-
child.on(
|
|
66
|
+
child.on("error", (error) => {
|
|
64
67
|
done({ status: 1, stdout, stderr: error.message });
|
|
65
68
|
});
|
|
66
|
-
child.on(
|
|
69
|
+
child.on("close", (code) => {
|
|
67
70
|
done({ status: code ?? 1, stdout, stderr });
|
|
68
71
|
});
|
|
69
72
|
});
|
|
73
|
+
/** Longest question text put into a pull request body (GitHub caps bodies at 65,536). */
|
|
74
|
+
const PR_QUESTION_MAX_CHARS = 20_000;
|
|
75
|
+
/**
|
|
76
|
+
* ENG-337: the "Waiting for your reply" block at the top of a draft pull
|
|
77
|
+
* request. The request is untrusted agent output, so it goes in a code fence
|
|
78
|
+
* longer than any backtick run inside it: no markdown, links, HTML or
|
|
79
|
+
* @-mentions are rendered from it. Pure — exported for unit testing.
|
|
80
|
+
*/
|
|
81
|
+
export function waitingPrBodyBlock(request) {
|
|
82
|
+
let text = formatNeedsInputText(request);
|
|
83
|
+
if (text.length > PR_QUESTION_MAX_CHARS)
|
|
84
|
+
text = `${text.slice(0, PR_QUESTION_MAX_CHARS)}\n…(cut short)`;
|
|
85
|
+
const longestRun = Math.max(0, ...Array.from(text.matchAll(/`+/g), (m) => m[0].length));
|
|
86
|
+
const fence = "`".repeat(Math.max(3, longestRun + 1));
|
|
87
|
+
return [
|
|
88
|
+
"Waiting for your reply",
|
|
89
|
+
"",
|
|
90
|
+
"The build stopped to ask you something. Answer it in CompBox and the build continues from here.",
|
|
91
|
+
"",
|
|
92
|
+
`${fence}text`,
|
|
93
|
+
text,
|
|
94
|
+
fence,
|
|
95
|
+
].join("\n");
|
|
96
|
+
}
|
|
70
97
|
/** Local-only files a run needs that git doesn't carry into a new worktree. */
|
|
71
98
|
export function isLocalConfigFile(path) {
|
|
72
|
-
if (path.split(
|
|
99
|
+
if (path.split("/").includes("node_modules"))
|
|
73
100
|
return false;
|
|
74
101
|
const name = basename(path);
|
|
75
|
-
return (name ===
|
|
76
|
-
name === 'CLAUDE.local.md' ||
|
|
77
|
-
path === '.claude/settings.local.json');
|
|
102
|
+
return (name === ".mcp.json" || name === "CLAUDE.local.md" || path === ".claude/settings.local.json");
|
|
78
103
|
// Never .env files: they can hold production credentials. On 2026-10-21 a
|
|
79
104
|
// build's test run read the copied packages/api/.env and wiped the prod
|
|
80
105
|
// database.
|
|
81
106
|
}
|
|
82
107
|
/** `ENG-E12` → `ENG-E12`; anything unusual becomes dashes. */
|
|
83
108
|
export function slugForBranch(value) {
|
|
84
|
-
return value
|
|
109
|
+
return (value
|
|
110
|
+
.replace(/[^A-Za-z0-9._-]+/g, "-")
|
|
111
|
+
.replace(/^-+|-+$/g, "")
|
|
112
|
+
.slice(0, 40) || "run");
|
|
85
113
|
}
|
|
86
114
|
function stamp(now) {
|
|
87
|
-
const pad = (n) => String(n).padStart(2,
|
|
115
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
88
116
|
return `${String(now.getFullYear())}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
|
|
89
117
|
}
|
|
118
|
+
/** The real path of `path` (git prints worktrees by real path), or `path` itself. */
|
|
119
|
+
function realpathOr(path) {
|
|
120
|
+
try {
|
|
121
|
+
return realpathSync(path);
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
return path;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/** ENG-337: the note for a paused run whose folder is kept for the reply. */
|
|
128
|
+
function keptForReplyNote(ws) {
|
|
129
|
+
return `The run is waiting for your reply. Its folder is kept for the reply: ${ws.dir} (branch ${ws.branch}).`;
|
|
130
|
+
}
|
|
90
131
|
/** Git's well-known empty tree (SHA-1 repositories). */
|
|
91
|
-
const EMPTY_TREE =
|
|
132
|
+
const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
|
|
92
133
|
/**
|
|
93
134
|
* The line of git's stderr that says what went wrong. Git prints progress
|
|
94
135
|
* ("Preparing worktree (new branch …)", "HEAD is now at …") before the actual
|
|
95
136
|
* `fatal:`/`error:` line, so the first line alone hid the reason.
|
|
96
137
|
*/
|
|
97
138
|
export function gitReason(text) {
|
|
98
|
-
const lines = text
|
|
139
|
+
const lines = text
|
|
140
|
+
.split("\n")
|
|
141
|
+
.map((l) => l.trim())
|
|
142
|
+
.filter(Boolean);
|
|
99
143
|
const failure = lines.find((l) => /^(fatal|error):/i.test(l));
|
|
100
144
|
if (failure)
|
|
101
145
|
return failure;
|
|
102
146
|
const notProgress = lines.filter((l) => !/^(Preparing worktree|HEAD is now at|Updating files)/.test(l));
|
|
103
|
-
return notProgress.at(-1) ?? lines.at(-1) ??
|
|
147
|
+
return notProgress.at(-1) ?? lines.at(-1) ?? "";
|
|
104
148
|
}
|
|
105
|
-
/**
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
return null;
|
|
149
|
+
/**
|
|
150
|
+
* Picks the install command for the repo's lockfile, or null when there is
|
|
151
|
+
* none. `opts.storeDir` points the package manager at a shared per-project
|
|
152
|
+
* store (ENG-349); `opts.offline` installs only from it. Pure.
|
|
153
|
+
*/
|
|
154
|
+
export function installCommand(dir, exists = existsSync, opts = {}) {
|
|
155
|
+
const found = detectLockfile(dir, exists);
|
|
156
|
+
return found ? [found.pm, installArgs(found.pm, opts)] : null;
|
|
114
157
|
}
|
|
115
158
|
/**
|
|
116
159
|
* GitHub "compare" link for a remote URL, so the person can open the pull
|
|
@@ -122,7 +165,7 @@ export function githubCompareUrl(remoteUrl, baseBranch, branch) {
|
|
|
122
165
|
/^(?:ssh:\/\/)?git@github\.com[:/]([^/]+)\/(.+?)(?:\.git)?\/?$/.exec(remoteUrl.trim());
|
|
123
166
|
if (!m)
|
|
124
167
|
return null;
|
|
125
|
-
return `https://github.com/${m[1] ??
|
|
168
|
+
return `https://github.com/${m[1] ?? ""}/${m[2] ?? ""}/compare/${encodeURIComponent(baseBranch)}...${encodeURIComponent(branch)}?expand=1`;
|
|
126
169
|
}
|
|
127
170
|
/**
|
|
128
171
|
* Git commands that write to the same repository (fetch, worktree add/remove,
|
|
@@ -150,11 +193,18 @@ export class RunWorkspaceManager {
|
|
|
150
193
|
copyFile;
|
|
151
194
|
env;
|
|
152
195
|
openPullRequest;
|
|
196
|
+
storesRoot;
|
|
197
|
+
retentionMs;
|
|
198
|
+
activeRunDirs;
|
|
199
|
+
mtimeMs;
|
|
200
|
+
readFile;
|
|
201
|
+
isPidAlive;
|
|
202
|
+
pid;
|
|
153
203
|
constructor(deps = {}) {
|
|
154
204
|
this.openPullRequest = deps.openPullRequest;
|
|
155
205
|
this.run = deps.run ?? defaultCommandRunner;
|
|
156
206
|
this.now = deps.now ?? (() => new Date());
|
|
157
|
-
this.runsRoot = deps.runsRoot ?? join(getConfigDir(),
|
|
207
|
+
this.runsRoot = deps.runsRoot ?? join(getConfigDir(), "runs");
|
|
158
208
|
this.exists = deps.exists ?? existsSync;
|
|
159
209
|
this.copyFile =
|
|
160
210
|
deps.copyFile ??
|
|
@@ -163,9 +213,95 @@ export class RunWorkspaceManager {
|
|
|
163
213
|
copyFileSync(from, to);
|
|
164
214
|
});
|
|
165
215
|
this.env = deps.env ?? process.env;
|
|
216
|
+
this.storesRoot = deps.storesRoot ?? join(dirname(this.runsRoot), "stores");
|
|
217
|
+
this.retentionMs = deps.retentionMs;
|
|
218
|
+
this.activeRunDirs = deps.activeRunDirs;
|
|
219
|
+
this.mtimeMs =
|
|
220
|
+
deps.mtimeMs ??
|
|
221
|
+
((path) => {
|
|
222
|
+
try {
|
|
223
|
+
return statSync(path).mtimeMs;
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
this.isPidAlive = deps.isPidAlive ?? pidAlive;
|
|
230
|
+
this.pid = deps.pid ?? process.pid;
|
|
231
|
+
this.readFile =
|
|
232
|
+
deps.readFile ??
|
|
233
|
+
((path) => {
|
|
234
|
+
try {
|
|
235
|
+
return readFileSync(path);
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
238
|
+
return null;
|
|
239
|
+
}
|
|
240
|
+
});
|
|
166
241
|
}
|
|
167
242
|
git(args, cwd) {
|
|
168
|
-
return this.run(
|
|
243
|
+
return this.run("git", args, cwd);
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Marks a run folder as in use (`<dir>.active`: pid + startedAt) and touches
|
|
247
|
+
* the folder, so a prune from another process never removes it. Called
|
|
248
|
+
* inside the repo lock. Best-effort.
|
|
249
|
+
*/
|
|
250
|
+
markActive(dir) {
|
|
251
|
+
try {
|
|
252
|
+
writeFileSync(activeMarkerPath(dir), formatActiveMarker({ pid: this.pid, startedAt: this.now().toISOString() }));
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
// Prune also skips recently touched folders.
|
|
256
|
+
}
|
|
257
|
+
try {
|
|
258
|
+
const now = this.now();
|
|
259
|
+
utimesSync(dir, now, now);
|
|
260
|
+
}
|
|
261
|
+
catch {
|
|
262
|
+
// A folder we can't touch just keeps its old age.
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
clearActive(dir) {
|
|
266
|
+
rmSync(activeMarkerPath(dir), { force: true });
|
|
267
|
+
}
|
|
268
|
+
/** Whether a `.active` marker still protects this folder from pruning. */
|
|
269
|
+
activeByMarker(dir) {
|
|
270
|
+
const path = activeMarkerPath(dir);
|
|
271
|
+
let text = null;
|
|
272
|
+
try {
|
|
273
|
+
text = readFileSync(path, "utf-8");
|
|
274
|
+
}
|
|
275
|
+
catch {
|
|
276
|
+
text = null;
|
|
277
|
+
}
|
|
278
|
+
const exists = text !== null || this.exists(path);
|
|
279
|
+
const touched = Math.max(this.mtimeMs(path) ?? 0, this.mtimeMs(dir) ?? 0);
|
|
280
|
+
return activeMarkerProtects({
|
|
281
|
+
exists,
|
|
282
|
+
marker: parseActiveMarker(text),
|
|
283
|
+
markerMtimeMs: touched === 0 ? null : touched,
|
|
284
|
+
nowMs: this.now().getTime(),
|
|
285
|
+
isAlive: this.isPidAlive,
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
/** Removes `.active`/`.waiting` markers whose run folder is gone. Best-effort. */
|
|
289
|
+
clearOrphanMarkers() {
|
|
290
|
+
let entries;
|
|
291
|
+
try {
|
|
292
|
+
entries = readdirSync(this.runsRoot);
|
|
293
|
+
}
|
|
294
|
+
catch {
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
for (const name of orphanMarkers(entries)) {
|
|
298
|
+
try {
|
|
299
|
+
rmSync(join(this.runsRoot, name), { force: true });
|
|
300
|
+
}
|
|
301
|
+
catch {
|
|
302
|
+
// Harmless leftover.
|
|
303
|
+
}
|
|
304
|
+
}
|
|
169
305
|
}
|
|
170
306
|
/** Creates the branch + worktree for a run. Never touches the person's checkout. */
|
|
171
307
|
/**
|
|
@@ -174,31 +310,146 @@ export class RunWorkspaceManager {
|
|
|
174
310
|
* rather than fall back to a fresh branch when it can't be checked out.
|
|
175
311
|
*/
|
|
176
312
|
async prepare(projectDir, epicId, opts = {}) {
|
|
177
|
-
const
|
|
313
|
+
const active = [...(opts.activeRunDirs ?? []), ...((await this.activeRunDirs?.()) ?? [])];
|
|
314
|
+
const created = await withRepoLock(projectDir, async () => {
|
|
315
|
+
// ENG-349: clear out old, clean, pushed run folders first.
|
|
316
|
+
const pruned = await this.pruneStaleRuns(projectDir, active);
|
|
317
|
+
const result = await this.createWorktree(projectDir, epicId, opts);
|
|
318
|
+
if (result.ok)
|
|
319
|
+
this.markActive(result.workspace.dir);
|
|
320
|
+
if (result.ok && pruned > 0) {
|
|
321
|
+
result.notes.push(`Removed ${String(pruned)} old run folder${pruned === 1 ? "" : "s"} that ${pruned === 1 ? "was" : "were"} no longer used.`);
|
|
322
|
+
}
|
|
323
|
+
return result;
|
|
324
|
+
});
|
|
178
325
|
if (!created.ok)
|
|
179
326
|
return created;
|
|
180
327
|
const { workspace, notes } = created;
|
|
181
328
|
const { dir, branch } = workspace;
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
329
|
+
// ENG-346: the agent can't push to the default branch from this run copy.
|
|
330
|
+
await this.guardPushes(projectDir, dir, workspace.baseBranch);
|
|
331
|
+
const installed = await this.installDeps(projectDir, dir);
|
|
332
|
+
if (installed) {
|
|
333
|
+
const { command, args, res } = installed;
|
|
186
334
|
if (res.status !== 0) {
|
|
187
335
|
await withRepoLock(projectDir, async () => {
|
|
188
|
-
await this.git([
|
|
189
|
-
await this.git([
|
|
336
|
+
await this.git(["worktree", "remove", "--force", dir], projectDir);
|
|
337
|
+
await this.git(["branch", "-D", branch], projectDir);
|
|
338
|
+
this.clearActive(dir);
|
|
190
339
|
});
|
|
191
340
|
return {
|
|
192
341
|
ok: false,
|
|
193
342
|
error: [
|
|
194
|
-
`Installing the project's dependencies failed (${command} ${args.join(
|
|
195
|
-
|
|
196
|
-
].join(
|
|
343
|
+
`Installing the project's dependencies failed (${command} ${args.join(" ")}): ${gitReason(res.stderr) || gitReason(res.stdout) || "unknown error"}`,
|
|
344
|
+
"The run was not started. Check that the same command works in your project folder.",
|
|
345
|
+
].join("\n"),
|
|
197
346
|
};
|
|
198
347
|
}
|
|
348
|
+
workspace.install = { ms: installed.ms, cacheHit: installed.cacheHit };
|
|
199
349
|
}
|
|
200
350
|
return { ok: true, workspace, notes };
|
|
201
351
|
}
|
|
352
|
+
/**
|
|
353
|
+
* ENG-349: installs dependencies through a shared per-project store. When the
|
|
354
|
+
* store's marker matches this lockfile and package-manager version, installs
|
|
355
|
+
* offline from it (hard links for pnpm); if that fails, or there is no
|
|
356
|
+
* match, runs the full frozen install. The marker is read and written under
|
|
357
|
+
* the repo lock and only updated after a successful install.
|
|
358
|
+
*/
|
|
359
|
+
async installDeps(projectDir, dir) {
|
|
360
|
+
const found = detectLockfile(dir, this.exists);
|
|
361
|
+
if (!found)
|
|
362
|
+
return null;
|
|
363
|
+
const storeDir = storeDirFor(this.storesRoot, projectDir);
|
|
364
|
+
const lock = this.readFile(found.lockfile);
|
|
365
|
+
const lockHash = lock ? hashLockfile(lock) : "";
|
|
366
|
+
const version = await this.run(found.pm, ["--version"], dir);
|
|
367
|
+
const pmVersion = version.status === 0 ? version.stdout.trim() : "";
|
|
368
|
+
const marker = await withRepoLock(projectDir, () => Promise.resolve(readInstallMarker(storeDir)));
|
|
369
|
+
const started = Date.now();
|
|
370
|
+
let cacheHit = false;
|
|
371
|
+
let res = null;
|
|
372
|
+
let args = installArgs(found.pm, { storeDir, pmVersion });
|
|
373
|
+
const fastArgs = installArgs(found.pm, { storeDir, offline: true, pmVersion });
|
|
374
|
+
// No offline variant (e.g. Yarn Berry): there is no separate fast path.
|
|
375
|
+
const hasFastPath = fastArgs.join(" ") !== args.join(" ");
|
|
376
|
+
if (hasFastPath && lockHash && markerMatches(marker, lockHash, pmVersion)) {
|
|
377
|
+
const fast = await this.run(found.pm, fastArgs, dir);
|
|
378
|
+
if (fast.status === 0) {
|
|
379
|
+
cacheHit = true;
|
|
380
|
+
res = fast;
|
|
381
|
+
args = fastArgs;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
// No match, or the fast path failed: the full install (silently).
|
|
385
|
+
res ??= await this.run(found.pm, args, dir);
|
|
386
|
+
const ms = Date.now() - started;
|
|
387
|
+
if (res.status === 0 && lockHash && pmVersion) {
|
|
388
|
+
await withRepoLock(projectDir, () => {
|
|
389
|
+
try {
|
|
390
|
+
writeInstallMarker(storeDir, { lockHash, pmVersion, at: this.now().toISOString() });
|
|
391
|
+
}
|
|
392
|
+
catch {
|
|
393
|
+
// A marker that can't be written only costs the next run its fast path.
|
|
394
|
+
}
|
|
395
|
+
return Promise.resolve();
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
return { command: found.pm, args, res, ms, cacheHit };
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* ENG-349: removes run folders under the runs folder that nothing uses any
|
|
402
|
+
* more. Runs inside the repo lock. A folder is removed only when it is older
|
|
403
|
+
* than the retention window, not used by a running job, not kept for a
|
|
404
|
+
* waiting job's reply, clean, and has no unpushed commits — and only with
|
|
405
|
+
* `git worktree remove` (never a plain delete). Returns how many went.
|
|
406
|
+
*/
|
|
407
|
+
async pruneStaleRuns(projectDir, activeRunDirs) {
|
|
408
|
+
const list = await this.git(["worktree", "list", "--porcelain"], projectDir);
|
|
409
|
+
if (list.status !== 0)
|
|
410
|
+
return 0;
|
|
411
|
+
const roots = [this.runsRoot, realpathOr(this.runsRoot)];
|
|
412
|
+
const inRuns = (dir) => roots.some((root) => dir.startsWith(`${root}/`));
|
|
413
|
+
const active = new Set(activeRunDirs.flatMap((d) => [d.replace(/\/+$/, ""), realpathOr(d)]));
|
|
414
|
+
const candidates = parseWorktreeList(list.stdout)
|
|
415
|
+
.filter((dir) => inRuns(dir) && !dir.split("/").includes(".."))
|
|
416
|
+
.map((dir) => ({
|
|
417
|
+
dir,
|
|
418
|
+
mtimeMs: this.mtimeMs(dir),
|
|
419
|
+
waiting: this.exists(waitingMarkerPath(dir)),
|
|
420
|
+
active: active.has(dir) || active.has(realpathOr(dir)) || this.activeByMarker(dir),
|
|
421
|
+
}));
|
|
422
|
+
// Markers left behind by folders that are already gone.
|
|
423
|
+
this.clearOrphanMarkers();
|
|
424
|
+
if (candidates.length === 0)
|
|
425
|
+
return 0;
|
|
426
|
+
let retention = this.retentionMs;
|
|
427
|
+
if (retention === undefined) {
|
|
428
|
+
try {
|
|
429
|
+
retention = getRunRetentionMs();
|
|
430
|
+
}
|
|
431
|
+
catch {
|
|
432
|
+
retention = DEFAULT_RUN_RETENTION_DAYS * 86_400_000;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
let pruned = 0;
|
|
436
|
+
for (const dir of selectStaleRuns(candidates, this.now().getTime(), retention)) {
|
|
437
|
+
if (await this.isDirty(dir))
|
|
438
|
+
continue;
|
|
439
|
+
// Commits on this branch that no remote has yet.
|
|
440
|
+
const unpushed = await this.git(["rev-list", "--count", "HEAD", "--not", "--remotes"], dir);
|
|
441
|
+
if (unpushed.status !== 0 || unpushed.stdout.trim() !== "0")
|
|
442
|
+
continue;
|
|
443
|
+
// --force only skips git's own ignored-file check; the folder is verified clean.
|
|
444
|
+
const removed = await this.git(["worktree", "remove", "--force", dir], projectDir);
|
|
445
|
+
if (removed.status === 0) {
|
|
446
|
+
pruned += 1;
|
|
447
|
+
this.clearActive(dir);
|
|
448
|
+
rmSync(waitingMarkerPath(dir), { force: true });
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
return pruned;
|
|
452
|
+
}
|
|
202
453
|
/**
|
|
203
454
|
* When neither the folder nor its remote has any commit, records one empty
|
|
204
455
|
* commit on `main` (and pushes it) so runs can branch and open pull requests.
|
|
@@ -206,63 +457,62 @@ export class RunWorkspaceManager {
|
|
|
206
457
|
* the folder is swept in: the person's files stay exactly as they were.
|
|
207
458
|
*/
|
|
208
459
|
async startEmptyRepository(projectDir, remote) {
|
|
209
|
-
if ((await this.git([
|
|
460
|
+
if ((await this.git(["rev-parse", "--verify", "--quiet", "HEAD"], projectDir)).status === 0)
|
|
210
461
|
return { ok: true };
|
|
211
462
|
if (remote) {
|
|
212
|
-
const heads = await this.git([
|
|
463
|
+
const heads = await this.git(["ls-remote", "--heads", remote], projectDir);
|
|
213
464
|
// Unreachable remote, or it already has branches: leave it to the usual path.
|
|
214
|
-
if (heads.status !== 0 || heads.stdout.trim() !==
|
|
465
|
+
if (heads.status !== 0 || heads.stdout.trim() !== "")
|
|
215
466
|
return { ok: true };
|
|
216
467
|
}
|
|
217
468
|
const fail = (what, res) => ({
|
|
218
469
|
ok: false,
|
|
219
470
|
error: [
|
|
220
|
-
`This repository has no commits yet, and CompBox couldn't ${what}: ${gitReason(res.stderr) ||
|
|
221
|
-
|
|
222
|
-
].join(
|
|
471
|
+
`This repository has no commits yet, and CompBox couldn't ${what}: ${gitReason(res.stderr) || "unknown error"}`,
|
|
472
|
+
"The run was not started. Make a first commit on main in your project folder (or push one to GitHub), then try again.",
|
|
473
|
+
].join("\n"),
|
|
223
474
|
});
|
|
224
|
-
const commit = await this.git([
|
|
475
|
+
const commit = await this.git(["commit-tree", EMPTY_TREE, "-m", "Start the project"], projectDir);
|
|
225
476
|
if (commit.status !== 0)
|
|
226
|
-
return fail(
|
|
477
|
+
return fail("make its first commit", commit);
|
|
227
478
|
const sha = commit.stdout.trim();
|
|
228
|
-
const ref = await this.git([
|
|
479
|
+
const ref = await this.git(["update-ref", "refs/heads/main", sha, ""], projectDir);
|
|
229
480
|
if (ref.status !== 0)
|
|
230
|
-
return fail(
|
|
231
|
-
await this.git([
|
|
481
|
+
return fail("create the main branch", ref);
|
|
482
|
+
await this.git(["symbolic-ref", "HEAD", "refs/heads/main"], projectDir);
|
|
232
483
|
if (!remote)
|
|
233
484
|
return {
|
|
234
485
|
ok: true,
|
|
235
|
-
note:
|
|
486
|
+
note: "The repository had no commits, so CompBox started main with an empty first commit.",
|
|
236
487
|
};
|
|
237
|
-
const push = await this.git([
|
|
488
|
+
const push = await this.git(["push", remote, "main"], projectDir);
|
|
238
489
|
if (push.status !== 0)
|
|
239
490
|
return fail(`push its first commit to ${remote}`, push);
|
|
240
|
-
return {
|
|
491
|
+
return {
|
|
492
|
+
ok: true,
|
|
493
|
+
note: `The repository had no commits, so CompBox started main with an empty first commit and pushed it to ${remote}.`,
|
|
494
|
+
};
|
|
241
495
|
}
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
const remotes = (await this.git([
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
let
|
|
254
|
-
let baseRef = 'HEAD';
|
|
496
|
+
/** The repository's remote: `origin`, else the first one, else null. */
|
|
497
|
+
async resolveRemote(projectDir) {
|
|
498
|
+
const remotes = (await this.git(["remote"], projectDir)).stdout
|
|
499
|
+
.split("\n")
|
|
500
|
+
.map((r) => r.trim())
|
|
501
|
+
.filter(Boolean);
|
|
502
|
+
return remotes.includes("origin") ? "origin" : (remotes[0] ?? null);
|
|
503
|
+
}
|
|
504
|
+
/** The branch pull requests target and the ref new branches start from. */
|
|
505
|
+
async resolveBase(projectDir, remote) {
|
|
506
|
+
let baseBranch = "";
|
|
507
|
+
let baseRef = "HEAD";
|
|
255
508
|
if (remote) {
|
|
256
|
-
|
|
257
|
-
notes.push(`Couldn't fetch from ${remote}, so the run starts from the last fetched copy.`);
|
|
258
|
-
}
|
|
259
|
-
const head = await this.git(['symbolic-ref', '--quiet', '--short', `refs/remotes/${remote}/HEAD`], projectDir);
|
|
509
|
+
const head = await this.git(["symbolic-ref", "--quiet", "--short", `refs/remotes/${remote}/HEAD`], projectDir);
|
|
260
510
|
if (head.status === 0 && head.stdout.trim().startsWith(`${remote}/`)) {
|
|
261
511
|
baseBranch = head.stdout.trim().slice(remote.length + 1);
|
|
262
512
|
}
|
|
263
513
|
else {
|
|
264
|
-
for (const candidate of [
|
|
265
|
-
if ((await this.git([
|
|
514
|
+
for (const candidate of ["main", "master"]) {
|
|
515
|
+
if ((await this.git(["rev-parse", "--verify", "--quiet", `${remote}/${candidate}`], projectDir)).status === 0) {
|
|
266
516
|
baseBranch = candidate;
|
|
267
517
|
break;
|
|
268
518
|
}
|
|
@@ -272,9 +522,143 @@ export class RunWorkspaceManager {
|
|
|
272
522
|
baseRef = `${remote}/${baseBranch}`;
|
|
273
523
|
}
|
|
274
524
|
if (!baseBranch) {
|
|
275
|
-
baseBranch =
|
|
276
|
-
|
|
525
|
+
baseBranch =
|
|
526
|
+
(await this.git(["rev-parse", "--abbrev-ref", "HEAD"], projectDir)).stdout.trim() || "main";
|
|
527
|
+
baseRef = "HEAD";
|
|
528
|
+
}
|
|
529
|
+
return { baseBranch, baseRef };
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* ENG-339: reopens the run copy a paused run kept (by its stored path, not
|
|
533
|
+
* by looking for an unfinished pushed branch: a copy with no commits sits
|
|
534
|
+
* on a branch that was never pushed). Verifies the folder is a worktree of
|
|
535
|
+
* this repository, inside CompBox's run folders, on the expected branch.
|
|
536
|
+
* When the folder was removed, re-creates it at the SAME path (Claude keys
|
|
537
|
+
* sessions by folder) from the local branch, or the pushed one. Runs the
|
|
538
|
+
* git steps inside the repo lock. Fails (so the caller runs fresh) rather
|
|
539
|
+
* than guessing.
|
|
540
|
+
*/
|
|
541
|
+
async reopen(input) {
|
|
542
|
+
const reopened = await withRepoLock(input.projectDir, async () => {
|
|
543
|
+
const result = await this.reopenLocked(input);
|
|
544
|
+
if (result.ok) {
|
|
545
|
+
// In use again before the lock is released, so no prune can take it.
|
|
546
|
+
this.markActive(result.workspace.dir);
|
|
547
|
+
// ENG-349: the reply arrived; the folder is a normal run folder again.
|
|
548
|
+
rmSync(waitingMarkerPath(result.workspace.dir), { force: true });
|
|
549
|
+
}
|
|
550
|
+
return result;
|
|
551
|
+
});
|
|
552
|
+
// ENG-346: a re-created (or older) run copy gets the push guard too.
|
|
553
|
+
if (reopened.ok) {
|
|
554
|
+
await this.guardPushes(input.projectDir, reopened.workspace.dir, reopened.workspace.baseBranch);
|
|
555
|
+
}
|
|
556
|
+
return reopened;
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* ENG-346: installs the pre-push hook that refuses pushes to the default
|
|
560
|
+
* branch, in this run copy only (per-worktree core.hooksPath; see
|
|
561
|
+
* installPrePushGuard). Best-effort: a guard that can't be installed never
|
|
562
|
+
* stops a run (the agent's disallowed tools and gh shim still apply).
|
|
563
|
+
*/
|
|
564
|
+
async guardPushes(projectDir, dir, baseBranch) {
|
|
565
|
+
// The repo lock: extensions.worktreeConfig is written to the shared config.
|
|
566
|
+
await withRepoLock(projectDir, () => installPrePushGuard(dir, baseBranch || null, (args, cwd) => this.git(args, cwd)));
|
|
567
|
+
}
|
|
568
|
+
async reopenLocked(input) {
|
|
569
|
+
const { projectDir } = input;
|
|
570
|
+
const fail = (why) => ({
|
|
571
|
+
ok: false,
|
|
572
|
+
error: `Couldn't reopen the paused run's folder ${input.runDir}: ${why}`,
|
|
573
|
+
});
|
|
574
|
+
const runDir = input.runDir.replace(/\/+$/, "");
|
|
575
|
+
if (!runDir.startsWith("/") || runDir.split("/").includes("..")) {
|
|
576
|
+
return fail("it isn't an absolute path.");
|
|
577
|
+
}
|
|
578
|
+
// Never a folder outside the runs folder (e.g. the person's own checkout).
|
|
579
|
+
const roots = [this.runsRoot, realpathOr(this.runsRoot)];
|
|
580
|
+
const inRuns = (dir) => roots.some((root) => dir.startsWith(`${root}/`));
|
|
581
|
+
// Both the literal path AND its real path (symlinks resolved) must be inside.
|
|
582
|
+
if (!inRuns(runDir) || !inRuns(realpathOr(runDir))) {
|
|
583
|
+
return fail("it isn't inside CompBox's run folders.");
|
|
584
|
+
}
|
|
585
|
+
const remote = await this.resolveRemote(projectDir);
|
|
586
|
+
const { baseBranch, baseRef } = await this.resolveBase(projectDir, remote);
|
|
587
|
+
const notes = [];
|
|
588
|
+
const given = input.branch?.trim() ?? "";
|
|
589
|
+
let branch = given === "" ? null : given;
|
|
590
|
+
// The branch comes from the job's result: never let it reach git as an
|
|
591
|
+
// option or an invalid ref.
|
|
592
|
+
if (branch && !(await this.isValidBranchName(branch, projectDir))) {
|
|
593
|
+
return fail(`the run's branch name ${JSON.stringify(branch)} isn't a valid branch name.`);
|
|
594
|
+
}
|
|
595
|
+
if (this.exists(runDir)) {
|
|
596
|
+
// Must be the top of a worktree of THIS repository, not just any folder.
|
|
597
|
+
const top = await this.git(["rev-parse", "--show-toplevel"], runDir);
|
|
598
|
+
if (top.status !== 0 || realpathOr(top.stdout.trim()) !== realpathOr(runDir)) {
|
|
599
|
+
return fail("it isn't a git worktree.");
|
|
600
|
+
}
|
|
601
|
+
const mine = await this.git(["rev-parse", "--path-format=absolute", "--git-common-dir"], runDir);
|
|
602
|
+
const theirs = await this.git(["rev-parse", "--path-format=absolute", "--git-common-dir"], projectDir);
|
|
603
|
+
if (mine.status !== 0 ||
|
|
604
|
+
theirs.status !== 0 ||
|
|
605
|
+
realpathOr(mine.stdout.trim()) !== realpathOr(theirs.stdout.trim())) {
|
|
606
|
+
return fail("it belongs to a different repository.");
|
|
607
|
+
}
|
|
608
|
+
const current = (await this.git(["symbolic-ref", "--quiet", "--short", "HEAD"], runDir)).stdout.trim();
|
|
609
|
+
if (!current)
|
|
610
|
+
return fail("it isn't on a branch.");
|
|
611
|
+
if (branch && current !== branch) {
|
|
612
|
+
return fail(`it is on ${current}, not ${branch}.`);
|
|
613
|
+
}
|
|
614
|
+
branch = current;
|
|
615
|
+
notes.push(`Resuming in the kept run folder ${runDir} on ${branch}.`);
|
|
616
|
+
}
|
|
617
|
+
else {
|
|
618
|
+
if (!branch)
|
|
619
|
+
return fail("the folder is gone and the run's branch is unknown.");
|
|
620
|
+
// Drop git's record of the removed folder so the path can be reused.
|
|
621
|
+
await this.git(["worktree", "prune"], projectDir);
|
|
622
|
+
const local = await this.git(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`], projectDir);
|
|
623
|
+
const add = local.status === 0
|
|
624
|
+
? await this.git(["worktree", "add", runDir, branch], projectDir)
|
|
625
|
+
: remote &&
|
|
626
|
+
(await this.git(["rev-parse", "--verify", "--quiet", `${remote}/${branch}`], projectDir)).status === 0
|
|
627
|
+
? await this.git(["worktree", "add", "-B", branch, runDir, `${remote}/${branch}`], projectDir)
|
|
628
|
+
: null;
|
|
629
|
+
if (!add)
|
|
630
|
+
return fail(`the folder is gone and the branch ${branch} no longer exists.`);
|
|
631
|
+
if (add.status !== 0)
|
|
632
|
+
return fail(gitReason(add.stderr) || "git worktree add failed.");
|
|
633
|
+
notes.push(`The paused run's folder was gone, so it was re-created at ${runDir} on ${branch}.`);
|
|
277
634
|
}
|
|
635
|
+
return {
|
|
636
|
+
ok: true,
|
|
637
|
+
workspace: { dir: runDir, projectDir, branch, baseRef, baseBranch, remote, continued: true },
|
|
638
|
+
notes,
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
/** A plain branch name: no leading '-', safe characters, and accepted by `git check-ref-format --branch`. */
|
|
642
|
+
async isValidBranchName(branch, cwd) {
|
|
643
|
+
if (branch.startsWith("-") || !/^[A-Za-z0-9._/-]+$/.test(branch))
|
|
644
|
+
return false;
|
|
645
|
+
const check = await this.git(["check-ref-format", "--branch", branch], cwd);
|
|
646
|
+
return check.status === 0;
|
|
647
|
+
}
|
|
648
|
+
async createWorktree(projectDir, epicId, opts = {}) {
|
|
649
|
+
const notes = [];
|
|
650
|
+
const remote = await this.resolveRemote(projectDir);
|
|
651
|
+
// A brand-new repository has no commits, so there is nothing to branch from
|
|
652
|
+
// and no base for a pull request. Give it one empty starting commit on main.
|
|
653
|
+
const started = await this.startEmptyRepository(projectDir, remote);
|
|
654
|
+
if (!started.ok)
|
|
655
|
+
return started;
|
|
656
|
+
if (started.note)
|
|
657
|
+
notes.push(started.note);
|
|
658
|
+
if (remote && (await this.git(["fetch", remote, "--quiet"], projectDir)).status !== 0) {
|
|
659
|
+
notes.push(`Couldn't fetch from ${remote}, so the run starts from the last fetched copy.`);
|
|
660
|
+
}
|
|
661
|
+
const { baseBranch, baseRef } = await this.resolveBase(projectDir, remote);
|
|
278
662
|
const when = stamp(this.now());
|
|
279
663
|
const dir = join(this.runsRoot, `${slugForBranch(basename(projectDir))}-${slugForBranch(epicId)}-${when}`);
|
|
280
664
|
mkdirSync(this.runsRoot, { recursive: true });
|
|
@@ -289,46 +673,62 @@ export class RunWorkspaceManager {
|
|
|
289
673
|
ok: false,
|
|
290
674
|
error: [
|
|
291
675
|
`Couldn't open the pull request's branch ${target}: ${why}`,
|
|
292
|
-
|
|
293
|
-
].join(
|
|
676
|
+
"The fix was not started, and your project folder was not changed.",
|
|
677
|
+
].join("\n"),
|
|
294
678
|
});
|
|
295
679
|
if (!remote)
|
|
296
|
-
return missing(
|
|
297
|
-
|
|
680
|
+
return missing("this project folder has no remote to fetch it from.");
|
|
681
|
+
// ENG-337: a paused run may still hold this branch in its kept folder.
|
|
682
|
+
await this.releaseKeptWorktree(target, remote, projectDir, notes);
|
|
683
|
+
if ((await this.git(["rev-parse", "--verify", "--quiet", `${remote}/${target}`], projectDir))
|
|
684
|
+
.status !== 0) {
|
|
298
685
|
return missing(`it isn't on ${remote} (was the pull request closed or the branch deleted?).`);
|
|
299
686
|
}
|
|
300
|
-
const checkout = await this.git([
|
|
687
|
+
const checkout = await this.git(["worktree", "add", "-B", target, dir, `${remote}/${target}`], projectDir);
|
|
301
688
|
if (checkout.status !== 0)
|
|
302
|
-
return missing(gitReason(checkout.stderr) ||
|
|
689
|
+
return missing(gitReason(checkout.stderr) || "unknown error");
|
|
303
690
|
branch = target;
|
|
304
691
|
continued = true;
|
|
305
692
|
}
|
|
306
|
-
const previous = !opts.branch && remote
|
|
307
|
-
|
|
308
|
-
|
|
693
|
+
const previous = !opts.branch && remote
|
|
694
|
+
? await this.unfinishedBranch(remote, slugForBranch(epicId), baseRef, projectDir)
|
|
695
|
+
: null;
|
|
696
|
+
// ENG-337: a run that paused for a reply kept its folder, which holds the
|
|
697
|
+
// branch checked out; a clean one is removed first so the branch can be
|
|
698
|
+
// checked out again. A dirty one is never touched (the fallback below runs).
|
|
699
|
+
if (remote && previous && !(await this.releaseKeptWorktree(previous, remote, projectDir, notes))) {
|
|
700
|
+
notes.push(`The earlier run on ${previous} is kept as it is, so this run starts a new branch.`);
|
|
701
|
+
}
|
|
702
|
+
else if (remote && previous) {
|
|
703
|
+
const resume = await this.git(["worktree", "add", "-B", previous, dir, `${remote}/${previous}`], projectDir);
|
|
309
704
|
if (resume.status === 0) {
|
|
310
705
|
branch = previous;
|
|
311
706
|
continued = true;
|
|
312
707
|
notes.push(`Continuing the earlier unfinished work on ${previous}.`);
|
|
313
708
|
}
|
|
314
709
|
else {
|
|
315
|
-
notes.push(`Couldn't continue the earlier unfinished branch ${previous} (${gitReason(resume.stderr) ||
|
|
710
|
+
notes.push(`Couldn't continue the earlier unfinished branch ${previous} (${gitReason(resume.stderr) || "unknown error"}), so the run starts a new branch.`);
|
|
316
711
|
}
|
|
317
712
|
}
|
|
318
|
-
const add = continued
|
|
713
|
+
const add = continued
|
|
714
|
+
? null
|
|
715
|
+
: await this.git(["worktree", "add", "-b", branch, dir, baseRef], projectDir);
|
|
319
716
|
if (add && add.status !== 0) {
|
|
320
717
|
return {
|
|
321
718
|
ok: false,
|
|
322
719
|
error: [
|
|
323
|
-
`Couldn't create a separate workspace for this run (git worktree add failed): ${gitReason(add.stderr) ||
|
|
324
|
-
|
|
325
|
-
].join(
|
|
720
|
+
`Couldn't create a separate workspace for this run (git worktree add failed): ${gitReason(add.stderr) || "unknown error"}`,
|
|
721
|
+
"The run was not started, and your project folder was not changed.",
|
|
722
|
+
].join("\n"),
|
|
326
723
|
};
|
|
327
724
|
}
|
|
328
725
|
// Local-only config the agents need (.mcp.json for CompBox tools, .env files for tests).
|
|
329
|
-
const ignored = await this.git([
|
|
330
|
-
const untracked = await this.git([
|
|
331
|
-
const candidates = new Set(`${ignored.stdout}\n${untracked.stdout}
|
|
726
|
+
const ignored = await this.git(["ls-files", "--others", "--ignored", "--exclude-standard", "--directory"], projectDir);
|
|
727
|
+
const untracked = await this.git(["ls-files", "--others", "--exclude-standard"], projectDir);
|
|
728
|
+
const candidates = new Set(`${ignored.stdout}\n${untracked.stdout}`
|
|
729
|
+
.split("\n")
|
|
730
|
+
.map((p) => p.trim())
|
|
731
|
+
.filter((p) => p && !p.endsWith("/")));
|
|
332
732
|
for (const path of candidates) {
|
|
333
733
|
if (!isLocalConfigFile(path))
|
|
334
734
|
continue;
|
|
@@ -345,19 +745,76 @@ export class RunWorkspaceManager {
|
|
|
345
745
|
notes,
|
|
346
746
|
};
|
|
347
747
|
}
|
|
748
|
+
/**
|
|
749
|
+
* ENG-337: removes kept run folders (worktrees) that still have `branch`
|
|
750
|
+
* checked out, so a later run can check the branch out again. Runs inside
|
|
751
|
+
* the repo lock (from prepare). Only a folder that is clean, and whose branch
|
|
752
|
+
* has nothing unpushed, is removed; returns false (with a note) when a
|
|
753
|
+
* folder had to stay.
|
|
754
|
+
*/
|
|
755
|
+
async releaseKeptWorktree(branch, remote, projectDir, notes) {
|
|
756
|
+
const list = await this.git(["worktree", "list", "--porcelain"], projectDir);
|
|
757
|
+
if (list.status !== 0)
|
|
758
|
+
return true;
|
|
759
|
+
const holders = [];
|
|
760
|
+
let path = null;
|
|
761
|
+
for (const line of list.stdout.split("\n")) {
|
|
762
|
+
if (line.startsWith("worktree "))
|
|
763
|
+
path = line.slice("worktree ".length).trim();
|
|
764
|
+
else if (line.trim() === `branch refs/heads/${branch}` && path)
|
|
765
|
+
holders.push(path);
|
|
766
|
+
}
|
|
767
|
+
// Never a folder outside the runs folder (e.g. the person's own checkout).
|
|
768
|
+
const roots = [this.runsRoot, realpathOr(this.runsRoot)];
|
|
769
|
+
const kept = holders.filter((dir) => roots.some((root) => dir.startsWith(`${root}/`)));
|
|
770
|
+
if (kept.length < holders.length) {
|
|
771
|
+
notes.push(`The branch ${branch} is checked out outside CompBox's run folders, so it was left alone.`);
|
|
772
|
+
return false;
|
|
773
|
+
}
|
|
774
|
+
if (kept.length === 0)
|
|
775
|
+
return true;
|
|
776
|
+
const unpushed = await this.git(["rev-list", "--count", `${remote}/${branch}..refs/heads/${branch}`], projectDir);
|
|
777
|
+
if (unpushed.status !== 0 || unpushed.stdout.trim() !== "0") {
|
|
778
|
+
notes.push(`The earlier run folder ${kept.join(", ")} has commits on ${branch} that aren't pushed, so it was kept.`);
|
|
779
|
+
return false;
|
|
780
|
+
}
|
|
781
|
+
for (const dir of kept) {
|
|
782
|
+
if (await this.isDirty(dir)) {
|
|
783
|
+
notes.push(`The earlier run folder ${dir} still has uncommitted changes, so it was kept (branch ${branch}).`);
|
|
784
|
+
return false;
|
|
785
|
+
}
|
|
786
|
+
// --force only skips git's own ignored-file check; the folder is verified clean.
|
|
787
|
+
const removed = await this.git(["worktree", "remove", "--force", dir], projectDir);
|
|
788
|
+
if (removed.status !== 0) {
|
|
789
|
+
notes.push(`Couldn't remove the earlier run folder ${dir}: ${gitReason(removed.stderr) || "unknown error"}.`);
|
|
790
|
+
return false;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
return true;
|
|
794
|
+
}
|
|
348
795
|
/** The newest pushed run branch for this epic that isn't merged into the base yet, if any. */
|
|
349
796
|
async unfinishedBranch(remote, epicSlug, baseRef, projectDir) {
|
|
350
|
-
const refs = await this.git([
|
|
351
|
-
|
|
797
|
+
const refs = await this.git([
|
|
798
|
+
"for-each-ref",
|
|
799
|
+
"--sort=-refname",
|
|
800
|
+
"--format=%(refname:short)",
|
|
801
|
+
`refs/remotes/${remote}/compbox/epic-${epicSlug}-*`,
|
|
802
|
+
], projectDir);
|
|
803
|
+
const latest = refs.stdout
|
|
804
|
+
.split("\n")
|
|
805
|
+
.map((r) => r.trim())
|
|
806
|
+
.find(Boolean);
|
|
352
807
|
if (!latest?.startsWith(`${remote}/`))
|
|
353
808
|
return null;
|
|
354
|
-
if ((await this.git([
|
|
809
|
+
if ((await this.git(["merge-base", "--is-ancestor", latest, baseRef], projectDir)).status === 0)
|
|
355
810
|
return null;
|
|
356
811
|
return latest.slice(remote.length + 1);
|
|
357
812
|
}
|
|
358
813
|
/** A cancelled run's result: the branch and worktree are kept locally, untouched. */
|
|
359
814
|
async keepCancelled(ws, notes, commits) {
|
|
360
|
-
const count = commits ??
|
|
815
|
+
const count = commits ??
|
|
816
|
+
(Number.parseInt((await this.git(["rev-list", "--count", `${ws.baseRef}..HEAD`], ws.dir)).stdout.trim(), 10) ||
|
|
817
|
+
0);
|
|
361
818
|
notes.push(`The run was cancelled, so nothing was pushed. Its work is kept in ${ws.dir} on branch ${ws.branch}.`);
|
|
362
819
|
return {
|
|
363
820
|
branch: ws.branch,
|
|
@@ -369,8 +826,28 @@ export class RunWorkspaceManager {
|
|
|
369
826
|
};
|
|
370
827
|
}
|
|
371
828
|
/** Commits, pushes and opens the pull request; then cleans up the worktree. */
|
|
372
|
-
finish(input) {
|
|
373
|
-
return withRepoLock(input.workspace.projectDir, () =>
|
|
829
|
+
async finish(input) {
|
|
830
|
+
return withRepoLock(input.workspace.projectDir, async () => {
|
|
831
|
+
const result = await this.finishLocked(input);
|
|
832
|
+
// ENG-349: a folder kept for a waiting job's reply is never pruned. The
|
|
833
|
+
// marker is written before the lock is released, so no prune slips in.
|
|
834
|
+
if (input.waiting?.keepRunCopy && result.keptWorktree) {
|
|
835
|
+
try {
|
|
836
|
+
writeFileSync(waitingMarkerPath(result.keptWorktree), `${input.jobId}\n`);
|
|
837
|
+
}
|
|
838
|
+
catch {
|
|
839
|
+
// Best-effort; prune also skips recent folders.
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
// The run is over: the folder is no longer in use by this job.
|
|
843
|
+
try {
|
|
844
|
+
this.clearActive(input.workspace.dir);
|
|
845
|
+
}
|
|
846
|
+
catch {
|
|
847
|
+
// A leftover marker only protects the folder for the grace window.
|
|
848
|
+
}
|
|
849
|
+
return result;
|
|
850
|
+
});
|
|
374
851
|
}
|
|
375
852
|
async finishLocked(input) {
|
|
376
853
|
const { workspace: ws } = input;
|
|
@@ -384,17 +861,22 @@ export class RunWorkspaceManager {
|
|
|
384
861
|
const dirtyBefore = await this.isDirty(ws.dir);
|
|
385
862
|
let commitFailed = false;
|
|
386
863
|
if (dirtyBefore) {
|
|
387
|
-
await this.git([
|
|
864
|
+
await this.git(["add", "-A"], ws.dir);
|
|
388
865
|
// --no-verify: these are the run's own commits, not the person's; review
|
|
389
866
|
// happens on the pull request. A repo pre-commit hook (e.g. one running
|
|
390
867
|
// the full test suite) once failed this commit and the work was lost.
|
|
391
|
-
const commit = await this.git([
|
|
868
|
+
const commit = await this.git([
|
|
869
|
+
"commit",
|
|
870
|
+
"--no-verify",
|
|
871
|
+
"-m",
|
|
872
|
+
`chore(compbox): save work left uncommitted by the orchestrator (epic ${input.epicId})`,
|
|
873
|
+
], ws.dir);
|
|
392
874
|
if (commit.status !== 0) {
|
|
393
875
|
commitFailed = true;
|
|
394
|
-
notes.push(`Couldn't commit the remaining changes: ${gitReason(commit.stderr) || gitReason(commit.stdout) ||
|
|
876
|
+
notes.push(`Couldn't commit the remaining changes: ${gitReason(commit.stderr) || gitReason(commit.stdout) || "unknown error"}`);
|
|
395
877
|
}
|
|
396
878
|
}
|
|
397
|
-
const commits = Number.parseInt((await this.git([
|
|
879
|
+
const commits = Number.parseInt((await this.git(["rev-list", "--count", `${ws.baseRef}..HEAD`], ws.dir)).stdout.trim(), 10) || 0;
|
|
398
880
|
const base = { branch: ws.branch, commits, pushed: false, notes };
|
|
399
881
|
// Never remove a worktree that still holds uncommitted work: keep it, say
|
|
400
882
|
// where it is, and flag the run for attention.
|
|
@@ -402,22 +884,32 @@ export class RunWorkspaceManager {
|
|
|
402
884
|
notes.push(`The run's changes couldn't all be committed, so nothing was removed. They are safe in ${ws.dir} on branch ${ws.branch}.`);
|
|
403
885
|
return { ...base, keptWorktree: ws.dir, needsAttention: true };
|
|
404
886
|
}
|
|
887
|
+
const keepRunCopy = input.waiting?.keepRunCopy === true;
|
|
405
888
|
if (commits === 0) {
|
|
889
|
+
if (!dirtyBefore && keepRunCopy) {
|
|
890
|
+
// ENG-337: nothing to push yet, but the paused session lives here.
|
|
891
|
+
notes.push(keptForReplyNote(ws));
|
|
892
|
+
return { ...base, keptWorktree: ws.dir };
|
|
893
|
+
}
|
|
406
894
|
if (!dirtyBefore) {
|
|
407
895
|
if (await this.removeWorktree(ws, notes)) {
|
|
408
|
-
await this.git([
|
|
896
|
+
await this.git(["branch", "-D", ws.branch], ws.projectDir);
|
|
409
897
|
}
|
|
410
898
|
else {
|
|
411
899
|
return { ...base, keptWorktree: ws.dir, needsAttention: true };
|
|
412
900
|
}
|
|
413
|
-
notes.push(
|
|
901
|
+
notes.push("The run made no code changes, so there is nothing to review.");
|
|
414
902
|
return base;
|
|
415
903
|
}
|
|
416
904
|
// Changes existed but no commit landed — keep everything.
|
|
417
905
|
notes.push(`The run's changes didn't end up in a commit, so nothing was removed. Check ${ws.dir} on branch ${ws.branch}.`);
|
|
418
906
|
return { ...base, keptWorktree: ws.dir, needsAttention: true };
|
|
419
907
|
}
|
|
420
|
-
if (!ws.remote || this.env[RUN_PUSH_ENV] ===
|
|
908
|
+
if (!ws.remote || this.env[RUN_PUSH_ENV] === "0") {
|
|
909
|
+
if (keepRunCopy) {
|
|
910
|
+
notes.push(keptForReplyNote(ws));
|
|
911
|
+
return { ...base, keptWorktree: ws.dir };
|
|
912
|
+
}
|
|
421
913
|
if (!(await this.removeWorktree(ws, notes))) {
|
|
422
914
|
return { ...base, keptWorktree: ws.dir, needsAttention: true };
|
|
423
915
|
}
|
|
@@ -428,51 +920,172 @@ export class RunWorkspaceManager {
|
|
|
428
920
|
}
|
|
429
921
|
if (input.signal?.aborted)
|
|
430
922
|
return this.keepCancelled(ws, notes, commits);
|
|
431
|
-
|
|
923
|
+
// ENG-327: bring the latest base into a completed run's branch before it
|
|
924
|
+
// is pushed. A clean merge becomes an ordinary merge commit on top, so the
|
|
925
|
+
// push below stays a fast-forward (never forced).
|
|
926
|
+
let baseMerge;
|
|
927
|
+
if (input.mergeBase && !input.waiting) {
|
|
928
|
+
if (!input.completed) {
|
|
929
|
+
baseMerge = {
|
|
930
|
+
outcome: "skipped",
|
|
931
|
+
reason: "The run stopped early, so the base branch was not merged in.",
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
else {
|
|
935
|
+
baseMerge = await this.mergeBaseLocked(ws, input.mergeBase.resolveConflicts, input.signal);
|
|
936
|
+
if (input.signal?.aborted)
|
|
937
|
+
return this.keepCancelled(ws, notes, commits);
|
|
938
|
+
if (baseMerge.outcome === "merged") {
|
|
939
|
+
base.commits =
|
|
940
|
+
Number.parseInt((await this.git(["rev-list", "--count", `${ws.baseRef}..HEAD`], ws.dir)).stdout.trim(), 10) || commits;
|
|
941
|
+
}
|
|
942
|
+
else if (baseMerge.outcome === "conflict") {
|
|
943
|
+
notes.push(`Merging the latest ${ws.baseBranch} hit conflicts that need a decision: ${baseMerge.files.join(", ") || "unknown files"}. ${baseMerge.reason}`);
|
|
944
|
+
// The merge was aborted; anything left behind means it isn't safe to clean up.
|
|
945
|
+
if (await this.isDirty(ws.dir)) {
|
|
946
|
+
notes.push(`The merge couldn't be fully undone, so nothing was pushed. Check ${ws.dir} on branch ${ws.branch}.`);
|
|
947
|
+
return { ...base, keptWorktree: ws.dir, needsAttention: true, baseMerge };
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
else if (baseMerge.outcome === "skipped") {
|
|
951
|
+
notes.push(baseMerge.reason);
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
base.baseMerge = baseMerge;
|
|
955
|
+
}
|
|
956
|
+
// A branch that still conflicts with its base isn't ready to merge.
|
|
957
|
+
const ready = input.completed && baseMerge?.outcome !== "conflict";
|
|
958
|
+
// ENG-327: checks, completeness and migrations, recorded as a wrap-up attempt.
|
|
959
|
+
let verdict;
|
|
960
|
+
if (input.wrapUp && input.completed && !input.waiting) {
|
|
961
|
+
try {
|
|
962
|
+
verdict = await input.wrapUp({
|
|
963
|
+
dir: ws.dir,
|
|
964
|
+
branch: ws.branch,
|
|
965
|
+
baseBranch: ws.baseBranch,
|
|
966
|
+
baseRef: ws.baseRef,
|
|
967
|
+
...(baseMerge ? { baseMerge } : {}),
|
|
968
|
+
});
|
|
969
|
+
base.wrapUp = { status: verdict.status, ready: verdict.ready, reasons: verdict.reasons };
|
|
970
|
+
if (!verdict.ready) {
|
|
971
|
+
notes.push(`The wrap-up didn't pass, so the pull request stays a draft: ${verdict.reasons.join(" ")}`);
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
catch (error) {
|
|
975
|
+
const reason = `The wrap-up couldn't run: ${error instanceof Error ? error.message : String(error)}.`;
|
|
976
|
+
base.wrapUp = { status: "failed", ready: false, reasons: [reason] };
|
|
977
|
+
notes.push(`${reason} The pull request stays a draft.`);
|
|
978
|
+
}
|
|
979
|
+
// The checks may leave build output or formatting changes behind. The
|
|
980
|
+
// run's work is already committed, so put the worktree back to HEAD.
|
|
981
|
+
await this.discardCheckLeftovers(ws, notes);
|
|
982
|
+
if (input.signal?.aborted)
|
|
983
|
+
return this.keepCancelled(ws, notes, commits);
|
|
984
|
+
}
|
|
985
|
+
// With a wrap-up, the pull request opens as a draft; the review marks it ready.
|
|
986
|
+
const draft = !ready || input.wrapUp !== undefined || input.waiting !== undefined;
|
|
987
|
+
const push = await this.git(["push", "--set-upstream", ws.remote, ws.branch], ws.dir);
|
|
432
988
|
if (push.status !== 0) {
|
|
433
|
-
notes.push(`Couldn't push the branch to ${ws.remote}: ${gitReason(push.stderr) ||
|
|
989
|
+
notes.push(`Couldn't push the branch to ${ws.remote}: ${gitReason(push.stderr) || "unknown error"}. The work is safe in ${ws.dir} on branch ${ws.branch}.`);
|
|
434
990
|
return { ...base, keptWorktree: ws.dir };
|
|
435
991
|
}
|
|
436
|
-
const title = `CompBox: epic ${input.epicId}${input.
|
|
992
|
+
const title = `CompBox: epic ${input.epicId}${input.waiting
|
|
993
|
+
? " (waiting for your reply)"
|
|
994
|
+
: input.completed
|
|
995
|
+
? ""
|
|
996
|
+
: " (stopped early, needs review)"}`;
|
|
437
997
|
const body = [
|
|
998
|
+
...(input.waiting ? [waitingPrBodyBlock(input.waiting.request), "", "---", ""] : []),
|
|
438
999
|
`Code written by the CompBox orchestrator for epic **${input.epicId}** (job \`${input.jobId}\`).`,
|
|
439
|
-
|
|
440
|
-
input.
|
|
441
|
-
?
|
|
442
|
-
:
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
1000
|
+
"",
|
|
1001
|
+
input.waiting
|
|
1002
|
+
? "The orchestrator paused to ask the question above. This is a draft until the build finishes."
|
|
1003
|
+
: !input.completed
|
|
1004
|
+
? `The orchestrator stopped before finishing${input.stopReason ? `: ${input.stopReason}` : "."} This is a draft so the partial work can be reviewed.`
|
|
1005
|
+
: baseMerge?.outcome === "conflict"
|
|
1006
|
+
? `The orchestrator finished every phase, but merging the latest \`${ws.baseBranch}\` hit conflicts that need a decision (${baseMerge.files.map((f) => `\`${f}\``).join(", ")}). This is a draft until they are resolved.`
|
|
1007
|
+
: input.wrapUp
|
|
1008
|
+
? "The orchestrator finished every phase. The CompBox wrap-up review below says whether it's ready to merge."
|
|
1009
|
+
: "The orchestrator finished every phase. Review the changes, check that CI passes, then merge.",
|
|
1010
|
+
"",
|
|
1011
|
+
`${String(base.commits)} commit${base.commits === 1 ? "" : "s"} on \`${ws.branch}\`, based on \`${ws.baseBranch}\`.`,
|
|
1012
|
+
].join("\n");
|
|
446
1013
|
// CompBox's GitHub app first (no local GitHub CLI needed), then `gh`.
|
|
447
1014
|
let prUrl;
|
|
1015
|
+
let prNumber;
|
|
448
1016
|
if (this.openPullRequest) {
|
|
449
1017
|
try {
|
|
450
|
-
|
|
1018
|
+
const opened = await this.openPullRequest({
|
|
1019
|
+
branch: ws.branch,
|
|
1020
|
+
base: ws.baseBranch,
|
|
1021
|
+
title,
|
|
1022
|
+
body,
|
|
1023
|
+
draft,
|
|
1024
|
+
});
|
|
1025
|
+
prUrl = opened.url;
|
|
1026
|
+
prNumber = opened.number;
|
|
451
1027
|
}
|
|
452
1028
|
catch {
|
|
453
1029
|
prUrl = undefined;
|
|
454
1030
|
}
|
|
455
1031
|
}
|
|
456
|
-
let pr = { status: 0, stdout:
|
|
1032
|
+
let pr = { status: 0, stdout: "", stderr: "" };
|
|
457
1033
|
if (!prUrl) {
|
|
458
|
-
const prArgs = [
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
1034
|
+
const prArgs = [
|
|
1035
|
+
"pr",
|
|
1036
|
+
"create",
|
|
1037
|
+
"--base",
|
|
1038
|
+
ws.baseBranch,
|
|
1039
|
+
"--head",
|
|
1040
|
+
ws.branch,
|
|
1041
|
+
"--title",
|
|
1042
|
+
title,
|
|
1043
|
+
"--body",
|
|
1044
|
+
body,
|
|
1045
|
+
];
|
|
1046
|
+
if (draft)
|
|
1047
|
+
prArgs.push("--draft");
|
|
1048
|
+
pr = await this.run("gh", prArgs, ws.dir);
|
|
462
1049
|
prUrl = pr.status === 0 ? /https:\/\/\S+/.exec(pr.stdout)?.[0] : undefined;
|
|
463
1050
|
if (!prUrl && ws.continued) {
|
|
464
1051
|
// The continued branch usually has its pull request already.
|
|
465
|
-
const existing = await this.run(
|
|
1052
|
+
const existing = await this.run("gh", ["pr", "view", ws.branch, "--json", "url", "--jq", ".url"], ws.dir);
|
|
466
1053
|
if (existing.status === 0)
|
|
467
1054
|
prUrl = /https:\/\/\S+/.exec(existing.stdout)?.[0];
|
|
468
1055
|
}
|
|
469
1056
|
}
|
|
470
1057
|
let compareUrl;
|
|
471
1058
|
if (!prUrl) {
|
|
472
|
-
const remoteUrl = (await this.git([
|
|
1059
|
+
const remoteUrl = (await this.git(["remote", "get-url", ws.remote], ws.dir)).stdout.trim();
|
|
473
1060
|
compareUrl = githubCompareUrl(remoteUrl, ws.baseBranch, ws.branch) ?? undefined;
|
|
474
|
-
notes.push(`The branch was pushed, but the pull request couldn't be opened automatically${gitReason(pr.stderr) ? ` (${gitReason(pr.stderr)})` :
|
|
475
|
-
(compareUrl
|
|
1061
|
+
notes.push(`The branch was pushed, but the pull request couldn't be opened automatically${gitReason(pr.stderr) ? ` (${gitReason(pr.stderr)})` : ""}.` +
|
|
1062
|
+
(compareUrl
|
|
1063
|
+
? " Use the link to open it."
|
|
1064
|
+
: ` Open a pull request for ${ws.branch} on your git host.`));
|
|
1065
|
+
}
|
|
1066
|
+
if (verdict && prUrl) {
|
|
1067
|
+
const problems = await verdict.publish({
|
|
1068
|
+
url: prUrl,
|
|
1069
|
+
...(prNumber !== undefined ? { number: prNumber } : {}),
|
|
1070
|
+
});
|
|
1071
|
+
notes.push(...problems);
|
|
1072
|
+
if (problems.length > 0 && base.wrapUp) {
|
|
1073
|
+
base.wrapUp = { status: "failed", ready: false, reasons: [...base.wrapUp.reasons, ...problems] };
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
else if (verdict) {
|
|
1077
|
+
notes.push("The wrap-up review couldn't be posted because there is no pull request yet.");
|
|
1078
|
+
}
|
|
1079
|
+
// ENG-337: a paused run keeps its folder so the reply can resume there.
|
|
1080
|
+
if (keepRunCopy) {
|
|
1081
|
+
notes.push(keptForReplyNote(ws));
|
|
1082
|
+
return {
|
|
1083
|
+
...base,
|
|
1084
|
+
pushed: true,
|
|
1085
|
+
...(prUrl ? { prUrl } : {}),
|
|
1086
|
+
...(compareUrl ? { compareUrl } : {}),
|
|
1087
|
+
keptWorktree: ws.dir,
|
|
1088
|
+
};
|
|
476
1089
|
}
|
|
477
1090
|
// The branch is pushed, so the worktree can go (removeWorktree still
|
|
478
1091
|
// re-checks it is clean first).
|
|
@@ -485,9 +1098,156 @@ export class RunWorkspaceManager {
|
|
|
485
1098
|
...(removed ? {} : { keptWorktree: ws.dir, needsAttention: true }),
|
|
486
1099
|
};
|
|
487
1100
|
}
|
|
1101
|
+
/**
|
|
1102
|
+
* Puts a run's worktree back to its last commit after the wrap-up checks
|
|
1103
|
+
* (ENG-327). Only check output can be there: the run's work was committed
|
|
1104
|
+
* before the checks ran. Ignored files (node_modules, build caches) stay.
|
|
1105
|
+
*/
|
|
1106
|
+
async discardCheckLeftovers(ws, notes) {
|
|
1107
|
+
if (!(await this.isDirty(ws.dir)))
|
|
1108
|
+
return;
|
|
1109
|
+
await this.git(["checkout", "--", "."], ws.dir);
|
|
1110
|
+
await this.git(["clean", "-fd"], ws.dir);
|
|
1111
|
+
notes.push("The project checks changed some files; those changes were discarded.");
|
|
1112
|
+
}
|
|
1113
|
+
/**
|
|
1114
|
+
* Merges the latest base branch into the run's branch (ENG-327). Runs under
|
|
1115
|
+
* the repo lock (from finish). Never rewrites history: a clean merge is a
|
|
1116
|
+
* normal merge commit; conflicts go to one time-boxed agent turn limited to
|
|
1117
|
+
* the conflicted files, and anything it doesn't settle — conflicts left,
|
|
1118
|
+
* markers left, other files touched, or the commit failing — aborts the merge.
|
|
1119
|
+
*/
|
|
1120
|
+
async mergeBaseLocked(ws, resolveConflicts, signal) {
|
|
1121
|
+
if (!ws.remote)
|
|
1122
|
+
return {
|
|
1123
|
+
outcome: "skipped",
|
|
1124
|
+
reason: "The repository has no remote, so the base branch was not merged in.",
|
|
1125
|
+
};
|
|
1126
|
+
const fetch = await this.git(["fetch", ws.remote, ws.baseBranch], ws.dir);
|
|
1127
|
+
if (fetch.status !== 0) {
|
|
1128
|
+
return {
|
|
1129
|
+
outcome: "skipped",
|
|
1130
|
+
reason: `Couldn't fetch the latest ${ws.baseBranch} to merge it in: ${gitReason(fetch.stderr) || "unknown error"}.`,
|
|
1131
|
+
};
|
|
1132
|
+
}
|
|
1133
|
+
// The run's work is all committed by now; a merge only ever starts from a
|
|
1134
|
+
// clean worktree, so undoing it below can't lose anything.
|
|
1135
|
+
if (await this.isDirty(ws.dir)) {
|
|
1136
|
+
return {
|
|
1137
|
+
outcome: "skipped",
|
|
1138
|
+
reason: "The run folder has uncommitted changes, so the base branch was not merged in.",
|
|
1139
|
+
};
|
|
1140
|
+
}
|
|
1141
|
+
const baseRef = `${ws.remote}/${ws.baseBranch}`;
|
|
1142
|
+
const behind = await this.git(["rev-list", "--count", `HEAD..${baseRef}`], ws.dir);
|
|
1143
|
+
if (behind.status === 0 && behind.stdout.trim() === "0")
|
|
1144
|
+
return { outcome: "up_to_date" };
|
|
1145
|
+
const message = `Merge ${baseRef} into ${ws.branch} (CompBox wrap-up)`;
|
|
1146
|
+
const merge = await this.git(["merge", "--no-ff", "--no-edit", "-m", message, baseRef], ws.dir);
|
|
1147
|
+
if (merge.status === 0)
|
|
1148
|
+
return { outcome: "merged", resolvedFiles: [] };
|
|
1149
|
+
const files = await this.conflictedFiles(ws.dir);
|
|
1150
|
+
if (files.length === 0) {
|
|
1151
|
+
// Not a content conflict (e.g. untracked files in the way): undo and report.
|
|
1152
|
+
await this.git(["merge", "--abort"], ws.dir);
|
|
1153
|
+
return {
|
|
1154
|
+
outcome: "conflict",
|
|
1155
|
+
files: [],
|
|
1156
|
+
reason: `The merge failed: ${gitReason(merge.stderr) || gitReason(merge.stdout) || "unknown error"}.`,
|
|
1157
|
+
};
|
|
1158
|
+
}
|
|
1159
|
+
const abort = async (reason) => {
|
|
1160
|
+
await this.git(["merge", "--abort"], ws.dir);
|
|
1161
|
+
// The worktree was clean when the merge started, so anything left now is
|
|
1162
|
+
// the conflict turn's own stray edits: drop them (never ignored files).
|
|
1163
|
+
await this.git(["reset", "--hard", "HEAD"], ws.dir);
|
|
1164
|
+
await this.git(["clean", "-fd"], ws.dir);
|
|
1165
|
+
return { outcome: "conflict", files, reason };
|
|
1166
|
+
};
|
|
1167
|
+
if (!resolveConflicts)
|
|
1168
|
+
return abort("No agent was available to resolve them, so the merge was undone.");
|
|
1169
|
+
if (signal?.aborted)
|
|
1170
|
+
return abort("The run was cancelled, so the merge was undone.");
|
|
1171
|
+
// Everything outside the conflicted files, as merged by git: the agent may
|
|
1172
|
+
// not change any of it.
|
|
1173
|
+
const before = await this.untouchableState(ws.dir, files);
|
|
1174
|
+
let resolved;
|
|
1175
|
+
try {
|
|
1176
|
+
resolved = await resolveConflicts({
|
|
1177
|
+
dir: ws.dir,
|
|
1178
|
+
files,
|
|
1179
|
+
baseBranch: ws.baseBranch,
|
|
1180
|
+
...(signal ? { signal } : {}),
|
|
1181
|
+
});
|
|
1182
|
+
}
|
|
1183
|
+
catch (error) {
|
|
1184
|
+
resolved = { ok: false, reason: error instanceof Error ? error.message : String(error) };
|
|
1185
|
+
}
|
|
1186
|
+
if (signal?.aborted)
|
|
1187
|
+
return abort("The run was cancelled, so the merge was undone.");
|
|
1188
|
+
if (!resolved.ok) {
|
|
1189
|
+
return abort(`The agent couldn't resolve them${resolved.reason ? ` (${resolved.reason})` : ""}, so the merge was undone.`);
|
|
1190
|
+
}
|
|
1191
|
+
if ((await this.untouchableState(ws.dir, files)) !== before) {
|
|
1192
|
+
return abort("The agent changed files outside the conflicts, so the merge was undone.");
|
|
1193
|
+
}
|
|
1194
|
+
const add = await this.git(["add", "--", ...files], ws.dir);
|
|
1195
|
+
if (add.status !== 0)
|
|
1196
|
+
return abort(`Couldn't stage the resolved files: ${gitReason(add.stderr) || "unknown error"}.`);
|
|
1197
|
+
if ((await this.conflictedFiles(ws.dir)).length > 0) {
|
|
1198
|
+
return abort("Some conflicts were left unresolved, so the merge was undone.");
|
|
1199
|
+
}
|
|
1200
|
+
// `git grep` exits 0 when it finds a match: leftover conflict markers.
|
|
1201
|
+
const markers = await this.git(["grep", "--cached", "-l", "-E", "^(<<<<<<<|>>>>>>>)( |$)", "--", ...files], ws.dir);
|
|
1202
|
+
if (markers.status === 0) {
|
|
1203
|
+
return abort(`Conflict markers were left in ${markers.stdout.trim().split("\n").join(", ")}, so the merge was undone.`);
|
|
1204
|
+
}
|
|
1205
|
+
const commit = await this.git(["commit", "--no-verify", "--no-edit", "-m", message], ws.dir);
|
|
1206
|
+
if (commit.status !== 0) {
|
|
1207
|
+
return abort(`Couldn't commit the merge: ${gitReason(commit.stderr) || gitReason(commit.stdout) || "unknown error"}.`);
|
|
1208
|
+
}
|
|
1209
|
+
return { outcome: "merged", resolvedFiles: files };
|
|
1210
|
+
}
|
|
1211
|
+
/** Paths git still marks as conflicted (unmerged). */
|
|
1212
|
+
async conflictedFiles(dir) {
|
|
1213
|
+
const result = await this.git(["diff", "--name-only", "--diff-filter=U", "-z"], dir);
|
|
1214
|
+
return [...new Set(result.stdout.split("\0").filter((f) => f.length > 0))];
|
|
1215
|
+
}
|
|
1216
|
+
/**
|
|
1217
|
+
* A fingerprint of everything outside `files`: the index entries, unstaged
|
|
1218
|
+
* changes and untracked files. Any change means the conflict turn strayed.
|
|
1219
|
+
*/
|
|
1220
|
+
async untouchableState(dir, files) {
|
|
1221
|
+
const allowed = new Set(files);
|
|
1222
|
+
const keep = (out) => out
|
|
1223
|
+
.split("\0")
|
|
1224
|
+
.filter((entry) => entry.length > 0)
|
|
1225
|
+
.filter((entry) => !allowed.has(entry.includes("\t") ? entry.slice(entry.indexOf("\t") + 1) : entry))
|
|
1226
|
+
.join("\n");
|
|
1227
|
+
const index = await this.git(["ls-files", "--stage", "-z"], dir);
|
|
1228
|
+
const unstaged = await this.git(["diff", "--name-only", "-z"], dir);
|
|
1229
|
+
const untracked = await this.git(["ls-files", "--others", "--exclude-standard", "-z"], dir);
|
|
1230
|
+
// Unstaged changes are fingerprinted by content too, so a second edit to an
|
|
1231
|
+
// already-dirty file still counts.
|
|
1232
|
+
const unstagedFiles = keep(unstaged.stdout)
|
|
1233
|
+
.split("\n")
|
|
1234
|
+
.filter((f) => f.length > 0);
|
|
1235
|
+
const hashes = unstagedFiles.length > 0
|
|
1236
|
+
? (await this.git(["hash-object", "--", ...unstagedFiles], dir)).stdout
|
|
1237
|
+
: "";
|
|
1238
|
+
return [
|
|
1239
|
+
String(index.status),
|
|
1240
|
+
keep(index.stdout),
|
|
1241
|
+
String(unstaged.status),
|
|
1242
|
+
unstagedFiles.join("\n"),
|
|
1243
|
+
hashes,
|
|
1244
|
+
String(untracked.status),
|
|
1245
|
+
keep(untracked.stdout),
|
|
1246
|
+
].join("\u0001");
|
|
1247
|
+
}
|
|
488
1248
|
/** True when the worktree has uncommitted (or unreadable) state. */
|
|
489
1249
|
async isDirty(dir) {
|
|
490
|
-
const status = await this.git([
|
|
1250
|
+
const status = await this.git(["status", "--porcelain"], dir);
|
|
491
1251
|
// A failed `git status` counts as dirty: never assume a worktree is clean.
|
|
492
1252
|
return status.status !== 0 || status.stdout.trim().length > 0;
|
|
493
1253
|
}
|
|
@@ -503,7 +1263,7 @@ export class RunWorkspaceManager {
|
|
|
503
1263
|
}
|
|
504
1264
|
// --force only skips git's own check for ignored/submodule state; this
|
|
505
1265
|
// method already verified there is nothing uncommitted.
|
|
506
|
-
await this.git([
|
|
1266
|
+
await this.git(["worktree", "remove", "--force", ws.dir], ws.projectDir);
|
|
507
1267
|
return true;
|
|
508
1268
|
}
|
|
509
1269
|
}
|