benignswarm 0.12.136 → 0.12.138

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/args.js CHANGED
@@ -22,7 +22,7 @@ export const STRING_FLAGS = [
22
22
  "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit",
23
23
  "require-pushed", "require-gate-receipt", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email",
24
24
  "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on",
25
- "flow-summary", "flow-min-age", "flow-min-impact", "checkout", "api", "nonce",
25
+ "flow-summary", "flow-min-age", "flow-min-impact", "checkout", "unit-worktree", "sibling-checkout", "api", "nonce",
26
26
  "sandbox", "thread", "turn-timeout", "turns-per-hour", "unproductive-per-hour", "turn-coalesce-seconds", "session", "operation",
27
27
  "plain", "if-yes", "if-no", "ssh", "variant", "count", "min", "max", "needs", "min-ram", "exclude", "carry", "from",
28
28
  "to-ssh", "ssh-from", "wait", "writable", "writable-root", "dsh", "agy", "for", "until", "reason", "at", "requires",
@@ -33,7 +33,7 @@ export const STRING_FLAGS = [
33
33
  "root", "signing-key", "catalog", "context", "context-action", "context-checkpoint-ref", "context-old-thread", "context-new-thread", "source-commit", "component", "normalized-key",
34
34
  "drain-timeout", "on-running-turn", "extend", "ssh-config", "poll-ms",
35
35
  "stage", "machines", "resolved-retention-days", "wont-fix-retention-days", "alert-cooldown-minutes", "alerts", "confirm-force",
36
- "machine-session-id", "pool-sessions", "registry", "detail", "worktree", "turn-claude-runtime", "turn-antigravity-runtime",
36
+ "machine-session-id", "harness-binary", "pool-sessions", "registry", "detail", "worktree", "turn-claude-runtime", "turn-antigravity-runtime",
37
37
  "purpose", "storage-mode", "hosts", "arn", "version-id",
38
38
  "mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class",
39
39
  "expires-at", "conflicts-with", "source-channel-id", "source-message-id", "plain-summary",
@@ -21,6 +21,7 @@ import { DEFAULT_TURN_COALESCE_SECONDS, MAX_TURN_COALESCE_SECONDS } from "../tur
21
21
  import { DEFAULT_WATCH_STARTUP_JITTER_SECONDS, MAX_WATCH_STARTUP_JITTER_SECONDS } from "../startup-jitter.js";
22
22
  import { ANTIGRAVITY_SETTINGS_PLACEHOLDER, antigravityConversationDb, antigravityLog, antigravityResumeCommand, antigravitySettings, antigravityTotalTokens, antigravityTurnArgs, antigravityTurnEnv, runAntigravityTurn } from "../antigravity.js";
23
23
  import { configureGitCredentialForWorktree } from "./git-credential.js";
24
+ import { checkAndRecordHarnessBinary } from "../machine-binary.js";
24
25
  const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
25
26
  export const DEFAULT_CLAUDE_MAX_BUDGET_USD = 1;
26
27
  /** The guard states why it refuses. A refusal without a reason is still a refusal (no turn starts) and is reported as the defect it is. */
@@ -152,6 +153,11 @@ export async function harnessStart(p, out, harness) {
152
153
  throw new CliError("not_found", "DeepSeek Harness CLI dsh was not found; install DeepSeek Harness or pass --dsh <path>");
153
154
  if (harness === "dsh" && !existsSync(bin))
154
155
  throw new CliError("not_found", `DeepSeek Harness CLI ${bin} does not exist; pass --dsh <path> to its runtime/cli/bin/dsh`);
156
+ const expectedBinary = str(p.flags, "harness-binary");
157
+ if (expectedBinary && !expectedBinary.startsWith("/"))
158
+ throw new CliError("usage", "--harness-binary must be an absolute path");
159
+ if (expectedBinary && bin !== expectedBinary)
160
+ throw new CliError("harness_binary_mismatch", `the selected ${label} executable is ${bin}, but this session records ${expectedBinary}; correct PATH or ask the operator to change the session binary`);
155
161
  const effort = str(p.flags, "effort");
156
162
  const requestedAdopt = str(p.flags, "thread") ?? str(p.flags, "session");
157
163
  // Machine-configured folders and explicit extra roots are combined with existing package caches
@@ -177,6 +183,8 @@ export async function harnessStart(p, out, harness) {
177
183
  }
178
184
  const { credentials: creds, ref } = startAgentIdentity(name);
179
185
  errorSlug = ref;
186
+ if (!inContainer)
187
+ await checkAndRecordHarnessBinary(creds, machineSessionId, harness, bin);
180
188
  if ((harness === "claude-code" || harness === "antigravity") && sandbox === "workspace-write")
181
189
  configureHttpsOriginForWorktree(process.cwd());
182
190
  await configureGitCredentialForWorktree(process.cwd(), creds);
@@ -281,11 +281,11 @@ export async function machineAdmin(action, rest, p, out) {
281
281
  }
282
282
  }
283
283
  const capabilityLines = machineCapabilityLines(m.capabilities ?? []);
284
- const rows = m.sessions.map((s) => ({ agent: s.agent, pool: s.pool ?? "-", desired: s.desired, state: s.reported?.state ?? "-", turns_per_hour: s.turns_per_hour ?? 60, coalesce_s: s.turn_coalesce_seconds ?? 180, thread: s.thread ?? "-", harness: s.harness, provider: s.provider ?? "anthropic", sandbox: s.sandbox, image: s.image_digest ? `${s.container_runtime ?? "container"}@${String(s.image_digest).slice(0, 19)}` : "host", model: s.model ?? "-", dir: s.dir || s.reported?.dir || "(auto)", error: s.reported?.error ?? s.reported?.detail ?? "", last_turn: (s.reported?.last_turn ?? "").replace(/^\S+ b9s watch\[[^\]]+\]: /, "") }));
284
+ const rows = m.sessions.map((s) => ({ agent: s.agent, pool: s.pool ?? "-", desired: s.desired, state: s.reported?.state ?? "-", budget: s.effective_max_budget_usd == null ? "-" : `$${s.effective_max_budget_usd}${s.max_budget_is_default ? " (default)" : ""}`, turns_per_hour: s.turns_per_hour ?? 60, coalesce_s: s.turn_coalesce_seconds ?? 180, thread: s.thread ?? "-", harness: s.harness, binary: s.harness_binary ? `${s.harness_binary} (pinned)` : s.observed_harness_binary ? `${s.observed_harness_binary} (observed, not pinned)` : "unrecorded (not pinned)", provider: s.provider ?? "anthropic", sandbox: s.sandbox, image: s.image_digest ? `${s.container_runtime ?? "container"}@${String(s.image_digest).slice(0, 19)}` : "host", model: s.model ?? "-", dir: s.dir || s.reported?.dir || "(auto)", error: s.reported?.error ?? s.reported?.detail ?? "", last_turn: (s.reported?.last_turn ?? "").replace(/^\S+ b9s watch\[[^\]]+\]: /, "") }));
285
285
  const providers = rep.claude_code?.providers ?? {};
286
286
  const providerLines = Object.entries(providers).map(([provider, check]) => ` Claude Code ${provider}: ${check.logged_in ? "verified" : `NOT verified (${check.reason ?? "unknown reason"})`}`);
287
287
  const output = liveReport ? { ...r, machine: { ...m, report: rep } } : r;
288
- return out.print([...head, ...machineMacLines(rep.macos), ...machineGitLines(rep.git), ...cacheLines, ...capabilityLines, ...providerLines, rows.length ? table(rows, ["agent", "pool", "desired", "state", "turns_per_hour", "coalesce_s", "thread", "harness", "provider", "sandbox", "image", "model", "dir", "error", "last_turn"]) : " no sessions", ...keptHere.map((k) => ` kept in place (cannot move): ${k.agent} (${k.pool}): ${k.reason}`), ...movingHere].filter((line) => line !== null).join("\n"), output);
288
+ return out.print([...head, ...machineMacLines(rep.macos), ...machineGitLines(rep.git), ...cacheLines, ...capabilityLines, ...providerLines, rows.length ? table(rows, ["agent", "pool", "desired", "state", "budget", "turns_per_hour", "coalesce_s", "thread", "harness", "provider", "sandbox", "image", "model", "dir", "error", "last_turn"]) : " no sessions", ...keptHere.map((k) => ` kept in place (cannot move): ${k.agent} (${k.pool}): ${k.reason}`), ...movingHere].filter((line) => line !== null).join("\n"), output);
289
289
  }
290
290
  if (action === "maintenance") {
291
291
  // A window on the machine: no new turns from 15 min before, its agents away until it ends.
@@ -370,7 +370,7 @@ export async function machineAdmin(action, rest, p, out) {
370
370
  if (action === "label" || action === "slots") {
371
371
  const name = rest[0];
372
372
  if (!name)
373
- throw new CliError("usage", "machine label <name> <label...> [--remove a,b] | machine slots <name> <n | auto>");
373
+ throw new CliError("usage", "machine label <name> <label...> [--remove a,b] [--preview | --impact-revision <revision>] | machine slots <name> <n | auto> [--preview | --impact-revision <revision>]");
374
374
  const cur = (await c.call("GET", `/machines/${name}`)).machine;
375
375
  let body;
376
376
  if (action === "label") {
@@ -382,9 +382,26 @@ export async function machineAdmin(action, rest, p, out) {
382
382
  throw new CliError("usage", "machine slots <name> <n | auto> (auto: one per 4 GB of RAM)");
383
383
  body = { slots: rest[1] === "auto" ? null : Number(rest[1]) };
384
384
  }
385
+ const suppliedRevision = str(p.flags, "impact-revision");
386
+ if (bool(p.flags, "preview") && suppliedRevision !== undefined)
387
+ throw new CliError("usage", "use either --preview or --impact-revision, not both");
388
+ const { impact } = await c.call("POST", `/machines/${encodeURIComponent(name)}/settings-impact`, body);
389
+ if (!impact || typeof impact.source_revision !== "string")
390
+ throw new CliError("invalid_response", "machine settings preview did not include a source revision");
391
+ const impactText = [
392
+ `${name}: ${action} placement preview (${impact.source_revision})`,
393
+ ` labels: ${impact.after.labels.join(", ") || "(none)"}; slots: ${impact.after.slots ?? "automatic"}`,
394
+ ...impact.placements.map((move) => ` ${move.project}/${move.pool}/${move.slot}: ${move.from ?? "unplaced"} → ${move.to ?? `unplaced (${move.reason ?? "no eligible machine"})`}`),
395
+ `Review this impact, then repeat the command with --impact-revision ${impact.source_revision}.`,
396
+ ].join("\n");
397
+ if (bool(p.flags, "preview") || suppliedRevision === undefined)
398
+ return out.print(impactText, { impact });
399
+ if (suppliedRevision !== impact.source_revision)
400
+ throw new CliError("stale_preview", `machine settings impact changed since revision ${suppliedRevision}; nothing was changed; review the new preview with --preview`);
401
+ body.source_revision = impact.source_revision;
385
402
  const r = await c.call("PATCH", `/machines/${name}`, body);
386
403
  const kept = keptInPlace(((await c.call("GET", "/pools")).pools ?? []));
387
- return out.print([`${name}: labels ${r.machine.labels.join(", ") || "(none)"}; slots ${r.machine.slots ?? "auto"}. Pools were re-placed: b9s-admin pool list`, ...keptWarningLines(kept)].join("\n"), { ...r, kept_in_place: kept });
404
+ return out.print([`${name}: labels ${r.machine.labels.join(", ") || "(none)"}; slots ${r.machine.slots ?? "auto"}. Pools were re-placed: b9s-admin pool list`, ...keptWarningLines(kept)].join("\n"), { ...r, impact, kept_in_place: kept });
388
405
  }
389
406
  if (action === "readiness") {
390
407
  const name = rest[0];
@@ -463,6 +480,9 @@ export async function machineAdmin(action, rest, p, out) {
463
480
  if (!sub || !machineName || !project || !agent)
464
481
  throw new CliError("usage", "machine session add|stop|start|resume|limit|coalesce|remove <machine> <project>/<agent> [...]");
465
482
  if (sub === "add") {
483
+ const budget = str(p.flags, "max-budget-usd");
484
+ if (budget !== undefined && (budget.trim() === "" || !Number.isFinite(Number(budget)) || Number(budget) <= 0))
485
+ throw new CliError("usage", "--max-budget-usd must be a positive finite number");
466
486
  const turnTimeout = str(p.flags, "turn-timeout");
467
487
  const turnsPerHour = str(p.flags, "turns-per-hour");
468
488
  const unproductivePerHour = str(p.flags, "unproductive-per-hour");
@@ -476,6 +496,8 @@ export async function machineAdmin(action, rest, p, out) {
476
496
  const body = {
477
497
  project, agent, harness: str(p.flags, "harness") ?? "codex", provider: str(p.flags, "provider") ?? "anthropic", dir: str(p.flags, "dir"), sandbox: str(p.flags, "sandbox"),
478
498
  model: str(p.flags, "model"), effort: str(p.flags, "effort"), thread: str(p.flags, "thread"),
499
+ ...(budget !== undefined ? { max_budget_usd: Number(budget) } : {}),
500
+ ...(str(p.flags, "harness-binary") !== undefined ? { harness_binary: str(p.flags, "harness-binary") } : {}),
479
501
  ...(turnTimeout ? { turn_timeout: Number(turnTimeout) } : {}),
480
502
  ...(turnsPerHour ? { turns_per_hour: Number(turnsPerHour) } : {}),
481
503
  ...(unproductivePerHour ? { unproductive_per_hour: Number(unproductivePerHour) } : {}),
@@ -485,6 +507,20 @@ export async function machineAdmin(action, rest, p, out) {
485
507
  const r = await c.call("POST", `/machines/${machineName}/sessions`, body);
486
508
  return out.print(`Declared ${r.session.agent} on ${machineName} (${r.session.harness}/${r.session.provider}, ${r.session.sandbox}, ${r.session.dir}). Its daemon starts it within 30 s: b9s-admin machine show ${machineName}`, r);
487
509
  }
510
+ if (sub === "binary") {
511
+ const value = rest[3];
512
+ if (!value || (value !== "default" && !value.startsWith("/")))
513
+ throw new CliError("usage", "machine session binary <machine> <project>/<agent> <absolute-path|default>");
514
+ const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { harness_binary: value === "default" ? null : value });
515
+ return out.print(`${ref} on ${machineName}: harness binary ${r.session.harness_binary ?? "not pinned"}; daemon applies the change within 30 s.`, r);
516
+ }
517
+ if (sub === "budget") {
518
+ const value = rest[3];
519
+ if (value === undefined || (value !== "default" && (value.trim() === "" || !Number.isFinite(Number(value)) || Number(value) <= 0)))
520
+ throw new CliError("usage", "machine session budget <machine> <project>/<agent> <positive-usd|default>");
521
+ const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { max_budget_usd: value === "default" ? null : Number(value) });
522
+ return out.print(`${ref} on ${machineName}: turn budget $${r.session.effective_max_budget_usd}${r.session.max_budget_is_default ? " (default)" : ""}; daemon applies the change within 30 s.`, r);
523
+ }
488
524
  if (sub === "stop" || sub === "start") {
489
525
  const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { desired: sub === "stop" ? "stopped" : "running" });
490
526
  return out.print(`${ref} on ${machineName}: desired ${r.session.desired}; its daemon acts within 30 s.`, r);
@@ -69,9 +69,10 @@ function writeMachineState(s) {
69
69
  * again once with them. 2: the agent's own worktree git folder is writable under workspace-write.
70
70
  * 3: turns get TMPDIR beside the checkout instead of the system's /tmp.
71
71
  * 11: Antigravity's linked-worktree Git permissions are narrowed to required data paths.
72
+ * 12: Claude Code workspace-write roots name only the checkout, active unit worktree, narrowed Git metadata, config and caches.
72
73
  */
73
- const START_REV = 11;
74
- export const sessionFingerprint = (s, writable = [], imageDigest = null) => JSON.stringify([s.id, s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR, s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR, s.turn_coalesce_seconds ?? 180, s.thread, ...(writable.length ? [writable] : []), ...(imageDigest ? [imageDigest] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
74
+ const START_REV = 12;
75
+ export const sessionFingerprint = (s, writable = [], imageDigest = null) => JSON.stringify([s.id, s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR, s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR, s.turn_coalesce_seconds ?? 180, ...(s.max_budget_usd != null ? [`budget:${s.max_budget_usd}`] : []), ...(s.harness_binary ? [`binary:${s.harness_binary}`] : []), s.thread, ...(writable.length ? [writable] : []), ...(imageDigest ? [imageDigest] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
75
76
  /** A server thread update must restart the watcher even if a stored fingerprint is unexpectedly stale. */
76
77
  export function sessionConfigChanged(s, local, fingerprint) {
77
78
  const serverThreadChanged = s.thread !== null && s.thread !== (local?.thread ?? null);
@@ -103,6 +104,8 @@ export function startArgs(s, thread, writable = [], startupJitterSeconds) {
103
104
  return [
104
105
  "start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--turns-per-hour", String(s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR), "--unproductive-per-hour", String(s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--turn-coalesce-seconds", String(s.turn_coalesce_seconds ?? 180), "--machine-session-id", s.id, "--json",
105
106
  ...((s.provider ?? "anthropic") === "deepseek" ? ["--provider", "deepseek"] : []),
107
+ ...(s.max_budget_usd != null ? ["--max-budget-usd", String(s.max_budget_usd)] : []),
108
+ ...(s.harness_binary ? ["--harness-binary", s.harness_binary] : []),
106
109
  ...(s.model ? ["--model", s.model] : []),
107
110
  ...(s.effort ? ["--effort", s.effort] : []),
108
111
  ...(thread ? ["--thread", thread] : []),
@@ -1033,7 +1036,7 @@ export async function launchDesiredSession(opts) {
1033
1036
  B9S_HOME: "/home/agent/.b9s",
1034
1037
  ...(opts.containerProgressFile ? { BSCHAT_MACHINE_START_PROGRESS_FILE: opts.containerProgressFile } : {}),
1035
1038
  },
1036
- command: ["b9s", ...startArgs(opts.s, opts.thread, opts.s.sandbox === "workspace-write" ? containerWritablePaths : [], opts.startupJitterSeconds), "--in-container"],
1039
+ command: ["b9s", ...startArgs({ ...opts.s, harness_binary: null }, opts.thread, opts.s.sandbox === "workspace-write" ? containerWritablePaths : [], opts.startupJitterSeconds), "--in-container"],
1037
1040
  });
1038
1041
  const launchRes = runner(runtime, runArgs, {
1039
1042
  cwd: opts.s.dir,
@@ -3480,7 +3483,7 @@ export async function machine(p, out) {
3480
3483
  const rows = desired.map((s) => {
3481
3484
  const w = watcherServices().find((x) => x.label === watchLabelOf(s.agent));
3482
3485
  const judgment = s.turn_judgment ? ` judgment ${s.turn_judgment.state}: ${s.turn_judgment.trigger_reasons.join(", ")}` : "";
3483
- return `${s.agent.padEnd(32)} desired ${s.desired.padEnd(8)} watcher ${w ? (serviceActive(w) ? "active" : "inactive") : "none"} ${s.harness}/${s.provider ?? "anthropic"} thread ${state.sessions[s.id]?.thread ?? s.thread ?? "-"}${judgment} ${s.dir}`;
3486
+ return `${s.agent.padEnd(32)} desired ${s.desired.padEnd(8)} watcher ${w ? (serviceActive(w) ? "active" : "inactive") : "none"} ${s.harness}/${s.provider ?? "anthropic"}${s.effective_max_budget_usd != null ? ` budget $${s.effective_max_budget_usd}${s.max_budget_is_default ? " (default)" : ""}` : ""} binary ${s.harness_binary ? `${s.harness_binary} (pinned)` : s.observed_harness_binary ? `${s.observed_harness_binary} (observed, not pinned)` : "unrecorded (not pinned)"} thread ${state.sessions[s.id]?.thread ?? s.thread ?? "-"}${judgment} ${s.dir}`;
3484
3487
  });
3485
3488
  const launchd = process.platform === "darwin" ? launchdFacts() : null;
3486
3489
  return out.print([`machine ${m.name} (${m.url})`, ...(launchd ? [launchdFactsLine(launchd)] : []), ...rows, rows.length ? "" : "no sessions declared"].join("\n"), { machine: m.name, sessions: desired, local: state, ...(launchd ? { launchd } : {}) });
@@ -6,21 +6,25 @@ import { describeFinding, describeProbe, evaluateProbe, expectedFor, runSandboxP
6
6
  /**
7
7
  * What the sandbox this command runs in really allows.
8
8
  *
9
- * b9s sandbox probe [--checkout <dir>] [--api <host>] [--out <file>] [--nonce <id>]
9
+ * b9s sandbox probe [--checkout <dir>] [--unit-worktree <dir>] [--sibling-checkout <dir>] [--api <host>] [--out <file>] [--nonce <id>] [--harness <h> --sandbox <mode>]
10
10
  * measure, from inside the sandbox: where commands run, which tools are there, what git can
11
11
  * do, which hosts answer, and what is writable. Records facts and judges nothing.
12
12
  * b9s sandbox check <file> --harness <h> --sandbox <mode>
13
13
  * compare a probe's result with what is expected of that harness and mode; exits 1 on a
14
14
  * difference, naming each one.
15
15
  *
16
- * Neither needs an identity or a server call of its own: a session start runs the probe before
17
- * anything else is trusted.
16
+ * A standalone probe needs no identity. A managed Antigravity workspace-write probe names its
17
+ * harness and mode so the watcher can later remove its namespaced ref; neither probe calls the API.
18
18
  */
19
19
  export async function sandbox(p, out) {
20
20
  const sub = p.positionals[1];
21
21
  if (sub === "probe") {
22
22
  const nonce = str(p.flags, "nonce") ?? randomBytes(6).toString("hex");
23
- const result = await runSandboxProbe({ nonce, checkout: str(p.flags, "checkout"), apiHost: str(p.flags, "api") });
23
+ const harness = str(p.flags, "harness");
24
+ const mode = str(p.flags, "sandbox");
25
+ if ((harness === undefined) !== (mode === undefined) || harness === "" || mode === "")
26
+ throw new CliError("usage", "sandbox probe --harness and --sandbox must be provided together");
27
+ const result = await runSandboxProbe({ nonce, checkout: str(p.flags, "checkout"), unitWorktree: str(p.flags, "unit-worktree"), siblingCheckout: str(p.flags, "sibling-checkout"), apiHost: str(p.flags, "api"), ...(harness !== undefined && mode !== undefined ? { harness, sandbox: mode } : {}) });
24
28
  const file = str(p.flags, "out");
25
29
  if (file)
26
30
  writeProbeResult(file, result);
@@ -42,7 +46,7 @@ export async function sandbox(p, out) {
42
46
  }
43
47
  if (result?.schema !== 1 || !result.checks)
44
48
  throw new CliError("probe_unreadable", `${file} is not a sandbox probe result`);
45
- const verdict = evaluateProbe(result, expectedFor(harness, mode));
49
+ const verdict = evaluateProbe(result, expectedFor(harness, mode, result));
46
50
  const lines = verdict.ok
47
51
  ? [`sandbox as expected for ${harness} ${mode} (${verdict.unjudged.length} recorded without a verdict)`]
48
52
  : [`sandbox differs from what is expected for ${harness} ${mode}:`, ...verdict.failures.map((f) => ` - ${describeFinding(f)}`)];
@@ -51,5 +55,5 @@ export async function sandbox(p, out) {
51
55
  throw new CliError("sandbox_differs", `${verdict.failures.length} sandbox check${verdict.failures.length === 1 ? "" : "s"} differ from what is expected`);
52
56
  return;
53
57
  }
54
- throw new CliError("usage", "sandbox probe [--checkout <dir>] [--api <host>] [--out <file>] | sandbox check <file> --harness <h> --sandbox <mode>");
58
+ throw new CliError("usage", "sandbox probe [--checkout <dir>] [--unit-worktree <dir>] [--sibling-checkout <dir>] [--api <host>] [--out <file>] [--nonce <id>] [--harness <h> --sandbox <mode>] | sandbox check <file> --harness <h> --sandbox <mode>");
55
59
  }
@@ -4,6 +4,7 @@ import { DEFAULT_TURN_COALESCE_SECONDS, MAX_TURN_COALESCE_SECONDS, shouldDeferTu
4
4
  import { drainingUntil } from "../maintenance.js";
5
5
  import { claudeSettings, probeFor, turnHarness } from "../harnesses.js";
6
6
  import { ANTIGRAVITY_SETTINGS_PLACEHOLDER, antigravitySettings } from "../antigravity.js";
7
+ import { cleanupAntigravitySandboxProbeRefs } from "../sandbox-probe.js";
7
8
  import { applyAck } from "./wake.js";
8
9
  import { launchdSessionTypeXml, lingerEnabled, plistLaunchdDomain, loadSystemdUnit, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
9
10
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statfsSync, writeFileSync } from "node:fs";
@@ -758,6 +759,9 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
758
759
  let preparedWorktree = null;
759
760
  if (turnSink && bindingToPrepare) {
760
761
  preparedWorktree = await (dependencies.prepareWorktree ?? prepareTurnWorktree)(name, bindingToPrepare);
762
+ if (!preparedWorktree && dependencies.claudeRuntime?.sandbox === "workspace-write") {
763
+ throw new CliError("unit_worktree_missing", `Claude Code workspace-write cannot start WU #${bindingToPrepare.work_unit_number}: the watcher did not prepare its unit worktree`);
764
+ }
761
765
  if (preparedWorktree) {
762
766
  wakePrefix.push(preparedWorktree.status === "assigned"
763
767
  ? `The watcher prepared WU #${preparedWorktree.number}'s worktree at ${preparedWorktree.path}. Run b9s wu start ${preparedWorktree.number} from this checkout to record the start, then work in that path.`
@@ -779,8 +783,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
779
783
  turnCwd = preparedWorktree?.path ?? process.cwd();
780
784
  if (turnSink && dependencies.claudeRuntime && turnExec?.includes(CLAUDE_SETTINGS_PLACEHOLDER)) {
781
785
  const runtime = dependencies.claudeRuntime;
782
- const cwd = turnCwd ?? process.cwd();
783
- const args = claudeSettings(runtime.sandbox, model, runtime.effort, cwd, configRoot(), runtime.writableRoots);
786
+ const args = claudeSettings(runtime.sandbox, model, runtime.effort, process.cwd(), configRoot(), runtime.writableRoots, preparedWorktree ?? undefined);
784
787
  turnExec = turnExec.replace(CLAUDE_SETTINGS_PLACEHOLDER, args.map(shellQuote).join(" "));
785
788
  }
786
789
  if (turnSink && dependencies.antigravityRuntime && turnExec?.includes(ANTIGRAVITY_SETTINGS_PLACEHOLDER)) {
@@ -1062,6 +1065,16 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
1062
1065
  updateState(name, (onDisk) => ({ ...onDisk, watch_pending: undefined, watch_dormant_logged_at: undefined }), env);
1063
1066
  ctl.failedAt = Date.now();
1064
1067
  }
1068
+ if (harness === "antigravity") {
1069
+ try {
1070
+ const removed = cleanupAntigravitySandboxProbeRefs(process.cwd(), agentRef(loadAgent(name)), env);
1071
+ if (removed.length)
1072
+ log(`removed ${removed.length} Antigravity sandbox probe ref(s) outside the session sandbox`);
1073
+ }
1074
+ catch (e) {
1075
+ log(`Antigravity sandbox probe ref cleanup failed outside the session sandbox: ${e.message}`);
1076
+ }
1077
+ }
1065
1078
  ctl.turn = null;
1066
1079
  await completePendingTurnGuard(name, probe, log, undefined, undefined, env);
1067
1080
  debug(`no inbox poll: turn #${turn.seq} just ended; checking for next work on the next watcher iteration`);
package/dist/harnesses.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { accessSync, constants, existsSync, readFileSync, readdirSync, statSync } from "node:fs";
2
+ import { accessSync, constants, existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
- import { dirname, join } from "node:path";
4
+ import { basename, dirname, join, resolve } from "node:path";
5
5
  import { CliError } from "./errors.js";
6
6
  import { configRoot } from "./config.js";
7
+ import { gitSandboxWritablePaths } from "./git-sandbox-paths.js";
7
8
  import { readState, updateState } from "./state.js";
8
9
  import { codexArchivedRollout, codexRollout } from "./sessions.js";
9
10
  import { readTurnPhase, usageLimitUntil } from "./turn.js";
@@ -579,19 +580,54 @@ function claudeProbe(session, ref) {
579
580
  * The Claude Code flags a headless turn runs with. Claude Code's sandbox always lets the agent write
580
581
  * its working folder, so read-only cannot be honoured and is refused. workspace-write is its sandbox
581
582
  * (refusing to start when the sandbox is unavailable, never running a command outside it), every
582
- * domain reachable as with Codex, edits allowed in the checkout and the folders `wu start` and bschat
583
- * write (the checkout's parent, ~/.b9s) plus the machine's writable folders; anything that would
584
- * need a prompt is denied, since nobody can answer one. danger-full-access skips permissions.
583
+ * domain reachable as with Codex, edits allowed in the agent's checkout, its active unit worktree,
584
+ * the Git metadata those checkouts need, b9s's config root, and the machine's writable folders;
585
+ * anything that would need a prompt is denied, since nobody can answer one. danger-full-access skips
586
+ * permissions.
585
587
  */
586
- export function claudeSettings(sandbox, model, effort, cwd, bschatHome, extraWritable = []) {
588
+ export function claudeSettings(sandbox, model, effort, checkoutRoot, bschatHome, extraWritable = [], unitWorktree) {
587
589
  const common = [...(model ? ["--model", model] : []), ...(effort ? ["--effort", effort] : [])];
588
590
  if (sandbox === "danger-full-access")
589
591
  return [...common, "--permission-mode", "bypassPermissions"];
590
592
  if (sandbox === "read-only")
591
- throw new CliError("unsupported", "Claude Code has no read-only sandbox: its sandbox always lets the agent write its working folder. Use workspace-write (sandboxed; writes limited to the checkout, its unit worktrees, ~/.b9s and the machine's writable folders) or danger-full-access");
593
+ throw new CliError("unsupported", "Claude Code has no read-only sandbox: its sandbox always lets the agent write its working folder. Use workspace-write (sandboxed; writes limited to the checkout, the active unit worktree, required Git metadata, b9s config and machine writable folders) or danger-full-access");
592
594
  if (sandbox !== "workspace-write")
593
595
  throw new CliError("usage", `unknown sandbox ${sandbox}`);
594
- const dirs = [dirname(cwd), bschatHome, ...extraWritable];
596
+ const requiredDirectory = (label, value) => {
597
+ let resolved;
598
+ try {
599
+ resolved = realpathSync(resolve(value));
600
+ if (!statSync(resolved).isDirectory())
601
+ throw new Error("not a directory");
602
+ }
603
+ catch {
604
+ throw new CliError("sandbox_path_missing", `Claude Code workspace-write cannot start: ${label} directory ${value} is missing or is not a directory`);
605
+ }
606
+ return resolved;
607
+ };
608
+ const checkout = requiredDirectory("agent checkout", checkoutRoot);
609
+ const directories = [checkout];
610
+ const files = [];
611
+ if (unitWorktree)
612
+ directories.push(requiredDirectory(`WU #${unitWorktree.number} worktree`, unitWorktree.path));
613
+ // Shared Git path discovery is also used by Antigravity. Add directories as roots and files
614
+ // only to allowWrite; the common .git root, hooks/config and unassigned worktree metadata stay out.
615
+ const exactGitFiles = new Set(["FETCH_HEAD", "FETCH_HEAD.lock", "packed-refs", "packed-refs.lock", "HEAD", "HEAD.lock", "index", "index.lock", "COMMIT_EDITMSG"]);
616
+ // The checkout and prepared worktree can be separate clones on a machine. Compute each Git
617
+ // metadata allowlist independently, then deduplicate; neither is allowed to widen the other.
618
+ const gitPaths = [
619
+ ...gitSandboxWritablePaths(checkout),
620
+ ...(unitWorktree ? gitSandboxWritablePaths(unitWorktree.path) : []),
621
+ ];
622
+ const gitFiles = gitPaths.filter((path) => exactGitFiles.has(basename(path)));
623
+ directories.push(...gitPaths.filter((path) => !exactGitFiles.has(basename(path))));
624
+ files.push(...gitFiles);
625
+ // A first-time `b9s start --token` computes settings before enrollment creates this exact folder.
626
+ // It is safe to allow the path before creation; never replace it with its parent.
627
+ directories.push(existsSync(bschatHome) ? requiredDirectory("b9s config", bschatHome) : resolve(bschatHome));
628
+ directories.push(...extraWritable.map((path) => resolve(path)));
629
+ const dirs = [...new Set(directories)];
630
+ const writable = [...new Set([...dirs, ...files])];
595
631
  const settings = {
596
632
  env: claudeSandboxEnv(sandbox),
597
633
  sandbox: {
@@ -599,7 +635,7 @@ export function claudeSettings(sandbox, model, effort, cwd, bschatHome, extraWri
599
635
  failIfUnavailable: true,
600
636
  autoAllowBashIfSandboxed: true,
601
637
  allowUnsandboxedCommands: false,
602
- filesystem: { allowWrite: dirs },
638
+ filesystem: { allowWrite: writable },
603
639
  network: { allowedDomains: ["*", "api.benignswarm.org"] },
604
640
  },
605
641
  };
package/dist/help.js CHANGED
@@ -230,10 +230,11 @@ Machine placement enforces configured session slots and reports machine pressure
230
230
  b9s update [--no-restart] the same as install --latest: upgrade this machine's b9s, repair PATH aliases,
231
231
  restart the machine daemon first, then watchers in batches of 5 with 5 s between batches
232
232
  b9s install [<version> | --latest] [--no-restart] make or upgrade this machine's one b9s (join does it once), repair PATH aliases,
233
- restart its daemon first, then watchers in batches of 5 with 5 s between batches
234
- b9s sandbox probe [--checkout <dir>] [--api <host>] [--out <file>] [--nonce <id>]
233
+ restart the machine daemon first, then watchers in batches of 5 with 5 s between batches
234
+ b9s sandbox probe [--checkout <dir>] [--unit-worktree <dir>] [--sibling-checkout <dir>] [--api <host>] [--out <file>] [--nonce <id>] [--harness <h> --sandbox <mode>]
235
235
  what the sandbox this runs in really allows: where commands run, which tools
236
- are there, what git can do, which hosts answer, what is writable; facts only
236
+ are there, what git can do, which hosts answer, what is writable; facts only.
237
+ The harness/mode pair is needed for watcher cleanup on Antigravity workspace-write
237
238
  b9s sandbox check <file> --harness <h> --sandbox <mode>
238
239
  compare a probe result with what is expected of that harness; exits 1 on a difference
239
240
  b9s doctor every b9s on this machine and who runs which (PATH, npx caches, this repo's
@@ -476,7 +477,9 @@ Machines (provisioned over your own ssh; a daemon on each runs the agent session
476
477
  b9s-admin machine unquarantine <name> [--reason <text>]
477
478
  exclude a host from scheduler/pool placement and preserve containment across scale-down; only unquarantine clears it
478
479
  b9s-admin machine session add <machine> <project>/<agent> --dir <checkout> --sandbox <read-only|workspace-write|danger-full-access> [--harness codex|claude-code|dsh|antigravity] [--provider anthropic|deepseek]
479
- [--create --role <role>] [--model m] [--effort e] [--thread <id>] [--turn-timeout min] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60] [--turn-coalesce-seconds 0..3600]
480
+ [--create --role <role>] [--model m] [--effort e] [--thread <id>] [--turn-timeout min] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60] [--turn-coalesce-seconds 0..3600] [--max-budget-usd n] [--harness-binary /absolute/path]
481
+ b9s-admin machine session budget <machine> <project>/<agent> <positive-usd|default> set Claude Code workspace-write per-turn budget (default $1)
482
+ b9s-admin machine session binary <machine> <project>/<agent> <absolute-path|default> pin the harness executable, or clear the pin
480
483
  b9s-admin machine session thread <machine> <project>/<agent> <thread-id|none> set or clear the thread a pool session adopts
481
484
  b9s-admin machine session stop|start|resume|limit|coalesce|remove <machine> <project>/<agent> set its busy, unproductive, or coalescing limit
482
485
  (change its count/settings, pause scaling, pin, or bench the agent)
@@ -488,9 +491,9 @@ Machines (provisioned over your own ssh; a daemon on each runs the agent session
488
491
  transfers thread/note plus local agent state over SSH,
489
492
  refuses newer destination state and avoids duplicate Codex hooks under managed policy,
490
493
  then commits the session only after handoff succeeds; work left on the source requires both flags
491
- b9s-admin machine label <name> <label...> [--remove a,b] what cannot be measured (lab-lan, builds); pools' --needs match it
494
+ b9s-admin machine label <name> <label...> [--remove a,b] [--preview | --impact-revision <revision>] preview affected pool placement, then confirm with its revision
492
495
  b9s-admin machine headroom [name] latest resource headroom, freshness, session ceiling and reservations (console WU #118)
493
- b9s-admin machine slots <name> <n | auto> how many sessions it takes (auto: one per 4 GB of RAM)
496
+ b9s-admin machine slots <name> <n | auto> [--preview | --impact-revision <revision>] preview affected pool placement, then confirm with its revision
494
497
  b9s-admin machine writable <name> <path...> | none folders workspace-write agents there may also write (~/.cargo, ~/.ester)
495
498
  b9s-admin machine workdir <name> <path | default> where its daemon clones projects for pool sessions (default ~/bschat)
496
499
  b9s-admin machine cache-budget <name> [<GB> | default] [--floor <pct | default>] per-cache budget (default 40 GB) and volume free-space floor (default 15%)
@@ -0,0 +1,20 @@
1
+ import { Client } from "./client.js";
2
+ import { CliError } from "./errors.js";
3
+ import { machineIdentityForAgent } from "./git.js";
4
+ /** Check a host session's operator pin atomically while recording this start's executable. */
5
+ export async function checkAndRecordHarnessBinary(creds, sessionId, harness, binary) {
6
+ const client = Client.raw(creds.url, creds.key);
7
+ const me = await client.call("GET", "/me");
8
+ if (!Array.isArray(me.machine_sessions))
9
+ throw new CliError("invalid_response", "the service did not return machine sessions; cannot check the recorded harness binary");
10
+ const sessions = me.machine_sessions;
11
+ const hostIdentity = sessionId ? null : machineIdentityForAgent(creds.machine);
12
+ const machineName = hostIdentity?.split("/").at(-1);
13
+ const matches = sessionId ? sessions.filter((s) => s.id === sessionId) : sessions.filter((s) => s.machine === machineName);
14
+ if (sessionId && matches.length !== 1)
15
+ throw new CliError("machine_session_mismatch", "the requested machine session does not belong to this agent");
16
+ if (!sessionId && matches.length > 1)
17
+ throw new CliError("machine_session_mismatch", "multiple sessions match this host; use its machine daemon to select a session");
18
+ if (matches.length === 1)
19
+ await client.call("POST", "/agents/me/harness-binary", { session_id: matches[0].id, harness, binary });
20
+ }
@@ -1,4 +1,5 @@
1
1
  import { spawnSync } from "node:child_process";
2
+ import { createHash } from "node:crypto";
2
3
  import { closeSync, existsSync, mkdirSync, openSync, readdirSync, realpathSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
3
4
  import { homedir } from "node:os";
4
5
  import { basename, delimiter, dirname, join } from "node:path";
@@ -9,9 +10,9 @@ import { sandboxProbeWorktreeName } from "./git-sandbox-paths.js";
9
10
  export const PROBE_CHECKS = [
10
11
  "cwd_is_checkout", "origin_is_https",
11
12
  "tool_node", "tool_npm", "tool_npx", "tool_git", "tool_b9s",
12
- "git_branch", "git_object", "git_worktree", "git_other_worktree", "git_remote_read",
13
+ "git_branch", "git_branch_delete", "git_object", "git_worktree", "git_other_worktree", "git_remote_read",
13
14
  "net_api", "net_other_host",
14
- "write_checkout", "write_checkout_parent", "write_b9s_home",
15
+ "write_checkout", "write_checkout_parent", "write_unit_worktree", "write_sibling_checkout", "git_commit", "git_fetch", "write_b9s_home",
15
16
  "write_git_config", "write_git_hooks", "write_home", "write_node_install",
16
17
  ];
17
18
  const clip = (text) => text.trim().replace(/\s+/g, " ").slice(0, 300);
@@ -20,6 +21,33 @@ function run(cmd, args, cwd, env, timeoutMs = 20_000) {
20
21
  const r = spawnSync(cmd, args, { cwd, env, encoding: "utf8", timeout: timeoutMs, maxBuffer: 1024 * 1024 });
21
22
  return { status: r.error ? null : r.status, out: (r.stdout ?? "").trim(), err: r.error ? r.error.message : (r.stderr ?? "").trim() };
22
23
  }
24
+ function isPackedRefsLockReadOnly(detail, commonDir) {
25
+ if (!commonDir)
26
+ return false;
27
+ const lockPath = join(commonDir, "packed-refs.lock").replace(/\\/g, "/").toLowerCase();
28
+ const reported = detail.replace(/\\/g, "/").toLowerCase();
29
+ return reported.includes(lockPath) && (reported.includes("read-only file system") || /(?:^|\W)erofs(?:$|\W)/i.test(detail));
30
+ }
31
+ /** Remove only this agent's sandbox-probe refs from the watcher, outside the Antigravity turn. */
32
+ export function cleanupAntigravitySandboxProbeRefs(checkout, agent, env = process.env) {
33
+ const commonDir = run("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], checkout, env);
34
+ if (commonDir.status !== 0 || !commonDir.out)
35
+ throw new CliError("sandbox_probe_cleanup_failed", commonDir.err || "could not resolve the Git common directory for sandbox probe cleanup");
36
+ const owner = createHash("sha256").update(agent).digest("hex").slice(0, 24);
37
+ const prefix = `refs/heads/b9s-sandbox-probe/${owner}/`;
38
+ const listed = run("git", ["for-each-ref", "--format=%(refname)", "refs/heads/b9s-sandbox-probe"], checkout, env);
39
+ if (listed.status !== 0)
40
+ throw new CliError("sandbox_probe_cleanup_failed", listed.err || "could not list sandbox probe refs");
41
+ const refs = listed.out.split("\n").map((ref) => ref.trim()).filter((ref) => ref.startsWith(prefix));
42
+ const removed = [];
43
+ for (const ref of refs) {
44
+ const deleted = run("git", ["update-ref", "-d", ref], checkout, env);
45
+ if (deleted.status !== 0)
46
+ throw new CliError("sandbox_probe_cleanup_failed", `could not remove Antigravity sandbox probe ref ${ref}: ${deleted.err}`);
47
+ removed.push(ref);
48
+ }
49
+ return removed;
50
+ }
23
51
  function observe(action) {
24
52
  try {
25
53
  const value = action();
@@ -82,10 +110,11 @@ export async function runSandboxProbe(options) {
82
110
  const originConfigured = read(["config", "--get", "remote.origin.url"]);
83
111
  const originEffective = read(["remote", "get-url", "origin"]);
84
112
  const checks = Object.fromEntries(PROBE_CHECKS.map((id) => [id, null]));
85
- checks.cwd_is_checkout = options.checkout
86
- ? cwd === options.checkout && toplevel === options.checkout
113
+ const expectedWorkingTree = options.unitWorktree ?? options.checkout;
114
+ checks.cwd_is_checkout = expectedWorkingTree
115
+ ? cwd === expectedWorkingTree && toplevel === expectedWorkingTree
87
116
  ? { ok: true, value: cwd }
88
- : { ok: false, value: cwd, detail: clip(`expected ${options.checkout}; the repository here is ${toplevel ?? "none"}`) }
117
+ : { ok: false, value: cwd, detail: clip(`expected ${expectedWorkingTree}; the repository here is ${toplevel ?? "none"}`) }
89
118
  : null;
90
119
  checks.origin_is_https = originEffective === null
91
120
  ? { ok: false, detail: "no origin remote is readable here" }
@@ -96,15 +125,33 @@ export async function runSandboxProbe(options) {
96
125
  checks.tool_git = tool("git", ["--version"], cwd, env);
97
126
  checks.tool_b9s = tool("b9s", null, cwd, env);
98
127
  if (toplevel) {
99
- const ref = `refs/heads/b9s-probe-${nonce}`;
100
- checks.git_branch = observe(() => {
101
- const made = git(["update-ref", ref, "HEAD"]);
102
- if (made.status !== 0)
103
- throw new Error(made.err || "git update-ref failed");
104
- const gone = git(["update-ref", "-d", ref]);
105
- if (gone.status !== 0)
106
- throw new Error(`created ${ref} but could not delete it: ${gone.err}`);
107
- });
128
+ const agent = env.BSCHAT_AGENT;
129
+ const watcherCleansRef = options.harness === "antigravity" && options.sandbox === "workspace-write";
130
+ let ref;
131
+ if (watcherCleansRef) {
132
+ ref = agent ? `refs/heads/b9s-sandbox-probe/${createHash("sha256").update(agent).digest("hex").slice(0, 24)}/${nonce}` : null;
133
+ }
134
+ else {
135
+ ref = `refs/heads/b9s-probe-${nonce}`;
136
+ }
137
+ checks.git_branch = ref
138
+ ? observe(() => {
139
+ const made = git(["update-ref", ref, "HEAD"]);
140
+ if (made.status !== 0)
141
+ throw new Error(made.err || "git update-ref failed");
142
+ return ref;
143
+ })
144
+ : { ok: false, detail: "BSCHAT_AGENT is required to scope Antigravity probe ref cleanup to its owner" };
145
+ checks.git_branch_delete = checks.git_branch?.value
146
+ ? observe(() => {
147
+ const gone = git(["update-ref", "-d", ref]);
148
+ if (gone.status !== 0)
149
+ throw new Error(`could not delete ${ref} inside this sandbox: ${gone.err}`);
150
+ })
151
+ : null;
152
+ if (checks.git_branch_delete && !checks.git_branch_delete.ok && isPackedRefsLockReadOnly(checks.git_branch_delete.detail ?? "", commonDir)) {
153
+ checks.git_branch_delete.refusal = "packed-refs-lock-read-only";
154
+ }
108
155
  // A commit object from the current tree: proves the object store takes a write without touching
109
156
  // the index, the working tree or any branch, and without running the repository's hooks.
110
157
  checks.git_object = observe(() => {
@@ -151,9 +198,52 @@ export async function runSandboxProbe(options) {
151
198
  checks.git_remote_read = remote.status === 0
152
199
  ? { ok: true }
153
200
  : { ok: false, detail: clip(remote.err || `git ls-remote origin exited ${remote.status ?? "without a status"}`) };
154
- checks.write_checkout = createAndRemove(toplevel, nonce);
155
- checks.write_checkout_parent = createAndRemove(dirname(toplevel), nonce);
201
+ checks.write_checkout = createAndRemove(options.checkout ?? toplevel, nonce);
202
+ checks.write_checkout_parent = createAndRemove(dirname(options.checkout ?? toplevel), nonce);
203
+ }
204
+ if (options.unitWorktree) {
205
+ const unitWorktree = options.unitWorktree;
206
+ checks.write_unit_worktree = createAndRemove(unitWorktree, nonce);
207
+ const commitFile = join(unitWorktree, `.b9s-probe-commit-${nonce}`);
208
+ const indexFile = join(unitWorktree, `.b9s-probe-index-${nonce}`);
209
+ checks.git_commit = observe(() => {
210
+ const original = run("git", ["rev-parse", "HEAD"], unitWorktree, env);
211
+ if (original.status !== 0 || !original.out)
212
+ throw new Error(original.err || "cannot read unit worktree HEAD");
213
+ const oldHead = original.out;
214
+ writeFileSync(commitFile, `b9s sandbox probe ${nonce}\n`, { flag: "wx" });
215
+ const gitEnv = { ...env, GIT_INDEX_FILE: indexFile };
216
+ const readTree = run("git", ["read-tree", "HEAD"], unitWorktree, gitEnv);
217
+ if (readTree.status !== 0)
218
+ throw new Error(readTree.err || "git read-tree failed");
219
+ const add = run("git", ["add", "--", `.b9s-probe-commit-${nonce}`], unitWorktree, gitEnv);
220
+ if (add.status !== 0)
221
+ throw new Error(add.err || "git add failed");
222
+ const commit = run("git", ["-c", "user.name=b9s sandbox probe", "-c", "user.email=probe@invalid", "commit", "--no-verify", "-m", `b9s sandbox probe ${nonce}`], unitWorktree, gitEnv);
223
+ if (commit.status !== 0)
224
+ throw new Error(commit.err || "git commit failed");
225
+ const committedHead = run("git", ["rev-parse", "HEAD"], unitWorktree, env);
226
+ if (committedHead.status !== 0 || !committedHead.out || committedHead.out === oldHead)
227
+ throw new Error("git commit returned without advancing HEAD");
228
+ const restore = run("git", ["update-ref", "HEAD", oldHead, committedHead.out], unitWorktree, env);
229
+ if (restore.status !== 0)
230
+ throw new Error(`probe commit ${committedHead.out} was created but HEAD could not be restored: ${restore.err}`);
231
+ return `created and removed probe commit ${committedHead.out.slice(0, 12)}`;
232
+ });
233
+ // The alternate index leaves the agent's staged and unstaged work untouched; HEAD is
234
+ // compare-and-swap restored after the successful temporary commit.
235
+ rmSync(commitFile, { force: true });
236
+ rmSync(indexFile, { force: true });
237
+ rmSync(`${indexFile}.lock`, { force: true });
238
+ const fetched = run("git", ["fetch", "--no-tags", "origin", "HEAD"], unitWorktree, env, 60_000);
239
+ checks.git_fetch = fetched.status === 0 ? { ok: true } : { ok: false, detail: clip(fetched.err || `git fetch exited ${fetched.status ?? "without a status"}`) };
156
240
  }
241
+ else {
242
+ checks.write_unit_worktree = null;
243
+ checks.git_commit = null;
244
+ checks.git_fetch = null;
245
+ }
246
+ checks.write_sibling_checkout = options.siblingCheckout ? createAndRemove(options.siblingCheckout, nonce) : null;
157
247
  if (commonDir) {
158
248
  // Opened for appending and closed: shows whether it could be changed without changing it.
159
249
  checks.write_git_config = observe(() => { closeSync(openSync(join(commonDir, "config"), "a")); });
@@ -168,7 +258,7 @@ export async function runSandboxProbe(options) {
168
258
  checks.net_other_host = await reach(`https://${options.otherHost ?? "example.com"}/`);
169
259
  return {
170
260
  schema: 1, nonce, at: new Date().toISOString(), cli_version: CLI_VERSION, platform: process.platform,
171
- cwd, checkout: options.checkout ?? null,
261
+ cwd, checkout: options.checkout ?? null, unit_worktree: options.unitWorktree ?? null, sibling_checkout: options.siblingCheckout ?? null,
172
262
  git: { toplevel, git_dir: gitDir, common_dir: commonDir, origin_configured: originConfigured?.replace(/\/\/[^@/]*@/, "//") ?? null, origin_effective: originEffective?.replace(/\/\/[^@/]*@/, "//") ?? null },
173
263
  checks,
174
264
  };
@@ -177,20 +267,22 @@ export function writeProbeResult(path, result) {
177
267
  mkdirSync(dirname(path), { recursive: true });
178
268
  writeFileSync(path, `${JSON.stringify(result, null, 2)}\n`, { mode: 0o600 });
179
269
  }
180
- const ACCEPTED_GIT = "accepted limit (2026-11-19): the clone's shared git folder is writable under the checkout's parent; see docs/REMOTE-MACHINES.md";
270
+ const ACCEPTED_GIT = "not measured for this harness yet";
181
271
  const UNMEASURED = "not measured for this harness yet";
182
272
  const CODEX_WORKSPACE_WRITE = "measured 2026-11-19 in Codex workspace-write: writes to the user's home and the Node installation are refused";
183
273
  const CLAUDE_WORKTREE = "measured 2026-11-19 in Claude Code workspace-write: git worktree add is refused because the clone's shared .git/worktrees folder is read-only; the watcher must prepare unit worktrees outside the sandbox";
184
- const CLAUDE_WORKSPACE_WRITE = "measured 2026-11-19 in Claude Code workspace-write: writes to the user's home, Node installation, shared git config and hooks are refused";
185
- const ANTIGRAVITY_GIT_SCOPE = "Antigravity workspace-write policy: shared Git stores and exact active/prepared worktree metadata are writable; arbitrary git worktree add is refused because only exact paths or recursive directories are supported, and recursive registry access would expose siblings. The watcher prepares the unit worktree before the turn; config, hooks, sibling worktrees and the checkout parent stay refused";
186
- export function expectedFor(harness, sandbox) {
274
+ const CLAUDE_WORKSPACE_WRITE = "measured 2026-11-19 in Claude Code workspace-write: writes to the user's home, Node installation, checkout parent, shared git config and hooks are refused";
275
+ const CLAUDE_ORIGIN = "origin transport is machine-specific; git remote read and active-worktree fetch are measured independently";
276
+ const ANTIGRAVITY_GIT_SCOPE = "Antigravity workspace-write policy: Git objects, refs and logs plus exact active/prepared worktree metadata are writable; arbitrary git worktree add is refused because only exact paths or recursive directories are supported, and recursive registry access would expose siblings. The watcher prepares the unit worktree before the turn; config, hooks, sibling worktrees and the checkout parent stay refused";
277
+ const ANTIGRAVITY_REF_CLEANUP = "measured 2026-11-20 on Linux Antigravity 1.5.13: branch creation and commit-object writes work, but deleting a ref requires .git/packed-refs.lock under the read-only common Git directory. The watcher removes refs in this probe namespace outside the sandbox after the check; the session does not delete branches";
278
+ export function expectedFor(harness, sandbox, result) {
187
279
  const works = { expected: "works" };
188
280
  const base = {
189
281
  cwd_is_checkout: works, origin_is_https: { expected: "any", note: UNMEASURED },
190
282
  tool_node: works, tool_npm: works, tool_npx: works, tool_git: works, tool_b9s: works,
191
- git_branch: works, git_object: works, git_worktree: works, git_other_worktree: { expected: "any", note: UNMEASURED }, git_remote_read: works,
283
+ git_branch: works, git_branch_delete: works, git_object: works, git_worktree: works, git_other_worktree: { expected: "any", note: UNMEASURED }, git_remote_read: works,
192
284
  net_api: works, net_other_host: { expected: "any", note: UNMEASURED },
193
- write_checkout: works, write_checkout_parent: works, write_b9s_home: works,
285
+ write_checkout: works, write_checkout_parent: works, write_unit_worktree: { expected: "any", note: "requires --unit-worktree" }, write_sibling_checkout: { expected: "any", note: "requires --sibling-checkout" }, git_commit: { expected: "any", note: "requires --unit-worktree" }, git_fetch: { expected: "any", note: "requires --unit-worktree" }, write_b9s_home: works,
194
286
  write_git_config: { expected: "any", note: ACCEPTED_GIT }, write_git_hooks: { expected: "any", note: ACCEPTED_GIT },
195
287
  write_home: { expected: "any", note: UNMEASURED }, write_node_install: { expected: "any", note: UNMEASURED },
196
288
  };
@@ -206,6 +298,7 @@ export function expectedFor(harness, sandbox) {
206
298
  return {
207
299
  ...base,
208
300
  origin_is_https: works,
301
+ git_branch_delete: { expected: "refused", note: ANTIGRAVITY_REF_CLEANUP },
209
302
  git_worktree: { expected: "refused", note: ANTIGRAVITY_GIT_SCOPE },
210
303
  write_checkout_parent: { expected: "refused", note: ANTIGRAVITY_GIT_SCOPE },
211
304
  git_other_worktree: { expected: "refused", note: ANTIGRAVITY_GIT_SCOPE },
@@ -215,18 +308,26 @@ export function expectedFor(harness, sandbox) {
215
308
  };
216
309
  }
217
310
  if (harness === "claude-code") {
218
- // Its sandbox proxies HTTP(S) only, so an SSH origin cannot be reached (the reason b9s start
219
- // rewrites it per worktree). On 2026-11-19 workspace-write also refused writes to home, the
311
+ // Origin transport is machine-specific; require the actual remote read below rather than
312
+ // requiring HTTPS. On 2026-11-20, ronald's real SSH origin was readable and fetchable in the
313
+ // live Claude Code workspace-write turn. Workspace-write also refuses writes to home, the
220
314
  // Node installation, shared git config/hooks, and git worktree registration.
221
315
  return {
222
316
  ...base,
223
- origin_is_https: works,
317
+ origin_is_https: { expected: "any", note: CLAUDE_ORIGIN },
318
+ write_checkout_parent: { expected: "refused", note: CLAUDE_WORKSPACE_WRITE },
224
319
  git_worktree: { expected: "refused", note: CLAUDE_WORKTREE },
225
- git_other_worktree: { expected: "any", note: CLAUDE_WORKTREE },
320
+ git_other_worktree: { expected: "refused", note: "another agent's linked-worktree Git metadata is outside the active turn's allow-list" },
226
321
  write_git_config: { expected: "refused", note: CLAUDE_WORKSPACE_WRITE },
227
322
  write_git_hooks: { expected: "refused", note: CLAUDE_WORKSPACE_WRITE },
228
323
  write_home: { expected: "refused", note: CLAUDE_WORKSPACE_WRITE },
229
324
  write_node_install: { expected: "refused", note: CLAUDE_WORKSPACE_WRITE },
325
+ ...(result?.unit_worktree ? {
326
+ write_unit_worktree: { expected: "works", note: "the prepared active unit worktree is explicitly allow-listed" },
327
+ git_commit: { expected: "works", note: "the probe creates a temporary commit and restores HEAD" },
328
+ git_fetch: { expected: "works", note: "fetch writes shared Git objects, refs/logs, and FETCH_HEAD" },
329
+ } : {}),
330
+ ...(result?.sibling_checkout ? { write_sibling_checkout: { expected: "refused", note: "sibling checkouts are outside the active turn's allow-list" } } : {}),
230
331
  };
231
332
  }
232
333
  if (harness === "codex")
@@ -246,7 +347,10 @@ export function evaluateProbe(result, expected) {
246
347
  for (const check of PROBE_CHECKS) {
247
348
  const seen = result.checks[check];
248
349
  const want = expected[check];
249
- const observed = seen === null || seen === undefined ? "not run" : seen.ok ? "works" : "refused";
350
+ const observed = seen === null || seen === undefined ? "not run"
351
+ : seen.ok ? "works"
352
+ : check === "git_branch_delete" ? seen.refusal === "packed-refs-lock-read-only" ? "refused" : "error"
353
+ : "refused";
250
354
  const detail = seen?.detail ?? seen?.value;
251
355
  if (want.expected === "any") {
252
356
  unjudged.push({ check, expected: "any", observed, ...(detail ? { detail } : {}), ...(want.note ? { note: want.note } : {}) });
@@ -258,25 +362,25 @@ export function evaluateProbe(result, expected) {
258
362
  return { ok: failures.length === 0, failures, unjudged };
259
363
  }
260
364
  const LABEL = {
261
- cwd_is_checkout: "commands run in the agent's checkout",
365
+ cwd_is_checkout: "commands run in the checkout or active unit worktree",
262
366
  origin_is_https: "origin is reached over HTTPS",
263
367
  tool_node: "node runs", tool_npm: "npm runs", tool_npx: "npx runs", tool_git: "git runs", tool_b9s: "b9s is on PATH",
264
- git_branch: "git can create a branch", git_object: "git can write a commit object", git_worktree: "git can add its reserved sandbox probe worktree", git_other_worktree: "another agent's Git worktree metadata is writable", git_remote_read: "git can read origin",
368
+ git_branch: "git can create a probe branch", git_branch_delete: "git can delete a branch from inside the session", git_object: "git can write a commit object", git_worktree: "git can add its reserved sandbox probe worktree", git_other_worktree: "another agent's Git worktree metadata is writable", git_remote_read: "git can read origin",
265
369
  net_api: "the BenignSwarm API is reachable", net_other_host: "a host outside the allow-list is reachable",
266
- write_checkout: "the checkout is writable", write_checkout_parent: "the checkout's parent is writable", write_b9s_home: "b9s's own folder is writable",
370
+ write_checkout: "the checkout is writable", write_checkout_parent: "the checkout's parent is writable", write_unit_worktree: "the active unit worktree is writable", write_sibling_checkout: "a sibling checkout is writable", git_commit: "git commit works in the active unit worktree", git_fetch: "git fetch works in the active unit worktree", write_b9s_home: "b9s's own folder is writable",
267
371
  write_git_config: "the clone's git config is writable", write_git_hooks: "the clone's git hooks are writable",
268
372
  write_home: "the home folder is writable", write_node_install: "the Node installation is writable",
269
373
  };
270
374
  export function describeFinding(f) {
271
375
  const want = f.expected === "works" ? "should work" : "should be refused";
272
- const got = f.observed === "works" ? "it works" : f.observed === "refused" ? "it is refused" : "the check could not run";
376
+ const got = f.observed === "works" ? "it works" : f.observed === "refused" ? "it is refused" : f.observed === "error" ? "the check failed" : "the check could not run";
273
377
  return `${LABEL[f.check]}: ${want}, but ${got}${f.detail ? ` (${f.detail})` : ""}`;
274
378
  }
275
379
  export function describeProbe(result) {
276
380
  const lines = [`sandbox probe ${result.nonce} at ${result.at} (b9s ${result.cli_version}, ${result.platform})`, ` ran in ${result.cwd}${result.checkout ? `; expected ${result.checkout}` : ""}`];
277
381
  for (const check of PROBE_CHECKS) {
278
382
  const seen = result.checks[check];
279
- const state = seen === null ? "not run" : seen.ok ? "yes" : "no";
383
+ const state = seen === null ? "not run" : seen.ok ? "yes" : seen.refusal ? "refused" : "no";
280
384
  lines.push(` ${state.padEnd(7)} ${LABEL[check]}${seen?.detail ? ` (${seen.detail})` : seen?.value ? ` (${seen.value})` : ""}`);
281
385
  }
282
386
  return lines.join("\n");
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.136";
1
+ export const CLI_VERSION = "0.12.138";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.136",
3
+ "version": "0.12.138",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {