benignswarm 0.12.139 → 0.12.141

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
@@ -47,7 +47,7 @@ export const BOOL_FLAGS = [
47
47
  "approve", "turn", "service", "print-hooks", "create", "rotate", "drain", "codex-userns", "bwrap-userns", "agy-userns", "print-apparmor",
48
48
  "cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "assessment-only",
49
49
  "no-wait-verify", "preview", "remove-empty", "dry-run", "quota-substitution",
50
- "in-container", "retrieve-ec2", "stdin", "context-confirmed", "confirm-compatible", "no-commits-beyond-target",
50
+ "in-container", "retrieve-ec2", "stdin", "context-confirmed", "confirm-compatible", "move-provisioned", "provisioned", "no-commits-beyond-target",
51
51
  ];
52
52
  export function parse(argv) {
53
53
  const options = {};
@@ -1,11 +1,11 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { boundSessions } from "../sessions.js";
3
3
  import { accessSync, constants, existsSync, readFileSync, readdirSync, realpathSync, statfsSync } from "node:fs";
4
- import { basename, delimiter, join } from "node:path";
4
+ import { basename, delimiter, dirname, join } from "node:path";
5
5
  import { homedir, platform } from "node:os";
6
6
  import { bool } from "../args.js";
7
7
  import { CliError } from "../errors.js";
8
- import { removeCopyCommand, binVersion, ensureCommandLinks, ensureInstall, latestPublished, launchdLoadedIn, launchdPid, launchdSessionNow, lingerEnabled, MACHINE_LABEL, ownNpm, plistLaunchdDomain, readInstall, restartInstallServices, watcherServices } from "../install.js";
8
+ import { removeCopyCommand, binVersion, ensureCommandLinks, ensureInstall, latestPublished, launchdLoadedIn, launchdPid, launchdSessionNow, lingerEnabled, MACHINE_LABEL, ownNpm, plistLaunchdDomain, readInstall, restartInstallServices, serviceUsesInstall, serviceUsesNode, watcherServices } from "../install.js";
9
9
  import { CLI_VERSION } from "../version.js";
10
10
  import { CODEX_REQUIREMENTS_PATH, codexHooksDuplicateWithManagedPolicy, reconcileCodexHooks, refreshInstalledHooks } from "../harness.js";
11
11
  import { configRoot } from "../config.js";
@@ -20,11 +20,18 @@ export async function install(p, out) {
20
20
  const want = p.positionals[1];
21
21
  if (want && !/^\d+\.\d+\.\d+$/.test(want))
22
22
  throw new CliError("usage", "install [<version> | --latest] e.g. b9s install --latest, b9s install 0.12.38");
23
- // Explicit install is the only command that may move the machine record to this Node's npm.
24
- const npm = ownNpm();
23
+ const move = bool(p.flags, "move-provisioned");
24
+ const reason = typeof p.flags.reason === "string" ? p.flags.reason.trim() : "";
25
+ if (prev?.provisioned && move && !reason)
26
+ throw new CliError("provisioned_move_reason_required", "moving a provisioned install requires --reason", "Use --move-provisioned --reason '<why>' only when deliberately changing this machine's Node");
27
+ const npm = prev?.provisioned && !move ? prev.npm : ownNpm();
25
28
  const version = want ?? (bool(p.flags, "latest") ? latestPublished(npm) : CLI_VERSION);
26
- const rec = ensureInstall(version, (m) => process.stderr.write(`b9s: ${m}\n`), npm);
29
+ const provisioned = !!(prev?.provisioned || bool(p.flags, "provisioned"));
30
+ const log = (m) => process.stderr.write(`b9s: ${m}\n`);
31
+ const rec = provisioned ? ensureInstall(version, log, npm, true, !!(prev?.provisioned && move)) : ensureInstall(version, log, npm);
27
32
  const lines = [`b9s ${rec.version} is this machine's install: ${rec.bin}`];
33
+ if (prev?.provisioned && move)
34
+ lines.push(`Provisioned Node moved by request: ${reason}`);
28
35
  const aliases = ensureCommandLinks(rec.bin);
29
36
  if (aliases.created.length)
30
37
  lines.push(`Updated PATH links: ${aliases.created.join(", ")}`);
@@ -173,6 +180,12 @@ export async function doctor(_p, out) {
173
180
  checks.push({ ok: false, what: `recorded install ${rec.bin} does not run`, fix: "npx -y benignswarm install" });
174
181
  else
175
182
  checks.push({ ok: true, what: `recorded install: ${rec.bin} (${recVersion})` });
183
+ if (rec?.provisioned) {
184
+ const expectedNode = join(homedir(), ".local", "node", "bin");
185
+ checks.push(dirname(rec.bin) === expectedNode && dirname(rec.npm) === expectedNode
186
+ ? { ok: true, what: `provisioned Node is pinned at ${expectedNode}` }
187
+ : { ok: false, what: `provisioned install is not using ${expectedNode}: b9s ${rec.bin}, npm ${rec.npm}`, fix: "re-run b9s-admin machine add or deliberately move with b9s install --move-provisioned --reason '<why>'" });
188
+ }
176
189
  // Every b9s on PATH, the one the shell finds first marked.
177
190
  const seen = new Set();
178
191
  const onPath = [];
@@ -279,15 +292,18 @@ export async function doctor(_p, out) {
279
292
  checks.push({ ok: false, what: "linger is off: systemd stops the watchers when your last login session on this machine ends", fix: "loginctl enable-linger $USER" });
280
293
  for (const w of services) {
281
294
  const args = w.args ?? [];
295
+ const serviceKind = w.label === MACHINE_LABEL ? "machine daemon" : "watcher";
282
296
  if (w.kind === "systemd") {
283
- const short = w.label.replace("org.benignswarm.watch.", "");
297
+ const short = w.label === MACHINE_LABEL ? "machine daemon" : w.label.replace("org.benignswarm.watch.", "");
284
298
  if (!args.length) {
285
299
  checks.push({ ok: false, what: `watcher ${short}: unreadable unit ${w.path}` });
286
300
  continue;
287
301
  }
288
302
  const ver = binVersion(args[0]);
289
- if (rec && args[0] !== rec.bin)
290
- checks.push({ ok: false, what: `watcher ${short} runs ${args[0]} (${ver ?? "does not run"}), not the recorded install`, fix: "re-run its b9s watch ... --service (it uses the recorded install and reloads)" });
303
+ if (rec && !serviceUsesInstall(args[0], rec.bin))
304
+ checks.push({ ok: false, what: `${serviceKind} ${short} runs ${args[0]} (${ver ?? "does not run"}), not the recorded install`, fix: "re-run its b9s watch ... --service (it uses the recorded install and reloads)" });
305
+ if (rec?.provisioned && !serviceUsesNode(w.pathEnv, rec.bin))
306
+ checks.push({ ok: false, what: `${serviceKind} ${short} PATH does not select the recorded Node runtime`, fix: "re-run its b9s watch ... --service to capture the pinned Node PATH" });
291
307
  const active = (spawnSync("systemctl", ["--user", "is-active", `${w.label}.service`], { encoding: "utf8" }).stdout ?? "").trim();
292
308
  checks.push(active === "active" ? { ok: true, what: `watcher ${short}: running ${args[0]} (${ver ?? "?"})` } : { ok: false, what: `watcher ${short} is ${active || "unknown"}; see ~/.b9s/logs/watch.${short}.err.log`, fix: `systemctl --user daemon-reload && systemctl --user restart ${w.label}.service` });
293
309
  continue;
@@ -305,8 +321,10 @@ export async function doctor(_p, out) {
305
321
  const pidNum = launchdPid(w.label);
306
322
  const pid = pidNum === null ? undefined : String(pidNum);
307
323
  const ver = binVersion(args[0]);
308
- if (rec && args[0] !== rec.bin)
309
- checks.push({ ok: false, what: `${short} runs ${args[0]} (${ver ?? "does not run"}), not the recorded install`, fix: isDaemon ? "run b9s machine service to rewrite and restart the daemon" : "re-run its b9s watch ... --launchd (it uses the recorded install and reloads)" });
324
+ if (rec && !serviceUsesInstall(args[0], rec.bin))
325
+ checks.push({ ok: false, what: `${serviceKind} ${short} runs ${args[0]} (${ver ?? "does not run"}), not the recorded install`, fix: isDaemon ? "run b9s machine service to rewrite and restart the daemon" : "re-run its b9s watch ... --launchd (it uses the recorded install and reloads)" });
326
+ if (rec?.provisioned && !serviceUsesNode(w.pathEnv, rec.bin))
327
+ checks.push({ ok: false, what: `${serviceKind} ${short} PATH does not select the recorded Node runtime`, fix: "re-run its b9s watch ... --launchd to capture the pinned Node PATH" });
310
328
  if (listed.status !== 0) {
311
329
  checks.push({ ok: false, what: isDaemon ? "machine daemon is not loaded; see b9s machine status" : `${short} is not loaded`, fix: isDaemon ? "run b9s machine service to write and load the daemon service" : `launchctl bootstrap ${domain} ${w.path} (or delete the plist if the agent is gone)` });
312
330
  continue;
@@ -45,10 +45,7 @@ step() { echo "BSCHAT-STEP $1 $2 \${3:-}"; }
45
45
  fail() { step "$1" failed "$2"; exit 1; }
46
46
  mkdir -p "$HOME/.local/bin"
47
47
  case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) export PATH="$HOME/.local/bin:$PATH"; printf '\\nexport PATH="$HOME/.local/bin:$PATH" # b9s\\n' >> "$HOME/.profile"; step path done "added ~/.local/bin to ~/.profile" ;; esac
48
- major=0
49
- if command -v node >/dev/null 2>&1; then major=$(node -p 'process.versions.node.split(".")[0]'); fi
50
- if [ "$major" -ge 22 ]; then step node ok "$(node --version) $(command -v node)"
51
- else
48
+ {
52
49
  os=$(uname -s | tr A-Z a-z); case "$(uname -m)" in x86_64|amd64) a=x64 ;; aarch64|arm64) a=arm64 ;; *) fail node "unsupported CPU $(uname -m)" ;; esac
53
50
  base=https://nodejs.org/dist/latest-v24.x
54
51
  f=$(curl -fsSL $base/SHASUMS256.txt | awk -v want="node-v[0-9.]*-$os-$a.tar.xz" '$2 ~ "^"want"$" {print $2}') || fail node "cannot reach nodejs.org"
@@ -58,12 +55,13 @@ else
58
55
  rm -rf "$HOME/.local/node" && mkdir -p "$HOME/.local/node" && tar -xJf "$tmp/$f" -C "$HOME/.local/node" --strip-components=1 || fail node "unpack failed"
59
56
  rm -rf "$tmp"
60
57
  for b in node npm npx; do ln -sf "$HOME/.local/node/bin/$b" "$HOME/.local/bin/$b"; done
61
- hash -r; step node done "$(node --version) in ~/.local/node"
62
- fi
58
+ step node done "$("$HOME/.local/node/bin/node" --version) in ~/.local/node"
59
+ }
60
+ export PATH="$HOME/.local/node/bin:/usr/bin:/bin:/usr/sbin:/sbin"
63
61
  # --prefer-online: a cached package listing from before the publish says the version does not exist.
64
- npx -y --prefer-online -p benignswarm@${version} b9s install ${version} >/tmp/bschat-install.$$ 2>&1 || fail b9s "$(grep -v 'complete log' /tmp/bschat-install.$$ | grep -m1 -iE 'error|failed' || tail -1 /tmp/bschat-install.$$)"
62
+ "$HOME/.local/node/bin/npm" exec --yes --prefer-online --package=benignswarm@${version} -- b9s install ${version} --provisioned >/tmp/bschat-install.$$ 2>&1 || fail b9s "$(grep -v 'complete log' /tmp/bschat-install.$$ | grep -m1 -iE 'error|failed' || tail -1 /tmp/bschat-install.$$)"
65
63
  rm -f /tmp/bschat-install.$$
66
- bin=$(node -p 'require(require("os").homedir()+"/.b9s/install.json").bin')
64
+ bin=$("$HOME/.local/node/bin/node" -p 'require(require("os").homedir()+"/.b9s/install.json").bin')
67
65
  for b in b9s b9s-admin bschat bschat-admin; do [ -e "$HOME/.local/bin/$b" ] || ln -sf "$(dirname "$bin")/$b" "$HOME/.local/bin/$b"; done
68
66
  step b9s ok "$("$bin" --version) $bin"
69
67
  `;
@@ -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, restartServicesInBatches, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices, INSTALL_RESTART_BATCH_SIZE, INSTALL_RESTART_BATCH_PAUSE_MS } from "../install.js";
19
+ import { installService, launchdFacts, launchdFactsLine, launchdGuidance, launchdSessionNow, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartServicesInBatches, restartWatcher, serviceActive, serviceUsesInstall, serviceUsesNode, 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";
@@ -2870,6 +2870,13 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
2870
2870
  // macOS: which launchd domain the services use, so a headless Mac is visible, never silent (WU #478).
2871
2871
  ...(platform() === "darwin" ? { launchd: (probes?.launchd ?? launchdFacts)() } : {}),
2872
2872
  bschat: { version: CLI_VERSION, bin: requireInstall().bin },
2873
+ b9s_services: watcherServices().map((service) => ({
2874
+ label: service.label,
2875
+ program: service.args?.[0] ?? null,
2876
+ install_match: !!service.args?.[0] && serviceUsesInstall(service.args[0], requireInstall().bin),
2877
+ provisioned: readInstall()?.provisioned === true,
2878
+ node_match: readInstall()?.provisioned === true ? serviceUsesNode(service.pathEnv, requireInstall().bin) : null,
2879
+ })),
2873
2880
  // IPv4 only: temporary IPv6 addresses rotate, and this report is compared for change.
2874
2881
  network: { interfaces: interfaceFacts(true) },
2875
2882
  git_identity: gitIdentity,
@@ -6,7 +6,7 @@ import { claudeSettings, probeFor, turnHarness } from "../harnesses.js";
6
6
  import { ANTIGRAVITY_SETTINGS_PLACEHOLDER, antigravitySettings } from "../antigravity.js";
7
7
  import { cleanupAntigravitySandboxProbeRefs } from "../sandbox-probe.js";
8
8
  import { applyAck } from "./wake.js";
9
- import { launchdSessionTypeXml, lingerEnabled, plistLaunchdDomain, loadSystemdUnit, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
9
+ import { launchdSessionTypeXml, lingerEnabled, machineDaemonPath, plistLaunchdDomain, loadSystemdUnit, readInstall, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
10
10
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statfsSync, writeFileSync } from "node:fs";
11
11
  import { createHash } from "node:crypto";
12
12
  import { homedir, totalmem, userInfo } from "node:os";
@@ -16,7 +16,7 @@ import { agentRef, configRoot, loadAgent, resolveAgentName } from "../config.js"
16
16
  import { Client } from "../client.js";
17
17
  import { heartbeatIfActive, reportWatcherHeartbeat, resolveActivitySource } from "../heartbeat.js";
18
18
  import { scanProject, unitWorktrees } from "./worktrees.js";
19
- import { formatBytes, freeSpaceProbe, pruneReport, removePrunable } from "../git.js";
19
+ import { branchAndHead, formatBytes, freeSpaceProbe, pruneReport, removePrunable } from "../git.js";
20
20
  import { CliError } from "../errors.js";
21
21
  import { claudeTurnEnv } from "../providers.js";
22
22
  import { acquireWatchLock } from "../lock.js";
@@ -484,7 +484,7 @@ export function withAgentEnv(ref, work) {
484
484
  }
485
485
  }
486
486
  /** Prepare an owned unit before launching its next turn, outside the harness sandbox. */
487
- async function prepareTurnWorktree(name, binding, allowSuperseded = false) {
487
+ async function prepareTurnWorktree(name, binding, allowSuperseded = false, dependencies = {}) {
488
488
  const creds = loadAgent(name);
489
489
  const project = binding.project ?? creds.project;
490
490
  if (!project)
@@ -512,9 +512,35 @@ async function prepareTurnWorktree(name, binding, allowSuperseded = false) {
512
512
  throw new Error(`assignment event ${binding.assignment_event_id} is no longer current`);
513
513
  }
514
514
  const process = await client.call("GET", `/projects/${encodeURIComponent(project)}/process`);
515
- const { prepareWorktreeForWatcher } = await import("./wu.js");
515
+ const { contextDecisionForStart, prepareWorktreeForWatcher } = await import("./wu.js");
516
516
  const prepared = withAgentEnv(agentRef(creds), () => prepareWorktreeForWatcher(binding.work_unit_number, unit, process.process?.definition, process.checkout?.exclude ?? []));
517
- return { number: binding.work_unit_number, path: prepared.path, status: unit.status };
517
+ const restrictedWorkspaceWrite = dependencies.antigravityRuntime?.sandbox === "workspace-write" || dependencies.claudeRuntime?.sandbox === "workspace-write";
518
+ const startedUnitRecovery = unit.status !== "assigned" && prepared.recoveryRequired;
519
+ if (prepared.needsRecord && restrictedWorkspaceWrite && startedUnitRecovery) {
520
+ const location = branchAndHead(prepared.path);
521
+ if (!location.branch || !location.head || location.branch !== prepared.branch)
522
+ throw new Error(`prepared worktree ${prepared.path} did not resolve to its expected branch and commit`);
523
+ const contextDecision = await contextDecisionForStart(client, base, unit, name, { positionals: [], flags: {} }, record.events ?? []);
524
+ if (contextDecision && "pending_clear" in contextDecision) {
525
+ throw new CliError("context_action_required", `WU #${unit.number} has a pending fresh-thread context clear; the watcher will start the fresh thread before recording this checkout`);
526
+ }
527
+ await client.call("POST", base + "/start", {
528
+ branch: location.branch,
529
+ head: location.head,
530
+ worktree: prepared.path,
531
+ mode: prepared.mode,
532
+ context: { pct: null, tokens: null, window: null, source: "unknown", measured_at: null, reason: "watcher recorded prepared worktree before launching turn" },
533
+ compactions_since_last: 0,
534
+ compactions_reason: null,
535
+ ...(contextDecision ? { context_decision: contextDecision } : {}),
536
+ });
537
+ const verified = await client.call("GET", base);
538
+ if (verified.unit?.status !== "open" || verified.unit?.branch !== location.branch || verified.unit?.head !== location.head || verified.unit?.worktree !== prepared.path) {
539
+ throw new Error("server did not persist the prepared branch, commit and worktree exactly; refusing to launch the turn");
540
+ }
541
+ return { number: binding.work_unit_number, path: prepared.path, branch: location.branch, status: verified.unit.status, homeChanges: prepared.homeChanges, homeCommits: prepared.homeCommits, needsRecord: false };
542
+ }
543
+ return { number: binding.work_unit_number, path: prepared.path, branch: prepared.branch, status: unit.status, homeChanges: prepared.homeChanges, homeCommits: prepared.homeCommits, needsRecord: prepared.needsRecord };
518
544
  }
519
545
  catch (error) {
520
546
  throw new CliError("unit_worktree_prepare_failed", `watcher could not prepare the worktree for WU #${binding.work_unit_number}; no turn was started and the unit remains unchanged: ${error.message}`);
@@ -758,14 +784,24 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
758
784
  const bindingToPrepare = bindingResolution?.binding ?? deliveredBinding;
759
785
  let preparedWorktree = null;
760
786
  if (turnSink && bindingToPrepare) {
761
- preparedWorktree = await (dependencies.prepareWorktree ?? prepareTurnWorktree)(name, bindingToPrepare);
787
+ preparedWorktree = dependencies.prepareWorktree
788
+ ? await dependencies.prepareWorktree(name, bindingToPrepare)
789
+ : await prepareTurnWorktree(name, bindingToPrepare, false, dependencies);
762
790
  if (!preparedWorktree && dependencies.claudeRuntime?.sandbox === "workspace-write") {
763
791
  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
792
  }
765
793
  if (preparedWorktree) {
766
- wakePrefix.push(preparedWorktree.status === "assigned"
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.`
768
- : `The watcher prepared WU #${preparedWorktree.number}'s worktree at ${preparedWorktree.path}; continue working there.`);
794
+ wakePrefix.push(preparedWorktree.needsRecord
795
+ ? `The watcher prepared WU #${preparedWorktree.number}'s worktree at ${preparedWorktree.path}. Run b9s wu start ${preparedWorktree.number}${preparedWorktree.branch ? ` --branch ${preparedWorktree.branch}` : ""} from this checkout to record this worktree on the unit, then work in that path.`
796
+ : preparedWorktree.status === "assigned"
797
+ ? `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.`
798
+ : `The watcher prepared WU #${preparedWorktree.number}'s worktree at ${preparedWorktree.path}; continue working there.`);
799
+ if (preparedWorktree.homeChanges?.length) {
800
+ wakePrefix.push(`The home checkout was left untouched with uncommitted changes: ${preparedWorktree.homeChanges.join(", ")}. Review and carry over only the changes that belong in this unit; they were not copied automatically.`);
801
+ }
802
+ if (preparedWorktree.homeCommits?.length) {
803
+ wakePrefix.push(`The home checkout was left untouched with committed changes beyond its recorded head: ${preparedWorktree.homeCommits.join("; ")}. Those commits are present in the prepared unit worktree.`);
804
+ }
769
805
  }
770
806
  }
771
807
  const payload = u ? formatUpdates(omitMeasuresAlreadyIn(recoveryPrompt, u), wakePrefix, wakeSuffix) : null;
@@ -779,8 +815,12 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
779
815
  const workUnitBinding = bindingResolution?.binding ?? null;
780
816
  let turnExec = exec;
781
817
  let turnCwd;
782
- if (turnSink && provider && dependencies.claudeRuntime?.sandbox === "workspace-write")
818
+ if (turnSink && provider && (dependencies.claudeRuntime?.sandbox === "workspace-write" || dependencies.antigravityRuntime?.sandbox === "workspace-write")) {
819
+ if (bindingToPrepare && !preparedWorktree) {
820
+ throw new CliError("unit_worktree_missing", `workspace-write ${dependencies.antigravityRuntime ? "Antigravity" : "Claude Code"} cannot start WU #${bindingToPrepare.work_unit_number}: the watcher did not prepare its unit worktree`);
821
+ }
783
822
  turnCwd = preparedWorktree?.path ?? process.cwd();
823
+ }
784
824
  if (turnSink && dependencies.claudeRuntime && turnExec?.includes(CLAUDE_SETTINGS_PLACEHOLDER)) {
785
825
  const runtime = dependencies.claudeRuntime;
786
826
  const args = claudeSettings(runtime.sandbox, model, runtime.effort, process.cwd(), configRoot(), runtime.writableRoots, preparedWorktree ?? undefined);
@@ -1641,7 +1681,8 @@ export function installWatcherService(name, exec, interval, followDelay, extraEn
1641
1681
  mkdirSync(systemdUserDir(), { recursive: true });
1642
1682
  mkdirSync(logDir, { recursive: true });
1643
1683
  const args = [requireInstall().bin, "watch", "--as", name, "--exec", exec, "--interval", String(interval), "--follow-delay", String(followDelay), "--startup-jitter-seconds", String(startupJitterSeconds), ...(activity ? ["--activity", activity] : []), ...(prune ? ["--prune"] : []), ...turnArgs(turn)];
1644
- const env = { PATH: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", HOME: homedir(), ...extraEnv };
1684
+ const servicePath = readInstall()?.provisioned ? machineDaemonPath() : process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin";
1685
+ const env = { PATH: servicePath, HOME: homedir(), ...extraEnv };
1645
1686
  const path = join(systemdUserDir(), `${label}.service`);
1646
1687
  writeFileAtomic(path, systemdUnit(label, args, process.cwd(), env, logDir));
1647
1688
  loadSystemdUnit(label);
@@ -1671,6 +1712,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
1671
1712
  // The machine's one recorded install, never the running copy (an npx cache frozen at this
1672
1713
  // version) or whatever `b9s` a PATH lookup finds: an upgrade must reach every watcher.
1673
1714
  const program = [requireInstall().bin];
1715
+ const servicePath = readInstall()?.provisioned ? machineDaemonPath() : process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin";
1674
1716
  const plist = `<?xml version="1.0" encoding="UTF-8"?>
1675
1717
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1676
1718
  <plist version="1.0"><dict>
@@ -1686,7 +1728,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
1686
1728
  <string>--startup-jitter-seconds</string><string>${startupJitterSeconds}</string>${turnArgs(turn).length ? `
1687
1729
  ${turnArgs(turn).map((a) => `<string>${escapeXml(a)}</string>`).join("")}` : ""}
1688
1730
  </array>
1689
- <key>EnvironmentVariables</key><dict><key>PATH</key><string>${escapeXml(process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin")}</string><key>HOME</key><string>${homedir()}</string>${Object.entries(extraEnv).map(([k, v]) => `<key>${escapeXml(k)}</key><string>${escapeXml(v)}</string>`).join("")}</dict>
1731
+ <key>EnvironmentVariables</key><dict><key>PATH</key><string>${escapeXml(servicePath)}</string><key>HOME</key><string>${homedir()}</string>${Object.entries(extraEnv).map(([k, v]) => `<key>${escapeXml(k)}</key><string>${escapeXml(v)}</string>`).join("")}</dict>
1690
1732
  <key>WorkingDirectory</key><string>${escapeXml(process.cwd())}</string>
1691
1733
  <key>RunAtLoad</key><true/>
1692
1734
  <key>KeepAlive</key><true/>${launchdSessionTypeXml()}
@@ -2,7 +2,7 @@ import { processDeps, runUnderLock, lockRunRetries } from "./lock-run.js";
2
2
  import { forgetLockJob, lockJobKey, lockJobsFile, rememberLockJob, savedLockJobs, tokenForRelease } from "../lock-jobs.js";
3
3
  import { spawnSync } from "node:child_process";
4
4
  import { createHash, randomBytes, randomUUID } from "node:crypto";
5
- import { lstatSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import { existsSync, lstatSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
6
6
  import { bool, str } from "../args.js";
7
7
  import { Client } from "../client.js";
8
8
  import { agentRef, loadAgent, resolveAgentName, resolveModel } from "../config.js";
@@ -10,7 +10,7 @@ import { readState, updateState } from "../state.js";
10
10
  import { codexRollout, sessionsOf } from "../sessions.js";
11
11
  import { claudeSessionWithHookMetadata, sessionCompactions, sessionContext, sessionStart, sessionUsage } from "../usage.js";
12
12
  import { CliError, WrittenReceiptMismatchError } from "../errors.js";
13
- import { branchAndHead, commitAtTime, defaultMachine, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, isShaBranchName, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, worktreeForBranch } from "../git.js";
13
+ import { branchAndHead, commitAtTime, defaultMachine, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, isShaBranchName, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, worktreeForBranch, worktreeState } from "../git.js";
14
14
  import { join, resolve } from "node:path";
15
15
  import { formatStepRules, table } from "../output.js";
16
16
  import { restoreRecoveryArchive, sha256 as recoverySha256 } from "../recovery-archive.js";
@@ -80,7 +80,7 @@ export function assignmentGuidanceOutput(warnings = []) {
80
80
  : "";
81
81
  }
82
82
  /** Prepare and verify the action metadata required before a work unit starts. */
83
- async function contextDecisionForStart(client, base, unit, name, p, events = []) {
83
+ export async function contextDecisionForStart(client, base, unit, name, p, events = []) {
84
84
  const snapshot = unit.context_policy;
85
85
  if (!snapshot || !["keep", "compact", "clear", "agent-decides"].includes(snapshot.resolved))
86
86
  return undefined;
@@ -1390,17 +1390,105 @@ function assertNotShaBranch(branch, flag = "--branch") {
1390
1390
  }
1391
1391
  }
1392
1392
  export function prepareWorktreeForWatcher(n, unit, def, exclude = []) {
1393
- const prepared = prepareWorktree(n, unit, def, { positionals: [], flags: {} }, exclude);
1393
+ const home = resolve(process.cwd());
1394
+ const samePath = (a, b) => {
1395
+ try {
1396
+ return realpathSync(a) === realpathSync(b);
1397
+ }
1398
+ catch {
1399
+ return resolve(a) === resolve(b);
1400
+ }
1401
+ };
1402
+ const recorded = typeof unit.worktree === "string" && unit.worktree.length ? unit.worktree : null;
1403
+ const branchCheckout = typeof unit.branch === "string" && unit.branch ? worktreeForBranch(unit.branch) : null;
1404
+ const homeCheckoutRecorded = (recorded !== null && samePath(recorded, home)) || (branchCheckout !== null && samePath(branchCheckout, home));
1405
+ const recordedWorktreeMissing = recorded !== null && !existsSync(recorded);
1406
+ const missingWithoutSafeLinkedBranch = recordedWorktreeMissing && (!branchCheckout || samePath(branchCheckout, home));
1407
+ const startedUnitWithoutRecordedWorktree = (unit.status === "open" || unit.status === "changes_requested") && recorded === null;
1408
+ const slug = String(unit.title).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
1409
+ const watcherBranchBase = `wu/${n}-${slug}-watcher`;
1410
+ let watcherBranch = watcherBranchBase;
1411
+ for (let suffix = 2; worktreeForBranch(watcherBranch) && !samePath(worktreeForBranch(watcherBranch), resolve(repoParent() ?? "", `${repoName()}-wu${n}`)); suffix++)
1412
+ watcherBranch = `${watcherBranchBase}-${suffix}`;
1413
+ const expectedPath = resolve(repoParent() ?? "", `${repoName()}-wu${n}`);
1414
+ const expectedBranches = new Set([watcherBranch, `wu/${n}-${slug}`, unit.branch].filter((value) => typeof value === "string" && !!value && !isShaBranchName(value)));
1415
+ const expectedState = worktreeState(expectedPath);
1416
+ let prepared;
1417
+ let homeCommits = [];
1418
+ const adoptedExistingWorktree = expectedState.state === "ready" && expectedBranches.has(expectedState.branch ?? "");
1419
+ const recoveryRequired = homeCheckoutRecorded || recordedWorktreeMissing || startedUnitWithoutRecordedWorktree || adoptedExistingWorktree;
1420
+ const recordedHead = recoveryRequired && typeof unit.head === "string" ? fullSha(unit.head) : null;
1421
+ const recordedBranchTip = recoveryRequired && typeof unit.branch === "string" && !isShaBranchName(unit.branch) ? fullSha(`refs/heads/${unit.branch}`) : null;
1422
+ let recoveryBase = recordedHead ?? recordedBranchTip;
1423
+ if (recordedHead && recordedBranchTip) {
1424
+ const headIsOnBranch = isAncestor(recordedHead, recordedBranchTip, home);
1425
+ const branchIsOnHead = isAncestor(recordedBranchTip, recordedHead, home);
1426
+ if (headIsOnBranch === true)
1427
+ recoveryBase = recordedBranchTip;
1428
+ else if (branchIsOnHead !== true) {
1429
+ throw new CliError("unit_worktree_prepare_failed", `recorded head ${recordedHead} and local branch ${unit.branch} diverge; refusing to guess which committed work belongs to WU #${n}`);
1430
+ }
1431
+ }
1432
+ if (adoptedExistingWorktree) {
1433
+ // A trusted preparer may have created this exact unit checkout before the watcher turn.
1434
+ // Adopt only the expected sibling path on a known unit branch; never mutate the home checkout.
1435
+ const adoptedBranch = expectedState.branch;
1436
+ if (!adoptedBranch)
1437
+ throw new CliError("unit_worktree_prepare_failed", `prepared path ${expectedPath} is detached; cannot adopt it for WU #${n}`);
1438
+ prepared = { path: expectedPath, branch: adoptedBranch, mode: "branch", created: false, branchCreated: false };
1439
+ }
1440
+ else if (homeCheckoutRecorded || missingWithoutSafeLinkedBranch || startedUnitWithoutRecordedWorktree) {
1441
+ // A branch checked out in the home checkout cannot also be attached to a linked worktree.
1442
+ if (!recoveryBase)
1443
+ throw new CliError("unit_worktree_prepare_failed", `cannot identify the committed work on WU #${n}'s home checkout; refusing to fork from the integration target`);
1444
+ prepared = prepareWorktree(n, { ...unit, branch: null, worktree: null }, def, { positionals: [], flags: { branch: watcherBranch } }, exclude, recoveryBase);
1445
+ }
1446
+ else {
1447
+ prepared = prepareWorktree(n, unit, def, { positionals: [], flags: {} }, exclude);
1448
+ }
1394
1449
  if (prepared.mode === "here")
1395
1450
  throw new CliError("unit_worktree_prepare_failed", "watchers must prepare a linked unit worktree; --here is not available in watcher preparation");
1396
- return { path: prepared.path, branch: prepared.branch, mode: prepared.mode, created: prepared.created, branchCreated: prepared.branchCreated };
1451
+ const dirty = spawnSync("git", ["status", "--short", "--untracked-files=all"], { cwd: home, encoding: "utf8" });
1452
+ const homeChanges = dirty.status === 0 ? dirty.stdout.split(/\r?\n/).filter(Boolean).map((line) => line.slice(3).trim()).filter(Boolean) : [];
1453
+ let preparedHead = branchAndHead(prepared.path).head;
1454
+ if (recoveryRequired && recoveryBase && preparedHead && isAncestor(recoveryBase, preparedHead, prepared.path) !== true) {
1455
+ if (isAncestor(preparedHead, recoveryBase, prepared.path) !== true) {
1456
+ throw new CliError("unit_worktree_prepare_failed", `prepared branch ${prepared.branch} and verified home tip ${recoveryBase} diverge; refusing to guess committed work for WU #${n}`);
1457
+ }
1458
+ const status = spawnSync("git", ["status", "--porcelain", "--untracked-files=all"], { cwd: prepared.path, encoding: "utf8" });
1459
+ if (status.status !== 0)
1460
+ throw new CliError("unit_worktree_prepare_failed", `cannot verify prepared worktree ${prepared.path} before fast-forwarding WU #${n}: ${(status.stderr || status.stdout).trim()}`);
1461
+ if (status.stdout.trim())
1462
+ throw new CliError("unit_worktree_prepare_failed", `prepared worktree ${prepared.path} has uncommitted changes; refusing to fast-forward it to verified home tip ${recoveryBase}`);
1463
+ const fastForward = spawnSync("git", ["merge", "--ff-only", recoveryBase], { cwd: prepared.path, encoding: "utf8" });
1464
+ if (fastForward.status !== 0)
1465
+ throw new CliError("unit_worktree_prepare_failed", `cannot fast-forward prepared WU #${n} worktree to verified home tip ${recoveryBase}: ${(fastForward.stderr || fastForward.stdout).trim()}`);
1466
+ preparedHead = branchAndHead(prepared.path).head;
1467
+ }
1468
+ if (recoveryRequired && recordedHead && preparedHead) {
1469
+ if (isAncestor(recordedHead, preparedHead, prepared.path) !== true) {
1470
+ throw new CliError("unit_worktree_prepare_failed", `prepared branch ${prepared.branch} does not contain recorded head ${recordedHead}; refusing to omit or guess committed unit work for WU #${n}`);
1471
+ }
1472
+ if (recordedHead !== preparedHead) {
1473
+ const commits = spawnSync("git", ["log", "--reverse", "--format=%h %s", `${recordedHead}..${preparedHead}`], { cwd: prepared.path, encoding: "utf8" });
1474
+ if (commits.status !== 0)
1475
+ throw new CliError("unit_worktree_prepare_failed", `cannot list committed home work for WU #${n}: ${(commits.stderr || commits.stdout).trim()}`);
1476
+ homeCommits = commits.stdout.split(/\r?\n/).filter(Boolean);
1477
+ }
1478
+ }
1479
+ return { path: prepared.path, branch: prepared.branch, mode: prepared.mode, created: prepared.created, branchCreated: prepared.branchCreated, homeChanges, homeCommits,
1480
+ needsRecord: !recorded || !existsSync(recorded) || !samePath(recorded, prepared.path) || unit.branch !== prepared.branch || (preparedHead !== null && unit.head !== preparedHead),
1481
+ recoveryRequired };
1397
1482
  }
1398
- function prepareWorktree(n, unit, def, p, exclude = []) {
1483
+ function prepareWorktree(n, unit, def, p, exclude = [], baseRefOverride) {
1399
1484
  // The unit's own target when it has one: a lane or release branch the work lands in.
1400
1485
  const target = unit.target ?? def.merge.target_branch;
1401
1486
  const log = (line) => process.stderr.write(`b9s: ${line}\n`);
1402
1487
  const explicitBranch = str(p.flags, "branch") ?? null;
1403
1488
  assertNotShaBranch(explicitBranch);
1489
+ if (p.flags.here && shouldInheritAntigravitySandboxUrlRewrites()) {
1490
+ throw new CliError("unit_worktree_required", "wu start --here is unavailable in Antigravity workspace-write: the shared Git directory is read-only; start from a prepared linked unit worktree");
1491
+ }
1404
1492
  if (p.flags.here)
1405
1493
  return { mode: "here", path: process.cwd(), branch: symbolicBranch(), created: false, branchCreated: false };
1406
1494
  const name = repoName();
@@ -1412,7 +1500,7 @@ function prepareWorktree(n, unit, def, p, exclude = []) {
1412
1500
  if (!fetchedTarget.ok) {
1413
1501
  throw new CliError("no_remote", `cannot fetch ${target} from origin: ${fetchedTarget.reason}`, `Check that origin is configured and reachable with branch ${target}, then try again.`);
1414
1502
  }
1415
- let baseRef = fetchedTarget.ref;
1503
+ let baseRef = baseRefOverride ?? fetchedTarget.ref;
1416
1504
  log(`starting from ${baseRef} (${fullSha(baseRef)?.slice(0, 9)})`);
1417
1505
  const recordedBranch = unit.branch && !isShaBranchName(unit.branch) ? unit.branch : null;
1418
1506
  if (unit.branch && !recordedBranch)
package/dist/git.js CHANGED
@@ -575,24 +575,40 @@ export function remoteHead(branch, remote = "origin", cwd = process.cwd()) {
575
575
  const line = r.stdout.split("\n").find((l) => l.trim().endsWith(`refs/heads/${branch}`));
576
576
  return line ? line.split(/\s+/)[0] : null;
577
577
  }
578
+ /** Verify ancestry against the immutable advertised tip, after proving its object is fetched. */
579
+ export function remoteTrackingRefContainsCommit(branch, advertisedTip, sha, cwd = process.cwd()) {
580
+ if (fullSha(`refs/remotes/${branch}`, cwd) !== advertisedTip)
581
+ return false;
582
+ return isAncestor(sha, advertisedTip, cwd) === true;
583
+ }
578
584
  /** Fetch origin, then report a remote branch containing the submitted commit. */
579
585
  export function findRemoteCommitBranch(sha, localBranch, cwd = process.cwd(), remote = "origin") {
580
586
  const checkedRef = `${remote}/${localBranch}`;
581
- const fetched = spawnSync("git", ["fetch", "--prune", remote], { cwd, encoding: "utf8", timeout: 120_000 });
587
+ // Submission only needs current remote-tracking refs. Force pruning off even when user/repo
588
+ // config enables it: pruning stale refs takes .git/packed-refs.lock in the shared Git dir.
589
+ const fetched = spawnSync("git", ["-c", "fetch.prune=false", "-c", `remote.${remote}.prune=false`, "fetch", remote], { cwd, encoding: "utf8", timeout: 120_000 });
582
590
  if (fetched.status !== 0) {
583
591
  const detail = (fetched.stderr || fetched.stdout || `git fetch ${remote} exited with status ${fetched.status ?? "unknown"}`).trim();
584
592
  return { remoteBranch: null, checkedRef, checked: false, reason: `git fetch ${remote} failed: ${detail}` };
585
593
  }
586
- const listed = spawnSync("git", ["branch", "-r", "--contains", sha, "--format=%(refname:short)"], { cwd, encoding: "utf8" });
587
- if (listed.status !== 0) {
588
- const detail = (listed.stderr || listed.stdout || `git branch -r --contains ${sha} exited with status ${listed.status ?? "unknown"}`).trim();
589
- return { remoteBranch: null, checkedRef, checked: true, reason: `git branch -r --contains ${sha} failed: ${detail}` };
594
+ const advertised = spawnSync("git", ["ls-remote", "--heads", remote], { cwd, encoding: "utf8", timeout: 30_000 });
595
+ if (advertised.status !== 0) {
596
+ const detail = (advertised.stderr || advertised.stdout || `git ls-remote ${remote} exited with status ${advertised.status ?? "unknown"}`).trim();
597
+ return { remoteBranch: null, checkedRef, checked: false, reason: `git ls-remote ${remote} failed: ${detail}` };
598
+ }
599
+ const advertisedTips = new Map();
600
+ for (const line of advertised.stdout.split("\n")) {
601
+ const [tip, ref] = line.trim().split(/\s+/);
602
+ if (ref?.startsWith("refs/heads/") && tip)
603
+ advertisedTips.set(`${remote}/${ref.slice("refs/heads/".length)}`, tip);
590
604
  }
591
- const branches = listed.stdout.split("\n").map((line) => line.trim()).filter((line) => line.startsWith(`${remote}/`) && line !== `${remote}/HEAD`).sort();
605
+ // Check ancestry against the advertised object ID, not a mutable tracking ref. A concurrent
606
+ // fetch can move that ref between checking its tip and asking Git about containment.
607
+ const branches = [...advertisedTips].filter(([branch, tip]) => branch !== `${remote}/HEAD` && remoteTrackingRefContainsCommit(branch, tip, sha, cwd)).map(([branch]) => branch).sort();
592
608
  const remoteBranch = branches.includes(checkedRef) ? checkedRef : branches[0] ?? null;
593
609
  return remoteBranch
594
610
  ? { remoteBranch, checkedRef, checked: true, reason: null }
595
- : { remoteBranch: null, checkedRef, checked: true, reason: `git branch -r --contains ${sha} found no ${remote} branch containing the submitted commit` };
611
+ : { remoteBranch: null, checkedRef, checked: true, reason: `no advertised ${remote} branch contains the submitted commit ${sha}` };
596
612
  }
597
613
  export function formatRemoteCommitFailure(localBranch, checkedRef, reason) {
598
614
  return `Could not verify the submitted commit for local branch ${localBranch}: checked ${checkedRef} and other origin branches; ${reason}`;
package/dist/harness.js CHANGED
@@ -225,8 +225,11 @@ export function refreshInstalledHooks(root, bin, requirementsPath = CODEX_REQUIR
225
225
  if (!settings)
226
226
  return undefined;
227
227
  if (!managed) {
228
+ const next = withCodexHooks(settings, bin);
229
+ if (JSON.stringify(next) === JSON.stringify(settings))
230
+ return undefined;
228
231
  changed = true;
229
- return withCodexHooks(settings, bin);
232
+ return next;
230
233
  }
231
234
  const cleaned = removeCodexHooks(settings);
232
235
  if (JSON.stringify(cleaned) === JSON.stringify(settings))
package/dist/help.js CHANGED
@@ -99,7 +99,7 @@ Agent commands
99
99
  b9s wu start <n> [--branch b | --here] [--context-action keep|compact|clear] [--context-confirmed] [--context-checkpoint-ref <id> --context-old-thread <id> --context-new-thread <id>] take it up: makes ../<repo>-wu<n> on branch wu/<n>-<slug> (replays: from the
100
100
  target as of the original); a worktree left half-written by an interrupted
101
101
  checkout is removed and made again; wu open does the same for your own units;
102
- --branch continues existing work (never a SHA); always fetches and branches from origin/<target>; --here uses this checkout
102
+ --branch continues existing work (never a SHA); always fetches and branches from origin/<target>; --here uses this checkout except Antigravity workspace-write, which requires a linked unit worktree
103
103
  context policy is resolved before worktree creation: keep is recorded automatically;
104
104
  compact requires a completed interactive /compact confirmation; Codex turn-mode clear saves a resume checkpoint
105
105
  automatically (or accepts --context-checkpoint-ref), then the watcher starts a fresh thread with the note and unit scope;
@@ -229,7 +229,7 @@ Machine placement enforces configured session slots and reports machine pressure
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
231
  restart the machine daemon first, then watchers in batches of 5 with 5 s between batches
232
- b9s install [<version> | --latest] [--no-restart] make or upgrade this machine's one b9s (join does it once), repair PATH aliases,
232
+ b9s install [<version> | --latest] [--no-restart] [--provisioned] [--move-provisioned --reason <why>] make or upgrade this machine's one b9s (join does it once), repair PATH aliases,
233
233
  restart the machine daemon first, then watchers in batches of 5 with 5 s between batches
234
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
@@ -539,7 +539,7 @@ Project devcontainer images & immutable registry builds (console controls in WU
539
539
  Pools (fixed or adaptive; the server names the agents and places them on machines)
540
540
  b9s-admin project repo <project> <git url | none> what machines clone for the project's pool sessions
541
541
  b9s-admin project checkout <project> --exclude <path,path | none> paths new worktrees leave out (sparse checkout), e.g. logs/
542
- b9s-admin pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight][@anthropic|deepseek] [--variant ...]
542
+ b9s-admin pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight][@anthropic|deepseek] [--variant ...] [--preview | --impact-revision <revision>]
543
543
  --count <n> | --min <n> --max <n> [--count <target>] --sandbox <mode> [--needs label,label] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60]
544
544
  fixed pools retain count; adaptive pools are opt-in, with target bounded by min/max and account/machine capacity
545
545
  slots are agents named <name>-<tag>-<n>; fewer retires the extra ones
@@ -550,11 +550,11 @@ Pools (fixed or adaptive; the server names the agents and places them on machine
550
550
  b9s-admin pool events <project>/<name> [--limit 1..100]
551
551
  Console: Pools → pool details → Adaptive history and overrides.
552
552
  Console → Pools shows seat/agent counts, placement, slot work/session state, machine headroom, and previewed slot suspend/restore (with /account recovery on 402 plan_limit)
553
- b9s-admin pool pause|resume <project>/<name> [--reason <text>] pause only automatic scaling; sessions keep running
554
- b9s-admin pool pin <project>/<name> <slot> --machine <name> [--until <ISO>] [--reason <text>]
555
- b9s-admin pool unpin <project>/<name> <slot>
556
- b9s-admin pool suspend|restore <project>/<name> <slot> [--reason <text>] [--note <text>] suspended agents stay benched until restored; no replacement is created
557
- b9s-admin pool remove <project>/<name> retires its agents; their units go back to the queue
553
+ b9s-admin pool pause|resume <project>/<name> [--reason <text>] [--preview | --impact-revision <revision>] pause only automatic scaling; sessions keep running
554
+ b9s-admin pool pin <project>/<name> <slot> --machine <name> [--until <ISO>] [--reason <text>] [--preview | --impact-revision <revision>]
555
+ b9s-admin pool unpin <project>/<name> <slot> [--preview | --impact-revision <revision>]
556
+ b9s-admin pool suspend|restore <project>/<name> <slot> [--reason <text>] [--note <text>] [--preview | --impact-revision <revision>] suspended agents stay benched until restored; no replacement is created
557
+ b9s-admin pool remove <project>/<name> [--preview | --impact-revision <revision>] retires its agents; their units go back to the queue
558
558
  Console → Pools (WU #185) creates, edits, and retires pools with server impact previews and revision confirmation; repository and checkout defaults save separately and immediately.
559
559
  b9s-admin pool slot stop <project>/<pool>/<slot> [--reason text] request session stop; the agent stays benched until restored
560
560
  b9s-admin pool move <project>/<name> --from <source-machine> --to <destination-machine> [--carry note|thread] [--ssh-from local|<host>] [--to-ssh <host>]
package/dist/install.js CHANGED
@@ -100,9 +100,10 @@ export function composeMachinePath(options) {
100
100
  return false;
101
101
  }
102
102
  });
103
+ const localBin = join(options.home, ".local", "bin");
104
+ const installBinDir = dirname(options.installBin);
103
105
  const preferred = [
104
- join(options.home, ".local", "bin"),
105
- dirname(options.installBin),
106
+ ...(options.provisioned ? [installBinDir, localBin] : [localBin, installBinDir]),
106
107
  dirname(options.npmBin),
107
108
  ...(options.platform === "darwin" ? ["/opt/homebrew/bin", "/usr/local/bin"] : []),
108
109
  ];
@@ -128,6 +129,7 @@ export function machineDaemonPath(currentPath = process.env.PATH ?? "", platform
128
129
  installBin: install.bin,
129
130
  npmBin: install.npm,
130
131
  currentPath,
132
+ provisioned: install.provisioned,
131
133
  });
132
134
  const prefix = spawnSync(install.npm, ["prefix", "-g"], {
133
135
  encoding: "utf8",
@@ -139,7 +141,11 @@ export function machineDaemonPath(currentPath = process.env.PATH ?? "", platform
139
141
  const globalPrefix = (prefix.stdout ?? "").trim();
140
142
  if (!globalPrefix || !globalPrefix.startsWith("/"))
141
143
  throw new CliError("npm_prefix_invalid", `${install.npm} prefix -g did not return an absolute path`, (prefix.stdout ?? "").trim().slice(0, 300));
142
- return composeMachinePath({ platform: platformName, home, installBin: install.bin, npmBin: join(globalPrefix, "bin", "npm"), currentPath });
144
+ const expectedPrefix = install.provisioned ? dirname(dirname(install.bin)) : globalPrefix;
145
+ if (install.provisioned && resolve(globalPrefix) !== resolve(expectedPrefix)) {
146
+ throw new CliError("recorded_install_prefix_mismatch", `${install.npm} resolves to ${globalPrefix}, but this machine records ${install.bin}`, `Unset npm_config_prefix and run ${install.bin} install --latest`);
147
+ }
148
+ return composeMachinePath({ platform: platformName, home, installBin: install.bin, npmBin: join(globalPrefix, "bin", "npm"), currentPath, provisioned: install.provisioned });
143
149
  }
144
150
  /** "b9s 0.12.38" -> "0.12.38"; null when the binary cannot run. */
145
151
  export function binVersion(bin) {
@@ -147,6 +153,14 @@ export function binVersion(bin) {
147
153
  const m = r.status === 0 ? /^(?:b9s|bschat)\s*(\d+\.\d+\.\d+)\s*$/.exec((r.stdout ?? "").trim()) : null;
148
154
  return m ? m[1] : null;
149
155
  }
156
+ export function serviceUsesInstall(program, installBin) {
157
+ try {
158
+ return realpathSync(program) === realpathSync(installBin);
159
+ }
160
+ catch {
161
+ return false;
162
+ }
163
+ }
150
164
  /** The npm belonging to the Node running this process: the same runtime installs and runs b9s. */
151
165
  export function ownNpm(execPath = process.execPath) {
152
166
  const npm = join(dirname(execPath), "npm");
@@ -172,13 +186,20 @@ export function latestPublished(npm) {
172
186
  * the running Node when it is missing or older, and records it. Progress goes to stderr so a
173
187
  * JSON caller's stdout stays clean. A failed install throws: nothing is recorded.
174
188
  */
175
- export function ensureInstall(version, log, npmOverride, nodeOverride = process.execPath) {
189
+ export function ensureInstall(version, log, npmOverride, provisioned, allowProvisionedMove = false, nodeOverride = process.execPath) {
176
190
  const npm = npmOverride ?? ownNpm();
191
+ const previous = readInstall();
177
192
  const env = npmEnv(npm);
178
193
  const pre = spawnSync(npm, ["prefix", "-g"], { encoding: "utf8", timeout: 30_000, env });
179
194
  if (pre.status !== 0)
180
195
  throw new CliError("npm_prefix_failed", `${npm} prefix -g failed`, (pre.stderr ?? "").trim().slice(0, 300));
181
- const bin = join(pre.stdout.trim(), "bin", "b9s");
196
+ const prefix = resolve(pre.stdout.trim());
197
+ const pinnedPrefix = previous?.provisioned ? dirname(dirname(previous.bin)) : join(homedir(), ".local", "node");
198
+ const isProvisioned = !!(provisioned ?? previous?.provisioned);
199
+ if (isProvisioned && !allowProvisionedMove && prefix !== resolve(pinnedPrefix)) {
200
+ throw new CliError("provisioned_prefix_mismatch", `npm prefix -g resolved to ${prefix}, but this provisioned machine is pinned to ${pinnedPrefix}`, "Unset npm_config_prefix; to deliberately move this machine, rerun with --move-provisioned --reason '<why>'");
201
+ }
202
+ const bin = join(prefix, "bin", "b9s");
182
203
  const current = existsSync(bin) ? binVersion(bin) : null;
183
204
  if (current && cmp(current, version) >= 0) {
184
205
  log(`b9s ${current} is installed at ${bin}`);
@@ -194,10 +215,11 @@ export function ensureInstall(version, log, npmOverride, nodeOverride = process.
194
215
  }
195
216
  // Record the npm in the global prefix's bin (a stable link, e.g. /opt/homebrew/bin/npm) rather than
196
217
  // the resolved runtime path, which names a versioned folder that a Node upgrade removes.
197
- const stableNpm = join(pre.stdout.trim(), "bin", "npm");
198
- const rec = { bin, node: nodeOverride, npm: existsSync(stableNpm) ? stableNpm : npm, version: binVersion(bin), installed_at: new Date().toISOString() };
199
- // Replaced in one step: every b9s command on the machine reads this record, and an upgrade runs
200
- // this once per agent at the same moment. A reader never sees it half-written.
218
+ const stableNpm = join(prefix, "bin", "npm");
219
+ const node = isProvisioned && previous?.node && !allowProvisionedMove
220
+ ? previous.node
221
+ : (isProvisioned && !allowProvisionedMove ? join(dirname(npm), "node") : nodeOverride);
222
+ const rec = { bin, node, npm: existsSync(stableNpm) ? stableNpm : npm, version: binVersion(bin), installed_at: new Date().toISOString(), ...(isProvisioned ? { provisioned: true } : {}) };
201
223
  writeFileAtomic(installFile(), JSON.stringify(rec, null, 2) + "\n");
202
224
  return rec;
203
225
  }
@@ -209,7 +231,7 @@ export function ensureInstall(version, log, npmOverride, nodeOverride = process.
209
231
  export function ensureMachineInstall(version, log) {
210
232
  const previous = readInstall();
211
233
  if (!previous)
212
- return ensureInstall(version, log, ownNpm(), process.execPath);
234
+ return ensureInstall(version, log, ownNpm(), false, false, process.execPath);
213
235
  if (!previous.npm || !existsSync(previous.npm)) {
214
236
  throw new CliError("recorded_npm_missing", `the recorded install npm ${previous.npm || "(missing)"} is unavailable`, `Run ${previous.bin} install --latest from the Node installation you want this machine to use`);
215
237
  }
@@ -230,9 +252,12 @@ export function ensureMachineInstall(version, log) {
230
252
  // A Node upgrade may remove the versioned runtime path recorded by the prior install. The
231
253
  // currently running CLI is the runtime that can refresh this install; persist its resolved,
232
254
  // live executable rather than carrying the dead path forward.
233
- const recordedNodeIsLive = isLiveExecutable(previous.node);
234
- const node = recordedNodeIsLive ? previous.node : realpathSync(process.execPath);
235
- return ensureInstall(version, log, previous.npm, node);
255
+ const pinnedNode = previous.node ?? join(dirname(previous.npm), "node");
256
+ if (previous.provisioned && !isLiveExecutable(pinnedNode)) {
257
+ throw new CliError("recorded_node_missing", `the provisioned Node ${pinnedNode} is unavailable`, `Restore the pinned Node at ~/.local/node before running ${previous.bin} install`);
258
+ }
259
+ const node = previous.provisioned ? pinnedNode : (isLiveExecutable(previous.node) ? previous.node : realpathSync(process.execPath));
260
+ return ensureInstall(version, log, previous.npm, previous.provisioned, false, node);
236
261
  }
237
262
  /** Creates b9s-named shell links beside aliases of the same recorded install, without replacing another copy. */
238
263
  export function ensureCommandLinks(installBin) {
@@ -399,7 +424,7 @@ export const systemdUserDir = () => join(process.env.XDG_CONFIG_HOME ?? join(hom
399
424
  /** Every watcher service on this machine. */
400
425
  export function watcherServices() {
401
426
  if (process.platform === "darwin")
402
- return watcherPlists().map((w) => ({ kind: "launchd", ...w, args: plistArgs(w.path), cwd: plistWorkingDirectory(w.path) }));
427
+ return watcherPlists().map((w) => ({ kind: "launchd", ...w, args: plistArgs(w.path), pathEnv: plistPath(w.path), cwd: plistWorkingDirectory(w.path) }));
403
428
  const dir = systemdUserDir();
404
429
  if (process.platform !== "linux" || !existsSync(dir))
405
430
  return [];
@@ -408,9 +433,48 @@ export function watcherServices() {
408
433
  .map((f) => {
409
434
  const path = join(dir, f);
410
435
  const text = readFileSync(path, "utf8");
411
- return { kind: "systemd", label: f.slice(0, -".service".length), path, args: unitArgs(text), cwd: unitWorkingDirectory(text) };
436
+ return { kind: "systemd", label: f.slice(0, -".service".length), path, args: unitArgs(text), pathEnv: unitPath(text), cwd: unitWorkingDirectory(text) };
412
437
  });
413
438
  }
439
+ function plistPath(path) {
440
+ const r = spawnSync("plutil", ["-convert", "json", "-o", "-", path], { encoding: "utf8" });
441
+ if (r.status !== 0)
442
+ return null;
443
+ try {
444
+ const env = JSON.parse(r.stdout).EnvironmentVariables;
445
+ return typeof env?.PATH === "string" ? env.PATH : null;
446
+ }
447
+ catch {
448
+ return null;
449
+ }
450
+ }
451
+ export function unitPath(text) {
452
+ const metadata = /^# bschat-env: (.*)$/m.exec(text);
453
+ if (metadata) {
454
+ try {
455
+ const env = JSON.parse(metadata[1]);
456
+ return typeof env.PATH === "string" ? env.PATH : null;
457
+ }
458
+ catch {
459
+ return null;
460
+ }
461
+ }
462
+ const line = /^Environment="?PATH=([^"\n]*)"?$/m.exec(text);
463
+ return line?.[1]?.replace(/\\([\\"$])/g, "$1") ?? null;
464
+ }
465
+ export function serviceUsesNode(servicePath, installBin) {
466
+ if (!servicePath)
467
+ return false;
468
+ const selected = findExecutableOnPath("node", servicePath);
469
+ if (!selected)
470
+ return false;
471
+ try {
472
+ return realpathSync(selected) === realpathSync(join(dirname(installBin), "node"));
473
+ }
474
+ catch {
475
+ return false;
476
+ }
477
+ }
414
478
  function plistWorkingDirectory(path) {
415
479
  const r = spawnSync("plutil", ["-convert", "json", "-o", "-", path], { encoding: "utf8" });
416
480
  if (r.status !== 0)
@@ -480,6 +544,7 @@ export function rewriteServiceInstall(s, installBin) {
480
544
  if (programReal !== installReal)
481
545
  throw new CliError("service_install_mismatch", `${s.label} resolves to ${programReal}, not ${installReal}`);
482
546
  const nextArgs = [installBin, ...args.slice(1)];
547
+ const pinnedPath = readInstall()?.provisioned ? machineDaemonPath(s.pathEnv ?? process.env.PATH ?? "") : null;
483
548
  if (s.kind === "systemd") {
484
549
  const original = readFileSync(s.path, "utf8");
485
550
  if (!/^# bschat-args: .*$/m.test(original) || !/^ExecStart=.*$/m.test(original)) {
@@ -488,6 +553,25 @@ export function rewriteServiceInstall(s, installBin) {
488
553
  let updated = original
489
554
  .replace(/^# bschat-args: .*$/m, `# bschat-args: ${JSON.stringify(nextArgs)}`)
490
555
  .replace(/^ExecStart=.*$/m, `ExecStart=${nextArgs.map(systemdQuote).join(" ")}`);
556
+ if (pinnedPath) {
557
+ const envMatch = /^# bschat-env: (.*)$/m.exec(updated);
558
+ let env = {};
559
+ if (envMatch) {
560
+ try {
561
+ env = JSON.parse(envMatch[1]);
562
+ }
563
+ catch {
564
+ throw new CliError("service_unreadable", `${s.label} has invalid service environment metadata`);
565
+ }
566
+ }
567
+ env.PATH = pinnedPath;
568
+ const metadata = `# bschat-env: ${JSON.stringify(env)}`;
569
+ updated = envMatch ? updated.replace(/^# bschat-env: .*$/m, metadata) : updated.replace(/^(# bschat-args: .*\n)/m, `$1${metadata}\n`);
570
+ const pathLine = /^Environment=(?:"PATH=.*"|PATH=.*)$/m;
571
+ updated = pathLine.test(updated)
572
+ ? updated.replace(pathLine, `Environment=${systemdQuote(`PATH=${pinnedPath}`)}`)
573
+ : updated.replace(/^(WorkingDirectory=.*)$/m, `$1\nEnvironment=${systemdQuote(`PATH=${pinnedPath}`)}`);
574
+ }
491
575
  if (s.label.startsWith(WATCH_LABEL_PREFIX)) {
492
576
  const limits = watcherMemoryLimits(totalmem());
493
577
  if (!limits)
@@ -513,6 +597,11 @@ export function rewriteServiceInstall(s, installBin) {
513
597
  }
514
598
  const original = readFileSync(s.path, "utf8");
515
599
  plist.ProgramArguments = nextArgs;
600
+ if (pinnedPath) {
601
+ const environment = plist.EnvironmentVariables && typeof plist.EnvironmentVariables === "object" ? plist.EnvironmentVariables : {};
602
+ environment.PATH = pinnedPath;
603
+ plist.EnvironmentVariables = environment;
604
+ }
516
605
  const write = spawnSync("plutil", ["-convert", "xml1", "-o", s.path, "-"], { input: JSON.stringify(plist), encoding: "utf8" });
517
606
  if (write.status !== 0)
518
607
  throw new CliError("service_rewrite_failed", `could not rewrite ${s.path}`, (write.stderr ?? "").trim());
@@ -596,6 +685,7 @@ export function systemdUnit(label, args, cwd, env, logDir, slug = label.slice(WA
596
685
  return [
597
686
  `# Written by b9s; re-run its b9s watch ... --service (or b9s codex start) to change it.`,
598
687
  `# bschat-args: ${JSON.stringify(args)}`,
688
+ `# bschat-env: ${JSON.stringify(env)}`,
599
689
  `[Unit]`,
600
690
  `Description=b9s ${label === MACHINE_LABEL ? "machine daemon" : `watcher for ${slug}`}`,
601
691
  `After=network-online.target`,
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.139";
1
+ export const CLI_VERSION = "0.12.141";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.139",
3
+ "version": "0.12.141",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {