neurastream 0.2.56 → 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/README.md CHANGED
@@ -141,7 +141,7 @@ An answer appends one record to `<queue_state>/owner-inbox.jsonl` (plan, questio
141
141
 
142
142
  ## Static pages (`neurastream pages`)
143
143
 
144
- `neurastream pages on [--port N] [--dir D]` installs the systemd user unit and serves regular files in the configured pages directory on the tailnet; `pages publish <file> [name] [--force] [--keep]` publishes an artifact and prints its MagicDNS URL, then `expires YYYY-MM-DD` or `kept`. A page without `--keep` is deleted `pages.keep_days` days after publishing (default 15). `pages list` prints each file as `<name> expires YYYY-MM-DD` or `<name> kept`, and `pages off` stops the service. Publish, list, and serve remove expired files first; serve repeats that sweep every hour. Requests are limited to the configured owner's tailnet login or loopback; hidden files, symlinks and paths outside the directory are not served. A published HTML page carries the notes panel `pages publish` injects: `neurastream notes check <page>` exits 1 while any note on it has no answer in `<queue_state>/page-notes/<page>.answers.json`, and `pages publish` refuses that page until the file answers every id; `pages publish <html> <name> --plan <plan.md>` marks the page as a plan's diagram: it then carries an Approve bar that records `Approved: <date> (<page>)` in the plan (disabled, and refused with 409, while a note on the page has no answer), and `neurastream diagram check <html> <plan.md>` requires that page to show every phase of the plan and every file or command its phase lines name, with 2+ kids behind every drilldown — `pages publish --plan` runs it, and Approve stays disabled (the server answers 409) until it passes. main-guard refuses a spawn on a plan that has such a page and no approval line — a chat "go" is recorded as the same line, and `Approval: self — owner: "<his words>"` covers a plan he hands to Main. the publish that goes through prints each answer beside its note, archives the closed notes and never reuses an id.
144
+ `neurastream pages on [--port N] [--dir D]` installs the systemd user unit and serves regular files in the configured pages directory on the tailnet; `pages publish <file> [name] [--force] [--keep]` publishes an artifact and prints its MagicDNS URL, then `expires YYYY-MM-DD` or `kept`. A page without `--keep` is deleted `pages.keep_days` days after publishing (default 15). `pages list` prints each file as `<name> expires YYYY-MM-DD` or `<name> kept`, and `pages off` stops the service. Publish, list, and serve remove expired files first; serve repeats that sweep every hour. Requests are limited to the configured owner's tailnet login or loopback; hidden files, symlinks and paths outside the directory are not served. A published HTML page carries the notes panel `pages publish` injects: `neurastream notes check <page>` exits 1 while any note on it has no answer in `<queue_state>/page-notes/<page>.answers.json`, and `pages publish` refuses that page until the file answers every id; `pages publish <html> <name> --plan <plan.md>` marks the page as a plan's diagram: it then carries an Approve bar that records the plan's text hash in `<queue_state>/plan-approvals.json` and never edits the plan (disabled, and refused with 409, while a note on the page has no answer), and `neurastream diagram check <html> <plan.md>` requires that page to show every phase of the plan and every file or command its phase lines name, with 2+ kids behind every drilldown — `pages publish --plan` runs it, and Approve stays disabled (the server answers 409) until it passes. main-guard refuses a spawn on a plan that has such a page and no approval record whose hash matches the plan's current text. The publish that goes through prints each answer beside its note, archives the closed notes and never reuses an id.
145
145
 
146
146
  ## Base tab (`/?tab=knowledge`)
147
147
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.56",
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",
@@ -21,6 +21,7 @@ import { basename, dirname, extname, join, resolve } from "node:path";
21
21
  import type { Decision } from "../../core/adapter.ts";
22
22
  import { AGENTS_TEMPLATE, renderBlock } from "../../core/agents-md.ts";
23
23
  import { chatGo, chatTier, type Tier } from "../../core/autonomy.ts";
24
+ import { chatApprove } from "../../core/plan-approval.ts";
24
25
  import { burdenRule, repoRules, rulesChanged } from "../../core/repo-rules.ts";
25
26
  import { configFile, loadConfig, reloadingConfig, type Config } from "../../core/config.ts";
26
27
  import { checkWrite, deferSteer, type WriteCheckConfig } from "../../core/write-check.ts";
@@ -1461,6 +1462,15 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1461
1462
  notifyGo(ctx, g);
1462
1463
  return { handled: true };
1463
1464
  }
1465
+ const a = chatApprove(text, cfg, "interactive");
1466
+ if (a.applied) {
1467
+ asRolloverCtx(ctx)?.notify(`approved ${basename(a.plan)}`);
1468
+ return { handled: true };
1469
+ }
1470
+ if (a.problem !== undefined) {
1471
+ asRolloverCtx(ctx)?.notify(a.problem);
1472
+ return { handled: true };
1473
+ }
1464
1474
  const r = q.chatUnlock(asString(e.text), cfg, "interactive");
1465
1475
  if (!r.applied) return undefined;
1466
1476
  notifyUnlock(ctx, r);
@@ -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] ?? "";
@@ -172,6 +172,8 @@ export interface Config {
172
172
  /** Minutes the spawn gate caches a repo's open-MR list in <queue_state>/mr-cache.json; 0 = no cache. */
173
173
  mr_cache_minutes: number;
174
174
  };
175
+ /** Plan approval hard gate (plan 20261029_1455 P3): a plan stamped at or after `since` needs a page and an approval record. "" = off. */
176
+ approval: { since: string };
175
177
  /** Static pages hosted over the tailnet. */
176
178
  pages: { enabled: boolean; port: number; dir: string; keep_days: number };
177
179
  /** Repo-local HTML explainers under docs/knowledge/ (owner page Knowledge tab). */
@@ -523,6 +525,8 @@ function check(cfg: Config): void {
523
525
  throw new ConfigError('review.agents must be a list of agent names allowed to run review spawns (default ["reviewer"])');
524
526
  if (!Number.isInteger(cfg.review.mr_cache_minutes) || cfg.review.mr_cache_minutes < 0)
525
527
  throw new ConfigError("review.mr_cache_minutes must be an integer >= 0 (minutes the spawn gate caches a repo's open-MR list; 0 = no cache)");
528
+ if (typeof cfg.approval.since !== "string" || (cfg.approval.since !== "" && !/^\d{8}_\d{4}$/.test(cfg.approval.since)))
529
+ throw new ConfigError('approval.since must be "" or a plan stamp YYYYMMDD_HHMM (plans stamped at or after it need a page and an approval record)');
526
530
  if (cfg.autonomy.tier !== "strict" && cfg.autonomy.tier !== "opinionated" && cfg.autonomy.tier !== "full")
527
531
  throw new ConfigError('autonomy.tier must be "strict", "opinionated" or "full"');
528
532
  if (!Number.isInteger(cfg.autonomy.strict_edit_limit) || cfg.autonomy.strict_edit_limit < 1)
@@ -23,12 +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
- import { approvalProblem } from "./plan-approval.ts";
30
+ import { approvalProblem, MAIN_ONLY_LINE, reviewHash } from "./plan-approval.ts";
31
+ export { reviewHash };
30
32
  import type { Config } from "./config.ts";
31
- 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";
32
34
  import { notifyProtectedPaths, notifySecretReadHit } from "./notify.ts";
33
35
  import { defaultRunner, listOpenMrs, mentioned, type CommandRunner, type OpenMr } from "./mr-sweep.ts";
34
36
  import { unlandedRows } from "./wip-check.ts";
@@ -37,6 +39,7 @@ import type { Plan } from "./queue/lib.ts";
37
39
 
38
40
  import { nowSec } from "./clock.ts";
39
41
  import { outUntil, pinModel, providerOfModel, readOut } from "./provider-state.ts";
42
+ import { lint } from "./brief-lint.ts";
40
43
  const ALLOW: Decision = { allow: true, reason: "" };
41
44
 
42
45
  /**
@@ -167,18 +170,6 @@ function writePlanReviews(reviews: Record<string, PlanReview>, cfg: Config): voi
167
170
  }
168
171
  }
169
172
 
170
- /** What a PASS covers: the plan text outside "## Progress" without the Main-only lines, so progress notes never expire a review. */
171
- export function reviewHash(text: string): string {
172
- return q.sha(
173
- q
174
- .outsideProgress(text)
175
- .split("\n")
176
- .filter(l => !MAIN_ONLY_LINE.test(l))
177
- .map(l => l.replace(/^(\s*[-*]\s+)\[[xX]\]/, "$1[ ]")) // a ticked phase box hashes as unticked: ticking never expires a PASS
178
- .join("\n"),
179
- );
180
- }
181
-
182
173
  /** The progress entry that records a review; only a subagent's edit can carry one. The verdict is the match, never a substring. */
183
174
  const REVIEW_LINE = /^- (?:\d{4}-\d{2}-\d{2} \d{2}:\d{2} [^\s:]+: )?PLAN REVIEW: (PASS|FAIL)\b/;
184
175
  /** Any entry that opens like a review line; one that REVIEW_LINE does not match is restored, not recorded. */
@@ -315,13 +306,14 @@ function matchReviewSpawn(spawns: Record<string, ReviewSpawn>, agentId: string):
315
306
  return null;
316
307
  }
317
308
 
318
- /** 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. */
319
310
  function secretPath(p: string, cfg: Config, cwd: string): boolean {
320
- const home = cfg.paths.home;
321
- 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);
322
312
  const base = path.basename(abs);
323
- const inCredDir = [".config", ".ssh", ".gnupg", ".aws"].some(d => abs.startsWith(path.join(home, d) + path.sep));
324
- 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
+ );
325
317
  }
326
318
 
327
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. */
@@ -338,6 +330,15 @@ function reviewLockProblem(e: ToolEvent, cfg: Config): string | null {
338
330
  const reads = [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)];
339
331
  return reads.some(p => secretPath(p, cfg, e.cwd)) ? `review spawn ${e.agentId} may not read credentials or env files.` : null;
340
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
+ }
341
342
  return `review spawn ${e.agentId} may only read, use todo, and edit its plan; ${e.tool} is denied.`;
342
343
  }
343
344
 
@@ -352,8 +353,13 @@ function staffingFile(): string {
352
353
  // The owner-message store (owner-messages.jsonl) and its matcher live in src/core/incidents.ts
353
354
  // (20261028_0900 P3): dismissIncident needs them too, and guards already imports incidents.
354
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
+
355
361
  function recordOwnerMessage(text: string, cfg: Config): void {
356
- if (text.trimStart().startsWith("main-guard:") || text.trimStart().startsWith("<system-notice>") || text.includes("<task-result")) return;
362
+ if (!isOwnerProse(text)) return;
357
363
  const file = ownerMessagesFile();
358
364
  try {
359
365
  mkdirSync(q.STATE_DIR, { recursive: true });
@@ -560,6 +566,12 @@ function unticked(p: Plan): string[] {
560
566
  return [...phases.matchAll(/^\s*[-*]\s+\[ \]\s+(P\d+[a-z]?)\b/gm)].map(m => m[1]!);
561
567
  }
562
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
+
563
575
  // Plans an implementer brief may run on; returns [reason, null] or [null, plan files].
564
576
  export function planGate(text: string, label: string, cfg?: Config): [string | null, string[]] {
565
577
  const plans = q.activePlans(undefined, undefined, cfg?.review.agents ?? []);
@@ -569,10 +581,7 @@ export function planGate(text: string, label: string, cfg?: Config): [string | n
569
581
  `${label}: ${unclosed.map(p => `${p.file} (${p.status})`).join(", ")} is still indexed. Verify it and run \`queue-close <plan>\` before any new spawn.`,
570
582
  [],
571
583
  ];
572
- // A `Priority skip: <path> — <why>` line names a plan it does NOT run on (20261025_0215 P3);
573
- // only the remaining text decides which plans this brief targets.
574
- const body = text.replace(/^\s*(?:[-*]\s+)?priority skip:.*$/gim, "");
575
- const named = plans.filter(p => body.includes(p.file));
584
+ const named = briefPlans(text, cfg);
576
585
  if (!named.length)
577
586
  return [
578
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}.`,
@@ -597,7 +606,7 @@ export function planGate(text: string, label: string, cfg?: Config): [string | n
597
606
  [],
598
607
  ];
599
608
  if (cfg) {
600
- const approval = approvalProblem(p.text, p.file, cfg.pages.dir);
609
+ const approval = approvalProblem(p.text, p.file, cfg.pages.dir, cfg.approval.since);
601
610
  if (approval) return [approval, []];
602
611
  }
603
612
  const open = unticked(p);
@@ -780,6 +789,37 @@ export function preferProblem(agent: string, brief: string, runningJobs: readonl
780
789
  return null;
781
790
  }
782
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
+
783
823
  /**
784
824
  * Who is rate-limited comes from live data (plan 20261025_1700 P1): refuse a brief that asserts a
785
825
  * provider shown free by providerStatus is rate-limited — named directly or through a prefer
@@ -805,7 +845,7 @@ export function providerClaimProblem(text: string, cfg: Config): string | null {
805
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.`;
806
846
  }
807
847
 
808
- /** 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). */
809
849
  export function spawnProblem(
810
850
  input: Record<string, unknown>,
811
851
  cfg: Config,
@@ -821,30 +861,43 @@ export function spawnProblem(
821
861
  const context = String(input?.context ?? "");
822
862
  const allowed = q.allowedAgents();
823
863
  const shared = briefBudget(context);
864
+ const problems: string[] = [];
824
865
  const named: Record<string, number | null> = {};
825
866
  for (const t of tasks) {
826
867
  const agent = String(t?.agent ?? "task");
827
868
  const label = String(t?.name ?? agent);
828
- if (!allowed.has(agent)) return `${label}: agent "${agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`;
829
- const [why, plans] = planGate(`${context}\n${String(t?.task ?? "")}`, label, cfg);
830
- 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
+ }
831
879
  // P3 (plan 20261028_1600): the task tool is the live spawn path; every task carries its own
832
- // pending-work check, before the call-wide gates below.
833
- const pending = pendingWorkProblem(plans, `${context}\n${String(t?.task ?? "")}`, cfg, runner);
834
- if (pending) return `${label}: ${pending}`;
835
- // The task's own `Call budget:` line wins over the shared context's.
836
- const role = reviewRole(t?.name, plans, `${context}\n${String(t?.task ?? "")}`, String(t?.agent ?? ""), cfg, spawner);
837
- if (role.problem) return `${label}: ${role.problem}`;
838
- if (t?.name) roles[label] = role.plan;
839
- const review = reviewPassProblem(plans, `${context}\n${String(t?.task ?? "")}`, String(t?.agent ?? ""), cfg, spawner);
840
- 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
+ ];
841
888
  const budget = briefBudget(String(t?.task ?? "")) ?? shared;
842
889
  if (budget !== null) {
843
- if (!t?.name) return `${label}: "Call budget: ${budget}" needs a task name (the budget is keyed by it).`;
844
- if (budget < 10 || budget > cfg.guards.sub_max_calls_cap)
845
- 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;
846
898
  }
847
899
  if (t?.name) {
900
+ roles[label] = role.plan;
848
901
  named[label] = budget;
849
902
  for (const f of plans) staffing[f] = [...(staffing[f] ?? []), label];
850
903
  }
@@ -853,22 +906,33 @@ export function spawnProblem(
853
906
  Object.assign(budgets, named);
854
907
  // Who is limited and who goes first come from live data and ledger.prefer (plan 20261025_1700
855
908
  // P3): the same rules checkSpawn applies to single-spawn events, per task.
856
- const claim = providerClaimProblem(`${context}\n${tasks.map(t => String(t?.task ?? "")).join("\n")}`, cfg);
857
- 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);
858
912
  for (const t of tasks) {
859
913
  const pick = preferProblem(String(t?.agent ?? "task"), `${context}\n${String(t?.task ?? "")}`, runningJobs, cfg);
860
- if (pick) return `${String(t?.name ?? t?.agent ?? "task")}: ${pick}`;
914
+ if (pick) problems.push(`${String(t?.name ?? t?.agent ?? "task")}: ${pick}`);
861
915
  }
862
916
  // Priority gate (20261025_0215 P3): once per `task` call, over the plans this call names; the
863
917
  // skip lines may sit in the shared context or any task text.
864
918
  const gate = priorityGate(
865
919
  files,
866
920
  runningJobs,
867
- `${context}\n${tasks.map(t => String(t?.task ?? "")).join("\n")}`,
921
+ joined,
868
922
  cfg,
869
923
  String((tasks[0] && (tasks[0].name ?? tasks[0].agent)) ?? "task"),
870
924
  );
871
- 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;
872
936
  for (const [name, plan] of Object.entries(roles)) recordReviewSpawn(name, plan);
873
937
  return null;
874
938
  }
@@ -888,10 +952,15 @@ function runBlockers(plan: Plan, hit: string[], e: ToolEvent, cfg: Config): stri
888
952
  stdio: ["pipe", "pipe", "pipe"],
889
953
  });
890
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() : "";
891
959
  const stderr = typeof err === "object" && err !== null && "stderr" in err && typeof err.stderr === "string" ? err.stderr.trim() : "";
892
960
  const message = err instanceof Error ? err.message : String(err);
893
- const why = stderr || `${path.basename(b.script)} failed (${message})`;
894
- 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}`;
895
964
  }
896
965
  }
897
966
  return null;
@@ -953,6 +1022,19 @@ function landingCommand(input: Record<string, unknown>): boolean {
953
1022
  });
954
1023
  }
955
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
+
956
1038
  // The read tool's stand-in for a value it hid. A file may hold one only where it is produced
957
1039
  // (secret-redact.ts) or exercised (its tests).
958
1040
  const PLACEHOLDER = "[REDACTED:";
@@ -1002,8 +1084,14 @@ function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[],
1002
1084
  const hit = paths.filter(p => !q.isOrchestrationPath(p, plans) && q.planCovers(plan, p, plans));
1003
1085
  if (!hit.length) continue;
1004
1086
  if (plan.errors.length) return `plan ${plan.file} is invalid (${plan.errors.join("; ")}). Stop and report to Main.`;
1005
- const why = runBlockers(plan, hit, e, cfg);
1006
- 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
+ }
1007
1095
  }
1008
1096
  return null;
1009
1097
  }
@@ -1065,12 +1153,13 @@ export function incidentLine(i: IncidentView): string {
1065
1153
  }
1066
1154
 
1067
1155
  /**
1068
- * While an incident is open, a launch must be fix work: its brief (or a plan the brief names)
1069
- * cites `INCIDENT <id>` of an open incident. Anything else is refused until every open incident
1070
- * 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.
1071
1160
  */
1072
1161
  function incidentSpawnProblem(label: string, brief: string, namedPlans: string[], cfg: Config): string | null {
1073
- const open = openIncidentList(cfg);
1162
+ const open = openIncidentList(cfg).filter(i => i.source === "realtime");
1074
1163
  if (!open.length) return null;
1075
1164
  const texts = [brief];
1076
1165
  for (const f of namedPlans) {
@@ -1099,6 +1188,8 @@ function taskLaunch(input: Record<string, unknown>, cfg: Config, runningJobs: st
1099
1188
  log(cfg.paths.guard_log, `BLOCK spawn: cancel pending (${pending.words})`);
1100
1189
  return `${CANCEL_TODO} Flagged: "${pending.words}"`;
1101
1190
  }
1191
+ // P4 (plan 20261031_1207): spawnProblem's verdict now carries the incident check too, so one
1192
+ // deny lists every problem.
1102
1193
  const files: string[] = [];
1103
1194
  const budgets: Record<string, number | null> = {};
1104
1195
  const staffing: Record<string, string[]> = {};
@@ -1107,8 +1198,6 @@ function taskLaunch(input: Record<string, unknown>, cfg: Config, runningJobs: st
1107
1198
  log(cfg.paths.guard_log, `BLOCK spawn: ${why}`);
1108
1199
  return why;
1109
1200
  }
1110
- const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
1111
- if (inc) return inc;
1112
1201
  recordSpawns(files, staffing);
1113
1202
  recordBudgets(budgets);
1114
1203
  return null;
@@ -1424,44 +1513,34 @@ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = d
1424
1513
  return deny(`main-guard: ${e.agent}: agent "${e.agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`);
1425
1514
  if (e.invocationKind !== "task")
1426
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[] = [];
1427
1519
  const [why, named] = planGate(e.brief, e.agent, cfg);
1428
- if (why) {
1429
- log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${why}`);
1430
- return deny(`main-guard: ${why}`);
1431
- }
1520
+ if (why) problems.push(why);
1432
1521
  const gate = priorityGate(named, e.runningJobs, e.brief, cfg, e.agent);
1433
- if (gate) {
1434
- log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${gate}`);
1435
- return deny(`main-guard: ${gate}`);
1436
- }
1522
+ if (gate) problems.push(gate);
1437
1523
  const pendingWork = pendingWorkProblem(named, e.brief, cfg, runner);
1438
- if (pendingWork) {
1439
- log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${pendingWork}`)
1440
- return deny(`main-guard: ${pendingWork}`)
1441
- }
1524
+ if (pendingWork) problems.push(pendingWork);
1442
1525
  const role = reviewRole(e.name, named, e.brief, e.agent, cfg, "main");
1443
- if (role.problem) {
1444
- log(cfg.paths.plan_guard_log, `BLOCK ${e.agent} ${e.name ?? "(unnamed)"} review spawn: ${role.problem}`);
1445
- return deny(`main-guard: ${role.problem}`);
1446
- }
1526
+ if (role.problem) problems.push(role.problem);
1447
1527
  const review = reviewPassProblem(named, e.brief, e.agent, cfg, "main");
1448
- if (review) {
1449
- log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${review}`);
1450
- return deny(`main-guard: ${review}`);
1451
- }
1528
+ if (review) problems.push(review);
1452
1529
  const inc = incidentSpawnProblem(`spawn ${e.agent}`, e.brief, named, cfg);
1453
- if (inc) return deny(`main-guard: ${inc}`);
1454
- // The owner's pick order and live provider state (plan 20261025_1700 P3), before the spawn records.
1530
+ if (inc) problems.push(inc);
1455
1531
  const claim = providerClaimProblem(e.brief, cfg);
