benignswarm 0.12.66 → 0.12.70

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
@@ -1,7 +1,7 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { CliError } from "./errors.js";
3
- export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "description", "permissions", "cardinality", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "follow-delay", "env", "scope", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "by", "target", "milestone", "file", "exit", "depends-on", "source", "by", "on", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "session", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable"];
4
- export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "unread", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "print-apparmor"];
3
+ export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "description", "permissions", "cardinality", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "follow-delay", "env", "scope", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "by", "target", "milestone", "file", "exit", "depends-on", "source", "by", "on", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "session", "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable"];
4
+ export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "unread", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "print-apparmor"];
5
5
  export function parse(argv) {
6
6
  const options = {};
7
7
  for (const f of STRING_FLAGS)
@@ -8,7 +8,7 @@ import { CliError } from "../errors.js";
8
8
  import { table } from "../output.js";
9
9
  import { milestoneWith, milestonesWith } from "./wu.js";
10
10
  import { agentMove, machineAdmin, poolAdmin, projectCheckoutAdmin, projectRepoAdmin } from "./machine-admin.js";
11
- import { accountAdmin, answerAdmin, keysAdmin, needsAdmin, notifierAdmin, processAdmin, skillAdmin, tagList, worktreeAdmin } from "./operator.js";
11
+ import { accountAdmin, answerAdmin, explainAdmin, keysAdmin, needsAdmin, notifierAdmin, processAdmin, skillAdmin, tagList, worktreeAdmin } from "./operator.js";
12
12
  function adminClient(p) {
13
13
  return Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
14
14
  }
@@ -90,6 +90,8 @@ export async function admin(p, out) {
90
90
  return needsAdmin(p, out);
91
91
  case "answer":
92
92
  return answerAdmin([action, ...rest].filter((x) => x !== undefined), p, out);
93
+ case "explain":
94
+ return explainAdmin([action, ...rest].filter((x) => x !== undefined), p, out);
93
95
  case "notifier":
94
96
  return notifierAdmin(p, out);
95
97
  case "account":
@@ -57,7 +57,7 @@ export async function harnessStart(p, out, harness) {
57
57
  throw new CliError("usage", "--writable takes absolute or ~/ paths, comma separated");
58
58
  // Refuses a sandbox the harness cannot honour before anything is enrolled.
59
59
  const settings = harness === "codex"
60
- ? codexSettings(sandbox, model, effort, process.cwd(), configRoot(), writable)
60
+ ? codexSettings(sandbox, model, effort, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
61
61
  : claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable);
62
62
  // 1. Who: enroll with the invite token, or use credentials already on this machine.
63
63
  const lines = [];
@@ -187,6 +187,22 @@ export function codexSettings(sandbox, model, effort, cwd, bschatHome, extraWrit
187
187
  : []),
188
188
  ];
189
189
  }
190
+ /**
191
+ * The agent's own linked-worktree git folder (<clone>/.git/worktrees/<name>), when it runs in one.
192
+ * Codex's sandbox makes the git folder of the directory it runs in read-only, and for a linked
193
+ * worktree that is this folder alone: the clone's common .git under the writable parent stays
194
+ * writable. So every reviewer on a machine failed `git fetch` from its home folder ("cannot open
195
+ * .../.git/worktrees/sol-reviewer/FETCH_HEAD: Read-only file system") while workers, committing in
196
+ * unit worktrees, did not. Listing it restores ordinary git there and opens nothing the agent could
197
+ * not already change through the common .git.
198
+ */
199
+ export function ownWorktreeGitDir(cwd) {
200
+ const r = spawnSync("git", ["rev-parse", "--absolute-git-dir", "--path-format=absolute", "--git-common-dir"], { cwd, encoding: "utf8" });
201
+ if (r.status !== 0)
202
+ return [];
203
+ const [gitDir, common] = r.stdout.trim().split("\n");
204
+ return gitDir && common && gitDir !== common ? [gitDir] : [];
205
+ }
190
206
  /** Starts a headless Codex session in its own process group and returns its thread id from the JSON event stream. */
191
207
  async function startThread(codexBin, args, logPath, agent) {
192
208
  const fd = openSync(logPath, "a");
@@ -10,7 +10,7 @@ import { CLI_VERSION } from "../version.js";
10
10
  * sessions they run (docs/REMOTE-MACHINES.md). The server never sees an ssh credential: every ssh
11
11
  * call here runs in the operator's terminal, and the machine key reaches the machine on ssh's stdin.
12
12
  *
13
- * machine add <name> --ssh <host> [--rotate] [--codex-userns]
13
+ * machine add <name> --ssh <host> [--rotate] [--codex-userns] [--bwrap-userns]
14
14
  * machine list | show <name> | remove <name>
15
15
  * machine session add <machine> <project>/<agent> --dir <path> --sandbox <mode> [--create --role r] [--model m] [--effort e] [--thread id] [--turn-timeout min]
16
16
  * machine session stop|start|remove <machine> <project>/<agent>
@@ -70,7 +70,7 @@ export async function machineAdmin(action, rest, p, out) {
70
70
  const name = rest[0];
71
71
  const host = str(p.flags, "ssh");
72
72
  if (!name || !host)
73
- throw new CliError("usage", "machine add <name> --ssh <host> [--rotate] [--codex-userns] (the host as your ssh knows it: an alias, user@host)");
73
+ throw new CliError("usage", "machine add <name> --ssh <host> [--rotate] [--codex-userns] [--bwrap-userns] (the host as your ssh knows it: an alias, user@host)");
74
74
  const lines = [];
75
75
  const say = (l) => { lines.push(l); if (!out.json)
76
76
  process.stderr.write(`${l}\n`); };
@@ -82,7 +82,7 @@ export async function machineAdmin(action, rest, p, out) {
82
82
  if (boot.status !== 0)
83
83
  throw new CliError("provision_failed", `bootstrapping ${host} failed${steps.length ? `: ${steps[steps.length - 1]}` : `: ${boot.stderr.trim().slice(-300)}`}`);
84
84
  // 2. Linger, Codex, managed hooks: checked and fixed on the machine itself.
85
- const prep = remoteBschat(host, `machine prepare --json${bool(p.flags, "codex-userns") ? " --codex-userns" : ""}`);
85
+ const prep = remoteBschat(host, `machine prepare --json${bool(p.flags, "codex-userns") ? " --codex-userns" : ""}${bool(p.flags, "bwrap-userns") ? " --bwrap-userns" : ""}`);
86
86
  if (prep.status !== 0)
87
87
  throw new CliError("provision_failed", `bschat machine prepare on ${host} failed: ${prep.stderr.trim().slice(-300)}`);
88
88
  const prepared = JSON.parse(prep.stdout).steps;
@@ -1,12 +1,12 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
- import { existsSync, mkdirSync, readFileSync, statfsSync, writeFileSync } from "node:fs";
2
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, statSync, statfsSync, writeFileSync } from "node:fs";
3
3
  import { arch, cpus, freemem, homedir, hostname, loadavg, platform, totalmem, userInfo } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
5
  import { str } from "../args.js";
6
6
  import { Client } from "../client.js";
7
7
  import { configRoot, loadAgent, saveAgent } from "../config.js";
8
8
  import { CliError } from "../errors.js";
9
- import { CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, CODEX_MANAGED_MARK, codexAppArmorProfile, codexManagedHooks } from "../harness.js";
9
+ import { BWRAP_APPARMOR_PATH, bwrapAppArmorProfile, CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, CODEX_MANAGED_MARK, codexAppArmorProfile, codexManagedHooks } from "../harness.js";
10
10
  import { applySparse } from "../git.js";
11
11
  import { TURN_HARNESSES, claudeFacts, claudeSandbox, probeFor, sessionProcesses } from "../harnesses.js";
12
12
  import { readState, writeState } from "../state.js";
@@ -26,7 +26,12 @@ function writeMachineState(s) {
26
26
  writeFileSync(stateFile(), JSON.stringify(s, null, 2) + "\n");
27
27
  }
28
28
  /** What a session's watcher is started with; a change means re-running codex start. The thread is compared separately. */
29
- export const sessionFingerprint = (s, writable = []) => JSON.stringify([s.harness, s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, ...(writable.length ? [writable] : [])]);
29
+ /**
30
+ * Bumped when `bschat start` builds a session's settings differently, so every session is started
31
+ * again once with them. 2: the agent's own worktree git folder is writable under workspace-write.
32
+ */
33
+ const START_REV = 2;
34
+ export const sessionFingerprint = (s, writable = []) => JSON.stringify([s.harness, s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, ...(writable.length ? [writable] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
30
35
  export const watchLabelOf = (ref) => `${WATCH_LABEL_PREFIX}${ref.replace("/", ".")}`;
31
36
  /** The `bschat start` arguments that bring a session up (adopting its thread or session when known). */
32
37
  export function startArgs(s, thread, writable = []) {
@@ -99,6 +104,13 @@ export async function reconcile(m, log) {
99
104
  }
100
105
  const w = svc();
101
106
  const th = state.sessions[s.id].thread;
107
+ // A watcher that exits at every start (a corrupt state file after the disk filled) is
108
+ // restarted by systemd forever and looked "running" here; report it as the error it is.
109
+ const fault = watcherFault(s.agent);
110
+ if (fault) {
111
+ out.push({ id: s.id, state: "error", dir: s.dir, thread: th, watcher: w && serviceActive(w) ? "active" : "inactive", error: `its watcher keeps exiting: ${fault}` });
112
+ continue;
113
+ }
102
114
  // The operator lifted a usage-limit pause: what bschat codex unpause does, here.
103
115
  if (s.unpause_at && state.sessions[s.id].unpause_applied !== s.unpause_at) {
104
116
  writeState(s.agent, { ...readState(s.agent), turn_unpaused_at: Date.parse(s.unpause_at) });
@@ -302,6 +314,47 @@ export function turnProcess(thread, harness = "codex", psOutput) {
302
314
  }
303
315
  return null;
304
316
  }
317
+ /**
318
+ * The error the watcher keeps exiting with, or null. A crash loop (systemd and launchd restart it
319
+ * every few seconds) leaves a fresh error line each time, while a watcher that failed once and
320
+ * recovered leaves an old one, so an error counts only when the line logged just before it is from
321
+ * the last two minutes. Error lines carry no time of their own.
322
+ */
323
+ export function watcherFault(ref, logText, nowMs = Date.now()) {
324
+ let text = logText;
325
+ if (text === undefined) {
326
+ const f = join(homedir(), ".bschat", "logs", `watch.${ref.replace("/", ".")}.err.log`);
327
+ if (!existsSync(f))
328
+ return null;
329
+ const size = statSync(f).size;
330
+ const fd = openSync(f, "r");
331
+ const buf = Buffer.alloc(Math.min(size, 16_384));
332
+ readSync(fd, buf, 0, buf.length, size - buf.length);
333
+ closeSync(fd);
334
+ text = buf.toString("utf8");
335
+ }
336
+ const lines = text.split("\n").filter((l) => l.trim());
337
+ let lastErr = -1;
338
+ for (let i = lines.length - 1; i >= 0; i--)
339
+ if (lines[i].startsWith('{"error"')) {
340
+ lastErr = i;
341
+ break;
342
+ }
343
+ if (lastErr < 0)
344
+ return null;
345
+ let at = NaN;
346
+ for (let i = lastErr - 1; i >= 0 && Number.isNaN(at); i--)
347
+ at = Date.parse(/^(\d{4}-\d\d-\d\dT[\d:.]+Z) /.exec(lines[i])?.[1] ?? "");
348
+ if (Number.isNaN(at) || nowMs - at > 120_000)
349
+ return null;
350
+ try {
351
+ const e = JSON.parse(lines[lastErr]);
352
+ return `${e.error ?? "error"}: ${(e.message ?? "").split("\n")[0].slice(0, 300)}`;
353
+ }
354
+ catch {
355
+ return lines[lastErr].slice(0, 300);
356
+ }
357
+ }
305
358
  /** The watcher's latest turn line (started, finished, FAILED, STOPPED, paused), for the report. */
306
359
  function lastTurnLine(ref) {
307
360
  const f = join(homedir(), ".bschat", "logs", `watch.${ref.replace("/", ".")}.err.log`);
@@ -421,9 +474,25 @@ export function prepare(opts = {}) {
421
474
  // Claude Code is optional on a machine; when it is there, say whether it can run agents.
422
475
  const claude = claudeFacts();
423
476
  if (claude) {
424
- steps.push({ step: "claude code", result: claude.logged_in ? "ok" : "failed", detail: claude.logged_in ? `${claude.version}, ${claude.login}` : `${claude.version} is not logged in: run claude auth login on this machine (over ssh it prints a link to open in your browser and asks for the code)` });
425
- const sb = claudeSandbox();
426
- steps.push({ step: "claude code sandbox", result: sb.ok ? "ok" : "failed", detail: sb.ok ? "sandboxed (workspace-write) Claude Code agents can run here" : `${sb.error}; only danger-full-access Claude Code agents can run here` });
477
+ steps.push({ step: "claude code", result: claude.logged_in ? "ok" : "failed", detail: claude.logged_in ? `${claude.version}, ${claude.login}` : `${claude.version}, ${claude.login}: run claude auth login on this machine (over ssh it prints a link to open in your browser and asks for the code)` });
478
+ let sb = claudeSandbox();
479
+ const userns = platform() === "linux" && /RTM_NEWADDR|uid map|Operation not permitted|Permission denied/i.test(sb.error ?? "");
480
+ if (sb.ok)
481
+ steps.push({ step: "claude code sandbox", result: "ok", detail: "sandboxed (workspace-write) Claude Code agents can run here" });
482
+ else if (!userns)
483
+ steps.push({ step: "claude code sandbox", result: "failed", detail: `${sb.error}; only danger-full-access Claude Code agents can run here` });
484
+ else if (!opts.bwrapUserns)
485
+ steps.push({ step: "claude code sandbox", result: "failed", detail: `${sb.error}: this system restricts the user namespaces bubblewrap needs. Re-run machine add with --bwrap-userns to install an AppArmor profile for /usr/bin/bwrap (${BWRAP_APPARMOR_PATH}; any local user may then use bubblewrap's namespaces), or run only danger-full-access Claude Code agents here` });
486
+ else if (!sudo)
487
+ steps.push({ step: "claude code sandbox", result: "failed", detail: `--bwrap-userns needs passwordless sudo; install ${BWRAP_APPARMOR_PATH} by hand (bschat machine prepare --print-apparmor shows it) and run sudo apparmor_parser -r on it` });
488
+ else {
489
+ const t = spawnSync("sudo", ["-n", "tee", BWRAP_APPARMOR_PATH], { input: bwrapAppArmorProfile(), stdio: ["pipe", "ignore", "pipe"], encoding: "utf8" });
490
+ const l = t.status === 0 ? spawnSync("sudo", ["-n", "apparmor_parser", "-r", BWRAP_APPARMOR_PATH], { encoding: "utf8" }) : t;
491
+ sb = claudeSandbox();
492
+ steps.push(l.status === 0 && sb.ok
493
+ ? { step: "claude code sandbox", result: "done", detail: `installed ${BWRAP_APPARMOR_PATH}; the sandbox works` }
494
+ : { step: "claude code sandbox", result: "failed", detail: l.status !== 0 ? `installing ${BWRAP_APPARMOR_PATH}: ${(l.stderr ?? "").trim()}` : `profile installed but the sandbox still fails: ${sb.error}` });
495
+ }
427
496
  }
428
497
  const req = "/etc/codex/requirements.toml";
429
498
  const { requirements, wrapper } = codexManagedHooks(requireInstall().bin);
@@ -466,8 +535,8 @@ export async function machine(p, out) {
466
535
  if (p.flags["print-hooks"])
467
536
  return out.print(codexManagedHooks(requireInstall().bin).requirements, codexManagedHooks(requireInstall().bin));
468
537
  if (p.flags["print-apparmor"])
469
- return out.print(codexAppArmorProfile(), { path: CODEX_APPARMOR_PATH, profile: codexAppArmorProfile() });
470
- const steps = prepare({ codexUserns: p.flags["codex-userns"] === true });
538
+ return out.print(`${CODEX_APPARMOR_PATH}:\n${codexAppArmorProfile()}\n${BWRAP_APPARMOR_PATH}:\n${bwrapAppArmorProfile()}`, { [CODEX_APPARMOR_PATH]: codexAppArmorProfile(), [BWRAP_APPARMOR_PATH]: bwrapAppArmorProfile() });
539
+ const steps = prepare({ codexUserns: p.flags["codex-userns"] === true, bwrapUserns: p.flags["bwrap-userns"] === true });
471
540
  return out.print(steps.map((s) => `${s.result.padEnd(8)} ${s.step}: ${s.detail}`).join("\n"), { steps });
472
541
  }
473
542
  if (sub === "service") {
@@ -241,7 +241,33 @@ export async function needsAdmin(p, out) {
241
241
  const r = await adminClient(p).call("GET", "/account/needs");
242
242
  if (!r.needs.length)
243
243
  return out.print("Nothing is waiting on you.", r);
244
- out.print(r.needs.map((n, i) => `${i + 1}. [${n.project}] ${n.kind === "unit_question" ? `WU #${n.unit}` : n.kind === "wake_broken" ? "wake path" : n.kind === "notifier" ? "your alerts" : "ask"} · ${n.asked_by} · since ${n.since.slice(0, 16).replace("T", " ")} UTC${n.blocks ? ` · waiting: ${n.blocks}` : ""}\n ${n.text.replace(/\n/g, "\n ")}${n.proposal ? `\n Proposed by ${n.proposed_by}: ${n.proposal.replace(/\n/g, "\n ")}` : ""}\n key: ${n.key}`).join("\n\n") + `\n\nAnswer with: bschat-admin answer <key> "decision", or bschat-admin answer <key> --approve [--note ".."] to accept a proposal`, r);
244
+ const ind = (t) => t.replace(/\n/g, "\n ");
245
+ out.print(r.needs.map((n, i) => [
246
+ `${i + 1}. [${n.project}] ${n.kind === "unit_question" ? `WU #${n.unit} question` : n.kind === "wake_broken" ? "wake path" : n.kind === "notifier" ? "your alerts" : n.kind === "machine_session" ? "machine" : "decision"} · ${n.asked_by} · since ${n.since.slice(0, 16).replace("T", " ")} UTC`,
247
+ n.plain ? ` In plain words: ${ind(n.plain)}` : n.unexplained ? ` In plain words: (${n.asked_by} did not explain this; bschat-admin explain ${n.key})` : null,
248
+ n.blocks ? ` What's stuck: ${ind(n.blocks)}` : null,
249
+ ` ${n.kind === "ask" ? "What I need from you: " : ""}${ind(n.text)}`,
250
+ n.if_yes ? ` If yes: ${ind(n.if_yes)}` : null,
251
+ n.if_no ? ` If no: ${ind(n.if_no)}` : null,
252
+ n.proposal ? ` Proposed by ${n.proposed_by}: ${ind(n.proposal)}` : null,
253
+ n.explanation ? ` Explained by ${n.explained_by}: ${ind(n.explanation)}` : n.explain_requested_at ? ` (explanation asked for ${n.explain_requested_at.slice(0, 16).replace("T", " ")} UTC)` : null,
254
+ ` key: ${n.key}`,
255
+ ].filter(Boolean).join("\n")).join("\n\n") + `\n\nAnswer with: bschat-admin answer <key> "decision", or bschat-admin answer <key> --approve [--note ".."] to accept a proposal; bschat-admin explain <key> asks the agent to explain it in plain words`, r);
256
+ }
257
+ /** bschat-admin explain <key>: the console's Explain; the agent is mentioned and asked to put it in plain words. */
258
+ export async function explainAdmin(rest, p, out) {
259
+ const key = rest[0];
260
+ if (!key)
261
+ throw new CliError("usage", "admin explain <key from admin needs>");
262
+ const c = adminClient(p);
263
+ const n = (await c.call("GET", "/account/needs")).needs.find((x) => x.key === key);
264
+ if (!n)
265
+ throw new CliError("not_found", `nothing waiting with key ${key}; list them with: bschat-admin needs`);
266
+ if (n.kind === "ask")
267
+ return out.print(`Asked ${n.asked_by} to explain; it appears with the decision (bschat-admin needs) and in the next report to you.`, await c.call("POST", `/projects/${n.project}/asks/${n.ask_id}/explain`, {}));
268
+ if (n.kind === "unit_question")
269
+ return out.print(`Asked for WU #${n.unit}'s question in plain words; it appears with the question (bschat-admin needs).`, await c.call("POST", `/projects/${n.project}/work-units/${n.unit}/question/explain`, {}));
270
+ throw new CliError("not_answerable", "only decisions (asks and unit questions) can be explained");
245
271
  }
246
272
  export async function answerAdmin(rest, p, out) {
247
273
  const [key, ...words] = rest;
@@ -177,6 +177,15 @@ export async function wu(p, out) {
177
177
  out.print(`${fmt(r.unit)}\nReopened: continue on the same branch and resubmit this unit.`, r);
178
178
  return;
179
179
  }
180
+ case "explain": {
181
+ // The operator asked (the banner's Explain) for the question on this unit in plain words.
182
+ const text = p.positionals.slice(3).join(" ").trim();
183
+ if (!text)
184
+ throw new CliError("usage", 'wu explain <n> "the question in plain words: what it is about, why it needs the operator, what to decide, what happens either way"');
185
+ const r = await client.call("POST", `${base}/${num()}/question/explanation`, { text });
186
+ out.print(`${fmt(r.unit)}\nExplained; the operator sees it with the question.`, r);
187
+ return;
188
+ }
180
189
  case "propose": {
181
190
  const text = (p.positionals.slice(3).join(" ") || str(p.flags, "propose") || "").trim();
182
191
  if (!text)
@@ -254,8 +263,14 @@ export async function wu(p, out) {
254
263
  case "done": {
255
264
  const def = await processDef();
256
265
  const merged = str(p.flags, "merged") ?? null;
257
- const landsIn = (await client.call("GET", `${base}/${num()}`)).unit.target ?? def.merge.target_branch;
258
- if (merged) {
266
+ const unit = (await client.call("GET", `${base}/${num()}`)).unit;
267
+ const landsIn = unit.target ?? def.merge.target_branch;
268
+ if (unit.replay_of) {
269
+ // A replay is an evaluation: it closes without merging (the server records it as evaluated).
270
+ if (merged)
271
+ throw new CliError("usage", `WU #${num()} is a replay, compared and never merged: close it without --merged`);
272
+ }
273
+ else if (merged) {
259
274
  // Where pushes are required the remote target is the truth, not this machine's copy of it.
260
275
  const target = def.merge.require_pushed ? (fetchRef(landsIn) ? `origin/${landsIn}` : null) : landsIn;
261
276
  if (target === null)
@@ -645,7 +660,10 @@ export async function lock(p, out) {
645
660
  ? `You hold ${lockName}${r.lock.machine ? ` on ${r.lock.machine}` : " (shared)"}${unit ? ` for WU #${unit}` : ""}. Release it when done: bschat unlock ${lockName}`
646
661
  : `${lockName} is held by ${r.lock.holder_name}${r.lock.unit ? ` (WU #${r.lock.unit})` : ""}; you are ${r.position === 1 ? "next" : `#${r.position} in line`}. You will be @mentioned when it is yours; do not poll. Leave the queue: bschat unlock ${lockName}`, r);
647
662
  }
648
- /** bschat ask-operator "question" [--blocks "what waits"] [--propose "recommended answer"]: a decision only the operator can make, on the record and reported to them. */
663
+ /**
664
+ * bschat ask-operator "what you need from them" --plain ".." --blocks ".." --if-yes ".." --if-no ".." [--propose ".."]:
665
+ * a decision only the operator can make, in a shape they can follow without the thread.
666
+ */
649
667
  export async function askOperator(p, out) {
650
668
  const name = resolveAgentName(str(p.flags, "as"));
651
669
  const creds = loadAgent(name);
@@ -654,10 +672,12 @@ export async function askOperator(p, out) {
654
672
  if (!project)
655
673
  throw new CliError("no_project", `${creds.agent} is an account-scoped agent; pass --project <name>`);
656
674
  const text = (p.positionals.slice(1).join(" ") || str(p.flags, "question") || "").trim();
657
- if (!text)
658
- throw new CliError("usage", 'ask-operator "the decision only the operator can make" [--blocks "what waits on it"] [--propose "your recommended answer, approvable as written"]');
675
+ const fields = { plain: str(p.flags, "plain") ?? "", blocks: str(p.flags, "blocks") ?? "", if_yes: str(p.flags, "if-yes") ?? "", if_no: str(p.flags, "if-no") ?? "" };
676
+ const missing = Object.entries({ "--plain": fields.plain, "--blocks": fields.blocks, "--if-yes": fields.if_yes, "--if-no": fields.if_no }).filter(([, v]) => !v.trim()).map(([k]) => k);
677
+ if (!text || missing.length)
678
+ 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(", ")}` : ""}`);
659
679
  const proposal = str(p.flags, "propose") ?? "";
660
- const r = await client.call("POST", `/projects/${project}/ask-operator`, { text, blocks: str(p.flags, "blocks") ?? "", proposal });
680
+ const r = await client.call("POST", `/projects/${project}/ask-operator`, { text, ...fields, proposal });
661
681
  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);
662
682
  }
663
683
  /**
@@ -691,3 +711,18 @@ async function roundUsage(client, base, n, name) {
691
711
  return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since, until, tokens: null, reason: `could not read the session: ${e.message}` };
692
712
  }
693
713
  }
714
+ /** bschat explain <ask-id> "...": the operator asked (the banner's Explain) for your request in plain words. */
715
+ export async function explainAsk(p, out) {
716
+ const name = resolveAgentName(str(p.flags, "as"));
717
+ const creds = loadAgent(name);
718
+ const client = Client.forAgent(creds, resolveModel(str(p.flags, "model"), process.env, process.cwd(), name), { effort: str(p.flags, "effort") });
719
+ const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
720
+ if (!project)
721
+ throw new CliError("no_project", `${creds.agent} is an account-scoped agent; pass --project <name>`);
722
+ const id = p.positionals[1];
723
+ const text = p.positionals.slice(2).join(" ").trim();
724
+ if (!id || !text)
725
+ throw new CliError("usage", 'explain <ask-id> "your request in plain words: what it is about, why it needs the operator, exactly what to do or decide, what happens on yes and on no"');
726
+ const r = await client.call("POST", `/projects/${project}/asks/${id}/explanation`, { text });
727
+ out.print("Explained; the operator sees it with your request, and it goes out with the next report to them.", r);
728
+ }
package/dist/harness.js CHANGED
@@ -307,6 +307,27 @@ export function codexManagedHooks(bin) {
307
307
  return { requirements, wrapper };
308
308
  }
309
309
  export const CODEX_APPARMOR_PATH = "/etc/apparmor.d/bschat-codex";
310
+ export const BWRAP_APPARMOR_PATH = "/etc/apparmor.d/bschat-bwrap";
311
+ /**
312
+ * An AppArmor profile that lets the system's bubblewrap create user namespaces, which Claude Code's
313
+ * Linux sandbox runs commands in. Broader than the Codex profile: any local user may then use
314
+ * bubblewrap to make a user namespace, as before Ubuntu 24.04 restricted them, so it is installed
315
+ * only when the operator opts in (machine add --bwrap-userns).
316
+ */
317
+ export function bwrapAppArmorProfile() {
318
+ return [
319
+ `# bschat: let bubblewrap create the user namespaces sandboxes (Claude Code) need (Ubuntu 24.04+ restricts them).`,
320
+ `# Written by bschat machine prepare --bwrap-userns; remove this file and run apparmor_parser -R on it to undo.`,
321
+ `abi <abi/4.0>,`,
322
+ `include <tunables/global>`,
323
+ ``,
324
+ `profile bschat-bwrap /usr/bin/bwrap flags=(unconfined) {`,
325
+ ` userns,`,
326
+ ` include if exists <local/bschat-bwrap>`,
327
+ `}`,
328
+ ``,
329
+ ].join("\n");
330
+ }
310
331
  /**
311
332
  * An AppArmor profile that lets only Codex's own binary create user namespaces, which its Linux
312
333
  * sandbox (bubblewrap, built into the binary) needs. Ubuntu 24.04+ restricts unprivileged user
package/dist/harnesses.js CHANGED
@@ -204,23 +204,51 @@ export function claudeSettings(sandbox, model, effort, cwd, bschatHome, extraWri
204
204
  };
205
205
  return [...common, "--permission-mode", "acceptEdits", ...dirs.flatMap((d) => ["--add-dir", d]), "--settings", JSON.stringify(settings)];
206
206
  }
207
- /** Claude Code's version and login (`claude auth status`), for the machine report. */
208
- export function claudeFacts() {
207
+ /**
208
+ * Claude Code's version and login, for the machine report. `claude auth status` only reads the stored
209
+ * credentials: on one machine it said logged in while every call failed with "401 OAuth access token
210
+ * is invalid". So the login is verified with one minimal call (`verifyClaudeLogin`), again whenever
211
+ * the credentials file changes and at most every 6 hours otherwise; only an authentication error
212
+ * counts as logged out, and any other failure is reported as unverified with its error.
213
+ */
214
+ export function claudeFacts(verify = verifyClaudeLoginCached) {
209
215
  const v = spawnSync("claude", ["--version"], { encoding: "utf8", timeout: 30_000 });
210
216
  if (v.status !== 0)
211
217
  return null;
212
218
  const s = spawnSync("claude", ["auth", "status"], { encoding: "utf8", timeout: 30_000 });
213
- let logged = false;
214
- let login = `${s.stdout ?? ""}${s.stderr ?? ""}`.trim();
219
+ let stored = false;
220
+ let method = "unknown method";
215
221
  try {
216
222
  const j = JSON.parse(s.stdout);
217
- logged = s.status === 0 && j.loggedIn === true;
218
- login = logged ? `logged in (${j.authMethod ?? "unknown method"})` : "not logged in";
223
+ stored = s.status === 0 && j.loggedIn === true;
224
+ method = j.authMethod ?? method;
219
225
  }
220
226
  catch {
221
- logged = false;
227
+ stored = false;
222
228
  }
223
- return { version: v.stdout.trim(), logged_in: logged, login: login.slice(0, 200) };
229
+ if (!stored)
230
+ return { version: v.stdout.trim(), logged_in: false, login: "not logged in", verified: { ok: false, error: "no stored login" } };
231
+ const verified = verify();
232
+ const login = verified.ok === true ? `logged in (${method})` : verified.ok === false ? `stored login rejected: ${verified.error}` : `logged in (${method}), not verified: ${verified.error}`;
233
+ return { version: v.stdout.trim(), logged_in: verified.ok !== false, login: login.slice(0, 200), verified };
234
+ }
235
+ /** One minimal headless call; ok false only when Claude Code reports an authentication failure. */
236
+ export function verifyClaudeLogin() {
237
+ const r = spawnSync("claude", ["-p", "Reply OK", "--model", "claude-haiku-4-5-20251001", "--output-format", "json"], { encoding: "utf8", timeout: 120_000, cwd: homedir() });
238
+ const error = claudeResultError(r.stdout ?? "") ?? (r.status !== 0 ? `${r.stderr ?? ""}`.trim().split("\n")[0] || `exit ${r.status}` : null);
239
+ if (!error)
240
+ return { ok: true, error: null };
241
+ return { ok: claudeIsAuthError(error) ? false : null, error: error.slice(0, 200) };
242
+ }
243
+ export const claudeIsAuthError = (e) => /401|403|authenticat|not logged in|\/login|oauth token|invalid api key/i.test(e);
244
+ let loginCache = null;
245
+ function verifyClaudeLoginCached() {
246
+ const cred = join(claudeHome(), ".credentials.json");
247
+ const key = existsSync(cred) ? String(statSync(cred).mtimeMs) : "keychain";
248
+ if (loginCache && loginCache.key === key && Date.now() - loginCache.at < 6 * 60 * 60_000)
249
+ return loginCache.result;
250
+ loginCache = { key, at: Date.now(), result: verifyClaudeLogin() };
251
+ return loginCache.result;
224
252
  }
225
253
  /**
226
254
  * Whether Claude Code's sandbox can run here. On macOS it uses the system's sandbox-exec; on Linux
package/dist/help.js CHANGED
@@ -79,7 +79,12 @@ Agent commands
79
79
  bschat wu escalate <n> [--note ..] the tag's expert: pass the question to the operator
80
80
  bschat wu wait <n> --on <m> | --clear owner or assigner: this unit cannot move until #m closes; reminders pause meanwhile
81
81
  bschat wu scope <n> --scope ".." --note ".." assigner or operator: amend what a unit covers; recorded and announced
82
- bschat ask-operator "question" [--blocks ".."] [--propose ".."] a decision only the operator can make: on their console banner and reported to them; never ask in chat.
82
+ bschat ask-operator "what you need from them" --plain ".." --blocks ".." --if-yes ".." --if-no ".." [--propose ".."]
83
+ a decision only the operator can make, on their console banner and reported to them; never
84
+ ask in chat. --plain: one or two sentences for someone who has not read the thread;
85
+ --blocks: what's stuck; --if-yes/--if-no: what happens on each answer
86
+ bschat explain <ask-id> "..." the operator asked you (Explain) to put your request in plain words
87
+ bschat wu explain <n> "..." the same for a unit's question waiting on the operator
83
88
  --propose: your recommended answer, phrased so they can approve it as written
84
89
  bschat wu tags <n> --add a --remove b retag (owner before review, a reviewer during it; may add a reviewer)
85
90
  bschat wu done <n> --merged <sha> [--keep-worktree] after approval; verifies the sha is on the target; removes the unit's clean worktree
@@ -197,15 +202,17 @@ bschat-admin login (approve it in your signed-in browser); the session lasts 30
197
202
  bschat-admin needs decisions waiting on you (asks, unit questions, broken wake paths, alert failures)
198
203
  bschat-admin answer <key> "decision" answer one; the asker is @mentioned
199
204
  bschat-admin answer <key> --approve [--note ".."] accept the proposal on an ask or a unit question as written
205
+ bschat-admin explain <key> ask the agent to explain a decision in plain words (the console's Explain)
200
206
  bschat-admin notifier [--agent name|none] [--email yes|no] [--repeat m] how you are reached away from the console, and the last report
201
207
  bschat-admin account [--summary-minutes m] plan, usage and the account summary period
202
208
  bschat-admin worktree forget <project> <id> delete a stale worktree record (never the directory)
203
209
 
204
210
  Machines (provisioned over your own ssh; a daemon on each runs the agent sessions you declare)
205
- bschat-admin machine add <name> --ssh <host> [--rotate] [--codex-userns] install Node and bschat (no sudo), linger, Codex check,
211
+ bschat-admin machine add <name> --ssh <host> [--rotate] [--codex-userns] [--bwrap-userns] install Node and bschat (no sudo), linger, Codex check,
206
212
  bschat's Codex hooks in /etc/codex (passwordless sudo only), register, start the daemon;
207
213
  --codex-userns: where Linux restricts user namespaces (Ubuntu 24.04+), install a
208
- Codex-only AppArmor profile so sandboxed agents can run
214
+ Codex-only AppArmor profile so sandboxed agents can run; --bwrap-userns: the same
215
+ for /usr/bin/bwrap (Claude Code's sandbox; broader: any local user may use it)
209
216
  bschat-admin machine list | show <name> | remove <name>
210
217
  bschat-admin machine session add <machine> <project>/<agent> --dir <checkout> --sandbox <read-only|workspace-write|danger-full-access>
211
218
  [--create --role <role>] [--model m] [--effort e] [--thread <id>] [--turn-timeout min]
package/dist/index.js CHANGED
@@ -17,7 +17,7 @@ import { turnHarness } from "./harnesses.js";
17
17
  import { machine } from "./commands/machine.js";
18
18
  import { doctor, install } from "./commands/install.js";
19
19
  import { warnIfForeignCopy } from "./install.js";
20
- import { processCmd, record, wu, milestones, milestone, lock, askOperator } from "./commands/wu.js";
20
+ import { processCmd, record, wu, milestones, milestone, lock, askOperator, explainAsk } from "./commands/wu.js";
21
21
  import { worktrees } from "./commands/worktrees.js";
22
22
  import { CliError } from "./errors.js";
23
23
  import { HELP } from "./help.js";
@@ -78,6 +78,7 @@ const COMMANDS = {
78
78
  unlock: lock,
79
79
  locks: lock,
80
80
  "ask-operator": askOperator,
81
+ explain: explainAsk,
81
82
  worktrees,
82
83
  follow: a.followCmd,
83
84
  unfollow: a.followCmd,
package/dist/state.js CHANGED
@@ -1,4 +1,5 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { CliError } from "./errors.js";
2
3
  import { join } from "node:path";
3
4
  import { configRoot, isRef, splitRef } from "./config.js";
4
5
  /** State is keyed by agent ref (`<scope>/<name>`), like credentials. */
@@ -23,10 +24,30 @@ export function readState(ref, env = process.env) {
23
24
  adoptLegacyState(ref, env);
24
25
  if (!existsSync(p))
25
26
  return { inbox_after: "", last_check: 0 };
26
- return { inbox_after: "", last_check: 0, ...JSON.parse(readFileSync(p, "utf8")) };
27
+ const text = readFileSync(p, "utf8");
28
+ let saved;
29
+ try {
30
+ saved = JSON.parse(text);
31
+ }
32
+ catch {
33
+ // Never started over silently: cursors, wake numbers and follows live here.
34
+ throw new CliError("corrupt_state", `${p} is not valid JSON (${text.length} bytes): a write to it was cut short`, "Check free disk space on this machine, then repair the file or move it aside (the agent then starts from fresh cursors and its wake-up numbering restarts)");
35
+ }
36
+ return { inbox_after: "", last_check: 0, ...saved };
27
37
  }
28
38
  export function writeState(agent, state, env = process.env) {
29
39
  const p = statePath(agent, env);
30
40
  mkdirSync(join(p, ".."), { recursive: true });
31
- writeFileSync(p, JSON.stringify(state, null, 2) + "\n", { mode: 0o600 });
41
+ // Written beside it and renamed over it: a full disk once truncated three agents' files to 0
42
+ // bytes mid-write, and their watchers failed on every start for 17 hours. A failed write now
43
+ // throws and leaves the previous file whole.
44
+ const tmp = `${p}.${process.pid}.tmp`;
45
+ try {
46
+ writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 0o600 });
47
+ renameSync(tmp, p);
48
+ }
49
+ catch (e) {
50
+ rmSync(tmp, { force: true });
51
+ throw e;
52
+ }
32
53
  }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.66";
1
+ export const CLI_VERSION = "0.12.70";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.66",
3
+ "version": "0.12.70",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {