benignswarm 0.12.92 → 0.12.94

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.
@@ -18,6 +18,7 @@ import { probeCapabilities } from "../capabilities.js";
18
18
  import { diskSpaceNotice } from "../notices.js";
19
19
  import { verifyClaudeProvider } from "../providers.js";
20
20
  import { resumeTurnGuard } from "../turn-guard.js";
21
+ import { defaultWorkspaceWritableRoots } from "../start-options.js";
21
22
  export const machineFile = () => join(configRoot(), "machine.json");
22
23
  export function loadMachine() {
23
24
  const f = machineFile();
@@ -31,14 +32,19 @@ function writeMachineState(s) {
31
32
  mkdirSync(dirname(stateFile()), { recursive: true });
32
33
  writeFileSync(stateFile(), JSON.stringify(s, null, 2) + "\n");
33
34
  }
34
- /** What a session's watcher is started with; a change means re-running codex start. The thread is compared separately. */
35
+ /** What a session's watcher is started with; a change means re-running codex start. */
35
36
  /**
36
37
  * Bumped when `b9s start` builds a session's settings differently, so every session is started
37
38
  * again once with them. 2: the agent's own worktree git folder is writable under workspace-write.
38
39
  * 3: turns get TMPDIR beside the checkout instead of the system's /tmp.
39
40
  */
40
- const START_REV = 4;
41
- export const sessionFingerprint = (s, writable = []) => JSON.stringify([s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? 20, ...(writable.length ? [writable] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
41
+ const START_REV = 5;
42
+ export const sessionFingerprint = (s, writable = []) => JSON.stringify([s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? 20, s.thread, ...(writable.length ? [writable] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
43
+ /** A clear is distinct from a thread that the server has not received from the machine yet. */
44
+ export function reconcileThread(s, local) {
45
+ const clearing = s.thread === null && !!s.thread_override_at && s.thread_override_at !== local?.thread_override_at;
46
+ return clearing ? null : s.thread ?? local?.thread ?? null;
47
+ }
42
48
  export const watchLabelOf = (ref) => `${WATCH_LABEL_PREFIX}${ref.replace("/", ".")}`;
43
49
  /**
44
50
  * During a maintenance drain or window, a session that would be started fresh (no known thread, so
@@ -62,7 +68,7 @@ export function startArgs(s, thread, writable = []) {
62
68
  ...(s.model ? ["--model", s.model] : []),
63
69
  ...(s.effort ? ["--effort", s.effort] : []),
64
70
  ...(thread ? ["--thread", thread] : []),
65
- ...(writable.length && s.sandbox === "workspace-write" ? ["--writable", writable.join(",")] : []),
71
+ ...(writable.length && s.sandbox === "workspace-write" ? writable.flatMap((path) => ["--writable-root", path]) : []),
66
72
  ];
67
73
  }
68
74
  const KEY_CHECK_MS = 10 * 60_000;
@@ -164,8 +170,11 @@ export async function reconcile(m, log) {
164
170
  }
165
171
  }
166
172
  await ensureCredentials(client, m, s, local, log);
167
- const fp = sessionFingerprint(s, s.sandbox === "workspace-write" ? writable : []);
168
- const thread = s.thread ?? local?.thread ?? null;
173
+ const sessionWritable = s.sandbox === "workspace-write"
174
+ ? [...new Set([...defaultWorkspaceWritableRoots(), ...writable])]
175
+ : writable;
176
+ const thread = reconcileThread(s, local);
177
+ const fp = sessionFingerprint({ ...s, thread }, s.sandbox === "workspace-write" ? sessionWritable : []);
169
178
  const threadChanged = !!local?.thread && !!s.thread && s.thread !== local.thread;
170
179
  if (!svc() || !local || local.fingerprint !== fp || threadChanged) {
171
180
  // A new session's start runs its first turn at once, past the watchers' check: during a
@@ -177,11 +186,17 @@ export async function reconcile(m, log) {
177
186
  out.push(held);
178
187
  continue;
179
188
  }
180
- const r = spawnSync(bin, startArgs(s, thread, writable), { cwd: s.dir, encoding: "utf8", timeout: 180_000 });
189
+ const r = spawnSync(bin, startArgs(s, thread, sessionWritable), { cwd: s.dir, encoding: "utf8", timeout: 180_000 });
181
190
  if (r.status !== 0)
182
191
  throw new Error(`b9s start failed: ${errorText(r.stderr || r.stdout)}`);
183
192
  const started = JSON.parse(r.stdout);
184
- state.sessions[s.id] = { label, fingerprint: fp, thread: started.thread, key_checked_at: state.sessions[s.id]?.key_checked_at ?? Date.now() };
193
+ state.sessions[s.id] = {
194
+ label,
195
+ fingerprint: sessionFingerprint({ ...s, thread: started.thread }, s.sandbox === "workspace-write" ? sessionWritable : []),
196
+ thread: started.thread,
197
+ thread_override_at: s.thread_override_at ?? null,
198
+ key_checked_at: state.sessions[s.id]?.key_checked_at ?? Date.now(),
199
+ };
185
200
  log(`${s.agent}: ${thread ? "adopted" : "started"} ${s.harness === "codex" ? "thread" : "session"} ${started.thread} in ${s.dir}`);
186
201
  }
187
202
  else {
@@ -22,8 +22,9 @@ import { formatUpdates, gatherUpdates, reportDelivery } from "./hook.js";
22
22
  import { readState, writeState } from "../state.js";
23
23
  import { probeCapabilities } from "../capabilities.js";
24
24
  import { fetchRecoveryBrief, formatRecoveryBrief, recoveryBriefUnavailableText, recoveryBriefWasDelivered } from "../brief.js";
25
- import { beginGuardedTurn, completeGuardedTurn, DEFAULT_TURNS_PER_HOUR, MAX_UNPRODUCTIVE_TURNS } from "../turn-guard.js";
25
+ import { beginGuardedTurn, completeGuardedTurn, DEFAULT_TURNS_PER_HOUR, MAX_TURNS_PER_HOUR, MAX_UNPRODUCTIVE_TURNS } from "../turn-guard.js";
26
26
  import { sessionUsage } from "../usage.js";
27
+ import { collectPruneProtection } from "../prune-protection.js";
27
28
  function omitMeasuresAlreadyIn(text, updates) {
28
29
  if (!text)
29
30
  return updates;
@@ -69,8 +70,8 @@ export async function watch(p, out) {
69
70
  if (!Number.isInteger(turnTimeout) || turnTimeout < 5)
70
71
  throw new CliError("usage", "--turn-timeout must be a whole number of minutes, at least 5");
71
72
  const turnsPerHour = Number(str(p.flags, "turns-per-hour") ?? String(DEFAULT_TURNS_PER_HOUR));
72
- if (!Number.isInteger(turnsPerHour) || turnsPerHour < 1 || turnsPerHour > DEFAULT_TURNS_PER_HOUR)
73
- throw new CliError("usage", `--turns-per-hour must be a whole number between 1 and ${DEFAULT_TURNS_PER_HOUR}`);
73
+ if (!Number.isInteger(turnsPerHour) || turnsPerHour < 1 || turnsPerHour > MAX_TURNS_PER_HOUR)
74
+ throw new CliError("usage", `--turns-per-hour must be a whole number between 1 and ${MAX_TURNS_PER_HOUR}`);
74
75
  if (!turnMode && p.flags["turns-per-hour"] !== undefined)
75
76
  throw new CliError("usage", "--turns-per-hour is only used with --turn");
76
77
  const thread = exec ? threadOfExec(exec) : null;
@@ -86,7 +87,7 @@ export async function watch(p, out) {
86
87
  throw new CliError("usage", "--turn runs the turn itself: --exec must be codex exec resume <thread-id> ... {text}, not codex queue");
87
88
  const named = str(p.flags, "harness") ?? (thread ? "codex" : undefined);
88
89
  if (!named)
89
- throw new CliError("usage", "--turn needs --harness <codex|claude-code|dsh> and --session <id> (a Codex exec resume command names its thread itself)");
90
+ throw new CliError("usage", "--turn needs --harness <codex|claude-code|dsh|antigravity> and --session <id> (a Codex exec resume command names its thread itself)");
90
91
  const harness = turnHarness(named);
91
92
  const session = (str(p.flags, "session") ?? (harness === "codex" ? thread : null))?.toLowerCase();
92
93
  if (!session)
@@ -187,7 +188,8 @@ export async function watch(p, out) {
187
188
  // Space back on a schedule: only clean worktrees whose work has landed or whose unit is
188
189
  // closed; never one a unit is still being worked in (it may have no commits yet).
189
190
  const units = await unitWorktrees(scanCreds, scanCreds.project);
190
- const prunable = pruneReport(process.cwd(), units.closed, units.active).prunable;
191
+ const protection = await collectPruneProtection(scanCreds, scanCreds.project);
192
+ const prunable = pruneReport(process.cwd(), units.closed, units.active, undefined, protection).prunable;
191
193
  const probe = freeSpaceProbe(prunable.map((c) => c.path));
192
194
  let pruned = 0;
193
195
  for (const c of prunable) {
@@ -579,7 +581,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
579
581
  ctl.failedAt = Date.now();
580
582
  }
581
583
  ctl.turn = null;
582
- await completePendingTurnGuard(name, probe, log, undefined, env);
584
+ await completePendingTurnGuard(name, probe, log, undefined, undefined, env);
583
585
  return;
584
586
  }
585
587
  if (!turn.killedForTimeout && Date.now() - turn.startedMs > timeoutMin * 60_000) {
@@ -610,7 +612,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
610
612
  }
611
613
  if ("missing" in ph) {
612
614
  if (savedGuard?.turns.some((attempt) => attempt.productive === null)) {
613
- await completePendingTurnGuard(name, probe, log, undefined, env);
615
+ await completePendingTurnGuard(name, probe, log, undefined, undefined, env);
614
616
  if (readState(name, env).turn_guard?.fault)
615
617
  return;
616
618
  }
@@ -618,7 +620,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
618
620
  return;
619
621
  }
620
622
  if (!ph.running && savedGuard?.turns.some((attempt) => attempt.productive === null)) {
621
- await completePendingTurnGuard(name, probe, log, undefined, env);
623
+ await completePendingTurnGuard(name, probe, log, undefined, undefined, env);
622
624
  if (readState(name, env).turn_guard?.fault)
623
625
  return;
624
626
  }
@@ -710,10 +712,7 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
710
712
  }
711
713
  return true;
712
714
  }
713
- export async function completePendingTurnGuard(name, probe, log, outputOverride, tokenOverrideOrEnv, envOverride = process.env) {
714
- // The watcher passes its isolated environment; start-turn callers may pass measured tokens.
715
- const env = tokenOverrideOrEnv !== null && typeof tokenOverrideOrEnv === "object" ? tokenOverrideOrEnv : envOverride;
716
- const tokenOverride = tokenOverrideOrEnv === null || typeof tokenOverrideOrEnv === "number" ? tokenOverrideOrEnv : undefined;
715
+ export async function completePendingTurnGuard(name, probe, log, outputOverride, tokenOverride, env = process.env) {
717
716
  const current = readState(name, env);
718
717
  const guard = current.turn_guard;
719
718
  const pending = guard?.turns.slice().reverse().find((attempt) => attempt.productive === null);
@@ -6,6 +6,7 @@ import { CliError } from "../errors.js";
6
6
  import { spawnSync } from "node:child_process";
7
7
  import { archiveWorktreeChanges, defaultMachine, formatBytes, freeSpaceProbe, scanWorktrees, pruneReport, removePrunable, PRUNE_STATUS_TIMEOUT_MS } from "../git.js";
8
8
  import { table } from "../output.js";
9
+ import { collectPruneProtection } from "../prune-protection.js";
9
10
  const CLOSED = ["done", "abandoned", "superseded"];
10
11
  const PRUNE_UNIT_STATES_TIMEOUT_MS = 30_000;
11
12
  const WORKTREE_SCAN_TIMEOUT_MS = 30_000;
@@ -88,7 +89,8 @@ export async function worktrees(p, out, timeouts = {}) {
88
89
  const requestTimeoutMs = timeouts.requestTimeoutMs ?? PRUNE_UNIT_STATES_TIMEOUT_MS;
89
90
  const statusTimeoutMs = timeouts.statusTimeoutMs ?? PRUNE_STATUS_TIMEOUT_MS;
90
91
  const units = await unitWorktrees(creds, project, { timeoutMs: requestTimeoutMs, onProgress: progress });
91
- const rep = pruneReport(process.cwd(), units.closed, units.active, undefined, { onProgress: progress, statusTimeoutMs });
92
+ const protection = await collectPruneProtection(creds, project);
93
+ const rep = pruneReport(process.cwd(), units.closed, units.active, undefined, { onProgress: progress, statusTimeoutMs, ...protection });
92
94
  // --archive: a closed unit's worktree with uncommitted files is saved to archive/wu<n>-leftovers
93
95
  // and then removed. Never for a unit still open, never for a worktree whose status is unreadable.
94
96
  const archive = bool(p.flags, "archive") ? rep.kept.filter((k) => k.archivable) : [];
@@ -1,5 +1,5 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { readFileSync, writeFileSync } from "node:fs";
2
+ import { lstatSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { bool, str } from "../args.js";
4
4
  import { Client } from "../client.js";
5
5
  import { agentRef, loadAgent, resolveAgentName, resolveModel } from "../config.js";
@@ -8,12 +8,22 @@ import { codexRollout, sessionsOf } from "../sessions.js";
8
8
  import { sessionUsage, watcherClaudeUsage } from "../usage.js";
9
9
  import { CliError } from "../errors.js";
10
10
  import { branchAndHead, commitAtTime, ensureReviewWorktree, ensureWorktree, fetchRef, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, removeWorktreeIfClean, repoName, repoParent, verifyMergedCommit, verifyNoCommitsBeyondTarget, worktreeForBranch } from "../git.js";
11
- import { resolve } from "node:path";
11
+ import { join, resolve } from "node:path";
12
12
  import { table } from "../output.js";
13
+ import { restoreRecoveryArchive, sha256 as recoverySha256 } from "../recovery-archive.js";
14
+ import { createRecoveryArchive } from "../recovery-archive.js";
15
+ import { tmpdir } from "node:os";
13
16
  /** Only Claude's workspace-write sandbox needs SSH origins rewritten for its HTTP-only proxy. */
14
17
  export function shouldInheritClaudeSandboxUrlRewrites(env = process.env) {
15
18
  return env.CLAUDECODE === "1" && env.BSCHAT_CLAUDE_SANDBOX === "workspace-write";
16
19
  }
20
+ /** Antigravity has an independent sandbox marker; never infer it from Claude's environment. */
21
+ export function shouldInheritAntigravitySandboxUrlRewrites(env = process.env) {
22
+ return env.BSCHAT_HARNESS === "antigravity" && env.BSCHAT_ANTIGRAVITY_SANDBOX === "workspace-write";
23
+ }
24
+ export function shouldInheritSandboxUrlRewrites(env = process.env) {
25
+ return shouldInheritClaudeSandboxUrlRewrites(env) || shouldInheritAntigravitySandboxUrlRewrites(env);
26
+ }
17
27
  export function scopeEditFromArgs(p) {
18
28
  const replacement = bool(p.flags, "replace");
19
29
  const append = str(p.flags, "append");
@@ -39,6 +49,150 @@ export function scopeEditFromArgs(p) {
39
49
  export function scopeOnlyOutput(unit, only) {
40
50
  return only ? unit.scope : null;
41
51
  }
52
+ function jsonFlag(p, key, expected) {
53
+ const raw = str(p.flags, key);
54
+ if (raw === undefined)
55
+ return undefined;
56
+ try {
57
+ return JSON.parse(raw);
58
+ }
59
+ catch {
60
+ throw new CliError("usage", `--${key} must be JSON ${expected}`);
61
+ }
62
+ }
63
+ export function needsRetrospectiveInput(status, events = []) {
64
+ if (status === "changes_requested")
65
+ return true;
66
+ const lastSubmission = events.reduce((last, event, index) => ["submitted", "resubmitted", "refreshed"].includes(event.type) ? index : last, -1);
67
+ return events.slice(lastSubmission + 1).some((event) => event.type === "changes_requested");
68
+ }
69
+ function retrospectiveEventDetail(event) {
70
+ const data = event.data ?? {};
71
+ if (event.type === "changes_requested") {
72
+ const cause = data.cause ? `cause=${data.cause}` : "cause=unclassified";
73
+ const citation = data.unmet ? `; cited ${data.cited_from ?? "clause"}: ${JSON.stringify(data.unmet)}` : "; no clause citation (legacy or citation rule disabled)";
74
+ return ` [event ${event.id}; ${cause}${citation}]`;
75
+ }
76
+ if (["resubmitted", "refreshed"].includes(event.type)) {
77
+ const lesson = typeof data.lesson === "string" ? `; lesson: ${data.lesson}` : "";
78
+ const disputes = Array.isArray(data.disputes) ? data.disputes.map((d) => `disputes ${d.send_back_event_id} as ${d.cause}: ${d.reason}`).join("; ") : "";
79
+ return `${lesson}${disputes ? `; ${disputes}` : ""}`;
80
+ }
81
+ if (event.type === "note" && data.annotation)
82
+ return ` [assigner view on ${data.annotation.finding_event_id}: ${data.annotation.cause}; ${data.annotation.reason}]`;
83
+ if (event.type === "ruled" && data.retrospective_resolution)
84
+ return ` [resolved ${data.send_back_event_id} as ${data.cause}; ${event.note}]`;
85
+ if (event.type === "approved" && Array.isArray(data.retrospective_confirmation))
86
+ return ` [confirmed send-back causes: ${data.retrospective_confirmation.map((x) => `${x.reviewer_cause} → ${x.confirmed_cause} (${x.cited_from ?? "uncited"})`).join(", ")}]`;
87
+ if (event.type === "abandoned" && data.retrospective?.complete)
88
+ return ` [send-back retrospective finalized: ${data.retrospective.send_backs.length} recorded]`;
89
+ return "";
90
+ }
91
+ const GIT_FILE_LIMIT = 50 * 1024 * 1024;
92
+ const RECOVERY_LIMIT = 1024 * 1024 * 1024;
93
+ const regenerablePath = (path) => /(^|\/)(node_modules|target|dist|build|coverage|\.cache|\.next|\.turbo|__pycache__)(\/|$)/i.test(path);
94
+ function gitRun(cwd, args, extraEnv = {}) {
95
+ const result = spawnSync("git", args, { cwd, env: { ...process.env, ...extraEnv }, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
96
+ if (result.status !== 0)
97
+ throw new CliError("recovery_git_failed", `git ${args[0]} failed: ${result.stderr?.trim() || "unknown Git error"}`);
98
+ return result.stdout;
99
+ }
100
+ /** Pushes the branch tip even when there was no dirty work to turn into a WIP commit. */
101
+ export function pushCutoffBranch(cwd, branch) {
102
+ const pushed = spawnSync("git", ["push", "origin", `HEAD:refs/heads/${branch}`], { cwd, encoding: "utf8", maxBuffer: 2 * 1024 * 1024 });
103
+ if (pushed.status === 0)
104
+ return null;
105
+ return (pushed.stderr?.trim() || "git push failed").replace(/https?:\/\/[^\s/@]+:[^\s/@]+@/g, "https://[redacted]@").slice(0, 1000);
106
+ }
107
+ export function saveWipCommit(cwd, branch) {
108
+ const head = gitRun(cwd, ["rev-parse", "HEAD"]).trim();
109
+ const temp = mkdtempSync(join(tmpdir(), "b9s-recovery-index-"));
110
+ const index = join(temp, "index");
111
+ const extra = { GIT_INDEX_FILE: index };
112
+ try {
113
+ gitRun(cwd, ["read-tree", "HEAD"], extra);
114
+ gitRun(cwd, ["add", "-A"], extra);
115
+ const staged = gitRun(cwd, ["diff", "--cached", "--name-only", "-z"], extra).split("\0").filter(Boolean);
116
+ const oversized = staged.filter((path) => {
117
+ try {
118
+ return lstatSync(resolve(cwd, path)).isFile() && lstatSync(resolve(cwd, path)).size > GIT_FILE_LIMIT;
119
+ }
120
+ catch {
121
+ return false;
122
+ }
123
+ });
124
+ for (const path of oversized)
125
+ gitRun(cwd, ["update-index", "--force-remove", "--", path], extra);
126
+ if (spawnSync("git", ["diff", "--cached", "--quiet"], { cwd, env: { ...process.env, ...extra } }).status === 0)
127
+ return { commit: null, oversized };
128
+ const tree = gitRun(cwd, ["write-tree"], extra).trim();
129
+ const commit = gitRun(cwd, ["-c", "user.name=BenignSwarm cutoff", "-c", "user.email=cutoff@benignswarm.invalid", "commit-tree", tree, "-p", head, "-m", `Forced cutoff WIP save for ${branch}`]).trim();
130
+ gitRun(cwd, ["update-ref", `refs/heads/${branch}`, commit, head]);
131
+ return { commit, oversized };
132
+ }
133
+ finally {
134
+ rmSync(temp, { recursive: true, force: true });
135
+ }
136
+ }
137
+ export function createCutoffBundle(cwd, branch, oversized, pushError) {
138
+ const ignored = gitRun(cwd, ["ls-files", "--others", "--ignored", "--exclude-standard", "-z"]).split("\0").filter(Boolean);
139
+ const candidates = [...new Set([...ignored, ...oversized])].sort();
140
+ const files = [];
141
+ const omitted = [];
142
+ const skipped = [];
143
+ let total = 0;
144
+ for (const path of candidates) {
145
+ if (regenerablePath(path)) {
146
+ skipped.push({ path, reason: "regenerable build/cache output" });
147
+ continue;
148
+ }
149
+ try {
150
+ const stat = lstatSync(resolve(cwd, path));
151
+ if (!stat.isFile()) {
152
+ omitted.push({ path, reason: "not a regular file; operator must inspect it on the source volume" });
153
+ continue;
154
+ }
155
+ if (total + stat.size > RECOVERY_LIMIT) {
156
+ omitted.push({ path, reason: "recovery bundle reached the 1 GiB uncompressed safety bound" });
157
+ continue;
158
+ }
159
+ const bytes = new Uint8Array(readFileSync(resolve(cwd, path)));
160
+ files.push({ path, bytes });
161
+ total += bytes.length;
162
+ }
163
+ catch {
164
+ omitted.push({ path, reason: "file could not be read at cutoff" });
165
+ }
166
+ }
167
+ if (pushError) {
168
+ const temp = mkdtempSync(join(tmpdir(), "b9s-recovery-bundle-"));
169
+ try {
170
+ const bundle = join(temp, "local.bundle");
171
+ const made = spawnSync("git", ["bundle", "create", bundle, `refs/heads/${branch}`], { cwd, encoding: "utf8", maxBuffer: 1024 * 1024 });
172
+ if (made.status === 0) {
173
+ const bytes = new Uint8Array(readFileSync(bundle));
174
+ if (total + bytes.length <= RECOVERY_LIMIT) {
175
+ files.push({ path: "recovery/local.bundle", bytes });
176
+ total += bytes.length;
177
+ }
178
+ else
179
+ omitted.push({ path: "recovery/local.bundle", reason: "local Git bundle exceeded the 1 GiB recovery bound" });
180
+ }
181
+ else
182
+ omitted.push({ path: "recovery/local.bundle", reason: `git bundle failed: ${made.stderr?.trim().slice(0, 250) || "unknown Git error"}` });
183
+ }
184
+ finally {
185
+ rmSync(temp, { recursive: true, force: true });
186
+ }
187
+ }
188
+ let archive = createRecoveryArchive(files);
189
+ while (archive.length > RECOVERY_LIMIT && files.length) {
190
+ const removed = files.pop();
191
+ omitted.push({ path: removed.path, reason: "compressed recovery bundle exceeded the 1 GiB limit" });
192
+ archive = createRecoveryArchive(files);
193
+ }
194
+ return { archive, manifest: { captured: files.map(({ path, bytes }) => ({ path, size: bytes.length })), omitted, skipped } };
195
+ }
42
196
  export function assignmentDisposition(unit, to) {
43
197
  if (unit.status !== "queued")
44
198
  return `Assigned to ${unit.owner_name}; they start it with b9s wu start ${unit.number}.`;
@@ -374,7 +528,16 @@ export async function wu(p, out) {
374
528
  const evidenceIds = list("evidence"); // validated before anything talks to the server
375
529
  const def = await processDef();
376
530
  const where = branchAndHead();
377
- const unitTarget = (await client.call("GET", `${base}/${num()}`)).unit.target ?? def.merge.target_branch;
531
+ const submitRecord = await client.call("GET", `${base}/${num()}`);
532
+ const submitUnit = submitRecord.unit;
533
+ const unitTarget = submitUnit.target ?? def.merge.target_branch;
534
+ const lesson = str(p.flags, "lesson");
535
+ const disputes = jsonFlag(p, "disputes", "an array of dispute objects");
536
+ const retrospectiveDue = needsRetrospectiveInput(submitUnit.status, Array.isArray(submitRecord.events) ? submitRecord.events : []);
537
+ if (retrospectiveDue && !lesson?.trim())
538
+ throw new CliError("usage", 'resubmitting after a send-back requires --lesson "what would have let you get this right the first time?" (up to 280 characters)');
539
+ if (!retrospectiveDue && (lesson !== undefined || disputes !== undefined))
540
+ throw new CliError("usage", "--lesson and --disputes are only used when resubmitting after a send-back");
378
541
  let rebased = null;
379
542
  // The rebase requirement may come from the project or from a tag; the server tells us which
380
543
  // when it refuses. Check locally whenever we are in a repo so the claim is always a finding.
@@ -415,7 +578,7 @@ export async function wu(p, out) {
415
578
  process.stderr.write(`b9s: could not attach branch measure results: ${error.message}\n`);
416
579
  }
417
580
  }
418
- const payload = submitPayload({ evidence: evidenceIds, ...where, branch_values: branchValueIds, pr_url: pr, rebased, pushed, usage, expect: str(p.flags, "expect") }, !!def.review_rules?.length, unitTarget);
581
+ const payload = submitPayload({ evidence: evidenceIds, ...where, branch_values: branchValueIds, pr_url: pr, rebased, pushed, usage, expect: str(p.flags, "expect"), ...(lesson === undefined ? {} : { lesson }), ...(disputes === undefined ? {} : { disputes }) }, !!def.review_rules?.length, unitTarget);
419
582
  const r = await client.call("POST", `${base}/${num()}/submit`, payload);
420
583
  const u = r.unit;
421
584
  out.print(`${fmt(u)}\n${u.status === "classifying" ? `Waiting for ${u.reviewers[0]?.name} to classify it.` : `Routed to ${u.reviewers.map((x) => `@${x.name}`).join(", ")}; you will be told in chat when it is reviewed.`}${remoteCommitBranch ? `\n${formatRemoteCommitSuccess(remoteCommitBranch)}` : ""}`, r);
@@ -452,9 +615,13 @@ export async function wu(p, out) {
452
615
  const text = (p.positionals.slice(3).join(" ") || str(p.flags, sub === "ask" ? "question" : "ruling") || str(p.flags, "note") || "").trim();
453
616
  if (!text && !approve)
454
617
  throw new CliError("usage", sub === "ask" ? 'wu ask <n> "the decision this unit cannot move without" (works on queued units too)' : 'wu rule <n> "what was decided" | wu rule <n> --approve [--note ".."]');
455
- const r = await client.call("POST", `${base}/${num()}/${sub}`, sub === "ask" ? { question: text } : approve ? { approve: true, ruling: text } : { ruling: text });
618
+ const sendBackEvent = str(p.flags, "send-back-event");
619
+ const cause = str(p.flags, "cause");
620
+ if (sendBackEvent && (sub !== "rule" || !cause || !text))
621
+ throw new CliError("usage", 'wu rule <n> --send-back-event <event-id> --cause <cause> --ruling "decision"');
622
+ const r = await client.call("POST", `${base}/${num()}/${sub}`, sub === "ask" ? { question: text } : sendBackEvent ? { send_back_event_id: sendBackEvent, cause, ruling: text } : approve ? { approve: true, ruling: text } : { ruling: text });
456
623
  const q = r.unit.question;
457
- out.print(`${fmt(r.unit)}\n${sub === "rule" ? "Ruled; the asker, owner and reviewers were told." : q.level === "expert" ? `Asked a ${q.roles.join(" or ")}; it goes to the operator if nobody rules in time.` : "Asked the operator."}`, r);
624
+ out.print(`${fmt(r.unit)}\n${sendBackEvent ? "Retrospective ruling recorded on the unit; no chat message was added." : sub === "rule" ? "Ruled; the asker, owner and reviewers were told." : q.level === "expert" ? `Asked a ${q.roles.join(" or ")}; it goes to the operator if nobody rules in time.` : "Asked the operator."}`, r);
458
625
  return;
459
626
  }
460
627
  case "escalate": {
@@ -516,7 +683,10 @@ export async function wu(p, out) {
516
683
  const unmet = str(p.flags, "unmet");
517
684
  if (!note)
518
685
  throw new CliError("usage", sub === "changes" ? 'wu changes <n> --unmet "<the clause of its scope, exit criterion or agreements it fails, quoted>" --note "what must change"' : `wu ${sub} <n> --note "what you checked"`);
519
- const r = await client.call("POST", `${base}/${num()}/${sub}`, { note, ...(unmet ? { unmet } : {}) });
686
+ const cause = str(p.flags, "cause");
687
+ if (sub === "changes" && !cause)
688
+ throw new CliError("usage", 'wu changes <n> --cause <scope_gap|missing_context|worker_error|reviewer_scope_growth|environment|stale_base> --unmet "<cited clause>" --note "what must change"');
689
+ const r = await client.call("POST", `${base}/${num()}/${sub}`, { note, ...(unmet ? { unmet } : {}), ...(cause ? { cause } : {}), ...(sub === "approve" && p.flags["confirm-causes"] !== undefined ? { confirmed_causes: list("confirm-causes") } : {}) });
520
690
  out.print(fmt(r.unit), r);
521
691
  return;
522
692
  }
@@ -615,7 +785,8 @@ export async function wu(p, out) {
615
785
  return;
616
786
  }
617
787
  case "note": {
618
- const r = await client.call("POST", `${base}/${num()}/note`, { note: str(p.flags, "note") ?? "", evidence: list("evidence") });
788
+ const annotation = jsonFlag(p, "annotation", "an annotation object");
789
+ const r = await client.call("POST", `${base}/${num()}/note`, { note: str(p.flags, "note") ?? "", evidence: list("evidence"), ...(annotation ? { annotation } : {}) });
619
790
  out.print(fmt(r.unit), r);
620
791
  return;
621
792
  }
@@ -683,6 +854,72 @@ export async function wu(p, out) {
683
854
  out.print(`${fmt(unit)}${context ? `\n${context}` : ""}\nReview checkout: ${path} (detached at ${remote.slice(0, 9)}${made.created ? "" : ", already there"})${onTarget ? `\nThe submitted commit is already on origin/${target}: the unit added no commits, so its evidence is the work.` : ""}\n cd ${path}\nEvidence: ${ev} (b9s evidence get <id>)\nVerdict: b9s wu approve ${n} --note "..." | b9s wu changes ${n} --note "..."\nWhen finished: git worktree remove ${path}`, { unit, worktree: path, head: remote, measure_context: reviewDetail.measure_context });
684
855
  return;
685
856
  }
857
+ case "recovery": {
858
+ if (p.positionals[2] === "save") {
859
+ const n = Number(p.positionals[3]);
860
+ if (!Number.isSafeInteger(n) || n < 1)
861
+ throw new CliError("usage", "wu recovery save <unit> --reason \"cutoff reason\"");
862
+ const reason = str(p.flags, "reason");
863
+ if (!reason?.trim())
864
+ throw new CliError("usage", "wu recovery save <unit> --reason \"cutoff reason\"");
865
+ const cwd = process.cwd();
866
+ const { branch } = branchAndHead(cwd);
867
+ if (!branch)
868
+ throw new CliError("recovery_branch_missing", "run recovery save from the unit's own branch worktree");
869
+ const existing = await client.call("GET", `${base}/${n}`);
870
+ if (existing.unit.branch !== branch)
871
+ throw new CliError("recovery_branch_mismatch", `current branch ${branch} does not match WU #${n}'s pinned branch ${existing.unit.branch}`);
872
+ const begun = await client.call("POST", `${base}/${n}/recovery`, { cutoff_reason: reason.trim(), branch });
873
+ const id = begun.recovery.id;
874
+ try {
875
+ const saved = saveWipCommit(cwd, branch);
876
+ // A clean worktree can still have a local-only HEAD; always prove its ref reached origin.
877
+ const pushError = pushCutoffBranch(cwd, branch);
878
+ const { archive, manifest } = createCutoffBundle(cwd, branch, saved.oversized, pushError);
879
+ const manifestText = JSON.stringify(manifest);
880
+ if (manifestText.length > 200_000)
881
+ throw new CliError("recovery_manifest_too_large", "the omitted-file manifest exceeds the API limit; keep this volume and ask the operator to resolve it");
882
+ const response = await client.raw("POST", `${base}/${n}/recovery/${id}/upload`, archive.buffer.slice(archive.byteOffset, archive.byteOffset + archive.byteLength), {
883
+ "content-type": "application/octet-stream", "x-bschat-sha256": recoverySha256(archive),
884
+ "x-bschat-recovery-manifest": manifestText, "x-bschat-cutoff-reason": reason.trim(),
885
+ ...(saved.commit ? { "x-bschat-wip-commit": saved.commit } : {}), ...(pushError ? { "x-bschat-push-error": pushError } : {}),
886
+ });
887
+ const result = await response.json();
888
+ out.print(`Recovery bundle ${result.recovery.status}; WIP commit ${saved.commit ?? "not needed"}${pushError ? `; push failed: ${pushError}` : ""}. Keep the source volume until the API reports safe_to_delete.`, result);
889
+ }
890
+ catch (error) {
891
+ try {
892
+ await client.call("POST", `${base}/${n}/recovery/${id}/failure`, { failure: error.message.slice(0, 1500) });
893
+ }
894
+ catch { /* the original recovery error is the useful one */ }
895
+ throw error;
896
+ }
897
+ return;
898
+ }
899
+ if (p.positionals[2] !== "restore")
900
+ throw new CliError("usage", "wu recovery save <unit> --reason \"cutoff reason\" | restore <unit>");
901
+ const n = Number(p.positionals[3]);
902
+ if (!Number.isSafeInteger(n) || n < 1)
903
+ throw new CliError("usage", "wu recovery restore <unit>");
904
+ const metadata = await client.call("GET", `${base}/${n}/recovery`);
905
+ const recovery = metadata.recovery;
906
+ if (!recovery?.available)
907
+ throw new CliError("recovery_unavailable", `no verified recovery bundle is available for WU #${n}`);
908
+ if (!recovery.id || !recovery.sha256)
909
+ throw new CliError("bad_response", "recovery metadata is missing its identifier or checksum");
910
+ const unitResult = await client.call("GET", `${base}/${n}`);
911
+ const worktree = worktreeForBranch(unitResult.unit.branch);
912
+ if (!worktree)
913
+ throw new CliError("recovery_worktree_missing", `the worktree for ${unitResult.unit.branch} is not checked out; start WU #${n} with b9s wu start ${n} --branch ${unitResult.unit.branch}`);
914
+ const response = await client.raw("GET", `${base}/${n}/recovery/${recovery.id}/content`);
915
+ const bytes = new Uint8Array(await response.arrayBuffer());
916
+ const digest = recoverySha256(bytes);
917
+ if (digest !== recovery.sha256)
918
+ throw new CliError("recovery_checksum_mismatch", `downloaded recovery checksum is ${digest}; expected ${recovery.sha256}; no files were restored`);
919
+ const restored = await restoreRecoveryArchive(bytes, worktree);
920
+ out.print(`Restored ${restored.length} recovery file(s) into ${worktree}${recovery.manifest?.omitted?.length ? `\nUncaptured files remain: ${recovery.manifest.omitted.length}; the source volume must stay protected.` : ""}`, { restored, worktree, recovery });
921
+ return;
922
+ }
686
923
  case "show": {
687
924
  const r = await client.call("GET", `${base}/${num()}`);
688
925
  const onlyScope = scopeOnlyOutput(r.unit, bool(p.flags, "scope-only"));
@@ -690,9 +927,12 @@ export async function wu(p, out) {
690
927
  out.print(onlyScope, { scope: onlyScope });
691
928
  return;
692
929
  }
693
- const events = r.events.map((e) => ` ${e.at.slice(0, 16).replace("T", " ")} ${e.type.padEnd(18)} ${e.actor_name}${e.note ? `: ${e.note}` : ""}${e.data?.to && Array.isArray(e.data.to) ? ` -> ${e.data.to.join(", ")}` : ""}`).join("\n");
930
+ const events = r.events.map((e) => ` ${e.at.slice(0, 16).replace("T", " ")} ${e.type.padEnd(18)} ${e.actor_name}${e.note ? `: ${e.note}` : ""}${e.data?.to && Array.isArray(e.data.to) ? ` -> ${e.data.to.join(", ")}` : ""}${retrospectiveEventDetail(e)}`).join("\n");
931
+ const lessons = [...r.events].reverse().filter((e) => typeof e.data?.lesson === "string").map((e) => ` ${e.actor_name}: ${e.data.lesson}`).join("\n");
694
932
  const context = measureContextOutput(r.measure_context, r.unit.expected_effect, r.unit.measured_effect);
695
- out.print(`${fmt(r.unit)}${context ? `\n${context}` : ""}\n${events}`, r);
933
+ const recovery = r.unit.recovery;
934
+ const recoveryText = recovery ? `\nRecovery: ${recovery.available ? `available (${recovery.size ?? "?"} bytes, sha256 ${recovery.sha256 ?? "?"})` : "not verified"}${recovery.expires_at ? `; expires ${recovery.expires_at}` : ""}${recovery.manifest?.skipped?.length ? `; skipped ${recovery.manifest.skipped.length} regenerable path(s)` : ""}${recovery.manifest?.omitted?.length ? `; ${recovery.manifest.omitted.length} uncaptured path(s), source volume remains protected` : ""}${recovery.available ? `; restore: b9s wu recovery restore ${r.unit.number}` : ""}` : "";
935
+ out.print(`${fmt(r.unit)}${context ? `\n${context}` : ""}${lessons ? `\nWorker lessons (latest first):\n${lessons}` : ""}${recoveryText}\n${events}`, r);
696
936
  return;
697
937
  }
698
938
  case "list":
@@ -813,7 +1053,7 @@ function prepareWorktree(n, unit, def, p, exclude = []) {
813
1053
  branchCreated = true;
814
1054
  log(`created ${pinned} from origin/${pinned}`);
815
1055
  }
816
- const result = !existing ? ensureWorktree(path, pinned, baseRef, process.cwd(), log, exclude, shouldInheritClaudeSandboxUrlRewrites()) : { created: false };
1056
+ const result = !existing ? ensureWorktree(path, pinned, baseRef, process.cwd(), log, exclude, shouldInheritSandboxUrlRewrites()) : { created: false };
817
1057
  return { mode: "branch", path, branch: pinned, created: result.created, branchCreated };
818
1058
  }
819
1059
  const slug = String(unit.title).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
@@ -827,7 +1067,7 @@ function prepareWorktree(n, unit, def, p, exclude = []) {
827
1067
  baseRef = at;
828
1068
  }
829
1069
  const branchCreated = fullSha(branch) === null;
830
- const result = ensureWorktree(path, branch, baseRef, process.cwd(), log, exclude, shouldInheritClaudeSandboxUrlRewrites());
1070
+ const result = ensureWorktree(path, branch, baseRef, process.cwd(), log, exclude, shouldInheritSandboxUrlRewrites());
831
1071
  return { mode: "fresh", path, branch, created: result.created, branchCreated };
832
1072
  }
833
1073
  /** Select the replay commit from the same target ref used to create its worktree. */
package/dist/git.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { copyFileSync, existsSync, readdirSync, realpathSync, rmSync, statSync, statfsSync } from "node:fs";
2
2
  import { spawnSync } from "node:child_process";
3
3
  import { hostname } from "node:os";
4
- import { dirname, join } from "node:path";
4
+ import { dirname, isAbsolute, join, relative, sep } from "node:path";
5
5
  import { CliError } from "./errors.js";
6
6
  export const PRUNE_STATUS_TIMEOUT_MS = 30_000;
7
7
  function status(cwd, timeoutMs) {
@@ -162,10 +162,36 @@ export function createWorktree(path, branch, base, cwd = process.cwd(), exclude
162
162
  else
163
163
  applyFullCheckout(path);
164
164
  // Git copies config.worktree into linked worktrees. Strip inherited URL rewrites first so a
165
- // Claude-specific proxy workaround never leaks into Codex or full-access Claude worktrees.
165
+ // sandbox-specific proxy workarounds never leak into Codex or full-access worktrees.
166
166
  clearWorktreeUrlRewrites(path);
167
167
  if (inheritUrlRewrites)
168
168
  copyWorktreeUrlRewrites(cwd, path);
169
+ else
170
+ copyGitHubAppUrlRewrites(cwd, path);
171
+ }
172
+ /** Carry back only HTTPS rewrites paired with this product's linked-repository credential helper. */
173
+ function copyGitHubAppUrlRewrites(from, to) {
174
+ const helpers = spawnSync("git", ["config", "--worktree", "--get-regexp", "^credential\\.https://github\\.com/.+\\.helper$"], { cwd: from, encoding: "utf8" });
175
+ if (helpers.status !== 0)
176
+ return;
177
+ for (const line of helpers.stdout.split(/\r?\n/).filter(Boolean)) {
178
+ const split = line.indexOf(" ");
179
+ if (split < 0 || !/^!.*\s+git-credential$/.test(line.slice(split + 1)))
180
+ continue;
181
+ const helperKey = line.slice(0, split);
182
+ const repoUrl = helperKey.slice("credential.".length, -".helper".length);
183
+ if (!repoUrl.startsWith("https://github.com/"))
184
+ continue;
185
+ const rewriteKey = `url.${repoUrl}.insteadOf`;
186
+ const rewrites = spawnSync("git", ["config", "--worktree", "--get-all", rewriteKey], { cwd: from, encoding: "utf8" });
187
+ if (rewrites.status !== 0)
188
+ continue;
189
+ for (const value of rewrites.stdout.split(/\r?\n/).filter(Boolean)) {
190
+ const copied = spawnSync("git", ["config", "--worktree", "--add", rewriteKey, value], { cwd: to, encoding: "utf8" });
191
+ if (copied.status !== 0)
192
+ throw new Error(`could not preserve linked GitHub App transport in ${to}: ${(copied.stderr || copied.stdout).trim()}`);
193
+ }
194
+ }
169
195
  }
170
196
  /** Carry worktree-scoped URL rewrites to new unit worktrees so HTTPS proxy access survives `wu start`. */
171
197
  export function copyWorktreeUrlRewrites(from, to) {
@@ -340,11 +366,29 @@ export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map(), ac
340
366
  kept.push({ path: w.path, branch: w.branch, reason: "you are standing in it" });
341
367
  continue;
342
368
  }
369
+ const worktreePath = realpathOrSelf(w.path);
370
+ const use = options.inUse?.find((entry) => {
371
+ if (!isAbsolute(entry.path))
372
+ return false;
373
+ const usePath = realpathOrSelf(entry.path);
374
+ const rel = relative(worktreePath, usePath);
375
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
376
+ });
377
+ if (use) {
378
+ kept.push({ path: w.path, branch: w.branch, reason: `in use by ${use.agent}` });
379
+ continue;
380
+ }
381
+ const homeAgent = w.branch?.startsWith("home/") ? w.branch.slice("home/".length) : null;
382
+ const retiredHome = homeAgent !== null && options.retiredHomeAgents?.has(homeAgent);
383
+ if (homeAgent && !retiredHome) {
384
+ kept.push({ path: w.path, branch: w.branch, reason: `agent home for ${homeAgent} (not retired)` });
385
+ continue;
386
+ }
343
387
  // An agent's home checkout is never leftovers, whatever its branch: join/setup bind an identity
344
388
  // there (unit worktrees never get one). And a worktree made in the last day is too new to judge:
345
389
  // StickJoy's watcher removed a home checkout two minutes after it was created, before the agent
346
390
  // could bind it, because a fresh branch on main's head looks merged.
347
- if (existsSync(join(w.path, ".b9s", "identity.json")) || existsSync(join(w.path, ".bschat", "identity.json"))) {
391
+ if (!retiredHome && (existsSync(join(w.path, ".b9s", "identity.json")) || existsSync(join(w.path, ".bschat", "identity.json")))) {
348
392
  kept.push({ path: w.path, branch: w.branch, reason: "an agent's home checkout (it has a b9s identity file)" });
349
393
  continue;
350
394
  }