agent-lyceum 0.54.0 → 0.55.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/README.zh-TW.md +2 -0
- package/dist/adapters/cursor.js +5 -1
- package/dist/attribution.d.ts +2 -0
- package/dist/cli.js +33 -7
- package/dist/config.d.ts +3 -0
- package/dist/config.js +5 -1
- package/dist/dispatcher.js +7 -2
- package/dist/doctor.js +12 -3
- package/dist/format.d.ts +4 -1
- package/dist/format.js +40 -2
- package/dist/mailbox.d.ts +29 -1
- package/dist/mailbox.js +56 -15
- package/dist/message-store.d.ts +10 -0
- package/dist/message-store.js +26 -0
- package/dist/open-pr.d.ts +13 -1
- package/dist/open-pr.js +12 -4
- package/dist/playbook.d.ts +28 -0
- package/dist/playbook.js +40 -0
- package/dist/policy.d.ts +12 -0
- package/dist/policy.js +55 -0
- package/dist/project-lock.d.ts +16 -0
- package/dist/project-lock.js +34 -2
- package/dist/prompt.d.ts +2 -0
- package/dist/prompt.js +25 -7
- package/dist/records.d.ts +10 -0
- package/dist/records.js +46 -0
- package/dist/review-gate.d.ts +33 -0
- package/dist/review-gate.js +78 -0
- package/dist/run-cleanup.d.ts +9 -2
- package/dist/run-cleanup.js +67 -4
- package/dist/run-outcome.d.ts +4 -0
- package/dist/run-outcome.js +8 -1
- package/dist/run-session.d.ts +27 -0
- package/dist/run-session.js +347 -39
- package/dist/run-store.d.ts +17 -3
- package/dist/run-store.js +10 -2
- package/dist/scaffold.d.ts +1 -1
- package/dist/scaffold.js +5 -2
- package/dist/schema.d.ts +12 -0
- package/dist/schema.js +6 -0
- package/dist/status.d.ts +1 -1
- package/dist/task-bind.d.ts +4 -0
- package/dist/task-bind.js +42 -0
- package/dist/wake-cap.d.ts +5 -0
- package/dist/wake-cap.js +11 -0
- package/dist/worktree.d.ts +153 -6
- package/dist/worktree.js +378 -15
- package/package.json +1 -1
- package/web/dist/public/assets/index-CVkc3V2B.js +92 -0
- package/web/dist/public/assets/index-zT-RkrlC.css +2 -0
- package/web/dist/public/index.html +2 -2
- package/web/dist/public/assets/index-BPY1-W3F.css +0 -2
- package/web/dist/public/assets/index-DzxHf7RE.js +0 -92
package/dist/worktree.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { execFileSync, spawn } from "node:child_process";
|
|
1
|
+
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
|
2
2
|
import crypto from "node:crypto";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import os from "node:os";
|
|
@@ -40,7 +40,7 @@ function tryGit(cwd, args, env) {
|
|
|
40
40
|
* otherwise visit with git reading that repository's own config (its fsmonitor and filters); `submodule.recurse` / `diff.submodule`
|
|
41
41
|
* would do the same for reset and diff; signing runs gpg.program.
|
|
42
42
|
*/
|
|
43
|
-
const PINNED_CONFIG = [
|
|
43
|
+
export const PINNED_CONFIG = [
|
|
44
44
|
"-c", "core.fsmonitor=false",
|
|
45
45
|
"-c", "core.hooksPath=/dev/null",
|
|
46
46
|
"-c", "diff.ignoreSubmodules=dirty",
|
|
@@ -172,6 +172,72 @@ const zList = (out) => out.split("\0").filter(Boolean);
|
|
|
172
172
|
const gitlinks = (out) => zList(out)
|
|
173
173
|
.filter((e) => e.startsWith("160000 "))
|
|
174
174
|
.map((e) => e.slice(e.indexOf("\t") + 1));
|
|
175
|
+
/** True when the worktree has any uncommitted or untracked path. Uses pinned git, never `dirtyPaths`. */
|
|
176
|
+
export function workspaceDirty(ws) {
|
|
177
|
+
assertNoNestedRepos(ws);
|
|
178
|
+
return agentGit(ws, ["status", "--porcelain", "-z", "--untracked-files=all"]) !== "";
|
|
179
|
+
}
|
|
180
|
+
/** Put the worktree back at `head` (the sha recorded on the claim) and drop untracked files. Never call this on `project.dir`. */
|
|
181
|
+
export function discardWorkspaceEdits(ws, head) {
|
|
182
|
+
assertNoNestedRepos(ws);
|
|
183
|
+
agentGit(ws, ["reset", "--hard", head]);
|
|
184
|
+
agentGit(ws, ["clean", "-fd"]);
|
|
185
|
+
}
|
|
186
|
+
/** HEAD and dirty paths of the user's checkout, before a read-only wake that has no worktree. Undefined when `dir` is not a git repo. */
|
|
187
|
+
export function snapshotCheckout(dir) {
|
|
188
|
+
if (!isGitRepo(dir))
|
|
189
|
+
return undefined;
|
|
190
|
+
const head = tryGit(dir, ["rev-parse", "HEAD"]);
|
|
191
|
+
if (!head)
|
|
192
|
+
return undefined;
|
|
193
|
+
return { head, dirty: dirtyPaths(dir) };
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* What changed in a checkout that has no worktree of its own since `snap`. Does not change the checkout:
|
|
197
|
+
* a borrowed folder is shared with the user, so a new path or a moved HEAD is only reported.
|
|
198
|
+
* A path that was already dirty is not listed again.
|
|
199
|
+
*/
|
|
200
|
+
export function borrowedEdits(dir, snap) {
|
|
201
|
+
if (!isGitRepo(dir))
|
|
202
|
+
return { headMoved: false, paths: [] };
|
|
203
|
+
const before = new Set(snap.dirty);
|
|
204
|
+
const headNow = tryGit(dir, ["rev-parse", "HEAD"]);
|
|
205
|
+
return { headMoved: Boolean(headNow && headNow !== snap.head), paths: dirtyPaths(dir).filter((p) => !before.has(p)) };
|
|
206
|
+
}
|
|
207
|
+
/** Dirty paths in an agent worktree, using pinned git. */
|
|
208
|
+
export function workspaceStatusPaths(ws) {
|
|
209
|
+
assertNoNestedRepos(ws);
|
|
210
|
+
return parseStatus(agentGit(ws, ["status", "--porcelain", "-z", "--untracked-files=all"]));
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Undo a read-only wake in an agent worktree. Earlier dirty paths stay, and the tree is not `reset --hard`
|
|
214
|
+
* or cleaned wholesale. Returns the paths that were put back. Never call this on `project.dir`.
|
|
215
|
+
*/
|
|
216
|
+
export function restoreWorkspaceEdits(ws, snap) {
|
|
217
|
+
assertNoNestedRepos(ws);
|
|
218
|
+
const before = new Set(snap.dirty);
|
|
219
|
+
const headNow = agentGit(ws, ["rev-parse", "HEAD"]);
|
|
220
|
+
if (headNow !== snap.head)
|
|
221
|
+
agentGit(ws, ["reset", "--mixed", snap.head]);
|
|
222
|
+
const touched = parseStatus(agentGit(ws, ["status", "--porcelain", "-z", "--untracked-files=all"])).filter((p) => !before.has(p));
|
|
223
|
+
return restoreTouched(touched, {
|
|
224
|
+
lsFiles: () => agentGit(ws, ["ls-files", "-z"]),
|
|
225
|
+
checkout: (paths) => agentGit(ws, ["checkout", "--", ...paths]),
|
|
226
|
+
clean: (paths) => agentGit(ws, ["clean", "-fd", "--", ...paths]),
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
function restoreTouched(touched, git) {
|
|
230
|
+
if (!touched.length)
|
|
231
|
+
return [];
|
|
232
|
+
const tracked = new Set(zList(git.lsFiles()));
|
|
233
|
+
const restore = touched.filter((p) => tracked.has(p));
|
|
234
|
+
const extra = touched.filter((p) => !tracked.has(p));
|
|
235
|
+
if (restore.length)
|
|
236
|
+
git.checkout(restore);
|
|
237
|
+
if (extra.length)
|
|
238
|
+
git.clean(extra);
|
|
239
|
+
return touched;
|
|
240
|
+
}
|
|
175
241
|
/**
|
|
176
242
|
* Refuse a worktree that holds a git repository of its own. `status`, `add -A` and `commit` can visit a nested repository and run
|
|
177
243
|
* git there with that repository's config — which the agent wrote. Run before any command that walks the working tree.
|
|
@@ -233,20 +299,208 @@ export function isolationBlocker(dir) {
|
|
|
233
299
|
return "reftable ref storage";
|
|
234
300
|
return undefined;
|
|
235
301
|
}
|
|
302
|
+
/** How long a `git fetch` may take before it counts as failed. */
|
|
303
|
+
const FETCH_TIMEOUT_MS = 60_000;
|
|
304
|
+
const defaultGitRunner = (cwd, args, env) => {
|
|
305
|
+
const r = spawnSync("git", args, { cwd, env: { ...process.env, ...env }, encoding: "utf8", timeout: FETCH_TIMEOUT_MS, killSignal: "SIGKILL", stdio: ["ignore", "pipe", "pipe"] });
|
|
306
|
+
if (r.error || r.status !== 0)
|
|
307
|
+
return { ok: false };
|
|
308
|
+
return { ok: true, stdout: r.stdout.replace(/\n$/, "") };
|
|
309
|
+
};
|
|
310
|
+
/**
|
|
311
|
+
* What `git fetch` must never do here: ask a person for a password or a host-key answer.
|
|
312
|
+
* The ssh command is the user's own (`GIT_SSH_COMMAND`, else the repo's `core.sshCommand`, else `ssh`) with `-o BatchMode=yes` added;
|
|
313
|
+
* a config that cannot be read counts as none.
|
|
314
|
+
*/
|
|
315
|
+
function noPromptEnv(dir) {
|
|
316
|
+
const ssh = process.env.GIT_SSH_COMMAND || tryGit(dir, ["config", "--get", "core.sshCommand"]) || "ssh";
|
|
317
|
+
return { GIT_TERMINAL_PROMPT: "0", GIT_SSH_COMMAND: `${ssh} -o BatchMode=yes` };
|
|
318
|
+
}
|
|
319
|
+
const REMOTE_BASE_FALLBACKS = ["origin/main", "origin/master"];
|
|
320
|
+
/**
|
|
321
|
+
* The commit new runs should start from: `origin/HEAD`, else `origin/main`, else `origin/master`.
|
|
322
|
+
* Fetches `origin` first when there is one; a fetch that fails or times out is not an error, the remote refs already in the repo are used.
|
|
323
|
+
* `onFetchFailed` is called when that fetch failed, so the caller can say so.
|
|
324
|
+
*/
|
|
325
|
+
export function resolveRemoteBase(dir, run = defaultGitRunner, onFetchFailed) {
|
|
326
|
+
const originUrl = tryGit(dir, ["remote", "get-url", "--push", "origin"]);
|
|
327
|
+
if (originUrl !== undefined && !run(dir, ["fetch", "--quiet", "--no-tags", "--no-recurse-submodules", "origin"], noPromptEnv(dir)).ok)
|
|
328
|
+
onFetchFailed?.();
|
|
329
|
+
const head = tryGit(dir, ["symbolic-ref", "-q", "refs/remotes/origin/HEAD"]);
|
|
330
|
+
const candidates = [...(head?.startsWith("refs/remotes/") ? [head.slice("refs/remotes/".length)] : []), ...REMOTE_BASE_FALLBACKS];
|
|
331
|
+
for (const ref of candidates) {
|
|
332
|
+
const sha = tryGit(dir, ["rev-parse", "--verify", "-q", `refs/remotes/${ref}^{commit}`]);
|
|
333
|
+
if (sha)
|
|
334
|
+
return { ref, sha, ...(originUrl ? { originUrl } : {}) };
|
|
335
|
+
}
|
|
336
|
+
return undefined;
|
|
337
|
+
}
|
|
338
|
+
/** Why the project checkout cannot be lent to a new run sitting at `base`, or undefined when it can. */
|
|
339
|
+
function checkoutBlocker(dir, base, heldByOther) {
|
|
340
|
+
if (heldByOther)
|
|
341
|
+
return "the project checkout is in use by another run";
|
|
342
|
+
if (dirtyPaths(dir).length > 0)
|
|
343
|
+
return "the project checkout has uncommitted changes";
|
|
344
|
+
if (tryGit(dir, ["rev-parse", "--verify", "-q", "HEAD^{commit}"]) !== base.sha)
|
|
345
|
+
return `the project checkout is not at ${base.ref}`;
|
|
346
|
+
const branch = tryGit(dir, ["symbolic-ref", "-q", "HEAD"]);
|
|
347
|
+
if (branch?.startsWith("refs/heads/agent-lyceum/"))
|
|
348
|
+
return `the project checkout is on ${branch.slice("refs/heads/".length)}`;
|
|
349
|
+
return undefined;
|
|
350
|
+
}
|
|
351
|
+
/** The plan a run falls back to when it cannot borrow the project checkout: the lead in its own worktree, no task branch; the remote base stays. */
|
|
352
|
+
export function toLeadWorktree(plan) {
|
|
353
|
+
const { taskBranch: _taskBranch, checkoutFrom: _checkoutFrom, ...rest } = plan;
|
|
354
|
+
return { ...rest, leadWorktree: true };
|
|
355
|
+
}
|
|
356
|
+
/** Does this (new run's) plan intend to borrow the project checkout? */
|
|
357
|
+
export const borrowsCheckout = (plan) => plan.leadWorktree === false && plan.baseSha !== undefined;
|
|
358
|
+
/** Why the checkout cannot be borrowed now (dirty, moved off `plan.baseSha`, on an `agent-lyceum/*` branch), or undefined when it still can. Takes no lock. */
|
|
359
|
+
export function checkoutBlockedNow(dir, plan) {
|
|
360
|
+
if (plan.baseSha === undefined)
|
|
361
|
+
return "no remote base";
|
|
362
|
+
return checkoutBlocker(dir, { ref: plan.baseRef ?? plan.baseSha, sha: plan.baseSha }, false);
|
|
363
|
+
}
|
|
364
|
+
/** Where HEAD is: `ref:refs/heads/x` on a branch, the commit when detached, undefined in a repo without a commit. Never reads the exit code of a git command that moved it. */
|
|
365
|
+
const headPlace = (dir) => {
|
|
366
|
+
const ref = tryGit(dir, ["symbolic-ref", "-q", "HEAD"]);
|
|
367
|
+
if (ref !== undefined)
|
|
368
|
+
return `ref:${ref}`;
|
|
369
|
+
return tryGit(dir, ["rev-parse", "--verify", "-q", "HEAD"]);
|
|
370
|
+
};
|
|
371
|
+
/** The checkout's current branch name, or its commit when HEAD is detached: what a failed start returns to. */
|
|
372
|
+
export function currentCheckoutRef(dir) {
|
|
373
|
+
return tryGit(dir, ["symbolic-ref", "-q", "--short", "HEAD"]) ?? tryGit(dir, ["rev-parse", "--verify", "-q", "HEAD"]);
|
|
374
|
+
}
|
|
375
|
+
const branchTip = (dir, branch) => tryGit(dir, ["rev-parse", "--verify", "-q", `refs/heads/${branch}^{commit}`]);
|
|
376
|
+
/**
|
|
377
|
+
* Cut `branch` at `sha` and switch the checkout to it (`git checkout -b`, never `-B`: an existing branch is an error and is not reset).
|
|
378
|
+
* The repository's hooks run. Whether it worked is judged by where HEAD is before and after, not by git's exit code: a failing
|
|
379
|
+
* `post-checkout` hook still leaves HEAD on the new branch (`moved: true`), a hook that stops the switch leaves it where it was (`moved: false`).
|
|
380
|
+
*/
|
|
381
|
+
export function checkoutLeadBranch(dir, branch, sha) {
|
|
382
|
+
if (branchTip(dir, branch) !== undefined)
|
|
383
|
+
throw new Error(`The branch ${branch} already exists in ${dir}; it was not touched.`);
|
|
384
|
+
const before = headPlace(dir);
|
|
385
|
+
const r = spawnSync("git", ["checkout", "-q", "-b", branch, sha], { cwd: dir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
|
|
386
|
+
const moved = headPlace(dir) !== before;
|
|
387
|
+
if (!moved && r.stderr)
|
|
388
|
+
process.stderr.write(r.stderr);
|
|
389
|
+
return { moved };
|
|
390
|
+
}
|
|
391
|
+
/** Where a failed start put the checkout back to: the recorded `checkout_from` still resolves (a local branch, or a commit when it was detached). */
|
|
392
|
+
function checkoutFromExists(dir, from) {
|
|
393
|
+
return branchTip(dir, from) !== undefined || (/^[0-9a-f]{40}$/.test(from) && tryGit(dir, ["rev-parse", "--verify", "-q", `${from}^{commit}`]) === from);
|
|
394
|
+
}
|
|
395
|
+
/** Is the checkout on `from` now (the branch, or the detached commit)? */
|
|
396
|
+
function checkoutIsAt(dir, from) {
|
|
397
|
+
const here = headPlace(dir);
|
|
398
|
+
return here === `ref:refs/heads/${from}` || (/^[0-9a-f]{40}$/.test(from) && here === from);
|
|
399
|
+
}
|
|
400
|
+
const removeRunDir = (runDir) => fs.rmSync(runDir, { recursive: true, force: true });
|
|
401
|
+
/**
|
|
402
|
+
* A new checkout run whose state is written but whose task is not yet in the lead's inbox, taken back: the checkout returns to
|
|
403
|
+
* `checkout_from`, the task branch (when it is still at `base_sha`) and the whole run dir are removed. Call it with the run's lock held.
|
|
404
|
+
* It only ever changes what this start changed: a branch with commits of its own, a tree with uncommitted changes, or a `checkout_from`
|
|
405
|
+
* that is gone make it throw and leave the state, the branch and HEAD alone (it never tries a second switch).
|
|
406
|
+
*/
|
|
407
|
+
export function rollbackCheckoutStart(dir, runDir, state) {
|
|
408
|
+
const branch = state.task_branch;
|
|
409
|
+
const tip = branch ? branchTip(dir, branch) : undefined;
|
|
410
|
+
if (branch === undefined || tip === undefined) {
|
|
411
|
+
removeRunDir(runDir); // the branch was never cut; HEAD never moved
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
if (tip !== state.base_sha) {
|
|
415
|
+
throw new Error(`The branch ${branch} has commits of its own (it is at ${tip.slice(0, 8)}, not at the base ${state.base_sha?.slice(0, 8) ?? "that was not recorded"}); nothing was removed. Run ${state.run_id} is kept as it is.`);
|
|
416
|
+
}
|
|
417
|
+
const ref = `refs/heads/${branch}`;
|
|
418
|
+
if (headPlace(dir) === `ref:${ref}`) {
|
|
419
|
+
const from = state.checkout_from;
|
|
420
|
+
if (dirtyPaths(dir).length > 0)
|
|
421
|
+
throw new Error(`The project checkout is on ${branch} and has uncommitted changes, so it was not switched back${from ? ` to ${from}` : ""}; nothing was removed. Run ${state.run_id} is kept as it is.`);
|
|
422
|
+
if (from === undefined || !checkoutFromExists(dir, from)) {
|
|
423
|
+
throw new Error(`The project checkout is on ${branch}, and the branch it was cut from (${from ?? "not recorded"}) is not there to go back to. Switch it yourself; nothing was removed. Run ${state.run_id} is kept as it is.`);
|
|
424
|
+
}
|
|
425
|
+
spawnSync("git", ["checkout", "-q", "--no-guess", from, "--"], { cwd: dir, stdio: "ignore" }); // once; hooks may fail it after it moved
|
|
426
|
+
if (!checkoutIsAt(dir, from)) {
|
|
427
|
+
throw new Error(`The project checkout could not be switched from ${branch} back to ${from}; it stays on ${branch}. Nothing was removed. Run ${state.run_id} is kept as it is.`);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
// Only the exact commit this start cut it at: the update fails when the branch moved meanwhile.
|
|
431
|
+
git(dir, ["update-ref", "-d", ref, tip]);
|
|
432
|
+
removeRunDir(runDir);
|
|
433
|
+
}
|
|
434
|
+
/** The first thing a new checkout run does once its state is saved (without `task_sent`): cut the task branch. On any failure the run dir is gone. */
|
|
435
|
+
export function beginCheckoutRun(dir, runDir, state) {
|
|
436
|
+
const { task_branch: branch, base_sha: sha } = state;
|
|
437
|
+
if (!branch || !sha) {
|
|
438
|
+
removeRunDir(runDir);
|
|
439
|
+
throw new Error(`Run ${state.run_id} has no task branch or base commit to check out.`);
|
|
440
|
+
}
|
|
441
|
+
let moved;
|
|
442
|
+
try {
|
|
443
|
+
({ moved } = checkoutLeadBranch(dir, branch, sha));
|
|
444
|
+
}
|
|
445
|
+
catch (e) {
|
|
446
|
+
removeRunDir(runDir);
|
|
447
|
+
throw e;
|
|
448
|
+
}
|
|
449
|
+
if (!moved) {
|
|
450
|
+
removeRunDir(runDir);
|
|
451
|
+
throw new Error(`git could not switch the project checkout to ${branch} (HEAD did not move), so run ${state.run_id} was not started.`);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Under the run's lock, before a checkout run goes on. Its task never reached the lead (`task_sent` missing): the start is taken back
|
|
456
|
+
* (see `rollbackCheckoutStart`) and this throws that the run is gone. Its task was sent: the checkout must still be on the task branch;
|
|
457
|
+
* it is never switched for you, and the run is not turned into a worktree run.
|
|
458
|
+
*/
|
|
459
|
+
export function assertCheckoutResumable(dir, runDir, state) {
|
|
460
|
+
if (state.task_sent !== true) {
|
|
461
|
+
rollbackCheckoutStart(dir, runDir, state);
|
|
462
|
+
throw new Error(`Run ${state.run_id} never got its task to ${state.task_branch ? `the lead on ${state.task_branch}` : "the lead"}; the start was taken back (the project checkout is as it was, the run's folder is removed). Start it again with \`run\`.`);
|
|
463
|
+
}
|
|
464
|
+
const branch = state.task_branch;
|
|
465
|
+
if (!branch)
|
|
466
|
+
throw new Error(`Run ${state.run_id} works in the project checkout, but its state does not record a task_branch.`);
|
|
467
|
+
if (headPlace(dir) !== `ref:refs/heads/${branch}`) {
|
|
468
|
+
const here = tryGit(dir, ["symbolic-ref", "-q", "--short", "HEAD"]) ?? "a detached HEAD";
|
|
469
|
+
throw new Error(`Run ${state.run_id} works on the branch ${branch}, but the project checkout is on ${here}. Switch to ${branch} (git checkout ${branch}) and resume again; it was not switched for you.`);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
/** Whether the repo knows an `origin` at all: a remote, or refs fetched from one. */
|
|
473
|
+
const hasOrigin = (dir) => tryGit(dir, ["remote", "get-url", "origin"]) !== undefined || (tryGit(dir, ["for-each-ref", "--count=1", "--format=%(refname)", "refs/remotes/origin/"]) ?? "") !== "";
|
|
236
474
|
/**
|
|
237
475
|
* Where a run's agents work. A new run is isolated when the project dir can be (see `isolationBlocker`), otherwise it shares the
|
|
238
|
-
* checkout.
|
|
476
|
+
* checkout. When the repo has a remote base and the project checkout is clean, sits exactly on it and nobody else holds it, the lead
|
|
477
|
+
* borrows the checkout (`leadWorktree: false`, with `baseSha`); otherwise the lead gets its own worktree. A resumed run keeps what its
|
|
478
|
+
* state recorded, whatever the repo looks like now. Decided once, before the run's lock is taken; it takes no lock itself.
|
|
239
479
|
*/
|
|
240
|
-
export function planWorkspace(project, resume) {
|
|
480
|
+
export function planWorkspace(project, resume, opts = {}) {
|
|
241
481
|
if (resume) {
|
|
242
482
|
if (resume.lead_workspace === true)
|
|
243
483
|
return { mode: "worktree", leadWorktree: true };
|
|
484
|
+
if (resume.workspace_mode === "checkout")
|
|
485
|
+
return { mode: "worktree", leadWorktree: false, ...(resume.task_branch ? { taskBranch: resume.task_branch } : {}) };
|
|
244
486
|
if (resume.workspace_mode === "worktree")
|
|
245
487
|
return { mode: "worktree", leadWorktree: false };
|
|
246
488
|
return { mode: "shared", leadWorktree: false };
|
|
247
489
|
}
|
|
248
|
-
const
|
|
249
|
-
|
|
490
|
+
const blocker = isolationBlocker(project.dir);
|
|
491
|
+
if (blocker !== undefined)
|
|
492
|
+
return { mode: "shared", leadWorktree: false, reason: blocker };
|
|
493
|
+
let fetchFailed = false;
|
|
494
|
+
const base = resolveRemoteBase(project.dir, opts.fetch, () => (fetchFailed = true));
|
|
495
|
+
const failed = fetchFailed ? { fetchFailed: true } : {};
|
|
496
|
+
if (!base) {
|
|
497
|
+
return hasOrigin(project.dir)
|
|
498
|
+
? { mode: "worktree", leadWorktree: true, ...failed, reason: "no remote base: origin/HEAD, origin/main and origin/master are all missing" }
|
|
499
|
+
: { mode: "worktree", leadWorktree: true };
|
|
500
|
+
}
|
|
501
|
+
const remote = { baseRef: base.ref, baseSha: base.sha, ...(base.originUrl ? { originUrl: base.originUrl } : {}), ...failed };
|
|
502
|
+
const reason = checkoutBlocker(project.dir, base, opts.checkoutHeldByOther === true);
|
|
503
|
+
return reason === undefined ? { mode: "worktree", leadWorktree: false, ...remote } : { mode: "worktree", leadWorktree: true, ...remote, reason };
|
|
250
504
|
}
|
|
251
505
|
/** Refuse to resume a worktree run when its repo can no longer be isolated; returns nothing when it is fine. */
|
|
252
506
|
export function assertWorktreeRunnable(project) {
|
|
@@ -265,6 +519,30 @@ export function snapshotHead(project, runId) {
|
|
|
265
519
|
git(top, ["update-ref", ref, sha]);
|
|
266
520
|
return ref;
|
|
267
521
|
}
|
|
522
|
+
/** `refs/agent-lyceum/<run>/base-0` pointing at `sha` (a remote base the run records): where a concurrent run with a remote base starts, whatever the local HEAD is. */
|
|
523
|
+
export function snapshotCommit(project, runId, sha) {
|
|
524
|
+
const top = toplevel(project.dir);
|
|
525
|
+
const commit = git(top, ["rev-parse", "--verify", `${sha}^{commit}`]);
|
|
526
|
+
const ref = `refs/agent-lyceum/${runId}/base-0`;
|
|
527
|
+
git(top, ["update-ref", ref, commit]);
|
|
528
|
+
return ref;
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* What to tell the user when a new run starts from the remote base `sha` while the local HEAD is somewhere else: on another task's
|
|
532
|
+
* `agent-lyceum/*` branch the run is moved into a worktree; otherwise your local checkout has not reached that commit.
|
|
533
|
+
* Undefined when HEAD is at `sha` (or the repo has no HEAD).
|
|
534
|
+
*/
|
|
535
|
+
export function remoteBaseNote(project, sha, baseRef) {
|
|
536
|
+
const dir = project.dir;
|
|
537
|
+
const head = tryGit(dir, ["rev-parse", "--verify", "-q", "HEAD^{commit}"]);
|
|
538
|
+
if (head === undefined || head === sha)
|
|
539
|
+
return undefined;
|
|
540
|
+
const branch = tryGit(dir, ["symbolic-ref", "-q", "HEAD"]);
|
|
541
|
+
if (branch?.startsWith("refs/heads/agent-lyceum/")) {
|
|
542
|
+
return `這次 run 改在 worktree:你的 checkout 在 ${branch.slice("refs/heads/".length)},不在 ${baseRef ?? "遠端基準"} ${sha.slice(0, 8)}`;
|
|
543
|
+
}
|
|
544
|
+
return `本地尚未進入這顆 commit(${baseRef ?? "遠端基準"} ${sha.slice(0, 8)}):這次 run 從它開始,不含你本地 HEAD ${head.slice(0, 8)} 上的提交`;
|
|
545
|
+
}
|
|
268
546
|
/**
|
|
269
547
|
* Commit the repo's current working tree (tracked changes and new, non-ignored files) as an unreferenced-by-branch
|
|
270
548
|
* snapshot `refs/agent-lyceum/<run>/base-<n>`. Uses a throwaway index, so HEAD, branches, the real index and the
|
|
@@ -687,7 +965,11 @@ export function recordedGitDir(project, runId, agent) {
|
|
|
687
965
|
return undefined;
|
|
688
966
|
}
|
|
689
967
|
}
|
|
690
|
-
/**
|
|
968
|
+
/**
|
|
969
|
+
* What is in an agent's worktree that exists nowhere else: uncommitted changes, and commits whose files are not in the main repo.
|
|
970
|
+
* `target`: where the commits are looked for. A worktree (the lead's, in a concurrent run), a commit of your repo (`{ commit }`: a checkout
|
|
971
|
+
* run's recorded result, compared as it was committed, whatever your HEAD is now), or by default your repo's working tree.
|
|
972
|
+
*/
|
|
691
973
|
export function inspectWorkspace(project, runId, agent, target) {
|
|
692
974
|
const root = workspaceRoot(project, runId, agent);
|
|
693
975
|
if (!fs.existsSync(root))
|
|
@@ -715,14 +997,15 @@ export function inspectWorkspace(project, runId, agent, target) {
|
|
|
715
997
|
try {
|
|
716
998
|
assertNoNestedRepos(ws);
|
|
717
999
|
work.dirty = parseStatus(agentGit(ws, ["status", "--porcelain", "-z", "--untracked-files=all"]));
|
|
718
|
-
const
|
|
1000
|
+
const commit = target && "commit" in target ? target.commit : undefined;
|
|
1001
|
+
const at = target && !commit ? { ws: target } : { top: toplevel(project.dir) };
|
|
719
1002
|
const head = agentGit(ws, ["rev-parse", "HEAD"]);
|
|
720
|
-
if (head !== ws.base && tryGitAt(at, ["merge-base", "--is-ancestor", head, "HEAD"]) === undefined) {
|
|
1003
|
+
if (head !== ws.base && tryGitAt(at, ["merge-base", "--is-ancestor", head, commit ?? "HEAD"]) === undefined) {
|
|
721
1004
|
const raw = agentGit(ws, ["diff", "--raw", "-z", "--no-renames", "--no-abbrev", ws.base, head]);
|
|
722
1005
|
const parts = raw.split("\0").filter(Boolean);
|
|
723
1006
|
for (let i = 1; i < parts.length; i += 2) {
|
|
724
1007
|
const file = parts[i] ?? "";
|
|
725
|
-
if (workingBlob(at, file) !== blobAt(at, head, file))
|
|
1008
|
+
if ((commit ? blobAt(at, commit, file) : workingBlob(at, file)) !== blobAt(at, head, file))
|
|
726
1009
|
work.unintegrated.push(file);
|
|
727
1010
|
}
|
|
728
1011
|
}
|
|
@@ -734,22 +1017,102 @@ export function inspectWorkspace(project, runId, agent, target) {
|
|
|
734
1017
|
}
|
|
735
1018
|
/** Commit the lead's checkout on its branch (once, at the end of a run) and write what changed as a patch. Never touches your repo's working tree. */
|
|
736
1019
|
export function finishLeadBranch(ws, message, patchFile) {
|
|
737
|
-
const { head } = commitWorkspace(ws, message);
|
|
738
|
-
|
|
1020
|
+
const { head, committed } = commitWorkspace(ws, message);
|
|
1021
|
+
// Member integrations are committed before a team lead wakes, so the tree can already be clean while the branch is ahead of its base. The closing commit still carries the run's message.
|
|
1022
|
+
if (!committed && head !== ws.base)
|
|
1023
|
+
agentGit(ws, ["commit", "-q", "--no-verify", "--allow-empty", "-m", message], IDENTITY);
|
|
1024
|
+
const tip = agentGit(ws, ["rev-parse", "HEAD"]);
|
|
1025
|
+
const files = tip === ws.base ? [] : agentGit(ws, ["diff", "--name-only", ws.base, tip]).split("\n").filter(Boolean);
|
|
1026
|
+
if (files.length)
|
|
1027
|
+
fs.writeFileSync(patchFile, agentGit(ws, ["diff", "--binary", "--full-index", ws.base, tip]) + "\n");
|
|
1028
|
+
return { branch: ws.branch, head: tip, base: ws.base, files: files.length, patch: files.length ? patchFile : undefined };
|
|
1029
|
+
}
|
|
1030
|
+
/** What a checkout run's task branch is now, for `clear`: its tip (undefined when the branch is gone), whether HEAD names it, and whether the tip is in HEAD. */
|
|
1031
|
+
export function taskBranchState(dir, branch) {
|
|
1032
|
+
const top = toplevel(dir);
|
|
1033
|
+
const tip = tryGit(top, ["rev-parse", "--verify", "-q", `refs/heads/${branch}^{commit}`]);
|
|
1034
|
+
const headIsBranch = tryGit(top, ["symbolic-ref", "-q", "HEAD"]) === `refs/heads/${branch}`;
|
|
1035
|
+
const tipInHead = tip !== undefined && tryGit(top, ["merge-base", "--is-ancestor", tip, "HEAD"]) !== undefined;
|
|
1036
|
+
return { tip, headIsBranch, tipInHead };
|
|
1037
|
+
}
|
|
1038
|
+
/** A commit of your repo by name (a sha), or undefined when it is not there. */
|
|
1039
|
+
export function resolveCommit(dir, sha) {
|
|
1040
|
+
return tryGit(toplevel(dir), ["rev-parse", "--verify", "-q", `${sha}^{commit}`]);
|
|
1041
|
+
}
|
|
1042
|
+
/**
|
|
1043
|
+
* `git branch -D` of a checkout run's task branch, only while it is still what `clear` planned to delete: HEAD does not name it, its tip
|
|
1044
|
+
* is `expectedTip` (nothing was committed on it since the plan) and that tip is in HEAD. Throws, deleting nothing, otherwise.
|
|
1045
|
+
*/
|
|
1046
|
+
export function deleteTaskBranch(dir, branch, expectedTip) {
|
|
1047
|
+
const s = taskBranchState(dir, branch);
|
|
1048
|
+
if (s.headIsBranch)
|
|
1049
|
+
throw new Error(`the project checkout is on ${branch}; switch to another branch first`);
|
|
1050
|
+
if (s.tip === undefined)
|
|
1051
|
+
return; // already gone
|
|
1052
|
+
if (s.tip !== expectedTip)
|
|
1053
|
+
throw new Error(`${branch} moved since the plan (now at ${s.tip.slice(0, 8)}); kept it`);
|
|
1054
|
+
if (!s.tipInHead)
|
|
1055
|
+
throw new Error(`${branch} is no longer in HEAD; kept it`);
|
|
1056
|
+
git(toplevel(dir), ["branch", "-D", "--", branch]);
|
|
1057
|
+
}
|
|
1058
|
+
/** Why the project checkout is not on its task branch `branch` (HEAD names another branch, or is detached), or undefined when it is. */
|
|
1059
|
+
export function checkoutHeadProblem(dir, branch) {
|
|
1060
|
+
const head = tryGit(dir, ["symbolic-ref", "-q", "HEAD"]);
|
|
1061
|
+
if (head === `refs/heads/${branch}`)
|
|
1062
|
+
return undefined;
|
|
1063
|
+
const where = head !== undefined ? head.replace(/^refs\/heads\//, "") : "a detached commit";
|
|
1064
|
+
return `The project checkout is no longer on the task branch ${branch} (HEAD is ${where}).`;
|
|
1065
|
+
}
|
|
1066
|
+
/** Runs git without a time limit (`add -A` and `commit` in a big checkout may take long), keeping stdout and stderr. */
|
|
1067
|
+
const checkoutRunner = (cwd, args, env) => {
|
|
1068
|
+
const r = spawnSync("git", args, { cwd, env: { ...process.env, ...env }, encoding: "utf8", maxBuffer: 256 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
|
|
1069
|
+
if (r.error || r.status !== 0)
|
|
1070
|
+
return { ok: false, stderr: (r.stderr || r.error?.message || "").trim() };
|
|
1071
|
+
return { ok: true, stdout: r.stdout.replace(/\n$/, "") };
|
|
1072
|
+
};
|
|
1073
|
+
/**
|
|
1074
|
+
* A checkout run, at its end: commit what is in the project checkout on the task branch `branch`, once, and write what changed since
|
|
1075
|
+
* `baseSha` as a patch. Returns undefined, and touches nothing, when HEAD is not `refs/heads/<branch>` (the checkout was moved: a commit
|
|
1076
|
+
* would land on the branch HEAD names now). `add -A` and `commit` run with the pinned config (no hooks, no fsmonitor, no signing, `--no-verify`),
|
|
1077
|
+
* and a nested git repository in the checkout is refused first, as in an agent's worktree. `run` is a test seam, as for `resolveRemoteBase`.
|
|
1078
|
+
*/
|
|
1079
|
+
export function finishCheckoutBranch(dir, branch, baseSha, message, patchFile, run = checkoutRunner) {
|
|
1080
|
+
if (checkoutHeadProblem(dir, branch) !== undefined)
|
|
1081
|
+
return undefined;
|
|
1082
|
+
const pinned = (args, env = {}) => run(dir, pinnedArgs(args), env);
|
|
1083
|
+
const need = (args, env) => {
|
|
1084
|
+
const r = pinned(args, env);
|
|
1085
|
+
if (!r.ok)
|
|
1086
|
+
throw new Error(`git ${args[0]} failed in ${dir}${r.stderr ? `: ${r.stderr.split("\n")[0]}` : ""}`);
|
|
1087
|
+
return r.stdout ?? "";
|
|
1088
|
+
};
|
|
1089
|
+
for (const p of zList(need(["ls-files", "-o", "--exclude-standard", "-z"])).filter((e) => e.endsWith("/"))) {
|
|
1090
|
+
throw new Error(`Refusing to run git in ${dir}: it contains a nested git repository at ${p.slice(0, -1)}; remove it, or add it to .gitignore if it must stay. Nothing in it was touched.`);
|
|
1091
|
+
}
|
|
1092
|
+
need(["add", "-A"]);
|
|
1093
|
+
if (!pinned(["diff", "--cached", "--quiet"]).ok)
|
|
1094
|
+
need(["commit", "-q", "--no-verify", "-m", message], IDENTITY);
|
|
1095
|
+
const head = need(["rev-parse", "HEAD"]);
|
|
1096
|
+
const files = head === baseSha ? [] : need(["diff", "--name-only", baseSha, head]).split("\n").filter(Boolean);
|
|
739
1097
|
if (files.length)
|
|
740
|
-
fs.writeFileSync(patchFile,
|
|
741
|
-
return { branch
|
|
1098
|
+
fs.writeFileSync(patchFile, need(["diff", "--binary", "--full-index", baseSha, head]) + "\n");
|
|
1099
|
+
return { branch, head, base: baseSha, files: files.length, patch: files.length ? patchFile : undefined };
|
|
742
1100
|
}
|
|
743
1101
|
/**
|
|
744
1102
|
* A reopened run whose lead branch was already merged into your HEAD starts its next segment on a fresh branch cut from HEAD,
|
|
745
1103
|
* so the merged work is not offered again. Only when nothing would be lost: the branch's last committed head (`resultHead`) is
|
|
746
1104
|
* in HEAD, the worktree is still at that head, and it holds no uncommitted work and nothing whose state is unknown.
|
|
747
|
-
* Otherwise the worktree and branch are returned unchanged.
|
|
1105
|
+
* Otherwise the worktree and branch are returned unchanged. Also unchanged while HEAD is on an `agent-lyceum/*` branch (another task's).
|
|
1106
|
+
* The new branch is always cut from the local HEAD, never from the run's `base_sha`, which would drop what you merged since.
|
|
1107
|
+
* Your working tree, index and HEAD are never touched.
|
|
748
1108
|
*/
|
|
749
1109
|
export function recutLeadWorkspace(project, runId, agent, ws, resultHead) {
|
|
750
1110
|
const keep = { ws, recut: false };
|
|
751
1111
|
if (!resultHead)
|
|
752
1112
|
return keep;
|
|
1113
|
+
// HEAD is on another task's branch: a branch cut from it would be built on that task's work, not on yours.
|
|
1114
|
+
if (tryGit(toplevel(project.dir), ["symbolic-ref", "-q", "HEAD"])?.startsWith("refs/heads/agent-lyceum/"))
|
|
1115
|
+
return keep;
|
|
753
1116
|
if (tryGit(toplevel(project.dir), ["merge-base", "--is-ancestor", resultHead, "HEAD"]) === undefined)
|
|
754
1117
|
return keep;
|
|
755
1118
|
const work = inspectWorkspace(project, runId, agent, ws);
|