benignswarm 0.12.155 → 0.12.156

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
@@ -15,7 +15,7 @@ export const STRING_FLAGS = [
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",
18
- "scope-file", "scope-from", "append", "pr", "note", "note-file", "add", "remove", "merged", "tag",
18
+ "session-harness", "session-sandbox", "session-machine", "session-machine-label", "scope-file", "scope-from", "append", "pr", "note", "note-file", "add", "remove", "merged", "tag",
19
19
  "activity", "max-unanswered", "to", "replay-of", "branch", "base", "effort", "max-budget-usd", "by", "target", "lands-with",
20
20
  "milestone", "file", "exit", "depends-on", "default-tags", "source", "on", "partial", "question", "ruling",
21
21
  "gaps", "unit", "units", "blocks", "sla", "takeover", "stall", "max-open", "max-in-progress", "require-scope",
@@ -42,7 +42,7 @@ export const STRING_FLAGS = [
42
42
  export const BOOL_FLAGS = [
43
43
  "latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels",
44
44
  "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "template", "scope-only", "unread",
45
- "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "log",
45
+ "clear-session", "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "log",
46
46
  "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive",
47
47
  "approve", "turn", "service", "print-hooks", "create", "rotate", "drain", "codex-userns", "bwrap-userns", "agy-userns", "print-apparmor", "overdue",
48
48
  "cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "assessment-only", "continue",
@@ -10,6 +10,7 @@ import { domainToASCII, fileURLToPath } from "node:url";
10
10
  export const CLAUDE_SECRET_EGRESS_OUTER_BOUNDARY = "bwrap-unshare-net-egress-proxy";
11
11
  const EGRESS_RUNNER_CONFIG_ENV = "B9S_CLAUDE_EGRESS_RUNNER_CONFIG";
12
12
  const DNS_HOSTNAME_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
13
+ const DARWIN_UNIX_SOCKET_PATH_MAX_BYTES = 103; // sockaddr_un.sun_path includes a trailing NUL byte.
13
14
  export function isIpv4Literal(host) {
14
15
  if (!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(host))
15
16
  return false;
@@ -40,6 +41,22 @@ export function normalizeEgressHostname(rawHost) {
40
41
  export function isInternalOrLocalHostname(host) {
41
42
  return host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal");
42
43
  }
44
+ function unixSocketPathLimit() {
45
+ if (platform() === "darwin")
46
+ return DARWIN_UNIX_SOCKET_PATH_MAX_BYTES;
47
+ if (platform() === "linux")
48
+ return 107;
49
+ return null;
50
+ }
51
+ function assertUnixSocketPathFits(path) {
52
+ const limit = unixSocketPathLimit();
53
+ if (limit === null)
54
+ return;
55
+ const length = Buffer.byteLength(path);
56
+ if (length > limit) {
57
+ throw new Error(`Claude egress Unix socket path is ${length} bytes; this platform allows at most ${limit}. Choose a shorter runtime directory.`);
58
+ }
59
+ }
43
60
  /** Strict host validation shared between project secret host declarations and the outer proxy. */
44
61
  export function validateDeclaredSecretHosts(rawHosts, allowEmpty = false) {
45
62
  if (!Array.isArray(rawHosts) || (!allowEmpty && rawHosts.length < 1) || rawHosts.length > 50 || rawHosts.some((h) => typeof h !== "string")) {
@@ -766,14 +783,20 @@ export async function startClaudeEgressProxy(opts) {
766
783
  resolveFn: opts.resolve ?? ((host) => lookup(host, { all: true, verbatim: true })),
767
784
  connectFn: opts.connect ?? ((address, port) => createConnection({ host: address, port })),
768
785
  };
769
- const socketDir = opts.socketDir ?? join(tmpdir(), `b9s-claude-egress-${process.pid}-${randomBytes(6).toString("hex")}`);
786
+ // Unix socket names have a small kernel limit. Keep these private sockets in
787
+ // the short, canonical system temp directory rather than inheriting an
788
+ // arbitrarily long TMPDIR from a user or test runner.
789
+ const socketBase = platform() === "darwin" || platform() === "linux" ? realpathSync("/tmp") : tmpdir();
790
+ const socketDir = opts.socketDir ?? join(socketBase, `b9s-egress-${process.pid}-${randomBytes(6).toString("hex")}`);
791
+ const httpSocketPath = join(socketDir, "http.sock");
792
+ const socksSocketPath = join(socketDir, "socks.sock");
793
+ assertUnixSocketPathFits(httpSocketPath);
794
+ assertUnixSocketPathFits(socksSocketPath);
770
795
  mkdirSync(socketDir, { recursive: true, mode: 0o700 });
771
796
  try {
772
797
  chmodSync(socketDir, 0o700);
773
798
  }
774
799
  catch { /* ignore */ }
775
- const httpSocketPath = join(socketDir, "http.sock");
776
- const socksSocketPath = join(socketDir, "socks.sock");
777
800
  const { httpProxyPort, socksProxyPort } = opts.httpPort && opts.socksPort
778
801
  ? { httpProxyPort: opts.httpPort, socksProxyPort: opts.socksPort }
779
802
  : await allocateClaudeEgressPortPair();
package/dist/client.js CHANGED
@@ -19,6 +19,8 @@ function expectedTextReceiptFields(method, path, body, response) {
19
19
  return strings("text");
20
20
  if (verb === "POST" && /^\/projects\/[^/]+\/channels$/.test(route))
21
21
  return strings("topic");
22
+ if (verb === "POST" && /^\/projects\/[^/]+\/pause$/.test(route))
23
+ return strings("note");
22
24
  if (verb === "POST" && route === "/machine-operations")
23
25
  return strings("ssh_host");
24
26
  if (verb === "POST" && /^\/projects\/[^/]+\/machines\/[^/]+\/jobs$/.test(route))
@@ -136,7 +138,7 @@ function expectedTextReceiptFields(method, path, body, response) {
136
138
  }
137
139
  if (["approve", "changes", "proceed"].includes(action))
138
140
  return strings("note", "unmet");
139
- if (["park", "requeue", "decline", "classify", "tags", "reopen", "supersede", "done", "abandon", "merge", "evidence/replace", "restore", "note", "hold", "hold/release", "question/escalate"].includes(action))
141
+ if (["park", "unpark", "requeue", "decline", "classify", "tags", "reopen", "supersede", "done", "abandon", "merge", "evidence/replace", "restore", "note", "hold", "hold/release", "question/escalate"].includes(action))
140
142
  return strings("note");
141
143
  }
142
144
  if (verb === "POST" && milestone.test(route)) {
@@ -286,6 +288,10 @@ function expectedStoredText(method, path, body, response) {
286
288
  const stored = {};
287
289
  if (verb === "POST" && /^\/projects\/[^/]+\/work-units\/\d+\/head$/.test(route) && typeof fields.reason === "string")
288
290
  stored.reason = fields.reason.trim();
291
+ if (verb === "POST" && /^\/projects\/[^/]+\/work-units\/\d+\/unpark$/.test(route) && typeof fields.note === "string")
292
+ stored.note = fields.note.trim();
293
+ if (verb === "POST" && /^\/projects\/[^/]+\/pause$/.test(route) && typeof fields.note === "string")
294
+ stored.note = fields.note.trim();
289
295
  if (verb === "POST" && /^\/projects\/[^/]+\/asks\/[^/]+\/answer$/.test(route) && typeof fields.answer === "string" && fields.answer.trim()) {
290
296
  const receipts = Array.isArray(response?.receipts) ? response.receipts : [];
291
297
  if (!receipts.some((receipt) => receipt?.field === "answer"))
@@ -129,7 +129,9 @@ export async function admin(p, out) {
129
129
  return;
130
130
  }
131
131
  case "needs":
132
- return needsAdmin(p, out);
132
+ if (rest.length > 0)
133
+ throw new CliError("usage", "needs [project]");
134
+ return needsAdmin(p, out, action);
133
135
  case "flow":
134
136
  return flowAdmin(action, rest, p, out);
135
137
  case "diag":
@@ -350,8 +352,23 @@ async function project(action, rest, p, out) {
350
352
  const r = await c.call("DELETE", `/projects/${rest[0]}`);
351
353
  out.print(`deleted project ${rest[0]} and all its data`, r);
352
354
  }
355
+ else if ((action === "pause" || action === "resume") && rest.length === 1) {
356
+ const projectName = rest[0];
357
+ const base = `/projects/${encodeURIComponent(projectName)}`;
358
+ if (action === "pause") {
359
+ const note = need(p.flags, "note").trim();
360
+ if (!note)
361
+ throw new CliError("usage", "admin project pause <project> --note \"why it is paused\"");
362
+ const r = await c.call("POST", `${base}/pause`, { note });
363
+ out.print(`Paused project ${projectName} by ${r.paused.by}: ${r.paused.note}`, r);
364
+ }
365
+ else {
366
+ const r = await c.call("POST", `${base}/resume`, {});
367
+ out.print(`Resumed project ${projectName}; stall clocks restart at ${r.resumed_at}.`, r);
368
+ }
369
+ }
353
370
  else
354
- throw new CliError("usage", "admin project create|list|delete <name>");
371
+ throw new CliError("usage", 'admin project create|list|delete <name> | pause <project> --note "why" | resume <project>');
355
372
  }
356
373
  async function agent(action, rest, p, out) {
357
374
  const c = adminClient(p);
@@ -571,6 +588,18 @@ async function role(action, rest, p, out) {
571
588
  throw new CliError("usage", "admin role create|edit|list|delete <name> [--project p] [--projects a,b|*] [--post ch1,ch2] [--broadcast] [--create-channels] [--read-account-status] [--assign-outside-qualifications yes|no] [--judges yes|no] [--description d] [--cardinality one|many]");
572
589
  }
573
590
  async function workUnitAdmin(action, rest, p, out) {
591
+ if ((action === "park" || action === "unpark") && rest.length === 2 && /^\d+$/.test(rest[1])) {
592
+ const [projectName, numberText] = rest;
593
+ const number = Number(numberText);
594
+ const path = `/projects/${encodeURIComponent(projectName)}/work-units/${number}/${action}`;
595
+ const note = need(p.flags, "note").trim();
596
+ const body = { note };
597
+ if (!note)
598
+ throw new CliError("usage", `admin wu ${action} <project> <n> --note "why ${action === "park" ? "it is parked" : "it is unparked"}"`);
599
+ const r = await adminClient(p).call("POST", path, body);
600
+ out.print(action === "park" ? `Parked WU #${number} in ${projectName}.` : `Unparked WU #${number} in ${projectName}.`, r);
601
+ return;
602
+ }
574
603
  if (action === "head" && rest[0] && /^\d+$/.test(rest[1] ?? "")) {
575
604
  const project = rest[0];
576
605
  const number = Number(rest[1]);
@@ -632,7 +661,7 @@ async function workUnitAdmin(action, rest, p, out) {
632
661
  return runRequiredClassUpdate(adminClient(p), rest[0], Number(rest[1]), p, out);
633
662
  }
634
663
  if (action !== "assign" || !rest[0] || !/^\d+$/.test(rest[1] ?? ""))
635
- throw new CliError("usage", 'b9s-admin wu assign <project> <n> --to <agent> [--reason "why"] | b9s-admin wu done <project> <n> --merged <sha> [--gate-override-note "why"] | b9s-admin wu merged-sha <project> <n> --sha <full-sha> --reason "why" | b9s-admin wu required-class <project> <n> (--class p/h/m/e | --clear) --reason "why"');
664
+ throw new CliError("usage", 'b9s-admin wu assign <project> <n> --to <agent> [--reason "why"] | park|unpark <project> <n> --note "why" | b9s-admin wu done <project> <n> --merged <sha> [--gate-override-note "why"] | b9s-admin wu merged-sha <project> <n> --sha <full-sha> --reason "why" | b9s-admin wu required-class <project> <n> (--class p/h/m/e | --clear) --reason "why"');
636
665
  const to = str(p.flags, "to");
637
666
  if (!to)
638
667
  throw new CliError("usage", 'b9s-admin wu assign <project> <n> --to <agent> [--reason "why"]');
@@ -124,11 +124,11 @@ export async function who(p, out) {
124
124
  const { client, creds } = agentClient(p);
125
125
  const projectStalls = async (project) => {
126
126
  const response = await client.call("GET", `/projects/${encodeURIComponent(project)}/work-units?all=1`);
127
- return (response.units ?? []).filter((unit) => unit.stalled).map((unit) => ({ number: unit.number, owner_name: unit.owner_name, age_minutes: unit.stalled.age_minutes, reason: unit.stalled.reason }));
127
+ return (response.units ?? []).filter((unit) => unit.stalled?.kind === "stalled").map((unit) => ({ number: unit.number, owner_name: unit.owner_name, label: unit.stalled.label, reason: unit.stalled.reason }));
128
128
  };
129
129
  const statusLines = (statuses, stalled) => statuses.map((status) => {
130
130
  const owned = stalled.filter((unit) => unit.owner_name === status.agent_name);
131
- return `${fmtStatus(status)}${owned.length ? `\n stalled work: ${owned.map((unit) => `WU #${unit.number} · ${unit.age_minutes} min · ${unit.reason}`).join("; ")}` : ""}`;
131
+ return `${fmtStatus(status)}${owned.length ? `\n stalled work: ${owned.map((unit) => `WU #${unit.number} · ${unit.label} · ${unit.reason}`).join("; ")}` : ""}`;
132
132
  });
133
133
  if (bool(p.flags, "account") || (!creds.project && !str(p.flags, "project") && !process.env.BSCHAT_PROJECT)) {
134
134
  const [r, me] = await Promise.all([client.call("GET", "/account/agents/status"), client.call("GET", "/me")]);
@@ -234,7 +234,7 @@ export async function gatherUpdates(name, opts) {
234
234
  try {
235
235
  const work = await client.call("GET", `/projects/${encodeURIComponent(project)}/work-units?agent=${encodeURIComponent(creds.agent)}`);
236
236
  const activeStalls = new Set();
237
- for (const unit of (work.units ?? []).filter((item) => item.owner_name === creds.agent && item.stalled)) {
237
+ for (const unit of (work.units ?? []).filter((item) => item.owner_name === creds.agent && item.stalled?.kind === "stalled")) {
238
238
  const key = `${project}/${unit.number}`;
239
239
  activeStalls.add(key);
240
240
  const episode = unit.stalled.since;
@@ -243,7 +243,7 @@ export async function gatherUpdates(name, opts) {
243
243
  continue;
244
244
  }
245
245
  if (stalledNext[key] !== episode) {
246
- stalledLines.push(` ${creds.project ? "" : `[${project}] `}WU #${unit.number}: stalled ${unit.stalled.age_minutes} min · ${unit.stalled.reason} — b9s wu show ${creds.project ? "" : `--project ${project} `}${unit.number}`);
246
+ stalledLines.push(` ${creds.project ? "" : `[${project}] `}WU #${unit.number}: ${unit.stalled.label} · ${unit.stalled.reason} — b9s wu show ${creds.project ? "" : `--project ${project} `}${unit.number}`);
247
247
  stalledNext[key] = episode;
248
248
  }
249
249
  }
@@ -1740,6 +1740,15 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1740
1740
  out.push({ id: s.id, state: "error", dir: s.dir, thread: th, watcher: watcherState, error: `its watcher keeps exiting: ${fault}` });
1741
1741
  continue;
1742
1742
  }
1743
+ // WU #751: mirror the operator's project pause into the agent's state, so its watcher starts no new turn
1744
+ // while the project is paused (a running turn finishes). Written only when it changes.
1745
+ const pausedKey = s.project_paused ? s.project_paused.at : "";
1746
+ if ((state.sessions[s.id].project_paused_applied ?? "") !== pausedKey) {
1747
+ const paused = s.project_paused ?? undefined;
1748
+ updateState(s.agent, (onDisk) => ({ ...onDisk, project_paused: paused }), agentStateEnv);
1749
+ state.sessions[s.id].project_paused_applied = pausedKey;
1750
+ log(`${s.agent}: project ${paused ? `paused since ${paused.at}; no new turns` : "resumed; turns may start"}`);
1751
+ }
1743
1752
  // The operator lifted a usage-limit pause: what b9s codex unpause does, here.
1744
1753
  if (s.unpause_at && state.sessions[s.id].unpause_applied !== s.unpause_at) {
1745
1754
  const unpausedAt = Date.parse(s.unpause_at);
@@ -2987,7 +2996,7 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
2987
2996
  const isDarwin = hostPlatform === "darwin";
2988
2997
  const pageSizeResult = hostPlatform === "linux"
2989
2998
  ? spawnSync("getconf", ["PAGESIZE"], { encoding: "utf8", timeout: 2_000 })
2990
- : isDarwin ? spawnSync("sysctl", ["-n", "hw.pagesize"], { encoding: "utf8", timeout: 2_000 }) : null;
2999
+ : null;
2991
3000
  const pageSize = pageSizeResult?.status === 0 ? parsePageSize(pageSizeResult.stdout ?? "") : null;
2992
3001
  const macSwapResult = isDarwin ? spawnSync("sysctl", ["-n", "vm.swapusage"], { encoding: "utf8", timeout: 2_000 }) : null;
2993
3002
  const macVmStatResult = isDarwin ? spawnSync("vm_stat", [], { encoding: "utf8", timeout: 2_000 }) : null;
@@ -321,17 +321,18 @@ function packetLines(j) {
321
321
  lines.push("packet: expired or not retained");
322
322
  return lines.join("\n");
323
323
  }
324
- export async function needsAdmin(p, out) {
325
- const r = await adminClient(p).call("GET", "/account/needs");
324
+ export async function needsAdmin(p, out, project) {
325
+ const r = await adminClient(p).call("GET", project ? `/projects/${encodeURIComponent(project)}/needs` : "/account/needs");
326
326
  if (!r.needs.length)
327
- return out.print("Nothing is waiting on you.", r);
327
+ return out.print(project ? `Nothing waiting in ${r.project?.name ?? project}.` : "Nothing is waiting on you.", r);
328
328
  const ind = (t) => t.replace(/\n/g, "\n ");
329
329
  out.print(r.needs.map((n, i) => [
330
- `${i + 1}. [${n.project || "Account"}] ${n.display_id ?? (n.kind === "unit_question" ? `WU #${n.unit} question` : "decision id unavailable")} · ${n.kind === "unit_question" ? "unit question" : n.kind === "wake_broken" || n.kind === "wake_unresponsive" ? "wake path" : n.kind === "notifier" ? "your alerts" : n.kind === "machine_report_refused" ? "machine report refused" : n.kind === "machine_session" ? "machine" : n.kind === "lock_silent" ? "silent lock job" : "decision"} · ${n.asked_by} · since ${n.since.slice(0, 16).replace("T", " ")} UTC`,
330
+ `${i + 1}. [${n.project || "Account"}] ${n.display_id ?? (n.kind === "unit_question" ? `WU #${n.unit} question` : n.kind === "sendback_reviewer_gap" ? "send-back reviewer gap" : "decision id unavailable")} · ${n.kind === "unit_question" ? "unit question" : n.kind === "wake_broken" || n.kind === "wake_unresponsive" ? "wake path" : n.kind === "sendback_reviewer_gap" ? "send-back reviewer gap" : n.kind === "notifier" ? "your alerts" : n.kind === "machine_report_refused" ? "machine report refused" : n.kind === "machine_session" ? "machine" : n.kind === "lock_silent" ? "silent lock job" : "decision"} · ${n.asked_by} · since ${n.since.slice(0, 16).replace("T", " ")} UTC`,
331
331
  ` Console: ${consoleLink("decision", n.project, n.key)}`,
332
332
  n.plain ? ` In plain words: ${ind(n.plain)}` : n.unexplained ? ` In plain words: (${n.asked_by} did not explain this; b9s-admin explain ${n.key})` : null,
333
333
  n.blocks ? ` What's stuck: ${ind(n.blocks)}` : null,
334
334
  ` ${n.kind === "ask" ? "What I need from you: " : ""}${ind(n.text)}`,
335
+ n.kind === "sendback_reviewer_gap" ? ` Next: staff ${n.required_role ?? "the send-back reviewer"} at ${n.required_model ?? "the required model"} in the project's Process settings.` : null,
335
336
  n.if_yes ? ` If yes: ${ind(n.if_yes)}` : null,
336
337
  n.if_no ? ` If no: ${ind(n.if_no)}` : null,
337
338
  n.proposal ? ` Proposed by ${n.proposed_by}: ${ind(n.proposal)}` : null,
@@ -34,7 +34,7 @@ import { collectPruneProtection } from "../prune-protection.js";
34
34
  import { bootTimeMs } from "../boot-time.js";
35
35
  import { DEFAULT_WATCH_STARTUP_JITTER_SECONDS, MAX_WATCH_STARTUP_JITTER_SECONDS, waitForWatcherStartup } from "../startup-jitter.js";
36
36
  import { macMemoryFloorRefusal, parseMemoryEvents } from "../watcher-memory.js";
37
- import { parseMacVmStat, parsePageSize } from "../machine-telemetry.js";
37
+ import { parseMacVmStat, parseMacVmStatPageSize } from "../machine-telemetry.js";
38
38
  function omitMeasuresAlreadyIn(text, updates) {
39
39
  if (!text)
40
40
  return updates;
@@ -1313,12 +1313,11 @@ export function cgroupOomFailureReason(exit, before, after) {
1313
1313
  ? `systemd watcher cgroup OOM-killed the turn (memory.events oom_kill increased from ${before} to ${after})`
1314
1314
  : null;
1315
1315
  }
1316
- function macTurnMemoryFloorRefusal() {
1317
- const pageSizeResult = spawnSync("sysctl", ["-n", "hw.pagesize"], { encoding: "utf8", timeout: 2_000 });
1318
- const vmStatResult = spawnSync("vm_stat", [], { encoding: "utf8", timeout: 2_000 });
1319
- const pageSize = pageSizeResult.status === 0 ? parsePageSize(pageSizeResult.stdout ?? "") : null;
1320
- const memory = vmStatResult.status === 0 ? parseMacVmStat(vmStatResult.stdout ?? "", pageSize) : null;
1321
- return macMemoryFloorRefusal(totalmem(), memory?.available_bytes ?? null);
1316
+ export function macTurnMemoryFloorRefusal(run = spawnSync, totalMemoryBytes = totalmem()) {
1317
+ const vmStatResult = run("vm_stat", [], { encoding: "utf8", timeout: 2_000 });
1318
+ const vmStat = vmStatResult.status === 0 ? vmStatResult.stdout ?? "" : "";
1319
+ const memory = vmStatResult.status === 0 ? parseMacVmStat(vmStat, parseMacVmStatPageSize(vmStat)) : null;
1320
+ return macMemoryFloorRefusal(totalMemoryBytes, memory?.available_bytes ?? null);
1322
1321
  }
1323
1322
  function turnMemoryFloorAllows(log) {
1324
1323
  if (process.platform !== "darwin")
@@ -1576,6 +1575,15 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
1576
1575
  log(`the turn started at ${ph.startedAt} has written nothing for ${Math.round(quietMs / 60_000)} min (over the ${timeoutMin}-min limit); treating it as dead`);
1577
1576
  ctl.loggedRunning = ph.startedAt;
1578
1577
  }
1578
+ // WU #751: the operator paused this agent's project (the daemon records it from the session list): no new
1579
+ // turn until it is resumed. A running turn was already handled above and finishes on its own.
1580
+ const projectPaused = readState(name).project_paused;
1581
+ if (projectPaused) {
1582
+ if (ctl.loggedRunning !== `paused:${projectPaused.at}`)
1583
+ log(`project paused since ${projectPaused.at.slice(0, 16)}: starting no new turns until it is resumed`);
1584
+ ctl.loggedRunning = `paused:${projectPaused.at}`;
1585
+ return;
1586
+ }
1579
1587
  // A maintenance window on this machine: no new turn from 15 min before it until it ends.
1580
1588
  const maint = drainingUntil(undefined, undefined, env);
1581
1589
  if (maint) {
@@ -22,6 +22,7 @@ import { formatStandingRuleSet } from "../standing-rules.js";
22
22
  import { projectOf } from "./agent.js";
23
23
  import { consoleLink } from "../console-links.js";
24
24
  import { isAntigravityWorkspaceWrite } from "../antigravity.js";
25
+ const waitAge = (minutes) => minutes < 60 ? `${minutes}m` : minutes < 24 * 60 ? `${Math.floor(minutes / 60)}h` : `${Math.floor(minutes / (24 * 60))}d`;
25
26
  /** Only Claude's workspace-write sandbox needs SSH origins rewritten for its HTTP-only proxy. */
26
27
  export function shouldInheritClaudeSandboxUrlRewrites(env = process.env) {
27
28
  return env.CLAUDECODE === "1" && env.BSCHAT_CLAUDE_SANDBOX === "workspace-write";
@@ -630,7 +631,8 @@ export async function wu(p, out) {
630
631
  const reviewers = u.reviewers.map((r) => `${r.name}${r.tags.length ? ` for ${r.tags.map((t) => `#${t}`).join(" ")}` : ""}`).join(", ");
631
632
  const approvals = u.approvals.map((a) => a.name).join(", ");
632
633
  return [
633
- `WU #${u.number} [${u.status}]${u.stalled ? ` STALLED ${u.stalled.age_minutes}m · ${u.stalled.reason}` : ""} ${tags(u)} ${u.title}${flags ? ` (${flags})` : ""}${u.requires?.length ? `\n requires: ${u.requires.join(", ")}` : ""}`,
634
+ `WU #${u.number} [${u.status}]${u.stalled ? ` ${u.stalled.kind === "stalled" ? "STALLED" : `WAITING ${u.stalled.kind}`} · ${u.stalled.label} · ${u.stalled.reason}` : ""} ${tags(u)} ${u.title}${flags ? ` (${flags})` : ""}${u.requires?.length ? `\n requires: ${u.requires.join(", ")}` : ""}`,
635
+ u.session_requirement ? ` session requirement: ${Object.entries(u.session_requirement).map(([key, value]) => `${key}=${value}`).join(", ")}` : null,
634
636
  u.candidate_record?.tags?.length ? ` ${u.candidate_record.agent} first-round approval: ${u.candidate_record.tags.map((x) => `#${x.tag} ${x.approved_first_round}/${x.units} (${Math.round(x.rate * 100)}%)`).join(", ")}` : null,
635
637
  ` owner ${u.owner_name || "unassigned (queued)"}${reviewers ? ` · reviewers ${reviewers}` : ""}${approvals ? ` · approved by ${approvals}` : ""}${u.uncovered?.length ? ` · awaiting ${u.uncovered.map((t) => `#${t}`).join(" ")}` : ""}`,
636
638
  Object.keys(u.tag_focus ?? {}).length ? ` review focus:\n${Object.entries(u.tag_focus).map(([tag, focus]) => ` #${tag}: ${focus}`).join("\n")}` : null,
@@ -678,6 +680,13 @@ export async function wu(p, out) {
678
680
  // when require_scope is off and no tagged template requires sections.
679
681
  return scope;
680
682
  };
683
+ const sessionRequirement = () => {
684
+ const fields = { harness: str(p.flags, "session-harness"), sandbox: str(p.flags, "session-sandbox"), machine: str(p.flags, "session-machine"), machine_label: str(p.flags, "session-machine-label") };
685
+ const entries = Object.entries(fields).filter(([, value]) => value !== undefined);
686
+ if (bool(p.flags, "clear-session") && entries.length)
687
+ throw new CliError("usage", "--clear-session cannot be combined with session requirement flags");
688
+ return bool(p.flags, "clear-session") ? null : entries.length ? Object.fromEntries(entries) : undefined;
689
+ };
681
690
  // The project's sparse-checkout exclusions (b9s-admin project checkout), for new worktrees.
682
691
  const checkoutExclude = async () => (await client.call("GET", `/projects/${project}/process`)).checkout?.exclude ?? [];
683
692
  switch (sub) {
@@ -694,7 +703,7 @@ export async function wu(p, out) {
694
703
  const priority = str(p.flags, "priority");
695
704
  if (priority !== undefined && priority !== "normal" && priority !== "urgent")
696
705
  throw new CliError("usage", "--priority must be urgent or normal");
697
- const r = await client.call("POST", base, { client_id: clientId, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), 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 });
706
+ const r = await client.call("POST", base, { client_id: clientId, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), ...(sessionRequirement() === undefined ? {} : { session_requirement: sessionRequirement() }), 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 });
698
707
  const n = r.unit.number;
699
708
  const created = createdReceipt(r.unit, r);
700
709
  if (r.unit.waiting_on != null) {
@@ -735,6 +744,8 @@ export async function wu(p, out) {
735
744
  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>]');
736
745
  const existingNumber = Number(p.positionals[2]);
737
746
  if (Number.isInteger(existingNumber) && existingNumber > 0 && p.positionals.length === 3) {
747
+ if (sessionRequirement() !== undefined)
748
+ throw new CliError("usage", "amend an existing unit session requirement with wu scope before assigning it");
738
749
  if (p.flags.after !== undefined)
739
750
  throw new CliError("usage", "--after applies when creating a unit; use b9s wu wait to change an existing unit's wait");
740
751
  const r = await client.call("POST", `${base}/${existingNumber}/assign`, { to, ...(reason === undefined ? {} : { reason }) });
@@ -753,7 +764,7 @@ export async function wu(p, out) {
753
764
  const scope = await scopeText();
754
765
  const replay = str(p.flags, "replay-of");
755
766
  const clientId = randomUUID();
756
- const r = await client.call("POST", `${base}/assign`, { client_id: clientId, to, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: explicitBranch, ...(baseFlag !== undefined ? { base: baseFlag } : {}), ...(continueFlag ? { continue: true } : {}), 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 });
767
+ const r = await client.call("POST", `${base}/assign`, { client_id: clientId, to, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), ...(sessionRequirement() === undefined ? {} : { session_requirement: sessionRequirement() }), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: explicitBranch, ...(baseFlag !== undefined ? { base: baseFlag } : {}), ...(continueFlag ? { continue: true } : {}), 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 });
757
768
  const clientWarnings = [];
758
769
  if (explicitBranch && baseFlag === undefined && repoName() && hasRemote("origin")) {
759
770
  const remoteState = inspectRemoteBranch(explicitBranch);
@@ -1011,6 +1022,16 @@ export async function wu(p, out) {
1011
1022
  }
1012
1023
  case "scope": {
1013
1024
  const note = str(p.flags, "note");
1025
+ const session = sessionRequirement();
1026
+ if (session !== undefined) {
1027
+ if (!note?.trim())
1028
+ throw new CliError("usage", "wu scope session requirement needs --note");
1029
+ if (str(p.flags, "scope") !== undefined || str(p.flags, "scope-file") !== undefined || str(p.flags, "scope-from") !== undefined || bool(p.flags, "replace") || str(p.flags, "append") !== undefined)
1030
+ throw new CliError("usage", "amend the session requirement separately from scope text");
1031
+ const r = await client.call("POST", `${base}/${num()}/scope`, { session_requirement: session, note });
1032
+ out.print(`${fmt(r.unit)}\nSession requirement amended.`, r);
1033
+ return;
1034
+ }
1014
1035
  const hasScopeSource = str(p.flags, "scope") !== undefined || str(p.flags, "scope-file") !== undefined || str(p.flags, "scope-from") !== undefined;
1015
1036
  const hasEditMode = bool(p.flags, "replace") || str(p.flags, "append") !== undefined;
1016
1037
  if (Number(hasScopeSource) + Number(hasEditMode) !== 1)
@@ -1493,10 +1514,12 @@ export async function wu(p, out) {
1493
1514
  }
1494
1515
  case "stalled": {
1495
1516
  const response = await client.call("GET", `${base}?all=1`);
1496
- const units = response.units.filter((unit) => unit.stalled);
1497
- const rows = units.map((unit) => ({ n: `#${unit.number}`, age: `${unit.stalled.age_minutes} min`, status: unit.status, owner: unit.owner_name || "unassigned", reason: unit.stalled.reason, title: unit.title }));
1498
- out.print(rows.length ? table(rows, ["n", "age", "status", "owner", "reason", "title"]) : "(no stalled work units)", { project, units });
1499
- if (rows.length)
1517
+ const includeAll = p.flags.all === true;
1518
+ const units = response.units.filter((unit) => unit.stalled && (includeAll || unit.stalled.kind === "stalled" || unit.stalled.overdue))
1519
+ .sort((a, b) => Number(b.stalled.kind === "stalled") - Number(a.stalled.kind === "stalled") || b.stalled.age_minutes - a.stalled.age_minutes || a.number - b.number);
1520
+ const rows = units.map((unit) => ({ n: `#${unit.number}`, kind: unit.stalled.kind, age: waitAge(unit.stalled.age_minutes), status: unit.status, owner: unit.owner_name || "unassigned", label: unit.stalled.label, reason: unit.stalled.reason, title: unit.title }));
1521
+ out.print(rows.length ? table(rows, ["n", "kind", "age", "status", "owner", "label", "reason", "title"]) : `(no ${includeAll ? "waiting or stalled" : "stalled or overdue"} work units)`, { project, units });
1522
+ if (units.some((unit) => unit.stalled.kind === "stalled"))
1500
1523
  process.exitCode = 1;
1501
1524
  return;
1502
1525
  }
package/dist/help.js CHANGED
@@ -73,10 +73,10 @@ Agent commands
73
73
  b9s rule supersede <rule-id> --text "..." [--step cut|start|submit|verdict|merge|close] [--expires-at <UTC>] [--conflicts-with id,id] --confirm-compatible
74
74
  b9s rule retire <rule-id> authorized assigner; project agent credentials restrict scope
75
75
  review current charter/agreements before --confirm-compatible; no rule is inferred from chat
76
- b9s wu open "<title>" --scope "..." [--summary "plain work summary"] [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--priority urgent|normal] [--milestone <key>] [--force] [--evidence id[,id...]] [--target <branch>] [--here] [--json] open a work unit in its own
76
+ b9s wu open "<title>" --scope "..." [--summary "plain work summary"] [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--session-harness h] [--session-sandbox mode] [--session-machine name] [--session-machine-label label] [--priority urgent|normal] [--milestone <key>] [--force] [--evidence id[,id...]] [--target <branch>] [--here] [--json] open a work unit in its own
77
77
  worktree; tags come from the vocabulary; --target is the branch it lands in (default: the
78
78
  process target), e.g. a lane branch; wu target <n> <branch|default> changes it before review
79
- b9s wu assign "<title>" --to <agent|auto|queue> --scope ".." [--summary "plain work summary"] [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--priority urgent|normal] [--milestone <key>] [--branch <branch>] [--base <branch-or-sha>] [--continue] [--hold] [--evidence id[,id...]] [--force] [--replay-of n] [--template] [--reason "why"] [--json] hand out a unit (assigner roles);
79
+ b9s wu assign "<title>" --to <agent|auto|queue> --scope ".." [--summary "plain work summary"] [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--session-harness h] [--session-sandbox mode] [--session-machine name] [--session-machine-label label] [--priority urgent|normal] [--milestone <key>] [--branch <branch>] [--base <branch-or-sha>] [--continue] [--hold] [--evidence id[,id...]] [--force] [--replay-of n] [--template] [--reason "why"] [--json] hand out a unit (assigner roles);
80
80
  --to auto picks the active qualified worker with the lightest load; it queues when nobody fits,
81
81
  reports why candidates were passed over, and the sweep chases it;
82
82
  --to queue waits deliberately; naming a busy worker reserves it for them (theirs when free,
@@ -178,6 +178,7 @@ Machine placement enforces configured session slots and reports machine pressure
178
178
  owner, assigner or operator: wait for any non-closed unit; released when it closes
179
179
  b9s wu wait <n> --on "evidence|unit #m|ask id|machine name|text blocker" --note "why" [--partial "verdict"] | --clear
180
180
  owner or reviewer: pause review on a named blocker; reviewer may record a partial verdict
181
+ b9s wu scope <n> [--session-harness h] [--session-sandbox mode] [--session-machine name] [--session-machine-label label] [--clear-session] --note "why" amend the required session separately from scope text
181
182
  b9s wu scope <n> --scope ".." | --scope-file <path> | --scope-from <n> --note ".." [--summary "..." | --plain-summary "..."] assigner or operator: replace the full scope; recorded and announced
182
183
  b9s wu scope <n> --replace "<old>" "<new>" --note ".." replace one exact, unique substring of the scope
183
184
  b9s wu scope <n> --append ".." --note ".." add a dated scope amendment (up to 2000 chars); the base scope stays capped at 4000
@@ -207,7 +208,7 @@ Machine placement enforces configured session slots and reports machine pressure
207
208
  b9s wu recovery restore <n> next owner: verify and restore the restricted recovery bundle into the unit worktree
208
209
  b9s wu abandon <n> [--note ..] wu list [--all] [--json] for state and timeline (JSON keeps complete titles)
209
210
  b9s wu list [--all] [--status s] [--tag t] [--agent name] list visible work units; --all includes closed units
210
- b9s wu stalled list stalled units with age and reason; exits 1 when any are stalled
211
+ b9s wu stalled [--all] list stalled and overdue waits (or all wait kinds); KIND column; exits 1 only for true stalls
211
212
  b9s worktrees prune [--yes] [--archive] remove clean, fully pushed worktrees whose work landed or whose unit is closed (dry run without --yes);
212
213
  --archive also saves a closed unit's uncommitted files to archive/wu<n>-leftovers and removes it;
213
214
  refused in Antigravity workspace-write: watcher processes queued wu done worktrees at turn finalization; prune retained or abandoned worktrees from an unrestricted checkout
@@ -357,6 +358,7 @@ Successful writes verify stored-text receipts. If a 2xx write receipt mismatches
357
358
  the returned object and warning, then exits 3. Inspect the object and do not retry that write.
358
359
  Options are command-scoped; unsupported options are usage errors before command execution.
359
360
  Use --admin <nickname> to select one of this machine's saved operator identities.
361
+ Project agents inspect work waits with b9s wu stalled [--all]; its default includes true stalls and overdue waits, while --all includes every recorded wait kind.
360
362
 
361
363
  b9s-admin login [--as <nickname>] [--url <api>]
362
364
  prints a link and a code and opens it: approve it in a browser already signed in to BenignSwarm
@@ -368,6 +370,7 @@ Use --admin <nickname> to select one of this machine's saved operator identities
368
370
  b9s-admin text-check <project> find bschat mentions in working agreements, charter, tags, roles and open scopes
369
371
  b9s-admin signup --url <api> --key <signup-code> <account-name> <email>
370
372
  b9s-admin project create|list|delete <name>
373
+ b9s-admin project pause <project> --note "why" | resume <project> stop dispatch, steward actions, escalations, stall faults and new turns; queued and assigned work stays unchanged
371
374
  b9s-admin github status | disconnect <installation-id>
372
375
  b9s-admin project github <project> status | unlink
373
376
  b9s-admin project hosted-merge <project> enable [--confirm-bypass-signal]
@@ -420,6 +423,7 @@ Use --admin <nickname> to select one of this machine's saved operator identities
420
423
  b9s-admin role edit <name> [--project p] [--projects a,b|*] [--post c1,c2] [--broadcast] [--create-channels] [--read-account-status] [--assign-outside-qualifications yes|no] [--description d] [--cardinality one|many]
421
424
  b9s-admin role list [--project p]
422
425
  b9s-admin wu assign <project> <n> --to <agent> [--reason "why"] operator: reassign a unit in place
426
+ b9s-admin wu park|unpark <project> <n> --note "why" operator: park open or sent-back work, or return parked work to open
423
427
  b9s-admin wu done <project> <n> --merged <sha> [--gate-override-note "why"] [--note "context"] operator: close approved work; missing receipt override requires a recorded reason
424
428
  b9s-admin wu done <project> <n> --no-source --evidence id[,id...] --no-commits-beyond-target [--gate-override-note "why"] operator: close evidence-only work after confirming no commits beyond target
425
429
  b9s-admin wu merged-sha <project> <n> --sha <full-40-character-lowercase-sha> --reason "why" operator: correct a legacy abbreviated merged SHA with an audited reason
@@ -471,7 +475,7 @@ Use --admin <nickname> to select one of this machine's saved operator identities
471
475
  --assign-outside-qualifications yes|no allow assigners in this role to make reasoned ownership exceptions; dispatch stays qualified
472
476
  --judges yes|no the turn-judge capability: this role may be chosen as the independent judge (docs/TURN-JUDGE.md)
473
477
  b9s-admin obligations [--project p] [--overdue] who acts next and by when; unknown deadlines name their reason
474
- b9s-admin needs decisions waiting on you with decision/WU/fault IDs and Console links
478
+ b9s-admin needs [project] needs for one project, or all projects with decision/WU/fault IDs and Console links
475
479
  Browser conditional actions and retry receipts: docs/NEEDS-BROWSER-ACTIONS.md; console work #555/#556
476
480
  b9s-admin answer <id or key> "decision" answer one; the asker is @mentioned and a Console link is printed
477
481
  b9s-admin answer <id or key> --approve [--assign <agent>] [--note ".."] accept an ask proposal and name its action owner
@@ -157,7 +157,7 @@ export function machineResourceTelemetry(hostPlatform, readText, pageSizeBytes,
157
157
  const memoryText = linux ? readText("/proc/meminfo") : null;
158
158
  const linuxMemory = memoryText ? parseLinuxMemory(memoryText) : null;
159
159
  const macSwap = darwin && macSwapUsage !== null ? parseMacSwapUsage(macSwapUsage) : null;
160
- const macMemory = darwin && macVmStat !== null ? parseMacVmStat(macVmStat, pageSizeBytes) : null;
160
+ const macMemory = darwin && macVmStat !== null ? parseMacVmStat(macVmStat, parseMacVmStatPageSize(macVmStat)) : null;
161
161
  const vmstat = linux ? parseLinuxSwapCounters(readText("/proc/vmstat") ?? "", pageSizeBytes) : { in_bytes_total: null, out_bytes_total: null };
162
162
  const pressure = (kind) => linux ? parsePressureStall(readText(`/proc/pressure/${kind}`) ?? "") : null;
163
163
  const memoryPressure = pressure("memory");
@@ -238,3 +238,8 @@ export function parsePageSize(content) {
238
238
  const value = Number(content.trim());
239
239
  return Number.isSafeInteger(value) && value > 0 ? value : null;
240
240
  }
241
+ /** Read the kernel page size from vm_stat's own header so its page counts stay self-consistent. */
242
+ export function parseMacVmStatPageSize(content) {
243
+ const match = /^Mach Virtual Memory Statistics: \(page size of (\d+) bytes\)\s*$/m.exec(content);
244
+ return match ? parsePageSize(match[1]) : null;
245
+ }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.155";
1
+ export const CLI_VERSION = "0.12.156";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.155",
3
+ "version": "0.12.156",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {