benignswarm 0.12.122 → 0.12.123

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.
@@ -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 { removeCopyCommand, 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, MACHINE_LABEL, 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";
@@ -266,8 +266,8 @@ export async function doctor(_p, out) {
266
266
  const uid = process.getuid?.();
267
267
  if (process.platform === "darwin") {
268
268
  checks.push(launchdSessionNow() === "gui"
269
- ? { ok: true, what: "launchd: desktop session (services in the gui domain)" }
270
- : { ok: true, what: "launchd: headless Mac (no desktop session): services run as Background agents in the user domain; after a reboot an SSH login (FileVault unlock) is needed before they start" });
269
+ ? { ok: true, what: "launchd: desktop session (services in the gui domain); automatic desktop sign-in is the recommended unattended setup" }
270
+ : { ok: true, what: "launchd: headless Mac (no desktop session); headless startup across reboot has not been validated; automatic desktop sign-in is the recommended unattended setup" });
271
271
  }
272
272
  const services = watcherServices();
273
273
  if (services.some((s) => s.kind === "systemd") && lingerEnabled() === false)
@@ -287,11 +287,12 @@ export async function doctor(_p, out) {
287
287
  checks.push(active === "active" ? { ok: true, what: `watcher ${short}: running ${args[0]} (${ver ?? "?"})` } : { ok: false, what: `watcher ${short} is ${active || "unknown"}; see ~/.b9s/logs/watch.${short}.err.log`, fix: `systemctl --user daemon-reload && systemctl --user restart ${w.label}.service` });
288
288
  continue;
289
289
  }
290
- const short = w.label.replace("org.benignswarm.watch.", "");
290
+ const isDaemon = w.label === MACHINE_LABEL;
291
+ const short = isDaemon ? "machine daemon" : `watcher ${w.label.replace("org.benignswarm.watch.", "")}`;
291
292
  const domain = plistLaunchdDomain(w.path);
292
293
  const reload = `launchctl bootout ${domain}/${w.label}; launchctl bootstrap ${domain} ${w.path}`;
293
294
  if (!args.length) {
294
- checks.push({ ok: false, what: `watcher ${short}: unreadable plist ${w.path}` });
295
+ checks.push({ ok: false, what: `${short}: unreadable plist ${w.path}` });
295
296
  continue;
296
297
  }
297
298
  const loadedIn = launchdLoadedIn(w.label);
@@ -300,21 +301,21 @@ export async function doctor(_p, out) {
300
301
  const pid = pidNum === null ? undefined : String(pidNum);
301
302
  const ver = binVersion(args[0]);
302
303
  if (rec && args[0] !== rec.bin)
303
- checks.push({ ok: false, what: `watcher ${short} runs ${args[0]} (${ver ?? "does not run"}), not the recorded install`, fix: "re-run its b9s watch ... --launchd (it uses the recorded install and reloads)" });
304
+ checks.push({ ok: false, what: `${short} runs ${args[0]} (${ver ?? "does not run"}), not the recorded install`, fix: isDaemon ? "run b9s machine service to rewrite and restart the daemon" : "re-run its b9s watch ... --launchd (it uses the recorded install and reloads)" });
304
305
  if (listed.status !== 0) {
305
- checks.push({ ok: false, what: `watcher ${short} is not loaded (a login or reboot loads it)`, fix: `launchctl bootstrap ${domain} ${w.path} (or delete the plist if the agent is gone)` });
306
+ checks.push({ ok: false, what: isDaemon ? "machine daemon is not loaded; see b9s machine status" : `${short} is not loaded`, fix: isDaemon ? "run b9s machine service to write and load the daemon service" : `launchctl bootstrap ${domain} ${w.path} (or delete the plist if the agent is gone)` });
306
307
  continue;
307
308
  }
308
309
  if (!pid) {
309
- checks.push({ ok: false, what: `watcher ${short} is loaded but not running; see ~/.b9s/logs/watch.${short}.err.log`, fix: reload });
310
+ checks.push({ ok: false, what: isDaemon ? "machine daemon is loaded but not running; see ~/.b9s/logs/machine.*.log" : `${short} is loaded but not running; see ~/.b9s/logs/${w.label.replace("org.benignswarm.watch.", "watch.")}.err.log`, fix: reload });
310
311
  continue;
311
312
  }
312
313
  const running = (spawnSync("ps", ["-o", "command=", "-p", pid], { encoding: "utf8" }).stdout ?? "").trim();
313
314
  const tail = args.slice(1).join(" ");
314
315
  if (!running.endsWith(tail))
315
- checks.push({ ok: false, what: `watcher ${short} is running an older definition than its plist (launchd was never reloaded)\n plist: ${tail}\n running: ${running}`, fix: reload });
316
+ checks.push({ ok: false, what: `${short} is running an older definition than its plist (launchd was never reloaded)\n plist: ${tail}\n running: ${running}`, fix: reload });
316
317
  else
317
- checks.push({ ok: true, what: `watcher ${short}: running ${args[0]} (${ver ?? "?"})` });
318
+ checks.push({ ok: true, what: `${short}: running ${args[0]} (${ver ?? "?"})` });
318
319
  }
319
320
  const problems = checks.filter((c) => !c.ok);
320
321
  const environmentChecks = doctorEnvironmentChecks(process.env.PATH ?? "", defaultWorkspaceWritableRoots());
@@ -11,7 +11,7 @@ export async function runUnderLock(o, deps) {
11
11
  const now = deps.now ?? Date.now;
12
12
  const label = commandLabel(o.command);
13
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 };
14
+ const acquireBody = { unit: o.unit, note: o.note ?? label, shared: o.shared, machine: o.machine, job_token: o.token, lock_run: true };
15
15
  const release = async () => {
16
16
  try {
17
17
  await deps.call("POST", `${base}/release`, { shared: o.shared, machine: o.shared ? undefined : o.machine, job_token: o.token });
@@ -195,6 +195,7 @@ export async function watch(p, out, dependencies = {}) {
195
195
  log(`watcher heartbeat failed: ${e.message}`);
196
196
  }
197
197
  }
198
+ await reportUnreportedAck(name, log);
198
199
  if (turn?.harness === "codex") {
199
200
  const current = readState(name);
200
201
  const clear = current.pending_context_clear;
@@ -1304,15 +1305,37 @@ export async function completePendingTurnGuard(name, probe, log, outputOverride,
1304
1305
  function turnFaultSummary(fault) {
1305
1306
  return `${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns made no BenignSwarm call` : `${fault.unproductive_last_hour} unproductive turns in the rolling hour`}; likely cause: ${fault.likely_cause}; estimated tokens spent: ${fault.estimated_tokens}`;
1306
1307
  }
1307
- /** The watcher acknowledges a turn it started: the session shows the agent has the prompt. */
1308
- async function ackTurn(name, seq, log, env = process.env) {
1309
- writeState(name, applyAck(readState(name, env), seq).next, env);
1308
+ const postAck = (name, env) => async (seq) => {
1309
+ await Client.forAgent(loadAgent(name, env), undefined, { presence: false }).call("POST", "/agents/me/wake/ack", { seq });
1310
+ };
1311
+ /**
1312
+ * The watcher acknowledges a turn it started: the session shows the agent has the prompt.
1313
+ * The server derives a broken wake path from an acknowledgement it never received, so one that
1314
+ * fails to arrive is kept and sent again every poll (reportUnreportedAck), never dropped: a
1315
+ * database overload once lost one and the agent read as unreachable for 40 minutes while idle.
1316
+ */
1317
+ export async function ackTurn(name, seq, log, env = process.env, post = postAck(name, env)) {
1318
+ writeState(name, { ...applyAck(readState(name, env), seq).next, watch_ack_unreported: seq }, env);
1319
+ await reportUnreportedAck(name, log, env, post, true);
1320
+ }
1321
+ /** Sends the kept acknowledgement; clears it only when the server accepted it. */
1322
+ export async function reportUnreportedAck(name, log, env = process.env, post = postAck(name, env), first = false) {
1323
+ const seq = readState(name, env).watch_ack_unreported;
1324
+ if (seq === undefined)
1325
+ return;
1310
1326
  try {
1311
- await Client.forAgent(loadAgent(name, env), undefined, { presence: false }).call("POST", "/agents/me/wake/ack", { seq });
1327
+ await post(seq);
1312
1328
  }
1313
1329
  catch (e) {
1314
- log(`could not report the acknowledgement of turn #${seq} to the server: ${e.message}`);
1330
+ if (first)
1331
+ log(`could not report the acknowledgement of turn #${seq} to the server (it will be sent again every poll): ${e.message}`);
1332
+ return;
1315
1333
  }
1334
+ const now = readState(name, env);
1335
+ if (now.watch_ack_unreported === seq)
1336
+ writeState(name, { ...now, watch_ack_unreported: undefined }, env);
1337
+ if (!first)
1338
+ log(`acknowledgement of turn #${seq} reached the server on a later attempt`);
1316
1339
  }
1317
1340
  const processLine = (lag) => `The project process changed: it is version ${lag.version} now and ${lag.seen ? `you last read version ${lag.seen}` : "you have not read it"}. Read it first: b9s process`;
1318
1341
  const PROCESS_CHECK_MS = 5 * 60_000;
@@ -1281,7 +1281,10 @@ export async function processCmd(p, out) {
1281
1281
  const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
1282
1282
  if (!project)
1283
1283
  throw new CliError("no_project", `${creds.agent} is an account-scoped agent; pass --project <name>`);
1284
- const [r, b] = await Promise.all([client.call("GET", `/projects/${project}/process`), client.call("GET", `/projects/${project}/work-units/board`)]);
1284
+ const [r, b] = await Promise.all([client.call("GET", `/projects/${project}/process`),
1285
+ // Only the roles are needed. This used to fetch the whole Work board, the heaviest read in the
1286
+ // API, and every agent runs this command after each process change.
1287
+ client.call("GET", `/projects/${project}/roles`)]);
1285
1288
  const d = r.process.definition;
1286
1289
  const vocab = r.vocabulary;
1287
1290
  const roles = b.roles;
@@ -1289,7 +1292,10 @@ export async function processCmd(p, out) {
1289
1292
  const lines = [
1290
1293
  `Process v${r.process.version}${r.process.version === 0 ? " (defaults; the operator has not published one)" : ""}`,
1291
1294
  `Machine capabilities: ${(d.capabilities ?? []).map((c) => `${c.name} (${c.scope}${c.min_version ? ` >= ${c.min_version}` : ""})`).join(", ") || "none"}`,
1292
- `Unlisted heavy workflows use the exclusive unknown-heavy class (the whole safe budget); an unknown budget or stale telemetry waits for operator review.`,
1295
+ // Machine job permits were removed (WU #520). The old line here told agents an unlisted heavy run
1296
+ // "waits for operator review": three units in another project sat for days on asks for a permit
1297
+ // that no longer exists.
1298
+ `Heavy runs (builds, complete suites, device or browser runs) need no permit: run them one at a time under a named lock, b9s lock run <name> --unit <n> -- <command>. Machine pressure in b9s who is advisory.`,
1293
1299
  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"}).`,
1294
1300
  ...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)"}`),
1295
1301
  ...Object.entries(d.scope_templates ?? {}).flatMap(([tag, template]) => [` #${tag} scope template:`, ...template.sections.map((section) => ` ${section.name}${section.required ? " (required)" : ""}${section.hint ? ` — ${section.hint}` : ""}`)]),
@@ -1607,6 +1613,16 @@ export function lockActivity(l, nowMs) {
1607
1613
  return ` · running "${l.running.command}" for ${minutes(l.running.started_at)} min`;
1608
1614
  return l.acquired_at ? ` · held ${minutes(l.acquired_at)} min, no command reported` : "";
1609
1615
  }
1616
+ /** A `lock run` waiter remains live by polling; show the server-observed poll age in listings. */
1617
+ export function lockWaiterActivity(waiter, nowMs) {
1618
+ if (!waiter.lock_run)
1619
+ return "";
1620
+ const polledAt = waiter.last_poll_at === undefined ? NaN : Date.parse(waiter.last_poll_at);
1621
+ if (!Number.isFinite(polledAt))
1622
+ return " · last poll unknown";
1623
+ const seconds = Math.floor(Math.max(0, nowMs - polledAt) / 1000);
1624
+ return ` · last poll ${seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m`} ago`;
1625
+ }
1610
1626
  export async function lock(p, out) {
1611
1627
  const name = resolveAgentName(str(p.flags, "as"));
1612
1628
  const creds = loadAgent(name);
@@ -1618,7 +1634,7 @@ export async function lock(p, out) {
1618
1634
  const lockName = p.positionals[1];
1619
1635
  if (cmd === "locks") {
1620
1636
  const r = await client.call("GET", `/projects/${project}/locks`);
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);
1637
+ 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}` : ""}${lockWaiterActivity(w, Date.now())}`).join(", ")}` : ""}`).join("\n") : "No locks in this project. Take one with: b9s lock <name> [--unit n]", r);
1622
1638
  return;
1623
1639
  }
1624
1640
  if (cmd === "lock" && lockName === "run" && (p.rest !== undefined || p.positionals.length > 2)) {
package/dist/help.js CHANGED
@@ -127,8 +127,10 @@ Agent commands
127
127
  acquisition queues through a machine maintenance drain/window and resumes after it
128
128
  machine identity is this host's hostname plus its registered label, shared by all agents here
129
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
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
+ b9s lock run <name> [--unit n] [--note ..] [--shared] -- <command> poll until granted, run the command, then release; exits with its code
131
+ polls every 15s; stale waiters are skipped after 60s with a process notice; later polls reap unreported holders idle 60s
132
+ b9s locks shows waiter poll age; reported-command holders do not expire
133
+ b9s unlock <name> [--job <id> | --token <job-token>] [--machine <label>|--shared] | b9s locks shows lock-run waiters' last-poll age; on this host the job token is kept for you
132
134
  b9s unlock <name> --remove-empty [--machine <label>|--shared]
133
135
  new agent jobs release by token; legacy jobs retain identity release; assigners/operators may release without a token
134
136
  closing a unit does not release a new job's lock
@@ -474,6 +476,7 @@ Pools (fixed or adaptive; the server names the agents and places them on machine
474
476
  [--quota-substitution | --no-quota-substitution] allows another eligible variant after authoritative quota exhaustion
475
477
  pool writes first show a server impact preview; confirm a fresh revision with --impact-revision <revision>
476
478
  b9s-admin pool list [project] | show <project>/<name> | events <project>/<name> [--limit 1..100]
479
+ Console → Pools shows account/project placement, slot work/session state, and machine headroom
477
480
  b9s-admin pool pause|resume <project>/<name> [--reason <text>] pause only automatic scaling; sessions keep running
478
481
  b9s-admin pool pin <project>/<name> <slot> --machine <name> [--until <ISO>] [--reason <text>] | unpin <project>/<name> <slot>
479
482
  b9s-admin pool suspend|restore <project>/<name> <slot> [--reason <text>] [--note <text>] suspend keeps the same slot and does not create a replacement
package/dist/install.js CHANGED
@@ -355,8 +355,8 @@ export function launchdFacts() {
355
355
  export function launchdGuidance(session = launchdSessionNow()) {
356
356
  const uid = process.getuid();
357
357
  return session === "headless"
358
- ? `launchd: headless Mac, services are Background agents in user/${uid}. After a reboot they start once someone logs in over SSH (that also unlocks FileVault); a desktop sign-in is not needed. Harness sign-ins kept in the login keychain (Claude Code's by default) are unreadable without a desktop session; Codex and Antigravity keep theirs in files. External volumes may be refused to processes started while no one is signed in at the desktop: keep the workdir on the internal disk.`
359
- : `launchd: desktop session, services are LaunchAgents in gui/${uid}. They stop when that user signs out and start again at the next desktop sign-in; for a Mac meant to run unattended, use automatic sign-in, or install the services while no one is signed in so they run headless.`;
358
+ ? `launchd: headless Mac, services are Background agents in user/${uid}. Headless startup across reboot has not been validated; automatic desktop sign-in is the recommended unattended setup. A manual SSH login may load services for that session, but is not a verified boot-persistence method.`
359
+ : `launchd: desktop session, services are LaunchAgents in gui/${uid}. They stop when that user signs out and start again at the next desktop sign-in; automatic desktop sign-in is the recommended unattended setup.`;
360
360
  }
361
361
  /** One line for status output. */
362
362
  export function launchdFactsLine(f) {
package/dist/sessions.js CHANGED
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
1
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { dirname, join } from "node:path";
4
4
  import { configRoot } from "./config.js";
@@ -25,6 +25,51 @@ const KIND_NOUN = { codex: "a Codex thread", antigravity: "an Antigravity conver
25
25
  export function bindSession(kind, id, ref, opts = {}) {
26
26
  if (!UUID.test(id))
27
27
  throw new CliError("usage", `"${id}" is not ${KIND_NOUN[kind]} id (a UUID)`);
28
+ mkdirSync(dirname(file(kind)), { recursive: true });
29
+ withMapLock(kind, () => bindLocked(kind, id, ref, opts));
30
+ }
31
+ /**
32
+ * One writer at a time, and the file is replaced by rename. An upgrade restarts every session on a
33
+ * machine at once (39 on one host), and each start binds its thread: a start that read the map
34
+ * while another was writing it failed with "not valid JSON" (four sessions, 2026-11-18), and two
35
+ * that read the same version would have lost one binding. A lock older than 30 s belongs to a
36
+ * dead process and is taken over.
37
+ */
38
+ function withMapLock(kind, run) {
39
+ const lock = `${file(kind)}.lock`;
40
+ const deadline = Date.now() + 10_000;
41
+ for (;;) {
42
+ try {
43
+ closeSync(openSync(lock, "wx"));
44
+ break;
45
+ }
46
+ catch (error) {
47
+ if (error.code !== "EEXIST")
48
+ throw error;
49
+ let age = 0;
50
+ try {
51
+ age = Date.now() - statSync(lock).mtimeMs;
52
+ }
53
+ catch {
54
+ continue;
55
+ }
56
+ if (age > 30_000) {
57
+ rmSync(lock, { force: true });
58
+ continue;
59
+ }
60
+ if (Date.now() > deadline)
61
+ throw new CliError("session_map_busy", `${file(kind)} is locked by another b9s process`, "Retry in a moment");
62
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
63
+ }
64
+ }
65
+ try {
66
+ run();
67
+ }
68
+ finally {
69
+ rmSync(lock, { force: true });
70
+ }
71
+ }
72
+ function bindLocked(kind, id, ref, opts) {
28
73
  const m = read(kind);
29
74
  const key = id.toLowerCase();
30
75
  if (kind === "claude-code") {
@@ -40,8 +85,9 @@ export function bindSession(kind, id, ref, opts = {}) {
40
85
  m.auto = { ...(m.auto ?? {}), [key]: true };
41
86
  else if (m.auto)
42
87
  delete m.auto[key];
43
- mkdirSync(dirname(file(kind)), { recursive: true });
44
- writeFileSync(file(kind), JSON.stringify(m, null, 2) + "\n");
88
+ const next = `${file(kind)}.${process.pid}.tmp`;
89
+ writeFileSync(next, JSON.stringify(m, null, 2) + "\n");
90
+ renameSync(next, file(kind));
45
91
  }
46
92
  export function sessionAgent(kind, id) {
47
93
  return read(kind).conversations[id.toLowerCase()] ?? null;
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.122";
1
+ export const CLI_VERSION = "0.12.123";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.122",
3
+ "version": "0.12.123",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {