benignswarm 0.12.119 → 0.12.120

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/args.js CHANGED
@@ -11,7 +11,7 @@ export const STRING_FLAGS = [
11
11
  "as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task",
12
12
  "state", "blocked-on", "tags", "custom", "vendor", "role", "description", "permissions",
13
13
  "cardinality", "assign-outside-qualifications", "judges", "machine", "idempotency-key", "dir", "confirm", "impact-revision", "type",
14
- "name", "out", "token", "token-file", "job", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to",
14
+ "name", "out", "token", "token-file", "job", "gate-command", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to",
15
15
  "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent",
16
16
  "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval",
17
17
  "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "startup-jitter-seconds", "env", "scope",
@@ -58,7 +58,11 @@ export function parse(argv) {
58
58
  try {
59
59
  const seen = new Set();
60
60
  const negativeBooleans = new Set();
61
- for (const arg of argv) {
61
+ // Flags after a bare `--` belong to another program's command line and are never read as ours.
62
+ const dashes = argv.indexOf("--");
63
+ const own = dashes < 0 ? argv : argv.slice(0, dashes);
64
+ const rest = dashes < 0 ? undefined : argv.slice(dashes + 1);
65
+ for (const arg of own) {
62
66
  if (!arg.startsWith("--"))
63
67
  continue;
64
68
  const rawName = arg.slice(2).split("=", 1)[0];
@@ -81,12 +85,12 @@ export function parse(argv) {
81
85
  throw new CliError("usage", `--${name} was repeated; it may only be given once`);
82
86
  seen.add(name);
83
87
  }
84
- const parseArgv = argv.filter((arg) => {
85
- if (!arg.startsWith("--"))
86
- return true;
87
- const rawName = arg.slice(2).split("=", 1)[0];
88
- return !(rawName.startsWith("no-") && !(rawName in options) && negativeBooleans.has(rawName.slice(3)));
89
- });
88
+ const parseArgv = [...own.filter((arg) => {
89
+ if (!arg.startsWith("--"))
90
+ return true;
91
+ const rawName = arg.slice(2).split("=", 1)[0];
92
+ return !(rawName.startsWith("no-") && !(rawName in options) && negativeBooleans.has(rawName.slice(3)));
93
+ }), ...(dashes < 0 ? [] : argv.slice(dashes))];
90
94
  const { values, positionals } = parseArgs({ args: parseArgv, options, allowPositionals: true, strict: true });
91
95
  for (const name of negativeBooleans)
92
96
  values[name] = false;
@@ -99,6 +103,7 @@ export function parse(argv) {
99
103
  positionals,
100
104
  flags: Object.fromEntries(Object.entries(flags).map(([k, v]) => [k, Array.isArray(v) ? v.join(",") : v])),
101
105
  repeated: repeatValues,
106
+ ...(rest !== undefined ? { rest } : {}),
102
107
  };
103
108
  }
104
109
  catch (e) {
package/dist/client.js CHANGED
@@ -307,6 +307,8 @@ export class Client {
307
307
  h["x-bschat-auto"] = JSON.stringify(this.auto);
308
308
  if (this.machineIdentity)
309
309
  h["x-bschat-machine"] = this.machineIdentity;
310
+ if (this.requestOptions.stagedPoolPreparation)
311
+ h["x-b9s-pool-staged-prepare"] = "1";
310
312
  return h;
311
313
  }
312
314
  async raw(method, path, body, extraHeaders = {}) {
@@ -5,7 +5,7 @@ import { basename, delimiter, join } from "node:path";
5
5
  import { homedir, platform } from "node:os";
6
6
  import { bool } from "../args.js";
7
7
  import { CliError } from "../errors.js";
8
- import { binVersion, ensureCommandLinks, ensureInstall, latestPublished, launchdLoadedIn, launchdPid, launchdSessionNow, lingerEnabled, ownNpm, plistLaunchdDomain, readInstall, restartInstallServices, watcherServices } from "../install.js";
8
+ import { removeCopyCommand, binVersion, ensureCommandLinks, ensureInstall, latestPublished, launchdLoadedIn, launchdPid, launchdSessionNow, lingerEnabled, ownNpm, plistLaunchdDomain, readInstall, restartInstallServices, watcherServices } from "../install.js";
9
9
  import { CLI_VERSION } from "../version.js";
10
10
  import { CODEX_REQUIREMENTS_PATH, codexHooksDuplicateWithManagedPolicy, reconcileCodexHooks, refreshInstalledHooks } from "../harness.js";
11
11
  import { configRoot } from "../config.js";
@@ -191,7 +191,7 @@ export async function doctor(_p, out) {
191
191
  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" });
192
192
  onPath.forEach((b, i) => {
193
193
  const isRec = !!rec && realpathSync(rec.bin) === b.real;
194
- 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` : undefined });
194
+ 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 });
195
195
  });
196
196
  // npx caches: only used by commands that still say npx.
197
197
  const cache = spawnSync(join(process.execPath, "..", "npm"), ["config", "get", "cache"], { encoding: "utf8" }).stdout?.trim();
@@ -0,0 +1,85 @@
1
+ import { spawn } from "node:child_process";
2
+ import { constants } from "node:os";
3
+ import { CliError } from "../errors.js";
4
+ import { forgetLockJob, rememberLockJob } from "../lock-jobs.js";
5
+ /** What a listing shows for the command: one line, at most 200 characters. */
6
+ export function commandLabel(command) {
7
+ const line = command.join(" ").replace(/\s+/g, " ").trim();
8
+ return line.length <= 200 ? line : `${line.slice(0, 197)}...`;
9
+ }
10
+ export async function runUnderLock(o, deps) {
11
+ const now = deps.now ?? Date.now;
12
+ const label = commandLabel(o.command);
13
+ const base = `/projects/${o.project}/locks/${o.lock}`;
14
+ const acquireBody = { unit: o.unit, note: o.note ?? label, shared: o.shared, machine: o.machine, job_token: o.token };
15
+ const release = async () => {
16
+ try {
17
+ await deps.call("POST", `${base}/release`, { shared: o.shared, machine: o.shared ? undefined : o.machine, job_token: o.token });
18
+ }
19
+ catch (error) {
20
+ throw new CliError("lock_release_failed", `job ${o.jobId} could not release ${o.lock} (${error instanceof Error ? error.message : String(error)})`, `Release it: b9s unlock ${o.lock}${o.shared ? " --shared" : ""} --job ${o.jobId}`);
21
+ }
22
+ forgetLockJob(o.jobsFile, o.jobsKey, o.token);
23
+ };
24
+ let r = await deps.call("POST", `${base}/acquire`, acquireBody);
25
+ if (r.job_token !== o.token)
26
+ throw new CliError("lock_protocol_mismatch", "The server did not confirm job ownership; the command was not started. Inspect the lock state: b9s locks");
27
+ rememberLockJob(o.jobsFile, o.jobsKey, { job: o.jobId, token: o.token, at: new Date(now()).toISOString() });
28
+ let said = "";
29
+ while (!r.acquired) {
30
+ const state = r.maintenance ? `not handed out now: ${r.maintenance}` : `held by ${r.lock.holder_name ?? "nobody"}${r.lock.unit ? ` (WU #${r.lock.unit})` : ""}; job ${o.jobId} is #${r.position} in line`;
31
+ if (state !== said) {
32
+ deps.log(`${o.lock}: ${state}. Waiting.`);
33
+ said = state;
34
+ }
35
+ await deps.sleep(o.pollMs ?? 15_000);
36
+ if (deps.interrupted()) {
37
+ await release();
38
+ deps.log(`${o.lock}: interrupted while waiting; left the queue. The command was not run.`);
39
+ return 130;
40
+ }
41
+ r = await deps.call("POST", `${base}/acquire`, acquireBody);
42
+ }
43
+ const startedMs = now();
44
+ let code;
45
+ try {
46
+ await deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label });
47
+ deps.log(`job ${o.jobId} holds ${o.lock}; running: ${label}`);
48
+ code = await deps.run(o.command);
49
+ }
50
+ catch (error) {
51
+ await release();
52
+ throw error;
53
+ }
54
+ await release();
55
+ deps.log(`${o.lock} released after ${Math.round((now() - startedMs) / 1000)} s; the command exited ${code}.`);
56
+ return code;
57
+ }
58
+ /** The process-level pieces: the child with the terminal's streams, and signals passed on to it. */
59
+ export function processDeps(call, log) {
60
+ let interrupted = false;
61
+ let wake;
62
+ let forward;
63
+ const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
64
+ const onSignal = (signal) => { interrupted = true; wake?.(); forward?.(signal); };
65
+ for (const signal of signals)
66
+ process.on(signal, onSignal);
67
+ return {
68
+ call, log,
69
+ interrupted: () => interrupted,
70
+ sleep: (ms) => new Promise((resolve) => {
71
+ if (interrupted)
72
+ return resolve();
73
+ const timer = setTimeout(() => { wake = undefined; resolve(); }, ms);
74
+ wake = () => { clearTimeout(timer); wake = undefined; resolve(); };
75
+ }),
76
+ run: (command) => new Promise((resolve, reject) => {
77
+ const child = spawn(command[0], command.slice(1), { stdio: "inherit" });
78
+ forward = (signal) => { child.kill(signal); };
79
+ child.once("error", (error) => { forward = undefined; reject(new CliError("command_not_started", `could not start ${command[0]}: ${error.message}`)); });
80
+ child.once("exit", (code, signal) => { forward = undefined; resolve(code ?? 128 + (signal ? constants.signals[signal] ?? 0 : 0)); });
81
+ }),
82
+ dispose: () => { for (const signal of signals)
83
+ process.off(signal, onSignal); },
84
+ };
85
+ }
@@ -232,7 +232,9 @@ export async function machineAdmin(action, rest, p, out) {
232
232
  liveReport = live.latest?.report ?? null;
233
233
  }
234
234
  catch { /* A machine without a live sample still uses its last stable report. */ }
235
- const keptHere = keptInPlace(((await c.call("GET", "/pools")).pools ?? [])).filter((k) => k.machines.includes(m.name));
235
+ const pools = ((await c.call("GET", "/pools")).pools ?? []);
236
+ const keptHere = keptInPlace(pools).filter((k) => k.machines.includes(m.name));
237
+ const movingHere = pools.flatMap((pool) => (pool.slots ?? []).filter((slot) => slot.machine === m.name && /^moving to /i.test(slot.placement_reason ?? "")).map((slot) => ` ${slot.slot} (${pool.project}/${pool.name}): ${slot.placement_reason}`));
236
238
  const rep = liveReport ?? m.report ?? {};
237
239
  const pressureText = (pressure) => `some ${pressure?.some_avg10 ?? "unknown"}% / full ${pressure?.full_avg10 ?? "unknown"}% (10s avg)`;
238
240
  const agentPressure = rep.agent_cgroup_pressure;
@@ -283,7 +285,7 @@ export async function machineAdmin(action, rest, p, out) {
283
285
  const providers = rep.claude_code?.providers ?? {};
284
286
  const providerLines = Object.entries(providers).map(([provider, check]) => ` Claude Code ${provider}: ${check.logged_in ? "verified" : `NOT verified (${check.reason ?? "unknown reason"})`}`);
285
287
  const output = liveReport ? { ...r, machine: { ...m, report: rep } } : r;
286
- return out.print([...head, ...machineMacLines(rep.macos), ...machineGitLines(rep.git), ...cacheLines, ...capabilityLines, ...providerLines, rows.length ? table(rows, ["agent", "pool", "desired", "state", "turns_per_hour", "coalesce_s", "thread", "harness", "provider", "sandbox", "image", "model", "dir", "error", "last_turn"]) : " no sessions", ...keptHere.map((k) => ` kept in place (cannot move): ${k.agent} (${k.pool}): ${k.reason}`)].filter((line) => line !== null).join("\n"), output);
288
+ return out.print([...head, ...machineMacLines(rep.macos), ...machineGitLines(rep.git), ...cacheLines, ...capabilityLines, ...providerLines, rows.length ? table(rows, ["agent", "pool", "desired", "state", "turns_per_hour", "coalesce_s", "thread", "harness", "provider", "sandbox", "image", "model", "dir", "error", "last_turn"]) : " no sessions", ...keptHere.map((k) => ` kept in place (cannot move): ${k.agent} (${k.pool}): ${k.reason}`), ...movingHere].filter((line) => line !== null).join("\n"), output);
287
289
  }
288
290
  if (action === "maintenance") {
289
291
  // A window on the machine: no new turns from 15 min before, its agents away until it ends.
@@ -763,14 +765,20 @@ export async function poolAdmin(action, rest, p, out, argv) {
763
765
  ...(pool.adaptive?.paused ? [" scaling paused by operator"] : []),
764
766
  ...(pool.slots ?? []).map((slot) => ` ${slot.slot}: ${slot.suspended ? `SUSPENDED${slot.bench_note ? ` (${slot.bench_note})` : ""}` : slot.drain?.state && slot.drain.state !== "none" ? `DRAIN ${slot.drain.state}${slot.drain.reason ? ` (${slot.drain.reason})` : ""}` : slot.desired ?? "unplaced"}; ${slot.machine ? `on ${slot.machine}` : "NOT PLACED"}${slot.reported_state ? `; reported ${slot.reported_state}` : ""}${slot.stale_machine ? "; machine stale" : ""}${slot.pin ? `; pinned ${slot.pin.machine}${slot.pin.conflict ? ` (conflict: ${slot.pin.conflict})` : ""}` : ""}${slot.quota_pause ? `; quota paused: ${slot.quota_pause}` : ""}${slot.current_work ? `; work ${slot.current_work}` : ""}`),
765
767
  ...(pool.slots ? [] : (pool.status?.placed ?? []).map((x) => ` ${x.agent.padEnd(32)} on ${x.machine}`)),
766
- ...(pool.status?.unplaced ?? []).map((x) => KEPT_IN_PLACE.test(x.reason)
767
- ? ` ${x.agent.padEnd(32)} KEPT IN PLACE (cannot move): ${x.reason}`
768
- : ` ${x.agent.padEnd(32)} NOT PLACED: ${x.reason}`),
768
+ ...(pool.status?.unplaced ?? []).map((x) => /^moving to /i.test(x.reason ?? "")
769
+ ? ` ${x.agent.padEnd(32)} ${x.reason}`
770
+ : KEPT_IN_PLACE.test(x.reason)
771
+ ? ` ${x.agent.padEnd(32)} KEPT IN PLACE (cannot move): ${x.reason}`
772
+ : ` ${x.agent.padEnd(32)} NOT PLACED: ${x.reason}`),
769
773
  ];
770
774
  // WU #470: a slot whose machine no longer fits, with nowhere to go, keeps running; say so loudly after a change.
771
775
  const keptWarning = (pool) => {
772
776
  const kept = (pool.status?.unplaced ?? []).filter((x) => KEPT_IN_PLACE.test(x.reason)).map((x) => x.agent);
773
- return kept.length ? [`Warning: ${kept.length} slot(s) no longer fit their machine and nothing can take them, so they keep running where they are: ${kept.join(", ")}`] : [];
777
+ const protectedMoves = (pool.status?.unplaced ?? []).filter((x) => /^moving to .+ when its units close/.test(x.reason ?? "")).map((x) => `${x.agent}: ${x.reason}`);
778
+ return [
779
+ ...(kept.length ? [`Warning: ${kept.length} slot(s) no longer fit their machine and nothing can take them, so they keep running where they are: ${kept.join(", ")}`] : []),
780
+ ...(protectedMoves.length ? [`Warning: protected slots remain on their current machine: ${protectedMoves.join("; ")}`] : []),
781
+ ];
774
782
  };
775
783
  if (action === "set") {
776
784
  const [project, name] = (rest[0] ?? "").split("/");
@@ -13,13 +13,13 @@ import { CliError } from "../errors.js";
13
13
  import { AGY_APPARMOR_PATH, agyAppArmorProfile, BWRAP_APPARMOR_PATH, bwrapAppArmorProfile, CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, codexAppArmorProfile, codexManagedHooks, isCodexManagedRequirements } from "../harness.js";
14
14
  import { applySparse, sessionCheckoutFacts } from "../git.js";
15
15
  import { drainingUntil, writeMaintenance } from "../maintenance.js";
16
- import { TURN_HARNESSES, claudeFacts, claudeHome, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
16
+ import { TURN_HARNESSES, cachedClaudeLogin, claudeFacts, claudeHome, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
17
17
  import { readState, writeState } from "../state.js";
18
18
  import { installService, launchdFacts, launchdFactsLine, launchdGuidance, launchdSessionNow, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
19
19
  import { CLI_VERSION } from "../version.js";
20
20
  import { probeCapabilities } from "../capabilities.js";
21
21
  import { diskSpaceNotice } from "../notices.js";
22
- import { deepSeekKeyPath, verifyClaudeProvider } from "../providers.js";
22
+ import { cachedClaudeProviderCheck, deepSeekKeyPath, verifyClaudeProvider } from "../providers.js";
23
23
  import { busyTurnPause, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, resumeTurnGuard, verificationUnavailable } from "../turn-guard.js";
24
24
  import { defaultWorkspaceWritableRoots } from "../start-options.js";
25
25
  import { antigravityPath, antigravitySandboxPermissions, antigravityTurnArgs, antigravityTurnEnv, parseAntigravityJson } from "../antigravity.js";
@@ -1074,6 +1074,7 @@ let lastLogRotationAt = 0;
1074
1074
  export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1075
1075
  const client = Client.raw(m.url, m.key, {
1076
1076
  requestTimeoutMs: MACHINE_REQUEST_TIMEOUT_MS,
1077
+ stagedPoolPreparation: true,
1077
1078
  signal: deps?.signal,
1078
1079
  onRequest: (event) => log(event.phase === "start"
1079
1080
  ? `request start ${event.method} ${event.path}`
@@ -1174,7 +1175,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1174
1175
  const phase = probeFor(s.harness, thread, s.agent).phase();
1175
1176
  return "missing" in phase ? null : phase.running;
1176
1177
  });
1177
- out.push({ id: s.id, state: "stopped", ...facts, ...(s.pool_move_pending ? { checkout: sessionCheckoutFacts(dir) } : {}) });
1178
+ out.push({ id: s.id, state: "stopped", ...facts, ...(s.pool_move_pending ? { checkout: sessionCheckoutFacts(dir, { verifyOrigin: true }) } : {}) });
1178
1179
  continue;
1179
1180
  }
1180
1181
  if (!TURN_HARNESSES.includes(s.harness))
@@ -1214,6 +1215,31 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1214
1215
  if (!existsSync(s.dir))
1215
1216
  throw new Error(`checkout ${s.dir} does not exist on this machine`);
1216
1217
  let local = state.sessions[s.id];
1218
+ if (s.desired === "prepared") {
1219
+ if (svc() || local?.container_name || state.starting_sessions?.[s.id] || state.unsettled_turns?.[s.dir])
1220
+ throw new Error("target already has a watcher or recorded container; preparation will not start another");
1221
+ if (s.harness === "dsh")
1222
+ throw new Error(`DeepSeek Harness login cannot be verified on ${m.name}`);
1223
+ if (local) {
1224
+ const conflict = existingSessionDirectoryConflict(s.id, s.dir, local.thread, s.agent);
1225
+ if (conflict) {
1226
+ out.push(conflict);
1227
+ continue;
1228
+ }
1229
+ }
1230
+ await ensureCredentials(client, m, s, local, log);
1231
+ (deps?.prepareTargetCheckout ?? preparePoolTargetCheckout)(s.dir);
1232
+ const observed = deps?.prepareTargetFacts ? deps.prepareTargetFacts(s) : preparedTargetFacts(s);
1233
+ const reported = s.harness === "claude-code"
1234
+ ? observed.claude_code?.providers?.[s.provider ?? "anthropic"]
1235
+ : observed[s.harness];
1236
+ if (!reported || (reported.logged_in !== true && reported.secret_configured !== true))
1237
+ throw new Error(`${s.harness} login is not verified on this machine`);
1238
+ if (s.sandbox !== "danger-full-access" && reported.sandbox?.ok !== true)
1239
+ throw new Error(`${s.harness} sandbox is not verified on this machine`);
1240
+ out.push({ id: s.id, state: "ready", dir: s.dir, watcher: "inactive", detail: "checkout, harness login and sandbox verified; no watcher started" });
1241
+ continue;
1242
+ }
1217
1243
  const pendingStart = state.starting_sessions?.[s.id];
1218
1244
  preflightDone = true;
1219
1245
  let neverLaunched = false;
@@ -1550,7 +1576,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1550
1576
  watcher: watcherState,
1551
1577
  ...((t) => ({ last_turn: t.line, ...(t.unknown_reason ? { last_turn_unknown: t.unknown_reason } : {}) }))(lastTurn(s.agent)),
1552
1578
  turn_judgment: s.turn_judgment ?? null,
1553
- ...(s.pool_move_pending ? { checkout: sessionCheckoutFacts(s.dir) } : {}),
1579
+ ...(s.pool_move_pending ? { checkout: sessionCheckoutFacts(s.dir, { verifyOrigin: true }) } : {}),
1554
1580
  ...turnFacts(s.agent, s.harness, th, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR),
1555
1581
  ...sessionImageFacts,
1556
1582
  });
@@ -1816,6 +1842,28 @@ export async function answerWorktreeProcessQueries(client, desired, queries, log
1816
1842
  }
1817
1843
  }
1818
1844
  const git = (args, cwd) => spawnSync("git", args, { cwd, encoding: "utf8", timeout: 600_000 });
1845
+ /** Prepare only a clean, fully pushed checkout; never reset or discard local work. */
1846
+ export function preparePoolTargetCheckout(dir) {
1847
+ const facts = sessionCheckoutFacts(dir, { verifyOrigin: true });
1848
+ if (facts.clean !== true || facts.pushed !== true || facts.error)
1849
+ throw new Error(`target checkout is not verified clean and pushed${facts.error ? `: ${facts.error}` : ""}`);
1850
+ const remote = spawnSync("git", ["ls-remote", "--symref", "origin", "HEAD"], {
1851
+ cwd: dir, encoding: "utf8", timeout: 30_000, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
1852
+ });
1853
+ if (remote.status !== 0)
1854
+ throw new Error("cannot query origin default branch");
1855
+ const symbolic = remote.status === 0 ? /^ref:\s+refs\/heads\/(\S+)\s+HEAD$/m.exec(remote.stdout) : null;
1856
+ const advertised = remote.status === 0 ? /^([0-9a-f]{40,64})\s+HEAD$/m.exec(remote.stdout)?.[1] : null;
1857
+ const target = symbolic ? `refs/remotes/origin/${symbolic[1]}` : "";
1858
+ if (!target || !advertised || git(["check-ref-format", target], dir).status !== 0)
1859
+ throw new Error("origin default branch is unknown");
1860
+ const fetched = git(["rev-parse", "--verify", `${target}^{commit}`], dir);
1861
+ if (fetched.status !== 0 || fetched.stdout.trim() !== advertised)
1862
+ throw new Error("origin default branch changed during preparation; retry the move");
1863
+ const checkedOut = git(["checkout", "--detach", target], dir);
1864
+ if (checkedOut.status !== 0)
1865
+ throw new Error(`target checkout failed: ${(checkedOut.stderr ?? "").trim().slice(-300)}`);
1866
+ }
1819
1867
  /**
1820
1868
  * The checkout of a pool session: the project's repository cloned once per machine under
1821
1869
  * ~/bschat/<project>/main (in the background, since ester's is 20 GB; "preparing" until it is done),
@@ -2446,6 +2494,33 @@ function claudeReport(path = process.env.PATH ?? "", providersInUse = ["anthropi
2446
2494
  }
2447
2495
  return { ...f, sandbox: claudeSandboxCache.result, providers };
2448
2496
  }
2497
+ /** Check a prepared target without starting a model turn or a watcher. */
2498
+ export function preparedTargetFacts(session) {
2499
+ const path = process.env.PATH ?? "";
2500
+ const env = { ...process.env, PATH: path };
2501
+ if (session.harness === "codex") {
2502
+ const login = spawnSync("codex", ["login", "status"], { cwd: session.dir, encoding: "utf8", timeout: 30_000, env });
2503
+ const loggedIn = login.status === 0 && /(?:^|\n)\s*logged in\b/i.test(`${login.stdout ?? ""}\n${login.stderr ?? ""}`);
2504
+ const sandbox = session.sandbox === "danger-full-access" ? null : spawnSync("codex", ["sandbox", "--", "true"], { cwd: session.dir, encoding: "utf8", timeout: 60_000, env });
2505
+ return { codex: { logged_in: loggedIn, sandbox: sandbox ? { ok: sandbox.status === 0 } : null } };
2506
+ }
2507
+ if (session.harness === "claude-code") {
2508
+ const f = claudeFacts(() => cachedClaudeLogin(env), path);
2509
+ const provider = session.provider ?? "anthropic";
2510
+ const login = provider === "anthropic" ? { logged_in: f?.logged_in === true && f.verified.ok === true } : !f ? { logged_in: false, reason: "Claude Code is unavailable" } : cachedClaudeProviderCheck(provider) ?? { logged_in: false, reason: "no fresh provider verification" };
2511
+ const sandbox = session.sandbox === "danger-full-access" ? null : claudeSandbox(path, session.dir);
2512
+ return { claude_code: { providers: { [provider]: { ...login, sandbox } } } };
2513
+ }
2514
+ if (session.harness === "antigravity") {
2515
+ const login = antigravityLoginFacts(path);
2516
+ // The normal machine probe may run a model turn. Preparation must not run
2517
+ // one, so only a recent already-recorded sandbox proof is admissible.
2518
+ const bin = readInstall()?.bin ?? null;
2519
+ const cached = agySandboxCache && agySandboxCache.path === path && agySandboxCache.b9sBin === bin && Date.now() - agySandboxCache.at < AGY_SANDBOX_PROBE_MS ? agySandboxCache.result : null;
2520
+ return { antigravity: { ...login, sandbox: cached } };
2521
+ }
2522
+ return {};
2523
+ }
2449
2524
  const modelCheckCacheFile = () => join(configRoot(), "state", "model-checks.json");
2450
2525
  function readModelCheckCache() {
2451
2526
  try {
@@ -2673,6 +2748,7 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
2673
2748
  ...(containerImds ? { container_imds_isolation: containerImds } : {}),
2674
2749
  ...(container.runtime !== null || process.env.B9S_CLOUD_MACHINE === "1" ? { container_runtime: container } : {}),
2675
2750
  codex: codexFactsValue,
2751
+ pool_staged_prepare: true,
2676
2752
  "claude-code": claude,
2677
2753
  claude_code: claude,
2678
2754
  dsh: dshWithIdentity,
@@ -97,6 +97,9 @@ export function definitionPatch(p, cur) {
97
97
  const integ = str(p.flags, "integrator-role");
98
98
  if (integ !== undefined)
99
99
  merge.integrator_role = integ === "none" ? null : integ;
100
+ const gate = str(p.flags, "gate-command");
101
+ if (gate !== undefined)
102
+ merge.gate_command = gate === "none" || gate === "" ? null : gate;
100
103
  for (const [flag, key] of [["require-rebased", "require_rebased"], ["require-merge-commit", "require_merge_commit"], ["require-pushed", "require_pushed"]]) {
101
104
  const v = yesNo(str(p.flags, flag), flag);
102
105
  if (v !== undefined)
@@ -126,7 +129,7 @@ function describeProcess(r) {
126
129
  `Process v${r.process.version}${r.process.version === 0 ? " (defaults; nothing published yet)" : ""}`,
127
130
  ` timing: review SLA ${d.review_sla_minutes} min, takeover ${d.escalate_after_minutes} min, ${d.max_open_per_agent} open / ${d.max_in_progress_per_agent} in progress per agent`,
128
131
  ` requires: scope ${d.require_scope ? "yes" : "no"}, evidence to submit ${d.require_evidence_to_submit ? "yes" : "no"}; default approver ${d.default_approver_role ?? "none"}; assigners ${d.assigners.join(", ") || "none"}`,
129
- ` merging: into ${m.target_branch} by ${m.merged_by === "integrator" ? `a ${m.integrator_role}` : `the ${m.merged_by}`}; merge commit ${m.require_merge_commit ? "yes" : "no"}, rebased ${m.require_rebased ? "yes" : "no"}, pushed ${m.require_pushed ? "yes" : "no"}`,
132
+ ` merging: into ${m.target_branch} by ${m.merged_by === "integrator" ? `a ${m.integrator_role}` : `the ${m.merged_by}`}; merge commit ${m.require_merge_commit ? "yes" : "no"}, rebased ${m.require_rebased ? "yes" : "no"}, pushed ${m.require_pushed ? "yes" : "no"}; gate ${m.gate_command ?? "none"}`,
130
133
  ` capabilities: ${(d.capabilities ?? []).map((c) => `${c.name} (${c.scope}${c.min_version ? ` >= ${c.min_version}` : ""})`).join(", ") || "none"}`,
131
134
  ` heavy jobs: ${Object.entries(d.heavy_jobs ?? {}).map(([name, job]) => `${name} (${job.memory_gib} GiB; ${job.purpose}; workflows ${job.workflows.join(", ")})`).join("; ") || "none"}`,
132
135
  ` steward: ${d.steward.enabled ? "on" : "off"}, quiet ${d.steward.quiet_minutes} min, summary every ${d.steward.summary_minutes} min, ask the operator after ${d.steward.churn_rounds ? `${d.steward.churn_rounds} rounds on one goal` : "(never)"}`,
@@ -12,7 +12,7 @@ import { basename, dirname, join } from "node:path";
12
12
  import { bool, str } from "../args.js";
13
13
  import { configRoot, loadAgent, resolveAgentName } from "../config.js";
14
14
  import { Client } from "../client.js";
15
- import { heartbeatIfActive, resolveActivitySource } from "../heartbeat.js";
15
+ import { heartbeatIfActive, reportWatcherHeartbeat, resolveActivitySource } from "../heartbeat.js";
16
16
  import { scanProject, unitWorktrees } from "./worktrees.js";
17
17
  import { formatBytes, freeSpaceProbe, pruneReport, removePrunable } from "../git.js";
18
18
  import { CliError } from "../errors.js";
@@ -176,6 +176,7 @@ export async function watch(p, out, dependencies = {}) {
176
176
  // The watcher sits in a checkout on the machine, so it keeps the worktree registry current: a
177
177
  // scan on start and then hourly reports worktrees nobody is touching, which agent calls never would.
178
178
  const scanCreds = loadAgent(name);
179
+ const watcherClient = once ? null : Client.forAgent(scanCreds, undefined, { presence: false });
179
180
  let lastScan = 0;
180
181
  let lastCapabilities = 0;
181
182
  // A watcher holding a pending wake-up makes no server call, so a revoked key (the agent moved to
@@ -186,6 +187,14 @@ export async function watch(p, out, dependencies = {}) {
186
187
  let probe = turn ? turn.harness === "codex" ? followCurrentCodexProbe(name, turn.session) : probeFor(turn.harness, turn.session, name) : null;
187
188
  let resumeBriefDelivered = false;
188
189
  while (!stopping) {
190
+ if (watcherClient) {
191
+ try {
192
+ await (dependencies.reportWatcher ?? reportWatcherHeartbeat)(watcherClient, interval, turnMode ? "turn" : "queue");
193
+ }
194
+ catch (e) {
195
+ log(`watcher heartbeat failed: ${e.message}`);
196
+ }
197
+ }
189
198
  if (turn?.harness === "codex") {
190
199
  const current = readState(name);
191
200
  const clear = current.pending_context_clear;
@@ -1,3 +1,4 @@
1
+ import { processDeps, runUnderLock } from "./lock-run.js";
1
2
  import { forgetLockJob, lockJobKey, lockJobsFile, rememberLockJob, savedLockJobs, tokenForRelease } from "../lock-jobs.js";
2
3
  import { spawnSync } from "node:child_process";
3
4
  import { createHash, randomBytes, randomUUID } from "node:crypto";
@@ -1282,6 +1283,7 @@ export async function processCmd(p, out) {
1282
1283
  `Review SLA ${d.review_sla_minutes} min; after ${d.escalate_after_minutes} min another qualified reviewer takes over. Max ${d.max_open_per_agent} open units per agent. Announcements in #${d.channel}.`,
1283
1284
  ...(r.wake_path_warnings?.length ? [`No verified wake path:`, ...r.wake_path_warnings.map((warning) => ` ${warning.consequence}`)] : []),
1284
1285
  `Merging: ${d.merge.merged_by === "owner" ? "the owner" : d.merge.merged_by === "approver" ? "an approver" : `a ${d.merge.integrator_role}`} merges approved work into ${d.merge.target_branch}${d.merge.require_rebased ? "; the branch must contain " + d.merge.target_branch + " before review" : ""}${d.merge.require_merge_commit ? "; done carries the merge commit (b9s wu done <n> --merged <sha>)" : ""}.`,
1286
+ d.merge.gate_command ? `Merge gate (run exactly this, with the unit's number and head filled in): ${d.merge.gate_command}` : null,
1285
1287
  r.process.agreements ? `\nWorking agreements:\n${r.process.agreements}` : null,
1286
1288
  r.process.charter ? `\nCharter (how this project weighs its trade-offs; judge reviews and questions by it):\n${r.process.charter}` : null,
1287
1289
  `\n${formatStandingRuleSet(r.standing_rules, project)}`,
@@ -1582,6 +1584,13 @@ export async function record(p, out) {
1582
1584
  out.print(rows.length ? table(rows, ["agent", "tag", "done", "1st-round", "changes", "2nd-read send-backs", "replays", "reviewed", "overturned", "escalated"]) : "(no reviewed units yet)", r);
1583
1585
  }
1584
1586
  /** b9s lock <name> [--unit n] [--note ..] | b9s unlock <name> | b9s locks */
1587
+ /** What the holding job is doing, for a listing: the command it reported and for how long, or that it reported none. */
1588
+ export function lockActivity(l, nowMs) {
1589
+ const minutes = (since) => Math.max(0, Math.round((nowMs - Date.parse(since)) / 60_000));
1590
+ if (l.running)
1591
+ return ` · running "${l.running.command}" for ${minutes(l.running.started_at)} min`;
1592
+ return l.acquired_at ? ` · held ${minutes(l.acquired_at)} min, no command reported` : "";
1593
+ }
1585
1594
  export async function lock(p, out) {
1586
1595
  const name = resolveAgentName(str(p.flags, "as"));
1587
1596
  const creds = loadAgent(name);
@@ -1593,7 +1602,32 @@ export async function lock(p, out) {
1593
1602
  const lockName = p.positionals[1];
1594
1603
  if (cmd === "locks") {
1595
1604
  const r = await client.call("GET", `/projects/${project}/locks`);
1596
- out.print(r.locks.length ? r.locks.map((l) => `${l.name}${l.machine ? ` on ${l.machine}` : " (shared)"}: ${l.holder_name ? `held by ${l.holder_name}${l.unit ? ` (WU #${l.unit})` : ""}${l.holder_legacy === 1 ? " (legacy, no token)" : l.holder_job_id ? ` job ${l.holder_job_id}` : ""}${l.note ? `: ${l.note}` : ""} since ${l.acquired_at.slice(11, 16)} UTC` : "free"}${l.waiting.length ? ` · waiting: ${l.waiting.map((w) => `${w.name}${w.unit ? ` (#${w.unit})` : ""}${w.legacy === 1 ? " (legacy, no token)" : w.job_id ? ` job ${w.job_id}` : ""}${w.note ? `: ${w.note}` : ""}`).join(", ")}` : ""}`).join("\n") : "No locks in this project. Take one with: b9s lock <name> [--unit n]", r);
1605
+ out.print(r.locks.length ? r.locks.map((l) => `${l.name}${l.machine ? ` on ${l.machine}` : " (shared)"}: ${l.holder_name ? `held by ${l.holder_name}${l.unit ? ` (WU #${l.unit})` : ""}${l.holder_legacy === 1 ? " (legacy, no token)" : l.holder_job_id ? ` job ${l.holder_job_id}` : ""}${l.note ? `: ${l.note}` : ""} since ${l.acquired_at.slice(11, 16)} UTC${lockActivity(l, Date.now())}` : "free"}${l.waiting.length ? ` · waiting: ${l.waiting.map((w) => `${w.name}${w.unit ? ` (#${w.unit})` : ""}${w.legacy === 1 ? " (legacy, no token)" : w.job_id ? ` job ${w.job_id}` : ""}${w.note ? `: ${w.note}` : ""}`).join(", ")}` : ""}`).join("\n") : "No locks in this project. Take one with: b9s lock <name> [--unit n]", r);
1606
+ return;
1607
+ }
1608
+ if (cmd === "lock" && lockName === "run" && (p.rest !== undefined || p.positionals.length > 2)) {
1609
+ const runName = p.positionals[2];
1610
+ if (!runName || !p.rest?.length)
1611
+ throw new CliError("usage", "b9s lock run <name> [--unit n] [--note ..] [--shared] -- <command> [args..]");
1612
+ if (str(p.flags, "machine") !== undefined)
1613
+ throw new CliError("usage", "lock run is scoped to the host running the CLI; --machine is only for unlock");
1614
+ if (Object.hasOwn({ acquire: 1, list: 1, release: 1, show: 1, status: 1 }, runName))
1615
+ throw new CliError("usage", `lock name ${runName} is reserved`);
1616
+ const runUnit = str(p.flags, "unit");
1617
+ const shared = bool(p.flags, "shared");
1618
+ const runToken = str(p.flags, "token") ?? `b9sjob_${randomBytes(24).toString("hex")}`;
1619
+ const machine = defaultMachine();
1620
+ const deps = processDeps((method, path, body) => client.call(method, path, body), (line) => process.stderr.write(`[b9s] ${line}\n`));
1621
+ try {
1622
+ process.exitCode = await runUnderLock({
1623
+ project, lock: runName, shared, machine, unit: runUnit ? Number(runUnit) : null, note: str(p.flags, "note"), command: p.rest, token: runToken,
1624
+ jobId: createHash("sha256").update(runToken).digest("hex").slice(0, 12),
1625
+ jobsFile: lockJobsFile(creds.project ? `${creds.project}.${creds.agent}` : `account.${creds.agent}`), jobsKey: lockJobKey(project, runName, shared ? null : machine),
1626
+ }, deps);
1627
+ }
1628
+ finally {
1629
+ deps.dispose();
1630
+ }
1597
1631
  return;
1598
1632
  }
1599
1633
  if (!lockName)
package/dist/git.js CHANGED
@@ -16,24 +16,35 @@ function status(cwd, timeoutMs) {
16
16
  return r.stdout.trim();
17
17
  }
18
18
  /** Local, bounded proof that a session checkout is clean and every commit is reachable from a remote. */
19
- export function sessionCheckoutFacts(cwd) {
19
+ export function sessionCheckoutFacts(cwd, options = {}) {
20
+ const branchResult = spawnSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
21
+ cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 1024 * 1024, timeout: 5_000,
22
+ });
20
23
  const statusResult = spawnSync("git", ["status", "--porcelain"], {
21
24
  cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 16 * 1024 * 1024, timeout: 5_000,
22
25
  });
23
- const remoteResult = spawnSync("git", ["rev-list", "--count", "HEAD", "--not", "--remotes"], {
26
+ const fetched = options.verifyOrigin ? spawnSync("git", ["fetch", "--prune", "origin"], {
27
+ cwd, encoding: "utf8", stdio: ["ignore", "ignore", "ignore"], timeout: 30_000,
28
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
29
+ }) : null;
30
+ const remoteResult = spawnSync("git", ["rev-list", "--count", "HEAD", "--not", options.verifyOrigin ? "--remotes=origin" : "--remotes"], {
24
31
  cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 1024 * 1024, timeout: 5_000,
25
32
  });
26
33
  const statusError = statusResult.error;
27
34
  const remoteError = remoteResult.error;
28
35
  const statusOk = statusResult.status === 0;
29
36
  const countText = remoteResult.stdout.trim();
30
- const count = remoteResult.status === 0 && /^\d+$/.test(countText) ? Number(countText) : null;
37
+ const count = (!fetched || fetched.status === 0) && remoteResult.status === 0 && /^\d+$/.test(countText) ? Number(countText) : null;
31
38
  const entries = statusOk ? statusResult.stdout.split("\n").filter(Boolean) : [];
32
39
  const untracked = statusOk ? entries.some((line) => line.startsWith("??")) : null;
33
40
  const uncommitted = statusOk ? entries.some((line) => !line.startsWith("??")) : null;
34
41
  const clean = statusOk ? entries.length === 0 : null;
35
- const errors = [statusError?.code ?? (statusOk ? null : `git status exited ${statusResult.status}`), remoteError?.code ?? (count === null ? `git remote reachability exited ${remoteResult.status}` : null)].filter(Boolean);
42
+ const branch = branchResult.status === 0 && branchResult.stdout.trim() ? branchResult.stdout.trim() : null;
43
+ const branchError = branchResult.error;
44
+ const fetchError = fetched?.error;
45
+ const errors = [statusError?.code ?? (statusOk ? null : `git status exited ${statusResult.status}`), fetched && fetched.status !== 0 ? `git fetch origin failed: ${fetchError?.code ?? `exit ${fetched.status}`}` : null, remoteError?.code ?? (remoteResult.status !== 0 || !/^\d+$/.test(countText) ? `git remote reachability exited ${remoteResult.status}` : null), branchError?.code ?? (branch === null ? `git branch inspection exited ${branchResult.status}` : null)].filter(Boolean);
36
46
  return {
47
+ branch,
37
48
  clean,
38
49
  uncommitted,
39
50
  untracked,
package/dist/harnesses.js CHANGED
@@ -637,6 +637,15 @@ export function verifyClaudeLogin(env = process.env) {
637
637
  }
638
638
  export const claudeIsAuthError = (e) => /401|403|authenticat|not logged in|\/login|oauth token|invalid api key/i.test(e);
639
639
  let loginCache = null;
640
+ /** Inspect only a fresh existing login verification; never launch a model turn. */
641
+ export function cachedClaudeLogin(env = process.env) {
642
+ const cred = join(claudeHome(), ".credentials.json");
643
+ const key = existsSync(cred) ? String(statSync(cred).mtimeMs) : "keychain";
644
+ const cacheKey = `${key}\0${env.PATH ?? ""}`;
645
+ if (loginCache && loginCache.key === cacheKey && Date.now() >= loginCache.at && Date.now() - loginCache.at < 6 * 60 * 60_000)
646
+ return loginCache.result;
647
+ return { ok: null, error: "no fresh login verification" };
648
+ }
640
649
  function verifyClaudeLoginCached(env = process.env) {
641
650
  const cred = join(claudeHome(), ".credentials.json");
642
651
  const key = existsSync(cred) ? String(statSync(cred).mtimeMs) : "keychain";
@@ -651,15 +660,21 @@ function verifyClaudeLoginCached(env = process.env) {
651
660
  * bubblewrap and socat, and bubblewrap needs unprivileged user namespaces (Ubuntu 24.04 restricts
652
661
  * them with AppArmor), so this runs bubblewrap the way a sandboxed command would.
653
662
  */
654
- export function claudeSandbox(path = process.env.PATH ?? "") {
655
- if (process.platform === "darwin")
656
- return existsSync("/usr/bin/sandbox-exec") ? { ok: true, error: null } : { ok: false, error: "sandbox-exec is missing" };
663
+ export function claudeSandbox(path = process.env.PATH ?? "", cwd) {
664
+ if (process.platform === "darwin") {
665
+ if (!existsSync("/usr/bin/sandbox-exec"))
666
+ return { ok: false, error: "sandbox-exec is missing" };
667
+ if (!cwd)
668
+ return { ok: true, error: null };
669
+ const probe = spawnSync("/usr/bin/sandbox-exec", ["-p", "(version 1) (allow default)", "/usr/bin/true"], { cwd, encoding: "utf8", timeout: 30_000 });
670
+ return probe.status === 0 ? { ok: true, error: null } : { ok: false, error: "sandbox-exec could not start in the checkout" };
671
+ }
657
672
  if (process.platform !== "linux")
658
673
  return { ok: false, error: `no Claude Code sandbox on ${process.platform}` };
659
674
  const env = { ...process.env, PATH: path };
660
675
  const missing = ["bwrap", "socat"].filter((b) => spawnSync("/bin/sh", ["-c", `command -v ${b}`], { env }).status !== 0);
661
676
  if (missing.length)
662
677
  return { ok: false, error: `${missing.join(" and ")} not installed (sudo apt-get install bubblewrap socat)` };
663
- const r = spawnSync("bwrap", ["--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--unshare-all", "--die-with-parent", "true"], { encoding: "utf8", timeout: 30_000, env });
678
+ const r = spawnSync("bwrap", ["--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--unshare-all", "--die-with-parent", "true"], { cwd, encoding: "utf8", timeout: 30_000, env });
664
679
  return r.status === 0 ? { ok: true, error: null } : { ok: false, error: `bubblewrap cannot start: ${`${r.stderr ?? ""}`.trim().split("\n")[0].slice(0, 250) || `exit ${r.status}`}` };
665
680
  }
package/dist/heartbeat.js CHANGED
@@ -83,6 +83,10 @@ export async function heartbeatIfActive(client, src, prev, windowSeconds, log) {
83
83
  }
84
84
  return cur;
85
85
  }
86
+ /** A persistent watcher proves its own wake path independently of harness file activity. */
87
+ export async function reportWatcherHeartbeat(client, intervalSeconds, mode) {
88
+ await client.call("POST", "/agents/me/watcher/heartbeat", { interval_seconds: intervalSeconds, mode });
89
+ }
86
90
  /**
87
91
  * The hook variant: the hook running is itself the evidence, so report now, throttled by the
88
92
  * caller. `goal` undefined means "unknown, keep what you have"; null means "no goal is set".
package/dist/help.js CHANGED
@@ -126,6 +126,7 @@ Agent commands
126
126
  acquisition queues through a machine maintenance drain/window and resumes after it
127
127
  machine identity is this host's hostname plus its registered label, shared by all agents here
128
128
  save the returned job token; reuse --token to check/retry the same job
129
+ b9s lock run <name> [--unit n] [--note ..] [--shared] -- <command> wait for <name>, run the command, release when it ends (pass, fail or interrupt); exits with the command's code
129
130
  b9s unlock <name> [--job <id> | --token <job-token>] [--machine <label>|--shared] | b9s locks on the machine that took it the job's token is kept for you
130
131
  b9s unlock <name> --remove-empty [--machine <label>|--shared]
131
132
  new agent jobs release by token; legacy jobs retain identity release; assigners/operators may release without a token
@@ -369,7 +370,7 @@ the returned object and warning, then exits 3. Inspect the object and do not ret
369
370
  legacy project-first order also accepted; for operation-first with a project named add, edit, or remove:
370
371
  b9s-admin process tag <op> <tag> --project <project>
371
372
  b9s-admin process timing <project> [--sla m] [--takeover m] [--max-open n] [--max-in-progress n] [--require-scope yes|no] [--require-evidence yes|no] [--require-cited-changes yes|no] [--default-approver r|none]
372
- b9s-admin process merge <project> [--target b] [--merged-by owner|approver|integrator] [--integrator-role r] [--require-rebased|--require-merge-commit|--require-pushed yes|no]
373
+ b9s-admin process merge <project> [--target b] [--merged-by owner|approver|integrator] [--integrator-role r] [--require-rebased|--require-merge-commit|--require-pushed yes|no] [--gate-command "<one command>"|none]
373
374
  b9s-admin process assigners <project> role1,role2 | agreements <project> --file agreements.md
374
375
  b9s-admin process charter <project> --file charter.md how the project weighs trade-offs; sent with every expert question
375
376
  b9s-admin process steward <project> on|off [--quiet m] [--summary m] [--churn n] (--churn: ask the operator when a goal is sent back or handed over n times; 0 off)
package/dist/install.js CHANGED
@@ -778,6 +778,24 @@ export function lingerEnabled() {
778
778
  const r = spawnSync("loginctl", ["show-user", userInfo().username, "-p", "Linger", "--value"], { encoding: "utf8" });
779
779
  return r.status === 0 ? r.stdout.trim() === "yes" : null;
780
780
  }
781
+ /**
782
+ * The command that removes one extra copy of the CLI, from where that copy really lives; null
783
+ * when the layout is not one we know how to remove (then nothing is suggested, never a guess).
784
+ * A global npm install is removed with the npm of the same prefix, which is the only npm that
785
+ * owns it; an npx cache entry is one folder.
786
+ */
787
+ export function removeCopyCommand(real, exists = existsSync) {
788
+ const quote = (path) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(path) ? path : `'${path.replaceAll("'", "'\\''")}'`);
789
+ const npx = /^(.*\/_npx\/[^/]+)\/node_modules\/benignswarm\//.exec(real);
790
+ if (npx)
791
+ return `rm -rf ${quote(npx[1])}`;
792
+ const global = /^(.*)\/lib\/node_modules\/benignswarm\//.exec(real);
793
+ if (global) {
794
+ const npm = join(global[1], "bin", "npm");
795
+ return exists(npm) ? `${quote(npm)} uninstall -g benignswarm` : null;
796
+ }
797
+ return null;
798
+ }
781
799
  /** Commands that legitimately run from a copy other than the recorded install (npx join, old npx hooks). */
782
800
  const GUARD_EXEMPT = new Set(["join", "setup", "install", "doctor", "hook", "watch"]);
783
801
  /**
@@ -790,7 +808,8 @@ export function foreignCopyNotice(cmd, self, selfVersion, rec, recorded, lastAt,
790
808
  return null;
791
809
  if (lastAt !== null && now - lastAt < 24 * 3600_000)
792
810
  return null;
793
- return `[b9s] this is ${self} (${selfVersion}), not this machine's install ${rec.bin} (${rec.version}). Run that one (put ${dirname(rec.bin)} first on PATH, or remove this copy), or see: b9s doctor`;
811
+ const removal = removeCopyCommand(self);
812
+ return `[b9s] this is ${self} (${selfVersion}), not this machine's install ${rec.bin} (${rec.version}). Run that one (put ${dirname(rec.bin)} first on PATH, or remove this copy${removal ? `: ${removal}` : ""}), or see: b9s doctor`;
794
813
  }
795
814
  /**
796
815
  * Warns once a day per copy when a b9s other than the recorded install runs: another
package/dist/providers.js CHANGED
@@ -54,6 +54,11 @@ function keyFingerprint(provider, root) {
54
54
  return error.code === "ENOENT" ? "missing" : `unreadable:${error.code ?? "error"}`;
55
55
  }
56
56
  }
57
+ /** Return an existing, still-valid verification without starting a provider turn. */
58
+ export function cachedClaudeProviderCheck(provider, root = deepSeekKeyRoot(), nowMs = Date.now()) {
59
+ const cached = checks.get(`${root}\0${provider}`);
60
+ return cached && cached.fingerprint === keyFingerprint(provider, root) && nowMs >= cached.at && nowMs - cached.at < MAX_AGE_MS ? cached.result : null;
61
+ }
57
62
  /** Make one tiny provider call when first used, after its key changes, or every six hours. */
58
63
  export function verifyClaudeProvider(provider, root = deepSeekKeyRoot(), nowMs = Date.now(), run = spawnSync) {
59
64
  const fingerprint = keyFingerprint(provider, root);
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.119";
1
+ export const CLI_VERSION = "0.12.120";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.119",
3
+ "version": "0.12.120",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {