neurastream 0.2.57 → 0.2.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.57",
3
+ "version": "0.2.58",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -37,8 +37,13 @@ function escapeReg(s: string): string {
37
37
  /** A scanned path without its trailing sentence punctuation (the path loop's cleaning). */
38
38
  const clean = (raw: string): string => raw.replace(/[.,)]+$/, "");
39
39
 
40
- function lint(path: string, cfg: Config): { errs: string[]; warns: string[] } {
41
- const text = readFileSync(path, "utf8");
40
+ /** The same rules on a file on disk; the guard's spawn verdict lints the named plan files (plan 20261031_1207 P4). */
41
+ export function lint(path: string, cfg: Config): { errs: string[]; warns: string[] } {
42
+ return lintText(readFileSync(path, "utf8"), cfg);
43
+ }
44
+
45
+ /** P4 (plan 20261031_1207): the guard's spawn verdict lints the named plan files itself, so the rules must run on text the guard already has, not only on a file path. */
46
+ export function lintText(text: string, cfg: Config): { errs: string[]; warns: string[] } {
42
47
  const low = text.toLowerCase();
43
48
  const lines = text.split(/\r?\n/);
44
49
  const first = lines[0] ?? "";
@@ -23,13 +23,14 @@
23
23
 
24
24
  import { execFileSync } from "node:child_process";
25
25
  import { appendFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
26
+ import { homedir } from "node:os";
26
27
  import path from "node:path";
27
28
  import type { Decision, InjectEvent, PlanEditEvent, SpawnEvent, StopEvent, ToolEvent } from "./adapter.ts";
28
29
  import { currentTier, takeGo } from "./autonomy.ts";
29
30
  import { approvalProblem, MAIN_ONLY_LINE, reviewHash } from "./plan-approval.ts";
30
31
  export { reviewHash };
31
32
  import type { Config } from "./config.ts";
32
- import { addIncident, openIncidents, ownerMessagesFile, ownerSaid, readOwnerMessages, type IncidentView, type OwnerMessage } from "./incidents.ts";
33
+ import { openIncidents, ownerMessagesFile, ownerSaid, readOwnerMessages, type IncidentView, type OwnerMessage } from "./incidents.ts";
33
34
  import { notifyProtectedPaths, notifySecretReadHit } from "./notify.ts";
34
35
  import { defaultRunner, listOpenMrs, mentioned, type CommandRunner, type OpenMr } from "./mr-sweep.ts";
35
36
  import { unlandedRows } from "./wip-check.ts";
@@ -38,6 +39,7 @@ import type { Plan } from "./queue/lib.ts";
38
39
 
39
40
  import { nowSec } from "./clock.ts";
40
41
  import { outUntil, pinModel, providerOfModel, readOut } from "./provider-state.ts";
42
+ import { lint } from "./brief-lint.ts";
41
43
  const ALLOW: Decision = { allow: true, reason: "" };
42
44
 
43
45
  /**
@@ -304,13 +306,14 @@ function matchReviewSpawn(spawns: Record<string, ReviewSpawn>, agentId: string):
304
306
  return null;
305
307
  }
306
308
 
307
- /** P4f: the secret-read deny: credential dirs under home, and env files. */
309
+ /** P4f: the secret-read deny: credential dirs under a home, and env files. Shell text expands `~` to the process home (queue lib) while config points at the sandbox home in tests, so both roots are judged; they are the same directory in production. */
308
310
  function secretPath(p: string, cfg: Config, cwd: string): boolean {
309
- const home = cfg.paths.home;
310
- const abs = path.resolve(cwd, p.startsWith("~/") ? path.join(home, p.slice(2)) : p);
311
+ const abs = path.resolve(cwd, p.startsWith("~/") ? path.join(cfg.paths.home, p.slice(2)) : p);
311
312
  const base = path.basename(abs);
312
- const inCredDir = [".config", ".ssh", ".gnupg", ".aws"].some(d => abs.startsWith(path.join(home, d) + path.sep));
313
- return inCredDir || base.startsWith(".env") || base.endsWith(".env");
313
+ if (base.startsWith(".env") || base.endsWith(".env")) return true;
314
+ return [cfg.paths.home, homedir()].some(home =>
315
+ [".config", ".ssh", ".gnupg", ".aws"].some(d => abs.startsWith(path.join(path.resolve(home), d) + path.sep)),
316
+ );
314
317
  }
315
318
 
316
319
  /** P4f: a named review spawn may read, use todo, and edit only its own plan. Shell, spawn, cancel and MCP tools are denied; so are secret reads. */
@@ -327,6 +330,15 @@ function reviewLockProblem(e: ToolEvent, cfg: Config): string | null {
327
330
  const reads = [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)];
328
331
  return reads.some(p => secretPath(p, cfg, e.cwd)) ? `review spawn ${e.agentId} may not read credentials or env files.` : null;
329
332
  }
333
+ // P5 (plan 20261031_1207): a shell call gets the read tools' deny — allowed when it writes
334
+ // nothing and its text carries no landing/mutating/spawn command and no secret path.
335
+ if (cfg.guards.shell_tools.includes(e.tool)) {
336
+ const writes = [...(e.writes ?? []), ...q.writeTargets(e.tool, input, e.cwd, [])];
337
+ if (writes.length || writesShellText(input, cfg))
338
+ return `review spawn ${e.agentId} may only read, use todo, and edit its plan; shell writes, landing and mutating commands are denied.`;
339
+ const reads = [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)];
340
+ return reads.some(p => secretPath(p, cfg, e.cwd)) ? `review spawn ${e.agentId} may not read credentials or env files.` : null;
341
+ }
330
342
  return `review spawn ${e.agentId} may only read, use todo, and edit its plan; ${e.tool} is denied.`;
331
343
  }
332
344
 
@@ -341,8 +353,13 @@ function staffingFile(): string {
341
353
  // The owner-message store (owner-messages.jsonl) and its matcher live in src/core/incidents.ts
342
354
  // (20261028_0900 P3): dismissIncident needs them too, and guards already imports incidents.
343
355
 
356
+ /** P3 (plan 20261031_1207): the text is owner prose — not Main's own guard output, a system notice, a task result — so its words are the owner's. Gates both the owner-message store and the cancel flag. */
357
+ function isOwnerProse(text: string): boolean {
358
+ return !(text.trimStart().startsWith("main-guard:") || text.trimStart().startsWith("<system-notice>") || text.includes("<task-result"));
359
+ }
360
+
344
361
  function recordOwnerMessage(text: string, cfg: Config): void {
345
- if (text.trimStart().startsWith("main-guard:") || text.trimStart().startsWith("<system-notice>") || text.includes("<task-result")) return;
362
+ if (!isOwnerProse(text)) return;
346
363
  const file = ownerMessagesFile();
347
364
  try {
348
365
  mkdirSync(q.STATE_DIR, { recursive: true });
@@ -549,6 +566,12 @@ function unticked(p: Plan): string[] {
549
566
  return [...phases.matchAll(/^\s*[-*]\s+\[ \]\s+(P\d+[a-z]?)\b/gm)].map(m => m[1]!);
550
567
  }
551
568
 
569
+ /** 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). */
570
+ function briefPlans(text: string, cfg?: Config): Plan[] {
571
+ const body = text.replace(/^\s*(?:[-*]\s+)?priority skip:.*$/gim, "");
572
+ return q.activePlans(undefined, undefined, cfg?.review.agents ?? []).filter(p => body.includes(p.file));
573
+ }
574
+
552
575
  // Plans an implementer brief may run on; returns [reason, null] or [null, plan files].
553
576
  export function planGate(text: string, label: string, cfg?: Config): [string | null, string[]] {
554
577
  const plans = q.activePlans(undefined, undefined, cfg?.review.agents ?? []);
@@ -558,10 +581,7 @@ export function planGate(text: string, label: string, cfg?: Config): [string | n
558
581
  `${label}: ${unclosed.map(p => `${p.file} (${p.status})`).join(", ")} is still indexed. Verify it and run \`queue-close <plan>\` before any new spawn.`,
559
582
  [],
560
583
  ];
561
- // A `Priority skip: <path> — <why>` line names a plan it does NOT run on (20261025_0215 P3);
562
- // only the remaining text decides which plans this brief targets.
563
- const body = text.replace(/^\s*(?:[-*]\s+)?priority skip:.*$/gim, "");
564
- const named = plans.filter(p => body.includes(p.file));
584
+ const named = briefPlans(text, cfg);
565
585
  if (!named.length)
566
586
  return [
567
587
  `${label}: an implementer needs an open plan. Name the plan's absolute path in the brief; the plan must be listed in ${q.INDEX}.`,
@@ -769,6 +789,37 @@ export function preferProblem(agent: string, brief: string, runningJobs: readonl
769
789
  return null;
770
790
  }
771
791
 
792
+ /** 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). */
793
+ function ledgerCapProblem(agent: string, runningJobs: readonly string[] | undefined, cfg: Config): string | null {
794
+ const provider = providerOfModel(pinModel(cfg, agent));
795
+ if (provider === null || outUntil(cfg, provider) !== null) return null;
796
+ const sharers = [agent, ...cfg.ledger.prefer.filter(a => providerOfModel(pinModel(cfg, a)) === provider)];
797
+ const running = (runningJobs ?? []).filter(l => sharers.some(n => l.toLowerCase().includes(n.toLowerCase()))).length;
798
+ if (running < cfg.ledger.max_running_per_provider) return null;
799
+ 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.`;
800
+ }
801
+
802
+ /**
803
+ * The one spawn verdict (plan 20261031_1207 P4): every refusal in one numbered list, so Main fixes
804
+ * all of them in one round trip. The named plans' brief-lint errors and the provider-cap note (the
805
+ * advice Main gathered by hand through `brief-lint` and `agent-ledger --cap`) ride along on an
806
+ * already-refused spawn — alone they never refuse: real plans carry lint nits, and a full provider
807
+ * is the prefer order's to weigh, not a gate of its own.
808
+ */
809
+ function spawnVerdict(agent: string, problems: string[], lintFiles: string[], runningJobs: readonly string[] | undefined, cfg: Config): string | null {
810
+ if (!problems.length) return null;
811
+ const advice: string[] = [];
812
+ for (const f of new Set(lintFiles)) {
813
+ try {
814
+ for (const e of lint(f, cfg).errs) advice.push(`${f}: ${e}`);
815
+ } catch {} // an unreadable plan's refusal is planGate's to name
816
+ }
817
+ const cap = ledgerCapProblem(agent, runningJobs, cfg);
818
+ if (cap) advice.push(cap);
819
+ const all = [...problems, ...advice];
820
+ return `${agent}: ${all.length} ${all.length === 1 ? "problem" : "problems"}:\n${all.map((p, i) => `${i + 1}. ${p}`).join("\n")}`;
821
+ }
822
+
772
823
  /**
773
824
  * Who is rate-limited comes from live data (plan 20261025_1700 P1): refuse a brief that asserts a
774
825
  * provider shown free by providerStatus is rate-limited — named directly or through a prefer
@@ -794,7 +845,7 @@ export function providerClaimProblem(text: string, cfg: Config): string | null {
794
845
  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.`;
795
846
  }
796
847
 
797
- /** 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). */
848
+ /** 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). */
798
849
  export function spawnProblem(
799
850
  input: Record<string, unknown>,
800
851
  cfg: Config,
@@ -810,30 +861,43 @@ export function spawnProblem(
810
861
  const context = String(input?.context ?? "");
811
862
  const allowed = q.allowedAgents();
812
863
  const shared = briefBudget(context);
864
+ const problems: string[] = [];
813
865
  const named: Record<string, number | null> = {};
814
866
  for (const t of tasks) {
815
867
  const agent = String(t?.agent ?? "task");
816
868
  const label = String(t?.name ?? agent);
817
- if (!allowed.has(agent)) return `${label}: agent "${agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`;
818
- const [why, plans] = planGate(`${context}\n${String(t?.task ?? "")}`, label, cfg);
819
- if (why) return why;
869
+ const text = `${context}\n${String(t?.task ?? "")}`;
870
+ if (!allowed.has(agent)) {
871
+ problems.push(`${label}: agent "${agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`);
872
+ continue;
873
+ }
874
+ const [why, plans] = planGate(text, label, cfg);
875
+ if (why) {
876
+ problems.push(why);
877
+ continue;
878
+ }
820
879
  // P3 (plan 20261028_1600): the task tool is the live spawn path; every task carries its own
821
- // pending-work check, before the call-wide gates below.
822
- const pending = pendingWorkProblem(plans, `${context}\n${String(t?.task ?? "")}`, cfg, runner);
823
- if (pending) return `${label}: ${pending}`;
824
- // The task's own `Call budget:` line wins over the shared context's.
825
- const role = reviewRole(t?.name, plans, `${context}\n${String(t?.task ?? "")}`, String(t?.agent ?? ""), cfg, spawner);
826
- if (role.problem) return `${label}: ${role.problem}`;
827
- if (t?.name) roles[label] = role.plan;
828
- const review = reviewPassProblem(plans, `${context}\n${String(t?.task ?? "")}`, String(t?.agent ?? ""), cfg, spawner);
829
- if (review) return `${label}: ${review}`;
880
+ // pending-work check, before the call-wide gates below. The task's own `Call budget:` line
881
+ // wins over the shared context's.
882
+ const role = reviewRole(t?.name, plans, text, agent, cfg, spawner);
883
+ const taskProblems = [
884
+ pendingWorkProblem(plans, text, cfg, runner),
885
+ role.problem,
886
+ reviewPassProblem(plans, text, agent, cfg, spawner),
887
+ ];
830
888
  const budget = briefBudget(String(t?.task ?? "")) ?? shared;
831
889
  if (budget !== null) {
832
- if (!t?.name) return `${label}: "Call budget: ${budget}" needs a task name (the budget is keyed by it).`;
833
- if (budget < 10 || budget > cfg.guards.sub_max_calls_cap)
834
- return `${label}: call budget ${budget} is outside the allowed range 10..${cfg.guards.sub_max_calls_cap}.`;
890
+ if (!t?.name) taskProblems.push(`${label}: "Call budget: ${budget}" needs a task name (the budget is keyed by it).`);
891
+ else if (budget < 10 || budget > cfg.guards.sub_max_calls_cap)
892
+ taskProblems.push(`call budget ${budget} is outside the allowed range 10..${cfg.guards.sub_max_calls_cap}.`);
893
+ }
894
+ const own = taskProblems.filter((p): p is string => p !== null).map(p => (p.startsWith(`${label}:`) ? p : `${label}: ${p}`));
895
+ if (own.length) {
896
+ problems.push(...own);
897
+ continue;
835
898
  }
836
899
  if (t?.name) {
900
+ roles[label] = role.plan;
837
901
  named[label] = budget;
838
902
  for (const f of plans) staffing[f] = [...(staffing[f] ?? []), label];
839
903
  }
@@ -842,22 +906,33 @@ export function spawnProblem(
842
906
  Object.assign(budgets, named);
843
907
  // Who is limited and who goes first come from live data and ledger.prefer (plan 20261025_1700
844
908
  // P3): the same rules checkSpawn applies to single-spawn events, per task.
845
- const claim = providerClaimProblem(`${context}\n${tasks.map(t => String(t?.task ?? "")).join("\n")}`, cfg);
846
- if (claim) return claim;
909
+ const joined = `${context}\n${tasks.map(t => String(t?.task ?? "")).join("\n")}`;
910
+ const claim = providerClaimProblem(joined, cfg);
911
+ if (claim) problems.push(claim);
847
912
  for (const t of tasks) {
848
913
  const pick = preferProblem(String(t?.agent ?? "task"), `${context}\n${String(t?.task ?? "")}`, runningJobs, cfg);
849
- if (pick) return `${String(t?.name ?? t?.agent ?? "task")}: ${pick}`;
914
+ if (pick) problems.push(`${String(t?.name ?? t?.agent ?? "task")}: ${pick}`);
850
915
  }
851
916
  // Priority gate (20261025_0215 P3): once per `task` call, over the plans this call names; the
852
917
  // skip lines may sit in the shared context or any task text.
853
918
  const gate = priorityGate(
854
919
  files,
855
920
  runningJobs,
856
- `${context}\n${tasks.map(t => String(t?.task ?? "")).join("\n")}`,
921
+ joined,
857
922
  cfg,
858
923
  String((tasks[0] && (tasks[0].name ?? tasks[0].agent)) ?? "task"),
859
924
  );
860
- if (gate) return gate;
925
+ if (gate) problems.push(gate);
926
+ const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
927
+ if (inc) problems.push(inc);
928
+ const verdict = spawnVerdict(
929
+ String((tasks[0] && (tasks[0].name ?? tasks[0].agent)) ?? "task"),
930
+ problems,
931
+ files.length ? files : briefPlans(joined, cfg).map(p => p.file),
932
+ runningJobs,
933
+ cfg,
934
+ );
935
+ if (verdict) return verdict;
861
936
  for (const [name, plan] of Object.entries(roles)) recordReviewSpawn(name, plan);
862
937
  return null;
863
938
  }
@@ -877,10 +952,15 @@ function runBlockers(plan: Plan, hit: string[], e: ToolEvent, cfg: Config): stri
877
952
  stdio: ["pipe", "pipe", "pipe"],
878
953
  });
879
954
  } catch (err) {
955
+ // P5c (plan 20261031_1207): the deny names the hit paths and the script's own output
956
+ // (stdout+stderr, first 300 chars) so the worker can fix the named file instead of
957
+ // retrying blind; the Error message is the last resort for a script with no output.
958
+ const stdout = typeof err === "object" && err !== null && "stdout" in err && typeof err.stdout === "string" ? err.stdout.trim() : "";
880
959
  const stderr = typeof err === "object" && err !== null && "stderr" in err && typeof err.stderr === "string" ? err.stderr.trim() : "";
881
960
  const message = err instanceof Error ? err.message : String(err);
882
- const why = stderr || `${path.basename(b.script)} failed (${message})`;
883
- return `blocked by plan ${path.basename(plan.file)}: ${why}`;
961
+ const detail = `${stdout}\n${stderr}`.trim().slice(0, 300);
962
+ const why = detail || `${path.basename(b.script)} failed (${message})`;
963
+ return `blocked by plan ${path.basename(plan.file)} (${hit.join(", ")}): ${why}`;
884
964
  }
885
965
  }
886
966
  return null;
@@ -942,6 +1022,19 @@ function landingCommand(input: Record<string, unknown>): boolean {
942
1022
  });
943
1023
  }
944
1024
 
1025
+ // P5/P5c (plan 20261031_1207): the shell text a read-only fast path may never carry — a landing
1026
+ // command (push / MR merge), git add or commit, npm publish, a bypass_spawn launch, or a MUTATING
1027
+ // write. Landing and commit commands produce no write targets, so this text filter — not
1028
+ // writeTargets — is what keeps them out of the review lock's shell allow and the blocker skip.
1029
+ // One predicate for both callers; reviewLockProblem denies it, subRules keeps the blockers on it.
1030
+ function writesShellText(input: Record<string, unknown>, cfg: Config): boolean {
1031
+ if (landingCommand(input)) return true;
1032
+ const text = q.withoutQuotedRedirects(Object.values(input).filter((v): v is string => typeof v === "string").join("\n"));
1033
+ if (/\bgit\s+(add|commit)\b/.test(text) || /\bnpm\s+publish\b/.test(text)) return true;
1034
+ if (cfg.guards.bypass_spawn.some(entry => bypassRegExp(entry).test(text))) return true;
1035
+ return q.MUTATING.test(text);
1036
+ }
1037
+
945
1038
  // The read tool's stand-in for a value it hid. A file may hold one only where it is produced
946
1039
  // (secret-redact.ts) or exercised (its tests).
947
1040
  const PLACEHOLDER = "[REDACTED:";
@@ -991,8 +1084,14 @@ function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[],
991
1084
  const hit = paths.filter(p => !q.isOrchestrationPath(p, plans) && q.planCovers(plan, p, plans));
992
1085
  if (!hit.length) continue;
993
1086
  if (plan.errors.length) return `plan ${plan.file} is invalid (${plan.errors.join("; ")}). Stop and report to Main.`;
994
- const why = runBlockers(plan, hit, e, cfg);
995
- if (why) return why;
1087
+ // P5c (plan 20261031_1207): reads and read-only shell calls skip the phase-0 blockers — a
1088
+ // failing blocker used to deny every read of a covered path and send the worker back blind.
1089
+ // The shell filter is the review lock's (writesShellText), so landing text keeps its blocker.
1090
+ const readOnly = cfg.guards.read_tools.includes(e.tool) || (cfg.guards.shell_tools.includes(e.tool) && !writes.length && !writesShellText(input, cfg));
1091
+ if (!readOnly) {
1092
+ const why = runBlockers(plan, hit, e, cfg);
1093
+ if (why) return why;
1094
+ }
996
1095
  }
997
1096
  return null;
998
1097
  }