1456
- if (claim) {
1457
- log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${claim}`);
1458
- return deny(`main-guard: ${e.agent}: ${claim}`);
1459
- }
1532
+ if (claim) problems.push(`${e.agent}: ${claim}`);
1460
1533
  const pick = preferProblem(e.agent, e.brief, e.runningJobs, cfg);
1461
- if (pick) {
1462
- log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${pick}`);
1463
- 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}`);
1464
1542
  }
1543
+ // The owner's pick order and live provider state (plan 20261025_1700 P3), before the spawn records.
1465
1544
  const staffing: Record<string, string[]> = {};
1466
1545
  for (const f of named) staffing[f] = [e.agent];
1467
1546
  recordSpawns(named, staffing);
@@ -1507,7 +1586,11 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
1507
1586
  } catch (err) {
1508
1587
  summary = `Queue unreadable (${q.INDEX}): ${err}`;
1509
1588
  }
1510
- 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);
1511
1594
  const incidents = openIncidentList(cfg);
1512
1595
  const incidentText = incidents.length ? `\n${incidents.map(incidentLine).join("\n")}` : "";
1513
1596
  // 20261025_1940 P2: the injected line names the autonomy tier and what Main does without asking in it.
@@ -1527,9 +1610,6 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
1527
1610
  };
1528
1611
  }
1529
1612
 
1530
- // Lines only Main may write: the status, owner parking, plan waits, owner cancellation, cancelled-list clearance.
1531
- const MAIN_ONLY_LINE = /^\s*(?:[-*]\s+)?(Status:|WAITING on owner:|Waits on:|Cancelled by owner:|False positive:)/;
1532
-
1533
1613
  function mainOnlyLines(text: string): string {
1534
1614
  return text.split("\n").filter(l => MAIN_ONLY_LINE.test(l)).join("\n");
1535
1615
  }
@@ -1573,33 +1653,10 @@ export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1573
1653
  log(cfg.paths.plan_guard_log, `RESTORE ${e.path} review line from a spawn that is not its named review spawn`);
1574
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 } };
1575
1655
  }
1576
- recordFindings(e, cfg);
1577
1656
  recordReviews(e, cfg);
1578
1657
  return ALLOW;
1579
1658
  }
1580
1659
 
1581
- /**
1582
- * Each finding item of an allowed plan edit becomes an incident (source "findings", evidence =
1583
- * plan path + agent; the default fingerprint dedupes the same item text). A subagent's items are
1584
- * kind "agent-finding"; Main's own are kind "main-finding" (20261028_0900 P1: a bug Main writes
1585
- * down must block the stop like a subagent's). A store failure is logged and swallowed: it must
1586
- * not break the verified edit.
1587
- */
1588
- function recordFindings(e: PlanEditEvent, cfg: Config, kind: "agent-finding" | "main-finding" = "agent-finding"): void {
1589
- try {
1590
- const evidence = `${e.path} (${e.agent})`;
1591
- for (const block of newProgressEntries(e.before, e.after)) {
1592
- const value = findingsValue(block);
1593
- if (!value || /^none\.?$/i.test(value)) continue;
1594
- for (const item of value.split(";")) {
1595
- if (item.trim()) addIncident(cfg, { source: "findings", kind, summary: item.trim(), evidence });
1596
- }
1597
- }
1598
- } catch (err) {
1599
- log(cfg.paths.plan_guard_log, `findings: cannot record incidents for ${e.path}: ${err}`);
1600
- }
1601
- }
1602
-
1603
1660
  /** One "## Progress" entry: its "- " line plus indented continuation lines (trimProgressBody's entry rule). */
1604
1661
  function progressEntries(text: string): string[] {
1605
1662
  const blocks: string[] = [];
@@ -1646,7 +1703,6 @@ function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1646
1703
  };
1647
1704
  }
1648
1705
  if (q.outsideProgress(e.after) === q.outsideProgress(e.before)) {
1649
- recordFindings(e, cfg, "main-finding");
1650
1706
  return ALLOW;
1651
1707
  }
1652
1708
  // A cited file Main did read lands in the list instead of the refusal (I-20261025-208): fix the
@@ -1658,7 +1714,6 @@ function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1658
1714
  const known = new Set(e.before ? planReadProblems(e.before, e.path, cfg) : []);
1659
1715
  const problems = planReadProblems(fixed, e.path, cfg).filter(p => p === NO_SECTION || !known.has(p));
1660
1716
  if (!problems.length) {
1661
- recordFindings(e, cfg, "main-finding");
1662
1717
  if (!fix) return ALLOW;
1663
1718
  const list = fix.paths.join(", ");
1664
1719
  log(cfg.paths.plan_guard_log, `AUTO-LIST ${e.path}: ${list}`);
@@ -1837,8 +1892,9 @@ export const STOP_PLAN_OFFER_REFUSAL = "main-guard: don't promise it — do it n
1837
1892
 
1838
1893
  /**
1839
1894
  * stop: Main may not stop while an open plan is not parked "WAITING on owner" (or the queue has a
1840
- * problem) and no subagent is alive to wake it; an open incident (no plan, no dismissal) blocks
1841
- * 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
1842
1898
  * in between are let through. Returns the next counters in `state`.
1843
1899
  */
1844
1900
  export function checkStop(e: StopEvent, cfg: Config): Decision {
@@ -1850,6 +1906,16 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
1850
1906
  log(cfg.paths.guard_log, "BLOCK stop: reply offers or promises instead of doing it");
1851
1907
  return { allow: false, reason: STOP_PLAN_OFFER_REFUSAL, state };
1852
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
+ }
1853
1919
  let open: string[];
1854
1920
  try {
1855
1921
  open = openQueue(cfg.review.agents);
@@ -1866,7 +1932,8 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
1866
1932
  }
1867
1933
  // Same release valve as cancel-pending: an idle Main that cannot act is let out after two
1868
1934
  // empty stop attempts instead of looping forever. Live subagents do not clear this block.
1869
- 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");
1870
1937
  if (incidents.length && state.idleStops < 2) {
1871
1938
  if (state.callsSinceStop === 0) state.idleStops++;
1872
1939
  state.callsSinceStop = 0;
@@ -1893,6 +1960,9 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
1893
1960
  log(cfg.paths.guard_log, `ALLOW stop after ${state.idleStops} idle stop attempts; open: ${open.join(" | ")}`);
1894
1961
  return { allow: true, reason: "", state: { callsSinceStop: 0, idleStops: 0 } };
1895
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;
1896
1966
  log(cfg.paths.guard_log, `BLOCK stop; open: ${open.join(" | ")}`);
1897
1967
  return {
1898
1968
  allow: false,
@@ -1900,7 +1970,8 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
1900
1970
  `main-guard: the queue has ${open.length} open item${open.length === 1 ? "" : "s"} and no subagent is ` +
1901
1971
  `running to wake you. Owner rule: keep working while the queue has items. Start the next step (spawn an ` +
1902
1972
  `agent), close a finished plan with queue-close, or, if a plan truly waits on the owner, add a line ` +
1903
- `"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)` : ""),
1904
1975
  state,
