neurastream 0.3.18 → 0.3.21

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.
Files changed (66) hide show
  1. package/README.md +88 -490
  2. package/package.json +1 -1
  3. package/src/adapters/index.ts +3 -2
  4. package/src/adapters/omp/adapter.ts +2 -1
  5. package/src/adapters/omp/auto-close.ts +64 -0
  6. package/src/adapters/omp/chat-commands.ts +161 -0
  7. package/src/adapters/omp/inbox.ts +221 -0
  8. package/src/adapters/omp/index.ts +138 -1050
  9. package/src/adapters/omp/launch.ts +35 -9
  10. package/src/adapters/omp/rate-limit-controller.ts +196 -0
  11. package/src/adapters/omp/rollover-controller.ts +334 -0
  12. package/src/adapters/omp/types.ts +143 -0
  13. package/src/cli/claim.ts +1 -3
  14. package/src/cli/commands.ts +33 -2
  15. package/src/cli/dispatch.ts +55 -30
  16. package/src/cli/guard.ts +0 -3
  17. package/src/cli/incident.ts +2 -2
  18. package/src/cli/metrics.ts +1 -1
  19. package/src/cli/recall.ts +6 -8
  20. package/src/cli/results-build.ts +2 -4
  21. package/src/cli/workspace.ts +13 -5
  22. package/src/core/adapter.ts +16 -0
  23. package/src/core/autonomy.ts +24 -21
  24. package/src/core/blockers.ts +326 -30
  25. package/src/core/file-lock.ts +71 -12
  26. package/src/core/guards/plan-edit.ts +338 -0
  27. package/src/core/guards/planner.ts +70 -0
  28. package/src/core/guards/review.ts +391 -0
  29. package/src/core/guards/spawn.ts +699 -0
  30. package/src/core/guards/state.ts +581 -0
  31. package/src/core/guards/stop.ts +235 -0
  32. package/src/core/guards/tool.ts +541 -0
  33. package/src/core/guards.ts +12 -2661
  34. package/src/core/incidents.ts +134 -99
  35. package/src/core/machine-guard.ts +23 -5
  36. package/src/core/main-start.ts +11 -9
  37. package/src/core/mr-sweep.ts +4 -2
  38. package/src/core/notify.ts +15 -15
  39. package/src/core/owner-log.ts +19 -17
  40. package/src/core/owner-topics.ts +38 -48
  41. package/src/core/owner-ui/auth.ts +164 -0
  42. package/src/core/owner-ui/data.ts +437 -0
  43. package/src/core/owner-ui/handlers.ts +250 -0
  44. package/src/core/owner-ui/messages.ts +209 -0
  45. package/src/core/owner-ui/render.ts +714 -0
  46. package/src/core/owner-ui/results.ts +266 -0
  47. package/src/core/owner-ui/server.ts +142 -0
  48. package/src/core/owner-ui.ts +11 -2118
  49. package/src/core/page-notes.ts +25 -0
  50. package/src/core/pages.ts +452 -78
  51. package/src/core/plan-approval.ts +24 -26
  52. package/src/core/queue/lib.ts +170 -137
  53. package/src/core/queue-cancel.ts +29 -15
  54. package/src/core/queue-check.ts +5 -7
  55. package/src/core/queue-close.ts +54 -29
  56. package/src/core/queue-finished.ts +9 -10
  57. package/src/core/queue-migrate.ts +1 -3
  58. package/src/core/queue-trim.ts +2 -4
  59. package/src/core/results.ts +0 -2
  60. package/src/core/rollover.ts +2 -3
  61. package/src/core/secret-redact.ts +65 -14
  62. package/src/core/tailscale.ts +79 -3
  63. package/src/core/team-client.ts +18 -6
  64. package/src/core/uninstall.ts +2 -0
  65. package/src/core/watch.ts +3 -2
  66. package/src/core/queue/env.ts +0 -14
@@ -0,0 +1,699 @@
1
+ // Spawn gates: plan gate, priority order, provider preference/claims, incident gate, team claims/caps, and checkSpawn.
2
+
3
+ import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
4
+ import path from "node:path";
5
+ import type { Decision, RunSource, SpawnEvent } from "../adapter.ts";
6
+ import { currentPlanner, currentTier } from "../autonomy.ts";
7
+ import { lint } from "../brief-lint.ts";
8
+ import { heldByOther, type ClaimStore } from "../claims.ts";
9
+ import { nowSec } from "../clock.ts";
10
+ import type { Config } from "../config.ts";
11
+ import { ownerSaid, readOwnerMessages, type OwnerMessage } from "../incidents.ts";
12
+ import { defaultRunner, type CommandRunner } from "../mr-sweep.ts";
13
+ import { approvalProblem } from "../plan-approval.ts";
14
+ import { outUntil, pinModel, providerOfModel, readOut } from "../provider-state.ts";
15
+ import * as q from "../queue/lib.ts";
16
+ import type { Plan } from "../queue/lib.ts";
17
+ import { claimStoreFor, pathId, routeTeam, teamDir, type TeamEntry } from "../team-client.ts";
18
+ import { plannerPlanProblem, plannerRolePlan, recordPlannerSpawn } from "./planner.ts";
19
+ import { isReviewSpawn, pendingWorkProblem, readMrCache, recordReviewSpawn, reviewPassProblem, reviewRole } from "./review.ts";
20
+ import {
21
+ ALLOW,
22
+ briefBudget,
23
+ bypassRegExp,
24
+ CANCEL_TODO,
25
+ deny,
26
+ heldProblem,
27
+ log,
28
+ mainId,
29
+ openIncidentList,
30
+ readSpawns,
31
+ readStaffing,
32
+ recordBudgets,
33
+ recordSpawns,
34
+ staffedPlans,
35
+ tuned,
36
+ unticked,
37
+ type Spawner,
38
+ } from "./state.ts";
39
+
40
+ const RESEARCH_ASK = /\b(research|investigate|find where|map the code|read the code for)\b/i;
41
+ const PLAN_WRITE = /\b(write|writing|draft|drafting|author)\b[^\n]*\bplan\b/i;
42
+
43
+ /** The open plans the text names — a `Priority skip: <path> — <why>` line names a plan it does NOT run on (20261025_0215 P3), so only the remaining text decides. planGate's targeting, shared with the spawn verdict's brief-lint and cap notes (plan 20261031_1207 P4). */
44
+ function briefPlans(text: string, cfg: Config): Plan[] {
45
+ const body = text.replace(/^\s*(?:[-*]\s+)?priority skip:.*$/gim, "");
46
+ return q.activePlans(cfg.paths, cfg.review.agents).filter(p => body.includes(p.file));
47
+ }
48
+
49
+ // Plans an implementer brief may run on; returns [reason, null] or [null, plan files].
50
+ export function planGate(text: string, label: string, cfg: Config): [string | null, string[]] {
51
+ const plans = q.activePlans(cfg.paths, cfg.review.agents);
52
+ const unclosed = plans.filter(p => (p.status === "complete" || p.status === "cancelled") && !q.awaitingMerge(p, cfg.paths));
53
+ if (unclosed.length)
54
+ return [
55
+ `${label}: ${unclosed.map(p => `${p.file} (${p.status})`).join(", ")} is still indexed. Verify it and run \`queue-close <plan>\` before any new spawn.`,
56
+ [],
57
+ ];
58
+ const named = briefPlans(text, cfg);
59
+ if (!named.length)
60
+ return [
61
+ `${label}: an implementer needs an open plan. Name the plan's absolute path in the brief; the plan must be listed in ${cfg.paths.queue_index}.`,
62
+ [],
63
+ ];
64
+ if (RESEARCH_ASK.test(text) && PLAN_WRITE.test(text))
65
+ return [
66
+ `${label}: a brief must not ask for research for a plan to be written. Please never ever ever write a plan when another agent is doing the research or reading for you. Main reads the code for its plans itself.`,
67
+ [],
68
+ ];
69
+ // P5 (plan 20261031_0911): a landed open plan whose auto-close failed locks the queue — every
70
+ // brief must name it, so the next spawn works on closing it instead of around it. A named
71
+ // locked plan skips the unticked-phase checks below: its work has landed, the job is the close.
72
+ const locked = plans.filter(p => p.status === "open" && q.autoCloseCandidate(p) && q.lastCloseFailed(p.file, cfg.paths));
73
+ for (const s of locked) {
74
+ if (named.some(n => n.file === s.file)) continue;
75
+ return [
76
+ `${label}: ${s.file} landed but its auto-close failed (${(q.lastCloseResult(s.file, cfg.paths) ?? "").replace(/^queue-close: /, "")}). The queue is locked on it: name this plan in the brief and fix the close before any other spawn.`,
77
+ [],
78
+ ];
79
+ }
80
+ const spawns = readSpawns(cfg.paths);
81
+ for (const p of named) {
82
+ if (p.errors.length) return [`${label}: plan ${p.file} is not ready (${p.errors.join("; ")}).`, []];
83
+ if (p.waiting) return [`${label}: plan ${p.file} is parked "WAITING on owner".`, []];
84
+ if (p.status !== "open") return [`${label}: plan ${p.file} says "Status: ${p.status}".`, []];
85
+ const cancelled = q.cancelledMatches(p, cfg.paths);
86
+ if (cancelled.length) return [`${label}: plan ${p.file} ${q.cancelledProblem(p, cancelled[0]!, cfg.paths)}`, []];
87
+ const before = spawns[p.file];
88
+ if (before && before === q.sha(q.progressBody(p.text)))
89
+ return [
90
+ `${label}: plan ${p.file} has no new "## Progress" entry since the last agent ran on it. Write that run's progress (from its report) into the plan first.`,
91
+ [],
92
+ ];
93
+ const approval = approvalProblem(p.text, p.file, cfg.pages.dir, cfg.approval.since, cfg.paths);
94
+ if (approval) return [approval, []];
95
+ const open = unticked(p);
96
+ // A locked plan's work has landed: closing it is the job, there is no phase left to tick.
97
+ if (locked.some(l => l.file === p.file)) continue;
98
+ if (!open.length) return [`${label}: plan ${p.file} has no unticked phase left.`, []];
99
+ if (!open.some(id => new RegExp(`\\b${id}\\b`).test(text)))
100
+ return [`${label}: the brief must name an unticked phase of ${p.file} (${open.join(", ")}).`, []];
101
+ }
102
+ return [null, named.map(p => p.file)];
103
+ }
104
+
105
+ // --- priority: index order is priority (plan 20261025_0215_index_priority) ---
106
+
107
+ export interface PrioritySkip {
108
+ plan: string;
109
+ why: string;
110
+ }
111
+
112
+ export interface PriorityOutcome {
113
+ /** Refusal text, without the caller's label prefix. */
114
+ problem?: string;
115
+ /** Skip lines the brief justified; the caller logs each, then allows. */
116
+ skips?: PrioritySkip[];
117
+ /** No job info was available: the gate never refuses. */
118
+ unknown?: boolean;
119
+ }
120
+
121
+ const SKIP_LINE = /^\s*(?:[-*]\s+)?priority skip:\s*(.+?)\s+[—–-]\s*(.+?)\s*$/gim;
122
+
123
+ /** One plan is idle when a subagent could start on it right now: open, no owner hold, not awaiting merge, no template errors, an unticked phase left, and not waiting on another open plan of the active index. */
124
+ function priorityIdle(p: Plan, plans: Plan[], paths?: Pick<q.QueuePaths, "queue_state">): boolean {
125
+ if (p.waitsOn.some(f => plans.some(w => w.file === f && w.status === "open"))) return false;
126
+ return p.status === "open" && !p.waiting && !(paths ? q.awaitingMerge(p, paths) : false) && !p.errors.length && unticked(p).length > 0;
127
+ }
128
+
129
+ /**
130
+ * Pure priority gate: for the brief's named plans, every higher plan in index order that is idle
131
+ * and unstaffed needs proof before a lower plan takes a free slot; otherwise the spawn is refused.
132
+ * Proof is either the higher plan's own `Waits on: <plan>` line for a plan still open in the index
133
+ * (then it is not idle at all) or a `Priority skip: <path> — owner: "<words>"` line whose quoted
134
+ * words (≥ 4, normalised) appear in one of `messages` (the owner's recorded words of the last
135
+ * 24 h; `now` is the current unix seconds). A higher plan whose branch carries an open MR in the
136
+ * cached forge list (fresh within `review.mr_cache_minutes`; the one list the main-start sweep
137
+ * and pendingWorkProblem maintain — never queried here) is landing, not idle: no proof needed.
138
+ * A stale cache proves nothing, so the refusal stands (I-20261029-435). In tier full (`cfg`) a
139
+ * `Priority skip: <path> — Main: "<reason>"` line with ≥ 4 words is proof too; without `cfg` the
140
+ * refusal behaviour is the pre-tier one. Any other skip line is refused.
141
+ * `staffed === undefined` means the caller had no running-job info (CLI spawn without it): never
142
+ * refuse. Plans already named by this call never block it.
143
+ */
144
+ export function priorityProblem(plans: Plan[], named: string[], staffed: string[] | undefined, brief: string, messages: OwnerMessage[] = [], now: number = nowSec(), cfg?: Config): PriorityOutcome | null {
145
+ if (staffed === undefined) return { unknown: true };
146
+ const namedRanks = named.map(f => plans.findIndex(p => p.file === f)).filter(n => n >= 0);
147
+ if (!namedRanks.length) return null;
148
+ const higher = plans.slice(0, Math.min(...namedRanks));
149
+ const tier = cfg ? currentTier(cfg) : "opinionated";
150
+ const skipLines: Record<string, string> = {};
151
+ for (const m of brief.matchAll(SKIP_LINE)) {
152
+ const plan = (m[1] ?? "").trim();
153
+ const why = (m[2] ?? "").trim();
154
+ if (plan && why) skipLines[plan] = why;
155
+ }
156
+ const skips: PrioritySkip[] = [];
157
+ const cache = cfg ? readMrCache(cfg.paths) : { at: 0, repos: {} };
158
+ const fresh = cfg ? now - cache.at < cfg.review.mr_cache_minutes * 60 : false;
159
+ for (let i = 0; i < higher.length; i++) {
160
+ const p = higher[i]!;
161
+ if (!priorityIdle(p, plans, cfg?.paths) || staffed.includes(p.file)) continue;
162
+ if (fresh && p.branch && (cache.repos[p.repo] ?? []).some(mr => mr.branch === p.branch)) continue;
163
+ const why = skipLines[p.file];
164
+ // Tier full (20261025_1940 P2): Main's own >= 4-word reason is proof enough; every other
165
+ // tier refuses it exactly as before — only the owner's recorded words let a skip through.
166
+ const mainWhy = tier === "full" ? why?.match(/^Main:\s*"(.+)"\s*$/) : undefined;
167
+ if (why && mainWhy && mainWhy[1]!.trim().split(/\s+/).length >= 4) {
168
+ skips.push({ plan: p.file, why });
169
+ continue;
170
+ }
171
+ const quote = why?.match(/^owner:\s*"(.+)"\s*$/);
172
+ if (why && quote && ownerSaid(quote[1]!, messages, now)) {
173
+ skips.push({ plan: p.file, why });
174
+ continue;
175
+ }
176
+ return { problem: `higher plan ${p.file} (rank ${i + 1}) is idle; a skip needs the owner's words (Priority skip: ${p.file} — owner: "<quote>") or a "Waits on: ${p.file}" line in that plan` };
177
+ }
178
+ return skips.length ? { skips } : null;
179
+ }
180
+
181
+ /** Load staffing and the owner's recorded words, run the pure priority gate and log its outcome; the refusal comes back with the caller's label, or null. P8 (I-20261031-353): the plans a Main-authored brief reviews drop out first — a plan waiting for its reviewer is not a priority slot, so a call naming only reviewed plans passes with no skip line; implementer plans keep the gate. */
182
+ function priorityGate(named: string[], runningJobs: string[] | undefined, brief: string, cfg: Config, label: string, agent: string, spawner: Spawner): string | null {
183
+ const implementer = named.filter(f => !isReviewSpawn(f, brief, agent, cfg, spawner));
184
+ const outcome = priorityProblem(q.activePlans(cfg.paths), implementer, runningJobs === undefined ? undefined : staffedPlans(readStaffing(cfg.paths), runningJobs), brief, readOwnerMessages(cfg.paths), nowSec(), cfg);
185
+ if (outcome?.unknown) log(cfg.paths.guard_log, "PRIORITY unknown jobs");
186
+ for (const s of outcome?.skips ?? []) log(cfg.paths.guard_log, `PRIORITY skip ${s.plan}: ${s.why}`);
187
+ return outcome?.problem ? `${label}: ${outcome.problem}` : null;
188
+ }
189
+
190
+ /**
191
+ * The owner's pick order (plan 20261025_1700 P3): refuse a later `ledger.prefer` agent while an
192
+ * earlier one is free and under its provider cap, unless the brief carries "Pick note: <why>".
193
+ * Free comes from the pin's provider and provider-out.jsonl (absence of a record is free);
194
+ * "under its cap" counts the caller's running jobs whose label embeds the higher agent's name —
195
+ * a caller without job info counts 0, erring toward the owner's order, which Pick note unlocks.
196
+ */
197
+ export function preferProblem(agent: string, brief: string, runningJobs: readonly string[] | undefined, cfg: Config): string | null {
198
+ const prefer = cfg.ledger.prefer;
199
+ if (!prefer.length) return null;
200
+ const mine = prefer.indexOf(agent);
201
+ if (mine <= 0) return null; // the first pick, or an agent the order does not name
202
+ if (/\bPick note:/i.test(brief)) return null;
203
+ for (let j = 0; j < mine; j++) {
204
+ const higher = prefer[j]!;
205
+ const provider = providerOfModel(pinModel(cfg, higher));
206
+ if (provider === null || outUntil(cfg, provider) !== null) continue; // unknown or out
207
+ const running = (runningJobs ?? []).filter(l => l.toLowerCase().includes(higher.toLowerCase())).length;
208
+ if (running >= cfg.ledger.max_running_per_provider) continue; // the higher pick is at its provider cap
209
+ return `${higher} is ahead of ${agent} in ledger.prefer and free (under its provider cap) — spawn ${higher}, or add "Pick note: <why>" to the brief.`;
210
+ }
211
+ return null;
212
+ }
213
+
214
+ /** P4 (plan 20261031_1207): `agent-ledger --cap`'s FULL line at spawn time — the agent's provider already runs its full share of live subagents. Counted from the caller's running job labels, the live data preferProblem counts (a caller without job info counts 0). */
215
+ function ledgerCapProblem(agent: string, runningJobs: readonly string[] | undefined, cfg: Config): string | null {
216
+ const provider = providerOfModel(pinModel(cfg, agent));
217
+ if (provider === null || outUntil(cfg, provider) !== null) return null;
218
+ const sharers = [agent, ...cfg.ledger.prefer.filter(a => providerOfModel(pinModel(cfg, a)) === provider)];
219
+ const running = (runningJobs ?? []).filter(l => sharers.some(n => l.toLowerCase().includes(n.toLowerCase()))).length;
220
+ if (running < cfg.ledger.max_running_per_provider) return null;
221
+ return `provider ${provider} is at its cap (${running} live of ${cfg.ledger.max_running_per_provider} running); stop or wait for one before spawning more.`;
222
+ }
223
+
224
+ /**
225
+ * The one spawn verdict (plan 20261031_1207 P4): every refusal in one numbered list, so Main fixes
226
+ * all of them in one round trip. The named plans' brief-lint errors and the provider-cap note (the
227
+ * advice Main gathered by hand through `brief-lint` and `agent-ledger --cap`) ride along on an
228
+ * already-refused spawn — alone they never refuse: real plans carry lint nits, and a full provider
229
+ * is the prefer order's to weigh, not a gate of its own.
230
+ */
231
+ function spawnVerdict(agent: string, problems: string[], lintFiles: string[], runningJobs: readonly string[] | undefined, cfg: Config): string | null {
232
+ if (!problems.length) return null;
233
+ const advice: string[] = [];
234
+ for (const f of new Set(lintFiles)) {
235
+ try {
236
+ for (const e of lint(f, cfg).errs) advice.push(`${f}: ${e}`);
237
+ } catch {} // an unreadable plan's refusal is planGate's to name
238
+ }
239
+ const cap = ledgerCapProblem(agent, runningJobs, cfg);
240
+ if (cap) advice.push(cap);
241
+ const all = [...problems, ...advice];
242
+ return `${agent}: ${all.length} ${all.length === 1 ? "problem" : "problems"}:\n${all.map((p, i) => `${i + 1}. ${p}`).join("\n")}`;
243
+ }
244
+
245
+ /**
246
+ * Who is rate-limited comes from live data (plan 20261025_1700 P1): refuse a brief that asserts a
247
+ * provider shown free by providerStatus is rate-limited — named directly or through a prefer
248
+ * agent's pin. providerStatus lists only providers with a record, so a never-recorded provider is
249
+ * not protected here; a past-tense mention does not match, because the claim must say "is …".
250
+ */
251
+ export function providerClaimProblem(text: string, cfg: Config): string | null {
252
+ const recorded = new Set(readOut(cfg).map(r => r.provider));
253
+ const free = (provider: string | null): boolean => provider !== null && recorded.has(provider) && outUntil(cfg, provider) === null;
254
+ const names = new Map<string, string>();
255
+ for (const p of cfg.ledger.providers) if (free(p)) names.set(p, p);
256
+ for (const agent of cfg.ledger.prefer) {
257
+ const provider = providerOfModel(pinModel(cfg, agent));
258
+ if (free(provider) && !names.has(agent) && provider !== null) names.set(agent, provider);
259
+ }
260
+ if (!names.size || !/\bis\b/i.test(text)) return null;
261
+
262
+ const m = new RegExp(`\\b(${[...names.keys()].map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})\\b[^.\\n]{0,80}?\\b(?:is|are)\\s+(?:still\\s+|now\\s+)?(?:rate[ -]?limited|rate limiting|throttled|out until|limited)`, "i").exec(text);
263
+ if (!m) return null;
264
+ const hit = [...names.entries()].find(([n]) => n.toLowerCase() === (m[1] ?? "").toLowerCase());
265
+ if (hit === undefined) return null;
266
+ const [name, provider] = hit;
267
+ return `${name === provider ? provider : `${name} (provider ${provider})`} is free per the recorded provider state — do not claim it is rate-limited; read the providers line from agent-ledger --cap.`;
268
+ }
269
+
270
+ /**
271
+ * While an owner-correction incident (source "realtime") is open, a launch must be fix work: its
272
+ * brief (or a plan the brief names) cites `INCIDENT <id>` of an open one. Notes from worker
273
+ * findings/traces never refuse a spawn (plan 20261031_1207 P2). Returns the refusal reason, or
274
+ * null; `label` names the log line.
275
+ */
276
+ export function incidentSpawnProblem(label: string, brief: string, namedPlans: string[], cfg: Config): string | null {
277
+ const open = openIncidentList(cfg).filter(i => i.source === "realtime");
278
+ if (!open.length) return null;
279
+ const texts = [brief];
280
+ for (const f of namedPlans) {
281
+ try {
282
+ texts.push(readFileSync(f, "utf8"));
283
+ } catch {}
284
+ }
285
+ const remaining = open.filter(i => !texts.some(t => t.includes(`INCIDENT ${i.id}`)));
286
+ if (!remaining.length) return null;
287
+ const ids = remaining.map(i => i.id).join(", ");
288
+ log(cfg.paths.guard_log, `BLOCK ${label}: open incidents: ${ids}`);
289
+ return (
290
+ `open incident(s) ${ids} must be acted on before other work. Write a plan that contains "INCIDENT <id>" ` +
291
+ `(listed in ${cfg.paths.queue_index}) and record it: \`neurastream incident plan <id> <plan.md>\`, or dismiss the ` +
292
+ 'incident: `neurastream incident dismiss <id> --why "<text>"`. Fix work goes through: name that plan in the brief.'
293
+ );
294
+ }
295
+
296
+ /** A spawn's identity for the team cap: its named agents, and whether any spawned agent has no name (the cap cannot count it). */
297
+ export interface SpawnIdent {
298
+ agentIds: string[];
299
+ unnamed: boolean;
300
+ runs?: RunSource;
301
+ }
302
+
303
+ /** A plan file and the team it routes to. */
304
+ export interface RoutedTeam {
305
+ team: TeamEntry;
306
+ file: string;
307
+ }
308
+
309
+ function routedTeams(files: string[], cfg: Config): RoutedTeam[] {
310
+ const out: RoutedTeam[] = [];
311
+ for (const file of files) {
312
+ const team = routeTeam(file, cfg, undefined, defaultRunner);
313
+ if (team) out.push({ team, file });
314
+ }
315
+ return out;
316
+ }
317
+
318
+ /** Epoch seconds at local midnight: the start of the cap's day. */
319
+ function dayStartSec(): number {
320
+ const d = new Date(nowSec() * 1000);
321
+ d.setHours(0, 0, 0, 0);
322
+ return d.getTime() / 1000;
323
+ }
324
+
325
+ /** Agent ids recorded against a team's plans since `since`, from its spawns.jsonl rows; a corrupt row counts for nothing. */
326
+ function teamAgentsSince(cfg: Config, team: TeamEntry, since: number): Set<string> {
327
+ const ids = new Set<string>();
328
+ let text: string;
329
+ try {
330
+ text = readFileSync(path.join(teamDir(cfg, team), "spawns.jsonl"), "utf8");
331
+ } catch {
332
+ return ids;
333
+ }
334
+ for (const line of text.split("\n")) {
335
+ if (!line) continue;
336
+ try {
337
+ const row = JSON.parse(line) as { agentId?: unknown; at?: unknown };
338
+ if (typeof row.agentId === "string" && typeof row.at === "number" && row.at >= since) ids.add(row.agentId);
339
+ } catch {}
340
+ }
341
+ return ids;
342
+ }
343
+
344
+ /** The team token cap (plan P6b2 d): a refusal when a capped team's calls today reach its max_share of all calls today. Null when no team is capped or it is under. */
345
+ export function teamCapProblem(teams: RoutedTeam[], spawn: SpawnIdent, cfg: Config): string | null {
346
+ const capped = teams.flatMap(({ team }) => (team.max_share === undefined ? [] : [{ team, cap: team.max_share }]));
347
+ const [first] = capped;
348
+ if (first === undefined) return null;
349
+ if (!spawn.runs) return `team ${first.team.name} sets max_share: the cap cannot be computed without a run source`;
350
+ const since = dayStartSec();
351
+ const runs = spawn.runs.listRuns(since);
352
+ const total = runs.reduce((sum, r) => sum + r.calls, 0);
353
+ if (total === 0) return null;
354
+ for (const { team, cap } of capped) {
355
+ const ids = teamAgentsSince(cfg, team, since);
356
+ const mine = runs.filter((r) => ids.has(r.id)).reduce((sum, r) => sum + r.calls, 0);
357
+ if (mine / total >= cap) return `team ${team.name} cap reached: ${mine} of ${total} calls today (max_share ${cap}); team plans wait until local midnight`;
358
+ }
359
+ return null;
360
+ }
361
+
362
+ /** Records each named agent against each team plan it spawned on, one spawns.jsonl row each, so the cap counts its calls. Rows are written only for team plans. */
363
+ function recordTeamSpawns(teams: RoutedTeam[], agentIds: string[], cfg: Config): void {
364
+ if (agentIds.length === 0) return;
365
+ for (const { team, file } of teams) {
366
+ const planId = pathId(team, cfg, file, defaultRunner);
367
+ if (planId === null) continue;
368
+ const dir = teamDir(cfg, team);
369
+ const at = nowSec();
370
+ const rows = agentIds.map((agentId) => `${JSON.stringify({ planId, agentId, at })}\n`).join("");
371
+ try {
372
+ mkdirSync(dir, { recursive: true });
373
+ appendFileSync(path.join(dir, "spawns.jsonl"), rows);
374
+ } catch (err) {
375
+ log(cfg.paths.guard_log, `cannot record team spawn for ${team.name}: ${err}`);
376
+ }
377
+ }
378
+ }
379
+
380
+ /**
381
+ * The spawn claim gate (plan 20261027_1300 P3): a spawn on a plan claims it for this Main first;
382
+ * another Main's live claim refuses the launch — a sub's launch too, once its Main no longer
383
+ * holds the claim. Returns the refusal, or null.
384
+ */
385
+ function claimGate(files: string[], cfg: Config, spawn: SpawnIdent): string | null {
386
+ const teams = routedTeams(files, cfg);
387
+ const uncountable = teams.find(({ team }) => team.max_share !== undefined);
388
+ if (spawn.unnamed && uncountable) {
389
+ return `team ${uncountable.team.name} sets max_share: name this agent (tasks[].name) so its calls count against the team cap`;
390
+ }
391
+ const mine = mainId();
392
+ // With the chooser each file has its own store; `fresh` carries the store beside each file,
393
+ // so a fresh claim is released through the store that took it (a team claim released through
394
+ // the file store would be a silent no-op that outlives the refusal until the TTL).
395
+ const fresh: { file: string; store: ClaimStore }[] = [];
396
+ // A refusal leaves the store as it found it: claims this call newly created are released
397
+ // again through the store that took each one; a claim this Main already held before the
398
+ // call stays.
399
+ const releaseFresh = (): void => {
400
+ for (const g of fresh) g.store.release(g.file, mine);
401
+ };
402
+ for (const f of files) {
403
+ const store = claimStoreFor(f, cfg);
404
+ const h = store.holder(f);
405
+ // Fail closed: an unreachable server refuses the spawn and leaves no claim this call took.
406
+ if (h !== null && "unreachable" in h) {
407
+ releaseFresh();
408
+ return heldProblem(f, h);
409
+ }
410
+ const heldBefore = h !== null && !heldByOther(h, mine);
411
+ const c = store.claim(f, mine);
412
+ if ("unreachable" in c) {
413
+ // The outage started between holder() and claim(): release what this call took.
414
+ releaseFresh();
415
+ return heldProblem(f, c);
416
+ }
417
+ if ("heldBy" in c) {
418
+ releaseFresh();
419
+ return heldProblem(f, c.heldBy);
420
+ }
421
+ if (!heldBefore) fresh.push({ file: f, store });
422
+ }
423
+ const capped = teamCapProblem(teams, spawn, cfg);
424
+ if (capped) {
425
+ releaseFresh();
426
+ return capped;
427
+ }
428
+ recordTeamSpawns(teams, spawn.agentIds, cfg);
429
+ return null;
430
+ }
431
+
432
+ /** Reason to refuse a `task` brief, or null; `files` receives the plans to record, `budgets` every named task's call budget (null = none), `staffing` each plan's named tasks of this call, `runningJobs` the caller's running job labels (undefined = no job info). Every refusal lands in one numbered verdict (plan 20261031_1207 P4). */
433
+ export function spawnProblem(
434
+ input: Record<string, unknown>,
435
+ cfg: Config,
436
+ files: string[] = [],
437
+ budgets: Record<string, number | null> = {},
438
+ staffing: Record<string, string[]> = {},
439
+ runningJobs?: string[],
440
+ runner: CommandRunner = defaultRunner,
441
+ spawner: Spawner = "main",
442
+ ): string | null {
443
+ const roles: Record<string, string | null> = {};
444
+ const plannerRoles: Record<string, string> = {};
445
+ const tasks = Array.isArray(input?.tasks) ? input.tasks : [];
446
+ const context = String(input?.context ?? "");
447
+ const allowed = q.allowedAgents(cfg.paths.subagents);
448
+ const shared = briefBudget(context);
449
+ const problems: string[] = [];
450
+ const named: Record<string, number | null> = {};
451
+ for (const t of tasks) {
452
+ const agent = String(t?.agent ?? "task");
453
+ const label = String(t?.name ?? agent);
454
+ const text = `${context}\n${String(t?.task ?? "")}`;
455
+ // The role line belongs to the task's own brief (the adapter keys the spawn's brief by it);
456
+ // a mention in the shared context names no one's role.
457
+ const plannerFor = plannerRolePlan(String(t?.task ?? ""));
458
+ // planner mode P2 (c): a Planner-role brief is refused while the mode is main — the switch
459
+ // is the owner's (`planner delegated`). While delegated the planner spawn skips the open-plan
460
+ // gates below (the plan it names does not exist yet — writing it is the spawn's job), but the
461
+ // ## Allowed deny still holds, and it needs a name to key its role.
462
+ if (plannerFor && currentPlanner(cfg) === "main") {
463
+ problems.push(`${label}: planner mode is main — a Planner-role spawn needs the owner's \`planner delegated\` switch.`);
464
+ continue;
465
+ }
466
+ const plannerBad = plannerFor ? plannerPlanProblem(plannerFor) : null;
467
+ if (plannerBad) {
468
+ problems.push(`${label}: ${plannerBad}`);
469
+ continue;
470
+ }
471
+ if (plannerFor && !t?.name) {
472
+ problems.push(`${label}: a planner spawn needs a name (the task name keys its planner role).`);
473
+ continue;
474
+ }
475
+ if (plannerFor) {
476
+ if (!allowed.has(agent)) {
477
+ problems.push(`${label}: agent "${agent}" is not in "## Allowed" of ${cfg.paths.subagents} (no expensive or unpinned models).`);
478
+ continue;
479
+ }
480
+ plannerRoles[label] = plannerFor;
481
+ continue;
482
+ }
483
+ if (!allowed.has(agent)) {
484
+ problems.push(`${label}: agent "${agent}" is not in "## Allowed" of ${cfg.paths.subagents} (no expensive or unpinned models).`);
485
+ continue;
486
+ }
487
+ const [why, plans] = planGate(text, label, cfg);
488
+ if (why) {
489
+ problems.push(why);
490
+ continue;
491
+ }
492
+ // P3 (plan 20261028_1600): the task tool is the live spawn path; every task carries its own
493
+ // pending-work check, before the call-wide gates below. The task's own `Call budget:` line
494
+ // wins over the shared context's.
495
+ const role = reviewRole(t?.name, plans, text, agent, cfg, spawner);
496
+ const taskProblems = [
497
+ pendingWorkProblem(plans, text, cfg, runner),
498
+ role.problem,
499
+ reviewPassProblem(plans, text, agent, cfg, spawner),
500
+ ];
501
+ const budget = briefBudget(String(t?.task ?? "")) ?? shared;
502
+ if (budget !== null) {
503
+ if (!t?.name) taskProblems.push(`${label}: "Call budget: ${budget}" needs a task name (the budget is keyed by it).`);
504
+ else if (budget < 10 || budget > cfg.guards.sub_max_calls_cap)
505
+ taskProblems.push(`call budget ${budget} is outside the allowed range 10..${cfg.guards.sub_max_calls_cap}.`);
506
+ }
507
+ const own = taskProblems.filter((p): p is string => p !== null).map(p => (p.startsWith(`${label}:`) ? p : `${label}: ${p}`));
508
+ if (own.length) {
509
+ problems.push(...own);
510
+ continue;
511
+ }
512
+ if (t?.name) {
513
+ roles[label] = role.plan;
514
+ named[label] = budget;
515
+ for (const f of plans) staffing[f] = [...(staffing[f] ?? []), label];
516
+ }
517
+ files.push(...plans);
518
+ }
519
+ Object.assign(budgets, named);
520
+ // Who is limited and who goes first come from live data and ledger.prefer (plan 20261025_1700
521
+ // P3): the same rules checkSpawn applies to single-spawn events, per task.
522
+ const joined = `${context}\n${tasks.map(t => String(t?.task ?? "")).join("\n")}`;
523
+ const claim = providerClaimProblem(joined, cfg);
524
+ if (claim) problems.push(claim);
525
+ for (const t of tasks) {
526
+ const pick = preferProblem(String(t?.agent ?? "task"), `${context}\n${String(t?.task ?? "")}`, runningJobs, cfg);
527
+ if (pick) problems.push(`${String(t?.name ?? t?.agent ?? "task")}: ${pick}`);
528
+ }
529
+ // Priority gate (20261025_0215 P3): once per `task` call, over the plans this call names; the
530
+ // skip lines may sit in the shared context or any task text.
531
+ const gate = priorityGate(
532
+ files,
533
+ runningJobs,
534
+ joined,
535
+ cfg,
536
+ String((tasks[0] && (tasks[0].name ?? tasks[0].agent)) ?? "task"),
537
+ String((tasks[0] && tasks[0].agent) ?? "task"),
538
+ spawner,
539
+ );
540
+ if (gate) problems.push(gate);
541
+ const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
542
+ if (inc) problems.push(inc);
543
+ const verdict = spawnVerdict(
544
+ String((tasks[0] && (tasks[0].name ?? tasks[0].agent)) ?? "task"),
545
+ problems,
546
+ files.length ? files : briefPlans(joined, cfg).map(p => p.file),
547
+ runningJobs,
548
+ cfg,
549
+ );
550
+ if (verdict) return verdict;
551
+ for (const [name, plan] of Object.entries(roles)) recordReviewSpawn(name, plan, cfg.paths);
552
+ for (const [name, plan] of Object.entries(plannerRoles)) recordPlannerSpawn(name, plan, cfg.paths);
553
+ return null;
554
+ }
555
+
556
+ /**
557
+ * A `task` launch: the cancel check, the spawn gates, then the records. Main's and a sub's launch
558
+ * both come through here (plan 20261028_1600 P4i). Returns the refusal, or null.
559
+ */
560
+ export function taskLaunch(input: Record<string, unknown>, cfg: Config, runningJobs: string[] | undefined, spawner: Spawner, runs?: RunSource): string | null {
561
+ const pending = q.cancelPending(cfg.paths);
562
+ if (pending) {
563
+ log(cfg.paths.guard_log, `BLOCK spawn: cancel pending (${pending.words})`);
564
+ return `${CANCEL_TODO} Flagged: "${pending.words}"`;
565
+ }
566
+ // P4 (plan 20261031_1207): spawnProblem's verdict now carries the incident check too, so one
567
+ // deny lists every problem.
568
+ const files: string[] = [];
569
+ const budgets: Record<string, number | null> = {};
570
+ const staffing: Record<string, string[]> = {};
571
+ const why = spawnProblem(input, cfg, files, budgets, staffing, runningJobs, defaultRunner, spawner);
572
+ if (why) {
573
+ log(cfg.paths.guard_log, `BLOCK spawn: ${why}`);
574
+ return why;
575
+ }
576
+ const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
577
+ if (inc) return inc;
578
+ const spawned: unknown[] = Array.isArray(input.tasks) ? input.tasks : [];
579
+ const names = spawned.map((t) => (t as { name?: unknown } | null)?.name);
580
+ const held = claimGate(files, cfg, {
581
+ agentIds: names.filter((n): n is string => typeof n === "string" && n !== ""),
582
+ unnamed: names.some((n) => typeof n !== "string" || n === ""),
583
+ runs,
584
+ });
585
+ if (held) {
586
+ log(cfg.paths.guard_log, `BLOCK spawn: ${held}`);
587
+ return held;
588
+ }
589
+ recordSpawns(files, cfg.paths, staffing);
590
+ recordBudgets(budgets, cfg.paths);
591
+ return null;
592
+ }
593
+
594
+ /**
595
+ * A shell launch of a bypass_spawn agent: the cancel check, the plan gate, the review PASS, the
596
+ * incidents, then the record. Main's and a sub's launch both come through here (plan 20261028_1600 P4i).
597
+ */
598
+ export function bypassLaunch(command: string, cfg: Config, spawner: Spawner, runs?: RunSource): string | null {
599
+ for (const entry of cfg.guards.bypass_spawn) {
600
+ if (!bypassRegExp(entry).test(command)) continue;
601
+ const pending = q.cancelPending(cfg.paths);
602
+ if (pending) {
603
+ log(cfg.paths.guard_log, `BLOCK bypass launch: cancel pending (${pending.words})`);
604
+ return `${CANCEL_TODO} Flagged: "${pending.words}"`;
605
+ }
606
+ const [why, named] = planGate(command, entry, cfg);
607
+ if (why) {
608
+ log(cfg.paths.guard_log, `BLOCK bypass launch: ${why}`);
609
+ return why;
610
+ }
611
+ const review = reviewPassProblem(named, command, "", cfg, spawner);
612
+ if (review) {
613
+ log(cfg.paths.guard_log, `BLOCK bypass launch: ${review}`);
614
+ return review;
615
+ }
616
+ const inc = incidentSpawnProblem("bypass launch", command, named, cfg);
617
+ if (inc) return inc;
618
+ // I-20261031-280: a bypass launch takes the claims like every other spawn, as its last
619
+ // refusal before the record.
620
+ const held = claimGate(named, cfg, { agentIds: [], unnamed: true, runs });
621
+ if (held) {
622
+ log(cfg.paths.guard_log, `BLOCK bypass launch: ${held}`);
623
+ return held;
624
+ }
625
+ if (named.length) recordSpawns(named, cfg.paths);
626
+ }
627
+ return null;
628
+ }
629
+
630
+ /**
631
+ * spawn: the allow-list, task-only and open-plan gates for one implementer launch. Covers both
632
+ * original paths (the extension spawn event and a `task` tool call); the brief names the plan.
633
+ */
634
+ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = defaultRunner, runs?: RunSource): Decision {
635
+ return tuned(checkSpawnRules(e, cfg, runner, runs), cfg);
636
+ }
637
+
638
+ function checkSpawnRules(e: SpawnEvent, cfg: Config, runner: CommandRunner = defaultRunner, runs?: RunSource): Decision {
639
+ const pending = q.cancelPending(cfg.paths);
640
+ if (pending) {
641
+ log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: cancel pending (${pending.words}) rule=spawn.cancel-pending`);
642
+ return deny(`main-guard: ${CANCEL_TODO} Flagged: "${pending.words}"`, "spawn.cancel-pending");
643
+ }
644
+ const allowed = q.allowedAgents(cfg.paths.subagents);
645
+ if (!allowed.has(e.agent))
646
+ return deny(`main-guard: ${e.agent}: agent "${e.agent}" is not in "## Allowed" of ${cfg.paths.subagents} (no expensive or unpinned models).`, "spawn.agent-allowed");
647
+ if (e.invocationKind !== "task")
648
+ return deny("main-guard: spawn implementers with the task tool (the plan gate checks its brief).", "spawn.task-tool");
649
+ // P4 (plan 20261031_1207): every gate's refusal lands in one numbered verdict; nothing
650
+ // short-circuits, so Main sees all the problems in one round trip.
651
+ const problems: string[] = [];
652
+ // planner mode P2 (c): a Planner-role brief is refused while the mode is main — the switch is
653
+ // the owner's (`planner delegated`). While delegated the planner spawn skips the open-plan
654
+ // gates (the plan it names does not exist yet — writing it is the spawn's job) and its role
655
+ // binds to the spawn name at the tail; a planner spawn needs that name.
656
+ const plannerFor = plannerRolePlan(e.brief);
657
+ const delegatedPlanner = plannerFor !== null && currentPlanner(cfg) === "delegated";
658
+ if (plannerFor && !delegatedPlanner)
659
+ problems.push(`${e.agent}: planner mode is main — a Planner-role spawn needs the owner's \`planner delegated\` switch.`);
660
+ else if (delegatedPlanner && plannerPlanProblem(plannerFor)) problems.push(`${e.agent}: ${plannerPlanProblem(plannerFor)}`);
661
+ else if (delegatedPlanner && !e.name) problems.push(`${e.agent}: a planner spawn needs a name (the task name keys its planner role).`);
662
+ const [why, named] = delegatedPlanner ? [null, [] as string[]] : planGate(e.brief, e.agent, cfg);
663
+ if (why) problems.push(why);
664
+ const gate = priorityGate(named, e.runningJobs, e.brief, cfg, e.agent, e.agent, "main");
665
+ if (gate) problems.push(gate);
666
+ const pendingWork = pendingWorkProblem(named, e.brief, cfg, runner);
667
+ if (pendingWork) problems.push(pendingWork);
668
+ const role = reviewRole(e.name, named, e.brief, e.agent, cfg, "main");
669
+ if (role.problem) problems.push(role.problem);
670
+ const review = reviewPassProblem(named, e.brief, e.agent, cfg, "main");
671
+ if (review) problems.push(review);
672
+ const inc = incidentSpawnProblem(`spawn ${e.agent}`, e.brief, named, cfg);
673
+ if (inc) problems.push(inc);
674
+ const claim = providerClaimProblem(e.brief, cfg);
675
+ if (claim) problems.push(`${e.agent}: ${claim}`);
676
+ const pick = preferProblem(e.agent, e.brief, e.runningJobs, cfg);
677
+ if (pick) problems.push(`${e.agent}: ${pick}`);
678
+ const verdict = spawnVerdict(e.agent, problems, named.length ? named : briefPlans(e.brief, cfg).map(p => p.file), e.runningJobs, cfg);
679
+ if (verdict) {
680
+ for (const p of problems) {
681
+ if (p === role.problem) log(cfg.paths.plan_guard_log, `BLOCK ${e.agent} ${e.name ?? "(unnamed)"} review spawn: ${p} rule=spawn.verdict`);
682
+ else log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${p} rule=spawn.verdict`);
683
+ }
684
+ return deny(`main-guard: ${verdict}`, "spawn.verdict");
685
+ }
686
+ const held = claimGate(named, cfg, { agentIds: e.name ? [e.name] : [], unnamed: !e.name, runs });
687
+ if (held) {
688
+ log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${held} rule=spawn.claim-held`);
689
+ return deny(`main-guard: ${held}`, "spawn.claim-held");
690
+ }
691
+ // The owner's pick order and live provider state (plan 20261025_1700 P3), before the spawn records.
692
+ const staffing: Record<string, string[]> = {};
693
+ for (const f of named) staffing[f] = [e.agent];
694
+ recordSpawns(named, cfg.paths, staffing);
695
+ if (e.name) recordReviewSpawn(e.name, role.plan, cfg.paths);
696
+ // planner mode P2 (b): the approved planner spawn binds its name to the plan its brief named.
697
+ if (delegatedPlanner && e.name && plannerFor) recordPlannerSpawn(e.name, plannerFor, cfg.paths);
698
+ return ALLOW;
699
+ }