benignswarm 0.12.98 → 0.12.99

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.
@@ -0,0 +1,396 @@
1
+ import { bool, str } from "../args.js";
2
+ import { Client } from "../client.js";
3
+ import { loadAdmin, resolveAdminName } from "../config.js";
4
+ import { CliError } from "../errors.js";
5
+ import { table } from "../output.js";
6
+ const adminClient = (p) => Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
7
+ /** Parses provider/harness/canonical_model/effort, refusing shorthand guesses. */
8
+ export function parseClassSpec(raw) {
9
+ const parts = raw.trim().split("/");
10
+ if (parts.length !== 4 || parts.some((x) => !x.trim())) {
11
+ throw new CliError("usage", "routing class must be <provider>/<harness>/<canonical_model>/<effort> (e.g. anthropic/claude-code/claude-sonnet-4-5/high)");
12
+ }
13
+ const [provider, harness, canonical_model, effort] = parts.map((x) => x.trim());
14
+ return { provider: provider, harness: harness, canonical_model: canonical_model, effort: effort };
15
+ }
16
+ export function formatClassSpec(cls) {
17
+ if (!cls)
18
+ return "unknown";
19
+ return `${cls.provider ?? "unknown"}/${cls.harness ?? "unknown"}/${cls.canonical_model ?? cls.model ?? "unknown"}/${cls.effort ?? "unknown"}`;
20
+ }
21
+ function formatEstimate(row) {
22
+ if (row.weighted_estimate === null || row.weighted_estimate === undefined)
23
+ return "unknown";
24
+ if (row.unit === "milliseconds")
25
+ return `${Math.round(Number(row.weighted_estimate) / 1000)}s`;
26
+ return `${Math.round(Number(row.weighted_estimate) * 100)}%`;
27
+ }
28
+ function formatInterval(row) {
29
+ if (!row.interval_95)
30
+ return "-";
31
+ if (row.unit === "milliseconds") {
32
+ return `[${Math.round(row.interval_95.lower / 1000)}s, ${Math.round(row.interval_95.upper / 1000)}s]`;
33
+ }
34
+ return `[${Math.round(row.interval_95.lower * 100)}%, ${Math.round(row.interval_95.upper * 100)}%]`;
35
+ }
36
+ /** Formats class x tag confidence rows into an operator-readable matrix table. */
37
+ export function formatConfidenceMatrix(rows, opts = {}) {
38
+ const filtered = rows.filter((r) => (!opts.mode || r.mode === opts.mode) && (!opts.tag || `#${r.tag}` === `#${opts.tag.replace(/^#/, "")}`));
39
+ if (!filtered.length)
40
+ return "(no confidence matrix observations match filters)";
41
+ const mapped = filtered.map((r) => ({
42
+ mode: r.mode,
43
+ tag: `#${r.tag}`,
44
+ class: formatClassSpec(r.routing_class),
45
+ measure: r.outcome_measure,
46
+ estimate: formatEstimate(r),
47
+ ci95: formatInterval(r),
48
+ eff_n: String(Math.round((Number(r.effective_sample_size ?? 0)) * 10) / 10),
49
+ n: String(r.denominator ?? 0),
50
+ status: r.status,
51
+ guardrail: r.quality_guardrail ?? "-",
52
+ }));
53
+ return table(mapped, ["mode", "tag", "class", "measure", "estimate", "ci95", "eff_n", "n", "status", "guardrail"]);
54
+ }
55
+ /** Formats hard required_class + build/review assignment explanation recorded on a unit. */
56
+ export function formatUnitRoutingExplanation(u) {
57
+ const lines = [];
58
+ if (u.required_class) {
59
+ const rc = u.required_class;
60
+ lines.push(` required_class: ${formatClassSpec(rc)} (by ${rc.actor_name ?? "operator"}; reason: ${rc.reason ?? "none"})`);
61
+ }
62
+ if (u.route_decision) {
63
+ const rd = u.route_decision;
64
+ lines.push(` build_route: ${rd.chosen_agent ?? "queued"} · ${formatClassSpec(rd.chosen_class)} · mode ${rd.mode ?? "none"} · ${rd.reason ?? ""}${rd.cost_basis ? ` (cost basis: ${rd.cost_basis})` : ""}`);
65
+ if (rd.preferred_class_unavailable) {
66
+ const pu = rd.preferred_class_unavailable;
67
+ lines.push(` preferred unavailable: ${formatClassSpec(pu.preferred_class)} (${Array.isArray(pu.blockers) ? pu.blockers.join("; ") : pu.reason ?? "unavailable"})`);
68
+ }
69
+ if (Array.isArray(rd.per_tag) && rd.per_tag.length) {
70
+ lines.push(` per-tag: ${rd.per_tag.map((t) => `#${t.tag} score=${t.score ?? "?"}${t.provisional ? "" : " (floor)"}`).join(", ")}`);
71
+ }
72
+ }
73
+ if (u.review_route) {
74
+ const rr = u.review_route;
75
+ lines.push(` review_route: mode ${rr.mode ?? "none"} · chosen ${(rr.selected_reviewers ?? []).map((x) => `${x.agent ?? x.name}(${formatClassSpec(x.routing_class)})`).join(", ") || "none"} · ${rr.reason ?? ""}`);
76
+ }
77
+ if (Array.isArray(u.dispatch_reasons) && u.dispatch_reasons.length) {
78
+ lines.push(` dispatch_reasons:`);
79
+ for (const d of u.dispatch_reasons.slice(0, 8)) {
80
+ lines.push(` - ${d.agent ?? "?"} (${formatClassSpec(d.routing_class)}): eligible=${Boolean(d.eligible)}${d.score !== undefined ? ` score=${d.score}` : ""}${d.reason ? ` · ${d.reason}` : ""}`);
81
+ }
82
+ }
83
+ return lines;
84
+ }
85
+ export function formatExplorationSummary(label, state) {
86
+ if (!state)
87
+ return ` ${label}_exploration: unknown`;
88
+ return ` ${label}_exploration: budget ${state.budget_percent ?? 0}%, spent ${state.spent_percent ?? 0}% (${state.explored_assignments ?? 0}/${state.total_assignments ?? 0}), remaining ${state.remaining_percent ?? 0}%, ${state.paused ? `PAUSED (${state.pause_reason ?? "paused"})` : "active"}`;
89
+ }
90
+ export function formatPoolSuggestion(s) {
91
+ const before = Object.entries(s.slot_effect?.before ?? {}).map(([k, v]) => `${k}=${v}`).join(", ");
92
+ const after = Object.entries(s.slot_effect?.after ?? {}).map(([k, v]) => `${k}=${v}`).join(", ");
93
+ const costBasis = s.evidence_snapshot?.cost_basis ?? "unknown";
94
+ const machines = Array.isArray(s.evidence_snapshot?.constraints?.eligible_machines)
95
+ ? s.evidence_snapshot.constraints.eligible_machines.join(", ") || "none"
96
+ : "unknown";
97
+ return [
98
+ `${s.id} [${s.status}] pool ${s.pool_name} variant ${s.variant_tag} (#${s.tag}, basis: ${s.basis})`,
99
+ ` weight ${s.current_weight} -> ${s.suggested_weight}; slots(${s.slot_effect?.pool_count ?? "?"}): ${before} -> ${after}`,
100
+ ` ${s.summary}`,
101
+ ` machines: ${machines}; cost_basis: ${costBasis}${s.decision_note ? `; note: ${s.decision_note}` : ""}`,
102
+ ].join("\n");
103
+ }
104
+ function parseBoolChoice(raw, flag) {
105
+ const norm = raw.trim().toLowerCase();
106
+ if (norm === "yes" || norm === "true" || norm === "on")
107
+ return true;
108
+ if (norm === "no" || norm === "false" || norm === "off")
109
+ return false;
110
+ throw new CliError("usage", `--${flag} must be yes|no (or true|false)`);
111
+ }
112
+ function normalizeTag(raw) {
113
+ const t = raw.trim().replace(/^#/, "").toLowerCase();
114
+ if (!t)
115
+ throw new CliError("usage", "tag name is required");
116
+ return t;
117
+ }
118
+ function parseUnitNum(raw, usage) {
119
+ const n = Number(raw);
120
+ if (!raw || !Number.isInteger(n) || n < 1)
121
+ throw new CliError("usage", usage);
122
+ return n;
123
+ }
124
+ export async function runRequiredClassUpdate(c, project, unitNumber, p, out) {
125
+ const clear = bool(p.flags, "clear");
126
+ const clsRaw = str(p.flags, "class");
127
+ const reason = str(p.flags, "reason")?.trim();
128
+ if ((clear && clsRaw) || (!clear && !clsRaw) || !reason) {
129
+ throw new CliError("usage", 'required-class <project> <unit> (--class <provider>/<harness>/<canonical_model>/<effort> | --clear) --reason "why"');
130
+ }
131
+ const spec = clear ? null : parseClassSpec(clsRaw);
132
+ const body = clear
133
+ ? { required_class: null, reason }
134
+ : { required_class: { ...spec, reason }, reason };
135
+ const r = await c.call("POST", `/projects/${project}/work-units/${unitNumber}/required-class`, body);
136
+ const rc = r.unit?.required_class;
137
+ out.print(rc
138
+ ? `WU #${unitNumber}: required_class set to ${formatClassSpec(rc)} (reason: ${rc.reason}).`
139
+ : `WU #${unitNumber}: required_class cleared (reason: ${reason}).`, r);
140
+ }
141
+ /**
142
+ * Operator routing console CLI (WU #242):
143
+ * b9s-admin routing show <project> [--mode build|review] [--tag <tag>]
144
+ * b9s-admin routing policy <project> [--weights q,t,c] [--quality-target <0..100|none>] [--half-life <days>] [--min-samples <n>] [--build-explore <0..20>] [--review-explore <0..20>] [--pause-build yes|no] [--pause-review yes|no] [--reason "why"]
145
+ * b9s-admin routing explain <project> <unit>
146
+ * b9s-admin routing required-class <project> <unit> (--class p/h/m/e | --clear) --reason "why"
147
+ * b9s-admin routing tag-required-class <project> <tag> (--class p/h/m/e | --clear) --reason "why"
148
+ * b9s-admin routing tier-migration <project>
149
+ * b9s-admin routing pool-suggestions <project> [--status pending|accepted|rejected|superseded|all]
150
+ */
151
+ export async function routingAdmin(action, rest, p, out) {
152
+ const c = adminClient(p);
153
+ switch (action) {
154
+ case "show": {
155
+ const project = rest[0];
156
+ if (!project)
157
+ throw new CliError("usage", "routing show <project> [--mode build|review] [--tag <tag>]");
158
+ const mode = str(p.flags, "mode");
159
+ if (mode && mode !== "build" && mode !== "review")
160
+ throw new CliError("usage", "--mode must be build or review");
161
+ const tag = str(p.flags, "tag");
162
+ const r = await c.call("GET", `/projects/${project}/routing`);
163
+ const pol = r.policy ?? {};
164
+ const w = pol.weights ?? { quality: 65, time: 20, cost: 15 };
165
+ const lines = [
166
+ `Routing for ${r.project} (cost tracking is currently unavailable cleanly until WU #236):`,
167
+ ` policy: weights quality=${w.quality}% time=${w.time}% cost=${w.cost}%, quality target=${pol.quality_target_percent ?? "none"}, half-life=${pol.recency_half_life_days ?? 30}d, min samples=${pol.minimum_sample_count ?? 8}`,
168
+ formatExplorationSummary("build", r.exploration?.build),
169
+ formatExplorationSummary("review", r.exploration?.review),
170
+ r.vocabulary_required_classes?.length
171
+ ? ` tag required classes: ${r.vocabulary_required_classes.map((x) => `#${x.tag}=${formatClassSpec(x.required_class)}`).join("; ")}`
172
+ : ` tag required classes: none`,
173
+ "",
174
+ "Confidence matrix:",
175
+ formatConfidenceMatrix(r.confidence ?? [], { mode, tag }),
176
+ ];
177
+ if (Array.isArray(r.recent_build_decisions) && r.recent_build_decisions.length) {
178
+ lines.push("", "Recent build decisions:");
179
+ for (const d of r.recent_build_decisions.slice(0, 8)) {
180
+ lines.push(` WU #${d.unit_number} (${d.mode}): ${d.chosen_agent ?? "?"} · ${formatClassSpec(d.chosen_class)} · ${d.reason ?? ""}`);
181
+ }
182
+ }
183
+ if (Array.isArray(r.recent_review_decisions) && r.recent_review_decisions.length) {
184
+ lines.push("", "Recent review decisions:");
185
+ for (const d of r.recent_review_decisions.slice(0, 8)) {
186
+ lines.push(` WU #${d.unit_number} (${d.mode}): ${d.reason ?? ""}`);
187
+ }
188
+ }
189
+ if (Array.isArray(r.comparisons) && r.comparisons.length) {
190
+ lines.push("", `Recent comparisons (${r.comparisons.length}): ${r.comparisons.slice(0, 5).map((x) => `pair ${x.compare_group_id ?? x.id ?? "?"}`).join(", ")}`);
191
+ }
192
+ out.print(lines.join("\n"), r);
193
+ return;
194
+ }
195
+ case "policy": {
196
+ const project = rest[0];
197
+ if (!project)
198
+ throw new CliError("usage", "routing policy <project> [--weights q,t,c] [--quality-target <0..100|none>] [--half-life <days>] [--min-samples <n>] [--build-explore <0..20>] [--review-explore <0..20>] [--pause-build yes|no] [--pause-review yes|no] [--reason \"why\"]");
199
+ const current = await c.call("GET", `/projects/${project}/process`);
200
+ const nextPolicy = { ...(current.process?.definition?.routing_policy ?? {}) };
201
+ let changed = false;
202
+ const weightsRaw = str(p.flags, "weights");
203
+ if (weightsRaw !== undefined) {
204
+ const parts = weightsRaw.split(",").map((x) => Number(x.trim()));
205
+ if (parts.length !== 3 || parts.some((n) => !Number.isInteger(n) || n < 0) || parts[0] + parts[1] + parts[2] !== 100) {
206
+ throw new CliError("usage", "--weights must be three non-negative integers q,t,c summing to 100 (e.g. 65,20,15)");
207
+ }
208
+ nextPolicy.weights = { quality: parts[0], time: parts[1], cost: parts[2] };
209
+ changed = true;
210
+ }
211
+ const qtRaw = str(p.flags, "quality-target");
212
+ if (qtRaw !== undefined) {
213
+ if (qtRaw === "none" || qtRaw === "null")
214
+ nextPolicy.quality_target_percent = null;
215
+ else {
216
+ const qt = Number(qtRaw);
217
+ if (!Number.isFinite(qt) || qt < 0 || qt > 100)
218
+ throw new CliError("usage", "--quality-target must be 0..100 or none");
219
+ nextPolicy.quality_target_percent = qt;
220
+ }
221
+ changed = true;
222
+ }
223
+ const hlRaw = str(p.flags, "half-life");
224
+ if (hlRaw !== undefined) {
225
+ const hl = Number(hlRaw);
226
+ if (!Number.isInteger(hl) || hl < 1 || hl > 3650)
227
+ throw new CliError("usage", "--half-life must be an integer 1..3650");
228
+ nextPolicy.recency_half_life_days = hl;
229
+ changed = true;
230
+ }
231
+ const msRaw = str(p.flags, "min-samples");
232
+ if (msRaw !== undefined) {
233
+ const ms = Number(msRaw);
234
+ if (!Number.isInteger(ms) || ms < 5 || ms > 100000)
235
+ throw new CliError("usage", "--min-samples must be an integer 5..100000");
236
+ nextPolicy.minimum_sample_count = ms;
237
+ changed = true;
238
+ }
239
+ const beRaw = str(p.flags, "build-explore");
240
+ if (beRaw !== undefined) {
241
+ const be = Number(beRaw);
242
+ if (!Number.isInteger(be) || be < 0 || be > 20)
243
+ throw new CliError("usage", "--build-explore must be an integer 0..20");
244
+ nextPolicy.build_exploration_budget_percent = be;
245
+ changed = true;
246
+ }
247
+ const reRaw = str(p.flags, "review-explore");
248
+ if (reRaw !== undefined) {
249
+ const re = Number(reRaw);
250
+ if (!Number.isInteger(re) || re < 0 || re > 20)
251
+ throw new CliError("usage", "--review-explore must be an integer 0..20");
252
+ nextPolicy.review_exploration_budget_percent = re;
253
+ changed = true;
254
+ }
255
+ const pbRaw = str(p.flags, "pause-build");
256
+ if (pbRaw !== undefined) {
257
+ nextPolicy.build_exploration_paused = parseBoolChoice(pbRaw, "pause-build");
258
+ changed = true;
259
+ }
260
+ const prRaw = str(p.flags, "pause-review");
261
+ if (prRaw !== undefined) {
262
+ nextPolicy.review_exploration_paused = parseBoolChoice(prRaw, "pause-review");
263
+ changed = true;
264
+ }
265
+ if (!changed) {
266
+ throw new CliError("usage", "pass at least one routing policy flag (--weights, --quality-target, --half-life, --min-samples, --build-explore, --review-explore, --pause-build, --pause-review)");
267
+ }
268
+ const reason = str(p.flags, "reason");
269
+ const r = await c.call("PUT", `/projects/${project}/process`, {
270
+ definition: { routing_policy: nextPolicy },
271
+ ...(reason ? { reason } : {}),
272
+ });
273
+ const updated = r.process?.definition?.routing_policy ?? nextPolicy;
274
+ out.print(`${project} process v${r.process?.version ?? "?"}: weights ${updated.weights.quality}/${updated.weights.time}/${updated.weights.cost}, quality target ${updated.quality_target_percent ?? "none"}, half-life ${updated.recency_half_life_days ?? 30}d, min samples ${updated.minimum_sample_count}, build explore ${updated.build_exploration_budget_percent}%${updated.build_exploration_paused ? " (PAUSED)" : ""}, review explore ${updated.review_exploration_budget_percent}%${updated.review_exploration_paused ? " (PAUSED)" : ""}.`, r);
275
+ return;
276
+ }
277
+ case "explain": {
278
+ const project = rest[0];
279
+ const n = parseUnitNum(rest[1], "routing explain <project> <unit>");
280
+ if (!project)
281
+ throw new CliError("usage", "routing explain <project> <unit>");
282
+ const r = await c.call("GET", `/projects/${project}/work-units/${n}`);
283
+ const u = r.unit;
284
+ const lines = [
285
+ `WU #${u.number} [${u.status}] tags ${(u.tags ?? []).map((t) => `#${t}`).join(" ") || "(none)"} · owner ${u.owner_name || "(none)"}`,
286
+ ...formatUnitRoutingExplanation(u),
287
+ ];
288
+ const routeEvents = Array.isArray(r.events)
289
+ ? r.events.filter((e) => e.data?.route_decision || e.data?.required_class || e.type === "assigned" || e.type === "queued" || e.type === "submitted")
290
+ : [];
291
+ if (routeEvents.length) {
292
+ lines.push(" events:");
293
+ for (const e of routeEvents.slice(-5)) {
294
+ lines.push(` ${e.at?.slice(0, 16).replace("T", " ") ?? ""} ${e.type} by ${e.actor_name ?? "?"}${e.note ? `: ${e.note}` : ""}`);
295
+ }
296
+ }
297
+ out.print(lines.join("\n"), r);
298
+ return;
299
+ }
300
+ case "required-class": {
301
+ const project = rest[0];
302
+ const n = parseUnitNum(rest[1], 'routing required-class <project> <unit> (--class p/h/m/e | --clear) --reason "why"');
303
+ if (!project)
304
+ throw new CliError("usage", 'routing required-class <project> <unit> (--class p/h/m/e | --clear) --reason "why"');
305
+ await runRequiredClassUpdate(c, project, n, p, out);
306
+ return;
307
+ }
308
+ case "tag-required-class": {
309
+ const project = rest[0];
310
+ const tagRaw = rest[1];
311
+ const clear = bool(p.flags, "clear");
312
+ const clsRaw = str(p.flags, "class");
313
+ const reason = str(p.flags, "reason")?.trim();
314
+ if (!project || !tagRaw || (clear && clsRaw) || (!clear && !clsRaw) || !reason) {
315
+ throw new CliError("usage", 'routing tag-required-class <project> <tag> (--class p/h/m/e | --clear) --reason "why"');
316
+ }
317
+ const tag = normalizeTag(tagRaw);
318
+ const spec = clear ? null : parseClassSpec(clsRaw);
319
+ const cur = await c.call("GET", `/projects/${project}/process`);
320
+ const vocab = Array.isArray(cur.vocabulary) ? cur.vocabulary : [];
321
+ if (!vocab.some((v) => v.name === tag)) {
322
+ throw new CliError("not_found", `tag #${tag} is not in ${project}'s vocabulary`);
323
+ }
324
+ const nextVocab = vocab.map((v) => {
325
+ if (v.name !== tag)
326
+ return v;
327
+ if (clear)
328
+ return { ...v, required_class: null, required_class_clear_reason: reason };
329
+ return { ...v, required_class: { ...spec, reason } };
330
+ });
331
+ const r = await c.call("PUT", `/projects/${project}/process`, { vocabulary: nextVocab, reason });
332
+ out.print(clear
333
+ ? `${project} #${tag}: required_class cleared (process v${r.process?.version ?? "?"}, reason: ${reason}).`
334
+ : `${project} #${tag}: required_class set to ${formatClassSpec(spec)} (process v${r.process?.version ?? "?"}, reason: ${reason}).`, r);
335
+ return;
336
+ }
337
+ case "tier-migration": {
338
+ const project = rest[0];
339
+ if (!project)
340
+ throw new CliError("usage", "routing tier-migration <project>");
341
+ const r = await c.call("GET", `/projects/${project}/routing/tier-migration`);
342
+ const rows = Array.isArray(r.units) ? r.units : [];
343
+ out.print(rows.length
344
+ ? [
345
+ `${project} tier-migration backlog (${rows.length} legacy min_tier unit(s) needing explicit operator review; set or clear via b9s-admin routing required-class):`,
346
+ ...rows.map((u) => ` WU #${u.number} [${u.status}] legacy min_tier=${u.legacy_min_tier ?? "?"} · ${u.title ?? ""}`),
347
+ ].join("\n")
348
+ : `${project}: no legacy min_tier units awaiting required_class review.`, r);
349
+ return;
350
+ }
351
+ case "pool-suggestions": {
352
+ await poolSuggestionsAdmin("suggestions", rest, p, out);
353
+ return;
354
+ }
355
+ default:
356
+ throw new CliError("usage", "routing show <project> [--mode build|review] [--tag t] | policy <project> ... | explain <project> <unit> | required-class <project> <unit> ... | tag-required-class <project> <tag> ... | tier-migration <project> | pool-suggestions <project>");
357
+ }
358
+ }
359
+ /** Handles `b9s-admin pool suggestions` and `b9s-admin pool suggestion accept|reject`. */
360
+ export async function poolSuggestionsAdmin(action, rest, p, out) {
361
+ const c = adminClient(p);
362
+ if (action === "suggestions") {
363
+ const project = rest[0];
364
+ if (!project)
365
+ throw new CliError("usage", "pool suggestions <project> [--status pending|accepted|rejected|superseded|all]");
366
+ const statusFilter = str(p.flags, "status") ?? "pending";
367
+ const r = await c.call("GET", `/projects/${project}/pools/suggestions`);
368
+ const all = Array.isArray(r.suggestions) ? r.suggestions : [];
369
+ const shown = statusFilter === "all" ? all : all.filter((s) => s.status === statusFilter);
370
+ out.print(shown.length
371
+ ? [
372
+ ...shown.map(formatPoolSuggestion),
373
+ shown.some((s) => s.status === "pending")
374
+ ? `\nAct with: b9s-admin pool suggestion accept ${project} <id> [--note "..."] | reject ${project} <id> [--reason "..."]`
375
+ : "",
376
+ ].filter(Boolean).join("\n\n")
377
+ : `No ${statusFilter} pool-weight suggestions for ${project}.`, r);
378
+ return;
379
+ }
380
+ const sub = rest[0];
381
+ const project = rest[1];
382
+ const id = rest[2];
383
+ if (action === "suggestion" && (sub === "accept" || sub === "reject") && project && id) {
384
+ if (sub === "accept") {
385
+ const note = str(p.flags, "note");
386
+ const r = await c.call("POST", `/projects/${project}/pools/suggestions/${id}/accept`, note !== undefined ? { note } : {});
387
+ out.print(`Accepted pool suggestion ${id}: ${r.suggestion?.pool_name ?? "pool"} variant ${r.suggestion?.variant_tag ?? ""} weight -> ${r.suggestion?.suggested_weight ?? "?"}.\n${formatPoolSuggestion(r.suggestion)}`, r);
388
+ return;
389
+ }
390
+ const reason = str(p.flags, "reason") ?? str(p.flags, "note");
391
+ const r = await c.call("POST", `/projects/${project}/pools/suggestions/${id}/reject`, reason !== undefined ? { note: reason } : {});
392
+ out.print(`Rejected pool suggestion ${id}.\n${formatPoolSuggestion(r.suggestion)}`, r);
393
+ return;
394
+ }
395
+ throw new CliError("usage", 'pool suggestions <project> [--status ...] | pool suggestion accept <project> <id> [--note "..."] | pool suggestion reject <project> <id> [--reason "..."]');
396
+ }
@@ -135,6 +135,8 @@ export async function watch(p, out) {
135
135
  if (!exec && !once)
136
136
  throw new CliError("usage", 'watch --exec "<command>" [--interval 30] | watch --once (print and exit) | watch --exec ... --service (launchd on macOS, systemd on Linux)');
137
137
  const log = (m) => process.stderr.write(`${new Date().toISOString()} b9s watch[${name}]: ${m}\n`);
138
+ const debugLog = (m) => { if (process.env.BSCHAT_WATCH_DEBUG === "1")
139
+ log(`debug poll: ${m}`); };
138
140
  let stopping = false;
139
141
  let stoppingCode = 0;
140
142
  let signalStop = () => { };
@@ -294,7 +296,7 @@ export async function watch(p, out) {
294
296
  }
295
297
  let u;
296
298
  try {
297
- u = await gatherUpdates(name, { force: true, model: str(p.flags, "model"), delivery: "watch", dryRun: true });
299
+ u = await gatherUpdates(name, { force: true, model: str(p.flags, "model"), delivery: "watch", dryRun: true, watchCursor: true });
298
300
  }
299
301
  catch (e) {
300
302
  if (e.code === "agent_benched") {
@@ -311,6 +313,7 @@ export async function watch(p, out) {
311
313
  }
312
314
  if (stopping)
313
315
  return stoppingCode;
316
+ debugLog(`seen messages=${u?.counts.messages ?? 0} questions=${u?.counts.questions ?? 0} items=${u?.counts.items ?? 0} followed=${u?.counts.followed ?? 0} digest=${u?.counts.digest ?? 0} notices=${u?.counts.notices ?? 0}; tier=${u?.tier ?? "none"}; decision=${u ? "deliver" : "no updates"}`);
314
317
  if (u) {
315
318
  const recovery = resumeBriefDelivered ? null : await recoveryBriefText(name, log);
316
319
  const update = resumeBriefDelivered ? u : formatUpdates(omitMeasuresAlreadyIn(recovery, u), [recovery ?? recoveryBriefUnavailableText]);
@@ -358,6 +361,8 @@ async function waitIntervalOrStop(ms, stopped) {
358
361
  clearTimeout(timer);
359
362
  }
360
363
  export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn, allowTurn, sessionId, turnCoalesceSeconds = 0, dependencies = {}) {
364
+ const debug = (message) => { if (process.env.BSCHAT_WATCH_DEBUG === "1")
365
+ log(`debug poll: ${message}`); };
361
366
  const state = readState(name);
362
367
  const pending = state.watch_pending;
363
368
  if (pending) {
@@ -377,6 +382,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
377
382
  }
378
383
  const st = readState(name);
379
384
  if (st.watch_pending) {
385
+ debug(`no inbox fetch; wake-up ${st.watch_pending.seq ?? "(legacy)"} remains unacknowledged`);
380
386
  const waited = Date.now() - st.watch_pending.at;
381
387
  if (waited > unackedAfter * 1000 && Date.now() - (st.watch_dormant_logged_at ?? 0) > 3_600_000) {
382
388
  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`);
@@ -386,17 +392,27 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
386
392
  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`);
387
393
  return { sent: false, recoveryBriefDelivered: false };
388
394
  }
389
- const u = await (dependencies.gatherUpdates ?? gatherUpdates)(name, { force: true, model, delivery: "watch", dryRun: true });
395
+ const u = await (dependencies.gatherUpdates ?? gatherUpdates)(name, { force: true, model, delivery: "watch", dryRun: true, watchCursor: true });
396
+ const commitWatchCursor = () => {
397
+ if (!u?.watchCursorAfter)
398
+ return;
399
+ const current = readState(name);
400
+ if (!current.watch_inbox_after || current.watch_inbox_after < u.watchCursorAfter)
401
+ writeState(name, { ...current, watch_inbox_after: u.watchCursorAfter });
402
+ };
390
403
  // A process change is news too. Watched harnesses never see the Claude Code hook re-deliver the
391
404
  // standing rules, so the watcher compares the version the agent last read with the current one.
392
405
  const lag = await (dependencies.processLag ?? processLag)(name, st, !!u, log);
393
406
  const processNews = !!lag && st.watch_process_woken !== lag.version;
394
407
  const operatorNew = !!u && u.latestOperatorAt !== null && u.latestOperatorAt !== (st.watch_operator_at ?? null);
408
+ debug(`seen messages=${u?.counts.messages ?? 0} questions=${u?.counts.questions ?? 0} items=${u?.counts.items ?? 0} followed=${u?.counts.followed ?? 0} digest=${u?.counts.digest ?? 0} notices=${u?.counts.notices ?? 0}; tier=${u?.tier ?? "none"}; processNews=${processNews}; operatorNew=${operatorNew}`);
395
409
  // Turn mode is a direct-work runner: role, followed and process-only changes remain available
396
410
  // to the agent's normal inbox/hook, but must not start another headless turn on their own.
397
411
  if (turnSink && u?.tier !== "direct") {
412
+ commitWatchCursor();
398
413
  if (st.watch_turn_coalesce_since !== undefined)
399
414
  writeState(name, { ...readState(name), watch_turn_coalesce_since: undefined });
415
+ debug(`no wake: ${u ? `${u.tier}-level activity is not direct work` : "no direct work pending"}`);
400
416
  if (once)
401
417
  log(u ? `only ${u.tier}-level unread; not starting a turn` : "no direct work pending; not starting a turn");
402
418
  return { sent: false, recoveryBriefDelivered: false };
@@ -409,6 +425,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
409
425
  if (shouldDeferTurn({ pending: true, firstPendingAt, now: Date.now(), seconds: turnCoalesceSeconds, operator: operatorNew, urgent: u.urgent })) {
410
426
  writeState(name, { ...readState(name), watch_turn_coalesce_since: firstPendingAt });
411
427
  const readyAt = new Date(firstPendingAt + turnCoalesceSeconds * 1000).toISOString();
428
+ debug(`no wake: direct work is coalescing until ${readyAt}`);
412
429
  log(`direct wake-up is coalescing until ${readyAt}; later direct items will join it`);
413
430
  return { sent: false, recoveryBriefDelivered: false };
414
431
  }
@@ -419,6 +436,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
419
436
  if (st.watch_followed_since)
420
437
  writeState(name, { ...st, watch_followed_since: undefined });
421
438
  if (!processNews) {
439
+ debug("no wake: no updates and no new process version");
422
440
  if (once)
423
441
  log("nothing new");
424
442
  return { sent: false, recoveryBriefDelivered: false };
@@ -427,6 +445,8 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
427
445
  else if (u.tier === "digest" && !processNews) {
428
446
  // Tiering: things addressed to this agent wake it now; followed-channel chatter waits for the
429
447
  // follow delay so bursts collapse; digest-only channels never wake it on their own.
448
+ debug("no wake: digest-only activity");
449
+ commitWatchCursor();
430
450
  if (once)
431
451
  log("only digest-level unread; not waking");
432
452
  return { sent: false, recoveryBriefDelivered: false };
@@ -437,6 +457,8 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
437
457
  writeState(name, { ...st, watch_followed_since: since });
438
458
  const waited = Date.now() - since;
439
459
  if (waited < followDelay * 1000) {
460
+ commitWatchCursor();
461
+ debug(`no wake: followed-only activity waiting ${Math.round(waited / 1000)}/${followDelay}s`);
440
462
  if (once)
441
463
  log(`followed-channel traffic only; waiting (${Math.round(waited / 1000)}/${followDelay}s) before waking`);
442
464
  return { sent: false, recoveryBriefDelivered: false };
@@ -467,10 +489,14 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
467
489
  // `{summary}` commands get the same bounded prompt as `{text}`: this wrapper itself contains
468
490
  // the acknowledgement, operator note, process pointer, read commands, and delivery body.
469
491
  const line = wake;
470
- if (!(await deliver(name, exec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, provider, model, turnStdin, beforeTurn, { sessionId }, allowTurn)))
492
+ debug(`wake: delivering ${u?.tier ?? "process"} activity as wake-up #${seq}`);
493
+ if (!(await deliver(name, exec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, provider, model, turnStdin, beforeTurn, { sessionId }, allowTurn))) {
494
+ debug("no wake: delivery failed or turn guard denied the launch");
471
495
  return { sent: false, recoveryBriefDelivered: false };
496
+ }
472
497
  writeState(name, {
473
498
  ...readState(name),
499
+ ...(u?.watchCursorAfter ? { watch_inbox_after: u.watchCursorAfter } : {}),
474
500
  watch_seq: seq,
475
501
  ...(processNews ? { watch_process_woken: lag.version } : {}),
476
502
  watch_pending: { seq, at: Date.now(), inbox_after: st.inbox_after, channel_read: st.channel_read ?? {} },
@@ -590,6 +616,8 @@ const KEY_CHECK_MS = 5 * 60_000;
590
616
  * broken; one that runs past --turn-timeout is stopped and logged.
591
617
  */
592
618
  export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR, harness) {
619
+ const debug = (message) => { if (env.BSCHAT_WATCH_DEBUG === "1")
620
+ log(`debug poll: ${message}`); };
593
621
  const turn = ctl.turn;
594
622
  if (turn) {
595
623
  if (!turn.confirmed && probe.startedSince(turn.startedMs)) {
@@ -638,12 +666,14 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
638
666
  }
639
667
  ctl.turn = null;
640
668
  await completePendingTurnGuard(name, probe, log, undefined, undefined, env);
669
+ debug(`no inbox poll: turn #${turn.seq} just ended; checking for next work on the next watcher iteration`);
641
670
  return;
642
671
  }
643
672
  if (!turn.killedForTimeout && Date.now() - turn.startedMs > timeoutMin * 60_000) {
644
673
  log(`turn #${turn.seq} has run ${timeoutMin} min; stopping it`);
645
674
  stopTurn(turn);
646
675
  }
676
+ debug(`no inbox poll: turn #${turn.seq} is still running`);
647
677
  return;
648
678
  }
649
679
  // b9s unpause: the operator switched the harness to an account with quota.
@@ -653,10 +683,14 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
653
683
  ctl.pausedUntil = 0;
654
684
  ctl.failedAt = 0;
655
685
  }
656
- if (Date.now() - ctl.failedAt < TURN_RETRY_MS)
686
+ if (Date.now() - ctl.failedAt < TURN_RETRY_MS) {
687
+ debug(`no inbox poll: failed-turn backoff until ${new Date(ctl.failedAt + TURN_RETRY_MS).toISOString()}`);
657
688
  return;
658
- if (ctl.pausedUntil > Date.now())
689
+ }
690
+ if (ctl.pausedUntil > Date.now()) {
691
+ debug(`no inbox poll: usage-limit pause until ${new Date(ctl.pausedUntil).toISOString()}`);
659
692
  return;
693
+ }
660
694
  // A turn this watcher did not start: an app or a terminal on the same session, or a turn left
661
695
  // running by a watcher that restarted (turns run in their own process group and outlive it).
662
696
  // Never start a second one.
@@ -664,21 +698,27 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
664
698
  const savedGuard = readState(name, env).turn_guard;
665
699
  if (savedGuard?.fault) {
666
700
  log(`TURN MODE FAULT: ${turnFaultSummary(savedGuard.fault)}; operator/assigner must resume this session before turns can continue`);
701
+ debug("no inbox poll: turn guard is faulted");
667
702
  return;
668
703
  }
669
704
  if ("missing" in ph) {
670
705
  if (savedGuard?.turns.some((attempt) => attempt.productive === null)) {
671
706
  await completePendingTurnGuard(name, probe, log, undefined, undefined, env);
672
- if (readState(name, env).turn_guard?.fault)
707
+ if (readState(name, env).turn_guard?.fault) {
708
+ debug("no inbox poll: completing the prior turn faulted the turn guard");
673
709
  return;
710
+ }
674
711
  }
675
712
  log(ph.missing);
713
+ debug("no inbox poll: configured harness session is missing");
676
714
  return;
677
715
  }
678
716
  if (!ph.running && savedGuard?.turns.some((attempt) => attempt.productive === null)) {
679
717
  await completePendingTurnGuard(name, probe, log, undefined, undefined, env);
680
- if (readState(name, env).turn_guard?.fault)
718
+ if (readState(name, env).turn_guard?.fault) {
719
+ debug("no inbox poll: completing the prior turn faulted the turn guard");
681
720
  return;
721
+ }
682
722
  }
683
723
  if (probe.label === "DeepSeek Harness" && !ph.running && ph.lastError) {
684
724
  const failedAt = Date.parse(ph.lastErrorAt ?? "");
@@ -688,8 +728,10 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
688
728
  ctl.loggedFailureAt = ph.lastErrorAt;
689
729
  log(`the last DeepSeek Harness turn failed (${ph.lastError}); next turn is eligible at ${new Date(retryAt).toISOString()}`);
690
730
  }
691
- if (Date.now() < retryAt)
731
+ if (Date.now() < retryAt) {
732
+ debug(`no inbox poll: DeepSeek retry backoff until ${new Date(retryAt).toISOString()}`);
692
733
  return;
734
+ }
693
735
  }
694
736
  }
695
737
  // A watcher that restarted after a usage-limit failure reads the pause from the session itself.
@@ -698,6 +740,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
698
740
  ctl.pausedUntil = until;
699
741
  ctl.pausedAt = Date.now();
700
742
  log(`the last turn in ${probe.what} hit the ${probe.label} usage limit; no turns until ${new Date(until).toISOString()}`);
743
+ debug(`no inbox poll: usage-limit pause until ${new Date(until).toISOString()}`);
701
744
  return;
702
745
  }
703
746
  // A turn that started before this machine last booted died with it: no process survives a
@@ -714,6 +757,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
714
757
  if (ctl.loggedRunning !== ph.startedAt)
715
758
  log(`a turn started at ${ph.startedAt} is still running in ${probe.what} (an app or terminal on it, or a turn from before a restart); waiting for it`);
716
759
  ctl.loggedRunning = ph.startedAt;
760
+ debug(`no inbox poll: ${probe.what} is still running`);
717
761
  return;
718
762
  }
719
763
  if (probe.label !== "Codex") {
@@ -721,6 +765,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
721
765
  if (ctl.loggedRunning !== `stuck:${ph.startedAt}`)
722
766
  log(`a process still holds ${probe.what} and has written nothing for ${Math.round(quietMs / 60_000)} min (over the ${timeoutMin}-min limit); starting no turn while it runs. End it to free the session.`);
723
767
  ctl.loggedRunning = `stuck:${ph.startedAt}`;
768
+ debug(`no inbox poll: a process still holds ${probe.what}`);
724
769
  return;
725
770
  }
726
771
  // Codex: the rollout shows a turn that never closed; with nothing written for that long it is dead.
@@ -734,10 +779,12 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
734
779
  if (ctl.loggedRunning !== `maint:${maint.start}`)
735
780
  log(`maintenance on this machine ${maint.start.slice(0, 16)} to ${maint.end.slice(11, 16)} UTC: starting no new turns until it ends`);
736
781
  ctl.loggedRunning = `maint:${maint.start}`;
782
+ debug(`no inbox poll: machine maintenance runs until ${maint.end}`);
737
783
  return;
738
784
  }
739
785
  const st = readState(name, env);
740
786
  if (st.watch_pending) {
787
+ debug(`no inbox poll: wake-up ${st.watch_pending.seq ?? "(legacy)"} is still pending`);
741
788
  // Queued by a queue-mode watcher and never delivered, or failed: no turn is running, so the agent is not going to answer it.
742
789
  log(`wake-up ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}was never answered and no turn is running; a turn replaces it`);
743
790
  writeState(name, { ...st, watch_pending: undefined, watch_dormant_logged_at: undefined }, env);