1905
1976
  };
1906
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 {
@@ -122,7 +122,7 @@ function approveBlock(chrome: ApproveChrome): string {
122
122
  <script>(function(){var page="${page}",btn=document.getElementById("ns-approve-btn"),status=document.getElementById("ns-approve-status");
123
123
  function set(open,problems){var bad=(problems||[]);btn.disabled=open.length>0||bad.length>0;status.textContent=open.length>0?"Answer every note first ("+open.join(", ")+")":bad.length>0?"The diagram is not complete yet ("+bad.length+"): "+bad.slice(0,3).join("; "):"Approve and go \u2014 the plan records it.";}
124
124
  fetch("/_approve?page="+page).then(function(r){return r.json();}).then(function(d){set(d.open||[],d.problems);}).catch(function(){set(["?"],[]);});
125
- btn.addEventListener("click",function(){btn.disabled=true;fetch("/_approve?page="+page,{method:"POST",headers:{"content-type":"application/json"},body:"{}"}).then(function(r){return r.json().then(function(d){return {ok:r.ok,body:d};});}).then(function(res){status.textContent=res.ok?"Approved: "+res.body.approved:"Not approved: "+res.body.error;btn.disabled=!res.ok;}).catch(function(){status.textContent="Not approved: the pages server did not answer.";btn.disabled=false;});});
125
+ btn.addEventListener("click",function(){btn.disabled=true;fetch("/_approve?page="+page,{method:"POST",headers:{"content-type":"application/json"},body:"{}"}).then(function(r){return r.json().then(function(d){return {ok:r.ok,body:d};});}).then(function(res){status.textContent=res.ok?res.body.approved:"Not approved: "+res.body.error;btn.disabled=!res.ok;}).catch(function(){status.textContent="Not approved: the pages server did not answer.";btn.disabled=false;});});
126
126
  })();</script>
127
127
  </section>`;
128
128
  }
package/src/core/pages.ts CHANGED
@@ -27,9 +27,9 @@ export function startPagesServer(opts: PagesOptions): PagesServer {
27
27
  // rows Main delivers. Same origin only, so another site's tab cannot write to the inbox; nothing here
28
28
  // touches the page file, and a submit with no note text is refused.
29
29
  if (req.method === "POST") {
30
- // Approve from the plan's own page (plan 20261026 P9): the click records `Approved: <date> (<page>)`
31
- // in the plan recorded at publish. Only that plan, only from this page's origin, and never while a
32
- // note on the page has no answer.
30
+ // Approve from the plan's own page (plan 20261026 P9): the click records a hash of the plan text
31
+ // in the queue state (plan-approvals.json). Only that plan, only from this page's origin, and
32
+ // never while a note on the page has no answer.
33
33
  if (url.pathname === "/_approve") {
34
34
  if (req.headers.get("origin") !== `http://${req.headers.get("host")}`) return plain("forbidden: origin is not this page", 403);
35
35
  const page = url.searchParams.get("page") ?? "";
@@ -41,7 +41,11 @@ export function startPagesServer(opts: PagesOptions): PagesServer {
41
41
  if (unproven.length > 0) return Response.json({ error: `the diagram is not complete (${unproven.slice(0, 3).join("; ")})` }, { status: 409 });
42
42
  const plan = record.plan;
43
43
  if (!existsSync(plan)) return plain("not found: the plan file is gone", 404);
44
- return Response.json({ approved: approvePlanFile(plan, page) });
44
+ try {
45
+ return Response.json({ approved: approvePlanFile(plan, page) });
46
+ } catch (e) {
47
+ return plain(`not approved: ${e instanceof Error ? e.message : String(e)}`, 500);
48
+ }
45
49
  }
46
50
  if (url.pathname !== "/_notes") return plain("method not allowed", 405);
47
51
  if (req.headers.get("origin") !== `http://${req.headers.get("host")}`) return plain("forbidden: origin is not this page", 403);
@@ -1,13 +1,26 @@
1
1
  // Plan approval from the plan's own diagram page (plan 20261026_0930 P9). A plan that has a page in
2
- // Base is approved there — the Approve bar records `Approved: <date> (<page>)` in the plan — and a
3
- // chat "go" is the same thing: Main writes the same line. `Approval: self — owner: "<his words>"`
4
- // covers the plans he tells Main to do on its own. main-guard refuses a spawn on a plan that has a
5
- // page and no line; a plan with no page predates the convention and is left alone.
6
- import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
7
- import { join, resolve } from "node:path";
2
+ // Base is approved there: the Approve bar records a hash of the plan text in the queue state
3
+ // (plan-approvals.json). The plan file is never edited. main-guard refuses a spawn on a plan whose page
4
+ // has no record with the plan's current hash; a plan with no page predates the convention and is left alone, unless it is stamped at or after approval.since (plan 20261029_1455 P3), when it is refused until its page is published.
5
+ import { appendFileSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
6
+ import { basename, join, resolve } from "node:path";
7
+ import * as q from "./queue/lib.ts";
8
+ import type { Config } from "./config.ts";
8
9
 
9
- const APPROVED = /^\s*(?:[-*]\s+)?Approved:.*$/im;
10
- const SELF = /^\s*(?:[-*]\s+)?Approval:\s*self\b[^\n]*owner:\s*["\u201c][^"\u201d\n]+["\u201d]/im;
10
+ /** Lines only Main may write: the status, owner parking, plan waits, owner cancellation, cancelled-list clearance. */
11
+ export const MAIN_ONLY_LINE = /^\s*(?:[-*]\s+)?(Status:|WAITING on owner:|Waits on:|Cancelled by owner:|False positive:)/;
12
+
13
+ /** What a PASS covers: the plan text outside "## Progress" without the Main-only lines, so progress notes never expire a review. */
14
+ export function reviewHash(text: string): string {
15
+ return q.sha(
16
+ q
17
+ .outsideProgress(text)
18
+ .split("\n")
19
+ .filter(l => !MAIN_ONLY_LINE.test(l))
20
+ .map(l => l.replace(/^(\s*[-*]\s+)\[[xX]\]/, "$1[ ]")) // a ticked phase box hashes as unticked: ticking never expires a PASS
21
+ .join("\n"),
22
+ );
23
+ }
11
24
 
12
25
  /** What publishing recorded for a page: the plan it approves and what its diagram check found. */
13
26
  export interface PagePlan {
@@ -60,36 +73,99 @@ export function pageOfPlan(dir: string, file: string): string | null {
60
73
  return null;
61
74
  }
62
75
 
63
- export function isApproved(text: string): boolean {
64
- return APPROVED.test(text) || SELF.test(text);
76
+ // --- Plan approval records (plan 20261026_0930 P9): a hash in the queue state, not a line in the plan ---
77
+
78
+ /** One approval: the plan text it covers, when it was recorded, and how. */
79
+ export interface PlanApproval {
80
+ hash: string;
81
+ at: number;
82
+ via: "page" | "chat";
83
+ page: string;
84
+ }
85
+
86
+ function planApprovalsFile(): string {
87
+ return join(q.STATE_DIR, "plan-approvals.json");
65
88
  }
66
89
 
67
- export function isSelfApproved(text: string): boolean {
68
- return SELF.test(text);
90
+ function readPlanApprovals(): Record<string, PlanApproval> {
91
+ try {
92
+ const parsed = JSON.parse(readFileSync(planApprovalsFile(), "utf8"));
93
+ if (parsed?.approvals && typeof parsed.approvals === "object") return parsed.approvals as Record<string, PlanApproval>;
94
+ } catch {
95
+ }
96
+ return {};
97
+ }
98
+
99
+ function writePlanApprovals(approvals: Record<string, PlanApproval>): boolean {
100
+ try {
101
+ mkdirSync(q.STATE_DIR, { recursive: true });
102
+ writeFileSync(planApprovalsFile(), JSON.stringify({ approvals }, null, 1));
103
+ return true;
104
+ } catch {
105
+ return false;
106
+ }
69
107
  }
70
108
 
71
- export function approvalLine(page: string, now = new Date()): string {
72
- return `Approved: ${now.toISOString().slice(0, 10)} (${page})`;
109
+ function readPlanApproval(file: string): PlanApproval | null {
110
+ return readPlanApprovals()[file] ?? null;
73
111
  }
74
112
 
75
- /** The plan text with its approval line replaced, or added above the first `## ` section. */
76
- export function recordApproval(text: string, page: string, now = new Date()): string {
77
- const line = approvalLine(page, now);
78
- if (APPROVED.test(text)) return text.replace(APPROVED, line);
79
- const at = text.search(/^## /m);
80
- return at < 0 ? `${text.replace(/\s*$/, "")}\n${line}\n` : `${text.slice(0, at)}${line}\n\n${text.slice(at)}`;
113
+ /** Record one approval. Throws when the queue state cannot be written, so nobody reports "approved" for a record that is not there. */
114
+ function recordApproval(file: string, approval: PlanApproval): void {
115
+ const approvals = readPlanApprovals();
116
+ approvals[file] = approval;
117
+ if (!writePlanApprovals(approvals)) throw new Error(`cannot write ${planApprovalsFile()}`);
81
118
  }
82
119
 
83
- /** Write the owner's click into the plan and return the line it recorded. */
120
+ /** The owner's click on a plan page: record a hash of the plan text in the queue state and return the page it approved. The plan file itself is never edited. */
84
121
  export function approvePlanFile(file: string, page: string, now = new Date()): string {
85
- writeFileSync(file, recordApproval(readFileSync(file, "utf8"), page, now));
86
- return approvalLine(page, now);
122
+ const text = readFileSync(file, "utf8");
123
+ recordApproval(file, { hash: reviewHash(text), at: now.getTime(), via: "page", page });
124
+ return `approved ${page}`;
87
125
  }
88
126
 
89
- /** Why a spawn may not run on this plan, or null; only a plan with a page in Base is gated. */
90
- export function approvalProblem(text: string, file: string, pagesDir: string): string | null {
91
- if (isApproved(text)) return null;
92
- const page = pageOfPlan(pagesDir, file);
93
- if (page === null) return null;
94
- return `plan ${file} has no "Approved:" line. The owner approves it from ${page} in Base, or the plan says Approval: self \u2014 owner: "<his words>".`;
127
+ export type ChatApproveResult = { applied: true; plan: string } | { applied: false; problem?: string };
128
+
129
+ const APPROVE_CMD = /^approve (\d{8}_\d{4})$/;
130
+
131
+ /**
132
+ * The owner's own chat `approve <YYYYMMDD_HHMM>` (same trust rules as chatGo): the one open indexed
133
+ * plan whose file stamp matches records a chat approval and is logged to plan_guard_log. Any other
134
+ * text is not an approval. A stamp that matches none, or several, or a record that cannot be saved,
135
+ * is a problem for the owner to read; nothing is approved.
136
+ */
137
+ export function chatApprove(text: string, cfg: Config, source: string): ChatApproveResult {
138
+ if (!cfg.guards.chat_unlock) return { applied: false };
139
+ const m = APPROVE_CMD.exec(text.trim());
140
+ if (!m) return { applied: false };
141
+ const stamp = m[1];
142
+ const matches = q.activePlans().filter(p => p.status === "open" && basename(p.file).startsWith(`${stamp}_`));
143
+ const [plan, second] = matches;
144
+ if (!plan) return { applied: false, problem: `no open plan ${stamp}` };
145
+ if (second) return { applied: false, problem: `${matches.length} open plans match ${stamp}; nothing approved` };
146
+ try {
147
+ recordApproval(plan.file, { hash: reviewHash(plan.text), at: Date.now(), via: "chat", page: pageOfPlan(cfg.pages.dir, plan.file) ?? "" });
148
+ } catch (e) {
149
+ return { applied: false, problem: `plan ${stamp} not approved: ${e instanceof Error ? e.message : String(e)}` };
150
+ }
151
+ try {
152
+ appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} APPROVE chat source=${source} plan=${plan.file}\n`);
153
+ } catch {}
154
+ return { applied: true, plan: plan.file };
95
155
  }
156
+
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
+ export function approvalProblem(text: string, file: string, pagesDir: string, since: string): string | null {
159
+ if (since === "") return null;
160
+ const page = pageOfPlan(pagesDir, file);
161
+ const stamp = /^\d{8}_\d{4}/.exec(basename(file))?.[0] ?? null;
162
+ const gated = since !== "" && (stamp === null || stamp >= since);
163
+ if (page === null) {
164
+ if (!gated) return null; // predates the convention
165
+ return `plan ${file} has no page: publish its page with neurastream pages publish <page.html> --plan ${file}`;
166
+ }
167
+ const rec = readPlanApproval(file);
168
+ if (rec !== null && rec.hash === reviewHash(text)) return null;
169
+ const hint = stamp !== null ? `, or types: approve ${stamp}` : "";
170
+ return `plan ${file} has no approval record. The owner approves it from ${page} in Base${hint}.`;
171
+ }
@@ -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.
@@ -12,20 +12,21 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
12
12
  - Main writes every plan in `<repo>/docs/plans/`, shaped like `{{AGENT_DIR}}/queue/TEMPLATE.md`. Do the research yourself; never base a plan on another agent's findings.
13
13
  - Phase 0 of every plan: blocker scripts that stop the implementer from going against the plan. They must exist before any spawn.
14
14
  - Every plan has `## Reuse`; no spawn without a current reviewer PASS (`templates/plan-review-brief.md`, recorded only from the reviewer's own Progress edit); a brief names every open MR of its plan with an `MR !N:` line.
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.
15
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.
16
17
  - Owner asks about a past plan → grep FINISHED.md first; open the archived plan only for details.
17
- - 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.
18
19
  - Main may push and publish once the repo's AGENTS.md test rules are met.
19
20
 
20
21
  ## Scripts (run at the stated moment)
21
22
  |Script|When|
22
23
  |---|---|
23
24
  |`main-start`|session start, after an abort, before every status report; prints the MR sweep (open forge MRs vs open plans)|
24
- |`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|
25
26
  |`queue-finished`|owner asks about a past plan (`<word>` prints matching FINISHED.md entries; `--backfill` fills it from archived plans)|
26
- |`agent-ledger --cap`|before every spawn|
27
- |`agent-score`|`gate <agent>` before every spawn; `accept`/`diagnose`/`penalty` after reviewing a result; `check` after every merge; `board` after a score change|
28
- |`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)|
29
30
  |`wip-check`|session start, before new work|
30
31
  |`neurastream metrics ci <repo> <mr>`|after every merge|
31
32
  |`neurastream metrics report`|weekly when main-start says due; propose ONE rule change to the owner|
@@ -151,6 +151,8 @@ autonomy:
151
151
  review: # plan review gate (plan 20261028_1600): reuse lines now, reviewer PASS from P2 (docs/config.md)
152
152
  agents: ["reviewer"] # agents allowed to run a review spawn: one must be in "## Allowed" of notes/subagents.md (doctor and queue-check fail otherwise, e.g. ["glm"]); the PASS exemption needs one plus the brief's `Plan review:` line; an empty list turns both review gates off
153
153
  mr_cache_minutes: 10 # minutes the spawn gate caches a repo's open-MR list in <queue_state>/mr-cache.json; 0 = no cache
154
+ approval: # plan approval hard gate (plan 20261029_1455 P3): docs/config.md
155
+ since: "" # a plan stamped at or after this (YYYYMMDD_HHMM) needs a page and an approval record; "" = off
154
156
 
155
157
  ui:
156
158
  enabled: false # the owner's phone page (neurastream ui); binds the tailnet address only
@@ -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,