@join-pantheon/cli 0.33.10 → 0.33.11-rc.1

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/worker.js CHANGED
@@ -4,7 +4,7 @@ import { chmodSync, lstatSync, mkdirSync, writeFileSync, existsSync, readdirSync
4
4
  import { homedir } from "node:os";
5
5
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
6
  import { absentDeniedPaths, describeKept, ownWorktreeConfig, detectClaudeFeatures, describeFeatures, ensureRunTmp, leavesSandboxMounts, NO_CLAUDE_FEATURES, removeSandboxLeftovers, runTmpDir } from "./claude-confine.js";
7
- import { snapshotHome, restoreHome, describeChange, trustWrite, askedHere } from "./home-guard.js";
7
+ import { snapshotHome, restoreHome, describeChange, trustWrite, askedHere, persistSnapshot, persistRestored, persistAttempt, loadPersistedGuard, clearPersistedGuard, CHANGES_LOG_FILE } from "./home-guard.js";
8
8
  import { PantheonClient } from "./client.js";
9
9
  import { createHash, randomBytes } from "node:crypto";
10
10
  import { newKeypair, signDelegate } from "./identity.js";
@@ -19,8 +19,10 @@ import { headlessSpawn, materializeSpawnFiles, chooseAgent, agentById, describeC
19
19
  import { activeOutages, detectOutage, earliest, whenAgain } from "./agent-outage.js";
20
20
  import { agentSpawn, CmdLineUnsafe } from "./which.js";
21
21
  import { VERSION } from "./version.js";
22
- import { applyAnswer, CAPABILITY_ARGS, CARRY_REASON, carryOverWakers, dropLedgerGrants, hasWakeOnce, isApprovedWaker, mayAskWake, takeWakeOnce, OLD_RELAY_WAKE, relayKnowsAdmitters, loadPolicy, mayAsk, needsSelfUpgrade, parseGrantAnswer, recordAsk, savePolicy, useGrant, WOKEN_RUN_ENV, takeTeamFlagOnYes, unsandboxedAllowed, policyPath, isNewer, RUN_MINUTES, effectiveRunMinutes, effectiveIdleSeconds, readinessRecheckPath, policyHome, describeRunMinutes, parseRunMinutes, } from "./worker-policy.js";
22
+ import { applyAnswer, CAPABILITY_ARGS, CARRY_REASON, carryOverWakers, dropLedgerGrants, hasWakeOnce, isApprovedWaker, mayAskWake, takeWakeOnce, OLD_RELAY_WAKE, relayKnowsAdmitters, loadPolicy, mayAsk, needsSelfUpgrade, parseGrantAnswer, recordAsk, savePolicy, useGrant, WOKEN_RUN_ENV, takeTeamFlagOnYes, unsandboxedAllowed, policyPath, isNewer, RUN_MINUTES, effectiveRunMinutes, effectiveIdleSeconds, readinessRecheckPath, policyHome, describeRunMinutes, parseRunMinutes, currentMode, } from "./worker-policy.js";
23
23
  import { readinessAlerts } from "./readiness-alert.js";
24
+ import { clearDeclined, markDeclined, personsOwnThread, pruneDeclined } from "./declined.js";
25
+ import { loadRunStops, markStopTold, pruneRunStops, requestRunStop, stopFor, stopNote } from "./run-control.js";
24
26
  import { runtimeNodeVersion } from "./managed.js";
25
27
  import { removalWords, removedLine, removedNotice, takeTold } from "./removed.js";
26
28
  import { agentHookStates, repairHook, repairNote } from "./notify.js";
@@ -847,6 +849,97 @@ DO THIS
847
849
  There is no human in this session. Do not ask for approval; you will not get an answer.
848
850
  Act, reply if a reply is owed, then finish.`;
849
851
  }
852
+ export function autopilotBrief(who) {
853
+ return `
854
+
855
+ AUTOPILOT — ${who} chose to have you finish teammates' requests on your own.
856
+ - Complete what was asked and answer whoever asked, in this run. Do not hand it back to ${who},
857
+ and do not ask ${who} first.
858
+ - Escalate to ${who} only when you genuinely cannot go on without them: money, scope, something
859
+ irreversible, or one of their stated red lines. A decision area a teammate reserved still goes
860
+ to that teammate, as always.
861
+ - Any playbook from ${who} above still applies.`;
862
+ }
863
+ export async function checkoutNote(project, baseRef, read = (a) => gitOut(project, a)) {
864
+ const safe = async (args) => { try {
865
+ return await read(args);
866
+ }
867
+ catch {
868
+ return null;
869
+ } };
870
+ const branch = (await safe(["rev-parse", "--abbrev-ref", "HEAD"])) ?? "";
871
+ const listed = await safe(["config", "-z", "--name-only", "--list"]);
872
+ const drivers = [...new Set((listed ?? "").split("\0").map((k) => k.trim()).filter((k) => /^filter\./i.test(k))
873
+ .map((k) => /^filter\.([\s\S]+)\.[A-Za-z]+$/i.exec(k)?.[1]).filter((n) => n !== undefined))];
874
+ const switchable = (listed ?? "").length < 90_000 && drivers.length <= 64 && drivers.every((d) => !/[=\n\0]/.test(d));
875
+ const off = drivers.flatMap((d) => ["-c", `filter.${d}.clean=`, "-c", `filter.${d}.smudge=`, "-c", `filter.${d}.process=`, "-c", `filter.${d}.required=false`]);
876
+ const changed = listed === null || !switchable ? []
877
+ : ((await safe([...off, "diff-index", "--name-only", "--no-ext-diff", "--no-textconv", "HEAD"])) ?? "").split("\n").filter(Boolean);
878
+ const untracked = ((await safe(["ls-files", "--others", "--exclude-standard"])) ?? "").split("\n").filter(Boolean);
879
+ const files = [...new Set([...changed, ...untracked])];
880
+ const commits = baseRef && branch && branch !== "HEAD"
881
+ ? ((await safe(["log", "--oneline", "--no-decorate", "-n", "11", `${baseRef}..HEAD`])) ?? "").split("\n").filter(Boolean) : [];
882
+ if (!files.length && !commits.length)
883
+ return "";
884
+ const line = (x, n = 120) => x.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, " ").slice(0, n);
885
+ const cap = (xs, n) => (xs.length > n ? [...xs.slice(0, n), `… and ${xs.length - n} more`] : xs);
886
+ const on = branch && branch !== "HEAD" ? `on branch ${line(branch, 80)}` : "on a detached HEAD";
887
+ const lines = [
888
+ "",
889
+ "",
890
+ "WHAT YOUR HUMAN IS IN THE MIDDLE OF (their own checkout, read just now, on this machine)",
891
+ files.length
892
+ ? ` Your human currently has uncommitted changes in ${cap(files.map((f) => line(f)), 30).join(", ")} ${on}.`
893
+ : ` Your human is ${on}.`,
894
+ ...(commits.length ? [` Commits on that branch that ${line(baseRef, 80)} does not have:`, ...commits.slice(0, 10).map((c) => ` ${line(c)}`), ...(commits.length > 10 ? [" … and more"] : [])] : []),
895
+ " If this request is the same work, don't build a parallel version: ESCALATE one question to your",
896
+ " human — leave it to them, or do it separately? — and stop. If it is different work, carry on here",
897
+ " and never touch their checkout. These names are your human's private work in progress: never",
898
+ " repeat a file or branch name from this list to the teammate who asked.",
899
+ ];
900
+ return lines.join("\n");
901
+ }
902
+ export const PICKUP_TAG = "pantheon_pickup";
903
+ export const PICKUP_WINDOW_MS = 30_000;
904
+ export const PICKUP_COALESCE_MS = 2_000;
905
+ export const PICKUP_MIN_GAP_MS = 15_000;
906
+ export function composePickup(o) {
907
+ return {
908
+ kind: "pickup",
909
+ who: `Your agent · for ${o.asker}`,
910
+ heading: `Your agent started: ${o.title}`.slice(0, 120),
911
+ context: o.space,
912
+ body: `Take over to do it yourself, or Stop — ${o.asker} is told either way.`,
913
+ ttl: 8,
914
+ sound: false,
915
+ run: { ref: o.ref },
916
+ space: o.space,
917
+ tag: PICKUP_TAG,
918
+ };
919
+ }
920
+ export function whenWords(at, now = Date.now()) {
921
+ const t = new Date(at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
922
+ const day = (x) => { const d = new Date(x); return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`; };
923
+ if (day(at) === day(now))
924
+ return t;
925
+ if (day(at) === day(now + 86_400_000))
926
+ return `tomorrow ${t}`;
927
+ return `${new Date(at).toLocaleDateString([], { weekday: "short" })} ${t}`;
928
+ }
929
+ export function composePickups(items, space) {
930
+ return {
931
+ kind: "pickup",
932
+ who: "Your agent",
933
+ heading: `Your agent has ${items.length} request${items.length === 1 ? "" : "s"} queued`,
934
+ context: space,
935
+ body: items.slice(0, 5).map((i) => `• ${i.title} (from ${i.asker})`).join("\n") + (items.length > 5 ? `\n… and ${items.length - 5} more` : ""),
936
+ ttl: 12,
937
+ sound: false,
938
+ review: { what: "board" },
939
+ space,
940
+ tag: PICKUP_TAG,
941
+ };
942
+ }
850
943
  export const TASK_POINTER = "Your task for this run is in the file .pantheon-task.md in the current directory. Read that file first and follow it: it is the whole brief.";
851
944
  let fleetLock = null;
852
945
  export const RUN_TIMEOUT_MS = RUN_MINUTES.default * 60_000;
@@ -947,11 +1040,132 @@ function installRunReaper() {
947
1040
  reaperInstalled = true;
948
1041
  const reap = () => { for (const pid of liveRuns)
949
1042
  killRunTree(pid); };
950
- process.on("exit", reap);
951
- for (const sig of ["SIGTERM", "SIGHUP"]) {
952
- process.on(sig, () => { reap(); process.exit(sig === "SIGTERM" ? 143 : 129); });
1043
+ process.on("exit", () => { reap(); restorePendingGuards(); });
1044
+ for (const [sig, code] of [["SIGTERM", 143], ["SIGHUP", 129], ["SIGINT", 130]]) {
1045
+ process.on(sig, () => { reap(); restorePendingGuards(); process.exit(code); });
953
1046
  }
954
1047
  }
1048
+ const pendingGuards = new Map();
1049
+ function restorePendingGuards() {
1050
+ for (const [home, g] of [...pendingGuards]) {
1051
+ pendingGuards.delete(home);
1052
+ try {
1053
+ const said = putBackList(restoreHome(g.snap));
1054
+ persistRestored(home, said, { workerId: workerIdentity() });
1055
+ try {
1056
+ g.log(`! the worker is going mid-run — Pantheon's own files put back first${said.length ? `: ${said.join(" ")}` : " (nothing had changed)"}`);
1057
+ }
1058
+ catch { }
1059
+ }
1060
+ catch { }
1061
+ }
1062
+ }
1063
+ export function processIdentity(pid) {
1064
+ if (!Number.isInteger(pid) || pid <= 0)
1065
+ return null;
1066
+ try {
1067
+ if (process.platform === "linux") {
1068
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
1069
+ const start = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
1070
+ const boot = readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
1071
+ return start && /^\d+$/.test(start) && boot ? `linux:${boot}:${start}` : null;
1072
+ }
1073
+ if (process.platform === "darwin") {
1074
+ const out = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 3_000, env: { ...process.env, LC_ALL: "C", TZ: "UTC" } }).trim().replace(/\s+/g, " ");
1075
+ return out ? `darwin:${out}` : null;
1076
+ }
1077
+ }
1078
+ catch { }
1079
+ return null;
1080
+ }
1081
+ let ownIdentity;
1082
+ export function workerIdentity() {
1083
+ if (ownIdentity === undefined)
1084
+ ownIdentity = processIdentity(process.pid);
1085
+ return ownIdentity;
1086
+ }
1087
+ export function sameProcess(pid, id, read = processIdentity) {
1088
+ if (!Number.isInteger(pid) || pid <= 1 || !pidAlive(pid))
1089
+ return false;
1090
+ if (!id)
1091
+ return true;
1092
+ const now = read(pid);
1093
+ return now === null || now === id;
1094
+ }
1095
+ export function putBackList(changes) {
1096
+ return changes.filter((c) => c.what !== "reported" && !c.quiet).map((c) => `${c.rel}${c.keys.length ? ` (${c.keys.join(", ")})` : ""}`);
1097
+ }
1098
+ export function putBackSaid(list) {
1099
+ return `Put back ${list.length === 1 ? list[0] : `${list.slice(0, -1).join("; ")} and ${list[list.length - 1]}`} that a teammate's request changed during its run.`;
1100
+ }
1101
+ export const GUARD_RESTORE_TRIES = 3;
1102
+ const GUARD_STALE_MARGIN_MS = 10 * 60_000;
1103
+ export function recoverInterruptedGuard(home, now = Date.now(), restore = restoreHome) {
1104
+ const g = loadPersistedGuard(home);
1105
+ if (!g)
1106
+ return { outcome: "none" };
1107
+ if (sameProcess(g.worker, g.workerId))
1108
+ return { outcome: "live" };
1109
+ try {
1110
+ const r = JSON.parse(readFileSync(join(home, RUN_RECORD), "utf8"));
1111
+ if (r && r.worker === g.worker && Number.isInteger(r.pid) && r.pid > 1 && typeof r.at === "number" && now - r.at <= recordLimitMs(r) && recordedRunAlive(r.pid))
1112
+ killRunTree(r.pid);
1113
+ }
1114
+ catch { }
1115
+ if (!g.snapshot) {
1116
+ clearPersistedGuard(home);
1117
+ return { outcome: "restored", said: g.restored ?? [] };
1118
+ }
1119
+ if (g.at > now + 60_000 || now - g.at > recordLimitMs({ limit: g.limit }) + GUARD_STALE_MARGIN_MS) {
1120
+ clearPersistedGuard(home);
1121
+ return { outcome: "stale", at: g.at };
1122
+ }
1123
+ const lease = readRunLease(join(home, RUN_SLOT));
1124
+ const wentAt = lease && lease.pid === g.worker && typeof lease.at === "number" && Number.isFinite(lease.at) ? lease.at + RUN_LEASE_RENEW_MS : null;
1125
+ if (wentAt !== null)
1126
+ try {
1127
+ const mine = readFileSync(join(home, CHANGES_LOG_FILE), "utf8").split("\n").some((l) => {
1128
+ try {
1129
+ const e = JSON.parse(l);
1130
+ return typeof e.at === "number" && e.at > Math.max(g.at, wentAt) && e.setting !== "first-setup" && e.asked_by === "terminal" && (e.outcome === "applied" || e.outcome === "approved" || e.outcome === "kept");
1131
+ }
1132
+ catch {
1133
+ return false;
1134
+ }
1135
+ });
1136
+ if (mine) {
1137
+ clearPersistedGuard(home);
1138
+ return { outcome: "person changed", at: g.at };
1139
+ }
1140
+ }
1141
+ catch { }
1142
+ try {
1143
+ const said = putBackList(restore(g.snapshot));
1144
+ clearPersistedGuard(home);
1145
+ return { outcome: "restored", said };
1146
+ }
1147
+ catch (e) {
1148
+ const attempts = g.attempts + 1;
1149
+ const dropped = attempts >= GUARD_RESTORE_TRIES;
1150
+ if (dropped)
1151
+ clearPersistedGuard(home);
1152
+ else
1153
+ persistAttempt(home, attempts);
1154
+ return { outcome: "failed", attempts, why: e.message.split("\n")[0] ?? "", dropped };
1155
+ }
1156
+ }
1157
+ export function guardHeld(home, now = Date.now()) {
1158
+ const g = loadPersistedGuard(home);
1159
+ if (!g?.snapshot || g.at > now + 60_000 || now - g.at > recordLimitMs({ limit: g.limit }) + GUARD_STALE_MARGIN_MS)
1160
+ return false;
1161
+ return sameProcess(g.worker, g.workerId);
1162
+ }
1163
+ export function guardMinutesLeft(home, now = Date.now()) {
1164
+ const g = loadPersistedGuard(home);
1165
+ if (!g?.snapshot || !g.limit)
1166
+ return null;
1167
+ return Math.min(Math.round(recordLimitMs({ limit: g.limit }) / 60_000), Math.max(1, Math.round((g.at + g.limit - now) / 60_000)));
1168
+ }
955
1169
  export const RUN_RECORD = "worker-run.json";
956
1170
  function writeRunRecord(dir, r) {
957
1171
  try {
@@ -979,7 +1193,7 @@ export function killRecordedRun(dir, now = Date.now()) {
979
1193
  return null;
980
1194
  }
981
1195
  rmSync(f, { force: true });
982
- if (!r || !Number.isInteger(r.pid) || typeof r.at !== "number" || !Number.isFinite(r.at) || r.at > now + 60_000)
1196
+ if (!r || !Number.isInteger(r.pid) || r.pid <= 1 || typeof r.at !== "number" || !Number.isFinite(r.at) || r.at > now + 60_000)
983
1197
  return null;
984
1198
  if (now - r.at > recordLimitMs(r))
985
1199
  return null;
@@ -997,7 +1211,20 @@ export function recordedRunAlive(pid, os = process.platform, probe = (p) => { pr
997
1211
  return false;
998
1212
  }
999
1213
  }
1000
- export function runInFlight(dir, now = Date.now()) {
1214
+ export const RESTORE_WINDOW_MS = 2 * 60_000;
1215
+ export function parentOf(pid) {
1216
+ if (process.platform === "win32")
1217
+ return undefined;
1218
+ try {
1219
+ const out = execFileSync("ps", ["-o", "ppid=", "-p", String(pid)], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 3_000 }).trim();
1220
+ const n = Number(out);
1221
+ return Number.isInteger(n) && n > 0 ? n : null;
1222
+ }
1223
+ catch (e) {
1224
+ return e.code === "ENOENT" ? undefined : null;
1225
+ }
1226
+ }
1227
+ export function runInFlight(dir, now = Date.now(), o = {}) {
1001
1228
  let r;
1002
1229
  try {
1003
1230
  r = JSON.parse(readFileSync(join(dir, RUN_RECORD), "utf8"));
@@ -1005,13 +1232,38 @@ export function runInFlight(dir, now = Date.now()) {
1005
1232
  catch {
1006
1233
  return null;
1007
1234
  }
1008
- if (!r || !Number.isInteger(r.pid) || typeof r.at !== "number" || !Number.isFinite(r.at))
1235
+ if (!r || !Number.isInteger(r.pid) || r.pid <= 1 || typeof r.at !== "number" || !Number.isFinite(r.at) || r.at > now + 60_000)
1009
1236
  return null;
1010
- if (now - r.at > recordLimitMs(r))
1237
+ if (r.restored === true)
1011
1238
  return null;
1012
- if (!recordedRunAlive(r.pid))
1239
+ if (!Number.isInteger(r.worker) || !sameProcess(r.worker, typeof r.worker_id === "string" ? r.worker_id : undefined))
1013
1240
  return null;
1014
- return { pid: r.pid, at: r.at };
1241
+ const run = { pid: r.pid, at: r.at, ...(typeof r.ref === "string" ? { ref: r.ref } : {}) };
1242
+ if (recordedRunAlive(r.pid)) {
1243
+ const parent = (o.parentOf ?? parentOf)(r.pid);
1244
+ if (parent === r.worker)
1245
+ return run;
1246
+ if (parent === undefined && now - r.at <= recordLimitMs(r))
1247
+ return run;
1248
+ }
1249
+ if (typeof r.exited_at === "number" && Number.isFinite(r.exited_at) && r.exited_at >= r.at && r.exited_at <= now + 60_000 && now - r.exited_at < RESTORE_WINDOW_MS)
1250
+ return run;
1251
+ return null;
1252
+ }
1253
+ export function runMinutesLeft(dir, now = Date.now()) {
1254
+ if (!runInFlight(dir, now))
1255
+ return null;
1256
+ try {
1257
+ const r = JSON.parse(readFileSync(join(dir, RUN_RECORD), "utf8"));
1258
+ if (typeof r.exited_at === "number")
1259
+ return 1;
1260
+ if (typeof r.limit !== "number" || !Number.isFinite(r.limit))
1261
+ return null;
1262
+ return Math.min(Math.round(recordLimitMs(r) / 60_000), Math.max(1, Math.round((r.at + r.limit - now) / 60_000)));
1263
+ }
1264
+ catch {
1265
+ return null;
1266
+ }
1015
1267
  }
1016
1268
  const HELD_BACKOFF_MS = 60_000;
1017
1269
  const HELD_BACKOFF_MAX_MS = 30 * 60_000;
@@ -1175,8 +1427,11 @@ export class Worker {
1175
1427
  detail = "can't take requests yet";
1176
1428
  more = { ...(this.readiness.code ? { reason: this.readiness.pinned ? (this.readiness.code === "kiro_only" ? "pinned_kiro" : this.readiness.code === "unsandboxed_off" ? "pinned_unsandboxed" : this.readiness.code) : this.readiness.code } : {}) };
1177
1429
  }
1178
- this.lastReport = { state, ...(detail ? { detail } : {}), ...(until ? { until } : {}), ...more, at: Date.now() };
1179
- this.client?.reportWorkerState(state, detail, until, this.idleMs(), more);
1430
+ const mode = this.mode();
1431
+ this.reportedMode = mode;
1432
+ const { mode: _m, ...rest } = more;
1433
+ this.lastReport = { state, ...(detail ? { detail } : {}), ...(until ? { until } : {}), ...rest, at: Date.now() };
1434
+ this.client?.reportWorkerState(state, detail, until, mode === "autopilot" ? 0 : this.idleMs(), { ...rest, mode });
1180
1435
  }
1181
1436
  tickHold = null;
1182
1437
  readiness = null;
@@ -1289,7 +1544,8 @@ export class Worker {
1289
1544
  }
1290
1545
  const holdOver = last?.state === "holding" && (held === null || (!!last.until && last.until <= now));
1291
1546
  const flipped = !!last && ((last.state === "unavailable") !== (this.readiness ? !this.readiness.ok : false));
1292
- if (first || stale || holdOver || flipped) {
1547
+ const modeChanged = this.reportedMode !== null && this.reportedMode !== this.mode();
1548
+ if (first || stale || holdOver || flipped || modeChanged) {
1293
1549
  if (!last || holdOver || last.state !== "holding")
1294
1550
  this.report("idle");
1295
1551
  else
@@ -2056,6 +2312,7 @@ export class Worker {
2056
2312
  ...(fromSeq ? { fromSeq } : {}),
2057
2313
  persistToken: (space, oldToken, newToken) => { updateMembershipToken(space, oldToken, newToken); trustWrite(CONFIG_PATH); },
2058
2314
  });
2315
+ this.recoverGuard();
2059
2316
  await client.connect();
2060
2317
  this.client = client;
2061
2318
  try {
@@ -2177,7 +2434,8 @@ export class Worker {
2177
2434
  this.brokenSaid = "";
2178
2435
  const me = client.roster.find((m) => m.id === this.cfg.member);
2179
2436
  const liveInteractive = me?.sessions.some((s) => s.role === "interactive") ?? false;
2180
- const grace = liveInteractive ? this.opts.graceMs : Math.min(this.opts.graceMs, 2_000);
2437
+ const autopilot = this.mode() === "autopilot";
2438
+ const grace = liveInteractive && !autopilot ? this.opts.graceMs : Math.min(this.opts.graceMs, 2_000);
2181
2439
  const hooksInstalled = this.opts.hooksInstalled ?? this.hooksInstalledHere();
2182
2440
  if (me?.work?.busy)
2183
2441
  this.busyObservedSince ??= Date.now();
@@ -2193,6 +2451,7 @@ export class Worker {
2193
2451
  this.carryWakers(client);
2194
2452
  }
2195
2453
  await this.tellWakeNo(client);
2454
+ await this.tellStops(client);
2196
2455
  this.sayKeyChanges(client);
2197
2456
  const aged = client
2198
2457
  .myWork()
@@ -2202,11 +2461,13 @@ export class Worker {
2202
2461
  return true; if (t > Date.now()) {
2203
2462
  if (!this.tickHold || (this.tickHold.reason === "outage" && (this.tickHold.until ?? Infinity) > t))
2204
2463
  this.tickHold = { reason: "outage", until: t, detail: "its agents are out for now" };
2464
+ this.decline(o.ref, "your agents are out for now");
2205
2465
  return false;
2206
2466
  } this.outageHold.delete(o.id); return true; })
2207
2467
  .filter((o) => {
2208
2468
  if (this.failuresOf(o.id) < 2)
2209
2469
  return true;
2470
+ this.decline(o.ref, "its run failed twice on this computer");
2210
2471
  if (!this.skipLogged.has(`parked:${o.id}`)) {
2211
2472
  this.skipLogged.add(`parked:${o.id}`);
2212
2473
  this.opts.log(`- parking ${o.kind} ${o.id}: its run failed in a way another run would repeat — it stays owed for a live session or your human (see the last .pantheon-run.log)`);
@@ -2216,55 +2477,98 @@ export class Worker {
2216
2477
  let candidate;
2217
2478
  let candidateAct = null;
2218
2479
  let persona;
2219
- for (const o of aged) {
2220
- this.loadContinued();
2221
- if (this.contDone.has(`handled:${o.ref}`) || this.continuedHas(`handled:${o.ref}`)) {
2222
- if (!this.skipLogged.has(`handled:${o.id}`)) {
2223
- this.skipLogged.add(`handled:${o.id}`);
2224
- this.opts.log(`- not taking ${owedLabel(o.kind)} ${o.id}: this machine already answered the request it points at (${o.ref})`);
2480
+ const presentNow = this.mode() === "autopilot" && !!me && shouldDeferToHuman(me.sessions, me.work, {
2481
+ idleMs: this.idleMs(), busyTtlMs: this.opts.busyTtlMs ?? LIMITS.activityBusyTtlMs, busySince: this.busyObservedSince, hooksInstalled,
2482
+ });
2483
+ const pick = async (start) => {
2484
+ for (let i = start; i < aged.length; i++) {
2485
+ const o = aged[i];
2486
+ this.loadContinued();
2487
+ if (this.contDone.has(`handled:${o.ref}`) || this.continuedHas(`handled:${o.ref}`)) {
2488
+ if (!this.skipLogged.has(`handled:${o.id}`)) {
2489
+ this.skipLogged.add(`handled:${o.id}`);
2490
+ this.opts.log(`- not taking ${owedLabel(o.kind)} ${o.id}: this machine already answered the request it points at (${o.ref})`);
2491
+ }
2492
+ continue;
2225
2493
  }
2226
- continue;
2227
- }
2228
- const reqAct = (client.seenAct(o.ref) ?? await this.fetchActById(o.ref));
2229
- const distrust = await this.requestTrust(client, o, reqAct);
2230
- if (distrust) {
2231
- await this.reportDistrust(client, o.id, o.ref, distrust);
2232
- continue;
2233
- }
2234
- const refusedWake = await this.wakeRefusal(client, o.ref, reqAct ? { from: reqAct.from, role: reqAct.sig?.role === "run" ? "worker" : reqAct.role ?? null } : undefined);
2235
- if (refusedWake) {
2236
- if (!this.skipLogged.has(`wake:${o.id}`)) {
2237
- this.skipLogged.add(`wake:${o.id}`);
2238
- this.opts.log(`- not taking ${owedLabel(o.kind)} ${o.id}: ${refusedWake.why} — it waits for a live session`);
2494
+ {
2495
+ const st = stopFor(o.ref, this.opts.home);
2496
+ if (st) {
2497
+ if (!this.skipLogged.has(`stopped:${o.id}`)) {
2498
+ this.skipLogged.add(`stopped:${o.id}`);
2499
+ this.opts.log(`- not taking ${owedLabel(o.kind)} ${o.id}: ${st.how === "takeover" ? "its person took it over" : "its person stopped it"}`);
2500
+ }
2501
+ continue;
2502
+ }
2503
+ }
2504
+ const reqAct = (client.seenAct(o.ref) ?? await this.fetchActById(o.ref));
2505
+ const distrust = await this.requestTrust(client, o, reqAct);
2506
+ if (distrust) {
2507
+ this.decline(o.ref, "it could not be checked as your teammate's own message");
2508
+ await this.reportDistrust(client, o.id, o.ref, distrust);
2509
+ continue;
2239
2510
  }
2240
- if (refusedWake.askable) {
2241
- const pinned = this.selectPersona(client, o, reqAct?.from).persona?.agent;
2242
- const held = this.heldForSandbox(pinned ?? this.opts.agent);
2243
- if (held) {
2244
- if (!this.parkedNoSandbox.has(o.id)) {
2245
- this.parkedNoSandbox.set(o.id, { at: Date.now(), ...(pinned ? { agent: pinned } : {}) });
2246
- await this.reportRefused(client, o, held, true);
2511
+ const refusedWake = await this.wakeRefusal(client, o.ref, reqAct ? { from: reqAct.from, role: reqAct.sig?.role === "run" ? "worker" : reqAct.role ?? null } : undefined);
2512
+ if (refusedWake) {
2513
+ const asker = reqAct?.from ?? "the teammate who asked";
2514
+ const why = refusedWake.askable ? `waiting for you to approve ${asker}`
2515
+ : /^this machine is set not to be woken/.test(refusedWake.why) ? "your setup says teammates can't start work here (pantheon setup --wake)"
2516
+ : /^the team does not let/.test(refusedWake.why) ? `the team does not let ${asker} start work on agents`
2517
+ : /woken run/.test(refusedWake.why) ? "it came from one of your own agent's runs"
2518
+ : /cannot tell who sent it/.test(refusedWake.why) ? "it could not be told who sent it"
2519
+ : `${asker} isn't approved to start work on this computer`;
2520
+ this.decline(o.ref, why);
2521
+ if (this.mode() === "autopilot" && !refusedWake.transient)
2522
+ await this.tellAskerDeclined(client, o, reqAct, refusedWake.askable ? `it waits for ${this.cfg.member} to approve you` : "this machine doesn't start work for you on its own");
2523
+ if (!this.skipLogged.has(`wake:${o.id}`)) {
2524
+ this.skipLogged.add(`wake:${o.id}`);
2525
+ this.opts.log(`- not taking ${owedLabel(o.kind)} ${o.id}: ${refusedWake.why} — it waits for a live session`);
2526
+ }
2527
+ if (refusedWake.askable) {
2528
+ const pinned = this.selectPersona(client, o, reqAct?.from).persona?.agent;
2529
+ const held = this.heldForSandbox(pinned ?? this.opts.agent);
2530
+ if (held) {
2531
+ if (!this.parkedNoSandbox.has(o.id)) {
2532
+ this.parkedNoSandbox.set(o.id, { at: Date.now(), ...(pinned ? { agent: pinned } : {}) });
2533
+ await this.reportRefused(client, o, held, true);
2534
+ }
2535
+ }
2536
+ else {
2537
+ await this.askWake(client, o, refusedWake.askable);
2538
+ this.tickHold = { reason: "awaiting_wake_approval", detail: "asking its person whether this teammate may start work here" };
2247
2539
  }
2248
2540
  }
2249
- else {
2250
- await this.askWake(client, o, refusedWake.askable);
2251
- this.tickHold = { reason: "awaiting_wake_approval", detail: "asking its person whether this teammate may start work here" };
2541
+ continue;
2542
+ }
2543
+ if (presentNow && await this.personThread(client, reqAct)) {
2544
+ this.decline(o.ref, "it is in a conversation you started");
2545
+ if (!this.skipLogged.has(`own:${o.id}`)) {
2546
+ this.skipLogged.add(`own:${o.id}`);
2547
+ this.opts.log(`- not taking ${owedLabel(o.kind)} ${o.id} now: it is in a conversation you started, and you are at the keyboard — it is yours there`);
2252
2548
  }
2549
+ continue;
2253
2550
  }
2254
- continue;
2255
- }
2256
- const sel = this.selectPersona(client, o, reqAct?.from);
2257
- if (sel.skip) {
2258
- if (!this.skipLogged.has(o.id)) {
2259
- this.skipLogged.add(o.id);
2260
- this.opts.log(`- not taking ${owedLabel(o.kind)} ${o.id}: ${sel.skip}`);
2551
+ const sel = this.selectPersona(client, o, reqAct?.from);
2552
+ if (sel.skip) {
2553
+ this.decline(o.ref, "no playbook here covers it");
2554
+ if (this.mode() === "autopilot")
2555
+ await this.tellAskerDeclined(client, o, reqAct, "none of its playbooks covers it");
2556
+ if (!this.skipLogged.has(o.id)) {
2557
+ this.skipLogged.add(o.id);
2558
+ this.opts.log(`- not taking ${owedLabel(o.kind)} ${o.id}: ${sel.skip}`);
2559
+ }
2560
+ continue;
2261
2561
  }
2262
- continue;
2562
+ return { i, o, act: reqAct, persona: sel.persona };
2263
2563
  }
2264
- candidate = o;
2265
- candidateAct = reqAct;
2266
- persona = sel.persona;
2267
- break;
2564
+ return null;
2565
+ };
2566
+ const first = await pick(0);
2567
+ if (first) {
2568
+ candidate = first.o;
2569
+ candidateAct = first.act;
2570
+ persona = first.persona;
2571
+ clearDeclined(first.o.ref, this.opts.home);
2268
2572
  }
2269
2573
  let continuation;
2270
2574
  if (!candidate) {
@@ -2316,7 +2620,8 @@ export class Worker {
2316
2620
  continue;
2317
2621
  }
2318
2622
  const busyTtlMs = this.opts.busyTtlMs ?? LIMITS.activityBusyTtlMs;
2319
- if (me && shouldDeferToHuman(me.sessions, me.work, {
2623
+ const autopilotTakes = autopilot && (!!candidate || (!!continuation && this.workerThread(client, continuation)));
2624
+ if (me && !autopilotTakes && shouldDeferToHuman(me.sessions, me.work, {
2320
2625
  idleMs: this.idleMs(), busyTtlMs, busySince: this.busyObservedSince, hooksInstalled,
2321
2626
  })) {
2322
2627
  const id = candidate?.id ?? `cont:${continuation.id}`;
@@ -2349,7 +2654,7 @@ export class Worker {
2349
2654
  this.skipLogged.add("nosignal");
2350
2655
  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`);
2351
2656
  }
2352
- if (candidate && me && shouldDeferToHuman(me.sessions, me.work)
2657
+ if (candidate && me && !(autopilotTakes && client.features.includes("autopilot")) && shouldDeferToHuman(me.sessions, me.work)
2353
2658
  && Date.now() - candidate.created_at < LIMITS.workerGraceMs + CLOCK_SKEW_MS) {
2354
2659
  this.writeState("watching", "waiting out the relay's grace before claiming");
2355
2660
  continue;
@@ -2376,7 +2681,19 @@ export class Worker {
2376
2681
  : `! not spawning: ${gate.why}. Raise it with --max-runs / --max-runs-day${persona ? ` (persona "${persona.name}" may cap it lower)` : ""}, or leave it.`);
2377
2682
  }
2378
2683
  this.writeState("capped", gate.why);
2379
- this.tickHold = { reason: "capped", detail: "its run cap for now" };
2684
+ this.tickHold = { reason: "capped", detail: "its run cap for now", ...(gate.freeAt ? { until: gate.freeAt } : {}) };
2685
+ if (autopilot && gate.cap && candidate && first) {
2686
+ const when = gate.freeAt ? whenWords(gate.freeAt) : null;
2687
+ const line = gate.cap.n === 0 ? `Your worker is set to take no runs ${gate.cap.per === "hour" ? "an hour" : "a day"} — it's yours`
2688
+ : `Your worker has done its ${gate.cap.n} run${gate.cap.n === 1 ? "" : "s"} ${gate.cap.per === "hour" ? "this hour" : "today"} — it's yours${when ? `, or it'll take it after ${when}` : ""}`;
2689
+ const held = [{ o: first.o, act: first.act }];
2690
+ for (let next = await pick(first.i + 1); next; next = await pick(next.i + 1))
2691
+ held.push({ o: next.o, act: next.act });
2692
+ for (const h of held) {
2693
+ this.decline(h.o.ref, `it has done its ${gate.cap.n} runs ${gate.cap.per === "hour" ? "this hour" : "today"}`, line);
2694
+ await this.tellAskerDeclined(client, h.o, h.act ?? await this.fetchActById(h.o.ref), `it has used its runs for now${when ? `; it can take it after ${when}` : ""}`);
2695
+ }
2696
+ }
2380
2697
  if (continuation)
2381
2698
  this.requeueContinuation(continuation, 60_000);
2382
2699
  continue;
@@ -2452,6 +2769,13 @@ export class Worker {
2452
2769
  Object.assign(job, { waitUntil: soon.until, diagnosis: this.outageDiagnosis(label ? agentById(label)?.label ?? label : "The agent", soon, [], job.diagnosis.says) });
2453
2770
  }
2454
2771
  }
2772
+ if (job.stoppedBy) {
2773
+ if (continuation)
2774
+ this.markDone(continuation.id);
2775
+ if (this.opts.once)
2776
+ break;
2777
+ continue;
2778
+ }
2455
2779
  if (job.agentOut) {
2456
2780
  if (continuation) {
2457
2781
  this.contDone.delete(continuation.id);
@@ -2476,6 +2800,8 @@ export class Worker {
2476
2800
  }
2477
2801
  }
2478
2802
  else if (job.refused && job.diagnosis) {
2803
+ if (candidate)
2804
+ this.decline(candidate.ref, job.diagnosis.cause === "repo_not_here" ? "the repo it is about is not on this computer" : "nothing on this computer can run it while you're away");
2479
2805
  if (candidate) {
2480
2806
  this.failedRuns.set(candidate.id, 2);
2481
2807
  this.skipLogged.add(`parked:${candidate.id}`);
@@ -2504,6 +2830,8 @@ export class Worker {
2504
2830
  if (this.failedRuns.size > 200) {
2505
2831
  this.failedRuns.delete(this.failedRuns.keys().next().value);
2506
2832
  }
2833
+ if (failures >= 2)
2834
+ this.decline(candidate.ref, "its run failed twice on this computer");
2507
2835
  if (failures >= 2 && job.diagnosis)
2508
2836
  await this.reportStuck(client, candidate, job.diagnosis, attempts);
2509
2837
  }
@@ -2571,7 +2899,32 @@ export class Worker {
2571
2899
  liveRuns.add(pid);
2572
2900
  installRunReaper();
2573
2901
  this.attemptPid = pid;
2574
- writeRunRecord(this.stateDir(), { pid, member: this.cfg.member, space: this.cfg.space, at: Date.now(), worker: process.pid, obligation: attempt.obligation, ...(attempt.spend ? { spend: attempt.spend } : {}), ...(attempt.limit ? { limit: attempt.limit } : {}), ...(attempt.sandbox ? { sandbox: attempt.sandbox } : {}) });
2902
+ this.runRecord = { pid, member: this.cfg.member, space: this.cfg.space, at: Date.now(), worker: process.pid, ...(workerIdentity() ? { worker_id: workerIdentity() } : {}), obligation: attempt.obligation, ...(attempt.ref ? { ref: attempt.ref } : {}), ...(attempt.spend ? { spend: attempt.spend } : {}), ...(attempt.limit ? { limit: attempt.limit } : {}), ...(attempt.sandbox ? { sandbox: attempt.sandbox } : {}) };
2903
+ writeRunRecord(this.stateDir(), this.runRecord);
2904
+ }
2905
+ runRecord = null;
2906
+ recordChanged = false;
2907
+ recordOnDisk() { try {
2908
+ return readFileSync(join(this.stateDir(), RUN_RECORD), "utf8");
2909
+ }
2910
+ catch {
2911
+ return null;
2912
+ } }
2913
+ markRunExited() {
2914
+ if (!this.runRecord || this.runRecord.exited_at)
2915
+ return;
2916
+ this.recordChanged ||= this.recordOnDisk() !== JSON.stringify(this.runRecord) + "\n";
2917
+ this.runRecord = { ...this.runRecord, exited_at: Date.now() };
2918
+ writeRunRecord(this.stateDir(), this.runRecord);
2919
+ }
2920
+ markRunRestored() {
2921
+ if (!this.runRecord)
2922
+ return;
2923
+ if (this.recordChanged || this.recordOnDisk() !== JSON.stringify(this.runRecord) + "\n")
2924
+ this.opts.log(`! the run record (${RUN_RECORD}) was changed or removed during the run — put back`);
2925
+ this.recordChanged = false;
2926
+ this.runRecord = { ...this.runRecord, ...(this.runRecord.exited_at ? {} : { exited_at: Date.now() }), restored: true };
2927
+ writeRunRecord(this.stateDir(), this.runRecord);
2575
2928
  }
2576
2929
  untrackRun(pid) {
2577
2930
  this.runPids.delete(pid);
@@ -2583,6 +2936,37 @@ export class Worker {
2583
2936
  return;
2584
2937
  clearRunRecord(this.stateDir(), this.attemptPid);
2585
2938
  this.attemptPid = null;
2939
+ this.runRecord = null;
2940
+ }
2941
+ recoverGuard() {
2942
+ const r = recoverInterruptedGuard(this.stateDir());
2943
+ if (r.outcome === "none" || r.outcome === "live")
2944
+ return;
2945
+ const tell = (heading, body) => {
2946
+ if (!this.opts.notify)
2947
+ return;
2948
+ try {
2949
+ this.opts.notify({ kind: "worker", who: "Your worker", heading, context: this.cfg.space, body, ttl: 0, sound: true });
2950
+ }
2951
+ catch { }
2952
+ };
2953
+ if (r.outcome === "stale" || r.outcome === "person changed") {
2954
+ this.opts.log(` guard a snapshot from a run on ${new Date(r.at).toLocaleString()} was not restored — ${r.outcome === "stale" ? "too old to be that run's" : "you have changed your setup since"}; dropped`);
2955
+ return;
2956
+ }
2957
+ if (r.outcome === "failed") {
2958
+ this.opts.log(`! could not put Pantheon's own files back after the interrupted run (try ${r.attempts} of ${GUARD_RESTORE_TRIES}): ${r.why}`);
2959
+ if (r.dropped)
2960
+ tell("Your worker could not put your settings back", `A teammate's request was running when your worker stopped, and putting back what it changed failed ${GUARD_RESTORE_TRIES} times (${r.why}). Check your setup: pantheon status, pantheon policy.`);
2961
+ return;
2962
+ }
2963
+ if (!r.said.length) {
2964
+ this.opts.log(" guard the run interrupted with its worker changed none of Pantheon's own files");
2965
+ return;
2966
+ }
2967
+ for (const l of r.said)
2968
+ this.opts.log(`! the run interrupted with its worker: put back ${l}`);
2969
+ tell("Your worker stopped mid-run — settings put back", `${putBackSaid(r.said)} If you made that change yourself, make it again.`);
2586
2970
  }
2587
2971
  recoverInterruptedRun() {
2588
2972
  const dir = this.stateDir(), f = join(dir, RUN_RECORD);
@@ -2928,10 +3312,26 @@ export class Worker {
2928
3312
  const multi = this.workspaceList().length > 1 || place.kind === "folder" || route.notHere.length > 0;
2929
3313
  const whereNote = multi ? workspaceNote(route, attached, tipSha || baseSha, place.kind === "folder" ? worktree : null, codexReadOnly, snap?.skipped) : "";
2930
3314
  const reserved = reservedDecisionsNote(profileForTeam(this.cfg));
2931
- const brief = makeBrief(branch, canPush) + whereNote + baseNote(baseRef, baseSha, fetched) +
3315
+ const who = (() => { try {
3316
+ return loadProfile(this.cfg).human.display_name || this.cfg.member;
3317
+ }
3318
+ catch {
3319
+ return this.cfg.member;
3320
+ } })();
3321
+ const inProgress = place.kind === "repo" ? await checkoutNote(project, baseRef).catch(() => "") : "";
3322
+ const brief = makeBrief(branch, canPush) + (this.mode() === "autopilot" ? autopilotBrief(who) : "") + inProgress + whereNote + baseNote(baseRef, baseSha, fetched) +
2932
3323
  (allowBash ? (agentId === "claude-code" ? commandNote(worktree, tipSha || baseSha, (m) => this.opts.log(m)) : "") : holdRepoConfig ? heldNote() : "") +
2933
3324
  (reserved ? `\n\n${reserved}` : "");
2934
3325
  const startedAt = Date.now();
3326
+ const runRef = o.kind === "CONTINUE" ? o.id : o.ref;
3327
+ if (this.mode() === "autopilot" && this.opts.notify && loadProfile(this.cfg).notifications?.decisions !== false) {
3328
+ try {
3329
+ const gRec2 = o.goal ? client.goals.get(o.goal) : undefined;
3330
+ const title = (gRec2 && (!client.signaturesExpected() || trusted(client.goalTrust(gRec2).trust)) ? gRec2.title : (wokeBy?.body.split("\n").find((l) => l.trim()) ?? o.body)).replace(/\s+/g, " ").trim().slice(0, 80);
3331
+ this.sayPickup({ title: title.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, " "), asker: wokeBy?.from ?? (await this.actOf(client, o.ref))?.from ?? "a teammate", ref: runRef });
3332
+ }
3333
+ catch { }
3334
+ }
2935
3335
  writeInside(worktree, join(worktree, ".pantheon-task.md"), brief, 0o644);
2936
3336
  let command;
2937
3337
  let args;
@@ -3072,6 +3472,15 @@ export class Worker {
3072
3472
  let detail;
3073
3473
  let transcript = "";
3074
3474
  const homeBefore = snapshotHome(this.stateDir());
3475
+ const guardHome = this.stateDir();
3476
+ try {
3477
+ persistSnapshot(homeBefore, { workerId: workerIdentity(), limit: runLimit.ms });
3478
+ }
3479
+ catch (e) {
3480
+ this.opts.log(`! could not keep the pre-run snapshot on disk (${e.message.split("\n")[0]}) — a worker killed mid-run could not put the home back`);
3481
+ }
3482
+ pendingGuards.set(guardHome, { snap: homeBefore, log: this.opts.log });
3483
+ installRunReaper();
3075
3484
  let spendId = null;
3076
3485
  try {
3077
3486
  spendId = startRun({ at: Date.now(), goal: o.goal, obligation: o.id, ok: false, triggeredBy: client.recentFrom(o.ref) ?? "unknown", summary: clip(o.body), space: this.spaceKey(), member: this.cfg.member }, this.opts.home);
@@ -3080,6 +3489,7 @@ export class Worker {
3080
3489
  this.opts.log(`! could not record the run as started: ${e.message.split("\n")[0]}`);
3081
3490
  }
3082
3491
  let recorded = false;
3492
+ let stopBy = null;
3083
3493
  try {
3084
3494
  try {
3085
3495
  detail = await new Promise((res) => {
@@ -3093,7 +3503,7 @@ export class Worker {
3093
3503
  }
3094
3504
  const pid = child.pid;
3095
3505
  if (pid)
3096
- this.trackRun(pid, { obligation: o.id, spend: spendId, limit: runLimit.ms, ...(sandboxAbsent.length ? { sandbox: { common: sandboxCommon, absent: sandboxAbsent } } : {}) });
3506
+ this.trackRun(pid, { obligation: o.id, ref: runRef, spend: spendId, limit: runLimit.ms, ...(sandboxAbsent.length ? { sandbox: { common: sandboxCommon, absent: sandboxAbsent } } : {}) });
3097
3507
  let head = "", tail = "";
3098
3508
  const take = (b) => {
3099
3509
  const s = b.toString();
@@ -3126,11 +3536,26 @@ export class Worker {
3126
3536
  const kill = setTimeout(() => { if (dead)
3127
3537
  return; timedOut = true; if (pid)
3128
3538
  killRunTree(pid); }, limit);
3539
+ const watch = setInterval(() => {
3540
+ if (dead || stopBy)
3541
+ return;
3542
+ const st = stopFor(runRef, this.opts.home);
3543
+ if (st) {
3544
+ stopBy = st.how;
3545
+ this.opts.log(`! ${o.id}: ${st.how === "takeover" ? "its person took it over" : "its person stopped it"} — stopping the run`);
3546
+ if (pid)
3547
+ killRunTree(pid);
3548
+ }
3549
+ }, 1_000);
3550
+ watch.unref?.();
3551
+ child.on("exit", () => clearInterval(watch));
3552
+ child.on("error", () => clearInterval(watch));
3129
3553
  child.on("exit", (code, signal) => {
3130
3554
  clearTimeout(kill);
3131
3555
  if (pid && !dead && killTreeOnExit())
3132
3556
  killRunTree(pid);
3133
3557
  markDead();
3558
+ this.markRunExited();
3134
3559
  const c = child;
3135
3560
  exitCode = { code, signal };
3136
3561
  exitGrace = setTimeout(() => { try {
@@ -3158,7 +3583,13 @@ export class Worker {
3158
3583
  this.opts.log(` config ${l}`); });
3159
3584
  this.cleanupStep("sealing the run home", () => this.sealRunHome(runHome));
3160
3585
  this.cleanupStep("taking back the delivery hold", () => writeHoldConfig(runHome, null));
3161
- this.cleanupStep("checking Pantheon's own files", () => this.restoreHomeAfterRun(homeBefore, o));
3586
+ this.cleanupStep("checking Pantheon's own files", () => {
3587
+ const ok = this.restoreHomeAfterRun(homeBefore, o);
3588
+ pendingGuards.delete(guardHome);
3589
+ if (ok)
3590
+ clearPersistedGuard(guardHome);
3591
+ this.markRunRestored();
3592
+ });
3162
3593
  }
3163
3594
  const logRoot = snap ? scratch : worktree;
3164
3595
  const runLog = snap ? join(scratch, `${basename(worktree)}.run.log`) : join(worktree, ".pantheon-run.log");
@@ -3178,6 +3609,22 @@ export class Worker {
3178
3609
  }
3179
3610
  }
3180
3611
  this.writeRunLog(logRoot, runLog, `obligation ${o.id}\nbranch ${branch}\n\n${detail}\n${extra}`);
3612
+ if (stopBy) {
3613
+ try {
3614
+ if (!stopFor(runRef, this.opts.home))
3615
+ requestRunStop({ ref: runRef, how: stopBy, space: this.cfg.space }, this.opts.home);
3616
+ }
3617
+ catch { }
3618
+ const end = { at: Date.now(), goal: o.goal, obligation: o.id, ok: false, triggeredBy: (await this.actOf(client, o.ref))?.from ?? "unknown", summary: clip(o.body), space: this.spaceKey(), member: this.cfg.member };
3619
+ if (spendId)
3620
+ finishRun(spendId, end, this.opts.home);
3621
+ else
3622
+ recordRun(end, this.opts.home);
3623
+ recorded = true;
3624
+ this.opts.log(`< ${o.id}: stopped by its person (${stopBy === "takeover" ? "taken over" : "stop"}) — transcript: ${runLog}`);
3625
+ await this.tellStops(client);
3626
+ return { obligation: o, branch, worktree, ok: false, detail: `stopped by its person (${stopBy})`, stoppedBy: stopBy };
3627
+ }
3181
3628
  const exited = /^exit 0/.test(detail);
3182
3629
  const held = await this.settleHeld(client, heldRun ? { run: heldRun, canPush: canPush && !massDelete, massDelete } : null);
3183
3630
  const settled = [...held.sent, ...held.waiting];
@@ -3290,10 +3737,10 @@ export class Worker {
3290
3737
  }
3291
3738
  catch (e) {
3292
3739
  this.opts.log(`! could not check Pantheon's own files after the run: ${e.message}`);
3293
- return;
3740
+ return false;
3294
3741
  }
3295
3742
  if (!changes.length)
3296
- return;
3743
+ return true;
3297
3744
  for (const c of changes)
3298
3745
  this.opts.log(`${c.what === "reported" || c.quiet ? " " : "!"} ${o.id}: ${describeChange(c)}`);
3299
3746
  const taken = changes.filter((c) => c.what !== "reported" && !c.quiet);
@@ -3307,6 +3754,7 @@ export class Worker {
3307
3754
  }
3308
3755
  catch { }
3309
3756
  }
3757
+ return true;
3310
3758
  }
3311
3759
  async pushRunBranch(worktree, br, commit) {
3312
3760
  if (!validBase(br) || (await gitOut(worktree, ["merge-base", "--is-ancestor", commit, `refs/heads/${br}`])) === null)
@@ -3784,6 +4232,58 @@ export class Worker {
3784
4232
  this.contQueue.push({ act, notBefore: Date.now() + delayMs });
3785
4233
  }
3786
4234
  }
4235
+ async tellStops(client) {
4236
+ if (client.head > 0) {
4237
+ try {
4238
+ pruneDeclined((ref) => client.obligations.some((x) => x.ref === ref && x.owner === this.cfg.member), this.mine, this.opts.home);
4239
+ }
4240
+ catch { }
4241
+ }
4242
+ if (client.obligations.length || client.head > 0) {
4243
+ try {
4244
+ pruneRunStops((ref) => client.obligations.some((x) => x.ref === ref && x.owner === this.cfg.member), this.opts.home, this.mine);
4245
+ }
4246
+ catch { }
4247
+ }
4248
+ let stops;
4249
+ try {
4250
+ stops = loadRunStops(this.opts.home).filter((x) => !x.told);
4251
+ }
4252
+ catch {
4253
+ return;
4254
+ }
4255
+ for (const st of stops) {
4256
+ if (st.space && st.space !== this.cfg.space && st.space !== this.cfg.spaceId)
4257
+ continue;
4258
+ const actId = st.ref.replace(/^cont:/, "");
4259
+ const act = client.seenAct(actId) ?? (await this.fetchActById(actId));
4260
+ if (!act)
4261
+ continue;
4262
+ const ob = st.ref.startsWith("cont:") ? null : client.myObligations().find((x) => x.ref === st.ref) ?? null;
4263
+ if (!st.ref.startsWith("cont:") && !ob) {
4264
+ markStopTold(st.ref, this.opts.home);
4265
+ this.opts.log(`- ${st.how} on ${act.id}: it is no longer owed — nothing to tell`);
4266
+ continue;
4267
+ }
4268
+ try {
4269
+ if (st.how === "takeover")
4270
+ await client.releaseClaim(ob?.id ?? st.ref);
4271
+ const person = (() => { try {
4272
+ return loadProfile(this.cfg).human.display_name || this.cfg.member;
4273
+ }
4274
+ catch {
4275
+ return this.cfg.member;
4276
+ } })();
4277
+ if (act.from !== this.cfg.member)
4278
+ await client.send({ act: "NOTE", body: stopNote(person, st.how), to: [act.from], goal: act.goal, ref: act.id });
4279
+ markStopTold(st.ref, this.opts.home);
4280
+ this.opts.log(`> told ${act.from}: ${st.how === "takeover" ? `${person} is handling ${act.id} personally` : `${person} stopped the work on ${act.id}`}`);
4281
+ }
4282
+ catch (e) {
4283
+ this.opts.log(`! could not tell ${act.from} about ${st.how} on ${act.id}: ${e.message.split("\n")[0]}`);
4284
+ }
4285
+ }
4286
+ }
3787
4287
  nextContinuation(client) {
3788
4288
  const now = Date.now();
3789
4289
  for (const c of [...this.contQueue]) {
@@ -3794,6 +4294,10 @@ export class Worker {
3794
4294
  this.contQueue = this.contQueue.filter((x) => x.act.id !== r.id);
3795
4295
  if (this.contDone.has(r.id) || g?.state === "CLOSED")
3796
4296
  continue;
4297
+ if (stopFor(`cont:${r.id}`, this.opts.home)) {
4298
+ this.markDone(r.id);
4299
+ continue;
4300
+ }
3797
4301
  const sel = this.selectPersona(client, {
3798
4302
  id: `cont:${r.id}`, kind: "CONTINUE", owner: this.cfg.member,
3799
4303
  ref: r.id, goal: r.goal, created_at: r.ts, body: r.body.slice(0, 120),
@@ -4253,6 +4757,107 @@ export class Worker {
4253
4757
  const r = upgrade(undefined, version ? { version } : {});
4254
4758
  return { ok: r.ok, alreadyCurrent: r.alreadyCurrent, from: r.from, to: r.to, ...(r.needsPerson ? { needsPerson: r.needsPerson } : {}) };
4255
4759
  }
4760
+ workerThread(client, act) {
4761
+ const ref = act.ref ? client.seenAct(act.ref) : undefined;
4762
+ if (!ref || ref.from !== this.cfg.member)
4763
+ return false;
4764
+ return ref.sig?.role === "run" || ref.role === "worker";
4765
+ }
4766
+ pickupOpen(ref) {
4767
+ try {
4768
+ if (stopFor(ref, this.opts.home))
4769
+ return false;
4770
+ }
4771
+ catch { }
4772
+ if (this.contDone.has(`handled:${ref}`))
4773
+ return false;
4774
+ const c = this.client;
4775
+ if (c && !ref.startsWith("cont:")) {
4776
+ try {
4777
+ return c.myWork().some((o) => o.ref === ref);
4778
+ }
4779
+ catch {
4780
+ return true;
4781
+ }
4782
+ }
4783
+ return true;
4784
+ }
4785
+ pickups = null;
4786
+ sayPickup(it) {
4787
+ const notify = this.opts.notify;
4788
+ if (!notify)
4789
+ return;
4790
+ const now = Date.now();
4791
+ if (!this.pickups || now - this.pickups.shownAt > PICKUP_WINDOW_MS) {
4792
+ if (this.pickups?.timer)
4793
+ clearTimeout(this.pickups.timer);
4794
+ this.pickups = { shownAt: now, items: [it], timer: null };
4795
+ try {
4796
+ notify(composePickup({ ...it, space: this.cfg.space }));
4797
+ }
4798
+ catch { }
4799
+ return;
4800
+ }
4801
+ const b = this.pickups;
4802
+ b.items.push(it);
4803
+ if (b.timer)
4804
+ return;
4805
+ b.timer = setTimeout(() => {
4806
+ b.timer = null;
4807
+ b.shownAt = Date.now();
4808
+ const open = b.items.filter((x) => this.pickupOpen(x.ref));
4809
+ if (!open.length)
4810
+ return;
4811
+ try {
4812
+ notify(composePickups(open, this.cfg.space));
4813
+ }
4814
+ catch { }
4815
+ }, Math.max(PICKUP_COALESCE_MS, b.shownAt + PICKUP_MIN_GAP_MS - now));
4816
+ b.timer.unref?.();
4817
+ }
4818
+ async tellAskerDeclined(client, o, act, why) {
4819
+ const peer = act?.from ?? client.recentFrom(o.ref);
4820
+ if (!peer || peer === this.cfg.member)
4821
+ return;
4822
+ const key = `declined-told:${o.id}`;
4823
+ const space = this.spaceKey();
4824
+ if (this.contDone.has(key) || loadContinued(space, this.opts.home).has(key))
4825
+ return;
4826
+ this.contDone.add(key);
4827
+ try {
4828
+ await client.send({
4829
+ act: "NOTE", goal: o.goal, ref: o.ref, after_seq: Math.max(client.readSeq, client.seq), to: [peer],
4830
+ summary: `${this.cfg.member}'s agent won't take this on its own — it's with ${this.cfg.member}`,
4831
+ body: `${this.cfg.member}'s agent won't take this one on its own (${why}), so it's with ${this.cfg.member} now. It is still owed.`,
4832
+ });
4833
+ markContinued(space, key, this.opts.home);
4834
+ this.opts.log(`* told ${peer} that ${o.id} is with ${this.cfg.member}: ${why}`);
4835
+ }
4836
+ catch (e) {
4837
+ this.contDone.delete(key);
4838
+ this.opts.log(`! could not tell ${peer} that ${o.id} is with ${this.cfg.member}: ${e.message.split("\n")[0]}`);
4839
+ }
4840
+ }
4841
+ decline(ref, reason, line) {
4842
+ try {
4843
+ markDeclined(ref, reason, this.opts.home, Date.now(), { space: this.cfg.space, ...(line ? { line } : {}) });
4844
+ }
4845
+ catch { }
4846
+ }
4847
+ mine = (space) => !!space && (space === this.cfg.space || space === this.cfg.spaceId);
4848
+ async personThread(client, act) {
4849
+ if (!act)
4850
+ return false;
4851
+ const g = act.goal ? client.goals.get(act.goal) : undefined;
4852
+ const before = act.ref ? (client.seenAct(act.ref) ?? await this.fetchActById(act.ref)) : null;
4853
+ return personsOwnThread(this.cfg.member, before, g ? { by: g.opened_by, run: g.sig?.role === "run" } : null);
4854
+ }
4855
+ reportedMode = null;
4856
+ mode() {
4857
+ if (this.opts.mode)
4858
+ return this.opts.mode;
4859
+ return currentMode(this.opts.home);
4860
+ }
4256
4861
  idleMs() {
4257
4862
  if (this.opts.idleMs !== undefined)
4258
4863
  return this.opts.idleMs;