benignswarm 0.12.134 → 0.12.136

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.
@@ -1,10 +1,12 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { appendFileSync, existsSync, mkdirSync, readFileSync, realpathSync, statSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
- import { basename, delimiter, dirname, join, sep } from "node:path";
4
+ import { basename, delimiter, dirname, join, resolve, sep } from "node:path";
5
5
  import { configRoot } from "./config.js";
6
6
  import { repoDirectory } from "./directories.js";
7
7
  import { CliError } from "./errors.js";
8
+ import { gitSandboxDeniedPaths, gitSandboxWritablePaths, sandboxProbeWorktreeAdminPath } from "./git-sandbox-paths.js";
9
+ export const ANTIGRAVITY_SETTINGS_PLACEHOLDER = "__B9S_ANTIGRAVITY_TURN_SETTINGS__";
8
10
  export function antigravityTotalTokens(usage) {
9
11
  if (!usage)
10
12
  return null;
@@ -58,7 +60,7 @@ export function antigravitySandboxPermissions(apiHost, b9sHome, b9sBin, nodeBin
58
60
  }
59
61
  return [...new Set(allow)];
60
62
  }
61
- export function antigravitySettings(sandbox, cwd, b9sHome, apiHost, extraWritable = [], b9sBin, nodeBin = process.execPath) {
63
+ export function antigravitySettings(sandbox, cwd, b9sHome, apiHost, extraWritable = [], b9sBin, nodeBin = process.execPath, agentRef, unitWorktree) {
62
64
  if (sandbox === "read-only")
63
65
  throw new CliError("unsupported", "Antigravity has no read-only permission mode; use workspace-write or danger-full-access");
64
66
  if (sandbox === "danger-full-access")
@@ -69,30 +71,41 @@ export function antigravitySettings(sandbox, cwd, b9sHome, apiHost, extraWritabl
69
71
  throw new CliError("usage", "the BenignSwarm API host is invalid for Antigravity sandbox permissions");
70
72
  if (!b9sBin)
71
73
  throw new CliError("not_installed", "the recorded b9s install path is required for Antigravity workspace-write");
72
- // Antigravity runs the agent's commands in the outermost workspace folder. A workspace folder
73
- // that contains the checkout (its parent, where unit worktrees and the clone's git data live)
74
- // therefore moved every command out of the checkout: `git` found no repository and the start's
75
- // own check failed. Such folders are granted by permission instead, and only folders beside the
76
- // checkout are added as workspaces. Verified with agy 1.5.11: pwd is the checkout, git reaches
77
- // origin, and a sibling worktree can be created.
78
- const wanted = [...new Set([dirname(cwd), b9sHome, ...extraWritable])];
79
- const containsCheckout = (dir) => cwd === dir || cwd.startsWith(dir.endsWith(sep) ? dir : dir + sep);
80
- const around = wanted.filter(containsCheckout);
81
- // A folder inside the checkout's parent, which is already granted by permission, needs nothing
82
- // more and must not become a workspace: with the clone's shared git folders (<clone>/.git/logs and the like, inside
83
- // the checkout's parent) added as workspaces, agy ran every command in <clone>/.git/logs. The
84
- // start's own `git ls-remote origin` then read the clone's SSH origin and failed, so each start
85
- // attempt spent a model turn and no session came up (verified with agy on Linux, two models;
86
- // granted through the parent alone, commands run in the checkout and git can branch, commit and
87
- // add worktrees).
88
- const within = (dir, outer) => dir !== outer && dir.startsWith(outer.endsWith(sep) ? outer : outer + sep);
89
- const parent = dirname(cwd);
90
- const besideCheckout = (dir) => within(dir, parent) && !within(dir, cwd);
91
- const beside = wanted.filter((dir) => !containsCheckout(dir) && !besideCheckout(dir));
92
- const allow = [...new Set([...antigravitySandboxPermissions(apiHost, b9sHome, b9sBin, nodeBin, repoDirectory(cwd)), ...around.map((dir) => `write_file(${dir})`)])];
74
+ if (!agentRef)
75
+ throw new CliError("sandbox_agent_invalid", "Antigravity workspace-write requires the agent identity for scoped Git permissions");
76
+ const absoluteCwd = resolve(cwd);
77
+ const absoluteParent = dirname(absoluteCwd);
78
+ const containsPath = (dir, path) => path === dir || path.startsWith(dir.endsWith(sep) ? dir : dir + sep);
79
+ const containsCheckout = (dir) => containsPath(dir, absoluteCwd);
80
+ const configured = [...new Set([resolve(b9sHome), ...extraWritable.map((path) => resolve(path)), ...(unitWorktree ? [resolve(unitWorktree.path)] : [])])];
81
+ const home = resolve(homedir());
82
+ if (configured.some((dir) => dir !== absoluteCwd && (containsCheckout(dir) || containsPath(dir, home)))) {
83
+ throw new CliError("sandbox_root_too_broad", "Antigravity workspace-write refuses a writable root that contains the checkout or home directory; configure the exact writable folder instead");
84
+ }
85
+ const additionalCheckouts = unitWorktree ? [{ label: `WU #${unitWorktree.number} worktree`, path: unitWorktree.path }] : [];
86
+ const gitPaths = gitSandboxWritablePaths(absoluteCwd, additionalCheckouts);
87
+ const exactGitFiles = new Set(["packed-refs", "packed-refs.lock", "FETCH_HEAD", "FETCH_HEAD.lock", "HEAD", "HEAD.lock", "index", "index.lock", "COMMIT_EDITMSG"]);
88
+ const commonGitFiles = gitPaths.filter((path) => exactGitFiles.has(basename(path)) && (!existsSync(path) || !statSync(path).isDirectory()));
89
+ const gitDirectories = gitPaths.filter((path) => !commonGitFiles.includes(path));
90
+ const worktreeAdmin = dirname(sandboxProbeWorktreeAdminPath(absoluteCwd, agentRef));
91
+ const allow = [...new Set([
92
+ ...antigravitySandboxPermissions(apiHost, b9sHome, b9sBin, nodeBin, repoDirectory(cwd)),
93
+ `write_file(${absoluteCwd})`,
94
+ ...configured.map((dir) => `write_file(${dir})`),
95
+ ...gitDirectories.map((dir) => `write_file(${dir})`),
96
+ ...commonGitFiles.map((path) => `write_file(${path})`),
97
+ // Git reads the registry to inspect linked worktrees. The watcher creates the unit entry
98
+ // before a turn and gitSandboxWritablePaths grants that exact entry; the agent must not add
99
+ // arbitrary worktree entries because recursive registry access would expose siblings.
100
+ `read_file(${worktreeAdmin})`,
101
+ ])];
102
+ const deny = [...new Set(gitSandboxDeniedPaths(absoluteCwd, additionalCheckouts).map((path) => `write_file(${path})`))];
103
+ // Do not make the checkout's parent a writable root. Antigravity path grants are recursive, so
104
+ // that would let one agent edit every sibling checkout and unit worktree on the machine.
105
+ const beside = configured.filter((dir) => !containsCheckout(dir) && !(dir.startsWith(absoluteParent + sep)));
93
106
  return [
94
107
  "--sandbox", "--settings",
95
- JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow } }),
108
+ JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow, deny } }),
96
109
  ...beside.flatMap((dir) => ["--add-dir", dir]),
97
110
  ];
98
111
  }
package/dist/args.js CHANGED
@@ -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",
36
+ "machine-session-id", "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",
@@ -19,7 +19,7 @@ import { claudeTurnEnv } from "../providers.js";
19
19
  import { DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, MAX_TURNS_PER_HOUR } from "../turn-guard.js";
20
20
  import { DEFAULT_TURN_COALESCE_SECONDS, MAX_TURN_COALESCE_SECONDS } from "../turn.js";
21
21
  import { DEFAULT_WATCH_STARTUP_JITTER_SECONDS, MAX_WATCH_STARTUP_JITTER_SECONDS } from "../startup-jitter.js";
22
- import { antigravityConversationDb, antigravityLog, antigravityResumeCommand, antigravitySettings, antigravityTotalTokens, antigravityTurnArgs, antigravityTurnEnv, runAntigravityTurn } from "../antigravity.js";
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
24
  const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
25
25
  export const DEFAULT_CLAUDE_MAX_BUDGET_USD = 1;
@@ -185,7 +185,7 @@ export async function harnessStart(p, out, harness) {
185
185
  if (harness === "antigravity") {
186
186
  if (inContainer)
187
187
  provisionContainerInstallRecord();
188
- settings = antigravitySettings(sandbox, process.cwd(), configRoot(), new URL(creds.url).host, [...writable, ...ownWorktreeGitDir(process.cwd()), ...sharedGitDataDirs(process.cwd())], requireInstall().bin);
188
+ settings = antigravitySettings(sandbox, process.cwd(), configRoot(), new URL(creds.url).host, writable, requireInstall().bin, process.execPath, ref);
189
189
  }
190
190
  const priorState = readState(ref);
191
191
  if (priorState.turn_guard?.fault) {
@@ -316,12 +316,15 @@ export async function harnessStart(p, out, harness) {
316
316
  const claudeTurnSettings = harness === "claude-code" && sandbox === "workspace-write"
317
317
  ? "__B9S_CLAUDE_TURN_SETTINGS__"
318
318
  : settings.map(shq).join(" ");
319
+ const antigravityTurnSettings = harness === "antigravity" && sandbox === "workspace-write"
320
+ ? [ANTIGRAVITY_SETTINGS_PLACEHOLDER]
321
+ : settings;
319
322
  const exec = harness === "codex"
320
323
  ? [bin, "exec", "resume", session, ...settings].map(shq).join(" ") + " {text}"
321
324
  : harness === "dsh"
322
325
  ? dshResumeCommand(bin, session, settings, dshTurnLog(ref))
323
326
  : harness === "antigravity"
324
- ? antigravityResumeCommand(bin, session, model, effort, turnTimeout * 60, settings, antigravityLog(ref))
327
+ ? antigravityResumeCommand(bin, session, model, effort, turnTimeout * 60, antigravityTurnSettings, antigravityLog(ref))
325
328
  // The result goes to a file the watcher reads when the turn ends: Claude Code can exit 0 with is_error set.
326
329
  : `${shq(bin)} -p {text} ${[claudeTurnSettings, ...(sandbox === "workspace-write" ? claudeTurnArgs(maxBudgetUsd) : []).map(shq), "--resume", session, "--output-format", "json"].join(" ")} > ${shq(claudeResultFile(ref))}`;
327
330
  const watcherOut = [];
@@ -336,6 +339,7 @@ export async function harnessStart(p, out, harness) {
336
339
  watcherEnv = { TMPDIR: tmp, ...(machineSessionId ? { BSCHAT_MACHINE_SESSION_ID: machineSessionId } : {}), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}), ...(harness === "antigravity" ? { ...antigravityTurnEnv(sandbox, install.bin), BSCHAT_MODEL: model, ...(effort ? { BSCHAT_EFFORT: effort } : {}) } : {}) };
337
340
  const turnSpec = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider, model,
338
341
  ...(harness === "claude-code" && sandbox === "workspace-write" ? { claudeRuntime: { sandbox, ...(effort ? { effort } : {}), writableRoots: writable, maxBudgetUsd } } : {}),
342
+ ...(harness === "antigravity" && sandbox === "workspace-write" ? { antigravityRuntime: { sandbox, apiHost: new URL(creds.url).host, b9sBin: install.bin, nodeBin: process.execPath, writableRoots: writable } } : {}),
339
343
  ...(machineSessionId ? { machineSessionId } : {}) };
340
344
  if (inContainer) {
341
345
  const sess = sessionOfExec(exec);
@@ -697,23 +701,6 @@ export function ownWorktreeGitDir(cwd) {
697
701
  const [gitDir, common] = r.stdout.trim().split("\n");
698
702
  return gitDir && common && gitDir !== common ? [gitDir] : [];
699
703
  }
700
- /**
701
- * The shared git data a linked worktree needs to commit, fetch, branch and add unit worktrees:
702
- * the common git folder's objects, refs, logs and worktrees. Antigravity's terminal sandbox mounts
703
- * every `.git` under a writable folder read-only unless a path inside it is added by name, so a
704
- * pool agent there could neither commit nor run `wu start` (EROFS on the clone's .git; seen on two
705
- * projects). The folder itself is deliberately not listed: its `config` and `hooks` stay read-only,
706
- * because a sandboxed write there would run outside the sandbox the next time git is used.
707
- */
708
- export function sharedGitDataDirs(cwd) {
709
- const r = spawnSync("git", ["rev-parse", "--absolute-git-dir", "--path-format=absolute", "--git-common-dir"], { cwd, encoding: "utf8" });
710
- if (r.status !== 0)
711
- return [];
712
- const [gitDir, common] = r.stdout.trim().split("\n");
713
- if (!gitDir || !common || gitDir === common)
714
- return [];
715
- return ["objects", "refs", "logs", "worktrees"].map((name) => joinPath(common, name));
716
- }
717
704
  /** Starts a headless Codex session in its own process group and returns its thread id from the JSON event stream. */
718
705
  async function startThread(codexBin, args, logPath, agent) {
719
706
  const fd = openSync(logPath, "a");
@@ -40,16 +40,21 @@ export async function install(p, out) {
40
40
  lines.push(`(was ${prev.bin}; run b9s doctor to find hooks and watchers still pointing there)`);
41
41
  const restarted = [];
42
42
  const elsewhere = [];
43
+ const failed = [];
43
44
  if (!bool(p.flags, "no-restart")) {
44
- const services = await restartInstallServices(rec.bin);
45
+ const services = await restartInstallServices(rec.bin, undefined, undefined, (message) => process.stderr.write(`b9s: ${message}\n`));
45
46
  restarted.push(...services.restarted);
46
47
  elsewhere.push(...services.not_restarted);
48
+ failed.push(...services.failed);
47
49
  }
48
50
  if (restarted.length)
49
51
  lines.push(`Restarted ${restarted.length} service${restarted.length === 1 ? "" : "s"} on it: ${restarted.map((l) => l.replace("org.benignswarm.watch.", "")).join(", ")}`);
50
52
  if (elsewhere.length)
51
53
  lines.push(`Not restarted:\n ${elsewhere.join("\n ")}`);
52
- out.print(lines.join("\n"), { install: rec, restarted, not_restarted: elsewhere });
54
+ if (failed.length)
55
+ lines.push(`Failed to restart:\n ${failed.join("\n ")}`);
56
+ out.print(lines.join("\n"), { install: rec, restarted, not_restarted: elsewhere, failed });
57
+ return failed.length ? 1 : 0;
53
58
  }
54
59
  export function embeddedHookCommands(value, marker) {
55
60
  const found = [];
@@ -16,7 +16,7 @@ import { drainingUntil, writeMaintenance } from "../maintenance.js";
16
16
  import { TURN_HARNESSES, cachedClaudeLogin, claudeFacts, claudeHome, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
17
17
  import { writeFileAtomic } from "../shared-file.js";
18
18
  import { readState, updateState } from "../state.js";
19
- import { installService, launchdFacts, launchdFactsLine, launchdGuidance, launchdSessionNow, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
19
+ import { installService, launchdFacts, launchdFactsLine, launchdGuidance, launchdSessionNow, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartServicesInBatches, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices, INSTALL_RESTART_BATCH_SIZE, INSTALL_RESTART_BATCH_PAUSE_MS } from "../install.js";
20
20
  import { CLI_VERSION } from "../version.js";
21
21
  import { probeCapabilities } from "../capabilities.js";
22
22
  import { diskSpaceNotice } from "../notices.js";
@@ -68,8 +68,9 @@ function writeMachineState(s) {
68
68
  * Bumped when `b9s start` builds a session's settings differently, so every session is started
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
+ * 11: Antigravity's linked-worktree Git permissions are narrowed to required data paths.
71
72
  */
72
- const START_REV = 10;
73
+ const START_REV = 11;
73
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
75
  /** A server thread update must restart the watcher even if a stored fingerprint is unexpectedly stale. */
75
76
  export function sessionConfigChanged(s, local, fingerprint) {
@@ -1135,7 +1136,62 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1135
1136
  ? (deps?.probeImdsContainer ? deps.probeImdsContainer({ runner }) : probeContainerImdsIsolation({ runner }))
1136
1137
  : null;
1137
1138
  const containerImdsOk = imdsContainerProbe ? imdsContainerProbe.ok : deps?.containerImdsBlocked;
1139
+ const recoveryFailures = new Map();
1140
+ const recoveryServices = [];
1141
+ const localWatcherServices = watcherServices();
1142
+ for (const session of desired) {
1143
+ if (session.desired !== "running")
1144
+ continue;
1145
+ const local = state.sessions[session.id];
1146
+ if (!local || local.container_name)
1147
+ continue;
1148
+ const project = projects.find((entry) => entry.id === session.project_id || entry.name === session.project);
1149
+ const poolImageOptIn = Boolean(session.pool) && !session.hardware_bound && Boolean(project?.image?.pool_sessions_enabled);
1150
+ const containerMode = isCloudHost || (poolImageOptIn && hostContainerProbe?.runtime !== null);
1151
+ if (containerMode)
1152
+ continue;
1153
+ const service = localWatcherServices.find((entry) => entry.label === watchLabelOf(session.agent));
1154
+ if (!service || serviceActive(service))
1155
+ continue;
1156
+ const sessionWritable = session.sandbox === "workspace-write"
1157
+ ? [...new Set([...defaultWorkspaceWritableRoots(), ...writable])]
1158
+ : writable;
1159
+ const fingerprint = sessionFingerprint({ ...session, thread: reconcileThread(session, local) }, session.sandbox === "workspace-write" ? sessionWritable : []);
1160
+ if (sessionConfigChanged(session, local, fingerprint))
1161
+ continue;
1162
+ recoveryServices.push(service);
1163
+ }
1164
+ if (recoveryServices.length) {
1165
+ const batchTotal = Math.ceil(recoveryServices.length / INSTALL_RESTART_BATCH_SIZE);
1166
+ const recovery = await restartServicesInBatches([], recoveryServices, {
1167
+ progress: (message) => log(`daemon watcher recovery: ${message}`),
1168
+ pause: deps?.wait,
1169
+ });
1170
+ for (const issue of recovery.not_started) {
1171
+ const entry = recoveryServices.find((service) => service.label === issue.label);
1172
+ if (entry)
1173
+ recoveryFailures.set(issue.label, issue.reason);
1174
+ }
1175
+ const count = recoveryServices.length;
1176
+ const returned = recovery.restarted.length;
1177
+ log(`daemon watcher recovery: attempted ${count} inactive session watcher${count === 1 ? "" : "s"} in ${batchTotal} batch${batchTotal === 1 ? "" : "es"}; ${returned} returned`);
1178
+ }
1138
1179
  const out = [];
1180
+ // Watcher recovery and session relaunch are one startup wave. Keep their counts together so
1181
+ // a short recovery tail cannot be followed immediately by a fresh full launch batch.
1182
+ let restartWorkScheduled = recoveryServices.length;
1183
+ const scheduleRestartWork = async (kind, agent) => {
1184
+ if (restartWorkScheduled > 0 && restartWorkScheduled % INSTALL_RESTART_BATCH_SIZE === 0) {
1185
+ log(`daemon restart wave: pausing ${INSTALL_RESTART_BATCH_PAUSE_MS / 1000}s after ${restartWorkScheduled} requests`);
1186
+ await (deps?.wait ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))))(INSTALL_RESTART_BATCH_PAUSE_MS);
1187
+ }
1188
+ const batch = Math.floor(restartWorkScheduled / INSTALL_RESTART_BATCH_SIZE) + 1;
1189
+ if (restartWorkScheduled % INSTALL_RESTART_BATCH_SIZE === 0) {
1190
+ log(`daemon restart wave batch ${batch}: starting up to ${INSTALL_RESTART_BATCH_SIZE} operations`);
1191
+ }
1192
+ restartWorkScheduled++;
1193
+ log(`daemon restart wave batch ${batch}: ${kind} for ${agent}`);
1194
+ };
1139
1195
  for (const s of desired) {
1140
1196
  const label = watchLabelOf(s.agent);
1141
1197
  const svc = () => watcherServices().find((w) => w.label === label);
@@ -1475,6 +1531,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1475
1531
  throw error;
1476
1532
  }
1477
1533
  try {
1534
+ await scheduleRestartWork("session start/relaunch", s.agent);
1478
1535
  pending.pid = (deps?.startTrackedSession ?? ((childBin, options, result) => startSessionChild(childBin, s.dir, options, result)))(bin, launchOptions, resultFile);
1479
1536
  }
1480
1537
  catch (error) {
@@ -1519,7 +1576,11 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1519
1576
  };
1520
1577
  }
1521
1578
  else if (!containerMode && hostSvc) {
1579
+ const recoveryFailure = recoveryFailures.get(label);
1580
+ if (recoveryFailure)
1581
+ throw new Error(`its watcher ${label} could not be restarted during daemon recovery: ${recoveryFailure}`);
1522
1582
  if (!serviceActive(hostSvc)) {
1583
+ await scheduleRestartWork("watcher restart", s.agent);
1523
1584
  if (!restartWatcher(hostSvc))
1524
1585
  throw new Error(`its watcher ${label} is not loaded and could not be restarted`);
1525
1586
  log(`${s.agent}: watcher was not running; restarted`);
@@ -3,6 +3,7 @@ import { bindSession, sessionOfExec, threadOfExec } from "../sessions.js";
3
3
  import { DEFAULT_TURN_COALESCE_SECONDS, MAX_TURN_COALESCE_SECONDS, shouldDeferTurn, startTurn, stopTurn } from "../turn.js";
4
4
  import { drainingUntil } from "../maintenance.js";
5
5
  import { claudeSettings, probeFor, turnHarness } from "../harnesses.js";
6
+ import { ANTIGRAVITY_SETTINGS_PLACEHOLDER, antigravitySettings } from "../antigravity.js";
6
7
  import { applyAck } from "./wake.js";
7
8
  import { launchdSessionTypeXml, lingerEnabled, plistLaunchdDomain, loadSystemdUnit, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
8
9
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statfsSync, writeFileSync } from "node:fs";
@@ -126,12 +127,29 @@ export async function watch(p, out, dependencies = {}) {
126
127
  throw new CliError("usage", `--turn-claude-runtime must be valid Claude runtime JSON: ${error.message}`);
127
128
  }
128
129
  }
130
+ let antigravityRuntime;
131
+ const antigravityRuntimeText = str(p.flags, "turn-antigravity-runtime");
132
+ if (antigravityRuntimeText !== undefined) {
133
+ if (harness !== "antigravity")
134
+ throw new CliError("usage", "--turn-antigravity-runtime is only valid with --harness antigravity");
135
+ try {
136
+ const value = JSON.parse(antigravityRuntimeText);
137
+ if (value.sandbox !== "workspace-write" || typeof value.apiHost !== "string" || typeof value.b9sBin !== "string" || typeof value.nodeBin !== "string"
138
+ || !Array.isArray(value.writableRoots) || !value.writableRoots.every((root) => typeof root === "string")) {
139
+ throw new Error("invalid Antigravity turn runtime fields");
140
+ }
141
+ antigravityRuntime = { sandbox: value.sandbox, apiHost: value.apiHost, b9sBin: value.b9sBin, nodeBin: value.nodeBin, writableRoots: value.writableRoots };
142
+ }
143
+ catch (error) {
144
+ throw new CliError("usage", `--turn-antigravity-runtime must be valid Antigravity runtime JSON: ${error.message}`);
145
+ }
146
+ }
129
147
  const machineSessionId = str(p.flags, "machine-session-id") ?? process.env.BSCHAT_MACHINE_SESSION_ID;
130
148
  if (machineSessionId && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(machineSessionId))
131
149
  throw new CliError("usage", "machine session id must be a UUID");
132
150
  if (machineSessionId)
133
151
  process.env.BSCHAT_MACHINE_SESSION_ID = machineSessionId;
134
- turn = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider: providerName, model, ...(claudeRuntime ? { claudeRuntime } : {}), ...(machineSessionId ? { machineSessionId } : {}) };
152
+ turn = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider: providerName, model, ...(claudeRuntime ? { claudeRuntime } : {}), ...(antigravityRuntime ? { antigravityRuntime } : {}), ...(machineSessionId ? { machineSessionId } : {}) };
135
153
  }
136
154
  else if (p.flags.provider !== undefined) {
137
155
  throw new CliError("usage", "--provider is only used with --turn --harness claude-code");
@@ -327,7 +345,7 @@ export async function watch(p, out, dependencies = {}) {
327
345
  const activeProbe = probe;
328
346
  if (activeProbe)
329
347
  await (dependencies.turnStep ?? turnStep)(ctl, activeProbe, turnTimeout, log, async (sink, beforeTurn) => {
330
- const wakeDependencies = { ...dependencies.wakeOnceDependencies, ...(turn?.claudeRuntime ? { claudeRuntime: turn.claudeRuntime } : {}) };
348
+ const wakeDependencies = { ...dependencies.wakeOnceDependencies, ...(turn?.claudeRuntime ? { claudeRuntime: turn.claudeRuntime } : {}), ...(turn?.antigravityRuntime ? { antigravityRuntime: turn.antigravityRuntime } : {}) };
331
349
  const result = await (dependencies.wakeOnce ?? 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", () => activeProbe.beginTurn?.(), beforeTurn, turn?.harness === "claude-code" ? turn.session : undefined, turn?.coalesceSeconds ?? 0, wakeDependencies);
332
350
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
333
351
  }, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour, turn?.harness);
@@ -765,6 +783,11 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
765
783
  const args = claudeSettings(runtime.sandbox, model, runtime.effort, cwd, configRoot(), runtime.writableRoots);
766
784
  turnExec = turnExec.replace(CLAUDE_SETTINGS_PLACEHOLDER, args.map(shellQuote).join(" "));
767
785
  }
786
+ if (turnSink && dependencies.antigravityRuntime && turnExec?.includes(ANTIGRAVITY_SETTINGS_PLACEHOLDER)) {
787
+ const runtime = dependencies.antigravityRuntime;
788
+ const args = antigravitySettings(runtime.sandbox, process.cwd(), configRoot(), runtime.apiHost, [...runtime.writableRoots, ...(preparedWorktree ? [preparedWorktree.path] : [])], runtime.b9sBin, runtime.nodeBin, name, preparedWorktree ?? undefined);
789
+ turnExec = turnExec.replace(ANTIGRAVITY_SETTINGS_PLACEHOLDER, args.map(shellQuote).join(" "));
790
+ }
768
791
  if (!(await deliver(name, turnExec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, provider, model, turnStdin, beforeTurn, { ...(dependencies.startTurn ? { startTurn: dependencies.startTurn } : {}), sessionId, workUnitBinding, workUnitBindingReason: bindingResolution?.reason ?? null, ...(turnCwd ? { cwd: turnCwd } : {}) }, allowTurn))) {
769
792
  debug("no wake: delivery failed or turn guard denied the launch");
770
793
  return { sent: false, recoveryBriefDelivered: false };
@@ -1669,7 +1692,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
1669
1692
  bindSession(sess.kind, sess.id, name);
1670
1693
  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 ${plistLaunchdDomain(path)}/${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] });
1671
1694
  }
1672
- export 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), "--turn-coalesce-seconds", String(t.coalesceSeconds), "--harness", t.harness, "--session", t.session, ...(t.machineSessionId ? ["--machine-session-id", t.machineSessionId] : []), ...(t.provider === "deepseek" ? ["--provider", t.provider] : []), ...(t.model ? ["--model", t.model] : []), ...(t.claudeRuntime ? ["--turn-claude-runtime", JSON.stringify(t.claudeRuntime)] : [])] : []);
1695
+ export 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), "--turn-coalesce-seconds", String(t.coalesceSeconds), "--harness", t.harness, "--session", t.session, ...(t.machineSessionId ? ["--machine-session-id", t.machineSessionId] : []), ...(t.provider === "deepseek" ? ["--provider", t.provider] : []), ...(t.model ? ["--model", t.model] : []), ...(t.claudeRuntime ? ["--turn-claude-runtime", JSON.stringify(t.claudeRuntime)] : []), ...(t.antigravityRuntime ? ["--turn-antigravity-runtime", JSON.stringify(t.antigravityRuntime)] : [])] : []);
1673
1696
  function escapeXml(s) {
1674
1697
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1675
1698
  }
@@ -0,0 +1,129 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { existsSync, lstatSync, readdirSync, realpathSync, statSync } from "node:fs";
4
+ import { join, resolve } from "node:path";
5
+ import { CliError } from "./errors.js";
6
+ function gitMetadata(cwd, label) {
7
+ const result = spawnSync("git", ["rev-parse", "--path-format=absolute", "--absolute-git-dir", "--git-common-dir"], { cwd, encoding: "utf8" });
8
+ const [gitDir, commonDir] = (result.stdout ?? "").trim().split("\n");
9
+ if (result.status !== 0 || !gitDir || !commonDir) {
10
+ throw new CliError("sandbox_git_metadata_missing", `workspace-write cannot resolve Git metadata for ${label} ${cwd}`);
11
+ }
12
+ return { gitDir: realpathSync(gitDir), commonDir: realpathSync(commonDir) };
13
+ }
14
+ function requireDirectory(path, label) {
15
+ try {
16
+ if (!lstatSync(path).isDirectory())
17
+ throw new Error("not a real directory");
18
+ const resolved = realpathSync(path);
19
+ if (!statSync(resolved).isDirectory())
20
+ throw new Error("not a directory");
21
+ return resolved;
22
+ }
23
+ catch {
24
+ throw new CliError("sandbox_path_missing", `workspace-write cannot grant ${label}: directory ${path} is missing or is not a directory`);
25
+ }
26
+ }
27
+ function gitStorePath(commonDir, name, label, mayBeCreated = false) {
28
+ const path = join(commonDir, name);
29
+ if (mayBeCreated) {
30
+ try {
31
+ if (!lstatSync(path).isDirectory())
32
+ throw new Error("not a real directory");
33
+ const resolved = realpathSync(path);
34
+ if (!statSync(resolved).isDirectory())
35
+ throw new Error("not a directory");
36
+ return resolved;
37
+ }
38
+ catch (error) {
39
+ if (error.code === "ENOENT")
40
+ return resolve(path);
41
+ throw new CliError("sandbox_path_missing", `workspace-write cannot grant ${label}: path ${path} is not a directory`);
42
+ }
43
+ }
44
+ return requireDirectory(path, label);
45
+ }
46
+ function worktreeRegistryPath(commonDir) {
47
+ const path = join(commonDir, "worktrees");
48
+ try {
49
+ if (!lstatSync(path).isDirectory())
50
+ throw new Error("not a real directory");
51
+ return realpathSync(path);
52
+ }
53
+ catch (error) {
54
+ if (error.code === "ENOENT")
55
+ return resolve(path);
56
+ throw new CliError("sandbox_path_missing", `workspace-write cannot grant Git worktree administration: ${path} is not a directory`);
57
+ }
58
+ }
59
+ function exactGitFilePath(commonDir, name) {
60
+ const path = resolve(commonDir, name);
61
+ try {
62
+ if (!lstatSync(path).isFile())
63
+ throw new Error("not a regular file");
64
+ }
65
+ catch (error) {
66
+ if (error.code !== "ENOENT") {
67
+ throw new CliError("sandbox_path_missing", `workspace-write cannot grant Git file ${path}: expected a regular file`);
68
+ }
69
+ }
70
+ return path;
71
+ }
72
+ /**
73
+ * The Git paths a linked-worktree agent needs to mutate. Directory entries are limited to the
74
+ * dynamic stores Git writes into; config, hooks and other worktree admin entries are not included.
75
+ */
76
+ export function gitSandboxWritablePaths(checkout, additionalCheckouts = []) {
77
+ const checkouts = [{ label: "agent checkout", path: checkout }, ...additionalCheckouts];
78
+ const metadata = checkouts.map(({ label, path }) => gitMetadata(path, label));
79
+ const commonDir = metadata[0].commonDir;
80
+ if (metadata.some((item) => item.commonDir !== commonDir)) {
81
+ throw new CliError("sandbox_git_metadata_mismatch", "workspace-write checkouts do not share one Git common directory");
82
+ }
83
+ const paths = new Set();
84
+ for (const item of metadata) {
85
+ if (item.gitDir !== commonDir)
86
+ paths.add(requireDirectory(item.gitDir, "the active worktree Git metadata"));
87
+ }
88
+ paths.add(gitStorePath(commonDir, "objects", "Git objects"));
89
+ paths.add(gitStorePath(commonDir, "refs", "Git refs"));
90
+ // Git may create reflogs on the first branch update in a freshly initialized repository.
91
+ paths.add(gitStorePath(commonDir, "logs", "Git logs", true));
92
+ // Git replaces these shared files via their lockfiles during branch updates and fetches. Exact
93
+ // file grants permit that lifecycle without making the common .git directory writable.
94
+ for (const name of ["packed-refs", "packed-refs.lock", "FETCH_HEAD", "FETCH_HEAD.lock"]) {
95
+ paths.add(exactGitFilePath(commonDir, name));
96
+ }
97
+ // The primary clone (unlike a linked worktree) updates these files while creating a branch,
98
+ // staging a commit, and recording the last commit message. Grant only those exact files.
99
+ if (metadata[0].gitDir === commonDir) {
100
+ for (const name of ["HEAD", "HEAD.lock", "index", "index.lock", "COMMIT_EDITMSG"]) {
101
+ paths.add(exactGitFilePath(commonDir, name));
102
+ }
103
+ }
104
+ return [...paths];
105
+ }
106
+ /** Paths that must remain explicitly unwritable even as Git's mutable stores are granted. */
107
+ export function gitSandboxDeniedPaths(checkout, additionalCheckouts = []) {
108
+ const { gitDir, commonDir } = gitMetadata(checkout, "agent checkout");
109
+ const worktrees = worktreeRegistryPath(commonDir);
110
+ const allowedEntries = new Set([gitDir, ...additionalCheckouts.map(({ label, path }) => gitMetadata(path, label).gitDir)]);
111
+ const entries = existsSync(worktrees) ? readdirSync(worktrees, { withFileTypes: true }) : [];
112
+ return [
113
+ join(commonDir, "config"),
114
+ join(commonDir, "hooks"),
115
+ ...entries
116
+ .filter((entry) => entry.isDirectory() && !allowedEntries.has(join(worktrees, entry.name)))
117
+ .map((entry) => join(worktrees, entry.name)),
118
+ ];
119
+ }
120
+ /** A deterministic, agent-specific metadata slot for the sandbox's create/remove worktree probe. */
121
+ export function sandboxProbeWorktreeAdminPath(checkout, agent) {
122
+ const { commonDir } = gitMetadata(checkout, "agent checkout");
123
+ return join(worktreeRegistryPath(commonDir), sandboxProbeWorktreeName(agent));
124
+ }
125
+ export function sandboxProbeWorktreeName(agent) {
126
+ if (!agent.trim())
127
+ throw new CliError("sandbox_agent_invalid", "workspace-write requires an agent name for the Git worktree probe");
128
+ return `.b9s-probe-${createHash("sha256").update(agent).digest("hex").slice(0, 16)}`;
129
+ }
package/dist/help.js CHANGED
@@ -205,7 +205,7 @@ Machine placement enforces configured session slots and reports machine pressure
205
205
  report your harness's /goal so the board shows what you are held to (Codex app
206
206
  threads and DeepSeek keep it where no file shows it; Claude Code's hook reads it itself)
207
207
  b9s hook claude-code [--event E] harness hook: prints new inbox items as hook JSON (installed by join)
208
- b9s watch --exec "<cmd>" [--interval seconds] [--unacked-after seconds] [--follow-delay seconds] [--startup-jitter-seconds 0..60] [--once] [--full] [--env A,B] [--activity path] [--prune] [--turn] [--harness codex|claude-code|dsh|antigravity] [--provider anthropic|deepseek] [--session id] [--machine-session-id uuid] [--turn-timeout min] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60] [--turn-coalesce-seconds 0..3600] [--turn-claude-runtime JSON] [--service|--launchd] event bridge: queue ONE numbered wake-up when something new arrives, then
208
+ b9s watch --exec "<cmd>" [--interval seconds] [--unacked-after seconds] [--follow-delay seconds] [--startup-jitter-seconds 0..60] [--once] [--full] [--env A,B] [--activity path] [--prune] [--turn] [--harness codex|claude-code|dsh|antigravity] [--provider anthropic|deepseek] [--session id] [--machine-session-id uuid] [--turn-timeout min] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60] [--turn-coalesce-seconds 0..3600] [--turn-claude-runtime JSON] [--turn-antigravity-runtime JSON] [--service|--launchd] event bridge: queue ONE numbered wake-up when something new arrives, then
209
209
  nothing more, for any reason, until the agent runs b9s wake ack <n>. An
210
210
  unacknowledged wake-up is logged after --unacked-after 1800 s (once an hour), never re-queued.
211
211
  Tiers: direct (@you, replies, assignments, operator) wake now; @role wakes now;
@@ -216,7 +216,7 @@ Machine placement enforces configured session slots and reports machine pressure
216
216
  Set BSCHAT_WATCH_DEBUG=1 for per-poll item counts, tier and wake decisions.
217
217
  --service (launchd on macOS, systemd on Linux; --launchd is the same). --turn runs each turn
218
218
  itself (--harness codex|claude-code|dsh|antigravity --session <id> [--machine-session-id uuid]); without activated judgment capture,
219
- --turn-claude-runtime is internal Claude Code runtime settings used by b9s start to rebuild workspace-write permissions for each turn's cwd.
219
+ --turn-claude-runtime is internal Claude Code runtime settings used by b9s start to rebuild workspace-write permissions for each turn's cwd; --turn-antigravity-runtime does the same for Antigravity's Git paths and prepared unit worktree.
220
220
  3 consecutive turns without an agent-key call fault it and six unproductive turns in a rolling hour also fault.
221
221
  With judgment capture activated, these become triggers and the watcher pauses before the next turn;
222
222
  hard-budget caps still reserve each launch independently. Capture defaults off; hard caps alone do not activate it.
@@ -228,9 +228,9 @@ Machine placement enforces configured session slots and reports machine pressure
228
228
  fault with b9s-admin machine session resume.
229
229
  Codex: b9s watch --exec "codex queue --thread <id> --message {summary}" --service
230
230
  b9s update [--no-restart] the same as install --latest: upgrade this machine's b9s, repair PATH aliases,
231
- restart services on that install without waiting on one stop, and report failures
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 services resolving to it; other installs are left alone and named
233
+ restart its daemon first, then watchers in batches of 5 with 5 s between batches
234
234
  b9s sandbox probe [--checkout <dir>] [--api <host>] [--out <file>] [--nonce <id>]
235
235
  what the sandbox this runs in really allows: where commands run, which tools
236
236
  are there, what git can do, which hosts answer, what is writable; facts only
package/dist/install.js CHANGED
@@ -519,10 +519,11 @@ export function rewriteServiceInstall(s, installBin) {
519
519
  return original;
520
520
  }
521
521
  /** Rewrites matching service definitions, then restarts the services on the updated install. */
522
- export async function restartInstallServices(installBin, services = watcherServices(), driver) {
522
+ export async function restartInstallServices(installBin, services = watcherServices(), driver, progress = () => { }, pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) {
523
523
  const installReal = realpathSync(installBin);
524
524
  const restarted = [];
525
525
  const notRestarted = [];
526
+ const failed = [];
526
527
  const matching = [];
527
528
  for (const service of services) {
528
529
  const program = service.args?.[0];
@@ -548,8 +549,9 @@ export async function restartInstallServices(installBin, services = watcherServi
548
549
  ensureWatcherSliceMemoryLimits();
549
550
  }
550
551
  catch (error) {
551
- notRestarted.push(`Linux watcher memory limits were not applied; services were not restarted: ${error.message}`);
552
- return { restarted, not_restarted: notRestarted };
552
+ const reason = `Linux watcher memory limits were not applied; service was not restarted: ${error.message}`;
553
+ failed.push(...matching.map((service) => `${service.label}: ${reason}`));
554
+ return { restarted, not_restarted: notRestarted, failed };
553
555
  }
554
556
  }
555
557
  const rewritten = [];
@@ -558,7 +560,7 @@ export async function restartInstallServices(installBin, services = watcherServi
558
560
  rewritten.push({ service, original: rewriteServiceInstall(service, installBin) });
559
561
  }
560
562
  catch (error) {
561
- notRestarted.push(`${service.label} resolves to ${installReal}, but was not restarted: ${error.message}`);
563
+ failed.push(`${service.label} resolves to ${installReal}, but was not restarted: ${error.message}`);
562
564
  }
563
565
  }
564
566
  const systemd = rewritten.filter(({ service }) => service.kind === "systemd");
@@ -567,29 +569,23 @@ export async function restartInstallServices(installBin, services = watcherServi
567
569
  if (reload.status !== 0) {
568
570
  for (const { service, original } of systemd) {
569
571
  writeFileAtomic(service.path, original);
570
- notRestarted.push(`${service.label} resolves to ${installReal}, but its rewritten unit could not be loaded`);
572
+ failed.push(`${service.label} resolves to ${installReal}, but its rewritten unit could not be loaded`);
571
573
  }
572
574
  spawnSync("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
573
575
  rewritten.splice(0, rewritten.length, ...rewritten.filter(({ service }) => service.kind !== "systemd"));
574
576
  }
575
577
  }
576
- const launchdServices = rewritten.filter(({ service }) => service.kind === "launchd");
577
- const systemdServices = rewritten.filter(({ service }) => service.kind === "systemd").map(({ service }) => service);
578
- for (const { service } of launchdServices) {
579
- try {
580
- reloadLaunchAgent(service.label, service.path);
581
- restarted.push(service.label);
582
- }
583
- catch (error) {
584
- notRestarted.push(`${service.label} resolves to ${installReal}, but could not be restarted: ${error.message}`);
585
- }
586
- }
587
- if (systemdServices.length) {
588
- const report = await restartWatcherServices(systemdServices, driver);
589
- restarted.push(...report.restarted);
590
- notRestarted.push(...report.not_started.map(({ label, reason }) => `${label} resolves to ${installReal}, but could not be restarted: ${reason}`));
591
- }
592
- return { restarted, not_restarted: notRestarted };
578
+ const restartable = rewritten.map(({ service }) => service);
579
+ const daemon = restartable.find((service) => service.label === MACHINE_LABEL);
580
+ const watchers = restartable.filter((service) => service.label.startsWith(WATCH_LABEL_PREFIX)).sort((a, b) => a.label.localeCompare(b.label));
581
+ const report = await restartServicesInBatches(daemon ? [daemon] : [], watchers, {
582
+ driver,
583
+ progress,
584
+ pause,
585
+ });
586
+ restarted.push(...report.restarted);
587
+ failed.push(...report.not_started.map(({ label, reason }) => `${label} resolves to ${installReal}, but could not be restarted: ${reason}`));
588
+ return { restarted, not_restarted: notRestarted, failed };
593
589
  }
594
590
  /**
595
591
  * A systemd user unit that keeps a watcher running. KillMode=process: a restart or upgrade stops the
@@ -722,6 +718,43 @@ export function requestWatcherRestart(s) {
722
718
  return restartLaunchAgent(s.label);
723
719
  return spawnSync("systemctl", ["--user", "--no-block", "restart", `${s.label}.service`], { stdio: "ignore" }).status === 0;
724
720
  }
721
+ export const INSTALL_RESTART_BATCH_SIZE = 5;
722
+ export const INSTALL_RESTART_BATCH_PAUSE_MS = 5_000;
723
+ /** Start the daemon first, then cap watcher startup bursts and let each wave settle before the next. */
724
+ export async function restartServicesInBatches(daemon, watchers, options = {}) {
725
+ const driver = options.driver ?? watcherRestartDriver;
726
+ const progress = options.progress ?? (() => { });
727
+ const pause = options.pause ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
728
+ const batchSize = options.batchSize ?? INSTALL_RESTART_BATCH_SIZE;
729
+ const pauseMs = options.pauseMs ?? INSTALL_RESTART_BATCH_PAUSE_MS;
730
+ if (!Number.isInteger(batchSize) || batchSize < 1)
731
+ throw new RangeError("restart batch size must be a positive integer");
732
+ if (!Number.isFinite(pauseMs) || pauseMs < 0)
733
+ throw new RangeError("restart batch pause must be non-negative");
734
+ const restarted = [];
735
+ const notStarted = [];
736
+ if (daemon.length) {
737
+ progress("Restarting machine daemon before watcher services");
738
+ const report = await restartWatcherServices(daemon, driver);
739
+ restarted.push(...report.restarted);
740
+ notStarted.push(...report.not_started);
741
+ }
742
+ const batchCount = Math.ceil(watchers.length / batchSize);
743
+ for (let offset = 0; offset < watchers.length; offset += batchSize) {
744
+ const batch = watchers.slice(offset, offset + batchSize);
745
+ const batchNumber = Math.floor(offset / batchSize) + 1;
746
+ progress(`Watcher batch ${batchNumber}/${batchCount}: restarting ${batch.length} services`);
747
+ const report = await restartWatcherServices(batch, driver);
748
+ restarted.push(...report.restarted);
749
+ notStarted.push(...report.not_started);
750
+ progress(`Watcher batch ${batchNumber}/${batchCount}: ${report.restarted.length}/${batch.length} services returned`);
751
+ if (batchNumber < batchCount) {
752
+ progress(`Pausing ${pauseMs / 1000}s before the next watcher batch`);
753
+ await pause(pauseMs);
754
+ }
755
+ }
756
+ return { restarted, not_started: notStarted };
757
+ }
725
758
  function watcherPid(service) {
726
759
  if (service.kind === "systemd") {
727
760
  const r = spawnSync("systemctl", ["--user", "show", "--property=MainPID", "--value", `${service.label}.service`], { encoding: "utf8" });
@@ -746,7 +779,14 @@ export async function restartWatcherServices(services, driver = watcherRestartDr
746
779
  const pending = new Map();
747
780
  const notStarted = [];
748
781
  for (const service of services) {
749
- const previousPid = driver.pid(service);
782
+ let previousPid;
783
+ try {
784
+ previousPid = driver.pid(service);
785
+ }
786
+ catch (error) {
787
+ notStarted.push({ label: service.label, reason: `could not read pre-restart process: ${error.message}` });
788
+ continue;
789
+ }
750
790
  let accepted = false;
751
791
  try {
752
792
  accepted = driver.request(service);
@@ -1,14 +1,15 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { closeSync, existsSync, mkdirSync, openSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { closeSync, existsSync, mkdirSync, openSync, readdirSync, realpathSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
- import { delimiter, dirname, join } from "node:path";
4
+ import { basename, delimiter, dirname, join } from "node:path";
5
5
  import { configRoot } from "./config.js";
6
6
  import { CliError } from "./errors.js";
7
7
  import { CLI_VERSION } from "./version.js";
8
+ import { sandboxProbeWorktreeName } from "./git-sandbox-paths.js";
8
9
  export const PROBE_CHECKS = [
9
10
  "cwd_is_checkout", "origin_is_https",
10
11
  "tool_node", "tool_npm", "tool_npx", "tool_git", "tool_b9s",
11
- "git_branch", "git_object", "git_worktree", "git_remote_read",
12
+ "git_branch", "git_object", "git_worktree", "git_other_worktree", "git_remote_read",
12
13
  "net_api", "net_other_host",
13
14
  "write_checkout", "write_checkout_parent", "write_b9s_home",
14
15
  "write_git_config", "write_git_hooks", "write_home", "write_node_install",
@@ -112,18 +113,39 @@ export async function runSandboxProbe(options) {
112
113
  throw new Error(made.err || "git commit-tree failed");
113
114
  return made.out.slice(0, 12);
114
115
  });
115
- const sibling = join(dirname(toplevel), `.b9s-probe-${nonce}`);
116
116
  checks.git_worktree = observe(() => {
117
- const made = git(["worktree", "add", "--detach", "--no-checkout", sibling, "HEAD"], 60_000);
118
- if (made.status !== 0)
117
+ const agent = env.BSCHAT_AGENT;
118
+ const target = join(toplevel, agent ? sandboxProbeWorktreeName(agent) : `.b9s-probe-${nonce}`);
119
+ const adminPath = join(commonDir, "worktrees", basename(target));
120
+ if (existsSync(target) || existsSync(adminPath))
121
+ throw new Error(`the reserved sandbox probe worktree path already exists: ${target}`);
122
+ const made = git(["worktree", "add", "--detach", "--no-checkout", target, "HEAD"], 60_000);
123
+ if (made.status !== 0) {
124
+ if (existsSync(target))
125
+ rmSync(target, { recursive: true, force: true });
126
+ if (existsSync(adminPath))
127
+ rmSync(adminPath, { recursive: true, force: true });
119
128
  throw new Error(made.err || "git worktree add failed");
120
- const gone = git(["worktree", "remove", "--force", sibling]);
129
+ }
130
+ const gone = git(["worktree", "remove", "--force", target]);
121
131
  if (gone.status !== 0) {
122
- rmSync(sibling, { recursive: true, force: true });
123
- git(["worktree", "prune"]);
132
+ rmSync(target, { recursive: true, force: true });
133
+ if (existsSync(adminPath))
134
+ rmSync(adminPath, { recursive: true, force: true });
124
135
  throw new Error(`added a worktree but could not remove it: ${gone.err}`);
125
136
  }
126
137
  });
138
+ checks.git_other_worktree = observe(() => {
139
+ const currentGitDir = realpathSync(gitDir);
140
+ const entries = readdirSync(join(commonDir, "worktrees"), { withFileTypes: true })
141
+ .filter((entry) => entry.isDirectory() && realpathSync(join(commonDir, "worktrees", entry.name)) !== currentGitDir);
142
+ const other = entries[0];
143
+ if (!other)
144
+ throw new Error("no other linked-worktree entry is available to check");
145
+ const result = createAndRemove(join(commonDir, "worktrees", other.name), nonce);
146
+ if (!result.ok)
147
+ throw new Error(result.detail ?? `another worktree entry was refused: ${other.name}`);
148
+ });
127
149
  const remote = git(["ls-remote", "origin", "HEAD"], 30_000);
128
150
  // Exit 0 is the remote answering; a remote whose HEAD names no branch yet answers with nothing.
129
151
  checks.git_remote_read = remote.status === 0
@@ -160,12 +182,13 @@ const UNMEASURED = "not measured for this harness yet";
160
182
  const CODEX_WORKSPACE_WRITE = "measured 2026-11-19 in Codex workspace-write: writes to the user's home and the Node installation are refused";
161
183
  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";
162
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";
163
186
  export function expectedFor(harness, sandbox) {
164
187
  const works = { expected: "works" };
165
188
  const base = {
166
189
  cwd_is_checkout: works, origin_is_https: { expected: "any", note: UNMEASURED },
167
190
  tool_node: works, tool_npm: works, tool_npx: works, tool_git: works, tool_b9s: works,
168
- git_branch: works, git_object: works, git_worktree: works, git_remote_read: works,
191
+ git_branch: works, git_object: works, git_worktree: works, git_other_worktree: { expected: "any", note: UNMEASURED }, git_remote_read: works,
169
192
  net_api: works, net_other_host: { expected: "any", note: UNMEASURED },
170
193
  write_checkout: works, write_checkout_parent: works, write_b9s_home: works,
171
194
  write_git_config: { expected: "any", note: ACCEPTED_GIT }, write_git_hooks: { expected: "any", note: ACCEPTED_GIT },
@@ -178,10 +201,18 @@ export function expectedFor(harness, sandbox) {
178
201
  if (sandbox !== "workspace-write")
179
202
  throw new CliError("usage", `no sandbox expectations for ${sandbox}`);
180
203
  if (harness === "antigravity") {
181
- // Measured with agy 1.5.12 on Linux, 2026-11-19: the terminal sandbox reaches only allow-listed
182
- // hosts over an HTTP proxy (an SSH origin cannot resolve), and the Node installation is mounted
183
- // read-only.
184
- return { ...base, origin_is_https: works, write_node_install: { expected: "refused" } };
204
+ // These are the outcomes required by the scoped grants. A live Linux probe is required before
205
+ // the policy can be described as measured.
206
+ return {
207
+ ...base,
208
+ origin_is_https: works,
209
+ git_worktree: { expected: "refused", note: ANTIGRAVITY_GIT_SCOPE },
210
+ write_checkout_parent: { expected: "refused", note: ANTIGRAVITY_GIT_SCOPE },
211
+ git_other_worktree: { expected: "refused", note: ANTIGRAVITY_GIT_SCOPE },
212
+ write_git_config: { expected: "refused", note: ANTIGRAVITY_GIT_SCOPE },
213
+ write_git_hooks: { expected: "refused", note: ANTIGRAVITY_GIT_SCOPE },
214
+ write_node_install: { expected: "refused" },
215
+ };
185
216
  }
186
217
  if (harness === "claude-code") {
187
218
  // Its sandbox proxies HTTP(S) only, so an SSH origin cannot be reached (the reason b9s start
@@ -191,6 +222,7 @@ export function expectedFor(harness, sandbox) {
191
222
  ...base,
192
223
  origin_is_https: works,
193
224
  git_worktree: { expected: "refused", note: CLAUDE_WORKTREE },
225
+ git_other_worktree: { expected: "any", note: CLAUDE_WORKTREE },
194
226
  write_git_config: { expected: "refused", note: CLAUDE_WORKSPACE_WRITE },
195
227
  write_git_hooks: { expected: "refused", note: CLAUDE_WORKSPACE_WRITE },
196
228
  write_home: { expected: "refused", note: CLAUDE_WORKSPACE_WRITE },
@@ -229,7 +261,7 @@ const LABEL = {
229
261
  cwd_is_checkout: "commands run in the agent's checkout",
230
262
  origin_is_https: "origin is reached over HTTPS",
231
263
  tool_node: "node runs", tool_npm: "npm runs", tool_npx: "npx runs", tool_git: "git runs", tool_b9s: "b9s is on PATH",
232
- git_branch: "git can create a branch", git_object: "git can write a commit object", git_worktree: "git can add a worktree beside the checkout", git_remote_read: "git can read origin",
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",
233
265
  net_api: "the BenignSwarm API is reachable", net_other_host: "a host outside the allow-list is reachable",
234
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",
235
267
  write_git_config: "the clone's git config is writable", write_git_hooks: "the clone's git hooks are writable",
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.134";
1
+ export const CLI_VERSION = "0.12.136";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.134",
3
+ "version": "0.12.136",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {