benignswarm 0.12.138 → 0.12.140

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.
@@ -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/container.js CHANGED
@@ -975,12 +975,13 @@ export function agentContainerRunArgs(opts) {
975
975
  const hostCache = assertSafeMountPath(join(opts.cacheRootDir, cacheName), "cache", boundaryOpts);
976
976
  args.push("-v", `${hostCache}:/caches/${cacheName}:rw`);
977
977
  }
978
+ const secretEnvKeys = new Set(opts.secretEnvKeys ?? []);
978
979
  for (const [k, v] of Object.entries(opts.extraEnv ?? {})) {
979
980
  if (/^(AWS_|B9S_MACHINE|BSCHAT_MACHINE)/i.test(k))
980
981
  continue;
981
982
  if (SECRET_KEY_RE.test(k) && v.includes("machine.json"))
982
983
  continue;
983
- args.push("-e", `${k}=${v}`);
984
+ args.push("-e", secretEnvKeys.has(k) ? k : `${k}=${v}`);
984
985
  }
985
986
  args.push(opts.imageDigest, ...opts.command);
986
987
  return args;
@@ -989,7 +990,7 @@ export function agentContainerRunArgs(opts) {
989
990
  * Constructs a secret-free host subprocess environment for disposable image builds and
990
991
  * container-runtime client invocations, stripping AWS, harness, GitHub, and machine credentials.
991
992
  */
992
- export function isolatedSubprocessEnv(baseEnv = process.env, extraEnv = {}) {
993
+ export function isolatedSubprocessEnv(baseEnv = process.env, extraEnv = {}, passSecretKeys = []) {
993
994
  const out = {};
994
995
  const allowKeys = ["PATH", "LANG", "LC_ALL", "TERM", "TMPDIR", "XDG_RUNTIME_DIR", "CONTAINER_HOST", "DOCKER_HOST"];
995
996
  for (const key of allowKeys) {
@@ -998,7 +999,7 @@ export function isolatedSubprocessEnv(baseEnv = process.env, extraEnv = {}) {
998
999
  out[key] = v;
999
1000
  }
1000
1001
  for (const [k, v] of Object.entries(extraEnv)) {
1001
- if (!SECRET_KEY_RE.test(k))
1002
+ if (!SECRET_KEY_RE.test(k) || passSecretKeys.includes(k))
1002
1003
  out[k] = v;
1003
1004
  }
1004
1005
  return out;
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,11 +229,13 @@ 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
236
236
  are there, what git can do, which hosts answer, what is writable; facts only.
237
+ Prints to stdout by default; --out must name a writable file, such as one inside
238
+ the checkout.
237
239
  The harness/mode pair is needed for watcher cleanup on Antigravity workspace-write
238
240
  b9s sandbox check <file> --harness <h> --sandbox <mode>
239
241
  compare a probe result with what is expected of that harness; exits 1 on a difference
@@ -352,13 +354,15 @@ Use --admin <nickname> to select one of this machine's saved operator identities
352
354
  enable only after exact ruleset verification in console and live bypass-change signal check; controls are also in console WU #196
353
355
  b9s-admin project secrets <project> list
354
356
  b9s-admin project secrets <project> show <name>
357
+ b9s-admin project secrets <project> audit [<name>] [--limit n]
355
358
  b9s-admin project secrets <project> create <name> --purpose <text> --storage-mode hosted|aws_secrets_manager --units 1,2 --tags api --hosts host[,host] [--arn <exact ARN> --version-id <id>]
356
359
  b9s-admin project secrets <project> update <name> [--purpose <text>] [--units 1,2] [--tags api] [--hosts host[,host]]
357
- b9s-admin project secrets <project> rotate <name> --arn <exact ARN> --version-id <id>
360
+ b9s-admin project secrets <project> rotate <name> (--arn <exact ARN> --version-id <id> | --stdin) [--drain]
358
361
  b9s-admin project secrets <project> revoke <name>
359
362
  b9s-admin project secrets <project> delete <name>
360
- b9s-admin project secrets <project> set <name> [--stdin]
361
- purpose is trimmed before send (1–200 characters); values remain unavailable until encrypted storage lands in WU #231; set checks before reading input; console control is WU #230
363
+ b9s-admin project secrets <project> set <name> [--stdin] [--drain]
364
+ --hosts stores declared hostnames only; all current machine adapters refuse secret grants until outer egress enforcement exists
365
+ purpose is trimmed before send (1–200 characters); set/rotate check AWS KMS availability before reading a value; no plaintext fallback; console control is WU #230
362
366
  b9s-admin project environment show <project>
363
367
  b9s-admin project environment setup <project> [--catalog family@version] [--assessment-only] [--context text]
364
368
  b9s-admin project environment set <project> --file declaration.json --source-commit <merged-sha>
@@ -446,6 +450,8 @@ Use --admin <nickname> to select one of this machine's saved operator identities
446
450
  b9s-admin explain <key> ask the agent to explain a decision in plain words (the console's Explain)
447
451
  b9s-admin notifier [--agent name|none] [--email yes|no] [--repeat m] [--flow-summary yes|no] [--flow-min-age m] [--flow-min-impact n] how you are reached away from the console, and the last report
448
452
  b9s-admin account [--summary-minutes m] plan, usage and the account summary period
453
+ b9s-admin account secrets-kms status | enable --region <aws-region> [--kms-key <arn-or-id>]
454
+ dedicated per-account KMS key; foreign, shared, or untagged keys are refused
449
455
  assistant stays opt-in: PATCH /account {"assistant_enabled":true|false}; GET /account/usage shows used, allowance, uncertain calls and reset date
450
456
  b9s-admin account-stores migrations show|run [--json] inspect or resume the per-account SQLite schema migration runner (platform admin only)
451
457
  session/admin clients use GET /assistant/conversations/:id/messages for paged history and GET/POST/DELETE /assistant/conversations; POST messages streams data and saves tool notices with assistant messages; old assistant messages have notices_available=false; operator must explicitly apply or discard (see operator skill)
@@ -533,7 +539,7 @@ Project devcontainer images & immutable registry builds (console controls in WU
533
539
  Pools (fixed or adaptive; the server names the agents and places them on machines)
534
540
  b9s-admin project repo <project> <git url | none> what machines clone for the project's pool sessions
535
541
  b9s-admin project checkout <project> --exclude <path,path | none> paths new worktrees leave out (sparse checkout), e.g. logs/
536
- 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>]
537
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]
538
544
  fixed pools retain count; adaptive pools are opt-in, with target bounded by min/max and account/machine capacity
539
545
  slots are agents named <name>-<tag>-<n>; fewer retires the extra ones
@@ -544,11 +550,11 @@ Pools (fixed or adaptive; the server names the agents and places them on machine
544
550
  b9s-admin pool events <project>/<name> [--limit 1..100]
545
551
  Console: Pools → pool details → Adaptive history and overrides.
546
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)
547
- b9s-admin pool pause|resume <project>/<name> [--reason <text>] pause only automatic scaling; sessions keep running
548
- b9s-admin pool pin <project>/<name> <slot> --machine <name> [--until <ISO>] [--reason <text>]
549
- b9s-admin pool unpin <project>/<name> <slot>
550
- b9s-admin pool suspend|restore <project>/<name> <slot> [--reason <text>] [--note <text>] suspended agents stay benched until restored; no replacement is created
551
- 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
552
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.
553
559
  b9s-admin pool slot stop <project>/<pool>/<slot> [--reason text] request session stop; the agent stays benched until restored
554
560
  b9s-admin pool move <project>/<name> --from <source-machine> --to <destination-machine> [--carry note|thread] [--ssh-from local|<host>] [--to-ssh <host>]