benignswarm 0.12.160 → 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.
package/dist/args.js CHANGED
@@ -50,6 +50,10 @@ export const BOOL_FLAGS = [
50
50
  "in-container", "retrieve-ec2", "stdin", "context-confirmed", "confirm-compatible", "move-provisioned", "provisioned", "no-commits-beyond-target", "train",
51
51
  ];
52
52
  export function parse(argv) {
53
+ // `gh` owns its option grammar. Preserve its arguments verbatim instead of interpreting
54
+ // GitHub CLI flags as b9s options.
55
+ if (argv[0] === "gh")
56
+ return { positionals: ["gh"], flags: {}, rest: argv.slice(1) };
53
57
  const options = {};
54
58
  for (const f of STRING_FLAGS)
55
59
  options[f] = { type: "string", ...(LIST_FLAGS.includes(f) ? { multiple: true } : {}) };
@@ -32,6 +32,13 @@ function commandUsageLines(help) {
32
32
  result[result.length - 1] = `${result[result.length - 1]} ${groups.join(" ")}`;
33
33
  continue;
34
34
  }
35
+ // A wrapped synopsis line may also start with a required option ("--count <n> | --min <n> ...
36
+ // --sandbox <mode> [--needs ...]"): its synopsis part (up to the aligned description column) belongs
37
+ // to the command. `pool set` documented --count and --sandbox there and refused both (2026-11-23).
38
+ if (continuing && /^\s+--[a-z]/.test(lines[i])) {
39
+ result[result.length - 1] = `${result[result.length - 1]} ${lines[i].trim().split(/\s{2,}/, 1)[0]}`;
40
+ continue;
41
+ }
35
42
  continuing = false;
36
43
  }
37
44
  return result;
@@ -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 {
@@ -0,0 +1,156 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { mkdtempSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { Client } from "../client.js";
6
+ import { loadAgent, resolveAgentName } from "../config.js";
7
+ import { CliError } from "../errors.js";
8
+ import { githubCredentialForRepository, remoteRepository } from "./git-credential.js";
9
+ const run = (command, args, options) => spawnSync(command, args, options);
10
+ function repositoryArgument(value) {
11
+ if (!value)
12
+ return null;
13
+ const normalized = value.trim().replace(/^https?:\/\/github\.com\//i, "").replace(/\.git$/i, "").replace(/\/$/, "");
14
+ return /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(normalized) ? normalized.toLowerCase() : null;
15
+ }
16
+ const GH_COMMAND_OPTIONS = {
17
+ "pr view": {
18
+ values: new Set(["--repo", "-R", "--hostname", "-H", "--json", "--jq", "--template"]),
19
+ booleans: new Set(["--comments"]),
20
+ },
21
+ "pr checks": {
22
+ values: new Set(["--repo", "-R", "--hostname", "-H", "--interval", "--json", "--jq", "--template"]),
23
+ booleans: new Set(["--watch", "--required", "--fail-fast"]),
24
+ },
25
+ "pr status": {
26
+ values: new Set(["--repo", "-R", "--hostname", "-H", "--json", "--jq", "--template"]),
27
+ booleans: new Set(),
28
+ },
29
+ };
30
+ function pullRequestTarget(value, linkedRepository) {
31
+ if (/^\d+$/.test(value))
32
+ return Number(value) > 0;
33
+ try {
34
+ const url = new URL(value);
35
+ if (url.origin !== "https://github.com" || url.username || url.password)
36
+ return false;
37
+ const match = /^\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/.exec(url.pathname);
38
+ return Boolean(match && `${match[1]}/${match[2]}`.toLowerCase() === linkedRepository && Number(match[3]) > 0 && !url.search && !url.hash);
39
+ }
40
+ catch {
41
+ return false;
42
+ }
43
+ }
44
+ function validateGhOperation(args, linkedRepository, env) {
45
+ const operation = `${args[0] ?? ""} ${args[1] ?? ""}`;
46
+ const contract = GH_COMMAND_OPTIONS[operation];
47
+ if (!contract) {
48
+ throw new CliError("github_command_unsupported", "b9s gh supports only read-only gh pr view, gh pr checks, and gh pr status operations.");
49
+ }
50
+ if (env.GH_REPO && repositoryArgument(env.GH_REPO) !== linkedRepository) {
51
+ throw new CliError("github_repository_mismatch", `GH_REPO points to ${env.GH_REPO}, not the linked project repository ${linkedRepository}.`);
52
+ }
53
+ const positional = [];
54
+ for (let index = 2; index < args.length; index += 1) {
55
+ const arg = args[index];
56
+ if (arg === "--")
57
+ throw new CliError("github_arguments_unsupported", "b9s gh does not accept an argument separator or shell passthrough.");
58
+ if (!arg.startsWith("-")) {
59
+ positional.push(arg);
60
+ continue;
61
+ }
62
+ const equal = arg.indexOf("=");
63
+ const flag = equal > 0 ? arg.slice(0, equal) : (arg.startsWith("-R") && arg !== "-R" ? "-R" : arg);
64
+ const inlineValue = equal > 0 ? arg.slice(equal + 1) : (flag === "-R" && arg !== "-R" ? arg.slice(2) : undefined);
65
+ if (contract.values.has(flag)) {
66
+ const value = inlineValue ?? args[index + 1];
67
+ if (!value || value.startsWith("--"))
68
+ throw new CliError("usage", `${flag} requires a value.`);
69
+ if (inlineValue === undefined)
70
+ index += 1;
71
+ if (flag === "--repo" || flag === "-R") {
72
+ if (repositoryArgument(value) !== linkedRepository) {
73
+ throw new CliError("github_repository_mismatch", `gh target ${value} is not the linked project repository ${linkedRepository}.`);
74
+ }
75
+ }
76
+ else if ((flag === "--hostname" || flag === "-H") && value.toLowerCase() !== "github.com") {
77
+ throw new CliError("github_host_unsupported", "b9s gh is pinned to github.com.");
78
+ }
79
+ continue;
80
+ }
81
+ if (contract.booleans.has(flag) && inlineValue === undefined)
82
+ continue;
83
+ throw new CliError("github_option_unsupported", `b9s gh does not support ${arg}.`);
84
+ }
85
+ if (operation === "pr status" && positional.length > 0) {
86
+ throw new CliError("github_target_unsupported", "gh pr status does not accept a repository or pull request target.");
87
+ }
88
+ if ((operation === "pr view" || operation === "pr checks") && positional.some((value) => !pullRequestTarget(value, linkedRepository))) {
89
+ throw new CliError("github_repository_mismatch", "b9s gh accepts only a pull request number or a github.com URL in the linked repository.");
90
+ }
91
+ if (positional.length > 1 || (operation === "pr status" && positional.length !== 0)) {
92
+ throw new CliError("github_target_unsupported", `b9s gh ${operation} accepts at most one pull request target.`);
93
+ }
94
+ }
95
+ export async function runGhWithProjectCredential(args, cwd, api, runner = run, parentEnv = process.env) {
96
+ if (args.length === 0)
97
+ throw new CliError("usage", "b9s gh <gh arguments>");
98
+ const origin = runner("git", ["config", "--get", "remote.origin.url"], { cwd, encoding: "utf8", env: parentEnv });
99
+ if (origin.error || origin.status !== 0) {
100
+ throw new CliError("github_repository_required", "b9s gh requires a GitHub repository checkout with remote.origin.url.");
101
+ }
102
+ const repository = remoteRepository(origin.stdout.trim());
103
+ if (!repository) {
104
+ throw new CliError("github_repository_required", "b9s gh only supports GitHub HTTPS or SSH repository origins.");
105
+ }
106
+ validateGhOperation(args, repository.path, parentEnv);
107
+ const credential = await githubCredentialForRepository(repository.path, api, true);
108
+ if (!credential?.password)
109
+ throw new CliError("github_credential_missing", "The linked repository did not return a GitHub credential.");
110
+ // The scoped installation token exists only in the gh child's environment. It is never
111
+ // included in arguments, output, diagnostics, or persistent CLI configuration.
112
+ const childEnv = { ...parentEnv, GH_HOST: "github.com", GH_REPO: repository.path, GH_TOKEN: credential.password };
113
+ // gh's --web option can launch a browser subprocess with its environment. Do not
114
+ // pass browser selection through even if the parent shell configured one.
115
+ delete childEnv.BROWSER;
116
+ delete childEnv.GH_BROWSER;
117
+ // Caller diagnostics and gh's user configuration can expose secrets through
118
+ // debug logs, aliases, or a configured external pager. Run with an empty,
119
+ // temporary config directory and no diagnostic/pager overrides. Piped output
120
+ // also keeps gh from starting its default pager on interactive terminals.
121
+ delete childEnv.GH_DEBUG;
122
+ delete childEnv.DEBUG;
123
+ delete childEnv.GH_PAGER;
124
+ delete childEnv.PAGER;
125
+ childEnv.GH_PROMPT_DISABLED = "1";
126
+ const configDir = mkdtempSync(join(tmpdir(), "b9s-gh-config-"));
127
+ childEnv.GH_CONFIG_DIR = configDir;
128
+ let result;
129
+ try {
130
+ result = runner("gh", args, {
131
+ cwd,
132
+ encoding: "utf8",
133
+ env: childEnv,
134
+ stdio: ["inherit", "pipe", "pipe"],
135
+ });
136
+ }
137
+ finally {
138
+ rmSync(configDir, { recursive: true, force: true });
139
+ }
140
+ if (result.stdout)
141
+ process.stdout.write(result.stdout);
142
+ if (result.stderr)
143
+ process.stderr.write(result.stderr);
144
+ if (result.error)
145
+ throw new CliError("gh_failed", `could not start gh: ${result.error.message}`);
146
+ return result.status ?? 1;
147
+ }
148
+ export async function gh(args) {
149
+ const agentName = resolveAgentName(undefined);
150
+ const agent = loadAgent(agentName);
151
+ if (!agent.project)
152
+ throw new CliError("github_not_connected", "b9s gh requires a project-scoped agent identity.");
153
+ const client = Client.forAgent(agent, undefined, { presence: false });
154
+ const base = `/projects/${encodeURIComponent(agent.project)}/git-credentials`;
155
+ return runGhWithProjectCredential(args, process.cwd(), (method, _path, body) => client.call(method, base, body));
156
+ }
@@ -33,15 +33,25 @@ export async function credentialResponse(input, api) {
33
33
  const wanted = repositoryPath(request.path);
34
34
  if (!wanted)
35
35
  return "";
36
+ const credential = await githubCredentialForRepository(wanted, api);
37
+ if (!credential)
38
+ return "";
39
+ return `username=${credential.username}\npassword=${credential.password}\n\n`;
40
+ }
41
+ /** Resolve a short-lived token through the same scoped credential endpoint used by Git. */
42
+ export async function githubCredentialForRepository(wanted, api, refuseUnlinkedRepository = false) {
36
43
  const metadata = await api("GET", "");
37
44
  if (!metadata.linked || !metadata.repository) {
38
45
  throw new CliError("github_not_connected", "GitHub is not connected for this project. Connect GitHub in the console to enable repository access.");
39
46
  }
40
47
  const linked = `${metadata.repository.owner}/${metadata.repository.name}`.toLowerCase();
41
- if (wanted !== linked)
42
- return "";
43
- const credential = await api("POST", "", {});
44
- return `username=${credential.username}\npassword=${credential.password}\n\n`;
48
+ if (wanted.toLowerCase() !== linked) {
49
+ if (refuseUnlinkedRepository) {
50
+ throw new CliError("github_repository_mismatch", `This checkout is ${wanted}, but the linked project repository is ${metadata.repository.owner}/${metadata.repository.name}.`);
51
+ }
52
+ return null;
53
+ }
54
+ return api("POST", "", {});
45
55
  }
46
56
  function missingRepositoryPathHint(input) {
47
57
  const request = credentialInput(input);
@@ -80,7 +90,7 @@ export async function gitCredential(p, stdin = process.stdin) {
80
90
  if (result)
81
91
  process.stdout.write(result);
82
92
  }
83
- function remoteRepository(url) {
93
+ export function remoteRepository(url) {
84
94
  const scp = /^git@github\.com:([^?#]+)$/i.exec(url);
85
95
  const ssh = /^ssh:\/\/(?:git@)?github\.com\/([^?#]+)$/i.exec(url);
86
96
  const https = /^https:\/\/github\.com\/([^?#]+)$/i.exec(url);
@@ -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/help.js CHANGED
@@ -29,7 +29,7 @@ Mac capacity/signing API (profiles, leases, signer-only references, TestFlight a
29
29
  Standing rules are resolved by account, project, role, and exact-agent scope. GET /agents/me/standing-rules and GET /projects/:p/standing-rules return complete authorized sets and fingerprints; their separate ack endpoints accept only a current fingerprint after complete delivery. Operators and authorized assigners manage rules through the API; limits, compatibility confirmation, audit, and authorization are in packages/skill/references/api.md. Console management and chat promotion are WU #313.
30
30
  Claude Code, Codex, and Antigravity SessionStart hooks retrieve the complete effective rules at fresh start, resume, compaction, and clear into a new thread. They acknowledge only after complete output; an unavailable or over-budget payload points to b9s process without acknowledgment. b9s me shows concise rule text and acknowledgment, b9s process shows the full project rules and acknowledges that fingerprint after display, and b9s resume includes the effective rulesets.
31
31
 
32
- GitHub connection and repository status are available in the console and through b9s-admin github status and b9s-admin project github <project> status|unlink. A repository link enables agent credentials without requiring a ruleset. An agent can inspect its effective repository permission with GET /projects/:p/git-credentials; a project admin can inspect a named agent with GET /projects/:p/git-credentials?agent=<name-or-id>. Each issuance records its permission reason without storing the token. Open or reuse a PR for a unit's pushed branch with b9s wu pr <n>; add --auto-merge to ask GitHub to merge it after required checks pass. The API scopes its installation token to the linked repository, stores the PR URL on the unit, and never prints or persists the token. Verify an exact target ruleset in Account -> GitHub connection before enabling hosted merge; the CLI cannot perform this owner OAuth step. Disconnect an installation with b9s-admin github disconnect <installation-id>. Hosted merge execution and status use b9s wu merge <n> and b9s wu merge status <n>; they call POST/GET /projects/:p/work-units/:n/merge and never inspect local Git state. API role checks use merge.merged_by and operator override; operator_hold is checked, merges serialize in MergeTargetDO, and retries reconcile idempotently. Manual wu done remains disabled for enabled linked targets. Enable with b9s-admin project hosted-merge <project> enable --confirm-bypass-signal only after ruleset verification and the live GitHub bypass-change check; disable with b9s-admin project hosted-merge <project> disable. The console control is WU #196. App setup steps are in packages/skill-admin/references/setup.md.
32
+ GitHub connection and repository status are available in the console and through b9s-admin github status and b9s-admin project github <project> status|unlink. A repository link enables agent credentials without requiring a ruleset. An agent can inspect its effective repository permission with GET /projects/:p/git-credentials; a project admin can inspect a named agent with GET /projects/:p/git-credentials?agent=<name-or-id>. Each issuance records its permission reason without storing the token. Open or reuse a PR for a unit's pushed branch with b9s wu pr <n>; add --auto-merge to ask GitHub to merge it after required checks pass. Use b9s gh <args> for the supported read-only gh pr view, gh pr checks, and gh pr status operations from that linked repository. It obtains the same repository-scoped credential, pins GH_HOST and GH_REPO, and sets GH_TOKEN only in the gh child process. Other commands, hosts, and repositories are refused before credential issuance; the token is never printed or stored. The API scopes its installation token to the linked repository, stores the PR URL on the unit, and never prints or persists the token. Verify an exact target ruleset in Account -> GitHub connection before enabling hosted merge; the CLI cannot perform this owner OAuth step. Disconnect an installation with b9s-admin github disconnect <installation-id>. Hosted merge execution and status use b9s wu merge <n> and b9s wu merge status <n>; they call POST/GET /projects/:p/work-units/:n/merge and never inspect local Git state. API role checks use merge.merged_by and operator override; operator_hold is checked, merges serialize in MergeTargetDO, and retries reconcile idempotently. Manual wu done remains disabled for enabled linked targets. Enable with b9s-admin project hosted-merge <project> enable --confirm-bypass-signal only after ruleset verification and the live GitHub bypass-change check; disable with b9s-admin project hosted-merge <project> disable. The console control is WU #196. App setup steps are in packages/skill-admin/references/setup.md.
33
33
 
34
34
  Environment problems: agents report bounded, redacted observations with b9s environment report; reports use scoped project or machine access, account-scoped evidence, and only the agent's own blocked units. Agents can append observations but cannot claim, diagnose, or resolve issues. Operators and agents whose role has own_environment_problems can manage visible issues. Operators use Account → Environment in the console to filter and inspect issues, claim/assign/reassign, record diagnoses, and resolve with a note and verification. Manual diagnoses use source agent; doctor/daemon provenance is for actual check results. Banner links open the same issue detail with impact context. Issue detail links active notices in the same scope and current machine-session faults related to its machine or explicitly linked unit owner. The read-only steward summary lists active linked issues and currently waiting linked units, without publishing notices or creating work. Machine issue views respect linked-project access. Spending impact is unknown and creates no banner until unit-attributed telemetry lands in WU #236; see packages/skill/references/api.md.
35
35
 
@@ -46,6 +46,7 @@ Agent commands
46
46
  b9s identities list saved identities on this machine
47
47
  b9s me who am I, role, permissions, channels, standing rules and acknowledgment; --json includes your machine sessions
48
48
  b9s git-credential get|store|erase linked GitHub helper; Git must send the repo path (credential.https://github.com.useHttpPath true)
49
+ b9s gh <gh arguments> run gh with this project's repository-scoped token from its linked checkout
49
50
  b9s resume compact recovery brief: units, reviews, asks, slices, decisions, outcomes, process, standing rules and notices
50
51
  b9s notice add --project <p> "<text>" [--until <time>] [--command-pattern <regex>]
51
52
  assigner only: add a project notice; matching commands warn but continue
package/dist/index.js CHANGED
@@ -36,6 +36,7 @@ import { agentNotice } from "./commands/notices.js";
36
36
  import { versionLine, warnLegacyAlias } from "./legacy-alias.js";
37
37
  import { validateCommandFlags } from "./command-flags.js";
38
38
  import { gitCredentialMain } from "./commands/git-credential.js";
39
+ import { gh } from "./commands/gh.js";
39
40
  import { templates } from "./commands/templates.js";
40
41
  import { realpathSync } from "node:fs";
41
42
  import { fileURLToPath } from "node:url";
@@ -53,6 +54,7 @@ const COMMANDS = {
53
54
  me: a.me,
54
55
  resume,
55
56
  "git-credential": async (p) => gitCredentialMain(p),
57
+ gh: async (p) => gh(p.rest ?? []),
56
58
  templates,
57
59
  "test-results": testResults,
58
60
  ux,
@@ -129,14 +131,15 @@ const COMMANDS = {
129
131
  // These commands establish identity, own their startup validation, or inspect/change only local
130
132
  // machine state. Their dispatch must run before any notice lookup attempts to load an agent.
131
133
  const NOTICE_PREFLIGHT_EXEMPT_COMMANDS = new Set([
132
- "join", "setup", "login", "logout", "identities", "skill", "hook", "machine", "install", "doctor", "sandbox", "update", "version", "admin", "start", "git-credential", "templates",
134
+ "join", "setup", "login", "logout", "identities", "skill", "hook", "machine", "install", "doctor", "sandbox", "update", "version", "admin", "start", "git-credential", "templates", "gh",
133
135
  ]);
134
136
  let invokedCommand;
135
137
  export async function main(argv) {
136
138
  warnLegacyAlias();
137
139
  applyEnvAliases();
138
140
  const p = parse(argv);
139
- validateCommandFlags(p, HELP, argv);
141
+ if (argv[0] !== "gh")
142
+ validateCommandFlags(p, HELP, argv);
140
143
  const out = makeOut(bool(p.flags, "json"));
141
144
  if (bool(p.flags, "version")) {
142
145
  process.stdout.write(`${versionLine(CLI_VERSION, false)}\n`);
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.160";
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.160",
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": {