benignswarm 0.12.93 → 0.12.95

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.
@@ -7,7 +7,7 @@ import { applyAck } from "./wake.js";
7
7
  import { lingerEnabled, loadSystemdUnit, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
8
8
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
9
9
  import { createHash } from "node:crypto";
10
- import { homedir, uptime, userInfo } from "node:os";
10
+ import { homedir, userInfo } from "node:os";
11
11
  import { basename, dirname, join } from "node:path";
12
12
  import { bool, str } from "../args.js";
13
13
  import { configRoot, loadAgent, resolveAgentName } from "../config.js";
@@ -22,9 +22,10 @@ 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, DEFAULT_UNPRODUCTIVE_PER_HOUR, MAX_TURNS_PER_HOUR, MAX_UNPRODUCTIVE_TURNS } from "../turn-guard.js";
26
26
  import { sessionUsage } from "../usage.js";
27
27
  import { collectPruneProtection } from "../prune-protection.js";
28
+ import { bootTimeMs } from "../boot-time.js";
28
29
  function omitMeasuresAlreadyIn(text, updates) {
29
30
  if (!text)
30
31
  return updates;
@@ -70,10 +71,15 @@ export async function watch(p, out) {
70
71
  if (!Number.isInteger(turnTimeout) || turnTimeout < 5)
71
72
  throw new CliError("usage", "--turn-timeout must be a whole number of minutes, at least 5");
72
73
  const turnsPerHour = Number(str(p.flags, "turns-per-hour") ?? String(DEFAULT_TURNS_PER_HOUR));
73
- if (!Number.isInteger(turnsPerHour) || turnsPerHour < 1 || turnsPerHour > DEFAULT_TURNS_PER_HOUR)
74
- throw new CliError("usage", `--turns-per-hour must be a whole number between 1 and ${DEFAULT_TURNS_PER_HOUR}`);
74
+ if (!Number.isInteger(turnsPerHour) || turnsPerHour < 1 || turnsPerHour > MAX_TURNS_PER_HOUR)
75
+ throw new CliError("usage", `--turns-per-hour must be a whole number between 1 and ${MAX_TURNS_PER_HOUR}`);
76
+ const unproductivePerHour = Number(str(p.flags, "unproductive-per-hour") ?? String(DEFAULT_UNPRODUCTIVE_PER_HOUR));
77
+ if (!Number.isInteger(unproductivePerHour) || unproductivePerHour < 1 || unproductivePerHour > 60)
78
+ throw new CliError("usage", "--unproductive-per-hour must be a whole number between 1 and 60");
75
79
  if (!turnMode && p.flags["turns-per-hour"] !== undefined)
76
80
  throw new CliError("usage", "--turns-per-hour is only used with --turn");
81
+ if (!turnMode && p.flags["unproductive-per-hour"] !== undefined)
82
+ throw new CliError("usage", "--unproductive-per-hour is only used with --turn");
77
83
  const thread = exec ? threadOfExec(exec) : null;
78
84
  // Which harness runs the turns and the session they continue. Codex watchers installed before
79
85
  // 0.12.66 carry neither flag: their thread is in the exec command.
@@ -87,7 +93,7 @@ export async function watch(p, out) {
87
93
  throw new CliError("usage", "--turn runs the turn itself: --exec must be codex exec resume <thread-id> ... {text}, not codex queue");
88
94
  const named = str(p.flags, "harness") ?? (thread ? "codex" : undefined);
89
95
  if (!named)
90
- throw new CliError("usage", "--turn needs --harness <codex|claude-code|dsh> and --session <id> (a Codex exec resume command names its thread itself)");
96
+ throw new CliError("usage", "--turn needs --harness <codex|claude-code|dsh|antigravity> and --session <id> (a Codex exec resume command names its thread itself)");
91
97
  const harness = turnHarness(named);
92
98
  const session = (str(p.flags, "session") ?? (harness === "codex" ? thread : null))?.toLowerCase();
93
99
  if (!session)
@@ -98,7 +104,7 @@ export async function watch(p, out) {
98
104
  if (providerName === "deepseek" && harness !== "claude-code")
99
105
  throw new CliError("usage", "--provider deepseek requires --harness claude-code");
100
106
  const model = str(p.flags, "model") ?? (providerName === "deepseek" ? "deepseek-flash" : undefined);
101
- turn = { harness, session, timeout: turnTimeout, turnsPerHour, provider: providerName, model };
107
+ turn = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, provider: providerName, model };
102
108
  }
103
109
  else if (p.flags.provider !== undefined) {
104
110
  throw new CliError("usage", "--provider is only used with --turn --harness claude-code");
@@ -250,7 +256,7 @@ export async function watch(p, out) {
250
256
  await turnStep(ctl, probe, turnTimeout, log, async (sink, beforeTurn) => {
251
257
  const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, turn?.model ?? str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "claude-code" ? turn.provider : undefined, turn?.harness === "dsh", () => probe.beginTurn?.(), beforeTurn, turn?.harness === "claude-code" ? turn.session : undefined);
252
258
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
253
- }, name, turn?.turnsPerHour ?? turnsPerHour);
259
+ }, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour);
254
260
  else {
255
261
  const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, undefined, !resumeBriefDelivered);
256
262
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
@@ -533,7 +539,7 @@ const KEY_CHECK_MS = 5 * 60_000;
533
539
  * leaves the wake-up unacknowledged on the server, so a wake path that keeps failing shows as
534
540
  * broken; one that runs past --turn-timeout is stopped and logged.
535
541
  */
536
- export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = process.env) {
542
+ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
537
543
  const turn = ctl.turn;
538
544
  if (turn) {
539
545
  if (!turn.confirmed && probe.startedSince(turn.startedMs)) {
@@ -581,7 +587,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
581
587
  ctl.failedAt = Date.now();
582
588
  }
583
589
  ctl.turn = null;
584
- await completePendingTurnGuard(name, probe, log, undefined, env);
590
+ await completePendingTurnGuard(name, probe, log, undefined, undefined, env);
585
591
  return;
586
592
  }
587
593
  if (!turn.killedForTimeout && Date.now() - turn.startedMs > timeoutMin * 60_000) {
@@ -612,7 +618,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
612
618
  }
613
619
  if ("missing" in ph) {
614
620
  if (savedGuard?.turns.some((attempt) => attempt.productive === null)) {
615
- await completePendingTurnGuard(name, probe, log, undefined, env);
621
+ await completePendingTurnGuard(name, probe, log, undefined, undefined, env);
616
622
  if (readState(name, env).turn_guard?.fault)
617
623
  return;
618
624
  }
@@ -620,7 +626,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
620
626
  return;
621
627
  }
622
628
  if (!ph.running && savedGuard?.turns.some((attempt) => attempt.productive === null)) {
623
- await completePendingTurnGuard(name, probe, log, undefined, env);
629
+ await completePendingTurnGuard(name, probe, log, undefined, undefined, env);
624
630
  if (readState(name, env).turn_guard?.fault)
625
631
  return;
626
632
  }
@@ -646,8 +652,8 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
646
652
  }
647
653
  // A turn that started before this machine last booted died with it: no process survives a
648
654
  // reboot, and waiting out the quiet limit would idle the agent for up to --turn-timeout.
649
- const bootedAt = ph.running ? Date.now() - uptime() * 1000 : 0;
650
- if (ph.running && ph.startedAt && Date.parse(ph.startedAt) < bootedAt) {
655
+ const bootedAt = ph.running ? bootTimeMs() : null;
656
+ if (ph.running && ph.startedAt && bootedAt !== null && Date.parse(ph.startedAt) < bootedAt) {
651
657
  if (ctl.loggedRunning !== `boot:${ph.startedAt}`)
652
658
  log(`the turn started at ${ph.startedAt} was cut off when this machine restarted (booted ${new Date(bootedAt).toISOString()}); treating it as ended`);
653
659
  ctl.loggedRunning = `boot:${ph.startedAt}`;
@@ -687,7 +693,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
687
693
  writeState(name, { ...st, watch_pending: undefined, watch_dormant_logged_at: undefined }, env);
688
694
  }
689
695
  await wake((t) => { ctl.turn = t; }, async () => {
690
- return beginTurnGuardAttempt(name, turnsPerHour, log, env);
696
+ return beginTurnGuardAttempt(name, turnsPerHour, log, env, unproductivePerHour);
691
697
  });
692
698
  }
693
699
  async function turnActivity(name, env) {
@@ -697,25 +703,25 @@ async function turnActivity(name, env) {
697
703
  return snapshot;
698
704
  }
699
705
  /** Reserve every actual harness launch, including b9s start's onboarding turn. */
700
- export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = process.env) {
706
+ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
701
707
  const before = await turnActivity(name, env);
702
708
  const current = readState(name, env);
703
709
  if (current.turn_guard?.fault) {
704
710
  log(`TURN MODE FAULT: ${turnFaultSummary(current.turn_guard.fault)}; no further turns until an operator or assigner resumes this session`);
705
711
  return false;
706
712
  }
707
- const begun = beginGuardedTurn(current.turn_guard, turnsPerHour, Date.now(), before.activity_seq);
713
+ const begun = beginGuardedTurn(current.turn_guard, turnsPerHour, Date.now(), before.activity_seq, unproductivePerHour);
708
714
  writeState(name, { ...current, turn_guard: begun.state }, env);
709
715
  if (!begun.start) {
710
- log(`TURN MODE FAULT: ${turnFaultSummary(begun.state.fault)}; no further turns until an operator or assigner resumes this session`);
716
+ if (begun.state.fault)
717
+ log(`TURN MODE FAULT: ${turnFaultSummary(begun.state.fault)}; no further turns until an operator or assigner resumes this session`);
718
+ else
719
+ log(`TURN MODE BUSY, NOT LOOPING: ${begun.state.turns.length}/${turnsPerHour} turns in the rolling hour; estimated tokens spent: ${begun.state.turns.reduce((sum, turn) => sum + turn.estimated_tokens, 0)}; resumes at ${new Date(begun.pause_until).toISOString()}`);
711
720
  return false;
712
721
  }
713
722
  return true;
714
723
  }
715
- export async function completePendingTurnGuard(name, probe, log, outputOverride, tokenOverrideOrEnv, envOverride = process.env) {
716
- // The watcher passes its isolated environment; start-turn callers may pass measured tokens.
717
- const env = tokenOverrideOrEnv !== null && typeof tokenOverrideOrEnv === "object" ? tokenOverrideOrEnv : envOverride;
718
- const tokenOverride = tokenOverrideOrEnv === null || typeof tokenOverrideOrEnv === "number" ? tokenOverrideOrEnv : undefined;
724
+ export async function completePendingTurnGuard(name, probe, log, outputOverride, tokenOverride, env = process.env) {
719
725
  const current = readState(name, env);
720
726
  const guard = current.turn_guard;
721
727
  const pending = guard?.turns.slice().reverse().find((attempt) => attempt.productive === null);
@@ -769,7 +775,7 @@ export async function completePendingTurnGuard(name, probe, log, outputOverride,
769
775
  log("turn was productive: an agent-key call reached BenignSwarm");
770
776
  }
771
777
  function turnFaultSummary(fault) {
772
- return `${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns made no BenignSwarm call` : `hourly ceiling reached (${fault.turns_last_hour} turns in the last hour)`}; likely cause: ${fault.likely_cause}; estimated tokens spent: ${fault.estimated_tokens}`;
778
+ return `${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns made no BenignSwarm call` : `${fault.unproductive_last_hour} unproductive turns in the rolling hour`}; likely cause: ${fault.likely_cause}; estimated tokens spent: ${fault.estimated_tokens}`;
773
779
  }
774
780
  /** The watcher acknowledges a turn it started: the session shows the agent has the prompt. */
775
781
  async function ackTurn(name, seq, log, env = process.env) {
@@ -893,7 +899,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
893
899
  bindSession(sess.kind, sess.id, name);
894
900
  out.print(`Wrote ${path} and (re)loaded it: the watcher is running ${program[0]}.${Object.keys(extraEnv).length ? `\nCaptured env: ${Object.keys(extraEnv).join(", ")} (re-run this command if the harness restarts and these change)` : ""}\nStop it: launchctl bootout gui/$(id -u)/${label}\nLogs: ${logDir}/watch.${slug}.*.log\nCheck it: b9s doctor\nThe watcher runs from ${process.cwd()} so the repo identity file applies.`, { plist: path, label, program: program[0] });
895
901
  }
896
- const turnArgs = (t) => (t ? ["--turn", "--turn-timeout", String(t.timeout), "--turns-per-hour", String(t.turnsPerHour), "--harness", t.harness, "--session", t.session, ...(t.provider === "deepseek" ? ["--provider", t.provider] : []), ...(t.model ? ["--model", t.model] : [])] : []);
902
+ const turnArgs = (t) => (t ? ["--turn", "--turn-timeout", String(t.timeout), "--turns-per-hour", String(t.turnsPerHour), "--unproductive-per-hour", String(t.unproductivePerHour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--harness", t.harness, "--session", t.session, ...(t.provider === "deepseek" ? ["--provider", t.provider] : []), ...(t.model ? ["--model", t.model] : [])] : []);
897
903
  function escapeXml(s) {
898
904
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
899
905
  }
@@ -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");
@@ -56,6 +66,11 @@ export function needsRetrospectiveInput(status, events = []) {
56
66
  const lastSubmission = events.reduce((last, event, index) => ["submitted", "resubmitted", "refreshed"].includes(event.type) ? index : last, -1);
57
67
  return events.slice(lastSubmission + 1).some((event) => event.type === "changes_requested");
58
68
  }
69
+ export function assignmentGuidanceOutput(warnings = []) {
70
+ return warnings.length
71
+ ? `\nScope checks and assignment suggestions (advisory; no changes applied):\n${warnings.map((warning) => `- ${warning}`).join("\n")}`
72
+ : "";
73
+ }
59
74
  function retrospectiveEventDetail(event) {
60
75
  const data = event.data ?? {};
61
76
  if (event.type === "changes_requested") {
@@ -78,6 +93,111 @@ function retrospectiveEventDetail(event) {
78
93
  return ` [send-back retrospective finalized: ${data.retrospective.send_backs.length} recorded]`;
79
94
  return "";
80
95
  }
96
+ const GIT_FILE_LIMIT = 50 * 1024 * 1024;
97
+ const RECOVERY_LIMIT = 1024 * 1024 * 1024;
98
+ const regenerablePath = (path) => /(^|\/)(node_modules|target|dist|build|coverage|\.cache|\.next|\.turbo|__pycache__)(\/|$)/i.test(path);
99
+ function gitRun(cwd, args, extraEnv = {}) {
100
+ const result = spawnSync("git", args, { cwd, env: { ...process.env, ...extraEnv }, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
101
+ if (result.status !== 0)
102
+ throw new CliError("recovery_git_failed", `git ${args[0]} failed: ${result.stderr?.trim() || "unknown Git error"}`);
103
+ return result.stdout;
104
+ }
105
+ /** Pushes the branch tip even when there was no dirty work to turn into a WIP commit. */
106
+ export function pushCutoffBranch(cwd, branch) {
107
+ const pushed = spawnSync("git", ["push", "origin", `HEAD:refs/heads/${branch}`], { cwd, encoding: "utf8", maxBuffer: 2 * 1024 * 1024 });
108
+ if (pushed.status === 0)
109
+ return null;
110
+ return (pushed.stderr?.trim() || "git push failed").replace(/https?:\/\/[^\s/@]+:[^\s/@]+@/g, "https://[redacted]@").slice(0, 1000);
111
+ }
112
+ export function saveWipCommit(cwd, branch) {
113
+ const head = gitRun(cwd, ["rev-parse", "HEAD"]).trim();
114
+ const temp = mkdtempSync(join(tmpdir(), "b9s-recovery-index-"));
115
+ const index = join(temp, "index");
116
+ const extra = { GIT_INDEX_FILE: index };
117
+ try {
118
+ gitRun(cwd, ["read-tree", "HEAD"], extra);
119
+ gitRun(cwd, ["add", "-A"], extra);
120
+ const staged = gitRun(cwd, ["diff", "--cached", "--name-only", "-z"], extra).split("\0").filter(Boolean);
121
+ const oversized = staged.filter((path) => {
122
+ try {
123
+ return lstatSync(resolve(cwd, path)).isFile() && lstatSync(resolve(cwd, path)).size > GIT_FILE_LIMIT;
124
+ }
125
+ catch {
126
+ return false;
127
+ }
128
+ });
129
+ for (const path of oversized)
130
+ gitRun(cwd, ["update-index", "--force-remove", "--", path], extra);
131
+ if (spawnSync("git", ["diff", "--cached", "--quiet"], { cwd, env: { ...process.env, ...extra } }).status === 0)
132
+ return { commit: null, oversized };
133
+ const tree = gitRun(cwd, ["write-tree"], extra).trim();
134
+ 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();
135
+ gitRun(cwd, ["update-ref", `refs/heads/${branch}`, commit, head]);
136
+ return { commit, oversized };
137
+ }
138
+ finally {
139
+ rmSync(temp, { recursive: true, force: true });
140
+ }
141
+ }
142
+ export function createCutoffBundle(cwd, branch, oversized, pushError) {
143
+ const ignored = gitRun(cwd, ["ls-files", "--others", "--ignored", "--exclude-standard", "-z"]).split("\0").filter(Boolean);
144
+ const candidates = [...new Set([...ignored, ...oversized])].sort();
145
+ const files = [];
146
+ const omitted = [];
147
+ const skipped = [];
148
+ let total = 0;
149
+ for (const path of candidates) {
150
+ if (regenerablePath(path)) {
151
+ skipped.push({ path, reason: "regenerable build/cache output" });
152
+ continue;
153
+ }
154
+ try {
155
+ const stat = lstatSync(resolve(cwd, path));
156
+ if (!stat.isFile()) {
157
+ omitted.push({ path, reason: "not a regular file; operator must inspect it on the source volume" });
158
+ continue;
159
+ }
160
+ if (total + stat.size > RECOVERY_LIMIT) {
161
+ omitted.push({ path, reason: "recovery bundle reached the 1 GiB uncompressed safety bound" });
162
+ continue;
163
+ }
164
+ const bytes = new Uint8Array(readFileSync(resolve(cwd, path)));
165
+ files.push({ path, bytes });
166
+ total += bytes.length;
167
+ }
168
+ catch {
169
+ omitted.push({ path, reason: "file could not be read at cutoff" });
170
+ }
171
+ }
172
+ if (pushError) {
173
+ const temp = mkdtempSync(join(tmpdir(), "b9s-recovery-bundle-"));
174
+ try {
175
+ const bundle = join(temp, "local.bundle");
176
+ const made = spawnSync("git", ["bundle", "create", bundle, `refs/heads/${branch}`], { cwd, encoding: "utf8", maxBuffer: 1024 * 1024 });
177
+ if (made.status === 0) {
178
+ const bytes = new Uint8Array(readFileSync(bundle));
179
+ if (total + bytes.length <= RECOVERY_LIMIT) {
180
+ files.push({ path: "recovery/local.bundle", bytes });
181
+ total += bytes.length;
182
+ }
183
+ else
184
+ omitted.push({ path: "recovery/local.bundle", reason: "local Git bundle exceeded the 1 GiB recovery bound" });
185
+ }
186
+ else
187
+ omitted.push({ path: "recovery/local.bundle", reason: `git bundle failed: ${made.stderr?.trim().slice(0, 250) || "unknown Git error"}` });
188
+ }
189
+ finally {
190
+ rmSync(temp, { recursive: true, force: true });
191
+ }
192
+ }
193
+ let archive = createRecoveryArchive(files);
194
+ while (archive.length > RECOVERY_LIMIT && files.length) {
195
+ const removed = files.pop();
196
+ omitted.push({ path: removed.path, reason: "compressed recovery bundle exceeded the 1 GiB limit" });
197
+ archive = createRecoveryArchive(files);
198
+ }
199
+ return { archive, manifest: { captured: files.map(({ path, bytes }) => ({ path, size: bytes.length })), omitted, skipped } };
200
+ }
81
201
  export function assignmentDisposition(unit, to) {
82
202
  if (unit.status !== "queued")
83
203
  return `Assigned to ${unit.owner_name}; they start it with b9s wu start ${unit.number}.`;
@@ -106,6 +226,8 @@ export function waitPayload(on, clear, note, partial = "") {
106
226
  * b9s wu classify <n> --tags a,b [--note ...] classifier role only, when the process has that step
107
227
  * b9s wu tags <n> --add a,b --remove c [--note ...] owner before review, a reviewer during it
108
228
  * b9s wu done <n> --merged <sha> after approval; the sha is checked against the target branch
229
+ * b9s wu merge <n> [--note "..."] request the role-checked hosted merge; API only, no local Git state
230
+ * b9s wu merge status <n> read hosted merge operation and audit status
109
231
  * b9s wu abandon <n> [--note ...]
110
232
  * b9s wu note <n> --note "..." [--evidence id]
111
233
  * b9s wu evidence replace <n> <old> <new> [--note "why"]
@@ -331,7 +453,7 @@ export async function wu(p, out) {
331
453
  const scope = await scopeText();
332
454
  const replay = str(p.flags, "replay-of");
333
455
  const r = await client.call("POST", `${base}/assign`, { to, title, scope, tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: str(p.flags, "branch") ?? null, target: str(p.flags, "target") ?? null, milestone: str(p.flags, "milestone") ?? null, min_tier: str(p.flags, "tier"), hold: !!p.flags.hold, force: bool(p.flags, "force"), ...(reason === undefined ? {} : { reason }), ...(allowLowerTier ? { allow_lower_tier: true } : {}) });
334
- out.print(`${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${allowLowerTier ? `\nLower-tier override reason supplied: ${reason.trim()}` : ""}${r.warnings?.length ? `\nScope warnings:\n${r.warnings.map((w) => `- ${w}`).join("\n")}` : ""}`, r);
456
+ out.print(`${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${allowLowerTier ? `\nLower-tier override reason supplied: ${reason.trim()}` : ""}${assignmentGuidanceOutput(r.warnings ?? [])}`, r);
335
457
  return;
336
458
  }
337
459
  case "park": {
@@ -657,6 +779,24 @@ export async function wu(p, out) {
657
779
  out.print(fmt(r.unit) + (verifiedRemoteTarget ? `\nverified on ${verifiedRemoteTarget}` : "") + cleanupUnitWorktree(r.unit.worktree, def, !!p.flags["keep-worktree"]), r);
658
780
  return;
659
781
  }
782
+ case "merge": {
783
+ const statusOnly = p.positionals[2] === "status";
784
+ const rawNumber = statusOnly ? p.positionals[3] : p.positionals[2];
785
+ const unitNumber = Number(rawNumber);
786
+ if (!Number.isInteger(unitNumber) || unitNumber < 1)
787
+ throw new CliError("usage", `wu merge ${statusOnly ? "status " : ""}<number>`);
788
+ const path = `${base}/${unitNumber}/merge`;
789
+ const r = statusOnly
790
+ ? await client.call("GET", path)
791
+ : await client.call("POST", path, { ...(str(p.flags, "note") !== undefined ? { note: str(p.flags, "note") } : {}) });
792
+ const operation = r.operation;
793
+ const unit = r.unit;
794
+ const detail = operation
795
+ ? `Hosted merge #${unitNumber}: ${operation.state}${operation.merge_sha ? ` (${operation.merge_sha})` : ""}${operation.error_code ? `; ${operation.error_code}` : ""}`
796
+ : `Hosted merge #${unitNumber}: no merge operation recorded`;
797
+ out.print(`${detail}${unit ? `\nWU #${unitNumber} [${unit.status}]${unit.merged_sha ? ` · merged ${unit.merged_sha}` : ""}` : ""}`, r);
798
+ return;
799
+ }
660
800
  case "abandon": {
661
801
  const r = await client.call("POST", `${base}/${num()}/abandon`, { note: str(p.flags, "note") ?? "" });
662
802
  // Same as done: a clean worktree goes (its branch, and every commit on it, stays).
@@ -739,6 +879,72 @@ export async function wu(p, out) {
739
879
  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 });
740
880
  return;
741
881
  }
882
+ case "recovery": {
883
+ if (p.positionals[2] === "save") {
884
+ const n = Number(p.positionals[3]);
885
+ if (!Number.isSafeInteger(n) || n < 1)
886
+ throw new CliError("usage", "wu recovery save <unit> --reason \"cutoff reason\"");
887
+ const reason = str(p.flags, "reason");
888
+ if (!reason?.trim())
889
+ throw new CliError("usage", "wu recovery save <unit> --reason \"cutoff reason\"");
890
+ const cwd = process.cwd();
891
+ const { branch } = branchAndHead(cwd);
892
+ if (!branch)
893
+ throw new CliError("recovery_branch_missing", "run recovery save from the unit's own branch worktree");
894
+ const existing = await client.call("GET", `${base}/${n}`);
895
+ if (existing.unit.branch !== branch)
896
+ throw new CliError("recovery_branch_mismatch", `current branch ${branch} does not match WU #${n}'s pinned branch ${existing.unit.branch}`);
897
+ const begun = await client.call("POST", `${base}/${n}/recovery`, { cutoff_reason: reason.trim(), branch });
898
+ const id = begun.recovery.id;
899
+ try {
900
+ const saved = saveWipCommit(cwd, branch);
901
+ // A clean worktree can still have a local-only HEAD; always prove its ref reached origin.
902
+ const pushError = pushCutoffBranch(cwd, branch);
903
+ const { archive, manifest } = createCutoffBundle(cwd, branch, saved.oversized, pushError);
904
+ const manifestText = JSON.stringify(manifest);
905
+ if (manifestText.length > 200_000)
906
+ 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");
907
+ const response = await client.raw("POST", `${base}/${n}/recovery/${id}/upload`, archive.buffer.slice(archive.byteOffset, archive.byteOffset + archive.byteLength), {
908
+ "content-type": "application/octet-stream", "x-bschat-sha256": recoverySha256(archive),
909
+ "x-bschat-recovery-manifest": manifestText, "x-bschat-cutoff-reason": reason.trim(),
910
+ ...(saved.commit ? { "x-bschat-wip-commit": saved.commit } : {}), ...(pushError ? { "x-bschat-push-error": pushError } : {}),
911
+ });
912
+ const result = await response.json();
913
+ 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);
914
+ }
915
+ catch (error) {
916
+ try {
917
+ await client.call("POST", `${base}/${n}/recovery/${id}/failure`, { failure: error.message.slice(0, 1500) });
918
+ }
919
+ catch { /* the original recovery error is the useful one */ }
920
+ throw error;
921
+ }
922
+ return;
923
+ }
924
+ if (p.positionals[2] !== "restore")
925
+ throw new CliError("usage", "wu recovery save <unit> --reason \"cutoff reason\" | restore <unit>");
926
+ const n = Number(p.positionals[3]);
927
+ if (!Number.isSafeInteger(n) || n < 1)
928
+ throw new CliError("usage", "wu recovery restore <unit>");
929
+ const metadata = await client.call("GET", `${base}/${n}/recovery`);
930
+ const recovery = metadata.recovery;
931
+ if (!recovery?.available)
932
+ throw new CliError("recovery_unavailable", `no verified recovery bundle is available for WU #${n}`);
933
+ if (!recovery.id || !recovery.sha256)
934
+ throw new CliError("bad_response", "recovery metadata is missing its identifier or checksum");
935
+ const unitResult = await client.call("GET", `${base}/${n}`);
936
+ const worktree = worktreeForBranch(unitResult.unit.branch);
937
+ if (!worktree)
938
+ 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}`);
939
+ const response = await client.raw("GET", `${base}/${n}/recovery/${recovery.id}/content`);
940
+ const bytes = new Uint8Array(await response.arrayBuffer());
941
+ const digest = recoverySha256(bytes);
942
+ if (digest !== recovery.sha256)
943
+ throw new CliError("recovery_checksum_mismatch", `downloaded recovery checksum is ${digest}; expected ${recovery.sha256}; no files were restored`);
944
+ const restored = await restoreRecoveryArchive(bytes, worktree);
945
+ 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 });
946
+ return;
947
+ }
742
948
  case "show": {
743
949
  const r = await client.call("GET", `${base}/${num()}`);
744
950
  const onlyScope = scopeOnlyOutput(r.unit, bool(p.flags, "scope-only"));
@@ -749,7 +955,9 @@ export async function wu(p, out) {
749
955
  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");
750
956
  const lessons = [...r.events].reverse().filter((e) => typeof e.data?.lesson === "string").map((e) => ` ${e.actor_name}: ${e.data.lesson}`).join("\n");
751
957
  const context = measureContextOutput(r.measure_context, r.unit.expected_effect, r.unit.measured_effect);
752
- out.print(`${fmt(r.unit)}${context ? `\n${context}` : ""}${lessons ? `\nWorker lessons (latest first):\n${lessons}` : ""}\n${events}`, r);
958
+ const recovery = r.unit.recovery;
959
+ 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}` : ""}` : "";
960
+ out.print(`${fmt(r.unit)}${context ? `\n${context}` : ""}${lessons ? `\nWorker lessons (latest first):\n${lessons}` : ""}${recoveryText}\n${events}`, r);
753
961
  return;
754
962
  }
755
963
  case "list":
@@ -766,7 +974,7 @@ export async function wu(p, out) {
766
974
  return;
767
975
  }
768
976
  default:
769
- throw new CliError("usage", "wu open|assign|start [--branch b|--here]|decline|submit|approve|changes|classify|tags|done [--keep-worktree]|abandon|note|ask|rule|propose|show|list");
977
+ throw new CliError("usage", "wu open|assign|start [--branch b|--here]|decline|submit|approve|changes|classify|tags|merge <n>|merge status <n>|done [--keep-worktree]|abandon|note|ask|rule|propose|show|list");
770
978
  }
771
979
  }
772
980
  /** Queued units have no owner; ask the API to reject before any local worktree is made. */
@@ -870,7 +1078,7 @@ function prepareWorktree(n, unit, def, p, exclude = []) {
870
1078
  branchCreated = true;
871
1079
  log(`created ${pinned} from origin/${pinned}`);
872
1080
  }
873
- const result = !existing ? ensureWorktree(path, pinned, baseRef, process.cwd(), log, exclude, shouldInheritClaudeSandboxUrlRewrites()) : { created: false };
1081
+ const result = !existing ? ensureWorktree(path, pinned, baseRef, process.cwd(), log, exclude, shouldInheritSandboxUrlRewrites()) : { created: false };
874
1082
  return { mode: "branch", path, branch: pinned, created: result.created, branchCreated };
875
1083
  }
876
1084
  const slug = String(unit.title).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
@@ -884,7 +1092,7 @@ function prepareWorktree(n, unit, def, p, exclude = []) {
884
1092
  baseRef = at;
885
1093
  }
886
1094
  const branchCreated = fullSha(branch) === null;
887
- const result = ensureWorktree(path, branch, baseRef, process.cwd(), log, exclude, shouldInheritClaudeSandboxUrlRewrites());
1095
+ const result = ensureWorktree(path, branch, baseRef, process.cwd(), log, exclude, shouldInheritSandboxUrlRewrites());
888
1096
  return { mode: "fresh", path, branch, created: result.created, branchCreated };
889
1097
  }
890
1098
  /** Select the replay commit from the same target ref used to create its worktree. */
package/dist/git.js CHANGED
@@ -58,19 +58,26 @@ export function scanWorktrees(cwd = process.cwd(), options = {}) {
58
58
  const list = git(["worktree", "list", "--porcelain"], cwd);
59
59
  if (list === null)
60
60
  return null;
61
- const paths = list.split("\n").filter((l) => l.startsWith("worktree ")).map((l) => l.slice(9));
62
- if (!paths.length)
61
+ const entries = list.split(/\n\n/).map((block) => {
62
+ const lines = block.split("\n");
63
+ const worktree = lines.find((line) => line.startsWith("worktree "));
64
+ if (!worktree)
65
+ return null;
66
+ const lock = lines.find((line) => line === "locked" || line.startsWith("locked "));
67
+ return { path: worktree.slice(9), locked: lock ? lock.slice("locked".length).trim() || "locked" : null };
68
+ }).filter((entry) => entry !== null);
69
+ if (!entries.length)
63
70
  return null;
64
- const repo = paths[0];
71
+ const repo = entries[0].path;
65
72
  options.onProgress?.(`Scanning repository ${repo}`);
66
- const worktrees = paths.map((p) => {
73
+ const worktrees = entries.map(({ path: p, locked }) => {
67
74
  options.onProgress?.(`Scanning worktree ${p}`);
68
75
  const branch = git(["symbolic-ref", "--short", "-q", "HEAD"], p) ?? git(["rev-parse", "--short", "HEAD"], p);
69
76
  const head = git(["rev-parse", "--short", "HEAD"], p);
70
77
  const worktreeStatus = status(p, options.statusTimeoutMs);
71
78
  const f = head ? mergeFacts(p, p) : { base: null, merged: null, ahead: null };
72
79
  const empty = existsSync(p) && readdirSync(p).every((e) => e === ".git");
73
- return { path: p, branch, head, dirty: worktreeStatus === null ? null : worktreeStatus.length > 0, base: f.base, merged: f.merged, ahead: f.ahead, empty };
80
+ return { path: p, branch, head, dirty: worktreeStatus === null ? null : worktreeStatus.length > 0, base: f.base, merged: f.merged, ahead: f.ahead, empty, locked };
74
81
  });
75
82
  return { repo, worktrees };
76
83
  }
@@ -162,7 +169,7 @@ export function createWorktree(path, branch, base, cwd = process.cwd(), exclude
162
169
  else
163
170
  applyFullCheckout(path);
164
171
  // 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.
172
+ // sandbox-specific proxy workarounds never leak into Codex or full-access worktrees.
166
173
  clearWorktreeUrlRewrites(path);
167
174
  if (inheritUrlRewrites)
168
175
  copyWorktreeUrlRewrites(cwd, path);
@@ -366,6 +373,13 @@ export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map(), ac
366
373
  kept.push({ path: w.path, branch: w.branch, reason: "you are standing in it" });
367
374
  continue;
368
375
  }
376
+ // Git locks are an explicit operator/agent retention request. Preserve the reason in both
377
+ // report modes; an interrupted add's `locked: initializing` still follows the empty-checkout
378
+ // cleanup path below.
379
+ if (w.locked && !/^initializing\b/i.test(w.locked)) {
380
+ kept.push({ path: w.path, branch: w.branch, reason: `locked: ${w.locked}` });
381
+ continue;
382
+ }
369
383
  const worktreePath = realpathOrSelf(w.path);
370
384
  const use = options.inUse?.find((entry) => {
371
385
  if (!isAbsolute(entry.path))
package/dist/harnesses.js CHANGED
@@ -7,21 +7,22 @@ import { configRoot } from "./config.js";
7
7
  import { readState, writeState } from "./state.js";
8
8
  import { codexArchivedRollout, codexRollout } from "./sessions.js";
9
9
  import { codexTurnPhase, usageLimitUntil } from "./turn.js";
10
+ import { antigravityProbe } from "./antigravity.js";
10
11
  /**
11
12
  * Harnesses a machine can run headless in turn mode (docs/REMOTE-MACHINES.md, "Harness adapters").
12
13
  * Each adapter says how to start a session, what one turn's command is, whether a turn is running in
13
14
  * that session (by anyone: an app, a terminal, a turn left by a watcher that restarted), and how the
14
- * last turn ended. Antigravity is a desktop application with no headless turn and stays hand-run;
15
- * Gemini CLI no longer accepts personal logins (Google moved individuals to Antigravity).
15
+ * last turn ended. Antigravity uses its `agy` CLI and cached login; Gemini CLI no longer accepts
16
+ * personal logins (Google moved individuals to Antigravity).
16
17
  */
17
- export const TURN_HARNESSES = ["codex", "claude-code", "dsh"];
18
+ export const TURN_HARNESSES = ["codex", "claude-code", "dsh", "antigravity"];
18
19
  export function turnHarness(h) {
19
20
  if (TURN_HARNESSES.includes(h))
20
21
  return h;
21
22
  throw new CliError("unsupported", `harness ${h} cannot run headless turns; supported: ${TURN_HARNESSES.join(", ")}`);
22
23
  }
23
- export const HARNESS_LABEL = { codex: "Codex", "claude-code": "Claude Code", dsh: "DeepSeek Harness" };
24
- export const HARNESS_BIN = { codex: "codex", "claude-code": "claude", dsh: "dsh" };
24
+ export const HARNESS_LABEL = { codex: "Codex", "claude-code": "Claude Code", dsh: "DeepSeek Harness", antigravity: "Antigravity" };
25
+ export const HARNESS_BIN = { codex: "codex", "claude-code": "claude", dsh: "dsh", antigravity: "agy" };
25
26
  /** Node's fetch ignores the sandbox's HTTP(S)_PROXY unless this opt-in is present. */
26
27
  export function claudeSandboxEnv(sandbox) {
27
28
  return sandbox === "workspace-write" ? { NODE_USE_ENV_PROXY: "1", BSCHAT_CLAUDE_SANDBOX: "workspace-write" } : {};
@@ -117,7 +118,7 @@ export function assertClaudeSelfCheck(stdout) {
117
118
  throw new CliError("sandbox_self_check_failed", `Claude Code workspace-write self-check failed; watcher was not enabled.\n${error}`);
118
119
  }
119
120
  export function probeFor(harness, session, ref) {
120
- return harness === "codex" ? codexProbe(session) : harness === "claude-code" ? claudeProbe(session, ref) : dshProbe(session, ref);
121
+ return harness === "codex" ? codexProbe(session) : harness === "claude-code" ? claudeProbe(session, ref) : harness === "dsh" ? dshProbe(session, ref) : antigravityProbe(session, ref);
121
122
  }
122
123
  export const dshTurnLog = (ref) => join(configRoot(), "logs", `turn.${ref.replace("/", ".")}.jsonl`);
123
124
  /** The first session event identifies a newly-created DeepSeek Harness session. */