benignswarm 0.12.119 → 0.12.121

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 = {}) {
@@ -3,7 +3,12 @@ import { printWrittenReceiptMismatch } from "./output.js";
3
3
  /** Print committed write results when their receipt is invalid; ordinary API refusals stay errors. */
4
4
  export async function runCommandSafely(run, out) {
5
5
  try {
6
- return (await run()) ?? 0;
6
+ const code = await run();
7
+ if (code !== undefined)
8
+ return code;
9
+ // A command that reports failure by setting process.exitCode (doctor, status, lock run) keeps it:
10
+ // the caller assigns our return value to process.exitCode, and a 0 here would erase the failure.
11
+ return typeof process.exitCode === "number" ? process.exitCode : 0;
7
12
  }
8
13
  catch (error) {
9
14
  if (error instanceof WrittenReceiptMismatchError) {
@@ -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";
@@ -793,14 +793,14 @@ export function processStartStamp(pid) {
793
793
  * since it may be another process, and not treated as gone, since it may be the child about to
794
794
  * begin a first turn. A record from before the start time was kept is judged by pid alone.
795
795
  */
796
- function startChildState(pending) {
796
+ function startChildState(pending, readStartStamp = processStartStamp) {
797
797
  if (!pidAlive(pending.pid))
798
798
  return "gone";
799
799
  if (pending.pid_started === undefined)
800
800
  return "alive";
801
801
  if (pending.pid_started === null)
802
802
  return "unknown";
803
- const stamp = processStartStamp(pending.pid);
803
+ const stamp = readStartStamp(pending.pid);
804
804
  if (stamp === null)
805
805
  return pidAlive(pending.pid) ? "unknown" : "gone";
806
806
  return stamp === pending.pid_started ? "alive" : "gone";
@@ -818,7 +818,7 @@ function cleanupMachineStart(pending) {
818
818
  for (const file of [pending.progress_file, pending.result_file, ...(pending.child_file ? [pending.child_file] : []), ...(pending.secret_files ?? [])])
819
819
  rmSync(file, { force: true });
820
820
  }
821
- function adoptStartChild(pending) {
821
+ function adoptStartChild(pending, readStartStamp = processStartStamp) {
822
822
  if (pending.pid !== 0)
823
823
  return;
824
824
  let childPid = 0;
@@ -828,7 +828,7 @@ function adoptStartChild(pending) {
828
828
  catch { /* not launched, or not yet */ }
829
829
  if (childPid > 1) {
830
830
  pending.pid = childPid;
831
- pending.pid_started = processStartStamp(childPid);
831
+ pending.pid_started = readStartStamp(childPid);
832
832
  }
833
833
  }
834
834
  /**
@@ -838,7 +838,7 @@ function adoptStartChild(pending) {
838
838
  * again on the next pass; nothing is started for the session meanwhile. It waits at most a second
839
839
  * for the child, so several endings cannot hold up the machine report. Throws while incomplete.
840
840
  */
841
- async function endPendingStart(state, id, pending, reason, runner, log) {
841
+ async function endPendingStart(state, id, pending, reason, runner, log, readStartStamp = processStartStamp) {
842
842
  if (!pending.ending) {
843
843
  // A first turn that had begun may outlive its start; nothing new starts beside it.
844
844
  if (startProgressState(pending) === "onboarding_turn_running" && pending.desired?.dir)
@@ -846,12 +846,12 @@ async function endPendingStart(state, id, pending, reason, runner, log) {
846
846
  pending.ending = { reason, since: new Date().toISOString() };
847
847
  writeMachineState(state);
848
848
  }
849
- adoptStartChild(pending);
849
+ adoptStartChild(pending, readStartStamp);
850
850
  if (pending.pid === 0 && Date.now() - Date.parse(pending.started_at) <= START_INTENT_GRACE_MS) {
851
851
  throw new Error(`${pending.ending.reason}; waiting to learn whether its start process was launched`);
852
852
  }
853
853
  // Only the process this record names is signalled: a pid that now belongs to something else is left alone.
854
- const child = pending.pid > 1 && pending.pid !== process.pid ? startChildState(pending) : "gone";
854
+ const child = pending.pid > 1 && pending.pid !== process.pid ? startChildState(pending, readStartStamp) : "gone";
855
855
  if (child === "unknown")
856
856
  throw new Error(`${pending.ending.reason}; process ${pending.pid} cannot be identified as its start process, so it is not signalled and nothing is started in its place until it has exited`);
857
857
  if (child === "alive") {
@@ -873,9 +873,9 @@ async function endPendingStart(state, id, pending, reason, runner, log) {
873
873
  }
874
874
  }
875
875
  const until = Date.now() + 1_000;
876
- while (startChildState(pending) !== "gone" && Date.now() < until)
876
+ while (startChildState(pending, readStartStamp) !== "gone" && Date.now() < until)
877
877
  await new Promise((resolve) => setTimeout(resolve, 50));
878
- if (startChildState(pending) !== "gone")
878
+ if (startChildState(pending, readStartStamp) !== "gone")
879
879
  throw new Error(`${pending.ending.reason}; its start process ${pending.pid} has not exited yet`);
880
880
  }
881
881
  const agent = pending.desired?.agent;
@@ -1072,8 +1072,10 @@ export async function launchDesiredSession(opts) {
1072
1072
  const LOG_ROTATION_EVERY_MS = 10 * 60_000;
1073
1073
  let lastLogRotationAt = 0;
1074
1074
  export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1075
+ const readStartStamp = deps?.processStartStamp ?? processStartStamp;
1075
1076
  const client = Client.raw(m.url, m.key, {
1076
1077
  requestTimeoutMs: MACHINE_REQUEST_TIMEOUT_MS,
1078
+ stagedPoolPreparation: true,
1077
1079
  signal: deps?.signal,
1078
1080
  onRequest: (event) => log(event.phase === "start"
1079
1081
  ? `request start ${event.method} ${event.path}`
@@ -1137,7 +1139,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1137
1139
  const local = state.sessions[s.id];
1138
1140
  const pending = state.starting_sessions?.[s.id];
1139
1141
  if (pending)
1140
- await endPendingStart(state, s.id, pending, "benched", runner, log);
1142
+ await endPendingStart(state, s.id, pending, "benched", runner, log, readStartStamp);
1141
1143
  const w = svc();
1142
1144
  const reason = `benched by ${s.benched_by ?? "the operator"}${s.benched_at ? ` at ${s.benched_at}` : ""}${s.bench_note ? `: ${s.bench_note}` : ""}`;
1143
1145
  if (w) {
@@ -1155,7 +1157,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1155
1157
  const local = state.sessions[s.id];
1156
1158
  const pending = state.starting_sessions?.[s.id];
1157
1159
  if (pending)
1158
- await endPendingStart(state, s.id, pending, "stopped", runner, log);
1160
+ await endPendingStart(state, s.id, pending, "stopped", runner, log, readStartStamp);
1159
1161
  const w = svc();
1160
1162
  if (w) {
1161
1163
  removeService(w);
@@ -1174,7 +1176,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1174
1176
  const phase = probeFor(s.harness, thread, s.agent).phase();
1175
1177
  return "missing" in phase ? null : phase.running;
1176
1178
  });
1177
- out.push({ id: s.id, state: "stopped", ...facts, ...(s.pool_move_pending ? { checkout: sessionCheckoutFacts(dir) } : {}) });
1179
+ out.push({ id: s.id, state: "stopped", ...facts, ...(s.pool_move_pending ? { checkout: sessionCheckoutFacts(dir, { verifyOrigin: true }) } : {}) });
1178
1180
  continue;
1179
1181
  }
1180
1182
  if (!TURN_HARNESSES.includes(s.harness))
@@ -1214,6 +1216,31 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1214
1216
  if (!existsSync(s.dir))
1215
1217
  throw new Error(`checkout ${s.dir} does not exist on this machine`);
1216
1218
  let local = state.sessions[s.id];
1219
+ if (s.desired === "prepared") {
1220
+ if (svc() || local?.container_name || state.starting_sessions?.[s.id] || state.unsettled_turns?.[s.dir])
1221
+ throw new Error("target already has a watcher or recorded container; preparation will not start another");
1222
+ if (s.harness === "dsh")
1223
+ throw new Error(`DeepSeek Harness login cannot be verified on ${m.name}`);
1224
+ if (local) {
1225
+ const conflict = existingSessionDirectoryConflict(s.id, s.dir, local.thread, s.agent);
1226
+ if (conflict) {
1227
+ out.push(conflict);
1228
+ continue;
1229
+ }
1230
+ }
1231
+ await ensureCredentials(client, m, s, local, log);
1232
+ (deps?.prepareTargetCheckout ?? preparePoolTargetCheckout)(s.dir);
1233
+ const observed = deps?.prepareTargetFacts ? deps.prepareTargetFacts(s) : preparedTargetFacts(s);
1234
+ const reported = s.harness === "claude-code"
1235
+ ? observed.claude_code?.providers?.[s.provider ?? "anthropic"]
1236
+ : observed[s.harness];
1237
+ if (!reported || (reported.logged_in !== true && reported.secret_configured !== true))
1238
+ throw new Error(`${s.harness} login is not verified on this machine`);
1239
+ if (s.sandbox !== "danger-full-access" && reported.sandbox?.ok !== true)
1240
+ throw new Error(`${s.harness} sandbox is not verified on this machine`);
1241
+ out.push({ id: s.id, state: "ready", dir: s.dir, watcher: "inactive", detail: "checkout, harness login and sandbox verified; no watcher started" });
1242
+ continue;
1243
+ }
1217
1244
  const pendingStart = state.starting_sessions?.[s.id];
1218
1245
  preflightDone = true;
1219
1246
  let neverLaunched = false;
@@ -1221,19 +1248,19 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1221
1248
  let result = readMachineStartResult(pendingStart.result_file);
1222
1249
  const ageMs = Date.now() - Date.parse(pendingStart.started_at);
1223
1250
  const endPending = async (reason) => {
1224
- await endPendingStart(state, s.id, pendingStart, reason, runner, log);
1251
+ await endPendingStart(state, s.id, pendingStart, reason, runner, log, readStartStamp);
1225
1252
  throw new Error(reason);
1226
1253
  };
1227
1254
  if (pendingStart.ending) {
1228
1255
  // An ending begun on an earlier pass: finish it (it throws while incomplete), then start afresh.
1229
- await endPendingStart(state, s.id, pendingStart, pendingStart.ending.reason, runner, log);
1256
+ await endPendingStart(state, s.id, pendingStart, pendingStart.ending.reason, runner, log, readStartStamp);
1230
1257
  neverLaunched = true;
1231
1258
  result = null;
1232
1259
  }
1233
1260
  else if (!result && pendingStart.pid === 0) {
1234
1261
  // The daemon stopped between recording the intent and recording the child. The child
1235
1262
  // names itself in its own file as its first act, so it is found here if it was launched.
1236
- adoptStartChild(pendingStart);
1263
+ adoptStartChild(pendingStart, readStartStamp);
1237
1264
  if (pendingStart.pid !== 0)
1238
1265
  writeMachineState(state);
1239
1266
  else if (ageMs > START_INTENT_GRACE_MS) {
@@ -1248,7 +1275,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1248
1275
  // Falls through to the ordinary launch decision below.
1249
1276
  }
1250
1277
  else if (!result) {
1251
- if (pendingStart.pid !== 0 && startChildState(pendingStart) === "gone")
1278
+ if (pendingStart.pid !== 0 && startChildState(pendingStart, readStartStamp) === "gone")
1252
1279
  await endPending("tracked b9s start process exited before returning a session or failure reason");
1253
1280
  const limitMs = startWaitMs(pendingStart.desired ?? s) + 120_000;
1254
1281
  if (ageMs > limitMs)
@@ -1449,7 +1476,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1449
1476
  cleanupMachineStart(pending);
1450
1477
  throw error;
1451
1478
  }
1452
- pending.pid_started = processStartStamp(pending.pid);
1479
+ pending.pid_started = readStartStamp(pending.pid);
1453
1480
  try {
1454
1481
  writeMachineState(state);
1455
1482
  }
@@ -1550,7 +1577,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1550
1577
  watcher: watcherState,
1551
1578
  ...((t) => ({ last_turn: t.line, ...(t.unknown_reason ? { last_turn_unknown: t.unknown_reason } : {}) }))(lastTurn(s.agent)),
1552
1579
  turn_judgment: s.turn_judgment ?? null,
1553
- ...(s.pool_move_pending ? { checkout: sessionCheckoutFacts(s.dir) } : {}),
1580
+ ...(s.pool_move_pending ? { checkout: sessionCheckoutFacts(s.dir, { verifyOrigin: true }) } : {}),
1554
1581
  ...turnFacts(s.agent, s.harness, th, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR),
1555
1582
  ...sessionImageFacts,
1556
1583
  });
@@ -1562,7 +1589,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1562
1589
  // The session as now asked for cannot run here, and a start made for its earlier form is
1563
1590
  // still pending: that start is ended, not left running behind the error.
1564
1591
  try {
1565
- await endPendingStart(state, s.id, stranded, "the session can no longer start as it was asked", runner, log);
1592
+ await endPendingStart(state, s.id, stranded, "the session can no longer start as it was asked", runner, log, readStartStamp);
1566
1593
  }
1567
1594
  catch (ending) {
1568
1595
  error = `${error}; ${ending.message}`.slice(0, 1000);
@@ -1594,7 +1621,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1594
1621
  continue;
1595
1622
  // One ending that cannot finish yet must not cost the other sessions their report; it is taken up again next pass.
1596
1623
  try {
1597
- await endPendingStart(state, id, pending, "session removed by the operator", runner, log);
1624
+ await endPendingStart(state, id, pending, "session removed by the operator", runner, log, readStartStamp);
1598
1625
  }
1599
1626
  catch (error) {
1600
1627
  log(`${pending.desired?.agent ?? id}: ${error.message}`);
@@ -1816,6 +1843,28 @@ export async function answerWorktreeProcessQueries(client, desired, queries, log
1816
1843
  }
1817
1844
  }
1818
1845
  const git = (args, cwd) => spawnSync("git", args, { cwd, encoding: "utf8", timeout: 600_000 });
1846
+ /** Prepare only a clean, fully pushed checkout; never reset or discard local work. */
1847
+ export function preparePoolTargetCheckout(dir) {
1848
+ const facts = sessionCheckoutFacts(dir, { verifyOrigin: true });
1849
+ if (facts.clean !== true || facts.pushed !== true || facts.error)
1850
+ throw new Error(`target checkout is not verified clean and pushed${facts.error ? `: ${facts.error}` : ""}`);
1851
+ const remote = spawnSync("git", ["ls-remote", "--symref", "origin", "HEAD"], {
1852
+ cwd: dir, encoding: "utf8", timeout: 30_000, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
1853
+ });
1854
+ if (remote.status !== 0)
1855
+ throw new Error("cannot query origin default branch");
1856
+ const symbolic = remote.status === 0 ? /^ref:\s+refs\/heads\/(\S+)\s+HEAD$/m.exec(remote.stdout) : null;
1857
+ const advertised = remote.status === 0 ? /^([0-9a-f]{40,64})\s+HEAD$/m.exec(remote.stdout)?.[1] : null;
1858
+ const target = symbolic ? `refs/remotes/origin/${symbolic[1]}` : "";
1859
+ if (!target || !advertised || git(["check-ref-format", target], dir).status !== 0)
1860
+ throw new Error("origin default branch is unknown");
1861
+ const fetched = git(["rev-parse", "--verify", `${target}^{commit}`], dir);
1862
+ if (fetched.status !== 0 || fetched.stdout.trim() !== advertised)
1863
+ throw new Error("origin default branch changed during preparation; retry the move");
1864
+ const checkedOut = git(["checkout", "--detach", target], dir);
1865
+ if (checkedOut.status !== 0)
1866
+ throw new Error(`target checkout failed: ${(checkedOut.stderr ?? "").trim().slice(-300)}`);
1867
+ }
1819
1868
  /**
1820
1869
  * The checkout of a pool session: the project's repository cloned once per machine under
1821
1870
  * ~/bschat/<project>/main (in the background, since ester's is 20 GB; "preparing" until it is done),
@@ -2446,6 +2495,33 @@ function claudeReport(path = process.env.PATH ?? "", providersInUse = ["anthropi
2446
2495
  }
2447
2496
  return { ...f, sandbox: claudeSandboxCache.result, providers };
2448
2497
  }
2498
+ /** Check a prepared target without starting a model turn or a watcher. */
2499
+ export function preparedTargetFacts(session) {
2500
+ const path = process.env.PATH ?? "";
2501
+ const env = { ...process.env, PATH: path };
2502
+ if (session.harness === "codex") {
2503
+ const login = spawnSync("codex", ["login", "status"], { cwd: session.dir, encoding: "utf8", timeout: 30_000, env });
2504
+ const loggedIn = login.status === 0 && /(?:^|\n)\s*logged in\b/i.test(`${login.stdout ?? ""}\n${login.stderr ?? ""}`);
2505
+ const sandbox = session.sandbox === "danger-full-access" ? null : spawnSync("codex", ["sandbox", "--", "true"], { cwd: session.dir, encoding: "utf8", timeout: 60_000, env });
2506
+ return { codex: { logged_in: loggedIn, sandbox: sandbox ? { ok: sandbox.status === 0 } : null } };
2507
+ }
2508
+ if (session.harness === "claude-code") {
2509
+ const f = claudeFacts(() => cachedClaudeLogin(env), path);
2510
+ const provider = session.provider ?? "anthropic";
2511
+ 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" };
2512
+ const sandbox = session.sandbox === "danger-full-access" ? null : claudeSandbox(path, session.dir);
2513
+ return { claude_code: { providers: { [provider]: { ...login, sandbox } } } };
2514
+ }
2515
+ if (session.harness === "antigravity") {
2516
+ const login = antigravityLoginFacts(path);
2517
+ // The normal machine probe may run a model turn. Preparation must not run
2518
+ // one, so only a recent already-recorded sandbox proof is admissible.
2519
+ const bin = readInstall()?.bin ?? null;
2520
+ const cached = agySandboxCache && agySandboxCache.path === path && agySandboxCache.b9sBin === bin && Date.now() - agySandboxCache.at < AGY_SANDBOX_PROBE_MS ? agySandboxCache.result : null;
2521
+ return { antigravity: { ...login, sandbox: cached } };
2522
+ }
2523
+ return {};
2524
+ }
2449
2525
  const modelCheckCacheFile = () => join(configRoot(), "state", "model-checks.json");
2450
2526
  function readModelCheckCache() {
2451
2527
  try {
@@ -2673,6 +2749,7 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
2673
2749
  ...(containerImds ? { container_imds_isolation: containerImds } : {}),
2674
2750
  ...(container.runtime !== null || process.env.B9S_CLOUD_MACHINE === "1" ? { container_runtime: container } : {}),
2675
2751
  codex: codexFactsValue,
2752
+ pool_staged_prepare: true,
2676
2753
  "claude-code": claude,
2677
2754
  claude_code: claude,
2678
2755
  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,9 +129,8 @@ 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
- ` heavy jobs: ${Object.entries(d.heavy_jobs ?? {}).map(([name, job]) => `${name} (${job.memory_gib} GiB; ${job.purpose}; workflows ${job.workflows.join(", ")})`).join("; ") || "none"}`,
132
134
  ` 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)"}`,
133
135
  ` agreements: ${r.process.agreements.length} of 8000 characters; charter: ${(r.process.charter ?? "").length ? `${r.process.charter.length} of 4000 characters` : "none (b9s-admin process charter <project> --file charter.md)"}; send-backs ${d.require_cited_changes === false ? "free-form" : "must cite the clause they fail"}`,
134
136
  ...(d.routing_policy ? [` routing: weights ${d.routing_policy.weights?.quality ?? 65}/${d.routing_policy.weights?.time ?? 20}/${d.routing_policy.weights?.cost ?? 15}, target ${d.routing_policy.quality_target_percent ?? "none"}, half-life ${d.routing_policy.recency_half_life_days ?? 30}d, min samples ${d.routing_policy.minimum_sample_count ?? 8}, build explore ${d.routing_policy.build_exploration_budget_percent ?? 10}%${d.routing_policy.build_exploration_paused ? " (paused)" : ""}, review explore ${d.routing_policy.review_exploration_budget_percent ?? 10}%${d.routing_policy.review_exploration_paused ? " (paused)" : ""}`] : []),
@@ -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";
@@ -574,7 +575,7 @@ export async function wu(p, out) {
574
575
  const createdReceiptLine = (u) => `WU #${u.number} created: ${u.title}`;
575
576
  const fmt = (u) => {
576
577
  const waitList = Array.isArray(u.waits_on) ? u.waits_on : u.waiting_on ? [u.waiting_on] : [];
577
- const flags = [u.assigned_by ? `assigned by ${u.assigned_by}` : null, u.preferred_name ? `reserved for ${u.preferred_name}${u.hold ? " until free" : ""}` : null, u.hold && u.status === "assigned" ? "held" : null, waitList.length ? `waits on ${waitList.map((n) => `#${n}`).join(", ")}` : null, u.lands_with ? `lands with WU #${u.lands_with}` : null, u.review_wait ? `waiting on ${u.review_wait.type === "unit" ? `WU #${u.review_wait.target}` : u.review_wait.type === "ask" ? `ask ${u.review_wait.target}` : u.review_wait.type === "machine" ? `machine ${u.review_wait.target}` : u.review_wait.type === "text" ? u.review_wait.target : "evidence"} for ${Math.max(0, Math.round((Date.now() - Date.parse(u.review_wait.started_at)) / 60000))} min` : null, u.milestone ? `milestone ${u.milestone}` : null, u.target ? `lands in ${u.target}` : null, u.replay_of ? "REPLAY" : null, u.trial_tags?.length ? `trial on ${u.trial_tags.map((t) => `#${t}`).join(" ")}` : null].filter(Boolean).join(" · ");
578
+ const flags = [u.priority === "urgent" ? "URGENT" : null, u.assigned_by ? `assigned by ${u.assigned_by}` : null, u.preferred_name ? `reserved for ${u.preferred_name}${u.hold ? " until free" : ""}` : null, u.hold && u.status === "assigned" ? "held" : null, waitList.length ? `waits on ${waitList.map((n) => `#${n}`).join(", ")}` : null, u.lands_with ? `lands with WU #${u.lands_with}` : null, u.review_wait ? `waiting on ${u.review_wait.type === "unit" ? `WU #${u.review_wait.target}` : u.review_wait.type === "ask" ? `ask ${u.review_wait.target}` : u.review_wait.type === "machine" ? `machine ${u.review_wait.target}` : u.review_wait.type === "text" ? u.review_wait.target : "evidence"} for ${Math.max(0, Math.round((Date.now() - Date.parse(u.review_wait.started_at)) / 60000))} min` : null, u.milestone ? `milestone ${u.milestone}` : null, u.target ? `lands in ${u.target}` : null, u.replay_of ? "REPLAY" : null, u.trial_tags?.length ? `trial on ${u.trial_tags.map((t) => `#${t}`).join(" ")}` : null].filter(Boolean).join(" · ");
578
579
  const reviewers = u.reviewers.map((r) => `${r.name}${r.tags.length ? ` for ${r.tags.map((t) => `#${t}`).join(" ")}` : ""}`).join(", ");
579
580
  const approvals = u.approvals.map((a) => a.name).join(", ");
580
581
  return [
@@ -634,7 +635,10 @@ export async function wu(p, out) {
634
635
  // and recorded exactly as `wu start` would; --here keeps the current checkout.
635
636
  // One client id per create, reused across retries: a lost response or a 5xx after the unit was written returns that unit instead of making a second.
636
637
  const clientId = randomUUID();
637
- const r = await client.call("POST", base, { client_id: clientId, title, scope, tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), reworks: list("reworks").map(Number), force: bool(p.flags, "force"), ...symbolicBranchAndHead(), worktree: process.cwd(), target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, ...startTelemetry(name) }, { retries: 3 });
638
+ const priority = str(p.flags, "priority");
639
+ if (priority !== undefined && priority !== "normal" && priority !== "urgent")
640
+ throw new CliError("usage", "--priority must be urgent or normal");
641
+ const r = await client.call("POST", base, { client_id: clientId, title, scope, tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), reworks: list("reworks").map(Number), force: bool(p.flags, "force"), ...(priority ? { priority } : {}), ...symbolicBranchAndHead(), worktree: process.cwd(), target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, ...startTelemetry(name) }, { retries: 3 });
638
642
  const n = r.unit.number;
639
643
  const created = createdReceipt(r.unit);
640
644
  if (r.unit.waiting_on != null) {
@@ -668,6 +672,9 @@ export async function wu(p, out) {
668
672
  }
669
673
  const to = str(p.flags, "to");
670
674
  const reason = str(p.flags, "reason");
675
+ const priority = str(p.flags, "priority");
676
+ if (priority !== undefined && priority !== "normal" && priority !== "urgent")
677
+ throw new CliError("usage", "--priority must be urgent or normal");
671
678
  if (!to)
672
679
  throw new CliError("usage", 'wu assign "<title>" --to <agent|auto|queue> --scope "<what it covers and does not>" [--scope-file <path> | --scope-from <n>] [--tags a,b] [--after <n>[,<m>]] [--evidence id] [--replay-of <n>]');
673
680
  const existingNumber = Number(p.positionals[2]);
@@ -686,7 +693,7 @@ export async function wu(p, out) {
686
693
  const scope = await scopeText();
687
694
  const replay = str(p.flags, "replay-of");
688
695
  const clientId = randomUUID();
689
- const r = await client.call("POST", `${base}/assign`, { client_id: clientId, to, title, scope, tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: explicitBranch, target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, hold: !!p.flags.hold, force: bool(p.flags, "force"), ...(reason === undefined ? {} : { reason }) }, { retries: 3 });
696
+ const r = await client.call("POST", `${base}/assign`, { client_id: clientId, to, title, scope, tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: explicitBranch, target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, hold: !!p.flags.hold, force: bool(p.flags, "force"), ...(priority ? { priority } : {}), ...(reason === undefined ? {} : { reason }) }, { retries: 3 });
690
697
  out.print(`${createdReceiptLine(r.unit)}\n${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${assignmentGuidanceOutput(r.warnings ?? [])}`, createdReceipt(r.unit));
691
698
  return;
692
699
  }
@@ -932,6 +939,17 @@ export async function wu(p, out) {
932
939
  out.print(`${fmt(r.unit)}\n${actionResult}`, r);
933
940
  return;
934
941
  }
942
+ case "priority": {
943
+ const value = p.positionals[3];
944
+ const note = str(p.flags, "note");
945
+ if (value !== "urgent" && value !== "normal")
946
+ throw new CliError("usage", 'wu priority <n> urgent|normal --note "why this priority changed"');
947
+ if (!note?.trim())
948
+ throw new CliError("usage", 'wu priority <n> urgent|normal --note "why this priority changed"');
949
+ const r = await client.call("POST", `${base}/${num()}/priority`, { priority: value, note });
950
+ out.print(`${fmt(r.unit)}\nWU #${num()} priority is ${value}.`, r);
951
+ return;
952
+ }
935
953
  case "supersede": {
936
954
  const by = str(p.flags, "by");
937
955
  if (!by)
@@ -1271,7 +1289,6 @@ export async function processCmd(p, out) {
1271
1289
  const lines = [
1272
1290
  `Process v${r.process.version}${r.process.version === 0 ? " (defaults; the operator has not published one)" : ""}`,
1273
1291
  `Machine capabilities: ${(d.capabilities ?? []).map((c) => `${c.name} (${c.scope}${c.min_version ? ` >= ${c.min_version}` : ""})`).join(", ") || "none"}`,
1274
- `Heavy job classes: ${Object.entries(d.heavy_jobs ?? {}).map(([name, job]) => `${name} (${job.memory_gib} GiB; ${job.purpose}; workflows ${job.workflows.join(", ")})`).join("; ") || "none"}`,
1275
1292
  `Unlisted heavy workflows use the exclusive unknown-heavy class (the whole safe budget); an unknown budget or stale telemetry waits for operator review.`,
1276
1293
  vocab.length ? `Tags (use them on b9s wu open --tags):` : `No tag vocabulary yet: units route to the default approver (${d.default_approver_role ?? "none"}).`,
1277
1294
  ...vocab.map((t) => ` #${t.name}: ${t.meaning || "(no meaning written)"}${t.require_evidence ? " · requires evidence" : ""}${t.require_rebased ? " · requires a rebased branch" : ""}${t.requires?.length ? ` · requires capabilities ${t.requires.join(", ")}` : ""}${t.focus ? ` · reviewer focus: ${t.focus}` : ""} · reviewed by ${whoReviews(t.name).join(", ") || "NOBODY (the operator must qualify a role)"}`),
@@ -1282,6 +1299,7 @@ export async function processCmd(p, out) {
1282
1299
  `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
1300
  ...(r.wake_path_warnings?.length ? [`No verified wake path:`, ...r.wake_path_warnings.map((warning) => ` ${warning.consequence}`)] : []),
1284
1301
  `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>)" : ""}.`,
1302
+ d.merge.gate_command ? `Merge gate (run exactly this, with the unit's number and head filled in): ${d.merge.gate_command}` : null,
1285
1303
  r.process.agreements ? `\nWorking agreements:\n${r.process.agreements}` : null,
1286
1304
  r.process.charter ? `\nCharter (how this project weighs its trade-offs; judge reviews and questions by it):\n${r.process.charter}` : null,
1287
1305
  `\n${formatStandingRuleSet(r.standing_rules, project)}`,
@@ -1582,6 +1600,13 @@ export async function record(p, out) {
1582
1600
  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
1601
  }
1584
1602
  /** b9s lock <name> [--unit n] [--note ..] | b9s unlock <name> | b9s locks */
1603
+ /** What the holding job is doing, for a listing: the command it reported and for how long, or that it reported none. */
1604
+ export function lockActivity(l, nowMs) {
1605
+ const minutes = (since) => Math.max(0, Math.round((nowMs - Date.parse(since)) / 60_000));
1606
+ if (l.running)
1607
+ return ` · running "${l.running.command}" for ${minutes(l.running.started_at)} min`;
1608
+ return l.acquired_at ? ` · held ${minutes(l.acquired_at)} min, no command reported` : "";
1609
+ }
1585
1610
  export async function lock(p, out) {
1586
1611
  const name = resolveAgentName(str(p.flags, "as"));
1587
1612
  const creds = loadAgent(name);
@@ -1593,7 +1618,32 @@ export async function lock(p, out) {
1593
1618
  const lockName = p.positionals[1];
1594
1619
  if (cmd === "locks") {
1595
1620
  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);
1621
+ 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);
1622
+ return;
1623
+ }
1624
+ if (cmd === "lock" && lockName === "run" && (p.rest !== undefined || p.positionals.length > 2)) {
1625
+ const runName = p.positionals[2];
1626
+ if (!runName || !p.rest?.length)
1627
+ throw new CliError("usage", "b9s lock run <name> [--unit n] [--note ..] [--shared] -- <command> [args..]");
1628
+ if (str(p.flags, "machine") !== undefined)
1629
+ throw new CliError("usage", "lock run is scoped to the host running the CLI; --machine is only for unlock");
1630
+ if (Object.hasOwn({ acquire: 1, list: 1, release: 1, show: 1, status: 1 }, runName))
1631
+ throw new CliError("usage", `lock name ${runName} is reserved`);
1632
+ const runUnit = str(p.flags, "unit");
1633
+ const shared = bool(p.flags, "shared");
1634
+ const runToken = str(p.flags, "token") ?? `b9sjob_${randomBytes(24).toString("hex")}`;
1635
+ const machine = defaultMachine();
1636
+ const deps = processDeps((method, path, body) => client.call(method, path, body), (line) => process.stderr.write(`[b9s] ${line}\n`));
1637
+ try {
1638
+ process.exitCode = await runUnderLock({
1639
+ project, lock: runName, shared, machine, unit: runUnit ? Number(runUnit) : null, note: str(p.flags, "note"), command: p.rest, token: runToken,
1640
+ jobId: createHash("sha256").update(runToken).digest("hex").slice(0, 12),
1641
+ jobsFile: lockJobsFile(creds.project ? `${creds.project}.${creds.agent}` : `account.${creds.agent}`), jobsKey: lockJobKey(project, runName, shared ? null : machine),
1642
+ }, deps);
1643
+ }
1644
+ finally {
1645
+ deps.dispose();
1646
+ }
1597
1647
  return;
1598
1648
  }
1599
1649
  if (!lockName)
@@ -1697,7 +1747,11 @@ export async function askOperator(p, out) {
1697
1747
  if (!text || missing.length)
1698
1748
  throw new CliError("usage", `ask-operator "exactly what you need the operator to do or decide" --plain "one or two plain sentences for someone who has not read the thread: what this is about (no unit numbers or jargon unexplained)" --blocks "what's stuck until they answer" --if-yes "what happens then" --if-no "what happens then" [--propose "your recommended answer, approvable as written"]${missing.length ? `\nmissing: ${missing.join(", ")}` : ""}`);
1699
1749
  const proposal = str(p.flags, "propose") ?? "";
1700
- const r = await client.call("POST", `/projects/${project}/ask-operator`, { text, ...fields, proposal });
1750
+ const milestone = str(p.flags, "milestone");
1751
+ const rawUnit = str(p.flags, "unit");
1752
+ if (rawUnit !== undefined && !/^[1-9]\d*$/.test(rawUnit))
1753
+ throw new CliError("usage", "--unit must be a positive work unit number");
1754
+ const r = await client.call("POST", `/projects/${project}/ask-operator`, { text, ...fields, proposal, ...(milestone !== undefined ? { milestone } : {}), ...(rawUnit !== undefined ? { unit: Number(rawUnit) } : {}) });
1701
1755
  out.print(`Asked the operator${proposal ? " with your proposal (they can approve it as written)" : ""}; it is on their console banner and reported to them. You will be @mentioned with the decision. Carry on with what does not depend on it.`, r);
1702
1756
  }
1703
1757
  async function reviewUsage(client, project, name) {
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
@@ -69,10 +69,10 @@ Agent commands
69
69
  b9s rule supersede <rule-id> --text "..." [--expires-at <UTC>] [--conflicts-with id,id] --confirm-compatible
70
70
  b9s rule retire <rule-id> authorized assigner; project agent credentials restrict scope
71
71
  review current charter/agreements before --confirm-compatible; no rule is inferred from chat
72
- b9s wu open "<title>" --scope "..." [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--force] [--evidence id[,id...]] [--target <branch>] [--here] [--json] open a work unit in its own
72
+ b9s wu open "<title>" --scope "..." [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--priority urgent|normal] [--force] [--evidence id[,id...]] [--target <branch>] [--here] [--json] open a work unit in its own
73
73
  worktree; tags come from the vocabulary; --target is the branch it lands in (default: the
74
74
  process target), e.g. a lane branch; wu target <n> <branch|default> changes it before review
75
- b9s wu assign "<title>" --to <agent|auto|queue> --scope ".." [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--force] [--replay-of n] [--template] [--reason "why"] [--json] hand out a unit (assigner roles);
75
+ b9s wu assign "<title>" --to <agent|auto|queue> --scope ".." [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--priority urgent|normal] [--force] [--replay-of n] [--template] [--reason "why"] [--json] hand out a unit (assigner roles);
76
76
  --to auto picks the active qualified worker with the lightest load; it queues when nobody fits,
77
77
  reports why candidates were passed over, and the sweep chases it;
78
78
  --to queue waits deliberately; naming a busy worker reserves it for them (theirs when free,
@@ -83,6 +83,7 @@ Agent commands
83
83
  b9s wu list --json keeps complete titles.
84
84
  b9s wu assign <n> --to <agent> [--reason "why"] reassign an assigned or queued unit in place
85
85
  b9s wu lands-with <n> <base-unit|clear> set or clear the base WU whose landing gates this unit
86
+ b9s wu priority <n> urgent|normal --note "why this priority changed" operator or assigner: change dispatch priority; urgent work is dispatched first
86
87
  b9s wu take <n> [--to <agent>] [--reason "why"] pull a unit or hand it to someone
87
88
  reason is required when an assigner uses its assign_outside_qualifications role capability
88
89
  b9s wu next take the oldest queued unit you qualify for
@@ -126,14 +127,15 @@ Agent commands
126
127
  acquisition queues through a machine maintenance drain/window and resumes after it
127
128
  machine identity is this host's hostname plus its registered label, shared by all agents here
128
129
  save the returned job token; reuse --token to check/retry the same job
130
+ 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
131
  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
132
  b9s unlock <name> --remove-empty [--machine <label>|--shared]
131
133
  new agent jobs release by token; legacy jobs retain identity release; assigners/operators may release without a token
132
134
  closing a unit does not release a new job's lock
133
135
  assigners/operators can remove an empty scoped lock with --remove-empty
134
136
  lock names acquire/list/release/show/status are reserved: use lock <name>, locks, or unlock <name> as suggested
135
- project locks are separate from account-wide weighted machine-job permits; a lock never grants permit capacity
136
- Machine placement shares capacity across the account's projects: session seats and granted job permits consume one safe-memory budget; queued work is shown separately. Operators can read GET /machines/:m/placement for the slot ceiling, headroom, and pressure/freshness readings. Current pressure is telemetry and does not gate admission; safe-memory budget, freshness, maintenance, quarantine and operator admission pause remain admission inputs.
137
+ project locks are the admission control for named concurrent work
138
+ Machine placement enforces configured session slots and reports machine pressure for operators. Pressure is telemetry only. Linux kernel memory limits protect running processes; a fresh disk-floor check blocks starts when the checkout or state volume is too low.
137
139
  b9s measures latest measure values, freshness and merges since each value
138
140
  b9s measure show <name> definition history, values and runner requests
139
141
  b9s measure run <name> --sha <commit> [--target branch] [--rerun] request a bounded runner unit
@@ -166,12 +168,13 @@ Machine placement shares capacity across the account's projects: session seats a
166
168
  b9s wu scope <n> --scope ".." | --scope-file <path> | --scope-from <n> --note ".." assigner or operator: replace the full scope; recorded and announced
167
169
  b9s wu scope <n> --replace "<old>" "<new>" --note ".." replace one exact, unique substring of the scope
168
170
  b9s wu scope <n> --append ".." --note ".." add a dated scope amendment (up to 2000 chars); the base scope stays capped at 4000
169
- b9s ask-operator "what you need from them" --plain ".." --blocks ".." --if-yes ".." --if-no ".." [--propose ".."]
171
+ b9s ask-operator "what you need from them" --plain ".." --blocks ".." --if-yes ".." --if-no ".." [--propose ".."] [--milestone <key> | --unit <n>]
170
172
  b9s ask-operator --amend <id> ["new question"] [--plain ".."] [--blocks ".."] [--if-yes ".."] [--if-no ".."] [--propose ".."] amend your own open ask
171
173
  b9s ask-operator withdraw <key> --note "why it no longer needs an operator answer" withdraw your own ask, a steward-raised declared-wait ask, or an ask if you are a project assigner
172
174
  b9s ask-operator refuses a second ask naming the same WU; use --amend <id>. Account needs group asks/questions by unit and can answer several together.
173
175
  a decision only the operator can make, on their console banner and reported to them; never
174
176
  ask in chat. --plain: one or two sentences for someone who has not read the thread; --propose: your recommended answer, phrased so they can approve it as written; --blocks: what's stuck; --if-yes/--if-no: what happens on each answer
177
+ b9s ask ... alias for ask-operator
175
178
  b9s explain <ask-id> "..." the operator asked you (Explain) to put your request in plain words
176
179
  b9s wu explain <n> "..." the same for a unit's question waiting on the operator
177
180
  b9s wu tags <n> --add a --remove b retag (owner before review, a reviewer during it; may add a reviewer)
@@ -231,7 +234,7 @@ Machine placement shares capacity across the account's projects: session seats a
231
234
  Persistent watcher startup waits a random logged 0..60 s by default; set --startup-jitter-seconds 0 to disable it for a deterministic start.
232
235
  Machine pressure is advisory: it is reported, never a reason to hold a turn. A turn is refused only while
233
236
  the checkout's or state volume has under 1 GiB or 2% free (checked fresh each time, nothing latched).
234
- Heavy machine-job permits still wait for normal, fresh telemetry.
237
+ Machine pressure is reported as telemetry and does not hold a turn.
235
238
  Claude Code workspace-write defaults to a $1 per-turn cap; configure it with --max-budget-usd
236
239
  Account turn-spend caps are set by the account operator separately; token caps support subscriptions,
237
240
  missing usage remains reserved. Hard caps alone do not enable judgment capture; the account owner explicitly
@@ -364,12 +367,12 @@ the returned object and warning, then exits 3. Inspect the object and do not ret
364
367
  b9s-admin channel create|delete <project> <name>
365
368
  b9s-admin keys [create | revoke <id>] list admin and agent keys; create shows a new admin key once
366
369
  b9s-admin process show|export <project> [--out f] the process as agents are told it, or as an editable file
367
- b9s-admin process set <project> --file process.json publish definition, vocabulary and agreements in one version (including capabilities, review_rules, tag focus and heavy_jobs class declarations under definition)
370
+ b9s-admin process set <project> --file process.json publish definition, vocabulary and agreements in one version (including capabilities, review_rules, and tag focus)
368
371
  b9s-admin process tag add|edit|remove <project> <tag> [--meaning ..] [--require-evidence yes|no] [--require-rebased yes|no] [--expert-role r|none] [--requires name,name]
369
372
  legacy project-first order also accepted; for operation-first with a project named add, edit, or remove:
370
373
  b9s-admin process tag <op> <tag> --project <project>
371
374
  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]
375
+ 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
376
  b9s-admin process assigners <project> role1,role2 | agreements <project> --file agreements.md
374
377
  b9s-admin process charter <project> --file charter.md how the project weighs trade-offs; sent with every expert question
375
378
  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/index.js CHANGED
@@ -105,6 +105,7 @@ const COMMANDS = {
105
105
  unlock: lock,
106
106
  locks: lock,
107
107
  "ask-operator": askOperator,
108
+ ask: askOperator,
108
109
  explain: explainAsk,
109
110
  worktrees,
110
111
  measures,
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/output.js CHANGED
@@ -51,9 +51,8 @@ export function fmtMessage(m) {
51
51
  return `${m.created_at.slice(11, 19)} ${ch}${String(m.seq).padStart(5)} ${m.agent_name}${role}: ${m.body}`;
52
52
  }
53
53
  export function fmtStatus(s) {
54
- const machineWaiting = s.machine_job_waiting === true;
55
54
  const parts = [
56
- `${s.state === "benched" ? "BENCHED " : ""}${s.agent_name}${s.role_name ? `[${s.role_name}]` : ""}${s.away ? ` (away until ${s.away.until}: ${s.away.reason})` : s.usage_limit_until ? ` (usage limit until ${s.usage_limit_until})` : machineWaiting ? " (waiting: heavy machine permit)" : s.liveness === "quiet" ? " (quiet: harness went silent)" : s.liveness === "unknown" ? " (stale, harness unmonitored)" : s.liveness === "scheduled" ? ` (checks every ${s.checks_every} min, next ${(s.next_check_at ?? "").slice(11, 16)} UTC)` : s.liveness === "missed" ? ` (missed its ${s.checks_every}-min check)` : ""}`,
55
+ `${s.state === "benched" ? "BENCHED " : ""}${s.agent_name}${s.role_name ? `[${s.role_name}]` : ""}${s.away ? ` (away until ${s.away.until}: ${s.away.reason})` : s.usage_limit_until ? ` (usage limit until ${s.usage_limit_until})` : s.liveness === "quiet" ? " (quiet: harness went silent)" : s.liveness === "unknown" ? " (stale, harness unmonitored)" : s.liveness === "scheduled" ? ` (checks every ${s.checks_every} min, next ${(s.next_check_at ?? "").slice(11, 16)} UTC)` : s.liveness === "missed" ? ` (missed its ${s.checks_every}-min check)` : ""}`,
57
56
  `state=${s.state ?? "-"}`,
58
57
  s.goal ? `goal="${s.goal}"` : null,
59
58
  s.task ? `task="${s.task}"` : null,
@@ -61,7 +60,6 @@ export function fmtStatus(s) {
61
60
  `model=${s.model ?? "-"}`,
62
61
  s.machine ? `machine=${s.machine}` : null,
63
62
  s.machine_pressure ? `machine_health=${s.machine_pressure.state ?? "unknown"} (sample_age=${typeof s.machine_pressure.age_seconds === "number" ? `${Math.floor(s.machine_pressure.age_seconds)}s` : "unknown"}${s.machine_pressure.reasons?.length ? `; reasons=${s.machine_pressure.reasons.join(",")}` : ""})` : null,
64
- machineWaiting ? "machine_wait=heavy_permit" : null,
65
63
  s.capabilities?.length ? `capabilities=${s.capabilities.map((c) => `${c.name}:${c.ready ? c.version ?? "ok" : c.error ?? "stale/unknown"}`).join(",")}` : null,
66
64
  s.branch ? `branch=${s.branch}${s.dirty ? "*" : ""}@${s.head ?? "?"}` : null,
67
65
  s.worktree ? `worktree=${s.worktree}` : null,
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.121";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.119",
3
+ "version": "0.12.121",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {