neurastream 0.2.49 → 0.2.50

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
@@ -23,14 +23,15 @@ flowchart LR
23
23
 
24
24
  | Part | What it enforces |
25
25
  |---|---|
26
- | Queue (`queue-check`, `queue-close`, `queue-cancel`) | Every open plan is a file in a main checkout, listed in the one main index (`paths.queue_index`, one absolute path per line — never repo directories) and follows a template; one plan = one worktree. A plan leaves the queue only when its branch is merged into remote main and its done check passes; a failing check reopens it. Closing removes the plan's worktree when it is clean and its branch landed — a plain `git worktree remove`; a dirty, unmerged or unremovable worktree and the repo's main checkout are kept with the reason. Branches leave only via `git branch -d`, so a branch whose merge git cannot see stays. |
26
+ | Queue (`queue-check`, `queue-close`, `queue-cancel`, `queue-finished`) | Every open plan is a file in a main checkout, listed in the one main index (`paths.queue_index`, one absolute path per line — never repo directories) and follows a template; one plan = one worktree. A plan leaves the queue only when its branch is merged into remote main and its done check passes; a failing check reopens it. Closing removes the plan's worktree when it is clean and its branch landed — a plain `git worktree remove`; a dirty, unmerged or unremovable worktree and the repo's main checkout are kept with the reason. Branches leave only via `git branch -d`, so a branch whose merge git cannot see stays. `queue-check` also sweeps the forge: an open MR that no open plan mentions fails it (a missing forge CLI or remote only skips that repo). The summary shows `N/M done` per plan. `queue-finished <word>` searches the list of closed plans. |
27
27
  | Blockers | Each plan's phase 0 lists what helpers may not do: push, touch a path, run a command, or write a text. The guard judges the command that runs and the files it changes, not words inside commit messages, quoted text or heredoc bodies: `git commit -m "... push ..."` is allowed, `git push` is refused. |
28
28
  | Guards | Helpers may only edit their plan's `## Progress`; every new entry ends with a `Findings:` line (`Findings: none`, or one item per finding with `file:line` evidence) or the edit is refused and the file restored, and each item becomes an incident. Helpers get a warning at call 90 and are stopped at call 100; Main can set a different stop for one run with a `Call budget: <N>` line in the task brief (see "Main reads the code for its plans" below). Protected files need an owner unlock (a file the owner touches, valid 30 minutes). With `guards.chat_unlock` on (default off), the owner's whole chat message `unlock` / `unlock N` / `lock` — typed in the terminal or through a collab guest prompt from a write peer — moves that file instead; nothing a model, a subagent or a tool produces can. |
29
29
  | Ledger (`agent-ledger`) | Tokens, cost, state and exit reason per agent; `--cap` refuses a spawn when a provider already runs `ledger.max_running_per_provider` (default 2), when a run is `OVER-BUDGET` (unless `--incident <id>`), or when a priority plan has no running agent (unless `--priority`). |
30
30
  | Scoring (`agent-score`) | Points only for work Main accepted by commit, times the phase difficulty. Ranked per dollar and per hour. |
31
31
  | Brief lint (`brief-lint`) | Refuses a helper brief that misses a required rule (acceptance, stop condition, no push, call budget). |
32
- | Plan review gate (`review.*`) | Every plan carries a `## Reuse` section (one checked line per new thing — a queue problem without it); no spawn on a plan without a current reviewer PASS, recorded by plan-guard only from a read-only reviewer subagent's `PLAN REVIEW: PASS` Progress edit (`templates/plan-review-brief.md`, `review.agents`) and expired when the plan text changes; and no spawn while the plan holds done-but-not-merged work — open MRs of its repo, branches with commits off main — that the brief does not name with an `MR !N:` / `Branch <name>:` line. brief-lint enforces the brief side: an MR named in prose without the line, a plan named only under a worktree path instead of its main checkout, and `src/tests` files the plan's blocker `ALLOWED` regex rejects are all refused. Plans stamped before `review.since` are exempt until audited. |
33
- | Write-time checks (`write_check`) | With `write_check.enabled` on, a subagent's write or edit to a file a configured linter covers is linted before and after the call. If the call adds a lint finding or a suppression comment (`noqa` and similar), the file is put back and the call returns an error. Main is left alone unless `applies_to: all`. Off by default. |
32
+ | Plan review gate (`review.*`) | Every plan carries a `## Reuse` section (one checked line per new thing — a queue problem without it); no spawn on a plan without a current reviewer PASS, recorded by plan-guard only from a read-only reviewer subagent's Progress line of the exact form `- [<date> <time> <name>: ]PLAN REVIEW: PASS|FAIL …` (any other `PLAN REVIEW` line is put back; `templates/plan-review-brief.md`, `review.agents`) and expired when the plan text changes — ticking a phase box does not count as a change; and no spawn while the plan holds done-but-not-merged work — open MRs of its repo, branches with commits off main — that the brief does not name with an `MR !N:` / `Branch <name>:` line. brief-lint enforces the brief side: an MR named in prose without the line, a plan named only under a worktree path instead of its main checkout, and `src/tests` files the plan's blocker `ALLOWED` regex rejects are all refused. Plans stamped before `review.since` are exempt until audited. |
33
+ | Review agents (`review.agents`) | `doctor` and `queue-check` fail when no `review.agents` entry is in `## Allowed` of `notes/subagents.md` (no review spawn could run), and warn for each entry that is not. The default `["reviewer"]` needs `neurastream agents allow reviewer`, or set e.g. `review.agents: ["glm"]` in `config.yml`. |
34
+ | Write-time checks (`write_check`) | With `write_check.enabled` on, a subagent's write or edit to a file a configured linter covers is linted before and after the call. If the call adds a lint finding or a suppression comment (`noqa` and similar), the file is put back and the call returns an error. Rules in `write_check.defer_rules` (default: unused names) are not refused at once: the turn's end re-lints and sends one reminder for what is still there, so declare-then-use edits work. Main is left alone unless `applies_to: all`. Off by default. |
34
35
  | Main call cap (`guards.main_max_calls`) | At most 15 tool calls per Main turn — counted since the owner's last message or Main's last hand-back, so answering or delegating wins over grinding. The wrap-up warning comes at `guards.main_warn_calls` (12); the tools in `guards.main_call_exempt_tools` (`task`, `todo`, `ask`, `wait`) are never counted and never refused; `0` switches it off and tier `full` ignores it. |
35
36
  | Machine health (`machine-guard`, `main-start`, `heavy-run`) | Load, free memory, disk and `/tmp` limits; one heavy test run at a time. |
36
37
  | Unlanded work (`wip-check`, `wip-snapshot`, `wip-backup`) | Lists branches on no remote and dirty worktrees; snapshots them as hidden commits; can push them to a backup repo. |
@@ -77,7 +78,7 @@ Check the merged result:
77
78
  neurastream config --json
78
79
  ```
79
80
 
80
- Every tool is one program, selected by the name it was called with: `agent-score`, `agent-ledger`, `brief-lint`, `oc-run`, `wip-check`, `wip-backup`, `wip-snapshot`, `main-health`, `queue-check`, `queue-close`, `queue-cancel`, `queue-trim`, `main-start`, `machine-guard`, `quota-reset`, `priority-watch`, `resource-alerts`, `tmp-snapshot`, `heavy-run`.
81
+ Every tool is one program, selected by the name it was called with: `agent-score`, `agent-ledger`, `brief-lint`, `oc-run`, `wip-check`, `wip-backup`, `wip-snapshot`, `main-health`, `queue-check`, `queue-close`, `queue-cancel`, `queue-finished`, `queue-trim`, `main-start`, `machine-guard`, `quota-reset`, `priority-watch`, `resource-alerts`, `tmp-snapshot`, `heavy-run`.
81
82
 
82
83
  ## Skill pack
83
84
 
@@ -132,7 +133,7 @@ One setting decides how much Main does without asking: `autonomy.tier` in the co
132
133
 
133
134
  `neurastream ui on --login <tailscale login> [--port N]` does the whole setup in one sentence: it writes `ui.enabled: true` and `ui.owner_login` (plus `ui.port` with `--port`) into `~/.config/neurastream/config.yml` — every other line of the file is kept byte-for-byte — copies `templates/systemd/neurastream-ui.service` to `~/.config/systemd/user/neurastream-ui.service`, runs `systemctl --user daemon-reload`, `enable` and `restart`, then prints the phone link `http://<MagicDNS name>:<port>`. The login must be one the tailnet knows (`tailscale status --json`); when tailscale cannot answer, the check is skipped with a printed warning, never a refusal. `neurastream ui off` stops and disables the unit and sets `ui.enabled: false`, keeping `ui.owner_login` for the next `on`.
134
135
 
135
- With `ui.enabled: true` and `ui.owner_login` set (`neurastream config`, `docs/config.md`), `neurastream ui` serves one page bound to this machine's tailnet address only (port `ui.port`, default 7787; `templates/systemd/neurastream-ui.service` runs it as a user unit). A sticky top bar holds the "ns" logo, four pill tabs — Now, Queue, Agents, Spend, each a server-rendered view (`/?tab=…`, an unknown value falls back to Now) — and the lock pill ("🔒 Off" / "🔓 12 min") that opens the guard unlock ("Unlock 15 min", "Unlock 30 min", "Lock now"; when `guards.chat_unlock` is off it says so in plain words with the exact config line). Now is the home tab: a Today tile card over the last 24 h (needs-you count in warn color, list-price spend with a sparkline and the Main/agents split, agent runs with running/died counts and a sparkline, open plans), then one card per open `WAITING on owner:` plan that says why it needs him — the plan's `#` title, then Do (what to do), Stuck until then (what stays blocked, including plans this answer unblocks), and Why you (why Main cannot do it), with the goal folded into a Background block. A question ask gets "Yes"/"No"/"Reply…"; a task ask gets "Done". The answer shows as a one-time receipt ("Sent to Main · 08:12"); once the owner inbox already holds an answer for a plan, the card says so ("You answered ‘yes' · 14:19 — Main is on it") with a small change-answer link. The queue is one flat ranked list in `INDEX.md` order. Each card shows the plan title, a two-line summary from the plan's `Summary:` header (one or two plain sentences under Branch; if that line is missing, the first Goal bullet with a leading Owner or INCIDENT prefix cut off), and a status chip — waits you, waits on another plan, not started, phase K of N, or all N done. Drag a card by its ≡ handle, or tap "↑ top"/"↑"/"↓"; the drop rewrites `INDEX.md`, Main gets the move as a message and the page confirms "Moved to #2". Now shows the first 8 rows with a "Show all N ›" link to the Queue tab. The Agents tab lists working-now rows (a run that died before its first reply shows the model from the spawning agent's `model:` frontmatter, never "?"), the agent-score table, open incidents, recent merges/CI and machine health; the Spend tab pairs the spend tile with per-model spend over 24 h. The Now tab also has a "Tell Main" message box for a text note and up to four images; Main receives the text and pictures, and the page keeps a "Sent today" list for 12 hours before removing those messages and their image files. Light and dark follow the OS; there are no external assets and no build step — one server-rendered HTML string, inline CSS and one small inline script under a per-response CSP nonce (`bun scripts/ui-preview.ts <out.html> [--tab <name>]` renders a preview without a server). No chat, no plan editing, no shell.
136
+ With `ui.enabled: true` and `ui.owner_login` set (`neurastream config`, `docs/config.md`), `neurastream ui` serves one page bound to this machine's tailnet address only (port `ui.port`, default 7787; `templates/systemd/neurastream-ui.service` runs it as a user unit). A sticky top bar holds the "ns" logo, five pill tabs — Now, Queue, Agents, Spend, Base (see "Base tab" below), each a server-rendered view (`/?tab=…`, an unknown value falls back to Now) — and the lock pill ("🔒 Off" / "🔓 12 min") that opens the guard unlock ("Unlock 15 min", "Unlock 30 min", "Lock now"; when `guards.chat_unlock` is off it says so in plain words with the exact config line). Now is the home tab: a Today tile card over the last 24 h (needs-you count in warn color, list-price spend with a sparkline and the Main/agents split, agent runs with running/died counts and a sparkline, open plans), then one card per open `WAITING on owner:` plan that says why it needs him — the plan's `#` title, then Do (what to do), Stuck until then (what stays blocked, including plans this answer unblocks), and Why you (why Main cannot do it), with the goal folded into a Background block. A question ask gets "Yes"/"No"/"Reply…"; a task ask gets "Done". The answer shows as a one-time receipt ("Sent to Main · 08:12"); once the owner inbox already holds an answer for a plan, the card says so ("You answered ‘yes' · 14:19 — Main is on it") with a small change-answer link. The queue is one flat ranked list in `INDEX.md` order. Each card shows the plan title, a two-line summary from the plan's `Summary:` header (one or two plain sentences under Branch; if that line is missing, the first Goal bullet with a leading Owner or INCIDENT prefix cut off), and a status chip — waits you, waits on another plan, not started, phase K of N, or all N done. Drag a card by its ≡ handle, or tap "↑ top"/"↑"/"↓"; the drop rewrites `INDEX.md`, Main gets the move as a message and the page confirms "Moved to #2". Now shows the first 8 rows with a "Show all N ›" link to the Queue tab. The Agents tab lists working-now rows (a run that died before its first reply shows the model from the spawning agent's `model:` frontmatter, never "?"), the agent-score table, open incidents, recent merges/CI and machine health; the Spend tab pairs the spend tile with per-model spend over 24 h. The Now tab also has a "Tell Main" message box for a text note and up to four images; Main receives the text and pictures, and the page keeps a "Sent today" list for 12 hours before removing those messages and their image files. Light and dark follow the OS; there are no external assets and no build step — one server-rendered HTML string, inline CSS and one small inline script under a per-response CSP nonce (`bun scripts/ui-preview.ts <out.html> [--tab <name>]` renders a preview without a server). No chat, no plan editing, no shell.
136
137
 
137
138
  A request is served only when the peer is a tailnet address that is neither loopback nor this machine's own tailnet IP, `tailscale whois` names the `ui.owner_login` login — and the Host header is this machine: the tailnet address or the MagicDNS name, with the served port. The Host check runs on every request before whois, and a POST's Origin must match it, so a DNS-rebinding page (foreign Host, matching Origin, owner's phone) gets a 403 like everyone else. Every request logs one `UI <method> <path> login=<l> → <code>` line to the guard log.
138
139
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.49",
3
+ "version": "0.2.50",
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",
@@ -13,7 +13,7 @@ import { stripBlock } from "../../core/agents-md.ts";
13
13
  import { loadConfig } from "../../core/config.ts";
14
14
  import { notifyFindings } from "../../core/notify.ts";
15
15
  import { loadKnownSecrets, proxyOnPath } from "../../core/secret-redact.ts";
16
- import { readIndex } from "../../core/queue/lib.ts";
16
+ import { allowedAgents, readIndex, reviewAgentsProblem } from "../../core/queue/lib.ts";
17
17
  import { realTailscale, type Tailscale } from "../../core/tailscale.ts";
18
18
 
19
19
  const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
@@ -218,6 +218,10 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env,
218
218
  const notify = notifyFindings(cfg);
219
219
  problems.push(...notify.problems);
220
220
  warnings.push(...notify.warnings);
221
+ // P4d (plan 20261028_1600): a review spawn needs a review.agents entry that Main may spawn.
222
+ const review = reviewAgentsProblem(cfg, allowedAgents(cfg.paths.subagents));
223
+ if (review.problem) problems.push(review.problem);
224
+ warnings.push(...review.warnings);
221
225
  // Secrets (plan 20261025_2204): the redactor's state and the second net, count only — doctor
222
226
  // never prints a value. A missing proxy binary is a warning, never a problem: the launch path
223
227
  // falls back to a plain harness start.
@@ -22,11 +22,11 @@ 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
24
  import { burdenRule, repoRules, rulesChanged } from "../../core/repo-rules.ts";
25
- import { loadConfig, type Config } from "../../core/config.ts";
25
+ import { configFile, loadConfig, reloadingConfig, type Config } from "../../core/config.ts";
26
26
  import { checkWrite, deferSteer, type WriteCheckConfig } from "../../core/write-check.ts";
27
27
  import { nowSec, strftime } from "../../core/clock.ts";
28
28
  import { runDetectors, runDetectorsGated, type DetectorInput } from "../../core/incident-detectors.ts";
29
- import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, newProgressEntries, planReadNote, recordMainResult, resetMainCalls, revertMainEdit, rekeySpawnFile } from "../../core/guards.ts";
29
+ import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, newProgressEntries, planReadNote, recordMainResult, resetMainCalls, revertMainEdit, rekeySpawnFile, reviewSpawnEnd } from "../../core/guards.ts";
30
30
  import { rateLimitWait } from "../../core/rate-limit.ts";
31
31
  import { notifyProviders, postReply } from "../../core/notify.ts";
32
32
  import { loadKnownSecrets, redactSecrets, redactSummary } from "../../core/secret-redact.ts";
@@ -565,8 +565,10 @@ export function deliverOwnerInbox(pi: ExtensionHost, cfg: Config): void {
565
565
  adapterLog(cfg, `owner inbox: delivered ${delivered} answer(s) (cursor ${cursor} → ${next})`);
566
566
  }
567
567
 
568
- /** Register the guard handlers on one extension host. `cfg` is injectable for tests. */
569
- export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
568
+ /** Register the guard handlers on one extension host. `initial` is injectable for tests; `freshConfig` re-reads the config per guarded call. */
569
+ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig: () => Config = () => initial): void {
570
+ // Guarded handlers take `cfg = freshConfig()` first, so an edited config.yml reaches the next call (P4e).
571
+ let cfg = initial;
570
572
  // The queue library resolves its paths from env snapshots; point them at this config first.
571
573
  applyQueueEnv(cfg);
572
574
  // Main's rules ride its system prompt each turn; they are never written into the owner's AGENTS.md.
@@ -575,12 +577,12 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
575
577
  let callsSinceStop = 0;
576
578
  let idleStops = 0;
577
579
  let timer: unknown;
578
- let inboxTimer: unknown;
579
580
  const calls = new Map<string, number>(); // subagent call budget, by agent id
580
581
  const pending = new Map<string, Map<string, string>>(); // toolCallId -> plan snapshots
581
582
  const pendingWrite = new Map<string, Map<string, string | null>>(); // toolCallId -> write-check snapshots; null: the file did not exist
582
583
  const deferredWrite = new Map<string, Map<string, string | null>>(); // agent id -> files that added deferred findings this turn -> text before the first one (null: new file); judged at that session's own agent_end
583
584
  const pendingRules = new Set<string>(); // repos Main worked in, rules to hand over at the next prompt
585
+ const pendingReviewNotes: string[] = []; // P4k: review spawns that ended with no verdict; Main hears at its next prompt
584
586
  // Chat notify (plans 20261024_2155, 20261025_0130): the text a hand-back already posted
585
587
  // (attempted) — one post per distinct text, never a retry loop. The reply itself comes from
586
588
  // the stop/agent_end event, never the session file (session_stop fires BEFORE agent_end, and
@@ -747,7 +749,6 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
747
749
  ? c.setInterval(() => deliverOwnerInbox(pi, cfg), OWNER_INBOX_POLL_MS)
748
750
  : setInterval(() => deliverOwnerInbox(pi, cfg), OWNER_INBOX_POLL_MS);
749
751
  if (it && typeof it === "object" && "unref" in it && typeof it.unref === "function") it.unref();
750
- inboxTimer = it;
751
752
  });
752
753
 
753
754
  // What a subagent is still missing (plan 20261027_1530 P2): the rules of the repo its plan is
@@ -786,6 +787,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
786
787
  };
787
788
 
788
789
  pi.on("before_agent_start", (event, ctx) => {
790
+ cfg = freshConfig();
789
791
  const c = asCtx(ctx);
790
792
  const prompt = asString(asRecord(event).prompt);
791
793
  if (c.kind !== "main") {
@@ -816,12 +818,13 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
816
818
  if (r && rulesChanged(cfg, asString(c.id) || "main", r.path, r.text)) rules.push(`Repo rules (${r.path}):\n${r.text}`);
817
819
  }
818
820
  pendingRules.clear();
821
+ const reviewNotes = isMain(ctx) ? pendingReviewNotes.splice(0) : [];
819
822
  const hostPrompt = asRecord(event).systemPrompt;
820
823
  return {
821
824
  systemPrompt: [...(Array.isArray(hostPrompt) ? hostPrompt : []), mainRules],
822
825
  message: {
823
826
  customType: "main-guard.queue",
824
- content: [d.inject, notice, ...rules].filter(Boolean).join("\n\n"),
827
+ content: [d.inject, notice, ...reviewNotes, ...rules].filter(Boolean).join("\n\n"),
825
828
  display: false,
826
829
  },
827
830
  };
@@ -830,7 +833,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
830
833
  // The spawn event carries no brief, so the plan gate runs at the task tool call (original
831
834
  // behaviour); here only the allow-list and the task-only rule apply, with the original texts.
832
835
  pi.on("before_subagent_spawn", (event, ctx) => {
833
- if (asCtx(ctx).kind === "sub") return;
836
+ cfg = freshConfig();
834
837
  const agent = asString(asRecord(event).agent);
835
838
  const kind = asString(asRecord(event).invocationKind);
836
839
  if (!q.allowedAgents().has(agent))
@@ -840,7 +843,10 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
840
843
  return undefined;
841
844
  });
842
845
 
846
+ let lastMainRc: RolloverCtx | null = null;
847
+
843
848
  pi.on("tool_call", (event, ctx) => {
849
+ cfg = freshConfig();
844
850
  const c = asCtx(ctx);
845
851
  const e = asRecord(event);
846
852
  const tool = asString(e.toolName);
@@ -859,8 +865,10 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
859
865
  // running ones finish first. Subagents' own tool calls are unaffected. Main's task calls
860
866
  // also carry the running job labels for the priority gate (20261025_0215 P2).
861
867
  let runningJobs: string[] | undefined;
862
- if (!isSub && tool === "task") {
863
- const rc = asRolloverCtx(ctx);
868
+ if (!isSub) lastMainRc = asRolloverCtx(ctx);
869
+ if (tool === "task") {
870
+ // A subagent's task call drains and labels by Main's rollover context: its own ctx has none.
871
+ const rc = lastMainRc;
864
872
  runningJobs = rc?.runningJobs();
865
873
  if (cfg.rollover.enabled && rc) {
866
874
  const why = spawnRefusal(rolloverSnapshot(rc).state, runningJobs ?? []);
@@ -902,6 +910,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
902
910
  };
903
911
 
904
912
  pi.on("tool_result", (event, ctx) => {
913
+ cfg = freshConfig();
905
914
  onSizeCheck("tool_result", event, ctx);
906
915
  const e = asRecord(event);
907
916
  const c = asCtx(ctx);
@@ -928,7 +937,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
928
937
  try {
929
938
  after = readFileSync(file, "utf8");
930
939
  } catch {}
931
- const d = checkPlanEdit({ path: file, before, after, agent: c.kind === "sub" ? "sub" : "main" }, cfg);
940
+ const d = checkPlanEdit({ path: file, before, after, agent: c.kind === "sub" ? "sub" : "main", agentId: id }, cfg);
932
941
  if (!d.allow && d.restore) {
933
942
  try {
934
943
  if (d.restore.text === null) rmSync(d.restore.path, { force: true });
@@ -1012,6 +1021,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
1012
1021
  });
1013
1022
 
1014
1023
  pi.on("session_stop", (e, ctx) => {
1024
+ cfg = freshConfig();
1015
1025
  const c = asCtx(ctx);
1016
1026
  if (c.hasAgent && c.kind !== "main") return;
1017
1027
  // A relaunch is requested: omp shuts down at the next idle, so the stop must not be continued.
@@ -1348,6 +1358,13 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
1348
1358
  if (asRecord(e).willContinue === true) return;
1349
1359
  resetMainCalls();
1350
1360
  });
1361
+ // P4k backstop (plan 20261028_1600): a named review spawn that ends with no verdict recorded at its edit is judged here, from its own plan file; the note tells Main at its next prompt.
1362
+ pi.on("agent_end", (_e, ctx) => {
1363
+ const c = asCtx(ctx);
1364
+ if (c.kind !== "sub" || !c.id) return;
1365
+ const note = reviewSpawnEnd(c.id, cfg);
1366
+ if (note) pendingReviewNotes.push(note);
1367
+ });
1351
1368
 
1352
1369
  // omp is really shutting down: the exit-grace fallback must not fire.
1353
1370
  pi.on("session_shutdown", () => clearGrace?.());
@@ -1535,5 +1552,6 @@ export default function ompExtension(pi: ExtensionHost): void {
1535
1552
  // no config read. `neurastream main` sets it for its child (launch.ts), so anything the Main
1536
1553
  // session spawns inherits it and stays guarded.
1537
1554
  if (process.env[MAIN_ENV] !== "1") return;
1538
- createOmpAdapter(pi, loadConfig());
1555
+ const initial = loadConfig();
1556
+ createOmpAdapter(pi, initial, reloadingConfig(initial, configFile(), () => loadConfig(), line => adapterLog(initial, line)));
1539
1557
  }
package/src/cli/guard.ts CHANGED
@@ -65,11 +65,18 @@ function decide(event: string, p: Record<string, unknown>, cfg: Config): Decisio
65
65
  invocationKind: asString(p.invocationKind, "task"),
66
66
  brief: asString(p.brief ?? p.context ?? p.task),
67
67
  ...(p.runningJobs === undefined ? {} : { runningJobs: asStringList(p.runningJobs) }),
68
+ ...(p.name === undefined ? {} : { name: asString(p.name) }),
68
69
  };
69
70
  return checkSpawn(e, cfg);
70
71
  }
71
72
  case "plan-edit": {
72
- const e: PlanEditEvent = { path: asString(p.path), before: asString(p.before), after: asString(p.after), agent: asAgent(p.agent) };
73
+ const e: PlanEditEvent = {
74
+ path: asString(p.path),
75
+ before: asString(p.before),
76
+ after: asString(p.after),
77
+ agent: asAgent(p.agent),
78
+ ...(p.agentId === undefined ? {} : { agentId: asString(p.agentId) }),
79
+ };
73
80
  return checkPlanEdit(e, cfg);
74
81
  }
75
82
  case "stop": {
@@ -116,6 +116,8 @@ export interface SpawnEvent {
116
116
  brief: string;
117
117
  /** Labels of the harness's own running background jobs; undefined when the caller has no job info. */
118
118
  runningJobs?: string[];
119
+ /** The spawn's name (its task name); keys the review lock of a named review spawn (P4f). */
120
+ name?: string;
119
121
  }
120
122
 
121
123
  export interface InjectEvent {
@@ -128,6 +130,8 @@ export interface PlanEditEvent {
128
130
  before: string;
129
131
  after: string;
130
132
  agent: "main" | "sub";
133
+ /** The sub's agent id; a review spawn's PLAN REVIEW line counts only from its own id (P4f). */
134
+ agentId?: string;
131
135
  }
132
136
 
133
137
  export interface StopEvent {
@@ -1,7 +1,7 @@
1
1
  // Loads ~/.config/neurastream/config.yml over templates/config.yml.
2
2
  // Values (paths, names, prices) live in the template, not in this file.
3
3
 
4
- import { existsSync, readFileSync } from "node:fs";
4
+ import { existsSync, readFileSync, statSync } from "node:fs";
5
5
  import { homedir } from "node:os";
6
6
  import { dirname, join } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
@@ -319,6 +319,32 @@ export function configFile(home = homedir()): string {
319
319
  return join(home, ".config", "neurastream", "config.yml");
320
320
  }
321
321
 
322
+ /**
323
+ * The config as of now. Each call stats `file`; when its mtime changed it calls `load()`.
324
+ * A failed reload keeps the last good config and reports one line through `onError`, so a
325
+ * broken edit never fails open or crashes a running guard. Used by a harness adapter per guarded call.
326
+ */
327
+ export function reloadingConfig(
328
+ initial: Config,
329
+ file: string,
330
+ load: () => Config,
331
+ onError: (line: string) => void,
332
+ ): () => Config {
333
+ let cfg = initial;
334
+ let seen = statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? 0;
335
+ return () => {
336
+ const now = statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? 0;
337
+ if (now === seen) return cfg;
338
+ seen = now;
339
+ try {
340
+ cfg = load();
341
+ } catch (err) {
342
+ onError(`config reload refused, keeping the last good config: ${err instanceof Error ? err.message : String(err)}`);
343
+ }
344
+ return cfg;
345
+ };
346
+ }
347
+
322
348
  function isObj(v: unknown): v is Record<string, unknown> {
323
349
  return typeof v === "object" && v !== null && !Array.isArray(v);
324
350
  }
@@ -55,6 +55,12 @@ function deny(reason: string): Decision {
55
55
  return { allow: false, reason };
56
56
  }
57
57
 
58
+ /** A raw target that names a plan: under a docs/plans/ directory, or a plan file name (YYYYMMDD_HHMM_*.md). */
59
+ function isPlanName(raw: string): boolean {
60
+ return /(^|\/)docs\/plans\//.test(raw) || /^\d{8}_\d{4}_[^/]*\.md$/.test(raw.split("/").pop() ?? "");
61
+ }
62
+ const PLAN_WRITE_TOOLS: Record<string, true> = { edit: true, write: true, ast_edit: true };
63
+
58
64
  /** Guard-log line, `<ISO UTC> <line>`; a failed append is swallowed. */
59
65
  export function log(file: string, line: string): void {
60
66
  try {
@@ -135,6 +141,7 @@ interface PlanReview {
135
141
  hash: string;
136
142
  finding: string;
137
143
  at: number;
144
+ by?: string;
138
145
  }
139
146
 
140
147
  function planReviewsFile(): string {
@@ -165,25 +172,30 @@ export function reviewHash(text: string): string {
165
172
  .outsideProgress(text)
166
173
  .split("\n")
167
174
  .filter(l => !MAIN_ONLY_LINE.test(l))
175
+ .map(l => l.replace(/^(\s*[-*]\s+)\[[xX]\]/, "$1[ ]")) // a ticked phase box hashes as unticked: ticking never expires a PASS
168
176
  .join("\n"),
169
177
  );
170
178
  }
171
179
 
172
- /** The progress entry that records a review; only a subagent's edit can carry one. */
173
- const REVIEW_LINE = /^- PLAN REVIEW: (PASS|FAIL)/;
180
+ /** The progress entry that records a review; only a subagent's edit can carry one. The verdict is the match, never a substring. */
181
+ const REVIEW_LINE = /^- (?:\d{4}-\d{2}-\d{2} \d{2}:\d{2} [^\s:]+: )?PLAN REVIEW: (PASS|FAIL)\b/;
182
+ /** Any entry that opens like a review line; one that REVIEW_LINE does not match is restored, not recorded. */
183
+ const REVIEW_LOOKALIKE = /^- (?:\d{4}-\d{2}-\d{2} \d{2}:\d{2} [^\s:]+: )?PLAN REVIEW\b/;
184
+
185
+ /** Who launches an agent: Main's launch may use a plan review's exemption, a sub's never may (plan 20261028_1600 P4i). */
186
+ export type Spawner = "main" | "sub";
174
187
 
175
188
  /**
176
189
  * P2 (plan 20261028_1600): a spawn on a plan needs a recorded reviewer PASS whose hash still
177
190
  * matches the plan text — progress-only edits keep a PASS valid, any other change expires it,
178
191
  * a FAIL is denied with its first finding. A review spawn itself — an agent from review.agents
179
- * whose brief has the `Plan review: <plan>` line — is exempt, and so is any plan stamped
192
+ * whose brief has the `Plan review: <plan>` line — is exempt when Main launches it, and so is any plan stamped
180
193
  * before `review.since` (P4c: same cutover as the reuse-line gate).
181
194
  */
182
- export function reviewPassProblem(named: string[], brief: string, agent: string, cfg: Config): string | null {
195
+ export function reviewPassProblem(named: string[], brief: string, agent: string, cfg: Config, spawner: Spawner): string | null {
183
196
  const reviews = readPlanReviews();
184
- const reviewLines = brief.split("\n").filter(l => l.startsWith("Plan review:"));
185
197
  for (const file of named) {
186
- if (cfg.review.agents.includes(agent) && reviewLines.some(l => l.slice("Plan review:".length).trim() === file)) continue;
198
+ if (isReviewSpawn(file, brief, agent, cfg, spawner)) continue;
187
199
  if (!q.reviewApplies(file, cfg.review.since)) continue;
188
200
  const rec = reviews[file];
189
201
  if (!rec) return `plan ${file} has no current reviewer PASS. Spawn a reviewer with templates/plan-review-brief.md.`;
@@ -203,16 +215,128 @@ export function reviewPassProblem(named: string[], brief: string, agent: string,
203
215
  function recordReviews(e: PlanEditEvent, cfg: Config): void {
204
216
  const entries = newProgressEntries(e.before, e.after).filter(b => REVIEW_LINE.test(b));
205
217
  if (!entries.length) return;
218
+ const spawns = readReviewSpawns();
219
+ const found = matchReviewSpawn(spawns, e.agentId ?? "");
220
+ if (!found) return;
221
+ const { name, spawn } = found;
206
222
  const reviews = readPlanReviews();
207
223
  for (const block of entries) {
208
- reviews[e.path] = {
209
- verdict: block.startsWith("- PLAN REVIEW: PASS") ? "PASS" : "FAIL",
210
- hash: reviewHash(e.after),
211
- finding: findingsValue(block) ?? "",
212
- at: nowSec(),
213
- };
224
+ const repeat = spawn.verdicts > 0;
225
+ spawn.verdicts++;
226
+ const at = nowSec();
227
+ // Judged against the plan as the spawn first saw it (P4k): a plan that moved during the review cannot pass.
228
+ if (repeat) reviews[e.path] = { verdict: "FAIL", hash: spawn.hash, finding: "review spawn wrote 2 verdicts", at, by: name };
229
+ else if (reviewHash(e.after) !== spawn.hash) reviews[e.path] = { verdict: "FAIL", hash: spawn.hash, finding: "plan changed during review", at, by: name };
230
+ else reviews[e.path] = { verdict: REVIEW_LINE.exec(block)![1] === "PASS" ? "PASS" : "FAIL", hash: spawn.hash, finding: findingsValue(block) ?? "", at, by: name };
214
231
  }
215
232
  writePlanReviews(reviews, cfg);
233
+ writeReviewSpawns(spawns);
234
+ }
235
+
236
+ /** P4k backstop, at a sub agent's end: a named review spawn whose PLAN REVIEW line reached no edit (a path the write targets miss) is recorded here. Returns Main's note when the spawn wrote no verdict at all. */
237
+ export function reviewSpawnEnd(agentId: string, cfg: Config): string | null {
238
+ const found = matchReviewSpawn(readReviewSpawns(), agentId);
239
+ if (!found || found.spawn.verdicts > 0) return null;
240
+ const { name, spawn } = found;
241
+ const after = readPlanText(spawn.plan);
242
+ if (newProgressEntries(spawn.text, after).some(b => REVIEW_LINE.test(b))) {
243
+ recordReviews({ path: spawn.plan, before: spawn.text, after, agent: "sub", agentId: name }, cfg);
244
+ return null;
245
+ }
246
+ return `${name} wrote no verdict on ${spawn.plan}.`;
247
+ }
248
+
249
+ /** P4f: a `Plan review: <plan>` brief from Main, by a configured review agent (the exemption from the plan gate). */
250
+ function isReviewSpawn(file: string, brief: string, agent: string, cfg: Config, spawner: Spawner): boolean {
251
+ const reviewLines = brief.split("\n").filter(l => l.startsWith("Plan review:"));
252
+ return spawner === "main" && cfg.review.agents.includes(agent) && reviewLines.some(l => l.slice("Plan review:".length).trim() === file);
253
+ }
254
+
255
+ /** P4f: the review role of one task: the plan it reviews (null for other spawns). A review spawn needs a name, the name keys its lock, and it reviews one plan. */
256
+ function reviewRole(name: string | undefined, named: string[], brief: string, agent: string, cfg: Config, spawner: Spawner): { plan: string | null; problem: string | null } {
257
+ const reviewed = named.filter(f => isReviewSpawn(f, brief, agent, cfg, spawner));
258
+ if (reviewed.length > 1) return { plan: null, problem: "a review spawn reviews one plan; split the spawn." };
259
+ if (reviewed.length && !name) return { plan: null, problem: "a review spawn needs a name (the task name keys its review lock)." };
260
+ return { plan: reviewed[0] ?? null, problem: null };
261
+ }
262
+
263
+ /** P4f/P4k: the named review spawns, spawn name → its review role: the plan, the plan text and hash as the spawn first saw them, and the verdicts it wrote (review-spawns.json in the state dir). */
264
+ interface ReviewSpawn {
265
+ plan: string;
266
+ text: string;
267
+ hash: string;
268
+ verdicts: number;
269
+ }
270
+
271
+ function reviewSpawnsFile(): string {
272
+ return path.join(q.STATE_DIR, "review-spawns.json");
273
+ }
274
+
275
+ function readReviewSpawns(): Record<string, ReviewSpawn> {
276
+ try {
277
+ const parsed = JSON.parse(readFileSync(reviewSpawnsFile(), "utf8"));
278
+ return parsed && typeof parsed === "object" ? parsed : {};
279
+ } catch {
280
+ return {};
281
+ }
282
+ }
283
+
284
+ function writeReviewSpawns(spawns: Record<string, ReviewSpawn>): void {
285
+ mkdirSync(q.STATE_DIR, { recursive: true });
286
+ writeFileSync(reviewSpawnsFile(), `${JSON.stringify(spawns, null, 2)}\n`);
287
+ }
288
+
289
+ function readPlanText(file: string): string {
290
+ try {
291
+ return readFileSync(file, "utf8");
292
+ } catch {
293
+ return "";
294
+ }
295
+ }
296
+
297
+ /** Set (plan) or drop (null) a named spawn's review role; a non-review spawn under the same name drops it. */
298
+ function recordReviewSpawn(name: string, plan: string | null): void {
299
+ const spawns = readReviewSpawns();
300
+ if (plan) {
301
+ const text = readPlanText(plan);
302
+ spawns[name] = { plan, text, hash: reviewHash(text), verdicts: 0 };
303
+ } else delete spawns[name];
304
+ writeReviewSpawns(spawns);
305
+ }
306
+
307
+ /** The review role an agent id belongs to: its spawn name, or the name without a -<digits> suffix (a sub agent's id, plan P4f gap). */
308
+ function matchReviewSpawn(spawns: Record<string, ReviewSpawn>, agentId: string): { name: string; spawn: ReviewSpawn } | null {
309
+ for (const name of [agentId, agentId.replace(/-\d+$/, "")]) {
310
+ const spawn = Object.hasOwn(spawns, name) ? spawns[name] : undefined;
311
+ if (spawn && typeof spawn.plan === "string") return { name, spawn };
312
+ }
313
+ return null;
314
+ }
315
+
316
+ /** P4f: the secret-read deny: credential dirs under home, and env files. */
317
+ function secretPath(p: string, cfg: Config, cwd: string): boolean {
318
+ const home = cfg.paths.home;
319
+ const abs = path.resolve(cwd, p.startsWith("~/") ? path.join(home, p.slice(2)) : p);
320
+ const base = path.basename(abs);
321
+ const inCredDir = [".config", ".ssh", ".gnupg", ".aws"].some(d => abs.startsWith(path.join(home, d) + path.sep));
322
+ return inCredDir || base.startsWith(".env") || base.endsWith(".env");
323
+ }
324
+
325
+ /** 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. */
326
+ function reviewLockProblem(e: ToolEvent, cfg: Config): string | null {
327
+ const plan = matchReviewSpawn(readReviewSpawns(), e.agentId ?? "")?.spawn.plan ?? null;
328
+ if (!plan) return null;
329
+ const input = e.input ?? {};
330
+ if (cfg.guards.write_tools.includes(e.tool)) {
331
+ const writes = [...(e.writes ?? []), ...q.writeTargets(e.tool, input, e.cwd, [])];
332
+ if (writes.length && writes.every(w => path.resolve(e.cwd, w) === path.resolve(plan))) return null;
333
+ return `review spawn ${e.agentId} may edit only its plan ${plan}.`;
334
+ }
335
+ if (cfg.guards.read_tools.includes(e.tool) || e.tool === "todo") {
336
+ const reads = [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)];
337
+ return reads.some(p => secretPath(p, cfg, e.cwd)) ? `review spawn ${e.agentId} may not read credentials or env files.` : null;
338
+ }
339
+ return `review spawn ${e.agentId} may only read, use todo, and edit its plan; ${e.tool} is denied.`;
216
340
  }
217
341
 
218
342
  function spawnsFile(): string {
@@ -682,7 +806,9 @@ export function spawnProblem(
682
806
  staffing: Record<string, string[]> = {},
683
807
  runningJobs?: string[],
684
808
  runner: CommandRunner = defaultRunner,
809
+ spawner: Spawner = "main",
685
810
  ): string | null {
811
+ const roles: Record<string, string | null> = {};
686
812
  const tasks = Array.isArray(input?.tasks) ? input.tasks : [];
687
813
  const context = String(input?.context ?? "");
688
814
  const allowed = q.allowedAgents();
@@ -699,7 +825,10 @@ export function spawnProblem(
699
825
  const pending = pendingWorkProblem(plans, `${context}\n${String(t?.task ?? "")}`, cfg, runner);
700
826
  if (pending) return `${label}: ${pending}`;
701
827
  // The task's own `Call budget:` line wins over the shared context's.
702
- const review = reviewPassProblem(plans, `${context}\n${String(t?.task ?? "")}`, String(t?.agent ?? ""), cfg);
828
+ const role = reviewRole(t?.name, plans, `${context}\n${String(t?.task ?? "")}`, String(t?.agent ?? ""), cfg, spawner);
829
+ if (role.problem) return `${label}: ${role.problem}`;
830
+ if (t?.name) roles[label] = role.plan;
831
+ const review = reviewPassProblem(plans, `${context}\n${String(t?.task ?? "")}`, String(t?.agent ?? ""), cfg, spawner);
703
832
  if (review) return `${label}: ${review}`;
704
833
  const budget = briefBudget(String(t?.task ?? "")) ?? shared;
705
834
  if (budget !== null) {
@@ -731,7 +860,9 @@ export function spawnProblem(
731
860
  cfg,
732
861
  String((tasks[0] && (tasks[0].name ?? tasks[0].agent)) ?? "task"),
733
862
  );
734
- return gate;
863
+ if (gate) return gate;
864
+ for (const [name, plan] of Object.entries(roles)) recordReviewSpawn(name, plan);
865
+ return null;
735
866
  }
736
867
 
737
868
  function runBlockers(plan: Plan, hit: string[], e: ToolEvent, cfg: Config): string | null {
@@ -774,13 +905,14 @@ function runsCloser(input: Record<string, unknown>): boolean {
774
905
  });
775
906
  }
776
907
 
908
+ const bin = (w: string | undefined) => (w ?? "").replace(/^["']+|["']+$/g, "").split("/").pop() ?? "";
909
+
777
910
  // True when a command segment starts the owner page (plan 20261024_2230 P3c): `neurastream ui`
778
911
  // serves it and `systemctl --user start/restart/enable` of neurastream-ui relaunches it — the
779
912
  // owner's systemd moves, never an agent's, unlocked or not. Segment splitting and launcher
780
913
  // skipping match runsCloser, so `sh -c "neurastream ui"` and `sudo systemctl --user ...` are seen.
781
914
  function startsOwnerUi(input: Record<string, unknown>): boolean {
782
915
  const text = Object.values(input).filter((v): v is string => typeof v === "string").join("\n");
783
- const bin = (w: string | undefined) => (w ?? "").replace(/^["']+|["']+$/g, "").split("/").pop() ?? "";
784
916
  return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
785
917
  const words = seg.trim().split(/\s+/).filter(Boolean).map(w => w.replace(/^["'(]+|["')]+$/g, ""));
786
918
  let i = 0;
@@ -949,26 +1081,64 @@ function incidentSpawnProblem(label: string, brief: string, namedPlans: string[]
949
1081
  );
950
1082
  }
951
1083
 
952
- function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): Decision {
953
- if (e.tool === "task") {
1084
+ /**
1085
+ * A `task` launch: the cancel check, the spawn gates, then the records. Main's and a sub's launch
1086
+ * both come through here (plan 20261028_1600 P4i). Returns the refusal, or null.
1087
+ */
1088
+ function taskLaunch(input: Record<string, unknown>, cfg: Config, runningJobs: string[] | undefined, spawner: Spawner): string | null {
1089
+ const pending = q.cancelPending();
1090
+ if (pending) {
1091
+ log(cfg.paths.guard_log, `BLOCK spawn: cancel pending (${pending.words})`);
1092
+ return `${CANCEL_TODO} Flagged: "${pending.words}"`;
1093
+ }
1094
+ const files: string[] = [];
1095
+ const budgets: Record<string, number | null> = {};
1096
+ const staffing: Record<string, string[]> = {};
1097
+ const why = spawnProblem(input, cfg, files, budgets, staffing, runningJobs, defaultRunner, spawner);
1098
+ if (why) {
1099
+ log(cfg.paths.guard_log, `BLOCK spawn: ${why}`);
1100
+ return why;
1101
+ }
1102
+ const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
1103
+ if (inc) return inc;
1104
+ recordSpawns(files, staffing);
1105
+ recordBudgets(budgets);
1106
+ return null;
1107
+ }
1108
+
1109
+ /**
1110
+ * A shell launch of a bypass_spawn agent: the cancel check, the plan gate, the review PASS, the
1111
+ * incidents, then the record. Main's and a sub's launch both come through here (plan 20261028_1600 P4i).
1112
+ */
1113
+ function bypassLaunch(command: string, cfg: Config, spawner: Spawner): string | null {
1114
+ for (const entry of cfg.guards.bypass_spawn) {
1115
+ if (!bypassRegExp(entry).test(command)) continue;
954
1116
  const pending = q.cancelPending();
955
1117
  if (pending) {
956
- log(cfg.paths.guard_log, `BLOCK spawn: cancel pending (${pending.words})`);
957
- return deny(`main-guard: ${CANCEL_TODO} Flagged: "${pending.words}"`);
1118
+ log(cfg.paths.guard_log, `BLOCK bypass launch: cancel pending (${pending.words})`);
1119
+ return `${CANCEL_TODO} Flagged: "${pending.words}"`;
958
1120
  }
959
- const files: string[] = [];
960
- const budgets: Record<string, number | null> = {};
961
- const staffing: Record<string, string[]> = {};
962
- const why = spawnProblem(input, cfg, files, budgets, staffing, e.runningJobs);
1121
+ const [why, named] = planGate(command, entry, cfg);
963
1122
  if (why) {
964
- log(cfg.paths.guard_log, `BLOCK spawn: ${why}`);
965
- return deny(`main-guard: ${why}`);
1123
+ log(cfg.paths.guard_log, `BLOCK bypass launch: ${why}`);
1124
+ return why;
966
1125
  }
967
- const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
968
- if (inc) return deny(`main-guard: ${inc}`);
969
- recordSpawns(files, staffing);
970
- recordBudgets(budgets);
971
- return ALLOW;
1126
+ const review = reviewPassProblem(named, command, "", cfg, spawner);
1127
+ if (review) {
1128
+ log(cfg.paths.guard_log, `BLOCK bypass launch: ${review}`);
1129
+ return review;
1130
+ }
1131
+ const inc = incidentSpawnProblem("bypass launch", command, named, cfg);
1132
+ if (inc) return inc;
1133
+ if (named.length) recordSpawns(named);
1134
+ }
1135
+ return null;
1136
+ }
1137
+
1138
+ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): Decision {
1139
+ if (e.tool === "task") {
1140
+ const why = taskLaunch(input, cfg, e.runningJobs, "main");
1141
+ return why ? deny(`main-guard: ${why}`) : ALLOW;
972
1142
  }
973
1143
  if (cfg.guards.shell_tools.includes(e.tool)) {
974
1144
  // Strict landing gate (20261025_1940 P2, P5): in tier strict every push/merge waits for the
@@ -980,22 +1150,8 @@ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): De
980
1150
  return deny(`main-guard: tier strict — type "${cfg.autonomy.go_phrase}" to approve one push/merge`);
981
1151
  }
982
1152
  const command = String(input?.command ?? input?.code ?? "");
983
- for (const entry of cfg.guards.bypass_spawn) {
984
- if (!bypassRegExp(entry).test(command)) continue;
985
- const pending = q.cancelPending();
986
- if (pending) {
987
- log(cfg.paths.guard_log, `BLOCK bypass launch: cancel pending (${pending.words})`);
988
- return deny(`main-guard: ${CANCEL_TODO} Flagged: "${pending.words}"`);
989
- }
990
- const [why, named] = planGate(command, entry, cfg);
991
- if (why) {
992
- log(cfg.paths.guard_log, `BLOCK bypass launch: ${why}`);
993
- return deny(`main-guard: ${why}`);
994
- }
995
- const inc = incidentSpawnProblem("bypass launch", command, named, cfg);
996
- if (inc) return deny(`main-guard: ${inc}`);
997
- if (named.length) recordSpawns(named);
998
- }
1153
+ const why = bypassLaunch(command, cfg, "main");
1154
+ if (why) return deny(`main-guard: ${why}`);
999
1155
  }
1000
1156
  return editWindow(e, input, cfg);
1001
1157
  }
@@ -1049,6 +1205,11 @@ export const MAIN_PLAN_FILE = /\/docs\/plans\/(?!archive\/)[^/]+\.md$/;
1049
1205
  * plus, for Main, the spawn gates and the project-file edit window.
1050
1206
  */
1051
1207
  export function checkTool(e: ToolEvent, cfg: Config): Decision {
1208
+ const lock = e.agent === "sub" ? reviewLockProblem(e, cfg) : null;
1209
+ if (lock) {
1210
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} review lock: ${lock}`);
1211
+ return deny(`plan-guard: ${lock}`);
1212
+ }
1052
1213
  if (cfg.guards.skip_tools.includes(e.tool)) return ALLOW;
1053
1214
  const input = e.input ?? {};
1054
1215
  // Starting the owner page (plan 20261024_2230 P3c) is the owner's systemd move, never an
@@ -1063,7 +1224,15 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
1063
1224
  const paths: string[] = [];
1064
1225
  for (const p of [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)]) if (!paths.includes(p)) paths.push(p);
1065
1226
  const writes: string[] = [];
1066
- for (const p of [...(e.writes ?? []), ...q.writeTargets(e.tool, input, e.cwd)]) if (!writes.includes(p)) writes.push(p);
1227
+ const relative: string[] = [];
1228
+ for (const p of [...(e.writes ?? []), ...q.writeTargets(e.tool, input, e.cwd, relative)]) if (!writes.includes(p)) writes.push(p);
1229
+ // A relative plan path resolves against cwd to a file that does not exist, so the plan gate never
1230
+ // sees the edit (plan 20261028_1600 P4j). A plan is named by its absolute path, for every agent.
1231
+ const relPlan = PLAN_WRITE_TOOLS[e.tool] ? relative.find(isPlanName) : undefined;
1232
+ if (relPlan) {
1233
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} relative plan path: ${relPlan}`);
1234
+ return deny(`plan-guard: use the absolute plan path, not ${relPlan}. The plan gate cannot see a relative one.`);
1235
+ }
1067
1236
  // Notify secrets: no agent, main or sub, reads a webhook URL — with or without the unlock.
1068
1237
  // A call that changes a secret is not a read: its target goes through the protected-write
1069
1238
  // rule above, so the owner's unlock covers it like any guard file.
@@ -1114,6 +1283,14 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
1114
1283
  log(cfg.paths.plan_guard_log, `BLOCK sub:${e.agentId} tool=${e.tool} ${why}`);
1115
1284
  return deny(`plan-guard: ${why}`);
1116
1285
  }
1286
+ // A sub's own launch passes the same spawn gates as Main's (plan 20261028_1600 P4i).
1287
+ let launch: string | null = null;
1288
+ if (e.tool === "task") launch = taskLaunch(input, cfg, e.runningJobs, "sub");
1289
+ else if (cfg.guards.shell_tools.includes(e.tool)) launch = bypassLaunch(String(input?.command ?? input?.code ?? ""), cfg, "sub");
1290
+ if (launch) {
1291
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} ${launch}`);
1292
+ return deny(`plan-guard: ${launch}`);
1293
+ }
1117
1294
  const n = e.calls + 1;
1118
1295
  // The warn band has the global width (sub_max_calls - sub_warn_calls) ending at the cap;
1119
1296
  // unbudgeted subs keep sub_warn_calls exactly.
@@ -1239,7 +1416,12 @@ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = d
1239
1416
  log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${pendingWork}`)
1240
1417
  return deny(`main-guard: ${pendingWork}`)
1241
1418
  }
1242
- const review = reviewPassProblem(named, e.brief, e.agent, cfg);
1419
+ const role = reviewRole(e.name, named, e.brief, e.agent, cfg, "main");
1420
+ if (role.problem) {
1421
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent} ${e.name ?? "(unnamed)"} review spawn: ${role.problem}`);
1422
+ return deny(`main-guard: ${role.problem}`);
1423
+ }
1424
+ const review = reviewPassProblem(named, e.brief, e.agent, cfg, "main");
1243
1425
  if (review) {
1244
1426
  log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${review}`);
1245
1427
  return deny(`main-guard: ${review}`);
@@ -1260,6 +1442,7 @@ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = d
1260
1442
  const staffing: Record<string, string[]> = {};
1261
1443
  for (const f of named) staffing[f] = [e.agent];
1262
1444
  recordSpawns(named, staffing);
1445
+ if (e.name) recordReviewSpawn(e.name, role.plan);
1263
1446
  return ALLOW;
1264
1447
  }
1265
1448
 
@@ -1354,6 +1537,19 @@ export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1354
1537
  restore: { path: e.path, text: e.before },
1355
1538
  };
1356
1539
  }
1540
+ const loose = newProgressEntries(e.before, e.after).filter(b => REVIEW_LOOKALIKE.test(b) && !REVIEW_LINE.test(b));
1541
+ if (loose.length) {
1542
+ log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (review line)`);
1543
+ return {
1544
+ allow: false,
1545
+ reason: `plan-guard: a PLAN REVIEW line in ${e.path} does not match "- [<date> <time> <name>: ]PLAN REVIEW: PASS|FAIL — …". The file was restored.`,
1546
+ restore: { path: e.path, text: e.before },
1547
+ };
1548
+ }
1549
+ if (e.agent === "sub" && newProgressEntries(e.before, e.after).some(b => REVIEW_LINE.test(b)) && matchReviewSpawn(readReviewSpawns(), e.agentId ?? "")?.spawn.plan !== e.path) {
1550
+ log(cfg.paths.plan_guard_log, `RESTORE ${e.path} review line from a spawn that is not its named review spawn`);
1551
+ 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 } };
1552
+ }
1357
1553
  recordFindings(e, cfg);
1358
1554
  recordReviews(e, cfg);
1359
1555
  return ALLOW;
@@ -1417,6 +1613,15 @@ export function findingsValue(block: string): string | null {
1417
1613
  // Main's plan text outside "## Progress" must rest on files Main read itself (planReadProblems).
1418
1614
  // An empty `before` means the plan file did not exist yet; a refusal then deletes it.
1419
1615
  function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1616
+ // A PLAN REVIEW line is a review spawn's verdict (P4k): Main writes none, so its edit is restored.
1617
+ if (newProgressEntries(e.before, e.after).some(b => REVIEW_LINE.test(b))) {
1618
+ log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (Main wrote a review line)`);
1619
+ return {
1620
+ allow: false,
1621
+ reason: `plan-guard: a PLAN REVIEW line is written only by the named review spawn of ${e.path}, never by Main. The file was restored.`,
1622
+ restore: { path: e.path, text: e.before || null },
1623
+ };
1624
+ }
1420
1625
  if (q.outsideProgress(e.after) === q.outsideProgress(e.before)) {
1421
1626
  recordFindings(e, cfg, "main-finding");
1422
1627
  return ALLOW;
@@ -572,11 +572,13 @@ function subagentsOpWrites(code: string): boolean {
572
572
  return false;
573
573
  }
574
574
 
575
- export function writeTargets(toolName: string, input: Record<string, unknown>, cwd: string): string[] {
575
+ export function writeTargets(toolName: string, input: Record<string, unknown>, cwd: string, relative?: string[]): string[] {
576
576
  const out = new Set<string>();
577
577
  const add = (raw: string, from: string) => {
578
- const s = expandHome(String(raw).trim().replace(/^["']|["']$/g, ""));
578
+ const typed = String(raw).trim().replace(/^["']|["']$/g, "");
579
+ const s = expandHome(typed);
579
580
  if (!s || s.includes("://") || s.startsWith("$") || s === "/dev/null" || s.startsWith("/dev/")) return;
581
+ if (relative && !typed.startsWith("/")) relative.push(typed);
580
582
  out.add(path.resolve(from, s));
581
583
  };
582
584
  if (toolName === "write") {
@@ -785,6 +787,21 @@ export function allowedAgents(file = subagentsPath()): Set<string> {
785
787
  return new Set([...body.matchAll(/^\s*[-*]\s+`([a-z0-9-]+)`/gm)].map(m => m[1] ?? ""));
786
788
  }
787
789
 
790
+ // P4d (plan 20261028_1600): a review spawn runs under a review.agents entry that Main may spawn
791
+ // (## Allowed of the subagents file). When Allowed names agents and none of them is a review.agents
792
+ // entry, every review spawn is refused: a problem. When Allowed is empty (a fresh install), no subagent
793
+ // can spawn at all yet, so there is no review spawn to refuse. An entry not allowed is a warning.
794
+ export function reviewAgentsProblem(cfg: Config, allowed: Set<string>): { problem: string | null; warnings: string[] } {
795
+ const agents = cfg.review.agents;
796
+ const warnings = agents
797
+ .filter(a => !allowed.has(a))
798
+ .map(a => `review.agents lists "${a}", which is not in "## Allowed" of ${cfg.paths.subagents}; it cannot run a review spawn`);
799
+ const problem = allowed.size === 0 || agents.some(a => allowed.has(a))
800
+ ? null
801
+ : `no review.agents entry is in "## Allowed" of ${cfg.paths.subagents}: set review.agents to an allowed agent in config.yml`;
802
+ return { problem, warnings };
803
+ }
804
+
788
805
  export const CANCELLED_REL = "docs/plans/CANCELLED.md";
789
806
  export function globalCancelledPath(): string {
790
807
  return process.env.QUEUE_CANCELLED ?? `${agentDir()}/CANCELLED.md`;
@@ -1015,7 +1032,8 @@ export function queueSummary(index = INDEX, reviewSince = ""): string {
1015
1032
  if (at === undefined || plans[at - 1]!.status !== "open") continue;
1016
1033
  waits.push(`waits on #${at}`);
1017
1034
  }
1018
- const flags = [status, hold, ...waits, p.priorityId ?? ""].filter(Boolean).join(", ");
1035
+ const done = p.phases.total ? `${p.phases.done}/${p.phases.total} done` : "";
1036
+ const flags = [status, done, hold, ...waits, p.priorityId ?? ""].filter(Boolean).join(", ");
1019
1037
  const goal = items(sections(p.text).get("goal") ?? "")[0]?.slice(0, 100) ?? "";
1020
1038
  lines.push(` ${i + 1}. ${p.file} [${flags}] ${goal}`);
1021
1039
  });
@@ -1,6 +1,6 @@
1
1
  import type { Config } from "./config.ts";
2
2
  import { applyQueueEnv } from "./queue/env.ts";
3
- import { activePlans, queueProblems, queueSummary } from "./queue/lib.ts";
3
+ import { activePlans, allowedAgents, queueProblems, queueSummary, reviewAgentsProblem } from "./queue/lib.ts";
4
4
  import { mrSweep } from "./mr-sweep.ts";
5
5
 
6
6
  // One index (20261024_1400_one_index): the main index lists plan files directly, so there are no
@@ -15,6 +15,13 @@ export function queueCheck(args: string[], cfg: Config): number {
15
15
  console.log(queueSummary(undefined, cfg.review.since));
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.since).length > 0;
18
+ // P4d (plan 20261028_1600): a review spawn needs a review.agents entry that Main may spawn.
19
+ const review = reviewAgentsProblem(cfg, allowedAgents(cfg.paths.subagents));
20
+ if (review.problem) {
21
+ console.log(`review gate: ${review.problem}`);
22
+ fail = true;
23
+ }
24
+ for (const w of review.warnings) console.log(`warning: ${w}`);
18
25
  if (!args.includes("--no-mr-sweep")) {
19
26
  try {
20
27
  const sweep = mrSweep();
@@ -150,7 +150,7 @@ autonomy:
150
150
 
151
151
  review: # plan review gate (plan 20261028_1600): reuse lines now, reviewer PASS from P2 (docs/config.md)
152
152
  since: "2026-10-28" # plans stamped before this ISO date are exempt from the reuse-line and reviewer-PASS gates; "" = off
153
- agents: ["reviewer"] # agents allowed to run a review spawn: the PASS exemption needs one plus the brief's `Plan review:` line
153
+ 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
154
154
  mr_cache_minutes: 10 # minutes the spawn gate caches a repo's open-MR list in <queue_state>/mr-cache.json; 0 = no cache
155
155
 
156
156
  ui:
@@ -14,16 +14,14 @@ Stop and report within ~20 tool calls.
14
14
  ## Task
15
15
  1. Read the plan whole, then every file it cites — each `## Reuse` line's `checked: <path>:<n>` opened at that path:line, confirming the cited code is what the line claims.
16
16
  2. For each unticked phase, grep the repo for code that already does that phase's job; a phase re-doing existing code is redundant.
17
- 3. List the repo's open MRs (`glab mr list`, or `gh pr list`) and compare each diff with the phases. Name every open MR on its own line here:
18
- MR !<N>: <what it holds> — this task: <why this review does not redo it>
19
- 4. Judge the plan's design for: secrets or credentials in examples, auth and input-trust mistakes, wasteful work (needless dependencies, duplicate state, what an existing guard or config key already covers).
17
+ 3. Judge the plan's design for: secrets or credentials in examples, auth and input-trust mistakes, wasteful work (needless dependencies, duplicate state, what an existing guard or config key already covers).
20
18
 
21
19
  ## Report
22
20
  Append one entry to the plan's `## Progress` — the PASS is recorded by plan-guard from that subagent edit only (Main can never write it), and it expires when the plan text changes:
23
21
 
24
- PLAN REVIEW: PASS|FAIL — redundant: <finding or none, file:line> — inefficient: <finding or none, file:line> — insecure: <finding or none, file:line> — MRs: <finding or none, file:line>
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>
25
23
 
26
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).
27
25
 
28
26
  ## Acceptance
29
- - the plan's `## Progress` holds the one `PLAN REVIEW:` entry with all four fields and a `Findings:` line
27
+ - the plan's `## Progress` holds the one `PLAN REVIEW:` entry with all three fields and a `Findings:` line