benignswarm 0.12.161 → 0.12.162

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.
File without changes
@@ -6,7 +6,7 @@ import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from "no
6
6
  import { configRoot } from "./config.js";
7
7
  import { repoDirectory } from "./directories.js";
8
8
  import { CliError } from "./errors.js";
9
- import { gitSandboxDeniedPaths, gitSandboxWritablePaths, sandboxProbeWorktreeAdminPath } from "./git-sandbox-paths.js";
9
+ import { gitSandboxDeniedPaths, gitSandboxReadablePaths, gitSandboxWritablePaths, sandboxProbeWorktreeAdminPath } from "./git-sandbox-paths.js";
10
10
  export const ANTIGRAVITY_SETTINGS_PLACEHOLDER = "__B9S_ANTIGRAVITY_TURN_SETTINGS__";
11
11
  export function isAntigravityWorkspaceWrite(env = process.env) {
12
12
  return env.BSCHAT_HARNESS === "antigravity" && env.BSCHAT_ANTIGRAVITY_SANDBOX === "workspace-write";
@@ -88,6 +88,7 @@ export function antigravitySettings(sandbox, cwd, b9sHome, apiHost, extraWritabl
88
88
  }
89
89
  const additionalCheckouts = unitWorktree ? [{ label: `WU #${unitWorktree.number} worktree`, path: unitWorktree.path }] : [];
90
90
  const gitPaths = gitSandboxWritablePaths(absoluteCwd, additionalCheckouts);
91
+ const gitReadPaths = gitSandboxReadablePaths(absoluteCwd, additionalCheckouts);
91
92
  const exactGitFiles = new Set(["packed-refs", "packed-refs.lock", "FETCH_HEAD", "FETCH_HEAD.lock", "HEAD", "HEAD.lock", "index", "index.lock", "COMMIT_EDITMSG"]);
92
93
  const commonGitFiles = gitPaths.filter((path) => exactGitFiles.has(basename(path)) && (!existsSync(path) || !statSync(path).isDirectory()));
93
94
  const gitDirectories = gitPaths.filter((path) => !commonGitFiles.includes(path));
@@ -98,6 +99,10 @@ export function antigravitySettings(sandbox, cwd, b9sHome, apiHost, extraWritabl
98
99
  ...configured.map((dir) => `write_file(${dir})`),
99
100
  ...gitDirectories.map((dir) => `write_file(${dir})`),
100
101
  ...commonGitFiles.map((path) => `write_file(${path})`),
102
+ // Linked worktrees store their repository config, refs and objects in the common directory.
103
+ // Read-only access is needed for origin resolution and object lookup; write access remains
104
+ // limited to the existing Git stores above, with config/hooks/sibling entries denied below.
105
+ ...gitReadPaths.map((path) => `read_file(${path})`),
101
106
  // Git reads the registry to inspect linked worktrees. The watcher creates the unit entry
102
107
  // before a turn and gitSandboxWritablePaths grants that exact entry; the agent must not add
103
108
  // arbitrary worktree entries because recursive registry access would expose siblings.
@@ -823,7 +823,10 @@ export function assertAntigravitySelfCheck(output) {
823
823
  throw new CliError("sandbox_self_check_failed", `Antigravity sandbox could not run b9s me${checks.b9s_me?.status === undefined ? "" : ` (exit ${checks.b9s_me.status})`}: ${checks.b9s_me?.output ?? "no output"}; watcher was not enabled`);
824
824
  }
825
825
  if (checks.git_ls_remote_origin?.status !== 0) {
826
- throw new CliError("sandbox_self_check_failed", `Antigravity sandbox git ls-remote origin failed${checks.git_ls_remote_origin?.status === undefined ? "" : ` (exit ${checks.git_ls_remote_origin.status})`}: ${checks.git_ls_remote_origin?.output ?? "no output"}; watcher was not enabled`);
826
+ const access = checks.git_metadata_access?.output?.trim();
827
+ const unreadable = access?.split(/\r?\n/).filter((line) => /^UNREADABLE\s/.test(line)).join("; ");
828
+ const metadata = unreadable || access || "Git metadata path diagnostic was not returned; check the active worktree Git directory and common Git directory (config, objects, refs)";
829
+ throw new CliError("sandbox_self_check_failed", `Antigravity sandbox git ls-remote origin failed${checks.git_ls_remote_origin?.status === undefined ? "" : ` (exit ${checks.git_ls_remote_origin.status})`}: ${checks.git_ls_remote_origin?.output ?? "no output"}; Git metadata access: ${metadata}; watcher was not enabled`);
827
830
  }
828
831
  }
829
832
  /** Run the two connectivity checks through the real model tools inside the per-turn sandbox. */
@@ -833,11 +836,12 @@ export async function runAntigravitySandboxSelfCheck(ref, bin, settings, cwd, se
833
836
  throw new CliError("turn_mode_fault", refusalReason(diagnostic));
834
837
  }
835
838
  const prompt = [
836
- "BenignSwarm sandbox startup check. Use your terminal tool to execute these two commands separately, exactly as written:",
839
+ "BenignSwarm sandbox startup check. Use your terminal tool to execute these three commands separately, exactly as written:",
837
840
  "1. b9s me",
838
841
  "2. git ls-remote origin",
842
+ '3. Run this exact diagnostic in the same terminal: common="$(git rev-parse --path-format=absolute --git-common-dir 2>&1)"; worktree="$(git rev-parse --path-format=absolute --absolute-git-dir 2>&1)"; for path in "$worktree" "$common" "$common/config" "$common/objects" "$common/refs"; do if test -r "$path" && { test ! -d "$path" || test -x "$path"; }; then printf "READABLE %s\\n" "$path"; else printf "UNREADABLE %s\\n" "$path"; fi; done',
839
843
  "Capture each real exit code and complete stdout/stderr. Do not infer or invent results.",
840
- 'Return only one JSON object with this shape: {"b9s_me":{"status":0,"output":"..."},"git_ls_remote_origin":{"status":0,"output":"..."}}.',
844
+ 'Return only one JSON object with this shape: {"b9s_me":{"status":0,"output":"..."},"git_ls_remote_origin":{"status":0,"output":"..."},"git_metadata_access":{"status":0,"output":"READABLE or UNREADABLE path per line"}}.',
841
845
  ].join("\n");
842
846
  let started;
843
847
  try {
@@ -175,9 +175,9 @@ export async function doctor(_p, out) {
175
175
  const rec = readInstall();
176
176
  const recVersion = rec && existsSync(rec.bin) ? binVersion(rec.bin) : null;
177
177
  if (!rec)
178
- checks.push({ ok: false, what: "no recorded install: hooks and watchers have no one b9s to run", fix: "npx -y benignswarm install" });
178
+ checks.push({ ok: false, what: "no recorded install: hooks and watchers have no one b9s to run", fix: `npx -y benignswarm@${CLI_VERSION} install` });
179
179
  else if (!recVersion)
180
- checks.push({ ok: false, what: `recorded install ${rec.bin} does not run`, fix: "npx -y benignswarm install" });
180
+ checks.push({ ok: false, what: `recorded install ${rec.bin} does not run`, fix: `npx -y benignswarm@${CLI_VERSION} install` });
181
181
  else
182
182
  checks.push({ ok: true, what: `recorded install: ${rec.bin} (${recVersion})` });
183
183
  if (rec?.provisioned) {
@@ -206,7 +206,7 @@ export async function doctor(_p, out) {
206
206
  }
207
207
  }
208
208
  if (!onPath.length)
209
- checks.push({ ok: false, what: "no b9s on this shell's PATH", fix: rec ? `add ${join(rec.bin, "..")} to PATH, or call ${rec.bin}` : "npx -y benignswarm install" });
209
+ checks.push({ ok: false, what: "no b9s on this shell's PATH", fix: rec ? `add ${join(rec.bin, "..")} to PATH, or call ${rec.bin}` : `npx -y benignswarm@${CLI_VERSION} install` });
210
210
  onPath.forEach((b, i) => {
211
211
  const isRec = !!rec && realpathSync(rec.bin) === b.real;
212
212
  checks.push({ ok: isRec || i > 0, what: `on PATH${i === 0 ? " (first)" : ""}: ${b.path} (${b.version ?? "does not run"})${isRec ? " = the recorded install" : ""}`, fix: !isRec && i === 0 && rec ? `this shell runs a different b9s than hooks and watchers; put ${join(rec.bin, "..")} first on PATH, or remove this copy${removeCopyCommand(b.real) ? `: ${removeCopyCommand(b.real)}` : ""}` : undefined });
@@ -6,7 +6,7 @@ import { readFileSync } from "node:fs";
6
6
  import { join as pathJoin } from "node:path";
7
7
  import { CliError } from "../errors.js";
8
8
  import { defaultMachine } from "../git.js";
9
- import { ensureMachineInstall } from "../install.js";
9
+ import { assertMachineInstallNotNewer, ensureMachineInstall } from "../install.js";
10
10
  import { claudeCheckoutOwner, claudeCheckoutTaken, reconcileCodexHooks, HARNESSES, findIdentityFile, installForHarness, normalizeVendor, readIdentityFile, writeIdentity } from "../harness.js";
11
11
  import { detectVendor } from "../vendor.js";
12
12
  import { CLI_VERSION } from "../version.js";
@@ -100,8 +100,9 @@ export async function join(p, out, expectedProject) {
100
100
  }
101
101
  if (!noBind)
102
102
  writeIdentityDryRun(root, vendor, name, bool(p.flags, "replace"));
103
- // The machine's one b9s install comes first: if it cannot be made, the token is not spent.
104
- const inst = machineInstall();
103
+ // A newer recorded install must reject this copy before the single-use enrollment token is sent.
104
+ // Otherwise wait to move/install the machine-wide CLI until credentials have been saved.
105
+ assertMachineInstallNotNewer(CLI_VERSION);
105
106
  let res;
106
107
  try {
107
108
  res = await fetch(`${url}/enroll`, { method: "POST", headers: { "content-type": "application/json", "user-agent": cliUserAgent() }, body: JSON.stringify({ token, name, vendor, machine }) });
@@ -118,6 +119,7 @@ export async function join(p, out, expectedProject) {
118
119
  assertEnrolledStartProject(expectedProject, project);
119
120
  const ref = agentRef({ project, agent: name });
120
121
  const path = saveAgent({ url, key: json.key, account: json.project ? json.project.id : "", project, agent: name, vendor, machine });
122
+ const inst = machineInstall();
121
123
  const idPath = noBind ? null : writeIdentity(root, vendor, name, model, bool(p.flags, "replace"), project);
122
124
  let written = [];
123
125
  if (!bool(p.flags, "no-skill") && !noBind) {
@@ -1,4 +1,5 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
+ import { Worker } from "node:worker_threads";
2
3
  import { FileFactsCache, scanLinesBackward, TAIL_CHUNK_BYTES, TAIL_MAX_BYTES } from "../tail-lines.js";
3
4
  import { rotateLogs } from "../log-rotation.js";
4
5
  import { createHash, createHmac, randomBytes } from "node:crypto";
@@ -38,9 +39,7 @@ import { machineResourceTelemetry, measuredWatcherServiceMemoryLimits, parsePage
38
39
  import { macReadiness, macReadinessSteps } from "../macos-readiness.js";
39
40
  import { collectModelChecksQueued, modelCheckRuntimeTuple, probeModelRunAsync } from "../model-checks.js";
40
41
  import { authorizeWorktreeScope, redactProcessCommand, scanWorktreeProcesses } from "../machine-processes.js";
41
- import { collectPruneProtection } from "../prune-protection.js";
42
42
  import { runMachineDaemonLoop } from "../machine-daemon.js";
43
- import { pruneProjectWorktrees } from "./worktrees.js";
44
43
  import { boundMachineReport } from "../machine-report.js";
45
44
  import { ECRClient } from "@aws-sdk/client-ecr";
46
45
  import { EcrHostedRegistry } from "../hosted-registry-ecr.js";
@@ -123,8 +122,14 @@ const KEY_CHECK_MS = 10 * 60_000;
123
122
  const CAPABILITY_PROBE_MS = 60 * 60_000;
124
123
  const lastCapabilityProbe = new Map();
125
124
  const WORKTREE_PRUNE_INTERVAL_MS = 60 * 60_000;
125
+ const WORKTREE_PRUNE_TIMEOUT_MS = 2 * 60_000;
126
126
  const lastWorktreePrune = new Map();
127
- export function resetWorktreePrune() { lastWorktreePrune.clear(); }
127
+ export function resetWorktreePrune() {
128
+ for (const state of lastWorktreePrune.values())
129
+ if (state.worker)
130
+ void state.worker.terminate();
131
+ lastWorktreePrune.clear();
132
+ }
128
133
  export function turnFaultSessionFields(fault, agent) {
129
134
  const binding = agent ? readState(agent).watch_turn_binding : undefined;
130
135
  return {
@@ -1887,35 +1892,93 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1887
1892
  const repo = join(actualWorkdir, project.name, "main");
1888
1893
  if (!existsSync(join(repo, ".git")))
1889
1894
  continue;
1890
- const prior = lastWorktreePrune.get(project.id);
1891
- if (prior && Date.now() - prior.at < WORKTREE_PRUNE_INTERVAL_MS) {
1892
- worktreePrune.push(prior.result);
1893
- continue;
1894
- }
1895
- // Record the attempt before network or filesystem work so a failing API cannot cause
1896
- // the daemon's 30-second report loop to repeat a destructive scan.
1897
- const attemptedAt = Date.now();
1898
- const session = desired.find((s) => s.project_id === project.id && s.agent);
1899
- if (!session) {
1900
- const skipped = { project: project.name, repo, status: "skipped", reason: "no project session is available to read pruning protections" };
1901
- lastWorktreePrune.set(project.id, { at: attemptedAt, result: skipped });
1902
- worktreePrune.push(skipped);
1903
- log(`${project.name}: worktree prune skipped: no project session is available`);
1904
- continue;
1905
- }
1906
- try {
1907
- const creds = loadAgent(session.agent);
1908
- const protection = await collectPruneProtection(creds, project.name);
1909
- const result = await pruneProjectWorktrees(creds, project.name, repo, protection, log);
1910
- lastWorktreePrune.set(project.id, { at: attemptedAt, result });
1911
- worktreePrune.push(result);
1912
- }
1913
- catch (error) {
1914
- const skipped = { project: project.name, repo, status: "error", reason: error.message };
1915
- lastWorktreePrune.set(project.id, { at: attemptedAt, result: skipped });
1916
- worktreePrune.push(skipped);
1917
- log(`${project.name}: worktree prune failed safely: ${error.message}`);
1895
+ let prior = lastWorktreePrune.get(project.id);
1896
+ const due = !prior || Date.now() - prior.at >= WORKTREE_PRUNE_INTERVAL_MS;
1897
+ if (due && !prior?.worker) {
1898
+ // Mark the attempt before starting the isolated worker, so overlapping reconcile passes
1899
+ // cannot start a second scan or removal for the same project.
1900
+ const attemptedAt = Date.now();
1901
+ const session = desired.find((s) => s.project_id === project.id && s.agent);
1902
+ if (!session) {
1903
+ const skipped = { project: project.name, repo, status: "skipped", reason: "no project session is available to read pruning protections" };
1904
+ prior = { at: attemptedAt, result: skipped };
1905
+ lastWorktreePrune.set(project.id, prior);
1906
+ log(`${project.name}: worktree prune skipped: no project session is available`);
1907
+ }
1908
+ else {
1909
+ try {
1910
+ const creds = loadAgent(session.agent);
1911
+ prior = { at: attemptedAt, result: { project: project.name, repo, status: "running" } };
1912
+ lastWorktreePrune.set(project.id, prior);
1913
+ if (deps?.pruneRunner) {
1914
+ void Promise.resolve().then(() => deps.pruneRunner(creds, project.name, repo, log)).then((result) => {
1915
+ if (lastWorktreePrune.get(project.id) === prior)
1916
+ prior.result = result;
1917
+ }).catch((error) => {
1918
+ if (lastWorktreePrune.get(project.id) !== prior)
1919
+ return;
1920
+ const failure = { project: project.name, repo, status: "error", reason: error.message };
1921
+ prior.result = failure;
1922
+ log(`${project.name}: worktree prune failed safely: ${error.message}`);
1923
+ });
1924
+ }
1925
+ else {
1926
+ const worker = new Worker(deps?.worktreePruneWorkerUrl ?? new URL("./worktree-prune-worker.js", import.meta.url), {
1927
+ workerData: { creds, project: project.name, repo },
1928
+ });
1929
+ prior.worker = worker;
1930
+ const timeoutMs = deps?.worktreePruneTimeoutMs ?? WORKTREE_PRUNE_TIMEOUT_MS;
1931
+ let settled = false;
1932
+ const timer = setTimeout(() => {
1933
+ if (settled)
1934
+ return;
1935
+ settled = true;
1936
+ prior.result = { project: project.name, repo, status: "error", reason: `worktree prune exceeded ${timeoutMs} ms; worker termination requested` };
1937
+ log(`${project.name}: worktree prune exceeded ${timeoutMs} ms; daemon reporting continues`);
1938
+ void worker.terminate().finally(() => {
1939
+ if (lastWorktreePrune.get(project.id) === prior)
1940
+ prior.worker = undefined;
1941
+ });
1942
+ }, timeoutMs);
1943
+ const finish = (result) => {
1944
+ if (settled)
1945
+ return;
1946
+ settled = true;
1947
+ clearTimeout(timer);
1948
+ if (lastWorktreePrune.get(project.id) === prior)
1949
+ prior.result = result;
1950
+ };
1951
+ worker.on("message", (message) => {
1952
+ if (message.type === "log" && message.line)
1953
+ log(message.line);
1954
+ else if (message.type === "result" && message.result)
1955
+ finish(message.result);
1956
+ });
1957
+ worker.on("error", (error) => {
1958
+ const reason = error.message;
1959
+ finish({ project: project.name, repo, status: "error", reason });
1960
+ log(`${project.name}: worktree prune failed safely: ${reason}`);
1961
+ });
1962
+ worker.on("exit", (code) => {
1963
+ if (!settled) {
1964
+ const reason = `worktree prune worker exited with code ${code} without a result`;
1965
+ finish({ project: project.name, repo, status: "error", reason });
1966
+ log(`${project.name}: ${reason}`);
1967
+ }
1968
+ if (lastWorktreePrune.get(project.id) === prior)
1969
+ prior.worker = undefined;
1970
+ });
1971
+ }
1972
+ }
1973
+ catch (error) {
1974
+ const failure = { project: project.name, repo, status: "error", reason: error.message };
1975
+ prior = { at: attemptedAt, result: failure };
1976
+ lastWorktreePrune.set(project.id, prior);
1977
+ log(`${project.name}: worktree prune failed safely: ${error.message}`);
1978
+ }
1979
+ }
1918
1980
  }
1981
+ worktreePrune.push(prior?.result ?? { project: project.name, repo, status: "running" });
1919
1982
  }
1920
1983
  const workSpace = volumeSpace(actualWorkdir, "workdir");
1921
1984
  const facts = machineFacts([...providerChecks], {
@@ -1931,7 +1994,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1931
1994
  const environmentChecks = machineEnvironmentChecks({ ...facts, workdir_free_bytes: workSpace?.freeBytes ?? null, workdir_total_bytes: workSpace?.totalBytes ?? null }, writable)
1932
1995
  .map(({ check, status, observation, remedy, recovery_verified }) => ({ check, status, diagnosis: observation, remedy, recovery_verified, observed_at: new Date().toISOString() }));
1933
1996
  const dirtyClosedWorktrees = worktreePrune.flatMap((result) => Array.isArray(result.dirty_closed) ? result.dirty_closed.filter((item) => typeof item === "string") : []);
1934
- const pruneUnavailable = worktreePrune.some((result) => result.status === "error" || result.status === "skipped");
1997
+ const pruneUnavailable = worktreePrune.some((result) => result.status === "error" || result.status === "skipped" || result.status === "running");
1935
1998
  const pruneStatus = dirtyClosedWorktrees.length ? "failed" : pruneUnavailable ? "unknown" : "healthy";
1936
1999
  const pruneDiagnosis = [
1937
2000
  ...dirtyClosedWorktrees.slice(-5),
@@ -0,0 +1,18 @@
1
+ import { parentPort, workerData } from "node:worker_threads";
2
+ import { collectPruneProtection } from "../prune-protection.js";
3
+ import { pruneProjectWorktrees } from "./worktrees.js";
4
+ const input = workerData;
5
+ const log = (line) => parentPort?.postMessage({ type: "log", line });
6
+ try {
7
+ const protection = await collectPruneProtection(input.creds, input.project);
8
+ const result = await pruneProjectWorktrees(input.creds, input.project, input.repo, protection, log);
9
+ parentPort?.postMessage({ type: "result", result });
10
+ parentPort?.close();
11
+ }
12
+ catch (error) {
13
+ parentPort?.postMessage({
14
+ type: "result",
15
+ result: { project: input.project, repo: input.repo, status: "error", reason: error.message },
16
+ });
17
+ parentPort?.close();
18
+ }
package/dist/config.js CHANGED
@@ -7,6 +7,7 @@ import { writeFileAtomic } from "./shared-file.js";
7
7
  import { readState, updateState } from "./state.js";
8
8
  import { detectVendor } from "./vendor.js";
9
9
  import { configDirectory } from "./directories.js";
10
+ import { CLI_VERSION } from "./version.js";
10
11
  export const DEFAULT_URL = "https://api.benignswarm.org";
11
12
  export function configRoot(env = process.env) {
12
13
  return configDirectory(env);
@@ -167,7 +168,7 @@ export function resolveAgentName(asFlag, env = process.env, cwd = process.cwd())
167
168
  const saved = listSaved("agents", env);
168
169
  throw new CliError("no_identity", `BSCHAT_AGENT is not set and --as was not given; b9s cannot tell which agent you are${identityWalkStoppedAt() ? ` (it looked for this checkout's identity file up to ${identityWalkStoppedAt()}, where it is not permitted to look)` : ""}`, saved.length
169
170
  ? `Saved identities on this machine: ${saved.join(", ")}. Ask the user which one is yours, then: export BSCHAT_AGENT=<project>/<name> (or run: b9s setup --as <project>/<name> to record it for this repo)`
170
- : "No identities are saved here. Ask the account owner for an invite (an enrollment token) and run: npx -y benignswarm join --as <name> --token <bs_enroll_...>");
171
+ : `No identities are saved here. Ask the account owner for an invite (an enrollment token). If b9s is installed, run: b9s join --as <name> --token <bs_enroll_...>. Otherwise use: npx -y benignswarm@${CLI_VERSION} join --as <name> --token <bs_enroll_...>`);
171
172
  }
172
173
  return isRef(name) ? name : resolveSavedRef(name, env);
173
174
  }
@@ -103,6 +103,16 @@ export function gitSandboxWritablePaths(checkout, additionalCheckouts = []) {
103
103
  }
104
104
  return [...paths];
105
105
  }
106
+ /** Git needs to read both the linked worktree's admin directory and its shared repository data. */
107
+ export function gitSandboxReadablePaths(checkout, additionalCheckouts = []) {
108
+ const checkouts = [{ label: "agent checkout", path: checkout }, ...additionalCheckouts];
109
+ const metadata = checkouts.map(({ label, path }) => gitMetadata(path, label));
110
+ const commonDir = metadata[0].commonDir;
111
+ if (metadata.some((item) => item.commonDir !== commonDir)) {
112
+ throw new CliError("sandbox_git_metadata_mismatch", "workspace-write checkouts do not share one Git common directory");
113
+ }
114
+ return [...new Set([commonDir, ...metadata.map((item) => item.gitDir)])];
115
+ }
106
116
  /** Paths that must remain explicitly unwritable even as Git's mutable stores are granted. */
107
117
  export function gitSandboxDeniedPaths(checkout, additionalCheckouts = []) {
108
118
  const { gitDir, commonDir } = gitMetadata(checkout, "agent checkout");
package/dist/index.js CHANGED
File without changes
package/dist/install.js CHANGED
@@ -17,16 +17,16 @@ export function readInstall() {
17
17
  return JSON.parse(readFileSync(p, "utf8"));
18
18
  }
19
19
  catch {
20
- throw new CliError("bad_install_record", `${p} is not valid JSON`, "Run: npx -y benignswarm install (rewrites it)");
20
+ throw new CliError("bad_install_record", `${p} is not valid JSON`, `Run: npx -y benignswarm@${CLI_VERSION} install (rewrites it)`);
21
21
  }
22
22
  }
23
23
  /** The recorded install, checked to still exist; what watchers and hooks are pointed at. */
24
24
  export function requireInstall() {
25
25
  const r = readInstall();
26
26
  if (!r)
27
- throw new CliError("not_installed", "b9s has no recorded install on this machine", "Run: npx -y benignswarm install (installs b9s once and records where; join does this too)");
27
+ throw new CliError("not_installed", "b9s has no recorded install on this machine", `Run: npx -y benignswarm@${CLI_VERSION} install (installs b9s once and records where; join does this too)`);
28
28
  if (!existsSync(r.bin))
29
- throw new CliError("install_missing", `the recorded b9s install ${r.bin} no longer exists`, "Run: npx -y benignswarm install");
29
+ throw new CliError("install_missing", `the recorded b9s install ${r.bin} no longer exists`, `Run: npx -y benignswarm@${CLI_VERSION} install`);
30
30
  if (basename(r.bin) === "bschat") {
31
31
  const primaryBin = join(dirname(r.bin), "b9s");
32
32
  if (!existsSync(primaryBin))
@@ -181,6 +181,13 @@ export function latestPublished(npm) {
181
181
  throw new CliError("npm_view_failed", `could not ask npm for the latest benignswarm version (${npm})`, (r.stderr ?? "").trim().slice(0, 300));
182
182
  return v;
183
183
  }
184
+ /** A second-copy join must refuse before the single-use token is sent when this machine is newer. */
185
+ export function assertMachineInstallNotNewer(version) {
186
+ const previous = readInstall();
187
+ if (previous && /^\d+\.\d+\.\d+$/.test(previous.version) && cmp(previous.version, version) > 0) {
188
+ throw new CliError("recorded_install_newer", `the recorded b9s ${previous.version} at ${previous.bin} is newer than this CLI ${version}`, `Run ${previous.bin} install --latest from the Node installation you want this machine to use`);
189
+ }
190
+ }
184
191
  /**
185
192
  * Makes sure this machine's global b9s is at least `version`, installing with the npm next to
186
193
  * the running Node when it is missing or older, and records it. Progress goes to stderr so a
@@ -246,9 +253,7 @@ export function ensureMachineInstall(version, log) {
246
253
  // A join/setup invoked by an older npx or global copy must never write its own version back
247
254
  // into a newer machine install. The operator can intentionally select or upgrade the install
248
255
  // by invoking the explicit install command from the desired Node installation.
249
- if (/^\d+\.\d+\.\d+$/.test(previous.version) && cmp(previous.version, version) > 0) {
250
- throw new CliError("recorded_install_newer", `the recorded b9s ${previous.version} at ${previous.bin} is newer than this CLI ${version}`, `Run ${previous.bin} install --latest from the Node installation you want this machine to use`);
251
- }
256
+ assertMachineInstallNotNewer(version);
252
257
  // A Node upgrade may remove the versioned runtime path recorded by the prior install. The
253
258
  // currently running CLI is the runtime that can refresh this install; persist its resolved,
254
259
  // live executable rather than carrying the dead path forward.
@@ -82,7 +82,7 @@ function summarizePrune(value) {
82
82
  }
83
83
  const projects = entries.map((entry, index) => ({
84
84
  index,
85
- priority: entry.status === "error" || entry.status === "skipped" ? 0 : Array.isArray(entry.dirty_closed) && entry.dirty_closed.length ? 1 : 2,
85
+ priority: entry.status === "error" || entry.status === "skipped" || entry.status === "running" ? 0 : Array.isArray(entry.dirty_closed) && entry.dirty_closed.length ? 1 : 2,
86
86
  summary: {
87
87
  project: boundedText(entry.project),
88
88
  status: boundedText(entry.status),
@@ -56,6 +56,45 @@ export function parseFailedGateStep(output, stepTimeline) {
56
56
  const failedTimelineStep = [...stepTimeline].reverse().find((s) => s.exit_code !== null && s.exit_code !== 0);
57
57
  return failedTimelineStep?.name ?? "gate";
58
58
  }
59
+ /** Classify only explicit baseline races and known gate-harness failure signatures. */
60
+ export function classifyRetryableGateFailure(output, exitCode) {
61
+ if (/^gate:\s+stale baseline:/im.test(output))
62
+ return "stale baseline";
63
+ const assertionFailure = /\bAssertionError\b|\bTests?\s+\d+\s+failed\b|\bTest Files?\s+\d+\s+failed\b/i.test(output);
64
+ const setupFailure = /\b(?:test setup error|setup file(?:s)?[^\n]*(?:failed|error)|failed (?:during|while) (?:the )?test setup|error (?:during|while) (?:the )?test setup)\b/i.test(output);
65
+ const localD1Failure = /\bD1_ERROR:\s*[^\n]*\binternal error\b|\binternal error in Durable Object storage\b/i.test(output);
66
+ const watchdogTimeout = (exitCode === 124 || /^gate:\s+.+\s+exit 124(?:\s+in\s+\d+\s+s)?\s*$/im.test(output)) && !assertionFailure;
67
+ if (setupFailure || localD1Failure || watchdogTimeout)
68
+ return "infrastructure";
69
+ return null;
70
+ }
71
+ export function changedFilesCanAffectGateStep(step, changedFiles) {
72
+ const target = /\bapi tests?\b/i.test(step)
73
+ ? "api"
74
+ : /\b(?:cli tests?|published CLI contract)\b/i.test(step)
75
+ ? "cli"
76
+ : /\bweb (?:tests?|build)\b/i.test(step)
77
+ ? "web"
78
+ : null;
79
+ if (!target)
80
+ return true;
81
+ const category = (file) => {
82
+ const normalized = file.replaceAll("\\", "/");
83
+ if (normalized.startsWith("apps/api/"))
84
+ return "api";
85
+ // The API's context-policy tests import CLI modules, and the API entrypoint
86
+ // embeds both skill packages. Changes there can fail API tests as well as CLI.
87
+ if (normalized.startsWith("packages/cli/") || normalized.startsWith("packages/skill/") || normalized.startsWith("packages/skill-admin/"))
88
+ return "shared";
89
+ if (normalized.startsWith("apps/web/public/") || normalized.startsWith("docs/") || normalized.startsWith("scripts/ux"))
90
+ return "irrelevant";
91
+ if (normalized.startsWith("apps/web/"))
92
+ return "web";
93
+ return "shared";
94
+ };
95
+ const categories = changedFiles.map(category);
96
+ return categories.includes(target) || categories.includes("shared");
97
+ }
59
98
  // The failure blocks of a test log: vitest's " FAIL <file> > <test>" sections up to the next separator rule
60
99
  // (⎯) or FAIL line, and node:test's "not ok" entries with their indented details. Nothing else.
61
100
  export function failingTestText(output) {
@@ -88,18 +127,6 @@ export function failingTestText(output) {
88
127
  blocks.push(current.join("\n"));
89
128
  return blocks.join("\n");
90
129
  }
91
- /** Classify only explicit baseline races and known gate-harness failure signatures. */
92
- export function classifyRetryableGateFailure(output, exitCode) {
93
- if (/^gate:\s+stale baseline:/im.test(output))
94
- return "stale baseline";
95
- const assertionFailure = /\bAssertionError\b|\bTests?\s+\d+\s+failed\b|\bTest Files?\s+\d+\s+failed\b/i.test(output);
96
- const setupFailure = /\b(?:test setup error|setup file(?:s)?[^\n]*(?:failed|error)|failed (?:during|while) (?:the )?test setup|error (?:during|while) (?:the )?test setup)\b/i.test(output);
97
- const localD1Failure = /\bD1_ERROR:\s*[^\n]*\binternal error\b|\binternal error in Durable Object storage\b/i.test(output);
98
- const watchdogTimeout = (exitCode === 124 || /^gate:\s+.+\s+exit 124(?:\s+in\s+\d+\s+s)?\s*$/im.test(output)) && !assertionFailure;
99
- if (setupFailure || localD1Failure || watchdogTimeout)
100
- return "infrastructure";
101
- return null;
102
- }
103
130
  export function detectUnitAttributedFailureFromOutput(output, entries) {
104
131
  const unitSet = new Set(entries.map((e) => e.work_unit_number));
105
132
  const matches = new Set();
@@ -446,39 +473,16 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
446
473
  if (mainRun.status !== 0) {
447
474
  failedStep = parseFailedGateStep(mainRun.output, h.stepTimeline);
448
475
  retryGateReason = classifyRetryableGateFailure(mainRun.output, mainRun.status);
449
- if (retryGateReason) {
476
+ if (retryGateReason)
450
477
  h.onLogLine(`merge-train ${trainRun.id}: gate failed with retryable ${retryGateReason} signature`);
451
- }
452
- else if (included.length === 1) {
453
- // A failed candidate alone does not establish that this unit broke the
454
- // gate: the target may already be failing. Verify the exact target before
455
- // assigning a single-unit failure.
456
- await resetCleanWorktree(h.worktreeDir, baseSha, h.runner, gitEnv);
457
- const baseProbe = await runGateAtHead(`verify target ${baseSha.slice(0, 9)}`, anchorUnit, baseSha);
458
- if (baseProbe.status !== 0) {
459
- retryGateReason = classifyRetryableGateFailure(baseProbe.output, baseProbe.status);
460
- if (retryGateReason) {
461
- h.onLogLine(`merge-train ${trainRun.id}: target-only verification had retryable ${retryGateReason} signature`);
462
- }
463
- else {
464
- attributionMethod = "unattributed";
465
- attributionReason = `target branch ${trainRun.target_branch} at ${baseSha.slice(0, 9)} already failed ${failedStep}`;
466
- }
467
- }
468
- else {
469
- attributedUnitNumber = included[0].entry.work_unit_number;
470
- attributionMethod = "single_unit";
471
- attributionReason = `verified ${trainRun.target_branch} passes and only WU #${attributedUnitNumber} fails ${failedStep}`;
472
- }
473
- }
474
- else {
478
+ if (!retryGateReason) {
479
+ const initialFailedStep = failedStep;
475
480
  const outputHint = detectUnitAttributedFailureFromOutput(mainRun.output, included.map((i) => i.entry));
476
- if (outputHint) {
477
- attributedUnitNumber = outputHint.unitNumber;
478
- attributionMethod = "unit_output";
479
- attributionReason = outputHint.reason;
480
- }
481
- else {
481
+ let candidateIndex = outputHint
482
+ ? included.findIndex((item) => item.entry.work_unit_number === outputHint.unitNumber)
483
+ : included.length === 1 ? 0 : -1;
484
+ let candidateMethod = outputHint ? "unit_output" : included.length === 1 ? "single_unit" : "bisect";
485
+ if (candidateIndex < 0 && included.length > 1) {
482
486
  // Binary-search prefixes [0..mid] to find the first failing unit.
483
487
  let lo = 0;
484
488
  let hi = included.length - 1;
@@ -494,6 +498,8 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
494
498
  env: gitEnv,
495
499
  timeoutMs: 15_000,
496
500
  });
501
+ if (midRev.status !== 0)
502
+ throw new Error("could not resolve bisection prefix HEAD");
497
503
  const midSha = midRev.stdout.trim().toLowerCase();
498
504
  const probe = await runGateAtHead(`bisect WU #${included.slice(0, mid + 1).map((x) => x.entry.work_unit_number).join(",#")}`, included[0].entry.work_unit_number, midSha);
499
505
  if (probe.status !== 0)
@@ -505,8 +511,12 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
505
511
  else
506
512
  hi = mid;
507
513
  }
508
- if (!retryGateReason && lo === 0) {
509
- // Verify baseline target wasn't already broken before blaming the first unit.
514
+ candidateIndex = lo;
515
+ }
516
+ if (!retryGateReason && candidateIndex >= 0) {
517
+ const candidate = included[candidateIndex];
518
+ // A first-unit failure may already exist on target/main; never blame its only addition without checking.
519
+ if (candidateIndex === 0) {
510
520
  await resetCleanWorktree(h.worktreeDir, baseSha, h.runner, gitEnv);
511
521
  const baseProbe = await runGateAtHead(`bisect target ${baseSha.slice(0, 9)}`, anchorUnit, baseSha);
512
522
  if (baseProbe.status !== 0) {
@@ -515,21 +525,56 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
515
525
  h.onLogLine(`merge-train ${trainRun.id}: target-only verification had retryable ${retryGateReason} signature`);
516
526
  }
517
527
  else {
518
- attributedUnitNumber = null;
519
- attributionMethod = "unattributed";
520
- attributionReason = `target branch ${trainRun.target_branch} at ${baseSha.slice(0, 9)} already failed ${failedStep}`;
528
+ attributionReason = `target branch ${trainRun.target_branch} at ${baseSha.slice(0, 9)} already failed ${initialFailedStep}`;
529
+ candidateIndex = -1;
521
530
  }
522
531
  }
523
- else {
524
- attributedUnitNumber = included[0].entry.work_unit_number;
525
- attributionMethod = "bisect";
526
- attributionReason = `bisect confirmed ${trainRun.target_branch} passes and WU #${attributedUnitNumber} fails ${failedStep}`;
532
+ }
533
+ if (!retryGateReason && candidateIndex >= 0) {
534
+ const diff = await h.runner("git", ["-C", h.worktreeDir, "diff", "--name-only", `${baseSha}...${candidate.resolvedSha}`], {
535
+ cwd: h.worktreeDir,
536
+ env: gitEnv,
537
+ timeoutMs: 15_000,
538
+ });
539
+ if (diff.status !== 0)
540
+ throw new Error(`could not inspect changed files for WU #${candidate.entry.work_unit_number}`);
541
+ const changedFiles = diff.stdout.split(/\r?\n/).filter(Boolean);
542
+ if (!changedFilesCanAffectGateStep(initialFailedStep, changedFiles)) {
543
+ failedStep = "flaky test";
544
+ attributionReason = `failure at ${initialFailedStep} cannot be caused by WU #${candidate.entry.work_unit_number}; its changed files are outside that package`;
545
+ candidateIndex = -1;
527
546
  }
528
547
  }
529
- else if (!retryGateReason) {
530
- attributedUnitNumber = included[lo].entry.work_unit_number;
531
- attributionMethod = "bisect";
532
- attributionReason = `bisect isolated failure at ${failedStep} to WU #${attributedUnitNumber}`;
548
+ if (!retryGateReason && candidateIndex >= 0) {
549
+ // A single failing bisection half is insufficient evidence: repeat that exact prefix once.
550
+ await resetCleanWorktree(h.worktreeDir, baseSha, h.runner, gitEnv);
551
+ for (let i = 0; i <= candidateIndex; i++) {
552
+ const part = included[i];
553
+ await mergeEntryIntoHead(h.worktreeDir, part.entry, part.resolvedSha, trainRun.require_merge_commit, h.runner, gitEnv);
554
+ }
555
+ const confirmRev = await h.runner("git", ["-C", h.worktreeDir, "rev-parse", "HEAD"], {
556
+ cwd: h.worktreeDir,
557
+ env: gitEnv,
558
+ timeoutMs: 15_000,
559
+ });
560
+ if (confirmRev.status !== 0)
561
+ throw new Error("could not resolve confirmation prefix HEAD");
562
+ const confirmation = await runGateAtHead(`confirm failing half through WU #${candidate.entry.work_unit_number}`, included[0].entry.work_unit_number, confirmRev.stdout.trim().toLowerCase());
563
+ if (confirmation.status !== 0)
564
+ retryGateReason = classifyRetryableGateFailure(confirmation.output, confirmation.status);
565
+ if (retryGateReason)
566
+ h.onLogLine(`merge-train ${trainRun.id}: confirmation probe had retryable ${retryGateReason} signature`);
567
+ else if (confirmation.status === 0 || parseFailedGateStep(confirmation.output, h.stepTimeline) !== initialFailedStep) {
568
+ failedStep = "flaky test";
569
+ attributionReason = `failure at ${initialFailedStep} did not reproduce for the same prefix through WU #${candidate.entry.work_unit_number}`;
570
+ }
571
+ else {
572
+ attributedUnitNumber = candidate.entry.work_unit_number;
573
+ attributionMethod = candidateMethod;
574
+ attributionReason = outputHint?.unitNumber === attributedUnitNumber
575
+ ? outputHint.reason
576
+ : `${candidateMethod === "single_unit" ? "single unit" : "bisect"} reproduced ${initialFailedStep} after confirmation for WU #${attributedUnitNumber}`;
577
+ }
533
578
  }
534
579
  }
535
580
  }
@@ -568,6 +613,7 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
568
613
  attribution_method: "unattributed",
569
614
  attribution_reason: reason.slice(0, 500),
570
615
  retry_count: retryCount,
616
+ ...(retryReasons.length ? { retry_reasons: [...retryReasons] } : {}),
571
617
  },
572
618
  };
573
619
  }
@@ -576,8 +622,7 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
576
622
  retryCount++;
577
623
  if (!retryReasons.includes(retryGateReason))
578
624
  retryReasons.push(retryGateReason);
579
- const retryLine = `merge-train ${trainRun.id}: retried: ${retryGateReason} (${retryCount}/${MAX_RE_GATE_ATTEMPTS})`;
580
- h.onLogLine(retryLine);
625
+ h.onLogLine(`merge-train ${trainRun.id}: retried: ${retryGateReason} (${retryCount}/${MAX_RE_GATE_ATTEMPTS})`);
581
626
  if (retryCount >= MAX_RE_GATE_ATTEMPTS) {
582
627
  const reasonText = `merge train exhausted ${MAX_RE_GATE_ATTEMPTS} attempts after retryable ${retryGateReason} failures`;
583
628
  return {
@@ -405,7 +405,7 @@ const CODEX_WORKSPACE_WRITE = "measured 2026-11-19 in Codex workspace-write: wri
405
405
  const CLAUDE_WORKTREE = "measured 2026-11-19 in Claude Code workspace-write: git worktree add is refused because the clone's shared .git/worktrees folder is read-only; the watcher must prepare unit worktrees outside the sandbox";
406
406
  const CLAUDE_WORKSPACE_WRITE = "measured 2026-11-19 in Claude Code workspace-write: writes to the user's home, Node installation, checkout parent, shared git config and hooks are refused";
407
407
  const CLAUDE_ORIGIN = "origin transport is machine-specific; git remote read and active-worktree fetch are measured independently";
408
- const ANTIGRAVITY_GIT_SCOPE = "Antigravity workspace-write policy: Git objects, refs and logs plus exact active/prepared worktree metadata are writable; arbitrary git worktree add is refused because only exact paths or recursive directories are supported, and recursive registry access would expose siblings. The watcher prepares the unit worktree before the turn; config, hooks, sibling worktrees and the checkout parent stay refused";
408
+ const ANTIGRAVITY_GIT_SCOPE = "Antigravity workspace-write policy: the active worktree Git directory and common Git directory are readable; Git objects, refs and logs plus exact active/prepared worktree metadata are writable. Shared config/hooks and sibling worktree metadata remain unwritable; arbitrary git worktree add is refused because recursive registry access would expose siblings. The watcher prepares the unit worktree before the turn, and the checkout parent stays unwritable";
409
409
  const ANTIGRAVITY_REF_CLEANUP = "measured 2026-11-20 on Linux Antigravity 1.5.13: branch creation and commit-object writes work, but deleting a ref requires .git/packed-refs.lock under the read-only common Git directory. The watcher removes refs in this probe namespace outside the sandbox after the check; the session does not delete branches";
410
410
  export function expectedFor(harness, sandbox, result) {
411
411
  const works = { expected: "works" };
package/dist/version.js CHANGED
@@ -1 +1,3 @@
1
- export const CLI_VERSION = "0.12.161";
1
+ export const CLI_VERSION = "0.12.162";
2
+ /** First release allowed to consume single-use join tokens with the save-before-install flow. */
3
+ export const CLI_JOIN_MIN_VERSION = "0.12.159";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.161",
3
+ "version": "0.12.162",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {