@join-pantheon/cli 0.37.1 → 0.37.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2344,6 +2344,10 @@ ${B("control")}
2344
2344
  pantheon hook install your agent keeps working when a peer is waiting on it
2345
2345
  (auto-detects claude / codex / cursor / copilot / kiro on this machine)
2346
2346
  pantheon spend woken runs on this machine, and what pantheon cannot see
2347
+ pantheon runs the copies of your repos the worker made for teammates' requests: which request each was
2348
+ for, who asked, and whether it holds anything unsaved
2349
+ (runs clean [<branch>] removes the ones that hold nothing unsaved · --pushed also deletes
2350
+ this computer's copy of branches that are pushed but not merged)
2347
2351
  pantheon leave remove what pantheon put on this machine
2348
2352
  pantheon uninstall remove Pantheon itself: its services, hooks, its own Node, the pantheon command, the PATH
2349
2353
  lines and what it keeps in ~/.pantheon — but not your identity, so installing again puts
@@ -2445,6 +2449,7 @@ const COMMAND_FLAGS = {
2445
2449
  history: "--goal <id> --from <member> --last <n> --since <seq> --short --presence --json",
2446
2450
  usage: "--space <team> --days <n> --json",
2447
2451
  network: "--proxy <url> [--no-proxy <hosts>] | --direct | --clear",
2452
+ runs: "[clean [<branch>]] --pushed (clean: also this computer's copy of branches that are pushed but not merged) --project <dir>",
2448
2453
  leave: "[<team> | <team id>] --yes --if-gone (only if the relay still says the team is deleted, or that you were removed) --keep-identity --stop-relay --project <dir>",
2449
2454
  uninstall: "--yes --forget-identity --stop-relay --project <dir>",
2450
2455
  stop: "[relay|worker|notifier|menubar|all] --port <n>",
@@ -4576,14 +4581,18 @@ async function main() {
4576
4581
  {
4577
4582
  const { removePantheonWorktrees, removeHomeLeftovers } = await import("./machine.js");
4578
4583
  const repos = [project, ...Object.values(all?.bindings ?? {}).map((b) => b.path).filter((p) => !!p)];
4579
- const trees = removePantheonWorktrees(repos, [...(homeRefusal ? [] : [join(CONFIG_DIR, "worktrees")]), ...repos.map((r) => join(r, ".pantheon", "worktrees"))]);
4584
+ const trees = removePantheonWorktrees(repos, [...(homeRefusal ? [] : [join(CONFIG_DIR, "worktrees")]), ...repos.map((r) => join(r, ".pantheon", "worktrees"))], CONFIG_DIR, undefined, undefined, !homeRefusal);
4580
4585
  removed.push(...trees.removed);
4581
4586
  left.push(...trees.left);
4582
4587
  if (!homeRefusal) {
4583
- try {
4584
- rmSync(join(CONFIG_DIR, "worktrees"), { recursive: true, force: true });
4588
+ if (!trees.kept) {
4589
+ try {
4590
+ rmSync(join(CONFIG_DIR, "worktrees"), { recursive: true, force: true });
4591
+ }
4592
+ catch { }
4585
4593
  }
4586
- catch { }
4594
+ else
4595
+ spare.push(join(CONFIG_DIR, "worktrees"));
4587
4596
  const rest = removeHomeLeftovers(CONFIG_DIR, keepIdentity, { uninstalling, refusal: null });
4588
4597
  removed.push(...rest.removed);
4589
4598
  left.push(...rest.left);
@@ -4648,6 +4657,53 @@ async function main() {
4648
4657
  console.log(l);
4649
4658
  return;
4650
4659
  }
4660
+ case "runs": {
4661
+ const { listRuns, runLines, cleanRuns } = await import("./runs.js");
4662
+ const { sameProcess, recordedRunAlive, RUN_RECORD } = await import("./worker.js");
4663
+ const all = loadAll();
4664
+ const project = resolve(flag("project", "."));
4665
+ const repos = [...new Set([project, ...Object.values(all?.bindings ?? {}).map((b) => b.path).filter((p) => !!p)].map((p) => resolve(p)))];
4666
+ const roots = [join(CONFIG_DIR, "worktrees"), ...repos.map((r) => join(r, ".pantheon", "worktrees"))];
4667
+ const runInFlight = (() => { try {
4668
+ const r = JSON.parse(readFileSync(join(CONFIG_DIR, RUN_RECORD), "utf8"));
4669
+ return typeof r.pid === "number" && Number.isInteger(r.pid) && r.pid > 1 && recordedRunAlive(r.pid);
4670
+ }
4671
+ catch {
4672
+ return false;
4673
+ } })();
4674
+ const alive = (pid, id) => sameProcess(pid, id);
4675
+ const trees = listRuns(repos, roots, CONFIG_DIR);
4676
+ const sub = argv[1];
4677
+ if (sub === "clean") {
4678
+ const which = argv.slice(2).find((a) => !a.startsWith("--"));
4679
+ const pick = which ? trees.filter((t) => t.branch === which || (!!t.worktree && (resolve(t.worktree) === resolve(which) || basename(t.worktree) === which))) : trees;
4680
+ if (which && !pick.length)
4681
+ die(`No background checkout or branch is called ${which} here. See them all: pantheon runs`);
4682
+ if (!pick.length) {
4683
+ console.log("Nothing to clean: the worker has no checkouts or branches on this computer.");
4684
+ break;
4685
+ }
4686
+ const r = cleanRuns(pick, { home: CONFIG_DIR, alive, runInFlight, dropPushed: argv.includes("--pushed") });
4687
+ for (const x of r.removed)
4688
+ console.log(` ✓ ${x.line}`);
4689
+ for (const x of r.kept)
4690
+ console.log(` · ${x.line}`);
4691
+ if (r.kept.length)
4692
+ console.log(D(`\n Kept ones hold something that would be lost. Look in the folder, commit or remove what is there, then run this again.`));
4693
+ break;
4694
+ }
4695
+ if (sub && sub !== "list")
4696
+ die("Usage: pantheon runs [clean [<branch>] [--pushed]]");
4697
+ if (!trees.length) {
4698
+ console.log("The worker has no checkouts or branches on this computer.");
4699
+ break;
4700
+ }
4701
+ console.log(B(`The worker's checkouts and branches (${trees.length}):\n`));
4702
+ for (const l of runLines(trees, { alive, runInFlight }))
4703
+ console.log(` ${l}`);
4704
+ console.log(D(`\n pantheon runs clean removes the ones that hold nothing unsaved; your own checkout and branches are never touched.`));
4705
+ break;
4706
+ }
4651
4707
  case "panic": {
4652
4708
  console.error(`${B("PANIC — locking down this machine")}\n`);
4653
4709
  logChanges([{ at: Date.now(), setting: "worker", from: "running", to: "stopped, wake grants revoked (pantheon panic)", asked_by: askedByLabel(whoIsAsking()), outcome: "stopped" }]);
package/dist/client.js CHANGED
@@ -2,7 +2,7 @@ import WebSocket from "ws";
2
2
  import { clearRemoval, recordGone, recordRemoval, restateDeletedWhen, removalFor, removalHoldMs, removalRefusal, REMOVED_CHECK_MS, REMOVED_FIRST_MS, REMOVED_MAX_MS } from "./removed.js";
3
3
  import { adoptSpaceId, loadAll, rememberTeamRepos, updateMembershipToken } from "./config.js";
4
4
  import { honourClearedAuthority } from "./profile.js";
5
- import { inflightKey, loadContinued, markContinued, releasedKey, storedKey, unmarkContinued } from "./continued.js";
5
+ import { inflightKey, liveReadKey, loadContinued, markContinued, markContinuedAll, releasedKey, storedKey, unmarkContinued } from "./continued.js";
6
6
  import { isAnsweredId, markAnswered, nonceOf, unmarkAnswered } from "./nonces.js";
7
7
  import { signedRead } from "./reads.js";
8
8
  import { repoName } from "./repo-route.js";
@@ -1233,6 +1233,16 @@ export class PantheonClient {
1233
1233
  catch { }
1234
1234
  }
1235
1235
  relayNow() { return Date.now() + this.relaySkewMs; }
1236
+ markShown(acts) {
1237
+ const now = Math.round(this.relayNow());
1238
+ if (!this.session)
1239
+ return;
1240
+ const ids = acts.filter((a) => a.from !== this.cfg.member && (a.act === "ANSWER" || a.act === "DELIVERED") && now - a.ts <= 24 * 3_600_000).map((a) => `${a.id} ${now} ${this.session}`);
1241
+ try {
1242
+ markContinuedAll(liveReadKey(this.pinTeam), ids);
1243
+ }
1244
+ catch { }
1245
+ }
1236
1246
  relaySkewMs = 0;
1237
1247
  learnRelayNow(now) {
1238
1248
  if (typeof now === "number" && Number.isFinite(now) && now > 0)
package/dist/continued.js CHANGED
@@ -35,6 +35,40 @@ export function continuationDone(id, home) {
35
35
  return all.includes(id) && !all.includes(`held-cont:${id}`);
36
36
  }
37
37
  export const inflightKey = (team) => `${team} inflight`;
38
+ export const liveReadKey = (team) => `${team} live-read`;
39
+ export function liveReadAt(teams, id, home) {
40
+ const out = [];
41
+ for (const t of teams) {
42
+ for (const x of loadContinued(liveReadKey(t), home)) {
43
+ const m = /^(\S+) (\d+) (\S+)$/.exec(x);
44
+ if (m && m[1] === id)
45
+ out.push({ at: Number(m[2]), session: m[3] });
46
+ }
47
+ }
48
+ return out;
49
+ }
50
+ export function markContinuedAll(space, ids, home) {
51
+ if (!ids.length)
52
+ return;
53
+ try {
54
+ const p = continuedPath(home);
55
+ const write = () => {
56
+ const all = readAll(home);
57
+ const list = (all[space] ?? []).filter((x) => !ids.includes(x));
58
+ list.push(...ids);
59
+ all[space] = capped(list);
60
+ mkdirSync(dirname(p), { recursive: true });
61
+ writeWhole(p, JSON.stringify(all));
62
+ };
63
+ try {
64
+ withFileLock(p, write);
65
+ }
66
+ catch {
67
+ write();
68
+ }
69
+ }
70
+ catch { }
71
+ }
38
72
  export const releasedKey = (team) => `${team} released`;
39
73
  export const SEND_LIFETIME_MS = 2 * 60_000;
40
74
  export function ownReleases(before, now, snapAt = Date.now()) {
@@ -222,7 +222,7 @@ function needsUsername(cmd, deps, email, suggested, why) {
222
222
  export function unreachableWhy(why, env) {
223
223
  if (env.CODEX_SANDBOX_NETWORK_DISABLED !== "1")
224
224
  return why;
225
- return `${why || "no network"}. This shell has no network (Codex's sandbox): run the same command in a terminal of your own, or allow Codex network access`;
225
+ return `${why || "no network"}. This shell has no network (Codex's sandbox): ask the person to approve network access for this command — or, if Codex turned it down without asking them, to choose "Ask for approval" in Codex's permissions menu — then run the same command again; the code still works`;
226
226
  }
227
227
  export async function enterCode(o) {
228
228
  const { deps, cmd } = o;
@@ -91,10 +91,14 @@ export function forgetTeamTraces(f, m, home = CONFIG_DIR) {
91
91
  else {
92
92
  const repos = Object.values(f.bindings ?? {}).filter((b) => b.space === m.id && b.path).map((b) => b.path);
93
93
  try {
94
- const trees = removePantheonWorktrees(repos, [dir]);
94
+ const trees = removePantheonWorktrees(repos, [dir], home);
95
95
  left.push(...trees.left);
96
- rmSync(dir, { recursive: true, force: true });
97
- removed.push("its worker's scratch worktrees");
96
+ if (!trees.kept) {
97
+ rmSync(dir, { recursive: true, force: true });
98
+ removed.push("its worker's scratch worktrees");
99
+ }
100
+ else if (trees.removed.length)
101
+ removed.push("its worker's scratch worktrees that held nothing unsaved");
98
102
  }
99
103
  catch (e) {
100
104
  left.push(`${dir} (${e.message})`);
package/dist/git-safe.js CHANGED
@@ -221,7 +221,7 @@ function inspect(worktree, a, snapshot = false) {
221
221
  }
222
222
  function commonOf(project) {
223
223
  try {
224
- const out = execFileSync("git", [...gitHarden(), "rev-parse", "--git-common-dir"], { cwd: project, encoding: "utf8", windowsHide: true, stdio: ["ignore", "pipe", "ignore"], env: { ...process.env, GIT_CONFIG_NOSYSTEM: "1" }, timeout: 10_000 }).trim();
224
+ const out = execFileSync("git", ["-c", "core.fsmonitor=false", "-c", "protocol.file.allow=user", "rev-parse", "--git-common-dir"], { cwd: project, encoding: "utf8", windowsHide: true, stdio: ["ignore", "pipe", "ignore"], env: { ...process.env, GIT_CONFIG_NOSYSTEM: "1" }, timeout: 10_000 }).trim();
225
225
  return real(resolve(project, out));
226
226
  }
227
227
  catch {
package/dist/machine.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, rmSync, rmdirSync, statSync, writeFileSync } from "node:fs";
2
+ import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, rmSync, rmdirSync, statSync, writeFileSync } from "node:fs";
3
3
  import { homedir, hostname, networkInterfaces, platform } from "node:os";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
  import { CONFIG_DIR } from "./config.js";
6
+ import { cleanRuns, listRuns, realGit, runRecordAlive } from "./runs.js";
6
7
  import { borrowedHome, disableService, existingUnitPath, plistPath, serviceInstalled, serviceLogFile, stopWindowsHost, unitPath, unitPaths, uninstallService } from "./service.js";
7
8
  import { LEGACY_TASK_NAME, hostAlive, hostChildRunning, hostFiles, isHostKind, readHostState, recordedTaskName } from "./win-host.js";
8
9
  import { copilotMcpConfigFile, vsCodeUserDir, kiroMcpConfigFile, kiroDir, claudeUserEntryState, userEntry } from "./install.js";
@@ -818,43 +819,32 @@ export function ownWorkerPid(io = realProcScanIo()) {
818
819
  const w = pidFileWorker(io);
819
820
  return w?.confirmed ? w.pid : null;
820
821
  }
821
- export function removePantheonWorktrees(repos, roots, git = (repo, args) => execFileSync("git", ["-C", repo, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 30_000 })) {
822
+ export function removePantheonWorktrees(repos, roots, home = CONFIG_DIR, git, alive = (pid) => { try {
823
+ process.kill(pid, 0);
824
+ return true;
825
+ }
826
+ catch {
827
+ return false;
828
+ } }, record = true) {
822
829
  const removed = [], left = [];
823
- const real = (p) => { try {
824
- return realpathSync(p);
825
- }
826
- catch {
827
- return resolve(p);
828
- } };
829
- const rootsReal = roots.map(real);
830
- const under = (p) => { const pp = real(p); return rootsReal.some((rr) => pp === rr || pp.startsWith(rr + "/") || pp.startsWith(rr + "\\")); };
831
- for (const repo of [...new Set(repos.map((r) => resolve(r)))]) {
832
- let list;
830
+ const trees = listRuns(repos, roots, home, git).filter((t) => t.worktree);
831
+ const r = cleanRuns(trees, { home, ...(git ? { git } : {}), alive, dropPushed: true, record, runInFlight: runRecordAlive(home) });
832
+ const byRepo = new Map();
833
+ for (const x of r.removed)
834
+ if (x.tree.worktree)
835
+ byRepo.set(x.tree.repo, (byRepo.get(x.tree.repo) ?? 0) + 1);
836
+ for (const [repo, n] of byRepo)
837
+ removed.push(`${n} worktree${n === 1 ? "" : "s"} the worker made in ${repo}`);
838
+ for (const x of r.kept)
839
+ left.push(`${x.line} — it is at ${x.tree.worktree}; look, then remove it yourself: git -C ${x.tree.repo} worktree remove ${x.tree.worktree}`);
840
+ for (const repo of new Set(trees.map((t) => t.repo))) {
833
841
  try {
834
- list = git(repo, ["worktree", "list", "--porcelain"]);
835
- }
836
- catch {
837
- continue;
838
- }
839
- const trees = [...list.matchAll(/^worktree (.+)$/gm)].map((m) => m[1].trim()).filter(under);
840
- let n = 0;
841
- for (const t of trees) {
842
- try {
843
- git(repo, ["worktree", "remove", "--force", t]);
844
- n++;
845
- }
846
- catch (e) {
847
- left.push(`the worktree ${t} in ${repo} (${e.message.split("\n")[0]}) — git -C ${repo} worktree remove --force ${t}`);
848
- }
849
- }
850
- try {
851
- git(repo, ["worktree", "prune"]);
842
+ (git ?? realGit)(repo, ["worktree", "prune"]);
852
843
  }
853
844
  catch { }
854
- if (n)
855
- removed.push(`${n} worktree${n === 1 ? "" : "s"} the worker made in ${repo}`);
856
845
  }
857
- return { removed, left };
846
+ const kept = r.kept.length > 0;
847
+ return { removed, left, kept };
858
848
  }
859
849
  const MANAGED_LAUNCHERS = ["pantheon", "pantheon.cmd"];
860
850
  export function removeHomeLeftovers(home, keep, opts = {}) {
package/dist/mcp.js CHANGED
@@ -370,6 +370,8 @@ export async function runMcp() {
370
370
  : h.goal !== null && h.goal === o.goal && o.claimed_by?.session === client.session);
371
371
  const stillOwed = () => role !== "worker" ? client.myWork() : client.myWork().filter((o) => !o.owner.startsWith("human:") && !handed(o));
372
372
  const fmtAll = (acts) => {
373
+ if (role === "interactive")
374
+ client.markShown(acts);
373
375
  const flagged = acts.some((a) => assess(a.body).length > 0);
374
376
  const rubric = !rubricShown || flagged ? fenceRubric(acts.length) : fenceReminder(acts.length);
375
377
  rubricShown = true;
@@ -62,7 +62,7 @@ export function agentRequest(invite, o) {
62
62
  `On a Mac or Linux: download the installer and read it before running it — curl -fsSL ${base}/install.sh -o pantheon-install.sh — then run: sh pantheon-install.sh ${verb} ${flags}`,
63
63
  `On Windows: curl.exe -fsSL ${base}/install.ps1 -o pantheon-install.ps1, read it, then run: powershell -NoProfile -Command "Set-Item Env:PANTHEON_ARGS '${psVerb} ${flags}'; Get-Content -Raw pantheon-install.ps1 | iex"`,
64
64
  `It emails me a 6-digit code (it may land in spam). Ask me for it, then run the exact command it prints next (it names Pantheon by its full path, since this shell may not find \`pantheon\` yet), with the code in place of <the 6-digit code>.`,
65
- `If this shell can't go online (Codex keeps it offline unless I allow it, and may turn the request down by itself), don't retry or look for a way around it: give me the same commands to run in a terminal of my own, without the --email and --username part. There it asks me for my email, the code and my username itself. Then I quit and reopen you once.`,
65
+ `The download and the sign-in need network access. In Codex, ask me to approve running them with network access. If the request is turned down without asking me, or this shell still can't go online, don't look for a way around it: tell me to choose "Ask for approval" in Codex's permissions menu (under the message box), then try again when I say so.`,
66
66
  "What it changes, to tell me before running it:",
67
67
  ...INSTALL_CHANGES.slice(0, 3).map((c) => `- ${c}`),
68
68
  ].join("\n");
package/dist/runs.js ADDED
@@ -0,0 +1,337 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, join, resolve, sep } from "node:path";
4
+ import { adoptWorktree, adoptedCommon, checkWorktree, gitCallEnv } from "./git-safe.js";
5
+ export function indexFile(home) { return join(home, "worktrees", "index.json"); }
6
+ export function readIndex(home) {
7
+ try {
8
+ const j = JSON.parse(readFileSync(indexFile(home), "utf8"));
9
+ if (!j || typeof j !== "object" || Array.isArray(j))
10
+ return {};
11
+ const out = {};
12
+ for (const [k, v] of Object.entries(j)) {
13
+ const e = v;
14
+ if (e && typeof e.worktree === "string" && typeof e.repo === "string" && typeof e.branch === "string" && typeof e.request === "string")
15
+ out[k] = e;
16
+ }
17
+ return out;
18
+ }
19
+ catch {
20
+ return {};
21
+ }
22
+ }
23
+ export function updateIndex(home, change) {
24
+ try {
25
+ const ix = readIndex(home);
26
+ change(ix);
27
+ const f = indexFile(home);
28
+ mkdirSync(dirname(f), { recursive: true });
29
+ const tmp = `${f}.${process.pid}.tmp`;
30
+ writeFileSync(tmp, JSON.stringify(ix, null, 1) + "\n", { mode: 0o600 });
31
+ renameSync(tmp, f);
32
+ }
33
+ catch { }
34
+ }
35
+ const key = (p) => real(p);
36
+ function real(p) {
37
+ try {
38
+ return realpathSync(p);
39
+ }
40
+ catch {
41
+ const abs = resolve(p), parent = dirname(abs);
42
+ return parent === abs ? abs : join(real(parent), basename(abs));
43
+ }
44
+ }
45
+ export function recordRunStart(home, e, worker, now = Date.now()) {
46
+ updateIndex(home, (ix) => {
47
+ const k = key(e.worktree);
48
+ const had = ix[k];
49
+ const same = !!had && had.branch === e.branch;
50
+ ix[k] = { ...(same ? { base_ref: had.base_ref, base_sha: had.base_sha, asker: had.asker } : {}), ...e, worktree: k, created: same ? had.created : now, last_run: now, active: { worker: worker.pid, ...(worker.id ? { worker_id: worker.id } : {}), since: now } };
51
+ for (const f of ["base_ref", "base_sha", "asker"])
52
+ if (ix[k][f] === undefined)
53
+ delete ix[k][f];
54
+ });
55
+ }
56
+ export function recordRunEnd(home, worktree) {
57
+ updateIndex(home, (ix) => {
58
+ const k = key(worktree);
59
+ const e = ix[k];
60
+ if (!e)
61
+ return;
62
+ if (!existsSync(worktree)) {
63
+ delete ix[k];
64
+ return;
65
+ }
66
+ delete e.active;
67
+ });
68
+ }
69
+ const NO_HOOKS = process.platform === "win32" ? "NUL" : "/dev/null";
70
+ export const realGit = (cwd, args) => {
71
+ checkWorktree(cwd);
72
+ return execFileSync("git", ["-c", "core.fsmonitor=false", "-c", "protocol.file.allow=user", "-c", `core.hooksPath=${NO_HOOKS}`, ...args], {
73
+ cwd, encoding: "utf8", windowsHide: true, stdio: ["ignore", "pipe", "pipe"], env: gitCallEnv(args, process.env), timeout: 60_000, killSignal: "SIGKILL", maxBuffer: 1 << 28,
74
+ }).trim();
75
+ };
76
+ export function listRuns(repos, roots, home, git = realGit) {
77
+ const ix = readIndex(home);
78
+ const rootsReal = roots.map(real);
79
+ const under = (p) => { const pp = real(p); return rootsReal.some((r) => pp === r || pp.startsWith(r + sep) || pp.startsWith(r + "/")); };
80
+ const out = [];
81
+ const seen = new Set();
82
+ for (const repo of [...new Set(repos.map((r) => real(r)))]) {
83
+ if (seen.has(repo))
84
+ continue;
85
+ seen.add(repo);
86
+ let list;
87
+ try {
88
+ list = git(repo, ["worktree", "list", "--porcelain"]);
89
+ }
90
+ catch {
91
+ continue;
92
+ }
93
+ const checkedOut = new Set();
94
+ for (const block of list.split(/\n\s*\n/)) {
95
+ const wt = /^worktree (.+)$/m.exec(block)?.[1]?.trim();
96
+ const br = /^branch refs\/heads\/(.+)$/m.exec(block)?.[1]?.trim() ?? null;
97
+ if (br)
98
+ checkedOut.add(br);
99
+ if (!wt || !under(wt))
100
+ continue;
101
+ out.push({ repo, worktree: wt, branch: br, ...(ix[key(wt)] ? { entry: ix[key(wt)] } : {}) });
102
+ }
103
+ let branches = [];
104
+ try {
105
+ branches = git(repo, ["for-each-ref", "--format=%(refname:short)", "refs/heads/pantheon/"]).split("\n").map((s) => s.trim()).filter(Boolean);
106
+ }
107
+ catch { }
108
+ for (const b of branches) {
109
+ if (checkedOut.has(b))
110
+ continue;
111
+ const entry = Object.values(ix).find((e) => e.branch === b && real(e.repo) === repo);
112
+ out.push({ repo, worktree: "", branch: b, ...(entry ? { entry } : {}) });
113
+ }
114
+ }
115
+ return out;
116
+ }
117
+ const STATUS_ARGS = ["-c", "diff.ignoreSubmodules=all", "--no-optional-locks", "status", "--porcelain", "--ignore-submodules=all"];
118
+ export function runRecordAlive(home) {
119
+ try {
120
+ const r = JSON.parse(readFileSync(join(home, "worker-run.json"), "utf8"));
121
+ if (typeof r.pid !== "number" || !Number.isInteger(r.pid) || r.pid <= 1)
122
+ return false;
123
+ try {
124
+ process.kill(process.platform === "win32" ? r.pid : -r.pid, 0);
125
+ return true;
126
+ }
127
+ catch {
128
+ return false;
129
+ }
130
+ }
131
+ catch {
132
+ return false;
133
+ }
134
+ }
135
+ function ownConfig(worktree) {
136
+ try {
137
+ const m = /^gitdir:\s*(.+?)\s*$/m.exec(readFileSync(join(worktree, ".git"), "utf8"));
138
+ if (!m)
139
+ return false;
140
+ const body = readFileSync(join(resolve(worktree, m[1]), "config.worktree"), "utf8");
141
+ return !/^?[ \t\r\n]*$/.test(body);
142
+ }
143
+ catch {
144
+ return false;
145
+ }
146
+ }
147
+ export function stateOf(t, o) {
148
+ const git = o.git ?? realGit;
149
+ const s = { active: false, missing: false, unsafe: null, dirty: 0, unpushed: null, merged: false, keep: null };
150
+ const a = t.entry?.active;
151
+ s.active = !!a && o.alive(a.worker, a.worker_id);
152
+ if (t.worktree) {
153
+ let st;
154
+ try {
155
+ st = lstatSync(t.worktree);
156
+ }
157
+ catch {
158
+ st = null;
159
+ }
160
+ if (!st)
161
+ s.missing = true;
162
+ else {
163
+ let why = null;
164
+ if (adoptedCommon(t.worktree)) {
165
+ try {
166
+ checkWorktree(t.worktree);
167
+ }
168
+ catch (e) {
169
+ why = e.message;
170
+ }
171
+ }
172
+ else
173
+ why = adoptWorktree(t.repo, t.worktree)?.why ?? null;
174
+ if (why)
175
+ s.unsafe = why;
176
+ else if (ownConfig(t.worktree))
177
+ s.unsafe = "it has git settings of its own (config.worktree)";
178
+ else if (!s.active) {
179
+ try {
180
+ if (/^160000 /m.test(git(t.worktree, ["ls-files", "--stage"])))
181
+ s.unsafe = "it holds a submodule (a repo inside it)";
182
+ else
183
+ s.dirty = git(t.worktree, STATUS_ARGS).split("\n").filter(Boolean).length;
184
+ }
185
+ catch (e) {
186
+ s.unsafe = `git could not read it (${e.message.split("\n")[0]})`;
187
+ }
188
+ }
189
+ }
190
+ }
191
+ if (t.branch) {
192
+ const ref = `refs/heads/${t.branch}`;
193
+ try {
194
+ s.unpushed = Number(git(t.repo, ["rev-list", "--count", ref, "--not", "--exclude=pantheon/*", "--branches", "--remotes"])) || 0;
195
+ }
196
+ catch {
197
+ s.unpushed = null;
198
+ }
199
+ const recorded = t.entry?.base_ref && /^[A-Za-z0-9_][A-Za-z0-9._\/-]*$/.test(t.entry.base_ref) && !t.entry.base_ref.includes("..") ? t.entry.base_ref : null;
200
+ const base = recorded ?? (() => { try {
201
+ return git(t.repo, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"]);
202
+ }
203
+ catch {
204
+ return "";
205
+ } })();
206
+ try {
207
+ s.merged = Number(git(t.repo, ["rev-list", "--count", ref, "--not", "--exclude=pantheon/*", "--branches", ...(base ? [base] : [])])) === 0;
208
+ }
209
+ catch {
210
+ s.merged = false;
211
+ }
212
+ }
213
+ s.keep = s.active ? "a run is working in it"
214
+ : o.runInFlight ? "a run is in progress on this computer; try again when it ends"
215
+ : s.unsafe ? `it could not be checked safely: ${s.unsafe}`
216
+ : s.dirty ? `${s.dirty} file${s.dirty === 1 ? "" : "s"} changed and not committed`
217
+ : null;
218
+ return s;
219
+ }
220
+ function branchKeep(t, s, dropPushed) {
221
+ if (!t.branch || !t.branch.startsWith("pantheon/"))
222
+ return "not a branch Pantheon made";
223
+ if (s.merged)
224
+ return null;
225
+ if (s.unpushed === null)
226
+ return "its commits could not be counted";
227
+ if (s.unpushed > 0)
228
+ return `${s.unpushed} commit${s.unpushed === 1 ? "" : "s"} found nowhere else (not pushed, not in your branches)`;
229
+ return dropPushed ? null : "pushed, not merged yet";
230
+ }
231
+ export function cleanRuns(trees, o) {
232
+ const record = o.record !== false;
233
+ const git = o.git ?? realGit;
234
+ const res = { removed: [], kept: [] };
235
+ for (const t of trees) {
236
+ const what = describeTree(t);
237
+ const s = stateOf(t, { git, alive: o.alive, ...(o.runInFlight !== undefined ? { runInFlight: o.runInFlight } : {}) });
238
+ if (s.keep) {
239
+ res.kept.push({ tree: t, why: s.keep, line: `${what} — kept: ${s.keep}` });
240
+ continue;
241
+ }
242
+ const now = t.worktree ? readIndex(o.home)[key(t.worktree)]?.active : undefined;
243
+ if (now && o.alive(now.worker, now.worker_id)) {
244
+ res.kept.push({ tree: t, why: "a run is working in it", line: `${what} — kept: a run is working in it` });
245
+ continue;
246
+ }
247
+ let treeGone = false;
248
+ if (t.worktree) {
249
+ if (s.missing) {
250
+ try {
251
+ git(t.repo, ["worktree", "prune"]);
252
+ }
253
+ catch { }
254
+ }
255
+ else {
256
+ if (record)
257
+ keepLog(o.home, t);
258
+ try {
259
+ git(t.repo, ["worktree", "remove", "--", t.worktree]);
260
+ }
261
+ catch (e) {
262
+ const why = `git would not remove it (${e.message.split("\n").find((l) => /fatal|error/.test(l)) ?? "it refused"})`;
263
+ res.kept.push({ tree: t, why, line: `${what} — kept: ${why}` });
264
+ continue;
265
+ }
266
+ }
267
+ treeGone = true;
268
+ if (record)
269
+ updateIndex(o.home, (ix) => { delete ix[key(t.worktree)]; });
270
+ }
271
+ const bkeep = branchKeep(t, s, !!o.dropPushed);
272
+ let branchGone = false;
273
+ if (!bkeep) {
274
+ try {
275
+ git(t.repo, ["branch", "-D", "--", t.branch]);
276
+ branchGone = true;
277
+ }
278
+ catch { }
279
+ }
280
+ if (!treeGone && !branchGone) {
281
+ res.kept.push({ tree: t, why: bkeep ?? "git would not delete it", line: `${what} — kept: ${bkeep ?? "git would not delete it"}` });
282
+ continue;
283
+ }
284
+ if (record && branchGone && !t.worktree && t.entry)
285
+ updateIndex(o.home, (ix) => { delete ix[key(t.entry.worktree)]; });
286
+ res.removed.push({ tree: t, line: `${what} — ${[treeGone ? "checkout removed" : null, branchGone ? "branch deleted on this computer" : t.branch ? `branch kept (${bkeep})` : null].filter(Boolean).join("; ")}` });
287
+ }
288
+ return res;
289
+ }
290
+ function keepLog(home, t) {
291
+ try {
292
+ const f = join(t.worktree, ".pantheon-run.log");
293
+ const st = lstatSync(f);
294
+ if (!st.isFile())
295
+ return;
296
+ const dir = join(home, "worktrees", "logs");
297
+ mkdirSync(dir, { recursive: true });
298
+ copyFileSync(f, join(dir, `${(t.branch ?? basename(t.worktree)).replace(/[^A-Za-z0-9._-]+/g, "_")}.log`));
299
+ }
300
+ catch { }
301
+ }
302
+ export function describeTree(t) {
303
+ const e = t.entry;
304
+ const name = t.branch ?? basename(t.worktree);
305
+ if (!e)
306
+ return `${name} (${t.worktree ? "a checkout" : "a branch"} from before 0.37.2: request unknown)`;
307
+ const parts = [e.goal_title ? `"${e.goal_title}"` : e.goal ? `goal ${e.goal}` : null, e.asker ? `asked by ${e.asker}` : null].filter(Boolean);
308
+ return `${name}${parts.length ? ` (${parts.join(", ")})` : ""}`;
309
+ }
310
+ export function runLines(trees, o) {
311
+ const now = o.now ?? Date.now();
312
+ const lines = [];
313
+ for (const t of trees) {
314
+ const s = stateOf(t, o);
315
+ const e = t.entry;
316
+ const commits = !t.branch ? null
317
+ : s.unpushed === null ? "commits not counted"
318
+ : s.merged ? "nothing unmerged"
319
+ : s.unpushed ? `${s.unpushed} commit${s.unpushed === 1 ? "" : "s"} not pushed`
320
+ : "pushed, not merged";
321
+ const state = s.active ? "a run is working in it"
322
+ : s.unsafe ? `could not be checked: ${s.unsafe}`
323
+ : [t.worktree ? (s.missing ? "folder gone" : s.dirty ? `${s.dirty} uncommitted change${s.dirty === 1 ? "" : "s"}` : "no uncommitted changes") : "no checkout", commits].filter(Boolean).join(", ");
324
+ lines.push(describeTree(t));
325
+ lines.push(` ${t.worktree || t.repo}${e?.request ? ` request ${e.request}` : ""}${e ? ` last run ${ago(now - e.last_run)}` : ""}`);
326
+ lines.push(` ${state}`);
327
+ }
328
+ return lines;
329
+ }
330
+ function ago(ms) {
331
+ const m = Math.round(ms / 60_000);
332
+ if (m < 60)
333
+ return `${Math.max(0, m)} min ago`;
334
+ const h = Math.round(m / 60);
335
+ return h < 48 ? `${h} h ago` : `${Math.round(h / 24)} days ago`;
336
+ }
337
+ //# sourceMappingURL=runs.js.map
package/dist/worker.js CHANGED
@@ -29,7 +29,7 @@ import { removalWords, removedLine, removedNotice, takeTold } from "./removed.js
29
29
  import { agentHookStates, repairHook, repairNote } from "./notify.js";
30
30
  import { fence, assess } from "./untrusted.js";
31
31
  import { allowed, closeStartedRun, finishRun, recordRun, startRun } from "./spend.js";
32
- import { handledIn, loadContinued, markContinued, storedIn, storedKey, unmarkContinued, wakeAlertedKey, WORKER_MARK } from "./continued.js";
32
+ import { handledIn, liveReadAt, loadContinued, markContinued, storedIn, storedKey, unmarkContinued, wakeAlertedKey, WORKER_MARK } from "./continued.js";
33
33
  import { decisionAlertsOn, loadProfile, profileForTeam, reservedDecisionsNote, saveProfile, wakeMode } from "./profile.js";
34
34
  import { clip } from "./brief.js";
35
35
  import { composeWakeAsk, composeWorker } from "./notice.js";
@@ -44,6 +44,7 @@ import { CONFIG_DIR, CONFIG_PATH, configFor, findMembership, load as loadConfig,
44
44
  import { shellArg } from "./team-name.js";
45
45
  import { repoName, routeRequest, safeName } from "./repo-route.js";
46
46
  import { holdsRepo } from "./repo-find.js";
47
+ import { cleanRuns, listRuns, recordRunEnd, recordRunStart, runRecordAlive } from "./runs.js";
47
48
  import { FOLDER_SNAPSHOT_LIMITS, keepDrafts, removeSnapshot, shown, snapshotDrafts, snapshotRoot, sweepSnapshots, takeSnapshot } from "./folder-snapshot.js";
48
49
  import { gitActivity } from "./workdir.js";
49
50
  import { isContinuationFor, LIMITS, shouldDeferToHuman } from "./protocol.js";
@@ -358,7 +359,7 @@ export function settleWorktree(project, worktree, log) {
358
359
  let whole = false;
359
360
  try {
360
361
  git(worktree, "rev-parse", "--verify", "HEAD^{commit}");
361
- const status = git(worktree, "status", "--porcelain", "--untracked-files=no");
362
+ const status = git(worktree, "-c", "diff.ignoreSubmodules=all", "status", "--porcelain", "--untracked-files=no", "--ignore-submodules=all");
362
363
  whole = !status.split("\n").some((l) => /^(?:D.|.D)/.test(l));
363
364
  }
364
365
  catch {
@@ -507,6 +508,39 @@ export async function prepareWorktreeAsync(project, scratch, goal, log, branch =
507
508
  throw addFailed(project, p.result.worktree, why);
508
509
  return finishWorktree(project, p.result, log);
509
510
  }
511
+ export function settledReply(r, mine, seen, me) {
512
+ const answered = mine.find((a) => a.ref === r.id && a.id !== r.id && a.role !== "worker");
513
+ if (answered)
514
+ return `your side already replied to it (${answered.act} ${answered.id})`;
515
+ if (r.act === "ANSWER" && r.ref) {
516
+ const to = seen(r.ref);
517
+ if (to && to.from === me && ["ANSWER", "ACCEPT", "CLOSE", "DELIVERED"].includes(to.act) && isThanksOnly(r.body))
518
+ return "a short thank-you to your reply, with nothing asked in it";
519
+ }
520
+ return null;
521
+ }
522
+ const THANKS_WORDS = new Set(["thanks", "thank", "you", "thx", "ty", "tysm", "great", "perfect", "got", "it", "ok", "okay", "k", "cool", "nice",
523
+ "awesome", "sounds", "good", "noted", "all", "much", "so", "very", "a", "lot", "lots", "cheers", "appreciated", "appreciate", "that",
524
+ "really", "super", "brilliant", "excellent", "wonderful", "amazing", "makes", "sense", "understood", "received", "ack", "acknowledged"]);
525
+ const THANKS_EMOJI = new Set(["👍", "🙏", "🎉", "✅", "🙌", "👌", "❤", "💯"]);
526
+ export function isThanksOnly(body) {
527
+ const b = body.trim();
528
+ if (!b || b.length > 120 || b.includes("?"))
529
+ return false;
530
+ const emoji = [...b.replace(/[\u{1F3FB}-\u{1F3FF}\uFE0F\u200D]/gu, "").matchAll(/\p{Extended_Pictographic}/gu)].map((m) => m[0]);
531
+ if (emoji.some((e) => !THANKS_EMOJI.has(e)))
532
+ return false;
533
+ const words = b.toLowerCase().replace(/[\p{Extended_Pictographic}\u{1F3FB}-\u{1F3FF}\uFE0F\u200D]/gu, " ").split(/[^\p{L}\p{N}']+/u).filter(Boolean);
534
+ if (!words.length)
535
+ return emoji.length > 0;
536
+ return words.every((w) => THANKS_WORDS.has(w.replace(/'/g, "")));
537
+ }
538
+ export const CHECKOUT_SWEEP_MS = 30 * 60_000;
539
+ export const READ_ONLY_IDLE_MS = 2 * 60 * 60_000;
540
+ export function adhocGoal(o) {
541
+ const tail = (o.ref || o.id || "").replace(/[^A-Za-z0-9]/g, "").slice(-12);
542
+ return tail ? `req-${tail}` : "adhoc";
543
+ }
510
544
  export function branchName(space, goalId, title) {
511
545
  const slug = (title ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, "");
512
546
  return `pantheon/${branchSpace(space)}/${slug ? `${slug}-${goalId.slice(-4)}` : goalId}`;
@@ -2020,6 +2054,7 @@ export class Worker {
2020
2054
  unmarkContinued(k, act.id, this.opts.home);
2021
2055
  if (!this.contDone.has(`held-cont:${act.id}`))
2022
2056
  this.markDone(`held-cont:${act.id}`);
2057
+ this.forgetQueued(act.id);
2023
2058
  }
2024
2059
  makeRoomForHeld(id) {
2025
2060
  if (this.parkedNoSandboxConts.has(id) || this.parkedNoSandboxConts.size < HELD_CONTINUATIONS_MAX)
@@ -2582,6 +2617,8 @@ export class Worker {
2582
2617
  markDone(id) {
2583
2618
  this.contDone.add(id);
2584
2619
  markContinued(this.pinTeam, id, this.opts.home);
2620
+ if (this.contDone.has(`queued-cont:${id}`))
2621
+ this.forgetQueued(id);
2585
2622
  if (WORKER_MARK.test(id))
2586
2623
  this.keepOwn();
2587
2624
  }
@@ -3172,8 +3209,10 @@ export class Worker {
3172
3209
  await this.recoverInterruptedRun(client);
3173
3210
  await this.settleLeftHeld(client);
3174
3211
  this.reportStanding(true);
3175
- if (this.opts.continuations !== false)
3212
+ if (this.opts.continuations !== false) {
3176
3213
  await this.restoreHeldContinuations(client);
3214
+ await this.restoreQueuedContinuations();
3215
+ }
3177
3216
  this.writeState("watching", "waiting for work");
3178
3217
  while (!this.stopped) {
3179
3218
  const arrived = await client.next(5000);
@@ -3208,6 +3247,8 @@ export class Worker {
3208
3247
  this.refusedSaid = false;
3209
3248
  if (this.opts.continuations !== false)
3210
3249
  this.enqueueContinuations(client, arrived);
3250
+ if (this.queuedRestoreAt && Date.now() >= this.queuedRestoreAt)
3251
+ await this.restoreQueuedContinuations();
3211
3252
  this.writeCursor(client.seq);
3212
3253
  this.putHookBack();
3213
3254
  await this.maintain(client, arrived);
@@ -3221,6 +3262,7 @@ export class Worker {
3221
3262
  this.tickHold = { reason: "busy_elsewhere", detail: "another team's run is in progress on this machine" };
3222
3263
  continue;
3223
3264
  }
3265
+ this.sweepCheckouts(client);
3224
3266
  if (this.settlePendingRestore()) {
3225
3267
  this.writeState("held", `${this.pendingRestore.rels.join(", ")} could not be put back after a run`);
3226
3268
  continue;
@@ -3472,6 +3514,19 @@ export class Worker {
3472
3514
  this.requeueContinuation(continuation, 10_000);
3473
3515
  continue;
3474
3516
  }
3517
+ if (continuation && me?.work && !me.work.busy && me.work.idle_since !== null && this.liveThread(client, continuation)) {
3518
+ const asked = continuation.ref ? client.seenAct(continuation.ref)?.session : undefined;
3519
+ const open = new Set(me.sessions.map((s) => s.id));
3520
+ const shown = asked && open.has(asked) ? (this.opts.home !== undefined ? [this.opts.home, undefined] : [undefined])
3521
+ .flatMap((h) => liveReadAt(this.contKeys(), continuation.id, h)).filter((m) => m.session === asked) : [];
3522
+ if (shown.some((m) => me.work.idle_since >= m.at)) {
3523
+ this.markDone(continuation.id);
3524
+ this.forgetQueued(continuation.id);
3525
+ this.opts.log(`- not continuing from ${continuation.act} ${continuation.id}: the window that asked was shown it, and its turn ended after that`);
3526
+ this.writeState("watching", "waiting for work");
3527
+ continue;
3528
+ }
3529
+ }
3475
3530
  if (me && !me.work && hooksInstalled && !this.skipLogged.has("nosignal")) {
3476
3531
  this.skipLogged.add("nosignal");
3477
3532
  this.opts.log(` no activity signal from the relay, but the wake-up hook is installed here — reading this machine as idle until a turn is reported`);
@@ -4042,17 +4097,74 @@ export class Worker {
4042
4097
  }
4043
4098
  async runJob(client, o, persona, policy, makeBrief, requireReply, needsCommands = false, trigger = "", wokeBy = null) {
4044
4099
  const snaps = [];
4100
+ const track = { tree: null };
4101
+ let job;
4045
4102
  try {
4046
- return await this.runJobIn(client, o, persona, policy, makeBrief, requireReply, needsCommands, trigger, wokeBy, snaps);
4103
+ job = await this.runJobIn(client, o, persona, policy, makeBrief, requireReply, needsCommands, trigger, wokeBy, snaps, track);
4104
+ return job;
4047
4105
  }
4048
4106
  finally {
4049
4107
  for (const s of snaps)
4050
4108
  if (!s.kept)
4051
4109
  await removeSnapshot(s.dir);
4110
+ if (track.tree)
4111
+ this.afterRunIn(track.tree, job);
4112
+ }
4113
+ }
4114
+ afterRunIn(tree, _job) {
4115
+ try {
4116
+ recordRunEnd(this.stateDir(), tree.worktree);
4117
+ }
4118
+ catch (e) {
4119
+ this.opts.log(`! could not record the end of the run in ${tree.worktree}: ${e.message.split("\n")[0]}`);
4120
+ }
4121
+ }
4122
+ checkoutsSweptAt = Date.now() - CHECKOUT_SWEEP_MS + 2 * 60_000;
4123
+ sweepCheckouts(client) {
4124
+ if (Date.now() - this.checkoutsSweptAt < CHECKOUT_SWEEP_MS)
4125
+ return;
4126
+ this.checkoutsSweptAt = Date.now();
4127
+ try {
4128
+ const repos = this.workspaceList().filter((w) => w.kind === "repo").map((w) => w.path);
4129
+ if (!repos.length)
4130
+ return;
4131
+ const g = (cwd, args) => gitScan(cwd, args).trim();
4132
+ const ours = listRuns(repos, [this.opts.scratch], this.stateDir(), g).filter((t) => !!t.worktree && !!t.entry && t.entry.space === this.cfg.space);
4133
+ const closed = (t) => !!t.entry.goal && client.goals.get(t.entry.goal)?.state === "CLOSED";
4134
+ const idleUnchanged = (t) => {
4135
+ if (!t.branch || !t.entry.base_sha || Date.now() - t.entry.last_run < READ_ONLY_IDLE_MS)
4136
+ return false;
4137
+ try {
4138
+ return git(t.repo, "rev-parse", "--verify", "--quiet", ...revSep(), `refs/heads/${t.branch}^{commit}`) === t.entry.base_sha;
4139
+ }
4140
+ catch {
4141
+ return false;
4142
+ }
4143
+ };
4144
+ const alive = (pid, id) => sameProcess(pid, id);
4145
+ if (runRecordAlive(this.stateDir()))
4146
+ return;
4147
+ const done = ours.filter(closed);
4148
+ const quiet = ours.filter((t) => !closed(t) && idleUnchanged(t));
4149
+ const r1 = done.length ? cleanRuns(done, { home: this.stateDir(), git: g, alive, dropPushed: true }) : { removed: [], kept: [] };
4150
+ const r2 = quiet.length ? cleanRuns(quiet, { home: this.stateDir(), git: g, alive }) : { removed: [], kept: [] };
4151
+ for (const x of r1.removed)
4152
+ this.opts.log(` cleanup ${x.line} (its goal is closed)`);
4153
+ for (const x of r2.removed)
4154
+ this.opts.log(` cleanup ${x.line} (its runs changed nothing, and it was unused for two hours)`);
4155
+ for (const x of [...r1.kept, ...r2.kept])
4156
+ if (!this.keptSaid.has(x.tree.worktree)) {
4157
+ this.keptSaid.add(x.tree.worktree);
4158
+ this.opts.log(` cleanup ${x.line} — see pantheon runs`);
4159
+ }
4160
+ }
4161
+ catch (e) {
4162
+ this.opts.log(`! could not look at this worker's checkouts: ${e.message.split("\n")[0]}`);
4052
4163
  }
4053
4164
  }
4054
- async runJobIn(client, o, persona, policy, makeBrief, requireReply, needsCommands, trigger, wokeBy, snaps) {
4055
- const goal = o.goal ? (safeSegment(o.goal) ?? `goal-${createHash("sha256").update(o.goal).digest("hex").slice(0, 12)}`) : "adhoc";
4165
+ keptSaid = new Set();
4166
+ async runJobIn(client, o, persona, policy, makeBrief, requireReply, needsCommands, trigger, wokeBy, snaps, track = { tree: null }) {
4167
+ const goal = o.goal ? (safeSegment(o.goal) ?? `goal-${createHash("sha256").update(o.goal).digest("hex").slice(0, 12)}`) : adhocGoal(o);
4056
4168
  const gRec = this.client?.goals.get(goal);
4057
4169
  let branch = branchName(this.cfg.space, goal, gRec && (!client.signaturesExpected() || trusted(client.goalTrust(gRec).trust)) ? gRec.title : undefined);
4058
4170
  let worktree = join(this.opts.scratch, goal);
@@ -4182,8 +4294,19 @@ export class Worker {
4182
4294
  this.opts.log(` copy ${taken.snap.files.size} file${taken.snap.files.size === 1 ? "" : "s"} (${mb(taken.snap.bytes)}) of ${place.name} into ${worktree}${skippedNote(taken.snap.skipped)}`);
4183
4295
  }
4184
4296
  else {
4297
+ const runEntry = { worktree, repo: project, ...(place.origin ? { origin: place.origin } : {}), branch, space: this.cfg.space, goal: o.goal, ...(gRec?.title ? { goal_title: gRec.title } : {}), request: o.ref };
4298
+ const self = { pid: process.pid, ...(workerIdentity() ? { id: workerIdentity() } : {}) };
4299
+ if (isRepo(project)) {
4300
+ recordRunStart(this.stateDir(), runEntry, self);
4301
+ track.tree = { repo: project, worktree, branch, baseSha: "" };
4302
+ }
4185
4303
  try {
4186
4304
  ({ branch, worktree, baseRef, baseSha, tipSha, fetched } = await prepareWorktreeAsync(project, scratch, goal, this.opts.log, branch, this.repoBase(place.fp)));
4305
+ if (branch && baseSha) {
4306
+ const asker = (await this.actOf(client, o.ref).catch(() => null))?.from;
4307
+ recordRunStart(this.stateDir(), { ...runEntry, worktree, branch, ...(asker ? { asker } : {}), base_ref: baseRef, base_sha: baseSha }, self);
4308
+ track.tree = { repo: project, worktree, branch, baseSha };
4309
+ }
4187
4310
  }
4188
4311
  catch (e) {
4189
4312
  if (e instanceof WorktreeTampered)
@@ -5568,13 +5691,66 @@ export class Worker {
5568
5691
  continue;
5569
5692
  }
5570
5693
  this.contQueue.push({ act: r, notBefore: Date.now() });
5571
- if (this.contQueue.length > 20)
5572
- this.contQueue.shift();
5694
+ this.markQueued(r.id);
5695
+ if (this.contQueue.length > 20) {
5696
+ const gone = this.contQueue.shift();
5697
+ if (gone)
5698
+ this.forgetQueued(gone.act.id);
5699
+ }
5573
5700
  }
5574
5701
  }
5575
5702
  requeueContinuation(act, delayMs) {
5576
5703
  if (!this.contQueue.some((c) => c.act.id === act.id)) {
5577
5704
  this.contQueue.push({ act, notBefore: Date.now() + delayMs });
5705
+ this.markQueued(act.id);
5706
+ }
5707
+ }
5708
+ markQueued(actId) { if (!this.contDone.has(`queued-cont:${actId}`))
5709
+ this.markDone(`queued-cont:${actId}`); }
5710
+ forgetQueued(actId) {
5711
+ if (!this.contDone.has(`queued-cont:${actId}`))
5712
+ return;
5713
+ this.contDone.delete(`queued-cont:${actId}`);
5714
+ for (const k of this.contKeys())
5715
+ unmarkContinued(k, `queued-cont:${actId}`, this.opts.home);
5716
+ }
5717
+ queuedRestoreAt = 0;
5718
+ queuedRestoreTries = new Map();
5719
+ async restoreQueuedContinuations() {
5720
+ this.queuedRestoreAt = 0;
5721
+ this.loadContinued();
5722
+ for (const key of [...this.contDone]) {
5723
+ if (!key.startsWith("queued-cont:"))
5724
+ continue;
5725
+ const actId = key.slice("queued-cont:".length);
5726
+ if (this.contDone.has(actId) || this.contQueue.some((c) => c.act.id === actId)) {
5727
+ if (this.contDone.has(actId))
5728
+ this.forgetQueued(actId);
5729
+ continue;
5730
+ }
5731
+ if (this.contDone.has(`held-cont:${actId}`)) {
5732
+ this.forgetQueued(actId);
5733
+ continue;
5734
+ }
5735
+ const got = await this.fetchHeldAct(actId);
5736
+ if (got === "gone") {
5737
+ this.forgetQueued(actId);
5738
+ continue;
5739
+ }
5740
+ if (!got) {
5741
+ const n = (this.queuedRestoreTries.get(actId) ?? 0) + 1;
5742
+ this.queuedRestoreTries.set(actId, n);
5743
+ if (n < 5)
5744
+ this.queuedRestoreAt = Date.now() + 60_000;
5745
+ continue;
5746
+ }
5747
+ if (Date.now() - got.ts > CONTINUATION_HORIZON_MS) {
5748
+ this.forgetQueued(actId);
5749
+ this.markDone(actId);
5750
+ continue;
5751
+ }
5752
+ this.contQueue.push({ act: got, notBefore: Date.now() });
5753
+ this.opts.log(` queue ${got.act} ${actId} was waiting when the worker last stopped — queued again`);
5578
5754
  }
5579
5755
  }
5580
5756
  async tellStops(client) {
@@ -5637,10 +5813,24 @@ export class Worker {
5637
5813
  const r = c.act;
5638
5814
  const g = r.goal ? client.goals.get(r.goal) : undefined;
5639
5815
  this.contQueue = this.contQueue.filter((x) => x.act.id !== r.id);
5640
- if (this.contDone.has(r.id) || g?.state === "CLOSED")
5816
+ if (this.contDone.has(r.id)) {
5817
+ this.forgetQueued(r.id);
5818
+ continue;
5819
+ }
5820
+ if (g?.state === "CLOSED") {
5821
+ this.forgetQueued(r.id);
5641
5822
  continue;
5823
+ }
5642
5824
  if (stopFor(`cont:${r.id}`, this.opts.home)) {
5643
5825
  this.markDone(r.id);
5826
+ this.forgetQueued(r.id);
5827
+ continue;
5828
+ }
5829
+ const why = settledReply(r, client.mineSince(r.ts, r.goal), (id) => client.seenAct(id), this.cfg.member);
5830
+ if (why) {
5831
+ this.markDone(r.id);
5832
+ this.forgetQueued(r.id);
5833
+ this.opts.log(`- not continuing from ${r.act} ${r.id}: ${why}`);
5644
5834
  continue;
5645
5835
  }
5646
5836
  const sel = this.selectPersona(client, {
@@ -6115,6 +6305,12 @@ export class Worker {
6115
6305
  return false;
6116
6306
  return ref.sig?.role === "run" || ref.role === "worker";
6117
6307
  }
6308
+ liveThread(client, act) {
6309
+ const ref = act.ref ? client.seenAct(act.ref) : undefined;
6310
+ if (!ref || ref.from !== this.cfg.member)
6311
+ return false;
6312
+ return !(ref.sig?.role === "run" || ref.role === "worker");
6313
+ }
6118
6314
  pickupOpen(ref) {
6119
6315
  try {
6120
6316
  if (stopFor(ref, this.opts.home))
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@join-pantheon/cli",
3
- "version": "0.37.1",
3
+ "version": "0.37.2",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@join-pantheon/cli",
9
- "version": "0.37.1",
9
+ "version": "0.37.2",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@modelcontextprotocol/sdk": "^1.32.1",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@join-pantheon/cli",
3
- "version": "0.37.1",
3
+ "version": "0.37.2",
4
4
  "description": "Let your coding agent collaborate directly with your teammates' agents — ask, agree an interface, and deliver, without a human relaying messages.",
5
5
  "type": "module",
6
6
  "bin": {