@@ -1054,12 +1153,13 @@ export function incidentLine(i: IncidentView): string {
1054
1153
  }
1055
1154
 
1056
1155
  /**
1057
- * While an incident is open, a launch must be fix work: its brief (or a plan the brief names)
1058
- * cites `INCIDENT <id>` of an open incident. Anything else is refused until every open incident
1059
- * has a plan or a dismissal. Returns the refusal reason, or null; `label` names the log line.
1156
+ * While an owner-correction incident (source "realtime") is open, a launch must be fix work: its
1157
+ * brief (or a plan the brief names) cites `INCIDENT <id>` of an open one. Notes from worker
1158
+ * findings/traces never refuse a spawn (plan 20261031_1207 P2). Returns the refusal reason, or
1159
+ * null; `label` names the log line.
1060
1160
  */
1061
1161
  function incidentSpawnProblem(label: string, brief: string, namedPlans: string[], cfg: Config): string | null {
1062
- const open = openIncidentList(cfg);
1162
+ const open = openIncidentList(cfg).filter(i => i.source === "realtime");
1063
1163
  if (!open.length) return null;
1064
1164
  const texts = [brief];
1065
1165
  for (const f of namedPlans) {
@@ -1088,6 +1188,8 @@ function taskLaunch(input: Record<string, unknown>, cfg: Config, runningJobs: st
1088
1188
  log(cfg.paths.guard_log, `BLOCK spawn: cancel pending (${pending.words})`);
1089
1189
  return `${CANCEL_TODO} Flagged: "${pending.words}"`;
1090
1190
  }
1191
+ // P4 (plan 20261031_1207): spawnProblem's verdict now carries the incident check too, so one
1192
+ // deny lists every problem.
1091
1193
  const files: string[] = [];
1092
1194
  const budgets: Record<string, number | null> = {};
1093
1195
  const staffing: Record<string, string[]> = {};
@@ -1096,8 +1198,6 @@ function taskLaunch(input: Record<string, unknown>, cfg: Config, runningJobs: st
1096
1198
  log(cfg.paths.guard_log, `BLOCK spawn: ${why}`);
1097
1199
  return why;
1098
1200
  }
1099
- const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
1100
- if (inc) return inc;
1101
1201
  recordSpawns(files, staffing);
1102
1202
  recordBudgets(budgets);
1103
1203
  return null;
@@ -1413,44 +1513,34 @@ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = d
1413
1513
  return deny(`main-guard: ${e.agent}: agent "${e.agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`);
1414
1514
  if (e.invocationKind !== "task")
1415
1515
  return deny("main-guard: spawn implementers with the task tool (the plan gate checks its brief).");
1516
+ // P4 (plan 20261031_1207): every gate's refusal lands in one numbered verdict; nothing
1517
+ // short-circuits, so Main sees all the problems in one round trip.
1518
+ const problems: string[] = [];
1416
1519
  const [why, named] = planGate(e.brief, e.agent, cfg);
1417
- if (why) {
1418
- log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${why}`);
1419
- return deny(`main-guard: ${why}`);
1420
- }
1520
+ if (why) problems.push(why);
1421
1521
  const gate = priorityGate(named, e.runningJobs, e.brief, cfg, e.agent);
1422
- if (gate) {
1423
- log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${gate}`);
1424
- return deny(`main-guard: ${gate}`);
1425
- }
1522
+ if (gate) problems.push(gate);
1426
1523
  const pendingWork = pendingWorkProblem(named, e.brief, cfg, runner);
1427
- if (pendingWork) {
1428
- log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${pendingWork}`)
1429
- return deny(`main-guard: ${pendingWork}`)
1430
- }
1524
+ if (pendingWork) problems.push(pendingWork);
1431
1525
  const role = reviewRole(e.name, named, e.brief, e.agent, cfg, "main");
1432
- if (role.problem) {
1433
- log(cfg.paths.plan_guard_log, `BLOCK ${e.agent} ${e.name ?? "(unnamed)"} review spawn: ${role.problem}`);
1434
- return deny(`main-guard: ${role.problem}`);
1435
- }
1526
+ if (role.problem) problems.push(role.problem);
1436
1527
  const review = reviewPassProblem(named, e.brief, e.agent, cfg, "main");
1437
- if (review) {
1438
- log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${review}`);
1439
- return deny(`main-guard: ${review}`);
1440
- }
1528
+ if (review) problems.push(review);
1441
1529
  const inc = incidentSpawnProblem(`spawn ${e.agent}`, e.brief, named, cfg);
1442
- if (inc) return deny(`main-guard: ${inc}`);
1443
- // The owner's pick order and live provider state (plan 20261025_1700 P3), before the spawn records.
1530
+ if (inc) problems.push(inc);
1444
1531
  const claim = providerClaimProblem(e.brief, cfg);
1445
- if (claim) {
1446
- log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${claim}`);
1447
- return deny(`main-guard: ${e.agent}: ${claim}`);
1448
- }
1532
+ if (claim) problems.push(`${e.agent}: ${claim}`);
1449
1533
  const pick = preferProblem(e.agent, e.brief, e.runningJobs, cfg);
1450
- if (pick) {
1451
- log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${pick}`);
1452
- return deny(`main-guard: ${e.agent}: ${pick}`);
1534
+ if (pick) problems.push(`${e.agent}: ${pick}`);
1535
+ const verdict = spawnVerdict(e.agent, problems, named.length ? named : briefPlans(e.brief, cfg).map(p => p.file), e.runningJobs, cfg);
1536
+ if (verdict) {
1537
+ for (const p of problems) {
1538
+ if (p === role.problem) log(cfg.paths.plan_guard_log, `BLOCK ${e.agent} ${e.name ?? "(unnamed)"} review spawn: ${p}`);
1539
+ else log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${p}`);
1540
+ }
1541
+ return deny(`main-guard: ${verdict}`);
1453
1542
  }
1543
+ // The owner's pick order and live provider state (plan 20261025_1700 P3), before the spawn records.
1454
1544
  const staffing: Record<string, string[]> = {};
1455
1545
  for (const f of named) staffing[f] = [e.agent];
1456
1546
  recordSpawns(named, staffing);
@@ -1496,7 +1586,11 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
1496
1586
  } catch (err) {
1497
1587
  summary = `Queue unreadable (${q.INDEX}): ${err}`;
1498
1588
  }
1499
- const cancel = continuation ? "" : flagCancel(e.inject, cfg);
1589
+ // P3 (plan 20261031_1207): only owner prose flags cancel, and incident lines pasted into a
1590
+ // prompt (guard output quoting "stop …") never do — their words are not the owner's.
1591
+ const cancel = continuation || !isOwnerProse(e.inject)
1592
+ ? ""
1593
+ : flagCancel(e.inject.split("\n").filter(l => !l.startsWith("INCIDENT I-")).join("\n"), cfg);
1500
1594
  const incidents = openIncidentList(cfg);
1501
1595
  const incidentText = incidents.length ? `\n${incidents.map(incidentLine).join("\n")}` : "";
1502
1596
  // 20261025_1940 P2: the injected line names the autonomy tier and what Main does without asking in it.
@@ -1559,33 +1653,10 @@ export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1559
1653
  log(cfg.paths.plan_guard_log, `RESTORE ${e.path} review line from a spawn that is not its named review spawn`);
1560
1654
  return { allow: false, reason: `plan-guard: a PLAN REVIEW line counts only from the named review spawn of ${e.path}; the file was restored.`, restore: { path: e.path, text: e.before } };
1561
1655
  }
1562
- recordFindings(e, cfg);
1563
1656
  recordReviews(e, cfg);
1564
1657
  return ALLOW;
1565
1658
  }
1566
1659
 
1567
- /**
1568
- * Each finding item of an allowed plan edit becomes an incident (source "findings", evidence =
1569
- * plan path + agent; the default fingerprint dedupes the same item text). A subagent's items are
1570
- * kind "agent-finding"; Main's own are kind "main-finding" (20261028_0900 P1: a bug Main writes
1571
- * down must block the stop like a subagent's). A store failure is logged and swallowed: it must
1572
- * not break the verified edit.
1573
- */
1574
- function recordFindings(e: PlanEditEvent, cfg: Config, kind: "agent-finding" | "main-finding" = "agent-finding"): void {
1575
- try {
1576
- const evidence = `${e.path} (${e.agent})`;
1577
- for (const block of newProgressEntries(e.before, e.after)) {
1578
- const value = findingsValue(block);
1579
- if (!value || /^none\.?$/i.test(value)) continue;
1580
- for (const item of value.split(";")) {
1581
- if (item.trim()) addIncident(cfg, { source: "findings", kind, summary: item.trim(), evidence });
1582
- }
1583
- }
1584
- } catch (err) {
1585
- log(cfg.paths.plan_guard_log, `findings: cannot record incidents for ${e.path}: ${err}`);
1586
- }
1587
- }
1588
-
1589
1660
  /** One "## Progress" entry: its "- " line plus indented continuation lines (trimProgressBody's entry rule). */
1590
1661
  function progressEntries(text: string): string[] {
1591
1662
  const blocks: string[] = [];
@@ -1632,7 +1703,6 @@ function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1632
1703
  };
1633
1704
  }
1634
1705
  if (q.outsideProgress(e.after) === q.outsideProgress(e.before)) {
1635
- recordFindings(e, cfg, "main-finding");
1636
1706
  return ALLOW;
1637
1707
  }
1638
1708
  // A cited file Main did read lands in the list instead of the refusal (I-20261025-208): fix the
@@ -1644,7 +1714,6 @@ function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1644
1714
  const known = new Set(e.before ? planReadProblems(e.before, e.path, cfg) : []);
1645
1715
  const problems = planReadProblems(fixed, e.path, cfg).filter(p => p === NO_SECTION || !known.has(p));
1646
1716
  if (!problems.length) {
1647
- recordFindings(e, cfg, "main-finding");
1648
1717
  if (!fix) return ALLOW;
1649
1718
  const list = fix.paths.join(", ");
1650
1719
  log(cfg.paths.plan_guard_log, `AUTO-LIST ${e.path}: ${list}`);
@@ -1823,8 +1892,9 @@ export const STOP_PLAN_OFFER_REFUSAL = "main-guard: don't promise it — do it n
1823
1892
 
1824
1893
  /**
1825
1894
  * stop: Main may not stop while an open plan is not parked "WAITING on owner" (or the queue has a
1826
- * problem) and no subagent is alive to wake it; an open incident (no plan, no dismissal) blocks
1827
- * the stop regardless of live subagents. Three stop attempts in a row with zero tool calls
1895
+ * problem) and no subagent is alive to wake it; an open owner-correction incident (source
1896
+ * "realtime", no plan, no dismissal) blocks the stop regardless of live subagents. Three stop
1897
+ * attempts in a row with zero tool calls
1828
1898
  * in between are let through. Returns the next counters in `state`.
1829
1899
  */
1830
1900
  export function checkStop(e: StopEvent, cfg: Config): Decision {
@@ -1836,6 +1906,16 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
1836
1906
  log(cfg.paths.guard_log, "BLOCK stop: reply offers or promises instead of doing it");
1837
1907
  return { allow: false, reason: STOP_PLAN_OFFER_REFUSAL, state };
1838
1908
  }
1909
+ // P5 (plan 20261031_1207): once the turn spent its call budget, the stop is the release —
1910
+ // refusing it would order a capped Main to keep making calls the cap itself refuses. The
1911
+ // 15-min window expiry restarts the count, and the keep-working rule with it.
1912
+ if (cfg.guards.main_max_calls > 0) {
1913
+ const w = readWindow();
1914
+ if (w.mainCalls >= cfg.guards.main_max_calls && !mainCallsExpired(w)) {
1915
+ log(cfg.paths.guard_log, `ALLOW stop: turn spent ${w.mainCalls}/${cfg.guards.main_max_calls} calls`);
1916
+ return { ...ALLOW, state };
1917
+ }
1918
+ }
1839
1919
  let open: string[];
1840
1920
  try {
1841
1921
  open = openQueue(cfg.review.agents);
@@ -1852,7 +1932,8 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
1852
1932
  }
1853
1933
  // Same release valve as cancel-pending: an idle Main that cannot act is let out after two
1854
1934
  // empty stop attempts instead of looping forever. Live subagents do not clear this block.
1855
- const incidents = openIncidentList(cfg);
1935
+ // Findings/traces stay notes: only owner corrections (source "realtime") block the stop.
1936
+ const incidents = openIncidentList(cfg).filter(i => i.source === "realtime");
1856
1937
  if (incidents.length && state.idleStops < 2) {
1857
1938
  if (state.callsSinceStop === 0) state.idleStops++;
1858
1939
  state.callsSinceStop = 0;
@@ -1879,6 +1960,9 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
1879
1960
  log(cfg.paths.guard_log, `ALLOW stop after ${state.idleStops} idle stop attempts; open: ${open.join(" | ")}`);
1880
1961
  return { allow: true, reason: "", state: { callsSinceStop: 0, idleStops: 0 } };
1881
1962
  }
1963
+ // P5b (plan 20261031_1207): the refusal repeats on every blocked stop; name the first 10 only.
1964
+ const listed = open.slice(0, q.SUMMARY_CAP);
1965
+ const moreOpen = open.length - listed.length;
1882
1966
  log(cfg.paths.guard_log, `BLOCK stop; open: ${open.join(" | ")}`);
1883
1967
  return {
1884
1968
  allow: false,
@@ -1886,7 +1970,8 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
1886
1970
  `main-guard: the queue has ${open.length} open item${open.length === 1 ? "" : "s"} and no subagent is ` +
1887
1971
  `running to wake you. Owner rule: keep working while the queue has items. Start the next step (spawn an ` +
1888
1972
  `agent), close a finished plan with queue-close, or, if a plan truly waits on the owner, add a line ` +
1889
- `"WAITING on owner: <what>" to that plan. Open: ${open.join(" | ")}`,
1973
+ `"WAITING on owner: <what>" to that plan. Open: ${listed.join(" | ")}` +
1974
+ (moreOpen > 0 ? ` … ${moreOpen} more (queue-check lists all)` : ""),
1890
1975
  state,
1891
1976
  };
1892
1977
  }
@@ -220,7 +220,7 @@ export function planIncident(cfg: Config, id: string, planPath: string): string
220
220
  // 50 messages). Guards match quotes against them (priority skip, autonomy go); incidents dismiss
221
221
  // a finding only with them (20261028_0900 P3).
222
222
 
223
- /** The kinds plan-guard's recordFindings writes; only the owner's own words dismiss them. */
223
+ /** The finding kinds worker/Main notes used to be filed as (legacy stores keep them); only the owner's own words dismiss them. */
224
224
  const FINDING_KINDS: Record<string, true> = { "agent-finding": true, "main-finding": true };
225
225
 
226
226
  export function isFindingKind(kind: string): boolean {
@@ -154,8 +154,9 @@ export function chatApprove(text: string, cfg: Config, source: string): ChatAppr
154
154
  return { applied: true, plan: plan.file };
155
155
  }
156
156
 
157
- /** Why a spawn may not run on this plan, or null. A plan with a page in Base needs a record with its current hash. A plan stamped at or after `since` (approval.since, "" = off) needs a page too (plan 20261029_1455 P3): with no page it is refused until the page is published. A file with no stamp counts as stamped after `since`. */
157
+ /** Why a spawn may not run on this plan, or null. Approval off (`since === ""`) approves everything, page or not (plan 20261031_1207 P5: the reviewer agent replaced the hard gate). Otherwise a plan with a page in Base needs a record with its current hash, and a plan stamped at or after `since` needs a page too (plan 20261029_1455 P3): with no page it is refused until the page is published. A file with no stamp counts as stamped after `since`. */
158
158
  export function approvalProblem(text: string, file: string, pagesDir: string, since: string): string | null {
159
+ if (since === "") return null;
159
160
  const page = pageOfPlan(pagesDir, file);
160
161
  const stamp = /^\d{8}_\d{4}/.exec(basename(file))?.[0] ?? null;
161
162
  const gated = since !== "" && (stamp === null || stamp >= since);
@@ -1004,14 +1004,19 @@ export function queueProblems(index = INDEX, blockersDir = BLOCKERS_DIR, reviewA
1004
1004
  return probs;
1005
1005
  }
1006
1006
 
1007
- export function queueSummary(index = INDEX, reviewAgents: string[] = []): string {
1007
+ // P5b (plan 20261031_1207, I-20261031-330): the summary rides every Main prompt and the stop
1008
+ // refusal repeats on every blocked stop, so both cap their lists; queue-check prints everything
1009
+ // and passes `cap = Infinity`.
1010
+ export const SUMMARY_CAP = 10;
1011
+
1012
+ export function queueSummary(index = INDEX, reviewAgents: string[] = [], cap: number = SUMMARY_CAP): string {
1008
1013
  // Index order IS priority (20261025_0215_index_priority): the list is flat and ranked,
1009
1014
  // rank 1 = the index's top line; repos only surface through each plan's own path.
1010
1015
  const plans = activePlans(index);
1011
1016
  const rank = new Map(plans.map((p, i) => [p.file, i + 1] as const));
1012
1017
  const repos = [...new Set(plans.map(p => p.repo))];
1013
1018
  const lines = [`Queue (${index}): ${plans.length ? `${plans.length} plan(s) in ${repos.length} repo(s)` : "empty, no open work"}`];
1014
- plans.forEach((p, i) => {
1019
+ plans.slice(0, cap).forEach((p, i) => {
1015
1020
  const status = awaitingMerge(p) ? "complete, awaiting merge" : (p.status ?? "INVALID");
1016
1021
  const hold = p.waiting ? `WAITING on owner: ${(p.waitingLine ?? "").slice(0, 80)}` : "";
1017
1022
  // I-20261025-208: an open plan waiting on an open plan of the queue shows the target's rank.
@@ -1029,7 +1034,13 @@ export function queueSummary(index = INDEX, reviewAgents: string[] = []): string
1029
1034
  });
1030
1035
  const nCancelled = repos.reduce((n, repo) => n + readCancelled(repo).length, 0);
1031
1036
  if (nCancelled) lines.push(`Cancelled rules: ${nCancelled}`);
1037
+ const more = plans.length - Math.min(plans.length, cap);
1038
+ if (more > 0) lines.push(`… ${more} more plans (queue-check lists all)`);
1032
1039
  const probs = queueProblems(index, BLOCKERS_DIR, reviewAgents);
1033
- if (probs.length) lines.push(`Problems (fix first):`, ...probs.map(q => ` - ${q.where}: ${q.problem}`));
1040
+ const shown = new Set(plans.slice(0, cap).map(p => p.file));
1041
+ const planProbs = probs.filter(x => shown.has(x.where));
1042
+ const hidden = probs.length - planProbs.length;
1043
+ if (planProbs.length) lines.push(`Problems (fix first):`, ...planProbs.map(x => ` - ${x.where}: ${x.problem}`));
1044
+ if (hidden > 0) lines.push(`… ${hidden} more problems (queue-check)`);
1034
1045
  return lines.join("\n");
1035
1046
  }
@@ -12,7 +12,7 @@ export function queueCheck(args: string[], cfg: Config): number {
12
12
  for (const p of activePlans()) if (p.priorityId && !p.waiting && p.status === "open") console.log(p.priorityId);
13
13
  return 0;
14
14
  }
15
- console.log(queueSummary(undefined, cfg.review.agents));
15
+ console.log(queueSummary(undefined, cfg.review.agents, Infinity));
16
16
  // main-start prints the sweep itself and passes this so the child bin does not print it twice.
17
17
  let fail = queueProblems(undefined, undefined, cfg.review.agents).length > 0;
18
18
  // P4d (plan 20261028_1600): a review spawn needs a review.agents entry that Main may spawn.
@@ -15,18 +15,18 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
15
15
  - Plan order: plan → page (`neurastream pages publish <page.html> --plan <plan.md>`) → owner approves (Approve on the page, or types `approve <YYYYMMDD_HHMM>`) → reviewer PASS → implementer. Once `approval.since` is set, a plan stamped at or after it gets no spawn without a page and an approval record for its current text; a body edit voids the approval, a Progress-only edit keeps it.
16
16
  - An open plan gets an implementer subagent. When it claims done, verify (another subagent or yourself). Not done → spawn another implementer for the rest. Done → set `Status: complete`; `queue-close` then archives it and cleans the indexes.
17
17
  - Owner asks about a past plan → grep FINISHED.md first; open the archived plan only for details.
18
- - An implementer's new `## Progress` entry ends with a `Findings:` line — `Findings: none`, or one item per finding with `file:line` evidence; plan-guard restores an entry without it, and each item becomes an incident.
18
+ - An implementer's new `## Progress` entry ends with a `Findings:` line — `Findings: none`, or one item per finding with `file:line` evidence; plan-guard restores an entry without it. Findings stay notes: they never become incidents.
19
19
  - Main may push and publish once the repo's AGENTS.md test rules are met.
20
20
 
21
21
  ## Scripts (run at the stated moment)
22
22
  |Script|When|
23
23
  |---|---|
24
24
  |`main-start`|session start, after an abort, before every status report; prints the MR sweep (open forge MRs vs open plans)|
25
- |`queue-check`|after changing a plan or an index, before every spawn; exit 1 = fix first; also fails when a reachable forge lists an open MR no open plan mentions (`MR !N: ignored <reason>` in a plan marks it tracked)|
25
+ |`queue-check`|after changing a plan or an index; exit 1 = fix first; also fails when a reachable forge lists an open MR no open plan mentions (`MR !N: ignored <reason>` in a plan marks it tracked); the spawn guard re-runs the queue rules at each spawn|
26
26
  |`queue-finished`|owner asks about a past plan (`<word>` prints matching FINISHED.md entries; `--backfill` fills it from archived plans)|
27
- |`agent-ledger --cap`|before every spawn|
28
- |`agent-score`|`gate <agent>` before every spawn; `accept`/`diagnose`/`penalty` after reviewing a result; `check` after every merge; `board` after a score change|
29
- |`brief-lint <plan.md>`|before every spawn on that plan|
27
+ |`agent-ledger --cap`|the spawn guard checks the provider cap itself; run it by hand when reading spend, not before spawns|
28
+ |`agent-score`|`accept`/`diagnose`/`penalty` after reviewing a result; `check` after every merge; `board` after a score change (the spawn guard applies the prefer order itself)|
29
+ |`brief-lint <plan.md>`|when writing or reworking a plan (the spawn guard lints the named plans itself)|
30
30
  |`wip-check`|session start, before new work|
31
31
  |`neurastream metrics ci <repo> <mr>`|after every merge|
32
32
  |`neurastream metrics report`|weekly when main-start says due; propose ONE rule change to the owner|
@@ -21,7 +21,7 @@ Append one entry to the plan's `## Progress` — the PASS is recorded by plan-gu
21
21
 
22
22
  - <date> <time> <YourName>: PLAN REVIEW: PASS|FAIL — redundant: <finding or none, file:line> — inefficient: <finding or none, file:line> — insecure: <finding or none, file:line>
23
23
 
24
- ending with a `Findings:` line — `Findings: none`, or one item per finding with `file:line` evidence (a FAIL finding opens an incident like any other).
24
+ ending with a `Findings:` line — `Findings: none`, or one item per finding with `file:line` evidence (findings stay notes: they never become incidents).
25
25
 
26
26
  ## Acceptance
27
27
  - the plan's `## Progress` holds the one `PLAN REVIEW:` entry with all three fields and a `Findings:` line
@@ -36,7 +36,7 @@ Status: open
36
36
  A hold is one line: `WAITING on owner: <what to do> — blocked: <what stays stuck until then> — why you: <why Main cannot do it>` (blocked and why you may be omitted).
37
37
  Every new entry ends with a Findings line: "Findings: none", or one item per finding (bug,
38
38
  workaround, improvement — any repo) with file:line evidence, items separated by ";". Plan-guard
39
- restores an entry without it, and each item becomes an incident Main must plan or dismiss.
39
+ restores an entry without it. Findings stay notes: Main reads them, they never become incidents.
40
40
  Main reviews the work and then writes "Status: complete"; main-guard auto-runs queue-close, which
41
41
  closes the plan once the branch is on main and the done check passes (else reopens it), then removes
42
42
  the plan's worktree with a plain git worktree remove when it is clean and its branch landed — a dirty,