benignswarm 0.12.82 → 0.12.83

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.
@@ -47,7 +47,7 @@ export function editVocabulary(vocab, op, tag, f) {
47
47
  throw new CliError("not_found", `#${name} is not in the vocabulary`);
48
48
  if (op === "remove")
49
49
  return vocab.filter((t) => t.name !== name);
50
- const base = i >= 0 ? vocab[i] : { name, meaning: "", require_evidence: false, require_rebased: false, expert_role: null };
50
+ const base = i >= 0 ? vocab[i] : { name, meaning: "", require_evidence: false, require_rebased: false, expert_role: null, min_tier: "routine" };
51
51
  const next = {
52
52
  ...base,
53
53
  ...(f.meaning !== undefined ? { meaning: f.meaning } : {}),
@@ -55,6 +55,7 @@ export function editVocabulary(vocab, op, tag, f) {
55
55
  ...(f.rebased !== undefined ? { require_rebased: f.rebased } : {}),
56
56
  ...(f.expert !== undefined ? { expert_role: f.expert === "none" || f.expert === "" ? null : f.expert } : {}),
57
57
  ...(f.requires !== undefined ? { requires: f.requires.length ? f.requires : undefined } : {}),
58
+ ...(f.tier !== undefined ? { min_tier: f.tier } : {}),
58
59
  };
59
60
  if (op === "add" && !next.meaning.trim())
60
61
  throw new CliError("usage", `a tag needs a meaning, the sentence workers decide by: --meaning ".."`);
@@ -129,9 +130,9 @@ function describeProcess(r) {
129
130
  ` merging: into ${m.target_branch} by ${m.merged_by === "integrator" ? `a ${m.integrator_role}` : `the ${m.merged_by}`}; merge commit ${m.require_merge_commit ? "yes" : "no"}, rebased ${m.require_rebased ? "yes" : "no"}, pushed ${m.require_pushed ? "yes" : "no"}`,
130
131
  ` capabilities: ${(d.capabilities ?? []).map((c) => `${c.name} (${c.scope}${c.min_version ? ` >= ${c.min_version}` : ""})`).join(", ") || "none"}`,
131
132
  ` steward: ${d.steward.enabled ? "on" : "off"}, quiet ${d.steward.quiet_minutes} min, summary every ${d.steward.summary_minutes} min, ask the operator after ${d.steward.churn_rounds ? `${d.steward.churn_rounds} rounds on one goal` : "(never)"}`,
132
- ` agreements: ${r.process.agreements.length} of 8000 characters; charter: ${(r.process.charter ?? "").length ? `${r.process.charter.length} of 4000 characters` : "none (bschat-admin process charter <project> --file charter.md)"}; send-backs ${d.require_cited_changes === false ? "free-form" : "must cite the clause they fail"}`,
133
+ ` agreements: ${r.process.agreements.length} of 8000 characters; charter: ${(r.process.charter ?? "").length ? `${r.process.charter.length} of 4000 characters` : "none (b9s-admin process charter <project> --file charter.md)"}; send-backs ${d.require_cited_changes === false ? "free-form" : "must cite the clause they fail"}`,
133
134
  v.length ? `Tags:` : `No tag vocabulary: every unit goes to the default approver.`,
134
- ...v.map((t) => ` #${t.name}: ${t.meaning || "(NO MEANING: workers cannot decide by it)"}${t.require_evidence ? " · evidence" : ""}${t.require_rebased ? " · rebased" : ""}${t.expert_role ? ` · expert ${t.expert_role}` : ""}${t.requires?.length ? ` · requires ${t.requires.join(", ")}` : ""}`),
135
+ ...v.map((t) => ` #${t.name}: ${t.meaning || "(NO MEANING: workers cannot decide by it)"}${t.min_tier && t.min_tier !== "routine" ? ` · minimum tier ${t.min_tier}` : ""}${t.require_evidence ? " · evidence" : ""}${t.require_rebased ? " · rebased" : ""}${t.expert_role ? ` · expert ${t.expert_role}` : ""}${t.requires?.length ? ` · requires ${t.requires.join(", ")}` : ""}`),
135
136
  ].join("\n");
136
137
  }
137
138
  export async function processAdmin(action, rest, p, out) {
@@ -158,7 +159,7 @@ export async function processAdmin(action, rest, p, out) {
158
159
  const text = JSON.stringify(doc, null, 2) + "\n";
159
160
  if (file) {
160
161
  writeFileSync(file, text);
161
- out.print(`Wrote v${r.process.version} to ${file}. Edit it and publish with: bschat-admin process set ${proj} --file ${file}`, doc);
162
+ out.print(`Wrote v${r.process.version} to ${file}. Edit it and publish with: b9s-admin process set ${proj} --file ${file}`, doc);
162
163
  }
163
164
  else
164
165
  process.stdout.write(text);
@@ -187,7 +188,10 @@ export async function processAdmin(action, rest, p, out) {
187
188
  if (!["add", "edit", "remove"].includes(op) || !tag)
188
189
  throw new CliError("usage", 'admin process tag add|edit|remove <project> <tag> [--meaning ".."] [--require-evidence yes|no] [--require-rebased yes|no] [--expert-role <role>|none] [--requires name,name]');
189
190
  const r = await get();
190
- const vocabulary = editVocabulary(r.vocabulary, op, tag, { meaning: str(p.flags, "meaning"), evidence: yesNo(str(p.flags, "require-evidence"), "require-evidence"), rebased: yesNo(str(p.flags, "require-rebased"), "require-rebased"), expert: str(p.flags, "expert-role"), requires: tagList(str(p.flags, "requires")) });
191
+ const tier = str(p.flags, "tier");
192
+ if (tier !== undefined && !["routine", "careful", "expert"].includes(tier))
193
+ throw new CliError("usage", "--tier must be routine, careful, or expert");
194
+ const vocabulary = editVocabulary(r.vocabulary, op, tag, { meaning: str(p.flags, "meaning"), evidence: yesNo(str(p.flags, "require-evidence"), "require-evidence"), rebased: yesNo(str(p.flags, "require-rebased"), "require-rebased"), expert: str(p.flags, "expert-role"), requires: tagList(str(p.flags, "requires")), tier });
191
195
  return publish({ vocabulary }, `tag #${tag.replace(/^#/, "")} ${op === "add" ? "added" : op === "edit" ? "edited" : "removed"}`);
192
196
  }
193
197
  case "timing":
@@ -246,7 +250,7 @@ export async function needsAdmin(p, out) {
246
250
  const ind = (t) => t.replace(/\n/g, "\n ");
247
251
  out.print(r.needs.map((n, i) => [
248
252
  `${i + 1}. [${n.project}] ${n.kind === "unit_question" ? `WU #${n.unit} question` : n.kind === "wake_broken" ? "wake path" : n.kind === "notifier" ? "your alerts" : n.kind === "machine_session" ? "machine" : "decision"} · ${n.asked_by} · since ${n.since.slice(0, 16).replace("T", " ")} UTC`,
249
- n.plain ? ` In plain words: ${ind(n.plain)}` : n.unexplained ? ` In plain words: (${n.asked_by} did not explain this; bschat-admin explain ${n.key})` : null,
253
+ 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,
250
254
  n.blocks ? ` What's stuck: ${ind(n.blocks)}` : null,
251
255
  ` ${n.kind === "ask" ? "What I need from you: " : ""}${ind(n.text)}`,
252
256
  n.if_yes ? ` If yes: ${ind(n.if_yes)}` : null,
@@ -254,9 +258,9 @@ export async function needsAdmin(p, out) {
254
258
  n.proposal ? ` Proposed by ${n.proposed_by}: ${ind(n.proposal)}` : null,
255
259
  n.explanation ? ` Explained by ${n.explained_by}: ${ind(n.explanation)}` : n.explain_requested_at ? ` (explanation asked for ${n.explain_requested_at.slice(0, 16).replace("T", " ")} UTC)` : null,
256
260
  ` key: ${n.key}`,
257
- ].filter(Boolean).join("\n")).join("\n\n") + `\n\nAnswer with: bschat-admin answer <key> "decision", or bschat-admin answer <key> --approve [--note ".."] to accept a proposal; bschat-admin explain <key> asks the agent to explain it in plain words`, r);
261
+ ].filter(Boolean).join("\n")).join("\n\n") + `\n\nAnswer with: b9s-admin answer <key> "decision", or b9s-admin answer <key> --approve [--note ".."] to accept a proposal; b9s-admin explain <key> asks the agent to explain it in plain words`, r);
258
262
  }
259
- /** bschat-admin explain <key>: the console's Explain; the agent is mentioned and asked to put it in plain words. */
263
+ /** b9s-admin explain <key>: the console's Explain; the agent is mentioned and asked to put it in plain words. */
260
264
  export async function explainAdmin(rest, p, out) {
261
265
  const key = rest[0];
262
266
  if (!key)
@@ -264,11 +268,11 @@ export async function explainAdmin(rest, p, out) {
264
268
  const c = adminClient(p);
265
269
  const n = (await c.call("GET", "/account/needs")).needs.find((x) => x.key === key);
266
270
  if (!n)
267
- throw new CliError("not_found", `nothing waiting with key ${key}; list them with: bschat-admin needs`);
271
+ throw new CliError("not_found", `nothing waiting with key ${key}; list them with: b9s-admin needs`);
268
272
  if (n.kind === "ask")
269
- return out.print(`Asked ${n.asked_by} to explain; it appears with the decision (bschat-admin needs) and in the next report to you.`, await c.call("POST", `/projects/${n.project}/asks/${n.ask_id}/explain`, {}));
273
+ return out.print(`Asked ${n.asked_by} to explain; it appears with the decision (b9s-admin needs) and in the next report to you.`, await c.call("POST", `/projects/${n.project}/asks/${n.ask_id}/explain`, {}));
270
274
  if (n.kind === "unit_question")
271
- return out.print(`Asked for WU #${n.unit}'s question in plain words; it appears with the question (bschat-admin needs).`, await c.call("POST", `/projects/${n.project}/work-units/${n.unit}/question/explain`, {}));
275
+ return out.print(`Asked for WU #${n.unit}'s question in plain words; it appears with the question (b9s-admin needs).`, await c.call("POST", `/projects/${n.project}/work-units/${n.unit}/question/explain`, {}));
272
276
  throw new CliError("not_answerable", "only decisions (asks and unit questions) can be explained");
273
277
  }
274
278
  export async function answerAdmin(rest, p, out) {
@@ -283,7 +287,7 @@ export async function answerAdmin(rest, p, out) {
283
287
  const c = adminClient(p);
284
288
  const n = (await c.call("GET", "/account/needs")).needs.find((x) => x.key === key);
285
289
  if (!n)
286
- throw new CliError("not_found", `nothing waiting with key ${key}; list them with: bschat-admin needs`);
290
+ throw new CliError("not_found", `nothing waiting with key ${key}; list them with: b9s-admin needs`);
287
291
  if (assign && n.kind !== "ask")
288
292
  throw new CliError("usage", "--assign names the owner of an approved ask action; this need is not an ask");
289
293
  if (approve && n.kind !== "ask" && n.kind !== "unit_question")
@@ -292,7 +296,7 @@ export async function answerAdmin(rest, p, out) {
292
296
  return out.print(approve ? `Approved the proposal${assign ? ` and assigned the action to ${assign}` : ""}; the asker was told.` : "Answered; the asker was told.", await c.call("POST", `/projects/${n.project}/asks/${n.ask_id}/answer`, approve ? { approve: true, answer, ...(assign ? { assign } : {}) } : { answer }));
293
297
  if (n.kind === "unit_question")
294
298
  return out.print(`Ruled on WU #${n.unit}${approve ? " (proposal approved)" : ""}; the asker, owner and reviewers were told.`, await c.call("POST", `/projects/${n.project}/work-units/${n.unit}/rule`, approve ? { approve: true, ruling: answer } : { ruling: answer }));
295
- throw new CliError("not_answerable", n.kind === "wake_broken" ? `a broken wake path clears when ${n.agent} shows activity: fix its watcher or harness session` : "a notifier problem clears on the next report that reaches you: fix it with bschat-admin notifier");
299
+ throw new CliError("not_answerable", n.kind === "wake_broken" ? `a broken wake path clears when ${n.agent} shows activity: fix its watcher or harness session` : "a notifier problem clears on the next report that reaches you: fix it with b9s-admin notifier");
296
300
  }
297
301
  export async function notifierAdmin(p, out) {
298
302
  const c = adminClient(p);
@@ -324,13 +328,52 @@ export async function accountAdmin(p, out) {
324
328
  const r = await c.call("GET", "/account");
325
329
  const u = await c.call("GET", "/account/usage");
326
330
  const a = r.account ?? r;
327
- out.print(`${a.name} · plan ${a.plan} · account summary every ${a.summary_minutes ?? 60} min\nusage: ${JSON.stringify(u.usage ?? u)}`, { account: a, usage: u });
331
+ const usage = u.usage ?? u;
332
+ out.print(`${a.name} · plan ${a.plan} · account summary every ${a.summary_minutes ?? 60} min\nusage: ${JSON.stringify(usage)}\nlegacy bschat CLI requests: ${usage.legacy_cli_invocations ?? 0}`, { account: a, usage: u });
333
+ }
334
+ export async function textCheckAdmin(project, p, out) {
335
+ if (!project)
336
+ throw new CliError("usage", "b9s-admin text-check <project>");
337
+ const c = adminClient(p);
338
+ const [pr, roles, units] = await Promise.all([
339
+ c.call("GET", `/projects/${project}/process`),
340
+ c.call("GET", `/projects/${project}/roles`),
341
+ c.call("GET", `/projects/${project}/work-units`),
342
+ ]);
343
+ const places = [];
344
+ const scan = (place, value) => {
345
+ if (typeof value !== "string")
346
+ return;
347
+ const matches = [];
348
+ value.split(/\r?\n/).forEach((text, i) => {
349
+ const count = text.match(/bschat/gi)?.length ?? 0;
350
+ if (count)
351
+ matches.push({ line: i + 1, text: text.trim() });
352
+ });
353
+ const count = matches.reduce((n, x) => n + (x.text.match(/bschat/gi)?.length ?? 0), 0);
354
+ if (count)
355
+ places.push({ place, count, matches });
356
+ };
357
+ const proc = pr.process ?? pr;
358
+ scan("working agreements", proc.agreements);
359
+ scan("charter", proc.charter);
360
+ for (const tag of pr.vocabulary ?? [])
361
+ scan(`tag #${tag.name} meaning`, tag.meaning);
362
+ for (const role of roles.roles ?? [])
363
+ scan(`role ${role.name} description`, role.description);
364
+ for (const unit of units.units ?? []) {
365
+ if (["done", "abandoned", "superseded", "closed"].includes(unit.status))
366
+ continue;
367
+ scan(`WU #${unit.number} scope`, unit.scope);
368
+ }
369
+ const total = places.reduce((n, x) => n + x.count, 0);
370
+ out.print(total ? places.map((x) => `${x.place} (${x.count})\n${x.matches.map((m) => ` line ${m.line}: ${m.text}`).join("\n")}`).join("\n") : "No bschat mentions found in project texts.", { project, count: total, places });
328
371
  }
329
372
  export async function keysAdmin(action, rest, p, out) {
330
373
  const c = adminClient(p);
331
374
  if (action === "create") {
332
375
  const r = await c.call("POST", "/account/keys", {});
333
- return out.print(`New admin key (shown once, store it now): ${r.admin_key}\nUse it with: bschat-admin login --as <nickname> --key <the key>`, r);
376
+ return out.print(`New admin key (shown once, store it now): ${r.admin_key}\nUse it with: b9s-admin login --as <nickname> --key <the key>`, r);
334
377
  }
335
378
  if (action === "revoke") {
336
379
  if (!rest[0])
@@ -343,37 +386,37 @@ export async function keysAdmin(action, rest, p, out) {
343
386
  export async function worktreeAdmin(action, rest, p, out) {
344
387
  const [proj, id] = rest;
345
388
  if (action !== "forget" || !proj || !id)
346
- throw new CliError("usage", "admin worktree forget <project> <record id from bschat worktrees --json> (deletes the record only, never the directory)");
389
+ throw new CliError("usage", "admin worktree forget <project> <record id from b9s worktrees --json> (deletes the record only, never the directory)");
347
390
  out.print(`forgot worktree record ${id}`, await adminClient(p).call("DELETE", `/projects/${proj}/worktrees/${id}`));
348
391
  }
349
392
  /**
350
- * For an AI agent asked to drive bschat-admin: what this is and how to load the full operator
393
+ * For an AI agent asked to drive b9s-admin: what this is and how to load the full operator
351
394
  * skill. Printed offline, so it works before sign-in.
352
395
  */
353
- export const AGENT_ORIENTATION = `bschat-admin, for an AI agent helping a person run BenignSwarm
396
+ export const AGENT_ORIENTATION = `b9s-admin, for an AI agent helping a person run BenignSwarm
354
397
 
355
398
  You are acting for the account's operator (a person), not as an agent in a project. BenignSwarm
356
399
  coordinates their AI coding agents (Claude Code, Codex, Antigravity, DeepSeek, Gemini; any
357
400
  machine) through work units, reviews by qualified roles, milestones and evidence. The agents use
358
- \`bschat\`; you use \`bschat-admin\` to set projects up and keep them running.
401
+ \`b9s\`; you use \`b9s-admin\` to set projects up and keep them running.
359
402
 
360
403
  Before acting, load the operator skill. It explains the philosophy, the setup interview, how to
361
404
  design the process (tags, roles, merge policy, milestones), how each harness joins and is woken,
362
405
  several machines, and how to recognise and fix stalls:
363
406
 
364
- bschat-admin skill install # writes ~/.claude/skills/benignswarm-operator (Claude Code)
365
- bschat-admin skill install --dir <path> # any other harness: a directory you will read from
366
- bschat-admin skill print # or print SKILL.md and read it now
407
+ b9s-admin skill install # writes ~/.claude/skills/benignswarm-operator (Claude Code)
408
+ b9s-admin skill install --dir <path> # any other harness: a directory you will read from
409
+ b9s-admin skill print # or print SKILL.md and read it now
367
410
 
368
411
  Then read references/setup.md and interview the operator before running anything. Rules that
369
412
  matter from the start:
370
- - Sign in with \`bschat-admin login\` (the operator approves it in their browser). Never ask for,
413
+ - Sign in with \`b9s-admin login\` (the operator approves it in their browser). Never ask for,
371
414
  print or store admin or agent keys in chat or in committed files.
372
415
  - Propose a process and get a yes before publishing it: a publish wakes every agent to re-read it.
373
416
  - Ask before anything destructive (deleting a project, agent, key or account).
374
417
  - You are not an agent in the project: never post as one, take units or approve work.
375
418
 
376
- Commands: bschat-admin --help
419
+ Commands: b9s-admin --help
377
420
  `;
378
421
  export async function skillAdmin(action, p, out) {
379
422
  const saved = listSaved("admins");
@@ -408,5 +451,5 @@ export async function skillAdmin(action, p, out) {
408
451
  out.print(`Installed the operator skill to ${dir} (SKILL.md and ${refs.length} references). Claude Code loads ~/.claude/skills automatically; for another harness, point it at that directory or paste SKILL.md into its instructions.`, { dir, references: refs });
409
452
  return;
410
453
  }
411
- throw new CliError("usage", "bschat-admin skill install [--dir <path>] | skill print");
454
+ throw new CliError("usage", "b9s-admin skill install [--dir <path>] | skill print");
412
455
  }
@@ -73,7 +73,7 @@ export async function handoffs(p, out) {
73
73
  }
74
74
  if (sub === "pickup") {
75
75
  const r = await c.call("POST", `/handoffs/${id}/pickup`, {});
76
- out.print(`picked up handoff:${id} as ${r.picked_up_by}. Read it with: bschat handoffs show ${id}`, r);
76
+ out.print(`picked up handoff:${id} as ${r.picked_up_by}. Read it with: b9s handoffs show ${id}`, r);
77
77
  return;
78
78
  }
79
79
  throw new CliError("usage", "handoffs [list] [--open] [--agent a] | show <id> | pickup <id>");
@@ -99,5 +99,5 @@ export async function checkpoint(p, out) {
99
99
  throw new CliError("usage", 'checkpoint "<title>" (--body "..." | --body-file notes.md) [--evidence id,id] what you are doing, open threads (units, branches, waits) and next steps');
100
100
  const evidence = (str(p.flags, "evidence") ?? "").split(",").map((s) => s.trim()).filter(Boolean);
101
101
  const r = await c.call("POST", "/agents/me/checkpoint", { title, body, evidence });
102
- out.print(`Saved resume note handoff:${r.handoff.id} for ${creds.agent}. Your next session reads it with: bschat handoffs --agent ${creds.agent}`, r);
102
+ out.print(`Saved resume note handoff:${r.handoff.id} for ${creds.agent}. Your next session reads it with: b9s handoffs --agent ${creds.agent}`, r);
103
103
  }
@@ -8,8 +8,8 @@ import { readState, writeState } from "../state.js";
8
8
  * watcher queues nothing else until it runs, and the server records it so the console can tell
9
9
  * a delivered wake-up from one waiting behind a long turn or a broken wake path.
10
10
  *
11
- * bschat wake ack <n> acknowledge wake-up #n (and every earlier one)
12
- * bschat wake ack acknowledge the one pending on this machine (a new session that never saw it)
11
+ * b9s wake ack <n> acknowledge wake-up #n (and every earlier one)
12
+ * b9s wake ack acknowledge the one pending on this machine (a new session that never saw it)
13
13
  */
14
14
  export async function wake(p, out) {
15
15
  if (p.positionals[1] !== "ack")
@@ -20,13 +20,13 @@ export async function wake(p, out) {
20
20
  let seq;
21
21
  if (arg === undefined) {
22
22
  if (!st.watch_pending)
23
- throw new CliError("nothing_pending", "no wake-up is pending for you on this machine", "If a wake-up named a number, run bschat wake ack <n>");
23
+ throw new CliError("nothing_pending", "no wake-up is pending for you on this machine", "If a wake-up named a number, run b9s wake ack <n>");
24
24
  seq = st.watch_pending.seq ?? st.watch_seq ?? 0;
25
25
  }
26
26
  else {
27
27
  seq = Number(arg.replace(/^#/, ""));
28
28
  if (!Number.isInteger(seq) || seq < 1)
29
- throw new CliError("usage", "wake ack <n>: n is the wake-up's number, e.g. bschat wake ack 17");
29
+ throw new CliError("usage", "wake ack <n>: n is the wake-up's number, e.g. b9s wake ack 17");
30
30
  }
31
31
  const { next, clears } = applyAck(st, seq);
32
32
  const pending = st.watch_pending;
@@ -21,6 +21,14 @@ import { formatUpdates, gatherUpdates, reportDelivery } from "./hook.js";
21
21
  import { readState, writeState } from "../state.js";
22
22
  import { probeCapabilities } from "../capabilities.js";
23
23
  import { fetchRecoveryBrief, formatRecoveryBrief, recoveryBriefUnavailableText, recoveryBriefWasDelivered } from "../brief.js";
24
+ function omitMeasuresAlreadyIn(text, updates) {
25
+ if (!text)
26
+ return updates;
27
+ const included = new Set(text.split("\n").filter((line) => line.startsWith("Outcome measure ")));
28
+ if (!included.size)
29
+ return updates;
30
+ return { ...updates, parts: { ...updates.parts, protectedDirect: updates.parts.protectedDirect?.filter((line) => !included.has(line)) } };
31
+ }
24
32
  /** Reports host probes without refreshing the agent's presence; the host identity is still explicit. */
25
33
  export async function reportWatcherCapabilities(creds, project, definitions, cwd = process.cwd()) {
26
34
  const results = probeCapabilities(definitions, cwd);
@@ -30,11 +38,11 @@ export async function reportWatcherCapabilities(creds, project, definitions, cwd
30
38
  * Event bridge for harnesses that can be woken from outside (Codex: `codex queue --thread <id>`).
31
39
  *
32
40
  * Default mode queues ONE short wake-up and nothing else until the agent has read (its own
33
- * `bschat inbox --unread` / `bschat read` advance the shared cursors). Content is never put in
41
+ * `b9s inbox --unread` / `b9s read` advance the shared cursors). Content is never put in
34
42
  * the queue, so the agent always reads it fresh and superseded messages collapse naturally.
35
43
  * A direct message from a human operator re-wakes immediately even while a wake-up is pending.
36
44
  * `--full` restores the old behaviour of queueing the text itself (for harnesses that cannot run
37
- * bschat themselves when woken).
45
+ * b9s themselves when woken).
38
46
  */
39
47
  export async function watch(p, out) {
40
48
  const name = resolveAgentName(str(p.flags, "as"));
@@ -46,7 +54,7 @@ export async function watch(p, out) {
46
54
  const full = bool(p.flags, "full");
47
55
  for (const gone of ["requeue-after", "max-unanswered"])
48
56
  if (p.flags[gone] !== undefined)
49
- throw new CliError("usage", `--${gone} was removed in 0.12.37: a wake-up is never re-queued; the watcher waits for the agent's ack (bschat wake ack <n>). Use --unacked-after <s> to choose when an unacknowledged wake-up is logged.`);
57
+ throw new CliError("usage", `--${gone} was removed in 0.12.37: a wake-up is never re-queued; the watcher waits for the agent's ack (b9s wake ack <n>). Use --unacked-after <s> to choose when an unacknowledged wake-up is logged.`);
50
58
  const unackedAfter = Number(str(p.flags, "unacked-after") ?? "1800");
51
59
  if (!Number.isInteger(unackedAfter) || unackedAfter < 60)
52
60
  throw new CliError("usage", "--unacked-after must be a whole number of seconds, at least 60");
@@ -92,7 +100,7 @@ export async function watch(p, out) {
92
100
  }
93
101
  if (!exec && !once)
94
102
  throw new CliError("usage", 'watch --exec "<command>" [--interval 30] | watch --once (print and exit) | watch --exec ... --service (launchd on macOS, systemd on Linux)');
95
- const log = (m) => process.stderr.write(`${new Date().toISOString()} bschat watch[${name}]: ${m}\n`);
103
+ const log = (m) => process.stderr.write(`${new Date().toISOString()} b9s watch[${name}]: ${m}\n`);
96
104
  let stopping = false;
97
105
  let stoppingCode = 0;
98
106
  let signalStop = () => { };
@@ -199,6 +207,11 @@ export async function watch(p, out) {
199
207
  await Client.forAgent(loadAgent(name), undefined, { presence: false }).call("GET", "/me");
200
208
  }
201
209
  catch (e) {
210
+ if (e.code === "agent_benched") {
211
+ stopBenchedWatcher(name, e.message, log);
212
+ finish(0);
213
+ return stoppingCode;
214
+ }
202
215
  if (e.code === "unauthorized") {
203
216
  stopRevokedWatcher(name, log);
204
217
  finish(0);
@@ -222,6 +235,11 @@ export async function watch(p, out) {
222
235
  }
223
236
  }
224
237
  catch (e) {
238
+ if (e.code === "agent_benched") {
239
+ stopBenchedWatcher(name, e.message, log);
240
+ finish(0);
241
+ return stoppingCode;
242
+ }
225
243
  if (e.code === "unauthorized" && !once) {
226
244
  stopRevokedWatcher(name, log);
227
245
  finish(0);
@@ -236,13 +254,29 @@ export async function watch(p, out) {
236
254
  await waitIntervalOrStop(interval * 1000, stopped);
237
255
  continue;
238
256
  }
239
- const u = await gatherUpdates(name, { force: true, model: str(p.flags, "model"), delivery: "watch" });
257
+ let u;
258
+ try {
259
+ u = await gatherUpdates(name, { force: true, model: str(p.flags, "model"), delivery: "watch", dryRun: true });
260
+ }
261
+ catch (e) {
262
+ if (e.code === "agent_benched") {
263
+ stopBenchedWatcher(name, e.message, log);
264
+ finish(0);
265
+ return stoppingCode;
266
+ }
267
+ if (e.code === "unauthorized") {
268
+ stopRevokedWatcher(name, log);
269
+ finish(0);
270
+ return stoppingCode;
271
+ }
272
+ throw e;
273
+ }
240
274
  if (stopping)
241
275
  return stoppingCode;
242
276
  if (u) {
243
277
  const recovery = resumeBriefDelivered ? null : await recoveryBriefText(name, log);
244
- const update = resumeBriefDelivered ? u : formatUpdates(u, [recovery ?? recoveryBriefUnavailableText]);
245
- const total = update.counts.messages + update.counts.items + update.counts.followed + update.counts.digest;
278
+ const update = resumeBriefDelivered ? u : formatUpdates(omitMeasuresAlreadyIn(recovery, u), [recovery ?? recoveryBriefUnavailableText]);
279
+ const total = update.counts.messages + update.counts.items + update.counts.followed + update.counts.digest + update.counts.notices;
246
280
  const summary = update.text.split("\n")[0].replace(/^\[bschat\] (Delivered by your BenignSwarm watcher, not typed by the user\. )?/, "");
247
281
  let delivered = true;
248
282
  if (exec) {
@@ -260,6 +294,8 @@ export async function watch(p, out) {
260
294
  // Full mode delivers the update payload directly instead of using the wake path, so
261
295
  // record the same actual payload bytes and kinds through the hook's existing metric call.
262
296
  await reportDelivery(name, update.text, update.delivery.by_kind, "watch");
297
+ if (delivered)
298
+ writeState(name, { ...readState(name), ...(update.noticeNext ? { notice_state: update.noticeNext } : {}), ...(update.measureSnapshot ? { measure_state: update.measureSnapshot } : {}) });
263
299
  resumeBriefDelivered = resumeBriefDelivered || recoveryBriefWasDelivered(recovery, delivered);
264
300
  if (stopping)
265
301
  return stoppingCode;
@@ -283,7 +319,7 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
283
319
  const state = readState(name);
284
320
  const pending = state.watch_pending;
285
321
  if (pending) {
286
- // Acknowledged (bschat wake ack clears it too; this covers an ack written by another process).
322
+ // Acknowledged (b9s wake ack clears it too; this covers an ack written by another process).
287
323
  if (pending.seq !== undefined && (state.watch_acked ?? 0) >= pending.seq) {
288
324
  writeState(name, { ...state, watch_pending: undefined, watch_dormant_logged_at: undefined });
289
325
  log(`wake-up #${pending.seq} acknowledged`);
@@ -301,7 +337,7 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
301
337
  if (st.watch_pending) {
302
338
  const waited = Date.now() - st.watch_pending.at;
303
339
  if (waited > unackedAfter * 1000 && Date.now() - (st.watch_dormant_logged_at ?? 0) > 3_600_000) {
304
- log(`WAKE-UP ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}NOT ACKNOWLEDGED for ${Math.round(waited / 60_000)} min. Not queueing another. The agent may still be in a long turn; if its session is gone, start one for ${name} and have it run: bschat wake ack`);
340
+ log(`WAKE-UP ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}NOT ACKNOWLEDGED for ${Math.round(waited / 60_000)} min. Not queueing another. The agent may still be in a long turn; if its session is gone, start one for ${name} and have it run: b9s wake ack`);
305
341
  writeState(name, { ...st, watch_dormant_logged_at: Date.now() });
306
342
  }
307
343
  else if (once)
@@ -346,10 +382,10 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
346
382
  const recoveryPrompt = includeResumeBrief ? recovery ?? recoveryBriefUnavailableText : null;
347
383
  const wakePrefix = [
348
384
  ...(turnSink
349
- ? [`[bschat] Turn #${seq}, started by your BenignSwarm watcher because you were idle; not typed by the user. It is already acknowledged.`]
385
+ ? [`[b9s] Turn #${seq}, started by your BenignSwarm watcher because you were idle; not typed by the user. It is already acknowledged.`]
350
386
  : [
351
- `[bschat] Wake-up #${seq} from your BenignSwarm watcher, not typed by the user.`,
352
- `First acknowledge it: bschat wake ack ${seq} (no other wake-up comes until you do). If you are in the middle of a task, acknowledge, read, then carry on with the task.`,
387
+ `[b9s] Wake-up #${seq} from your BenignSwarm watcher, not typed by the user.`,
388
+ `First acknowledge it: b9s wake ack ${seq} (no other wake-up comes until you do). If you are in the middle of a task, acknowledge, read, then carry on with the task.`,
353
389
  ]),
354
390
  operatorNew ? `A human operator wrote to you directly.` : null,
355
391
  recoveryPrompt,
@@ -357,11 +393,11 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
357
393
  ].filter(Boolean);
358
394
  const wakeSuffix = [
359
395
  ...(u ? [`Run these, in order, to read it all:`, ...u.readCommands.map((c) => ` ${c}`)] : []),
360
- `Reply in chat with bschat send, not here. Your role and the project's process: bschat me, bschat process.`,
396
+ `Reply in chat with b9s send, not here. Your role and the project's process: b9s me, b9s process.`,
361
397
  ];
362
- const payload = u ? formatUpdates(u, wakePrefix, wakeSuffix) : null;
398
+ const payload = u ? formatUpdates(omitMeasuresAlreadyIn(recoveryPrompt, u), wakePrefix, wakeSuffix) : null;
363
399
  const wake = payload?.text ?? [...wakePrefix, "Nothing else is new.", ...wakeSuffix].join("\n");
364
- const total = u ? u.counts.messages + u.counts.items + u.counts.followed + u.counts.digest : 0;
400
+ const total = u ? u.counts.messages + u.counts.items + u.counts.followed + u.counts.digest + u.counts.notices : 0;
365
401
  // Both command templates receive this same bounded text, with the acknowledgement first.
366
402
  // `{summary}` commands get the same bounded prompt as `{text}`: this wrapper itself contains
367
403
  // the acknowledgement, operator note, process pointer, read commands, and delivery body.
@@ -374,6 +410,8 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
374
410
  ...(processNews ? { watch_process_woken: lag.version } : {}),
375
411
  watch_pending: { seq, at: Date.now(), inbox_after: st.inbox_after, channel_read: st.channel_read ?? {} },
376
412
  watch_operator_at: u?.latestOperatorAt ?? st.watch_operator_at,
413
+ ...(u ? { notice_state: u.noticeNext } : {}),
414
+ ...(u?.measureSnapshot ? { measure_state: u.measureSnapshot } : {}),
377
415
  watch_followed_since: undefined,
378
416
  watch_dormant_logged_at: undefined,
379
417
  });
@@ -400,7 +438,7 @@ async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq,
400
438
  // The turn runs in the background; turnStep follows it, acknowledges it once the session shows
401
439
  // it started, and reports how it ended.
402
440
  log(`${prefix}[${tier}] starting turn #${seq}: ${summary}`);
403
- // The agent's own bschat calls in the turn know who they are without any repo file.
441
+ // The agent's own b9s calls in the turn know who they are without any repo file.
404
442
  turnSink(startTurn(cmd, { ...env, BSCHAT_AGENT: name }, seq));
405
443
  }
406
444
  else {
@@ -425,7 +463,7 @@ async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq,
425
463
  return true;
426
464
  }
427
465
  /**
428
- * The agent's key no longer works here: it was moved to another machine (bschat-admin agent move
466
+ * The agent's key no longer works here: it was moved to another machine (b9s-admin agent move
429
467
  * revokes every key not minted for the new one) or retired. Keys are only ever revoked on purpose,
430
468
  * so this watcher stops for good and removes its own service; otherwise launchd or systemd would
431
469
  * restart it into the same 401 forever. A daemon that still runs the agent here reinstalls it.
@@ -441,6 +479,15 @@ function stopRevokedWatcher(name, log) {
441
479
  if (svc)
442
480
  removeService(svc);
443
481
  }
482
+ function stopBenchedWatcher(name, reason, log) {
483
+ const label = `${WATCH_LABEL_PREFIX}${name.replace("/", ".")}`;
484
+ const bare = name.split("/").pop();
485
+ const svc = watcherServices().find((s) => s.label === label)
486
+ ?? watcherServices().find((s) => { const a = s.args ?? []; const i = a.indexOf("--as"); return a[1] === "watch" && i >= 0 && (a[i + 1] === name || a[i + 1] === bare); });
487
+ log(`${reason}; stopping and removing ${svc?.label ?? `${label} (no service found; exiting)`}`);
488
+ if (svc)
489
+ removeService(svc);
490
+ }
444
491
  const TURN_RETRY_MS = 5 * 60_000;
445
492
  const KEY_CHECK_MS = 5 * 60_000;
446
493
  /**
@@ -496,10 +543,10 @@ async function turnStep(ctl, probe, timeoutMin, log, wake, name) {
496
543
  }
497
544
  return;
498
545
  }
499
- // bschat unpause: the operator switched the harness to an account with quota.
546
+ // b9s unpause: the operator switched the harness to an account with quota.
500
547
  const unpausedAt = readState(name).turn_unpaused_at ?? 0;
501
548
  if (ctl.pausedUntil > Date.now() && unpausedAt > ctl.pausedAt) {
502
- log(`usage-limit pause lifted by bschat unpause`);
549
+ log(`usage-limit pause lifted by b9s unpause`);
503
550
  ctl.pausedUntil = 0;
504
551
  ctl.failedAt = 0;
505
552
  }
@@ -577,7 +624,7 @@ async function ackTurn(name, seq, log) {
577
624
  log(`could not report the acknowledgement of turn #${seq} to the server: ${e.message}`);
578
625
  }
579
626
  }
580
- const processLine = (lag) => `The project process changed: it is version ${lag.version} now and ${lag.seen ? `you last read version ${lag.seen}` : "you have not read it"}. Read it first: bschat process`;
627
+ const processLine = (lag) => `The project process changed: it is version ${lag.version} now and ${lag.seen ? `you last read version ${lag.seen}` : "you have not read it"}. Read it first: b9s process`;
581
628
  const PROCESS_CHECK_MS = 5 * 60_000;
582
629
  /**
583
630
  * The current process version and the one this agent last read (GET /me), when the agent is
@@ -619,10 +666,10 @@ export function installWatcherService(name, exec, interval, followDelay, extraEn
619
666
  if (process.platform === "darwin")
620
667
  return installLaunchd(name, exec, interval, followDelay, extraEnv, activity, out, prune, turn);
621
668
  if (process.platform !== "linux")
622
- throw new CliError("unsupported", "--service runs watchers under launchd (macOS) or systemd (Linux); on this system run bschat watch under your own supervisor");
669
+ throw new CliError("unsupported", "--service runs watchers under launchd (macOS) or systemd (Linux); on this system run b9s watch under your own supervisor");
623
670
  const slug = name.replace("/", ".");
624
671
  const label = `${WATCH_LABEL_PREFIX}${slug}`;
625
- const logDir = join(homedir(), ".bschat", "logs");
672
+ const logDir = join(configRoot(), "logs");
626
673
  mkdirSync(systemdUserDir(), { recursive: true });
627
674
  mkdirSync(logDir, { recursive: true });
628
675
  const args = [requireInstall().bin, "watch", "--as", name, "--exec", exec, "--interval", String(interval), "--follow-delay", String(followDelay), ...(activity ? ["--activity", activity] : []), ...(prune ? ["--prune"] : []), ...turnArgs(turn)];
@@ -639,22 +686,22 @@ export function installWatcherService(name, exec, interval, followDelay, extraEn
639
686
  linger === false ? `Linger is off for ${userInfo().username}: systemd stops this watcher when your last login session on this machine ends. To keep it running: loginctl enable-linger ${userInfo().username}` : null,
640
687
  `Stop it: systemctl --user disable --now ${label}.service`,
641
688
  `Logs: ${logDir}/watch.${slug}.*.log`,
642
- `Check it: bschat doctor`,
689
+ `Check it: b9s doctor`,
643
690
  `The watcher runs from ${process.cwd()} so the repo identity file applies.`,
644
691
  ].filter(Boolean).join("\n"), { unit: path, label, program: args[0], linger });
645
692
  }
646
- /** Writes a launchd agent that keeps `bschat watch` running for this identity on macOS. */
693
+ /** Writes a launchd agent that keeps `b9s watch` running for this identity on macOS. */
647
694
  function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, out, prune = false, turn = null) {
648
695
  if (process.platform !== "darwin")
649
- throw new CliError("unsupported", "--launchd is macOS only; on Linux run `bschat watch` under a systemd user service");
696
+ throw new CliError("unsupported", "--launchd is macOS only; on Linux run `b9s watch` under a systemd user service");
650
697
  const slug = name.replace("/", ".");
651
698
  const label = `org.benignswarm.watch.${slug}`;
652
699
  const dir = join(homedir(), "Library", "LaunchAgents");
653
- const logDir = join(homedir(), ".bschat", "logs");
700
+ const logDir = join(configRoot(), "logs");
654
701
  mkdirSync(dir, { recursive: true });
655
702
  mkdirSync(logDir, { recursive: true });
656
703
  // The machine's one recorded install, never the running copy (an npx cache frozen at this
657
- // version) or whatever `bschat` a PATH lookup finds: an upgrade must reach every watcher.
704
+ // version) or whatever `b9s` a PATH lookup finds: an upgrade must reach every watcher.
658
705
  const program = [requireInstall().bin];
659
706
  const plist = `<?xml version="1.0" encoding="UTF-8"?>
660
707
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -687,7 +734,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
687
734
  const sess = sessionOfExec(exec);
688
735
  if (sess)
689
736
  bindSession(sess.kind, sess.id, name);
690
- out.print(`Wrote ${path} and (re)loaded it: the watcher is running ${program[0]}.${Object.keys(extraEnv).length ? `\nCaptured env: ${Object.keys(extraEnv).join(", ")} (re-run this command if the harness restarts and these change)` : ""}\nStop it: launchctl bootout gui/$(id -u)/${label}\nLogs: ${logDir}/watch.${slug}.*.log\nCheck it: bschat doctor\nThe watcher runs from ${process.cwd()} so the repo identity file applies.`, { plist: path, label, program: program[0] });
737
+ out.print(`Wrote ${path} and (re)loaded it: the watcher is running ${program[0]}.${Object.keys(extraEnv).length ? `\nCaptured env: ${Object.keys(extraEnv).join(", ")} (re-run this command if the harness restarts and these change)` : ""}\nStop it: launchctl bootout gui/$(id -u)/${label}\nLogs: ${logDir}/watch.${slug}.*.log\nCheck it: b9s doctor\nThe watcher runs from ${process.cwd()} so the repo identity file applies.`, { plist: path, label, program: program[0] });
691
738
  }
692
739
  const turnArgs = (t) => (t ? ["--turn", "--turn-timeout", String(t.timeout), "--harness", t.harness, "--session", t.session] : []);
693
740
  function escapeXml(s) {
@@ -36,8 +36,8 @@ export async function unitWorktrees(creds, project) {
36
36
  }
37
37
  /**
38
38
  * The project's worktree registry.
39
- * bschat worktrees every worktree the project knows about: machine, path, branch, dirty, merged, who, suggestion
40
- * bschat worktrees scan report every linked worktree of the repository you are in (run on each machine)
39
+ * b9s worktrees every worktree the project knows about: machine, path, branch, dirty, merged, who, suggestion
40
+ * b9s worktrees scan report every linked worktree of the repository you are in (run on each machine)
41
41
  */
42
42
  export async function worktrees(p, out) {
43
43
  const sub = p.positionals[1];
@@ -118,13 +118,13 @@ export async function worktrees(p, out) {
118
118
  state: `${w.dirty === null ? "?" : w.dirty ? "dirty" : "clean"}, ${w.merged === null ? "?" : w.merged ? "merged" : `${w.ahead ?? "?"} ahead`}`,
119
119
  idle: `${w.idle_days}d`, who: w.agents.map((a) => a.name).slice(0, 3).join(","), unit: w.unit ? `#${w.unit.number}` : "-",
120
120
  }));
121
- out.print(rows.length ? table(rows, ["suggestion", "machine", "path", "branch", "state", "idle", "who", "unit"]) : "(no worktrees recorded; agents register them by working, or run: bschat worktrees scan)", r);
121
+ out.print(rows.length ? table(rows, ["suggestion", "machine", "path", "branch", "state", "idle", "who", "unit"]) : "(no worktrees recorded; agents register them by working, or run: b9s worktrees scan)", r);
122
122
  }
123
123
  /** Scan the repository at cwd and report it. Shared with the watcher, which runs it periodically. */
124
124
  export async function scanProject(creds, project) {
125
125
  const scan = scanWorktrees();
126
126
  if (!scan)
127
- throw new CliError("not_a_repo", "the current directory is not inside a git repository", "Run bschat worktrees scan from a checkout of the project's repository.");
127
+ throw new CliError("not_a_repo", "the current directory is not inside a git repository", "Run b9s worktrees scan from a checkout of the project's repository.");
128
128
  const machine = creds.machine || defaultMachine();
129
129
  const client = Client.forAgent(creds, undefined, { presence: false });
130
130
  const r = await client.call("POST", `/projects/${project}/worktrees/scan`, { machine, repo: scan.repo, worktrees: scan.worktrees });