benignswarm 0.12.96 → 0.12.97

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, min_tier: "routine" };
50
+ const { min_tier: _legacyMinTier, ...base } = i >= 0 ? vocab[i] : { name, meaning: "", require_evidence: false, require_rebased: false, expert_role: null };
51
51
  const next = {
52
52
  ...base,
53
53
  ...(f.meaning !== undefined ? { meaning: f.meaning } : {}),
@@ -55,7 +55,6 @@ 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 } : {}),
59
58
  };
60
59
  if (op === "add" && !next.meaning.trim())
61
60
  throw new CliError("usage", `a tag needs a meaning, the sentence workers decide by: --meaning ".."`);
@@ -129,10 +128,11 @@ function describeProcess(r) {
129
128
  ` requires: scope ${d.require_scope ? "yes" : "no"}, evidence to submit ${d.require_evidence_to_submit ? "yes" : "no"}; default approver ${d.default_approver_role ?? "none"}; assigners ${d.assigners.join(", ") || "none"}`,
130
129
  ` 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"}`,
131
130
  ` capabilities: ${(d.capabilities ?? []).map((c) => `${c.name} (${c.scope}${c.min_version ? ` >= ${c.min_version}` : ""})`).join(", ") || "none"}`,
131
+ ` heavy jobs: ${Object.entries(d.heavy_jobs ?? {}).map(([name, job]) => `${name} (${job.memory_gib} GiB; ${job.purpose}; workflows ${job.workflows.join(", ")})`).join("; ") || "none"}`,
132
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)"}`,
133
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"}`,
134
134
  v.length ? `Tags:` : `No tag vocabulary: every unit goes to the default approver.`,
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
+ ...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(", ")}` : ""}`),
136
136
  ].join("\n");
137
137
  }
138
138
  export async function processAdmin(action, rest, p, out) {
@@ -189,12 +189,9 @@ export async function processAdmin(action, rest, p, out) {
189
189
  const op = tagOperationFirst ? rest[0] : rest[1];
190
190
  const tag = tagProjectFlag ? (rest[2] ?? rest[1]) : rest[2];
191
191
  if (!["add", "edit", "remove"].includes(op) || !tag)
192
- throw new CliError("usage", 'b9s-admin process tag add|edit|remove <project> <tag> [--meaning ".."] [--tier routine|careful|expert] [--require-evidence yes|no] [--require-rebased yes|no] [--expert-role r|none] [--requires name,name] (legacy project-first order also accepted; for operation-first with project add, edit, or remove, use: process tag <op> <tag> --project <project>)');
192
+ throw new CliError("usage", 'b9s-admin process tag add|edit|remove <project> <tag> [--meaning ".."] [--require-evidence yes|no] [--require-rebased yes|no] [--expert-role r|none] [--requires name,name] (legacy project-first order also accepted; for operation-first with project add, edit, or remove, use: process tag <op> <tag> --project <project>)');
193
193
  const r = await get();
194
- const tier = str(p.flags, "tier");
195
- if (tier !== undefined && !["routine", "careful", "expert"].includes(tier))
196
- throw new CliError("usage", "--tier must be routine, careful, or expert");
197
- 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 });
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")) });
198
195
  return publish({ vocabulary }, `tag #${tag.replace(/^#/, "")} ${op === "add" ? "added" : op === "edit" ? "edited" : "removed"}`);
199
196
  }
200
197
  case "timing":
@@ -21,6 +21,8 @@ export async function retire(p, out) {
21
21
  throw new CliError("usage", 'retire --title "..." (--body "..." | --body-file notes.md) [--handoff-to @agent|@role:x] [--evidence id,id] [--project p]');
22
22
  let body = str(p.flags, "body");
23
23
  const file = str(p.flags, "body-file");
24
+ if (file && body !== undefined)
25
+ throw new CliError("usage", "retire accepts --body or --body-file, not both");
24
26
  if (file) {
25
27
  try {
26
28
  body = readFileSync(file, "utf8");
@@ -87,6 +89,8 @@ export async function checkpoint(p, out) {
87
89
  const title = str(p.flags, "title") ?? p.positionals.slice(1).join(" ").trim();
88
90
  let body = str(p.flags, "body");
89
91
  const file = str(p.flags, "body-file");
92
+ if (file && body !== undefined)
93
+ throw new CliError("usage", "checkpoint accepts --body or --body-file, not both");
90
94
  if (file) {
91
95
  try {
92
96
  body = readFileSync(file, "utf8");
@@ -0,0 +1,27 @@
1
+ import { str } from "../args.js";
2
+ import { CliError } from "../errors.js";
3
+ import { packTemplateCatalog, validateTemplateCatalog } from "../templates.js";
4
+ export async function templates(p, out) {
5
+ const action = p.positionals[1];
6
+ if (action !== "validate" && action !== "pack")
7
+ throw new CliError("usage", "templates needs validate or pack", "Run: b9s templates validate [--root <repo>] | b9s templates pack --signing-key <pem> [--root <repo>] [--out <dir>]");
8
+ const root = str(p.flags, "root") ?? process.cwd();
9
+ try {
10
+ if (action === "validate") {
11
+ const catalog = validateTemplateCatalog(root);
12
+ const result = { release: catalog.release, templates: catalog.entries.map(t => `${t.family}/${t.version}`) };
13
+ out.print(`Catalog ${result.release}: ${result.templates.length} validated templates\n${result.templates.join("\n")}`, result);
14
+ return;
15
+ }
16
+ const key = str(p.flags, "signing-key");
17
+ if (!key)
18
+ throw new CliError("usage", "templates pack requires --signing-key <pem>");
19
+ const result = packTemplateCatalog(root, str(p.flags, "out") ?? "dist/template-releases", key);
20
+ out.print(`Created ${result.archive}\nSHA-256 ${result.sha256}\nSignature ${result.signature}\nSource ${result.sourceRevision}`, result);
21
+ }
22
+ catch (error) {
23
+ if (error instanceof CliError)
24
+ throw error;
25
+ throw new CliError("template_catalog", error.message);
26
+ }
27
+ }
@@ -1,6 +1,6 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
2
  import { bindSession, sessionOfExec, threadOfExec } from "../sessions.js";
3
- import { startTurn, stopTurn } from "../turn.js";
3
+ import { DEFAULT_TURN_COALESCE_SECONDS, MAX_TURN_COALESCE_SECONDS, shouldDeferTurn, startTurn, stopTurn } from "../turn.js";
4
4
  import { drainingUntil } from "../maintenance.js";
5
5
  import { probeFor, turnHarness } from "../harnesses.js";
6
6
  import { applyAck } from "./wake.js";
@@ -70,6 +70,9 @@ export async function watch(p, out) {
70
70
  const turnTimeout = Number(str(p.flags, "turn-timeout") ?? "180");
71
71
  if (!Number.isInteger(turnTimeout) || turnTimeout < 5)
72
72
  throw new CliError("usage", "--turn-timeout must be a whole number of minutes, at least 5");
73
+ const turnCoalesceSeconds = Number(str(p.flags, "turn-coalesce-seconds") ?? String(DEFAULT_TURN_COALESCE_SECONDS));
74
+ if (!Number.isInteger(turnCoalesceSeconds) || turnCoalesceSeconds < 0 || turnCoalesceSeconds > MAX_TURN_COALESCE_SECONDS)
75
+ throw new CliError("usage", `--turn-coalesce-seconds must be a whole number between 0 and ${MAX_TURN_COALESCE_SECONDS}`);
73
76
  const turnsPerHour = Number(str(p.flags, "turns-per-hour") ?? String(DEFAULT_TURNS_PER_HOUR));
74
77
  if (!Number.isInteger(turnsPerHour) || turnsPerHour < 1 || turnsPerHour > MAX_TURNS_PER_HOUR)
75
78
  throw new CliError("usage", `--turns-per-hour must be a whole number between 1 and ${MAX_TURNS_PER_HOUR}`);
@@ -80,6 +83,8 @@ export async function watch(p, out) {
80
83
  throw new CliError("usage", "--turns-per-hour is only used with --turn");
81
84
  if (!turnMode && p.flags["unproductive-per-hour"] !== undefined)
82
85
  throw new CliError("usage", "--unproductive-per-hour is only used with --turn");
86
+ if (!turnMode && p.flags["turn-coalesce-seconds"] !== undefined)
87
+ throw new CliError("usage", "--turn-coalesce-seconds is only used with --turn");
83
88
  const thread = exec ? threadOfExec(exec) : null;
84
89
  // Which harness runs the turns and the session they continue. Codex watchers installed before
85
90
  // 0.12.66 carry neither flag: their thread is in the exec command.
@@ -104,7 +109,7 @@ export async function watch(p, out) {
104
109
  if (providerName === "deepseek" && harness !== "claude-code")
105
110
  throw new CliError("usage", "--provider deepseek requires --harness claude-code");
106
111
  const model = str(p.flags, "model") ?? (providerName === "deepseek" ? "deepseek-flash" : undefined);
107
- turn = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, provider: providerName, model };
112
+ turn = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider: providerName, model };
108
113
  }
109
114
  else if (p.flags.provider !== undefined) {
110
115
  throw new CliError("usage", "--provider is only used with --turn --harness claude-code");
@@ -254,7 +259,7 @@ export async function watch(p, out) {
254
259
  try {
255
260
  if (probe)
256
261
  await turnStep(ctl, probe, turnTimeout, log, async (sink, beforeTurn) => {
257
- const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, turn?.model ?? str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "claude-code" ? turn.provider : undefined, turn?.harness === "dsh", () => probe.beginTurn?.(), beforeTurn, turn?.harness === "claude-code" ? turn.session : undefined);
262
+ const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, turn?.model ?? str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "claude-code" ? turn.provider : undefined, turn?.harness === "dsh", () => probe.beginTurn?.(), beforeTurn, turn?.harness === "claude-code" ? turn.session : undefined, turn?.coalesceSeconds ?? 0);
258
263
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
259
264
  }, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour);
260
265
  else {
@@ -279,7 +284,7 @@ export async function watch(p, out) {
279
284
  return stoppingCode;
280
285
  if (once)
281
286
  return;
282
- await waitIntervalOrStop(interval * 1000, stopped);
287
+ await waitIntervalOrStop(watchPollMs(interval), stopped);
283
288
  continue;
284
289
  }
285
290
  let u;
@@ -333,17 +338,21 @@ export async function watch(p, out) {
333
338
  }
334
339
  if (once)
335
340
  return;
336
- await waitIntervalOrStop(interval * 1000, stopped);
341
+ await waitIntervalOrStop(watchPollMs(interval), stopped);
337
342
  }
338
343
  return stoppingCode;
339
344
  }
345
+ function watchPollMs(intervalSeconds) {
346
+ const override = Number(process.env.B9S_WATCH_INTERVAL_MS);
347
+ return Number.isFinite(override) && override > 0 ? Math.max(50, Math.floor(override)) : intervalSeconds * 1000;
348
+ }
340
349
  async function waitIntervalOrStop(ms, stopped) {
341
350
  let timer;
342
351
  await Promise.race([new Promise((resolve) => { timer = setTimeout(resolve, ms); }), stopped]);
343
352
  if (timer)
344
353
  clearTimeout(timer);
345
354
  }
346
- async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn, allowTurn, sessionId) {
355
+ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn, allowTurn, sessionId, turnCoalesceSeconds = 0, dependencies = {}) {
347
356
  const state = readState(name);
348
357
  const pending = state.watch_pending;
349
358
  if (pending) {
@@ -372,11 +381,35 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
372
381
  log(`wake-up ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}queued ${Math.round(waited / 1000)}s ago and not acknowledged; not queueing another`);
373
382
  return { sent: false, recoveryBriefDelivered: false };
374
383
  }
375
- const u = await gatherUpdates(name, { force: true, model, delivery: "watch", dryRun: true });
384
+ const u = await (dependencies.gatherUpdates ?? gatherUpdates)(name, { force: true, model, delivery: "watch", dryRun: true });
376
385
  // A process change is news too. Watched harnesses never see the Claude Code hook re-deliver the
377
386
  // standing rules, so the watcher compares the version the agent last read with the current one.
378
- const lag = await processLag(name, st, !!u, log);
387
+ const lag = await (dependencies.processLag ?? processLag)(name, st, !!u, log);
379
388
  const processNews = !!lag && st.watch_process_woken !== lag.version;
389
+ const operatorNew = !!u && u.latestOperatorAt !== null && u.latestOperatorAt !== (st.watch_operator_at ?? null);
390
+ // Turn mode is a direct-work runner: role, followed and process-only changes remain available
391
+ // to the agent's normal inbox/hook, but must not start another headless turn on their own.
392
+ if (turnSink && u?.tier !== "direct") {
393
+ if (st.watch_turn_coalesce_since !== undefined)
394
+ writeState(name, { ...readState(name), watch_turn_coalesce_since: undefined });
395
+ if (once)
396
+ log(u ? `only ${u.tier}-level unread; not starting a turn` : "no direct work pending; not starting a turn");
397
+ return { sent: false, recoveryBriefDelivered: false };
398
+ }
399
+ if (turnSink && turnCoalesceSeconds > 0 && u?.tier === "direct") {
400
+ const updateAt = u.firstDirectAt ? Date.parse(u.firstDirectAt) : Number.NaN;
401
+ const firstPendingAt = Number.isFinite(updateAt)
402
+ ? Math.min(updateAt, st.watch_turn_coalesce_since ?? updateAt)
403
+ : st.watch_turn_coalesce_since ?? Date.now();
404
+ if (shouldDeferTurn({ pending: true, firstPendingAt, now: Date.now(), seconds: turnCoalesceSeconds, operator: operatorNew, urgent: u.urgent })) {
405
+ writeState(name, { ...readState(name), watch_turn_coalesce_since: firstPendingAt });
406
+ const readyAt = new Date(firstPendingAt + turnCoalesceSeconds * 1000).toISOString();
407
+ log(`direct wake-up is coalescing until ${readyAt}; later direct items will join it`);
408
+ return { sent: false, recoveryBriefDelivered: false };
409
+ }
410
+ }
411
+ if (turnSink && st.watch_turn_coalesce_since !== undefined)
412
+ writeState(name, { ...readState(name), watch_turn_coalesce_since: undefined });
380
413
  if (!u) {
381
414
  if (st.watch_followed_since)
382
415
  writeState(name, { ...st, watch_followed_since: undefined });
@@ -405,7 +438,6 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
405
438
  }
406
439
  }
407
440
  const seq = (st.watch_seq ?? 0) + 1;
408
- const operatorNew = !!u && u.latestOperatorAt !== null && u.latestOperatorAt !== (st.watch_operator_at ?? null);
409
441
  const recovery = includeResumeBrief ? await recoveryBriefText(name, log) : null;
410
442
  const recoveryPrompt = includeResumeBrief ? recovery ?? recoveryBriefUnavailableText : null;
411
443
  const wakePrefix = [
@@ -441,6 +473,7 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
441
473
  ...(u ? { notice_state: u.noticeNext } : {}),
442
474
  ...(u?.measureSnapshot ? { measure_state: u.measureSnapshot } : {}),
443
475
  watch_followed_since: undefined,
476
+ watch_turn_coalesce_since: undefined,
444
477
  watch_dormant_logged_at: undefined,
445
478
  });
446
479
  return { sent: true, recoveryBriefDelivered: recoveryBriefWasDelivered(recovery, true) };
@@ -899,7 +932,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
899
932
  bindSession(sess.kind, sess.id, name);
900
933
  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] });
901
934
  }
902
- const turnArgs = (t) => (t ? ["--turn", "--turn-timeout", String(t.timeout), "--turns-per-hour", String(t.turnsPerHour), "--unproductive-per-hour", String(t.unproductivePerHour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--harness", t.harness, "--session", t.session, ...(t.provider === "deepseek" ? ["--provider", t.provider] : []), ...(t.model ? ["--model", t.model] : [])] : []);
935
+ export const turnArgs = (t) => (t ? ["--turn", "--turn-timeout", String(t.timeout), "--turns-per-hour", String(t.turnsPerHour), "--unproductive-per-hour", String(t.unproductivePerHour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--turn-coalesce-seconds", String(t.coalesceSeconds), "--harness", t.harness, "--session", t.session, ...(t.provider === "deepseek" ? ["--provider", t.provider] : []), ...(t.model ? ["--model", t.model] : [])] : []);
903
936
  function escapeXml(s) {
904
937
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
905
938
  }