benignswarm 0.12.112 → 0.12.113

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
@@ -23,7 +23,7 @@ export const STRING_FLAGS = [
23
23
  "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email",
24
24
  "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on",
25
25
  "sandbox", "thread", "turn-timeout", "turns-per-hour", "unproductive-per-hour", "turn-coalesce-seconds", "session", "operation",
26
- "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from",
26
+ "plain", "if-yes", "if-no", "ssh", "variant", "count", "min", "max", "needs", "min-ram", "exclude", "carry", "from",
27
27
  "to-ssh", "ssh-from", "wait", "writable", "writable-root", "dsh", "agy", "for", "until", "reason", "at", "requires",
28
28
  "priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect",
29
29
  "expectations", "reworks", "cause", "lesson", "disputes", "annotation", "send-back-event", "confirm-causes", "floor",
@@ -35,6 +35,7 @@ export const STRING_FLAGS = [
35
35
  "machine-session-id", "pool-sessions", "registry", "detail", "worktree",
36
36
  "purpose", "storage-mode", "hosts", "arn", "version-id",
37
37
  "mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class",
38
+ "expires-at", "conflicts-with", "source-channel-id", "source-message-id",
38
39
  "metadata-file",
39
40
  ];
40
41
  export const BOOL_FLAGS = [
@@ -43,7 +44,9 @@ export const BOOL_FLAGS = [
43
44
  "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind",
44
45
  "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive",
45
46
  "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "agy-userns", "print-apparmor",
46
- "cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "in-container", "assessment-only", "retrieve-ec2", "no-wait-verify", "preview", "remove-empty", "dry-run", "stdin", "context-confirmed",
47
+ "cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "assessment-only",
48
+ "no-wait-verify", "preview", "remove-empty", "dry-run", "quota-substitution",
49
+ "in-container", "retrieve-ec2", "stdin", "context-confirmed", "confirm-compatible",
47
50
  ];
48
51
  export function parse(argv) {
49
52
  const options = {};
@@ -53,17 +56,39 @@ export function parse(argv) {
53
56
  options[f] = { type: "boolean" };
54
57
  try {
55
58
  const seen = new Set();
59
+ const negativeBooleans = new Set();
56
60
  for (const arg of argv) {
57
61
  if (!arg.startsWith("--"))
58
62
  continue;
59
- const name = arg.slice(2).split("=", 1)[0].replace(/^no-/, "");
63
+ const rawName = arg.slice(2).split("=", 1)[0];
64
+ // A registered literal option wins over the conventional --no-<boolean>
65
+ // spelling. In particular, --no-source is an existing boolean CLI flag.
66
+ const negated = !(rawName in options) && rawName.startsWith("no-");
67
+ const name = negated ? rawName.slice(3) : rawName;
60
68
  if (!(name in options) || LIST_FLAGS.includes(name))
61
69
  continue;
70
+ if (negated) {
71
+ if (options[name]?.type !== "boolean" || arg.includes("="))
72
+ throw new CliError("usage", `${arg} is only valid for a boolean flag without a value`);
73
+ if (seen.has(name))
74
+ throw new CliError("usage", `--${name} was repeated; it may only be given once`);
75
+ seen.add(name);
76
+ negativeBooleans.add(name);
77
+ continue;
78
+ }
62
79
  if (seen.has(name))
63
80
  throw new CliError("usage", `--${name} was repeated; it may only be given once`);
64
81
  seen.add(name);
65
82
  }
66
- const { values, positionals } = parseArgs({ args: argv, options, allowPositionals: true, strict: true });
83
+ const parseArgv = argv.filter((arg) => {
84
+ if (!arg.startsWith("--"))
85
+ return true;
86
+ const rawName = arg.slice(2).split("=", 1)[0];
87
+ return !(rawName.startsWith("no-") && !(rawName in options) && negativeBooleans.has(rawName.slice(3)));
88
+ });
89
+ const { values, positionals } = parseArgs({ args: parseArgv, options, allowPositionals: true, strict: true });
90
+ for (const name of negativeBooleans)
91
+ values[name] = false;
67
92
  const flags = values;
68
93
  const repeatValues = {};
69
94
  for (const [key, value] of Object.entries(flags))
package/dist/brief.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Client } from "./client.js";
2
2
  import { loadAgent, resolveAgentName } from "./config.js";
3
+ import { formatStandingRuleSet } from "./standing-rules.js";
3
4
  export function formatOutcomeMeasures(measures = [], omitted = 0) {
4
5
  const rows = measures.slice(0, 6).map((m) => {
5
6
  const value = m.value === null || m.value === "unknown" ? "unknown" : `${String(m.value)}${m.unit ? ` ${m.unit}` : ""}`;
@@ -37,7 +38,7 @@ export async function fetchRecoveryBrief(nameOrRef) {
37
38
  throw new Error("GET /agents/me/notices returned no notices array");
38
39
  return { ...response.brief, notices: active.notices };
39
40
  }
40
- export function formatRecoveryBrief(brief) {
41
+ export function formatRecoveryBrief(brief, includeStandingRules = true) {
41
42
  const scope = (base, amendments, omitted = 0) => [
42
43
  ...(base ? [`\n base scope: ${base}`] : []),
43
44
  ...(amendments ?? []).map((amendment) => `\n amendment ${amendment.at} ${amendment.author}: ${amendment.text}`),
@@ -64,6 +65,15 @@ export function formatRecoveryBrief(brief) {
64
65
  lines.push(...(brief.decisions.length ? brief.decisions.map((d) => ` ${d.project} ${d.slice} WU #${d.unit} (${d.source}): ${d.ruling}`) : [" none"]));
65
66
  lines.push("Current notices:");
66
67
  lines.push(...(brief.notices?.length ? brief.notices.map((n) => ` [${n.scope} ${n.scope_name}] ${n.text}`) : [" none"]));
68
+ if (includeStandingRules && brief.standing_rules) {
69
+ lines.push("Standing rules:");
70
+ if (brief.standing_rules.delivery !== "complete")
71
+ lines.push(` delivery pending; retrieve the full rules with ${brief.standing_rules.process_command ?? "b9s process"}`);
72
+ else
73
+ lines.push(...(brief.standing_rules.rulesets.length
74
+ ? brief.standing_rules.rulesets.map((set) => formatStandingRuleSet(set, set.project ?? "account").split("\n").map((line) => ` ${line}`).join("\n"))
75
+ : [" (no rulesets)"]));
76
+ }
67
77
  lines.push(...formatOutcomeMeasures(brief.measures, brief.measures_omitted));
68
78
  return lines.join("\n");
69
79
  }
package/dist/client.js CHANGED
@@ -35,6 +35,12 @@ function expectedTextReceiptFields(method, path, body, response) {
35
35
  return strings("excerpt");
36
36
  if (verb === "PATCH" && /^\/projects\/[^/]+\/agents\/[^/]+\/moves\/[^/]+$/.test(route))
37
37
  return strings("detail");
38
+ if (verb === "POST" && /^\/projects\/[^/]+\/pools\/[^/]+\/(pause|resume)$/.test(route))
39
+ return strings("reason");
40
+ if ((verb === "PUT" || verb === "DELETE") && /^\/projects\/[^/]+\/pools\/[^/]+\/slots\/[^/]+\/pin$/.test(route))
41
+ return strings("reason");
42
+ if (verb === "POST" && /^\/projects\/[^/]+\/pools\/[^/]+\/slots\/[^/]+\/(suspend|restore)$/.test(route))
43
+ return strings("reason", "note");
38
44
  if (verb === "PUT" && /^\/projects\/[^/]+\/process$/.test(route)) {
39
45
  if (fields.dry_run === true)
40
46
  return [];
@@ -18,6 +18,7 @@ import { projectImageAdmin } from "./image-admin.js";
18
18
  import { environmentAdmin } from "./environment-admin.js";
19
19
  import { flowAdmin } from "./flow.js";
20
20
  import { projectSecrets } from "./project-secrets.js";
21
+ import { standingRuleAdmin } from "./standing-rules.js";
21
22
  function adminClient(p) {
22
23
  return Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
23
24
  }
@@ -97,6 +98,8 @@ export async function admin(p, out) {
97
98
  return keysAdmin(action, rest, p, out);
98
99
  case "process":
99
100
  return processAdmin(action, rest, p, out);
101
+ case "rule":
102
+ return standingRuleAdmin(action, rest, p, out);
100
103
  case "routing":
101
104
  return routingAdmin(action, rest, p, out);
102
105
  case "milestones": {
@@ -8,6 +8,7 @@ import { CliError } from "../errors.js";
8
8
  import { defaultMachine } from "../git.js";
9
9
  import { fmtMessage, fmtStatus, table } from "../output.js";
10
10
  import { readState, writeState } from "../state.js";
11
+ import { formatStandingRuleSummary } from "../standing-rules.js";
11
12
  function agentClient(p) {
12
13
  const name = resolveAgentName(str(p.flags, "as"));
13
14
  const creds = loadAgent(name);
@@ -72,6 +73,7 @@ export async function me(p, out) {
72
73
  r.role?.description ? `\n${r.role.description}\n` : "",
73
74
  `permissions: post=${r.permissions.post_channels.join(",")} broadcast=${r.permissions.broadcast} create_channels=${r.permissions.create_channels} read_account_status=${r.permissions.read_account_status}`,
74
75
  r.scope === "account" ? `tip: project commands take --project <name> (or BSCHAT_PROJECT)` : `channels: ${r.channels.map((c) => `#${c.name}`).join(" ")}`,
76
+ `standing rules:\n${formatStandingRuleSummary(r.standing_rules)}`,
75
77
  ];
76
78
  out.print(lines.join("\n"), r);
77
79
  }
@@ -10,6 +10,7 @@ import { goalFromClaudeTranscript, modelFromClaudeTranscript } from "../model.js
10
10
  import { bindSession, conversationAgent, sessionAgent, sessionsOf, syncFromWatchers } from "../sessions.js";
11
11
  import { fetchRecoveryBrief, formatOutcomeMeasures, formatRecoveryBrief, outcomeMeasureSnapshot, recoveryBriefUnavailableText } from "../brief.js";
12
12
  import { changedNotices, commandNoticeWarning, normalizeShellCommand } from "../notices.js";
13
+ import { formatStandingRuleSet, ruleAcknowledgmentTargets } from "../standing-rules.js";
13
14
  const HEARTBEAT_MS = 60_000;
14
15
  /** Reads the harness's hook payload from stdin without blocking when there is none. */
15
16
  function readStdinJson() {
@@ -136,8 +137,9 @@ export function formatHookDelivery(u, standing) {
136
137
  text = rendered.text;
137
138
  by_kind = rendered.by_kind;
138
139
  }
139
- const acknowledge = !!standing?.acknowledge && text.includes(standing.text) && standing.text !== standing.deferredText;
140
- return { text, by_kind, acknowledge };
140
+ const complete = !!standing && text.includes(standing.text) && standing.text !== standing.deferredText;
141
+ const acknowledge = complete && standing.acknowledge;
142
+ return { text, by_kind, acknowledge, complete };
141
143
  }
142
144
  /**
143
145
  * Collects everything new for an identity and advances its cursors. Returns null when nothing
@@ -420,9 +422,9 @@ export function claudeSessionBound(ref, sid, cwd, allowAutoBind = false) {
420
422
  export async function hook(p, payload) {
421
423
  const harness = p.positionals[1] ?? "plain";
422
424
  if (harness === "antigravity")
423
- return antigravityHook(p);
425
+ return antigravityHook(p, payload);
424
426
  if (harness === "codex")
425
- return codexHook(p);
427
+ return codexHook(p, payload);
426
428
  const event = str(p.flags, "event") ?? (harness === "claude-code" ? "UserPromptSubmit" : "");
427
429
  let name;
428
430
  try {
@@ -481,7 +483,7 @@ export async function hook(p, payload) {
481
483
  // version, and record that it was shown.
482
484
  const compacted = input?.source === "compact";
483
485
  const standing = harness === "claude-code" && event === "SessionStart"
484
- ? compacted ? await recoveryBrief(name) : await standingRules(name, false)
486
+ ? await standingRules(name, compacted)
485
487
  : null;
486
488
  // The hook firing is proof the harness is working; tell the server, at most once a minute.
487
489
  // The session goal (/goal) rides along from the transcript, and a change goes out at once.
@@ -512,12 +514,12 @@ export async function hook(p, payload) {
512
514
  else {
513
515
  process.stdout.write(text + "\n");
514
516
  }
515
- await acknowledgeStanding(name, standing, formatted.acknowledge);
517
+ await acknowledgeStanding(name, standing, formatted.complete);
516
518
  }
517
519
  /** After compaction, restore agent-specific state instead of repeating the standing agreements. */
518
- export async function recoveryBrief(name) {
520
+ export async function recoveryBrief(name, includeStandingRules = true) {
519
521
  try {
520
- const text = formatRecoveryBrief(await fetchRecoveryBrief(name));
522
+ const text = formatRecoveryBrief(await fetchRecoveryBrief(name), includeStandingRules);
521
523
  return { text, deferredText: text, acknowledge: false, version: 0, project: null };
522
524
  }
523
525
  catch (e) {
@@ -529,32 +531,63 @@ export async function recoveryBrief(name) {
529
531
  * The role and process the agent must hold after a new session or a compaction, when it has not
530
532
  * seen this process version (or always after a compaction). Records that it was shown.
531
533
  */
532
- async function standingRules(name, compacted) {
534
+ export async function standingRules(name, compacted) {
533
535
  try {
534
536
  const creds = loadAgent(name);
535
537
  const me = await Client.forAgent(creds, undefined, { presence: false }).call("GET", "/me");
536
538
  const proc = me.process;
539
+ const rules = me.standing_rules;
540
+ const ruleAcks = rules ? ruleAcknowledgmentTargets(rules, creds.project ?? undefined) : [];
541
+ const rulesText = Array.isArray(rules?.rulesets)
542
+ ? rules.rulesets.map((set) => formatStandingRuleSet(set, set.project ?? "account")).join("\n")
543
+ : formatStandingRuleSet(rules, me.project?.name ?? undefined);
544
+ const rulesComplete = rules?.complete === true && (Array.isArray(rules.rulesets)
545
+ ? rules.rulesets.every((set) => set.complete !== false && Array.isArray(set.rules))
546
+ : Array.isArray(rules.rules));
547
+ const ruleText = rulesComplete ? rulesText : "[b9s] Standing rule delivery is incomplete. Run b9s process to retrieve the complete current set; it was not acknowledged.";
537
548
  if (!proc)
538
- return null;
549
+ return { text: ruleText, deferredText: "[b9s] Standing rules could not be fully delivered. Run b9s process.", acknowledge: false, version: 0, project: null, ruleAcks: rulesComplete ? ruleAcks : [] };
539
550
  const roleIdentity = me.role ? `Your role: ${me.role.name}.` : `You hold no role in ${me.project?.name ?? "this project"}.`;
540
551
  const roleLine = me.role ? `${roleIdentity} ${me.role.description}` : roleIdentity;
541
- const rendered = renderStandingRules(proc, roleLine, compacted, roleIdentity);
542
- return { ...rendered, version: proc.version, project: creds.project };
552
+ const rendered = compacted
553
+ ? await recoveryBrief(name, false)
554
+ : { ...renderStandingRules(proc, roleLine, false, roleIdentity), version: proc.version, project: creds.project };
555
+ const text = `${ruleText}\n\n${rendered.text}`;
556
+ const deferredText = `[b9s] Standing rules or process context could not be fully delivered. Run b9s process to retrieve the complete current set; it was not acknowledged.`;
557
+ return { text, deferredText, acknowledge: !compacted && rendered.acknowledge, version: proc.version, project: creds.project, ruleAcks: rulesComplete ? ruleAcks : [] };
543
558
  }
544
559
  catch (e) {
545
560
  process.stderr.write(`b9s: could not fetch role/process: ${e.message}\n`);
546
- return null;
561
+ const deferredText = "[b9s] Standing rules and process could not be fetched. Run b9s process; no ruleset was acknowledged.";
562
+ return { text: deferredText, deferredText, acknowledge: false, version: 0, project: null, ruleAcks: [] };
547
563
  }
548
564
  }
549
- async function acknowledgeStanding(name, standing, emittedFullRules) {
550
- if (!standing || !emittedFullRules || !standing.acknowledge || !standing.project || standing.version <= 0)
565
+ export async function acknowledgeStanding(name, standing, emittedFullRules) {
566
+ if (!standing || !emittedFullRules)
551
567
  return;
568
+ let creds;
552
569
  try {
553
- const creds = loadAgent(name);
554
- await Client.forAgent(creds, undefined, { presence: false }).call("POST", `/projects/${standing.project}/process/ack`, { version: standing.version });
570
+ creds = loadAgent(name);
555
571
  }
556
572
  catch (e) {
557
- process.stderr.write(`b9s: could not acknowledge process rules: ${e.message}\n`);
573
+ process.stderr.write(`b9s: could not load identity for standing-rule acknowledgment: ${e.message}\n`);
574
+ return;
575
+ }
576
+ if (standing.acknowledge && standing.project && standing.version > 0) {
577
+ try {
578
+ await Client.forAgent(creds, undefined, { presence: false }).call("POST", `/projects/${standing.project}/process/ack`, { version: standing.version });
579
+ }
580
+ catch (e) {
581
+ process.stderr.write(`b9s: could not acknowledge process rules: ${e.message}\n`);
582
+ }
583
+ }
584
+ for (const target of standing.ruleAcks ?? []) {
585
+ try {
586
+ await Client.forAgent(creds, undefined, { presence: false }).call("POST", target.path, { fingerprint: target.fingerprint, delivered: true });
587
+ }
588
+ catch (e) {
589
+ process.stderr.write(`b9s: could not acknowledge standing-rule set: ${e.message}\n`);
590
+ }
558
591
  }
559
592
  }
560
593
  export function renderStandingRules(proc, roleLine, compacted, roleIdentity) {
@@ -594,10 +627,10 @@ export function renderStandingRules(proc, roleLine, compacted, roleIdentity) {
594
627
  * The agent is found by the conversation, never the workspace (several Antigravity agents share
595
628
  * one). Always prints valid JSON and exits 0: a hook must never break the session.
596
629
  */
597
- async function antigravityHook(p) {
630
+ async function antigravityHook(p, payload) {
598
631
  const event = str(p.flags, "event") ?? "";
599
632
  const out = (o) => { process.stdout.write(JSON.stringify(o) + "\n"); };
600
- const input = readStdinJson();
633
+ const input = payload === undefined ? readStdinJson() : payload;
601
634
  const conv = typeof input?.conversationId === "string" ? input.conversationId : null;
602
635
  let ref = conv ? conversationAgent(conv) : null;
603
636
  if (conv && !ref) {
@@ -660,7 +693,7 @@ async function antigravityHook(p) {
660
693
  if (formatted.text)
661
694
  await reportDelivery(name, formatted.text, formatted.by_kind);
662
695
  out(formatted.text ? { injectSteps: [{ systemMessage: { systemMessage: formatted.text } }] } : {});
663
- await acknowledgeStanding(name, standing, formatted.acknowledge);
696
+ await acknowledgeStanding(name, standing, formatted.complete);
664
697
  }
665
698
  /**
666
699
  * Codex's hooks (~/.codex/hooks.json, written by `b9s codex hooks`; Claude Code's format):
@@ -671,9 +704,9 @@ async function antigravityHook(p) {
671
704
  * `b9s codex bind`); any other Codex session (the user's own chats) gets nothing.
672
705
  * Always exits 0 with valid output: a hook must never break the session.
673
706
  */
674
- async function codexHook(p) {
707
+ async function codexHook(p, payload) {
675
708
  const event = str(p.flags, "event") ?? "";
676
- const input = readStdinJson();
709
+ const input = payload === undefined ? readStdinJson() : payload;
677
710
  const sid = typeof input?.session_id === "string" ? input.session_id : null;
678
711
  let ref = sid ? sessionAgent("codex", sid) : null;
679
712
  if (sid && !ref) {
@@ -736,7 +769,7 @@ async function codexHook(p) {
736
769
  await reportDelivery(name, formatted.text, formatted.by_kind);
737
770
  if (formatted.text)
738
771
  context(formatted.text);
739
- await acknowledgeStanding(name, standing, formatted.acknowledge);
772
+ await acknowledgeStanding(name, standing, formatted.complete);
740
773
  }
741
774
  /** Records where this agent's harness session writes, so `wu submit` can read its token counts. */
742
775
  function noteSession(name, harness, transcript, sessionId, compacted = false) {
@@ -191,6 +191,36 @@ export async function machineAdmin(action, rest, p, out) {
191
191
  const rows = r.machines.map((m) => ({ name: m.name, os: m.report?.os ?? "-", b9s: m.report?.bschat?.version ?? "-", codex: m.report?.codex ? (m.report.codex.logged_in ? "logged in" : "NOT logged in") : "-", sessions: m.sessions.length, last_report: m.last_report_at ?? "never" }));
192
192
  return out.print(rows.length ? table(rows, ["name", "os", "b9s", "codex", "sessions", "last_report"]) : "No machines. Add one: b9s-admin machine add <name> --ssh <host>", r);
193
193
  }
194
+ if (action === "headroom") {
195
+ const requested = rest[0];
196
+ const r = await c.call("GET", "/machines/headroom");
197
+ const machines = r.machines.filter((machine) => requested === undefined || machine.name === requested);
198
+ if (requested && !machines.length)
199
+ throw new CliError("not_found", `machine ${requested} not found`);
200
+ const metric = (value, unit) => {
201
+ if (!value || value.status !== "available")
202
+ return value?.status ?? "unknown";
203
+ if (unit === "ratio")
204
+ return `${Math.round(value.headroom * 100)}% headroom`;
205
+ return value.free_bytes == null ? "unknown" : `${Math.round(value.free_bytes / 1e9)} GB free`;
206
+ };
207
+ const lines = machines.flatMap((machine) => {
208
+ const h = machine.headroom, resources = h.resources ?? {};
209
+ const memory = resources.memory?.status === "available"
210
+ ? `${Math.round(resources.memory.available_bytes / 1e9)}/${Math.round(resources.memory.total_bytes / 1e9)} GB available (${metric(resources.memory, "ratio")})`
211
+ : resources.memory?.status ?? "unknown";
212
+ const storage = (value) => value?.status === "available"
213
+ ? `${Math.round(value.free_bytes / 1e9)} GB free of ${Math.round(value.total_bytes / 1e9)} GB`
214
+ : value?.status ?? "unknown";
215
+ const pools = machine.reservations.pools.map((pool) => `${pool.project}/${pool.pool}: ${pool.sessions}`).join(", ") || "none";
216
+ return [
217
+ `${machine.name}: resource headroom ${h.status}; latest sample ${machine.latest_sample_at ?? "never"}; limiting signal ${machine.limiting_signal ?? "unknown"}`,
218
+ ` CPU ${metric(resources.cpu, "ratio")}; RAM ${memory}; home storage ${storage(resources.home_storage)}; work storage ${storage(resources.work_storage)}; I/O pressure ${h.io_pressure?.status ?? "unknown"}`,
219
+ ` sessions ${machine.capacity.sessions_in_use}/${machine.capacity.effective_slots} (configured ${machine.capacity.configured_slots ?? "auto"}); ${machine.capacity.available_session_slots} available; manual ${machine.reservations.manual_sessions}, pool ${machine.reservations.pool_sessions} [${pools}]`,
220
+ ];
221
+ });
222
+ return out.print(lines.join("\n") || "No machines.", { machines });
223
+ }
194
224
  if (action === "show") {
195
225
  if (!rest[0])
196
226
  throw new CliError("usage", "machine show <name>");
@@ -640,8 +670,10 @@ export function repeated(argv, flag) {
640
670
  return out;
641
671
  }
642
672
  /**
643
- * pool set <project>/<name> --role r --variant spec [--variant ...] --count n --sandbox mode [--needs a,b] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60]
644
- * pool list [project] | show <project>/<name> | remove <project>/<name>
673
+ * pool set <project>/<name> --role r --variant spec [--variant ...] (--count n | --min n --max n) --sandbox mode [...]
674
+ * pool list [project] | show <project>/<name> | events <project>/<name> | pause|resume <project>/<name>
675
+ * pool pin <project>/<name> <slot> --machine <name> | unpin|suspend|restore <project>/<name> <slot>
676
+ * pool remove <project>/<name>
645
677
  */
646
678
  export async function poolAdmin(action, rest, p, out, argv) {
647
679
  if (action === "suggestions" || action === "suggestion") {
@@ -651,6 +683,30 @@ export async function poolAdmin(action, rest, p, out, argv) {
651
683
  throw new CliError("usage", "--turn-coalesce-seconds is only supported for individual machine sessions; pool settings do not support turn coalescing");
652
684
  }
653
685
  const c = adminClient(p);
686
+ const path = (project, name) => `/projects/${project}/pools/${name}`;
687
+ const previewOrConfirm = async (project, name, operation, payload, commit) => {
688
+ const base = path(project, name);
689
+ const suppliedRevision = str(p.flags, "impact-revision");
690
+ if (bool(p.flags, "preview") && suppliedRevision !== undefined)
691
+ throw new CliError("usage", "use either --preview or --impact-revision, not both");
692
+ const response = await c.call("POST", `${base}/preview`, { action: operation, ...payload });
693
+ const preview = response.preview;
694
+ const revision = preview?.revision ?? preview?.impact_revision;
695
+ if (!preview || typeof revision !== "string" || !revision)
696
+ throw new CliError("invalid_response", "pool preview did not include an impact revision");
697
+ const previewText = [
698
+ `${project}/${name}: ${operation} preview (${revision})`,
699
+ ` slots added: ${(preview.slots_added ?? []).length}; removed: ${(preview.slots_removed ?? []).length}; revived: ${(preview.revived ?? []).length}; retired: ${(preview.retired ?? []).length}`,
700
+ ` moves: ${(preview.moves ?? []).length}; unplaced: ${(preview.unplaced ?? []).length}; affected work/session: ${(preview.affected_work ?? []).length}/${(preview.affected_sessions ?? []).length}`,
701
+ ...((preview.refusals ?? []).length ? [` safety refusals: ${preview.refusals.map((item) => item.reason).join("; ")}`] : []),
702
+ `Review this impact, then repeat the command with --impact-revision ${revision}.`,
703
+ ].join("\n");
704
+ if (bool(p.flags, "preview") || suppliedRevision === undefined)
705
+ return out.print(previewText, { preview });
706
+ if (suppliedRevision !== revision)
707
+ throw new CliError("stale_preview", `pool impact changed since revision ${suppliedRevision}; the current preview is ${revision}. Nothing was changed; review it with --preview and confirm the new revision.`);
708
+ return commit(revision);
709
+ };
654
710
  if (action === "move") {
655
711
  const [project, name] = (rest[0] ?? "").split("/");
656
712
  const from = str(p.flags, "from");
@@ -697,8 +753,11 @@ export async function poolAdmin(action, rest, p, out, argv) {
697
753
  }
698
754
  const KEPT_IN_PLACE = KEPT_IN_PLACE_RE;
699
755
  const statusLines = (pool) => [
700
- `${pool.project}/${pool.name}: ${pool.count} × role ${pool.role ?? "(none)"}, ${pool.sandbox}; busy cap ${pool.turns_per_hour ?? 60}/hour, unproductive fault ${pool.unproductive_per_hour ?? 6}/hour; variants ${pool.variants.map((v) => `${v.tag}=${v.harness}:${v.model ?? "default"}${v.effort ? `:${v.effort}` : ""}${v.weight > 1 ? `*${v.weight}` : ""}${v.provider && v.provider !== "anthropic" ? `@${v.provider}` : ""}`).join(", ")}${pool.needs?.labels?.length ? `; needs ${pool.needs.labels.join(", ")}` : ""}${pool.needs?.min_ram_gb ? `; min ${pool.needs.min_ram_gb} GB` : ""}`,
701
- ...(pool.status?.placed ?? []).map((x) => ` ${x.agent.padEnd(32)} on ${x.machine}`),
756
+ `${pool.project}/${pool.name}: ${pool.count} × role ${pool.role ?? "(none)"}, ${pool.sandbox}; busy cap ${pool.turns_per_hour ?? 60}/hour, unproductive fault ${pool.unproductive_per_hour ?? 6}/hour${pool.quota_substitution ? "; quota substitution enabled" : ""}; variants ${pool.variants.map((v) => `${v.tag}=${v.harness}:${v.model ?? "default"}${v.effort ? `:${v.effort}` : ""}${v.weight > 1 ? `*${v.weight}` : ""}${v.provider && v.provider !== "anthropic" ? `@${v.provider}` : ""}`).join(", ")}${pool.needs?.labels?.length ? `; needs ${pool.needs.labels.join(", ")}` : ""}${pool.needs?.min_ram_gb ? `; min ${pool.needs.min_ram_gb} GB` : ""}`,
757
+ ...(pool.adaptive ? [` adaptive target ${pool.adaptive.target} (min ${pool.adaptive.min}, max ${pool.adaptive.max}); ${pool.adaptive.snapshot?.decision?.kind ?? "state unknown"}: ${pool.adaptive.snapshot?.decision?.reason ?? "no snapshot"}; queued ${pool.adaptive.snapshot?.queuedWork ?? "unknown"}, idle ${pool.adaptive.snapshot?.usableIdleSlots ?? "unknown"}, oldest ${pool.adaptive.snapshot?.oldestQueuedAgeSeconds == null ? "unknown" : `${Math.floor(pool.adaptive.snapshot.oldestQueuedAgeSeconds / 60)}m`}`] : []),
758
+ ...(pool.adaptive?.paused ? [" scaling paused by operator"] : []),
759
+ ...(pool.slots ?? []).map((slot) => ` ${slot.slot}: ${slot.suspended ? `SUSPENDED${slot.bench_note ? ` (${slot.bench_note})` : ""}` : slot.drain?.state && slot.drain.state !== "none" ? `DRAIN ${slot.drain.state}${slot.drain.reason ? ` (${slot.drain.reason})` : ""}` : slot.desired ?? "unplaced"}; ${slot.machine ? `on ${slot.machine}` : "NOT PLACED"}${slot.reported_state ? `; reported ${slot.reported_state}` : ""}${slot.stale_machine ? "; machine stale" : ""}${slot.pin ? `; pinned ${slot.pin.machine}${slot.pin.conflict ? ` (conflict: ${slot.pin.conflict})` : ""}` : ""}${slot.quota_pause ? `; quota paused: ${slot.quota_pause}` : ""}${slot.current_work ? `; work ${slot.current_work}` : ""}`),
760
+ ...(pool.slots ? [] : (pool.status?.placed ?? []).map((x) => ` ${x.agent.padEnd(32)} on ${x.machine}`)),
702
761
  ...(pool.status?.unplaced ?? []).map((x) => KEPT_IN_PLACE.test(x.reason)
703
762
  ? ` ${x.agent.padEnd(32)} KEPT IN PLACE (cannot move): ${x.reason}`
704
763
  : ` ${x.agent.padEnd(32)} NOT PLACED: ${x.reason}`),
@@ -711,9 +770,12 @@ export async function poolAdmin(action, rest, p, out, argv) {
711
770
  if (action === "set") {
712
771
  const [project, name] = (rest[0] ?? "").split("/");
713
772
  const variants = repeated(argv, "variant").map(parseVariant);
714
- const count = Number(str(p.flags, "count"));
715
- if (!project || !name || !variants.length || !Number.isInteger(count))
716
- throw new CliError("usage", "pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight][@anthropic|deepseek] [--variant ...] --count <n> --sandbox <read-only|workspace-write|danger-full-access> [--needs label,label] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60]");
773
+ const countRaw = str(p.flags, "count"), minRaw = str(p.flags, "min"), maxRaw = str(p.flags, "max");
774
+ const count = countRaw === undefined ? undefined : Number(countRaw);
775
+ const min = minRaw === undefined ? undefined : Number(minRaw), max = maxRaw === undefined ? undefined : Number(maxRaw);
776
+ const adaptive = minRaw !== undefined || maxRaw !== undefined;
777
+ if (!project || !name || !variants.length || (adaptive ? min === undefined || max === undefined || !Number.isInteger(min) || !Number.isInteger(max) || min < 0 || max > 50 || min > max || (count !== undefined && (!Number.isInteger(count) || count < min || count > max)) : count === undefined || !Number.isInteger(count) || count < 0 || count > 50))
778
+ throw new CliError("usage", "pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight][@anthropic|deepseek] [--variant ...] (--count <n> | --min <n> --max <n> [--count <target>]) --sandbox <read-only|workspace-write|danger-full-access> [--needs label,label] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60]");
717
779
  const needs = { ...(str(p.flags, "needs") ? { labels: str(p.flags, "needs").split(",").map((x) => x.trim()).filter(Boolean) } : {}), ...(str(p.flags, "min-ram") ? { min_ram_gb: Number(str(p.flags, "min-ram")) } : {}) };
718
780
  const tt = str(p.flags, "turn-timeout");
719
781
  const tph = str(p.flags, "turns-per-hour");
@@ -722,8 +784,11 @@ export async function poolAdmin(action, rest, p, out, argv) {
722
784
  throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to 60");
723
785
  if (uph !== undefined && (!/^\d+$/.test(uph) || Number(uph) < 1 || Number(uph) > 60))
724
786
  throw new CliError("usage", "--unproductive-per-hour must be a whole number from 1 to 60");
725
- const r = await c.call("PUT", `/projects/${project}/pools/${name}`, { role: str(p.flags, "role") ?? null, variants, count, sandbox: str(p.flags, "sandbox"), needs, ...(tt ? { turn_timeout: Number(tt) } : {}), ...(tph ? { turns_per_hour: Number(tph) } : {}), ...(uph ? { unproductive_per_hour: Number(uph) } : {}) });
726
- return out.print([...statusLines(r.pool), ...keptWarning(r.pool), "Their machines' daemons start them within 30 s: b9s-admin machine show <machine>"].join("\n"), r);
787
+ const body = { role: str(p.flags, "role") ?? null, variants, ...(count !== undefined ? { count } : {}), ...(adaptive ? { min, max } : {}), ...(p.flags["quota-substitution"] !== undefined ? { quota_substitution: bool(p.flags, "quota-substitution") } : {}), sandbox: str(p.flags, "sandbox"), needs, ...(tt ? { turn_timeout: Number(tt) } : {}), ...(tph ? { turns_per_hour: Number(tph) } : {}), ...(uph ? { unproductive_per_hour: Number(uph) } : {}) };
788
+ return previewOrConfirm(project, name, "configure", body, async (revision) => {
789
+ const r = await c.call("PUT", path(project, name), { ...body, impact_revision: revision });
790
+ return out.print([...statusLines(r.pool), ...keptWarning(r.pool), "Their machines' daemons start them within 30 s: b9s-admin machine show <machine>"].join("\n"), r);
791
+ });
727
792
  }
728
793
  if (action === "list" || action === undefined) {
729
794
  const r = await c.call("GET", rest[0] ? `/projects/${rest[0]}/pools` : "/pools");
@@ -731,20 +796,59 @@ export async function poolAdmin(action, rest, p, out, argv) {
731
796
  }
732
797
  if (action === "show") {
733
798
  const [project, name] = (rest[0] ?? "").split("/");
734
- const r = await c.call("GET", `/projects/${project}/pools`);
735
- const pool = r.pools.find((x) => x.name === name);
736
- if (!pool)
737
- throw new CliError("not_found", `no pool ${rest[0]}`);
799
+ if (!project || !name)
800
+ throw new CliError("usage", "pool show <project>/<name>");
801
+ const r = await c.call("GET", path(project, name));
802
+ const pool = r.pool;
738
803
  return out.print(statusLines(pool).join("\n"), { pool });
739
804
  }
805
+ if (action === "events" || action === "decisions") {
806
+ const [project, name] = (rest[0] ?? "").split("/");
807
+ if (!project || !name)
808
+ throw new CliError("usage", "pool events <project>/<name> [--limit 1..100]");
809
+ const limit = str(p.flags, "limit");
810
+ if (limit !== undefined && (!/^\d+$/.test(limit) || Number(limit) < 1 || Number(limit) > 100))
811
+ throw new CliError("usage", "--limit must be a whole number from 1 to 100");
812
+ const r = await c.call("GET", `${path(project, name)}/decisions${limit ? `?limit=${limit}` : ""}`);
813
+ const lines = (r.events ?? []).map((event) => `${event.at} ${event.kind} by ${event.actor}: ${event.reason}${event.after ? `; ${JSON.stringify(event.after)}` : ""}`);
814
+ return out.print(lines.join("\n") || "No pool decisions recorded.", r);
815
+ }
816
+ if (action === "pause" || action === "resume") {
817
+ const [project, name] = (rest[0] ?? "").split("/");
818
+ if (!project || !name)
819
+ throw new CliError("usage", `pool ${action} <project>/<name> [--reason <text>]`);
820
+ const reason = str(p.flags, "reason");
821
+ const body = reason === undefined ? {} : { reason };
822
+ return previewOrConfirm(project, name, action, body, async (revision) => {
823
+ const r = await c.call("POST", `${path(project, name)}/${action}`, { ...body, impact_revision: revision });
824
+ return out.print(`${project}/${name}: scaling ${action === "pause" ? "paused" : "resumed"}.${reason ? ` ${reason}` : ""}`, r);
825
+ });
826
+ }
827
+ if (["pin", "unpin", "suspend", "restore"].includes(action ?? "")) {
828
+ const [project, name] = (rest[0] ?? "").split("/");
829
+ const slot = rest[1];
830
+ if (!project || !name || !slot)
831
+ throw new CliError("usage", `pool ${action} <project>/<name> <slot> ${action === "pin" ? "--machine <name> " : ""}[--reason <text>] [--note <text>]`);
832
+ const reason = str(p.flags, "reason"), note = str(p.flags, "note"), machine = str(p.flags, "machine"), until = str(p.flags, "until");
833
+ if (action === "pin" && !machine)
834
+ throw new CliError("usage", "pool pin requires --machine <name>");
835
+ const body = { ...(machine ? { machine } : {}), ...(until !== undefined ? { expires_at: until } : {}), ...(reason !== undefined ? { reason } : {}), ...(note !== undefined ? { note } : {}) };
836
+ const endpoint = `${path(project, name)}/slots/${encodeURIComponent(slot)}/${action === "pin" || action === "unpin" ? "pin" : action === "suspend" ? "suspend" : "restore"}`;
837
+ return previewOrConfirm(project, name, action, { ...body, slot }, async (revision) => {
838
+ const r = await c.call(action === "pin" ? "PUT" : action === "unpin" ? "DELETE" : "POST", endpoint, { ...body, impact_revision: revision });
839
+ return out.print(`${project}/${name}/${slot}: ${action === "unpin" ? "pin cleared" : action === "restore" ? "slot restored" : action === "suspend" ? "slot suspended" : `pinned to ${machine}${until ? ` until ${until}` : ""}`}.`, r);
840
+ });
841
+ }
740
842
  if (action === "remove") {
741
843
  const [project, name] = (rest[0] ?? "").split("/");
742
844
  if (!project || !name)
743
845
  throw new CliError("usage", "pool remove <project>/<name> (retires its agents; their units go back to the queue)");
744
- await c.call("DELETE", `/projects/${project}/pools/${name}`);
745
- return out.print(`Removed pool ${rest[0]}: its agents are retired and their sessions removed.`, { removed: rest[0] });
846
+ return previewOrConfirm(project, name, "remove", {}, async (revision) => {
847
+ const r = await c.call("DELETE", `/projects/${project}/pools/${name}`, { impact_revision: revision });
848
+ return out.print(`Removed pool ${rest[0]}: its agents are retired and their sessions removed.`, { removed: rest[0], ...r });
849
+ });
746
850
  }
747
- throw new CliError("usage", "pool set <project>/<name> ... | list [project] | show <project>/<name> | remove <project>/<name>");
851
+ throw new CliError("usage", "pool set <project>/<name> ... | list [project] | show <project>/<name> | events <project>/<name> | pause|resume <project>/<name> | pin|unpin|suspend|restore <project>/<name> <slot> | remove <project>/<name>");
748
852
  }
749
853
  /** project checkout <project> --exclude logs/,docs/big | none: paths new worktrees leave out. */
750
854
  export async function projectCheckoutAdmin(rest, p, out) {
@@ -0,0 +1,129 @@
1
+ import { bool, str } from "../args.js";
2
+ import { Client } from "../client.js";
3
+ import { loadAdmin, loadAgent, resolveAdminName, resolveAgentName } from "../config.js";
4
+ import { CliError } from "../errors.js";
5
+ import { formatStandingRuleSet } from "../standing-rules.js";
6
+ import { projectOf } from "./agent.js";
7
+ function path(project) {
8
+ return `/projects/${encodeURIComponent(project)}/standing-rules`;
9
+ }
10
+ async function managementHistory(client, project, identifier) {
11
+ const base = `${path(project)}/manage${identifier === undefined ? "" : `/${encodeURIComponent(identifier)}`}`;
12
+ const rules = [];
13
+ const cursors = new Set();
14
+ let cursor;
15
+ let result;
16
+ do {
17
+ const query = new URLSearchParams({ limit: "100", ...(cursor === undefined ? {} : { cursor }) });
18
+ result = await client.call("GET", `${base}?${query.toString()}`);
19
+ if (!Array.isArray(result.rules))
20
+ throw new CliError("invalid_response", "standing-rule management response did not include a rules array");
21
+ rules.push(...result.rules);
22
+ const next = result.next_cursor;
23
+ if (next !== null && next !== undefined) {
24
+ if (typeof next !== "string" || !next || cursors.has(next))
25
+ throw new CliError("invalid_response", "standing-rule management returned an invalid or repeated cursor");
26
+ cursors.add(next);
27
+ cursor = next;
28
+ }
29
+ else {
30
+ cursor = undefined;
31
+ }
32
+ } while (cursor !== undefined);
33
+ return { ...result, rules, next_cursor: null, complete: true };
34
+ }
35
+ function formatRuleRows(rules, history = []) {
36
+ const rows = [...rules, ...history];
37
+ if (!rows.length)
38
+ return "(no standing rules)";
39
+ return rows.map((rule) => [
40
+ `${rule.id} r${rule.revision} [${rule.status}] ${rule.scope.kind}:${rule.scope.id}`,
41
+ ` by ${rule.author.name} (${rule.author.kind}) · created ${rule.created_at}${rule.expires_at ? ` · expires ${rule.expires_at}` : ""}`,
42
+ ` ${rule.text}`,
43
+ ...(rule.conflicts?.length ? [` unresolved conflicts: ${rule.conflicts.map((conflict) => conflict.rule_id).join(", ")}`] : []),
44
+ ].join("\n")).join("\n");
45
+ }
46
+ function body(p) {
47
+ const text = str(p.flags, "text");
48
+ if (!text?.trim())
49
+ throw new CliError("usage", "rule add/supersede needs --text <rule text>");
50
+ const conflicts = str(p.flags, "conflicts-with");
51
+ return {
52
+ text,
53
+ compatibility_confirmed: true,
54
+ ...(str(p.flags, "expires-at") === undefined ? {} : { expires_at: str(p.flags, "expires-at") }),
55
+ ...(conflicts === undefined ? {} : { conflicts_with: conflicts.split(",").map((value) => value.trim()).filter(Boolean) }),
56
+ ...(str(p.flags, "source-channel-id") === undefined ? {} : { source_channel_id: str(p.flags, "source-channel-id") }),
57
+ ...(str(p.flags, "source-message-id") === undefined ? {} : { source_message_id: str(p.flags, "source-message-id") }),
58
+ };
59
+ }
60
+ async function showPolicyBeforeWrite(client, project, p) {
61
+ const response = await client.call("GET", `/projects/${encodeURIComponent(project)}/process`);
62
+ const proc = response.process;
63
+ process.stdout.write(`Current charter for ${project}:\n${proc.charter || "(none)"}\n\nCurrent working agreements:\n${proc.agreements || "(none)"}\n\n`);
64
+ if (!bool(p.flags, "confirm-compatible")) {
65
+ throw new CliError("compatibility_confirmation", "Review the charter and working agreements above, then repeat with --confirm-compatible; no rule was written.");
66
+ }
67
+ }
68
+ async function runRuleAction(client, project, action, identifier, p, out) {
69
+ const base = path(project);
70
+ if (action === "list") {
71
+ const result = await managementHistory(client, project);
72
+ out.print(formatRuleRows(result.rules), result);
73
+ return;
74
+ }
75
+ if (action === "show") {
76
+ if (!identifier)
77
+ throw new CliError("usage", "rule show <rule-id>");
78
+ const result = await managementHistory(client, project, identifier);
79
+ if (!result.rules.length)
80
+ throw new CliError("not_found", `standing rule ${identifier} was not found in ${project}`);
81
+ out.print(formatRuleRows(result.rules), result);
82
+ return;
83
+ }
84
+ if (action === "add") {
85
+ const scope = str(p.flags, "scope");
86
+ if (!scope)
87
+ throw new CliError("usage", "rule add --scope account|project|role:<name>|agent:<name> --text <text>");
88
+ await showPolicyBeforeWrite(client, project, p);
89
+ const result = await client.call("POST", base, { ...body(p), scope });
90
+ out.print(`Created ${result.rule.scope.kind}:${result.rule.scope.id} standing rule ${result.rule.id} revision ${result.rule.revision}.`, result);
91
+ return;
92
+ }
93
+ if (action === "supersede") {
94
+ if (!identifier)
95
+ throw new CliError("usage", "rule supersede <rule-id> --text <new text> --confirm-compatible");
96
+ await showPolicyBeforeWrite(client, project, p);
97
+ const result = await client.call("POST", `${base}/${encodeURIComponent(identifier)}/supersede`, body(p));
98
+ out.print(`Superseded ${identifier} with revision ${result.rule.revision}.`, result);
99
+ return;
100
+ }
101
+ if (action === "retire") {
102
+ if (!identifier)
103
+ throw new CliError("usage", "rule retire <rule-id>");
104
+ const result = await client.call("POST", `${base}/${encodeURIComponent(identifier)}/retire`, {});
105
+ out.print(`Retired standing rule ${identifier}.`, result);
106
+ return;
107
+ }
108
+ throw new CliError("usage", "rule <list|show|add|supersede|retire>");
109
+ }
110
+ export async function standingRuleCommand(p, out) {
111
+ const name = resolveAgentName(str(p.flags, "as"));
112
+ const creds = loadAgent(name);
113
+ const project = projectOf(p, creds);
114
+ const client = Client.forAgent(creds, undefined);
115
+ const action = p.positionals[1];
116
+ const identifier = p.positionals[2];
117
+ await runRuleAction(client, project, action ?? "list", identifier, p, out);
118
+ }
119
+ export async function standingRuleAdmin(action, rest, p, out) {
120
+ const project = rest[0];
121
+ if (!project)
122
+ throw new CliError("usage", "b9s-admin rule <list|show|add|supersede|retire> <project> [rule-id] ...");
123
+ const creds = loadAdmin(resolveAdminName(str(p.flags, "admin")));
124
+ const client = Client.forAdmin(creds);
125
+ await runRuleAction(client, project, action ?? "list", rest[1], p, out);
126
+ }
127
+ export function formatOwnRuleSet(set, label) {
128
+ return formatStandingRuleSet(set, label);
129
+ }
@@ -16,6 +16,7 @@ import { createRecoveryArchive } from "../recovery-archive.js";
16
16
  import { tmpdir } from "node:os";
17
17
  import { chooseAgentContextAction, contextModeFromRuntime, explicitContextCompactSupport, hasCorrectionHistory } from "../context-policy.js";
18
18
  import { formatConfidenceMatrix, formatExplorationSummary, formatUnitRoutingExplanation } from "./routing-admin.js";
19
+ import { formatStandingRuleSet } from "../standing-rules.js";
19
20
  /** Only Claude's workspace-write sandbox needs SSH origins rewritten for its HTTP-only proxy. */
20
21
  export function shouldInheritClaudeSandboxUrlRewrites(env = process.env) {
21
22
  return env.CLAUDECODE === "1" && env.BSCHAT_CLAUDE_SANDBOX === "workspace-write";
@@ -1282,8 +1283,13 @@ export async function processCmd(p, out) {
1282
1283
  `Merging: ${d.merge.merged_by === "owner" ? "the owner" : d.merge.merged_by === "approver" ? "an approver" : `a ${d.merge.integrator_role}`} merges approved work into ${d.merge.target_branch}${d.merge.require_rebased ? "; the branch must contain " + d.merge.target_branch + " before review" : ""}${d.merge.require_merge_commit ? "; done carries the merge commit (b9s wu done <n> --merged <sha>)" : ""}.`,
1283
1284
  r.process.agreements ? `\nWorking agreements:\n${r.process.agreements}` : null,
1284
1285
  r.process.charter ? `\nCharter (how this project weighs its trade-offs; judge reviews and questions by it):\n${r.process.charter}` : null,
1286
+ `\n${formatStandingRuleSet(r.standing_rules, project)}`,
1285
1287
  ].filter(Boolean);
1286
1288
  out.print(lines.join("\n"), { ...r, roles });
1289
+ const standingRules = r.standing_rules;
1290
+ if (standingRules?.complete === true && standingRules.fingerprint && standingRules.acknowledged !== true) {
1291
+ await client.call("POST", `/projects/${encodeURIComponent(project)}/agents/me/standing-rules/ack`, { fingerprint: standingRules.fingerprint, delivered: true });
1292
+ }
1287
1293
  if (creds.project && r.process.version > 0)
1288
1294
  await client.call("POST", `/projects/${project}/process/ack`, { version: r.process.version });
1289
1295
  }
package/dist/help.js CHANGED
@@ -24,7 +24,8 @@ Free and paid accounts without a live Stripe subscription use the UTC calendar m
24
24
 
25
25
  Mac capacity/signing records and the hosted lease allocate/drain intents are documented in docs/MACOS-MACHINES-API.md. Allocation consumes WU #403's reviewed controller outputs; the API does not widen IAM. There is no CLI stop/release bypass. Operator controls are in the named hosted Mac lease console unit WU #381; signing remains a separate trusted worker.
26
26
  Mac capacity/signing API (profiles, leases, signer-only references, TestFlight approvals, and the isolated signer job contract) is documented in docs/MACOS-MACHINES-API.md. There is no CLI command to issue signer-host credentials or trigger release; operator controls are WU #286, real host/provider integration is WU #288.
27
- Standing rules are resolved by account, project, role, and exact-agent scope. GET /agents/me/standing-rules and GET /projects/:p/standing-rules return complete authorized sets and fingerprints; their separate ack endpoints accept only a current fingerprint after complete delivery. Operators and authorized assigners manage rules through the API; limits, compatibility confirmation, audit, and authorization are in packages/skill/references/api.md. Console management and chat promotion are planned in implementation unit 3 of docs/STANDING-RULES.md.
27
+ Standing rules are resolved by account, project, role, and exact-agent scope. GET /agents/me/standing-rules and GET /projects/:p/standing-rules return complete authorized sets and fingerprints; their separate ack endpoints accept only a current fingerprint after complete delivery. Operators and authorized assigners manage rules through the API; limits, compatibility confirmation, audit, and authorization are in packages/skill/references/api.md. Console management and chat promotion are WU #313.
28
+ Claude Code, Codex, and Antigravity SessionStart hooks retrieve the complete effective rules at fresh start, resume, compaction, and clear into a new thread. They acknowledge only after complete output; an unavailable or over-budget payload points to b9s process without acknowledgment. b9s me shows concise rule text and acknowledgment, b9s process shows the full project rules and acknowledges that fingerprint after display, and b9s resume includes the effective rulesets.
28
29
 
29
30
  GitHub connection and repository status are available in the console and through b9s-admin github status and b9s-admin project github <project> status|unlink. A repository link enables agent credentials without requiring a ruleset. An agent can inspect its effective repository permission with GET /projects/:p/git-credentials; a project admin can inspect a named agent with GET /projects/:p/git-credentials?agent=<name-or-id>. Each issuance records its permission reason without storing the token. Verify an exact target ruleset in Account -> GitHub connection before enabling hosted merge; the CLI cannot perform this owner OAuth step. Disconnect an installation with b9s-admin github disconnect <installation-id>. Hosted merge execution and status use b9s wu merge <n> and b9s wu merge status <n>; they call POST/GET /projects/:p/work-units/:n/merge and never inspect local Git state. API role checks use merge.merged_by and operator override; operator_hold is checked, merges serialize in MergeTargetDO, and retries reconcile idempotently. Manual wu done remains disabled for enabled linked targets. Enable with b9s-admin project hosted-merge <project> enable --confirm-bypass-signal only after ruleset verification and the live GitHub bypass-change check; disable with b9s-admin project hosted-merge <project> disable. The console control is WU #196. App setup steps are in packages/skill-admin/references/setup.md.
30
31
 
@@ -61,9 +62,12 @@ Agent commands
61
62
  b9s follow <channel> | unfollow <channel> | following followed channels' new messages are injected by the hook;
62
63
  other channels appear as a one-line unread digest
63
64
  b9s process the project's process: tag vocabulary, reviewers, wake-path warnings, scope templates, agreements and active standing rules
64
- b9s wu open "<title>" --scope "..." [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--after <n>[,<m>]] [--requires cap,cap] [--force] [--evidence id[,id...]] [--target <branch>] [--here] [--json] open a work unit in its own
65
- worktree; tags come from the vocabulary; --target is the branch it lands in (default: the
66
- process target), e.g. a lane branch; wu target <n> <branch|default> changes it before review
65
+ b9s rule list [--project <p>] list authorized project rules; assigner history uses API WU #459
66
+ b9s rule show <rule-id> [--project <p>]
67
+ b9s rule add --scope account|project|role:<name>|agent:<name> --text "..." [--expires-at <UTC>] [--conflicts-with id,id] [--source-channel-id <id> --source-message-id <id>] --confirm-compatible
68
+ b9s rule supersede <rule-id> --text "..." [--expires-at <UTC>] [--conflicts-with id,id] --confirm-compatible
69
+ b9s rule retire <rule-id> authorized assigner; project agent credentials restrict scope
70
+ review current charter/agreements before --confirm-compatible; no rule is inferred from chat
67
71
  b9s wu open "<title>" --scope "..." [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--force] [--evidence id[,id...]] [--target <branch>] [--here] [--json] open a work unit in its own
68
72
  worktree; tags come from the vocabulary; --target is the branch it lands in (default: the
69
73
  process target), e.g. a lane branch; wu target <n> <branch|default> changes it before review
@@ -362,6 +366,10 @@ the returned object and warning, then exits 3. Inspect the object and do not ret
362
366
  b9s-admin process assigners <project> role1,role2 | agreements <project> --file agreements.md
363
367
  b9s-admin process charter <project> --file charter.md how the project weighs trade-offs; sent with every expert question
364
368
  b9s-admin process steward <project> on|off [--quiet m] [--summary m] [--churn n] (--churn: ask the operator when a goal is sent back or handed over n times; 0 off)
369
+ b9s-admin rule list <project> | show <project> <rule-id>
370
+ b9s-admin rule add <project> --scope account|project|role:<name>|agent:<name> --text "..." [--expires-at <UTC>] [--conflicts-with id,id] [--source-channel-id <id> --source-message-id <id>] --confirm-compatible
371
+ b9s-admin rule supersede <project> <rule-id> --text "..." [--expires-at <UTC>] [--conflicts-with id,id] --confirm-compatible | retire <project> <rule-id>
372
+ rules are audited revisions; review charter and agreements first. Console promotion is the primary management surface.
365
373
  b9s-admin milestones <project> [export [--out plan.json] | set --file plan.json] the plan's slices: list, the editable JSON, or replace it (keys keep their status)
366
374
  b9s-admin milestone <project> add|edit <key> --title .. [--exit ..] [--source ..] [--depends-on a,b] [--informs c,d] [--default-tags a,b] one slice in, the rest untouched
367
375
  b9s-admin milestone <project> show|review|reopen <key> | decide <key> "ruling" --unit n | close <key> --note .. [--abandon|--defer] | verdict <key> --met|--gaps .. | gap-units <key> --units n,m
@@ -414,6 +422,7 @@ Machines (provisioned over your own ssh; a daemon on each runs the agent session
414
422
  refuses newer destination state and avoids duplicate Codex hooks under managed policy,
415
423
  then commits the session only after handoff succeeds; work left on the source requires both flags
416
424
  b9s-admin machine label <name> <label...> [--remove a,b] what cannot be measured (lab-lan, builds); pools' --needs match it
425
+ b9s-admin machine headroom [name] latest resource headroom, freshness, session ceiling and reservations (console WU #118)
417
426
  b9s-admin machine slots <name> <n | auto> how many sessions it takes (auto: one per 4 GB of RAM)
418
427
  b9s-admin machine writable <name> <path...> | none folders workspace-write agents there may also write (~/.cargo, ~/.ester)
419
428
  b9s-admin machine workdir <name> <path | default> where its daemon clones projects for pool sessions (default ~/bschat)
@@ -441,18 +450,26 @@ Project devcontainer images & immutable registry builds (console controls in WU
441
450
  b9s-admin project image activate <project> <sha256:...> explicitly select a ready candidate for future or restarted sessions
442
451
  b9s-admin project image rollback <project> (<sha256:...> | clear) select a prior ready digest or clear the active image selection without mutating tags
443
452
 
444
- Pools (a role, variants and a count; the server names the agents and places them on machines)
453
+ Pools (fixed or adaptive; the server names the agents and places them on machines)
445
454
  b9s-admin project repo <project> <git url | none> what machines clone for the project's pool sessions
446
455
  b9s-admin project checkout <project> --exclude <path,path | none> paths new worktrees leave out (sparse checkout), e.g. logs/
447
456
  b9s-admin pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight][@anthropic|deepseek] [--variant ...]
448
- --count <n> --sandbox <mode> [--needs label,label] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60]
457
+ --count <n> | --min <n> --max <n> [--count <target>] --sandbox <mode> [--needs label,label] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60]
458
+ fixed pools retain count; adaptive pools are opt-in, with target bounded by min/max and account/machine capacity
449
459
  slots are agents named <name>-<tag>-<n>; fewer retires the extra ones
450
- b9s-admin pool list [project] | show <project>/<name> | remove <project>/<name>
460
+ [--quota-substitution | --no-quota-substitution] allows another eligible variant after authoritative quota exhaustion
461
+ pool writes first show a server impact preview; confirm a fresh revision with --impact-revision <revision>
462
+ b9s-admin pool list [project] | show <project>/<name> | events <project>/<name> [--limit 1..100]
463
+ b9s-admin pool pause|resume <project>/<name> [--reason <text>] pause only automatic scaling; sessions keep running
464
+ b9s-admin pool pin <project>/<name> <slot> --machine <name> [--until <ISO>] [--reason <text>] | unpin <project>/<name> <slot>
465
+ b9s-admin pool suspend|restore <project>/<name> <slot> [--reason <text>] [--note <text>] suspend keeps the same slot and does not create a replacement
466
+ b9s-admin pool remove <project>/<name> retires its agents; their units go back to the queue
467
+ Console controls and impact previews are specified by WU #118.
451
468
  b9s-admin pool slot stop <project>/<pool>/<slot> [--reason text] suspend one slot and stop its session
452
469
  b9s-admin pool move <project>/<name> --from <source-machine> --to <destination-machine> [--carry note|thread] [--ssh-from local|<host>] [--to-ssh <host>]
453
470
  verifies each source slot independently; unsafe slots stay placed with a reason
454
471
  b9s-admin pool suggestions <project> [--status pending|accepted|rejected|superseded|all] inspect explicit non-mutating pool-weight suggestions
455
472
  b9s-admin pool suggestion accept <project> <id> [--note "..."] apply a pending pool-weight suggestion and audit it
456
- b9s-admin pool suggestion reject <project> <id> [--reason "..."] reject a pool-weight suggestion with an audit note
473
+ b9s-admin pool suggestion reject <project> <id> [--reason "..."] reject a pending pool-weight suggestion with an audit note
457
474
  b9s-admin delete-account --confirm "delete everything"
458
475
  `;
package/dist/index.js CHANGED
@@ -35,6 +35,7 @@ import { agentNotice } from "./commands/notices.js";
35
35
  import { versionLine, warnLegacyAlias } from "./legacy-alias.js";
36
36
  import { gitCredentialMain } from "./commands/git-credential.js";
37
37
  import { templates } from "./commands/templates.js";
38
+ import { standingRuleCommand } from "./commands/standing-rules.js";
38
39
  import { testResults } from "./commands/test-results.js";
39
40
  import { environment } from "./commands/environment.js";
40
41
  import { runCommandSafely } from "./command-runner.js";
@@ -96,6 +97,7 @@ const COMMANDS = {
96
97
  doctor,
97
98
  wu,
98
99
  process: processCmd,
100
+ rule: standingRuleCommand,
99
101
  record,
100
102
  milestones,
101
103
  milestone,
@@ -0,0 +1,78 @@
1
+ export function formatStandingRuleSet(set, label) {
2
+ if (!set || set.complete === false || !Array.isArray(set.rules)) {
3
+ return `[b9s] Standing rule delivery is incomplete${label ? ` for ${label}` : ""}. Run b9s process to retrieve the complete current set; it was not acknowledged.`;
4
+ }
5
+ const active = set.rules.filter((rule) => rule.status === "active");
6
+ const byId = new Map(active.map((rule) => [rule.id, rule]));
7
+ const state = set.acknowledged === true ? "acknowledged" : "acknowledgment pending";
8
+ const lines = [`Standing rules${label ? ` for ${label}` : ""}: ${active.length} active; ${state}${set.fingerprint ? ` (ruleset ${set.fingerprint})` : ""}.`];
9
+ if (!active.length)
10
+ lines.push(" (no active standing rules)");
11
+ for (const rule of active) {
12
+ const expires = rule.expires_at ? ` · expires ${rule.expires_at}` : " · no expiry";
13
+ lines.push(` [${rule.scope.kind}:${rule.scope.id} · revision ${rule.revision} · by ${rule.author.name}${expires}] ${rule.text}`);
14
+ for (const conflict of rule.conflicts ?? []) {
15
+ const other = byId.get(conflict.rule_id);
16
+ const source = other
17
+ ? `[${other.scope.kind}:${other.scope.id} · revision ${other.revision} · by ${other.author.name}] ${other.text}`
18
+ : `rule ${conflict.rule_id} (not in this effective ruleset)`;
19
+ lines.push(` conflicts with ${conflict.rule_id} (${conflict.resolution}): ${source}`);
20
+ }
21
+ }
22
+ return lines.join("\n");
23
+ }
24
+ export function formatStandingRuleSummary(response) {
25
+ if (!response || response.complete !== true)
26
+ return "standing rules: unavailable; run b9s process to retrieve the complete set";
27
+ const summarize = (set, label) => {
28
+ if (set.complete === false || !Array.isArray(set.rules))
29
+ return `${label}: incomplete; run b9s process`;
30
+ const active = set.rules.filter((rule) => rule.status === "active");
31
+ const byId = new Map(active.map((rule) => [rule.id, rule]));
32
+ const lines = [`${label}: ${active.length} active rule${active.length === 1 ? "" : "s"}; ${set.acknowledged === true ? "acknowledged" : "acknowledgment pending"}`];
33
+ for (const rule of active) {
34
+ lines.push(` - [${rule.scope.kind}:${rule.scope.id}] ${rule.text.slice(0, 180)}${rule.text.length > 180 ? "…" : ""}`);
35
+ for (const conflict of rule.conflicts ?? []) {
36
+ const other = byId.get(conflict.rule_id);
37
+ const source = other
38
+ ? `[${other.scope.kind}:${other.scope.id}] ${other.text.slice(0, 140)}${other.text.length > 140 ? "…" : ""}`
39
+ : `rule ${conflict.rule_id} (not in this effective ruleset)`;
40
+ lines.push(` conflicts with ${conflict.rule_id} (${conflict.resolution}): ${source}`);
41
+ }
42
+ }
43
+ return lines.join("\n");
44
+ };
45
+ const sets = response.rulesets;
46
+ if (Array.isArray(sets)) {
47
+ if (!sets.length)
48
+ return "standing rules: no project rulesets are available";
49
+ return sets.map((set) => summarize(set, set.project ?? "account")).join("\n");
50
+ }
51
+ if (!Array.isArray(response.rules))
52
+ return "standing rules: unavailable; run b9s process to retrieve the complete set";
53
+ return summarize({ rules: response.rules, complete: true, acknowledged: response.acknowledged }, "standing rules");
54
+ }
55
+ export function ruleAcknowledgmentTargets(response, project) {
56
+ if (response.complete !== true)
57
+ return [];
58
+ const targets = [];
59
+ const add = (path, fingerprint, acknowledged) => {
60
+ if (fingerprint && acknowledged !== true)
61
+ targets.push({ path, fingerprint });
62
+ };
63
+ if (Array.isArray(response.rulesets)) {
64
+ for (const set of response.rulesets) {
65
+ if (set.complete === false)
66
+ continue;
67
+ const route = set.project_id
68
+ ? `/projects/${encodeURIComponent(set.project_id)}/agents/me/standing-rules/ack`
69
+ : "/agents/me/standing-rules/ack";
70
+ add(route, set.fingerprint, set.acknowledged);
71
+ }
72
+ }
73
+ else {
74
+ const route = project ? `/projects/${encodeURIComponent(project)}/agents/me/standing-rules/ack` : "/agents/me/standing-rules/ack";
75
+ add(route, response.fingerprint, response.acknowledged);
76
+ }
77
+ return targets;
78
+ }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.112";
1
+ export const CLI_VERSION = "0.12.113";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.112",
3
+ "version": "0.12.113",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {