neurastream 0.2.48 → 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,16 @@ 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. |
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. |
34
36
  | Machine health (`machine-guard`, `main-start`, `heavy-run`) | Load, free memory, disk and `/tmp` limits; one heavy test run at a time. |
35
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. |
36
38
  | Session rollover | When the main session file passes 5 MB, or the installed neurastream version differs from the running plugin, Main writes a handoff note; a fresh session then starts on its own under `neurastream main`. |
@@ -76,7 +78,7 @@ Check the merged result:
76
78
  neurastream config --json
77
79
  ```
78
80
 
79
- 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`.
80
82
 
81
83
  ## Skill pack
82
84
 
@@ -131,7 +133,7 @@ One setting decides how much Main does without asking: `autonomy.tier` in the co
131
133
 
132
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`.
133
135
 
134
- 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.
135
137
 
136
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.
137
139
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.48",
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, 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.
@@ -1340,6 +1350,22 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
1340
1350
  else adapterLog(cfg, `WRITE-CHECK deferred still present: ${steers.join(" | ")}`);
1341
1351
  });
1342
1352
 
1353
+ // Terminal hand-back (plan 20261028_1545 P2): a willContinue agent_end keeps the turn going
1354
+ // (blocked stop, todo/plan-mode continuation, deferred hand-back), so only its absence ends
1355
+ // the turn — the per-turn call budget resets for the next one.
1356
+ pi.on("agent_end", (e, ctx) => {
1357
+ if (!isMain(ctx)) return;
1358
+ if (asRecord(e).willContinue === true) return;
1359
+ resetMainCalls();
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
+ });
1368
+
1343
1369
  // omp is really shutting down: the exit-grace fallback must not fire.
1344
1370
  pi.on("session_shutdown", () => clearGrace?.());
1345
1371
 
@@ -1526,5 +1552,6 @@ export default function ompExtension(pi: ExtensionHost): void {
1526
1552
  // no config read. `neurastream main` sets it for its child (launch.ts), so anything the Main
1527
1553
  // session spawns inherits it and stays guarded.
1528
1554
  if (process.env[MAIN_ENV] !== "1") return;
1529
- createOmpAdapter(pi, loadConfig());
1555
+ const initial = loadConfig();
1556
+ createOmpAdapter(pi, initial, reloadingConfig(initial, configFile(), () => loadConfig(), line => adapterLog(initial, line)));
1530
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";
@@ -113,6 +113,12 @@ export interface Config {
113
113
  sub_max_calls: number;
114
114
  /** Highest per-spawn `Call budget: <N>` a task brief may set. */
115
115
  sub_max_calls_cap: number;
116
+ /** Main tool calls per turn that draw the wrap-up warning (plan 20261028_1545 P1). */
117
+ main_warn_calls: number;
118
+ /** Main tool calls per turn before refusal; 0 = off. */
119
+ main_max_calls: number;
120
+ /** Tools the per-turn call cap never counts and never refuses: the ways out of a turn. */
121
+ main_call_exempt_tools: string[];
116
122
  main_edit_limit: number;
117
123
  main_window_min: number;
118
124
  unlock_minutes: number;
@@ -313,6 +319,32 @@ export function configFile(home = homedir()): string {
313
319
  return join(home, ".config", "neurastream", "config.yml");
314
320
  }
315
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
+
316
348
  function isObj(v: unknown): v is Record<string, unknown> {
317
349
  return typeof v === "object" && v !== null && !Array.isArray(v);
318
350
  }
@@ -446,6 +478,10 @@ function check(cfg: Config): void {
446
478
  if (cfg.guards.sub_warn_calls > cfg.guards.sub_max_calls) {
447
479
  throw new ConfigError("guards.sub_warn_calls must be <= guards.sub_max_calls");
448
480
  }
481
+ // 0 = off: the warn band has no cap to stay under, so the default warn loads untouched.
482
+ if (cfg.guards.main_max_calls > 0 && cfg.guards.main_warn_calls > cfg.guards.main_max_calls) {
483
+ throw new ConfigError("guards.main_warn_calls must be <= guards.main_max_calls");
484
+ }
449
485
  if (cfg.guards.sub_max_calls_cap < cfg.guards.sub_max_calls) {
450
486
  throw new ConfigError("guards.sub_max_calls_cap must be >= guards.sub_max_calls");
451
487
  }
@@ -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 {
@@ -74,6 +80,8 @@ export const CANCEL_TODO =
74
80
  interface EditWindow {
75
81
  used: string[];
76
82
  windowStart: number;
83
+ /** Main tool calls since the last owner prompt or terminal hand-back (main_call_exempt_tools never count). */
84
+ mainCalls: number;
77
85
  }
78
86
 
79
87
  function windowFile(): string {
@@ -82,10 +90,11 @@ function windowFile(): string {
82
90
 
83
91
  export function readWindow(): EditWindow {
84
92
  try {
85
- const w = JSON.parse(readFileSync(windowFile(), "utf8")) as EditWindow;
86
- if (Array.isArray(w.used) && typeof w.windowStart === "number") return w;
93
+ const w = JSON.parse(readFileSync(windowFile(), "utf8")) as Partial<EditWindow>;
94
+ if (Array.isArray(w.used) && typeof w.windowStart === "number")
95
+ return { used: w.used, windowStart: w.windowStart, mainCalls: typeof w.mainCalls === "number" ? w.mainCalls : 0 };
87
96
  } catch {}
88
- return { used: [], windowStart: 0 };
97
+ return { used: [], windowStart: 0, mainCalls: 0 };
89
98
  }
90
99
 
91
100
  export function writeWindow(w: EditWindow): void {
@@ -132,6 +141,7 @@ interface PlanReview {
132
141
  hash: string;
133
142
  finding: string;
134
143
  at: number;
144
+ by?: string;
135
145
  }
136
146
 
137
147
  function planReviewsFile(): string {
@@ -162,25 +172,30 @@ export function reviewHash(text: string): string {
162
172
  .outsideProgress(text)
163
173
  .split("\n")
164
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
165
176
  .join("\n"),
166
177
  );
167
178
  }
168
179
 
169
- /** The progress entry that records a review; only a subagent's edit can carry one. */
170
- 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";
171
187
 
172
188
  /**
173
189
  * P2 (plan 20261028_1600): a spawn on a plan needs a recorded reviewer PASS whose hash still
174
190
  * matches the plan text — progress-only edits keep a PASS valid, any other change expires it,
175
191
  * a FAIL is denied with its first finding. A review spawn itself — an agent from review.agents
176
- * 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
177
193
  * before `review.since` (P4c: same cutover as the reuse-line gate).
178
194
  */
179
- 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 {
180
196
  const reviews = readPlanReviews();
181
- const reviewLines = brief.split("\n").filter(l => l.startsWith("Plan review:"));
182
197
  for (const file of named) {
183
- 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;
184
199
  if (!q.reviewApplies(file, cfg.review.since)) continue;
185
200
  const rec = reviews[file];
186
201
  if (!rec) return `plan ${file} has no current reviewer PASS. Spawn a reviewer with templates/plan-review-brief.md.`;
@@ -200,16 +215,128 @@ export function reviewPassProblem(named: string[], brief: string, agent: string,
200
215
  function recordReviews(e: PlanEditEvent, cfg: Config): void {
201
216
  const entries = newProgressEntries(e.before, e.after).filter(b => REVIEW_LINE.test(b));
202
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;
203
222
  const reviews = readPlanReviews();
204
223
  for (const block of entries) {
205
- reviews[e.path] = {
206
- verdict: block.startsWith("- PLAN REVIEW: PASS") ? "PASS" : "FAIL",
207
- hash: reviewHash(e.after),
208
- finding: findingsValue(block) ?? "",
209
- at: nowSec(),
210
- };
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 };
211
231
  }
212
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.`;
213
340
  }
214
341
 
215
342
  function spawnsFile(): string {
@@ -679,7 +806,9 @@ export function spawnProblem(
679
806
  staffing: Record<string, string[]> = {},
680
807
  runningJobs?: string[],
681
808
  runner: CommandRunner = defaultRunner,
809
+ spawner: Spawner = "main",
682
810
  ): string | null {
811
+ const roles: Record<string, string | null> = {};
683
812
  const tasks = Array.isArray(input?.tasks) ? input.tasks : [];
684
813
  const context = String(input?.context ?? "");
685
814
  const allowed = q.allowedAgents();
@@ -696,7 +825,10 @@ export function spawnProblem(
696
825
  const pending = pendingWorkProblem(plans, `${context}\n${String(t?.task ?? "")}`, cfg, runner);
697
826
  if (pending) return `${label}: ${pending}`;
698
827
  // The task's own `Call budget:` line wins over the shared context's.
699
- 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);
700
832
  if (review) return `${label}: ${review}`;
701
833
  const budget = briefBudget(String(t?.task ?? "")) ?? shared;
702
834
  if (budget !== null) {
@@ -728,7 +860,9 @@ export function spawnProblem(
728
860
  cfg,
729
861
  String((tasks[0] && (tasks[0].name ?? tasks[0].agent)) ?? "task"),
730
862
  );
731
- return gate;
863
+ if (gate) return gate;
864
+ for (const [name, plan] of Object.entries(roles)) recordReviewSpawn(name, plan);
865
+ return null;
732
866
  }
733
867
 
734
868
  function runBlockers(plan: Plan, hit: string[], e: ToolEvent, cfg: Config): string | null {
@@ -771,13 +905,14 @@ function runsCloser(input: Record<string, unknown>): boolean {
771
905
  });
772
906
  }
773
907
 
908
+ const bin = (w: string | undefined) => (w ?? "").replace(/^["']+|["']+$/g, "").split("/").pop() ?? "";
909
+
774
910
  // True when a command segment starts the owner page (plan 20261024_2230 P3c): `neurastream ui`
775
911
  // serves it and `systemctl --user start/restart/enable` of neurastream-ui relaunches it — the
776
912
  // owner's systemd moves, never an agent's, unlocked or not. Segment splitting and launcher
777
913
  // skipping match runsCloser, so `sh -c "neurastream ui"` and `sudo systemctl --user ...` are seen.
778
914
  function startsOwnerUi(input: Record<string, unknown>): boolean {
779
915
  const text = Object.values(input).filter((v): v is string => typeof v === "string").join("\n");
780
- const bin = (w: string | undefined) => (w ?? "").replace(/^["']+|["']+$/g, "").split("/").pop() ?? "";
781
916
  return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
782
917
  const words = seg.trim().split(/\s+/).filter(Boolean).map(w => w.replace(/^["'(]+|["')]+$/g, ""));
783
918
  let i = 0;
@@ -946,26 +1081,64 @@ function incidentSpawnProblem(label: string, brief: string, namedPlans: string[]
946
1081
  );
947
1082
  }
948
1083
 
949
- function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): Decision {
950
- 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;
951
1116
  const pending = q.cancelPending();
952
1117
  if (pending) {
953
- log(cfg.paths.guard_log, `BLOCK spawn: cancel pending (${pending.words})`);
954
- 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}"`;
955
1120
  }
956
- const files: string[] = [];
957
- const budgets: Record<string, number | null> = {};
958
- const staffing: Record<string, string[]> = {};
959
- const why = spawnProblem(input, cfg, files, budgets, staffing, e.runningJobs);
1121
+ const [why, named] = planGate(command, entry, cfg);
960
1122
  if (why) {
961
- log(cfg.paths.guard_log, `BLOCK spawn: ${why}`);
962
- return deny(`main-guard: ${why}`);
1123
+ log(cfg.paths.guard_log, `BLOCK bypass launch: ${why}`);
1124
+ return why;
963
1125
  }
964
- const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
965
- if (inc) return deny(`main-guard: ${inc}`);
966
- recordSpawns(files, staffing);
967
- recordBudgets(budgets);
968
- 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;
969
1142
  }
970
1143
  if (cfg.guards.shell_tools.includes(e.tool)) {
971
1144
  // Strict landing gate (20261025_1940 P2, P5): in tier strict every push/merge waits for the
@@ -977,26 +1150,53 @@ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): De
977
1150
  return deny(`main-guard: tier strict — type "${cfg.autonomy.go_phrase}" to approve one push/merge`);
978
1151
  }
979
1152
  const command = String(input?.command ?? input?.code ?? "");
980
- for (const entry of cfg.guards.bypass_spawn) {
981
- if (!bypassRegExp(entry).test(command)) continue;
982
- const pending = q.cancelPending();
983
- if (pending) {
984
- log(cfg.paths.guard_log, `BLOCK bypass launch: cancel pending (${pending.words})`);
985
- return deny(`main-guard: ${CANCEL_TODO} Flagged: "${pending.words}"`);
986
- }
987
- const [why, named] = planGate(command, entry, cfg);
988
- if (why) {
989
- log(cfg.paths.guard_log, `BLOCK bypass launch: ${why}`);
990
- return deny(`main-guard: ${why}`);
991
- }
992
- const inc = incidentSpawnProblem("bypass launch", command, named, cfg);
993
- if (inc) return deny(`main-guard: ${inc}`);
994
- if (named.length) recordSpawns(named);
995
- }
1153
+ const why = bypassLaunch(command, cfg, "main");
1154
+ if (why) return deny(`main-guard: ${why}`);
996
1155
  }
997
1156
  return editWindow(e, input, cfg);
998
1157
  }
999
1158
 
1159
+ // Main's per-turn call cap (plan 20261028_1545 P2): the sub call-cap shape — warn at
1160
+ // main_warn_calls, hard stop at main_max_calls — over calls counted in the window state file
1161
+ // since the last real owner prompt or Main's terminal hand-back. The file, not the adapter's
1162
+ // session memory, is the counter: one-shot CLI calls and a reloaded plugin must see the same
1163
+ // count, and the reset points (checkInject here, the adapter's terminal agent_end) already write
1164
+ // this file. Off in tier full (same gate as editWindow) and at main_max_calls 0.
1165
+
1166
+ /** The per-turn call cap applies to this call: on, not tier full, and the tool is not exempt. */
1167
+ function mainCallApplies(e: ToolEvent, cfg: Config): boolean {
1168
+ return cfg.guards.main_max_calls > 0 && currentTier(cfg) !== "full" && !cfg.guards.main_call_exempt_tools.includes(e.tool);
1169
+ }
1170
+
1171
+ /** Refusal once this turn has spent main_max_calls, or null. */
1172
+ function mainCallStop(e: ToolEvent, cfg: Config): string | null {
1173
+ if (!mainCallApplies(e, cfg)) return null;
1174
+ const w = readWindow();
1175
+ if (w.mainCalls >= cfg.guards.main_max_calls)
1176
+ return `main-guard: call ${w.mainCalls}/${cfg.guards.main_max_calls} since the owner's last message or your last hand-back (guards.main_max_calls). End your turn with the answer, or spawn an implementer.`;
1177
+ return null;
1178
+ }
1179
+
1180
+ /** Count one allowed, non-exempt call; returns the warn-band inject at main_warn_calls, "" below it. */
1181
+ function mainCallWarn(e: ToolEvent, cfg: Config): string {
1182
+ if (!mainCallApplies(e, cfg)) return "";
1183
+ const w = readWindow();
1184
+ w.mainCalls += 1;
1185
+ writeWindow(w);
1186
+ if (w.mainCalls >= cfg.guards.main_warn_calls)
1187
+ return `main-guard: call ${w.mainCalls}/${cfg.guards.main_max_calls} this turn (guards.main_warn_calls). End your turn with the answer, or spawn an implementer.`;
1188
+ return "";
1189
+ }
1190
+
1191
+ /** Main's terminal hand-back (the adapter's agent_end without willContinue): the turn is over, so
1192
+ * the next one starts at 0 calls. The edit window keeps its own reset rules. */
1193
+ export function resetMainCalls(): void {
1194
+ const w = readWindow();
1195
+ if (w.mainCalls === 0) return;
1196
+ w.mainCalls = 0;
1197
+ writeWindow(w);
1198
+ }
1199
+
1000
1200
  /** A live plan file (archived plans excluded); Main's plan-text checks run on these. */
1001
1201
  export const MAIN_PLAN_FILE = /\/docs\/plans\/(?!archive\/)[^/]+\.md$/;
1002
1202
 
@@ -1005,6 +1205,11 @@ export const MAIN_PLAN_FILE = /\/docs\/plans\/(?!archive\/)[^/]+\.md$/;
1005
1205
  * plus, for Main, the spawn gates and the project-file edit window.
1006
1206
  */
1007
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
+ }
1008
1213
  if (cfg.guards.skip_tools.includes(e.tool)) return ALLOW;
1009
1214
  const input = e.input ?? {};
1010
1215
  // Starting the owner page (plan 20261024_2230 P3c) is the owner's systemd move, never an
@@ -1019,7 +1224,15 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
1019
1224
  const paths: string[] = [];
1020
1225
  for (const p of [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)]) if (!paths.includes(p)) paths.push(p);
1021
1226
  const writes: string[] = [];
1022
- 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
+ }
1023
1236
  // Notify secrets: no agent, main or sub, reads a webhook URL — with or without the unlock.
1024
1237
  // A call that changes a secret is not a read: its target goes through the protected-write
1025
1238
  // rule above, so the owner's unlock covers it like any guard file.
@@ -1052,10 +1265,17 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
1052
1265
  log(cfg.paths.plan_guard_log, `BLOCK main tool=${e.tool} shell write to plan ${shellPlan}`);
1053
1266
  return deny(`plan-guard: ${shellPlan} is a plan file: change it with the edit or write tool (close or cancel it with queue-close / queue-cancel).`);
1054
1267
  }
1268
+ const stop = mainCallStop(e, cfg);
1269
+ if (stop) {
1270
+ log(cfg.paths.guard_log, `BLOCK tool=${e.tool} after ${readWindow().mainCalls} calls this turn`);
1271
+ return deny(stop);
1272
+ }
1055
1273
  const d = mainTool(e, input, cfg);
1274
+ if (!d.allow) return d;
1275
+ const warn = mainCallWarn(e, cfg);
1056
1276
  // A task brief names paths it does not read; only the other tools' paths count as reads.
1057
- if (d.allow && e.tool !== "task") recordMainReads(paths.filter(p => !writes.includes(p)));
1058
- return d;
1277
+ if (e.tool !== "task") recordMainReads(paths.filter(p => !writes.includes(p)));
1278
+ return warn ? { ...d, inject: d.inject ? `${d.inject}\n${warn}` : warn } : d;
1059
1279
  }
1060
1280
  const cap = subCallCap(e.agentId, cfg);
1061
1281
  const why = subRules(e, input, paths, writes, cfg, cap);
@@ -1063,6 +1283,14 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
1063
1283
  log(cfg.paths.plan_guard_log, `BLOCK sub:${e.agentId} tool=${e.tool} ${why}`);
1064
1284
  return deny(`plan-guard: ${why}`);
1065
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
+ }
1066
1294
  const n = e.calls + 1;
1067
1295
  // The warn band has the global width (sub_max_calls - sub_warn_calls) ending at the cap;
1068
1296
  // unbudgeted subs keep sub_warn_calls exactly.
@@ -1188,7 +1416,12 @@ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = d
1188
1416
  log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${pendingWork}`)
1189
1417
  return deny(`main-guard: ${pendingWork}`)
1190
1418
  }
1191
- 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");
1192
1425
  if (review) {
1193
1426
  log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${review}`);
1194
1427
  return deny(`main-guard: ${review}`);
@@ -1209,6 +1442,7 @@ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = d
1209
1442
  const staffing: Record<string, string[]> = {};
1210
1443
  for (const f of named) staffing[f] = [e.agent];
1211
1444
  recordSpawns(named, staffing);
1445
+ if (e.name) recordReviewSpawn(e.name, role.plan);
1212
1446
  return ALLOW;
1213
1447
  }
1214
1448
 
@@ -1242,7 +1476,7 @@ export function flagCancel(text: string, cfg: Config): string {
1242
1476
  export function checkInject(e: InjectEvent, cfg: Config): Decision {
1243
1477
  if (e.agent !== "main") return ALLOW;
1244
1478
  const continuation = e.inject.trimStart().startsWith("main-guard:");
1245
- if (!continuation) writeWindow({ used: [], windowStart: 0 });
1479
+ if (!continuation) writeWindow({ used: [], windowStart: 0, mainCalls: 0 });
1246
1480
  recordOwnerMessage(e.inject, cfg);
1247
1481
  let summary: string;
1248
1482
  try {
@@ -1303,6 +1537,19 @@ export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1303
1537
  restore: { path: e.path, text: e.before },
1304
1538
  };
1305
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
+ }
1306
1553
  recordFindings(e, cfg);
1307
1554
  recordReviews(e, cfg);
1308
1555
  return ALLOW;
@@ -1366,6 +1613,15 @@ export function findingsValue(block: string): string | null {
1366
1613
  // Main's plan text outside "## Progress" must rest on files Main read itself (planReadProblems).
1367
1614
  // An empty `before` means the plan file did not exist yet; a refusal then deletes it.
1368
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
+ }
1369
1625
  if (q.outsideProgress(e.after) === q.outsideProgress(e.before)) {
1370
1626
  recordFindings(e, cfg, "main-finding");
1371
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();
@@ -34,4 +34,4 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
34
34
 
35
35
  Guard files are locked for every agent; the owner unlocks with `touch {{AGENT_DIR}}/.guard-unlock` (30 min), or — when `guards.chat_unlock` is on in the config — by typing `unlock 30` in chat (`lock` closes it again).
36
36
 
37
- Autonomy tiers: the owner sets how much Main does unattended with one word — `tier strict` (edit cap `autonomy.strict_edit_limit`; every `git push`, `glab mr merge` or `gh pr merge` also waits until the owner types the approve phrase from `autonomy.go_phrase` (default `go push`; a bare `go` is an ordinary message), which approves exactly one landing for `autonomy.go_minutes` minutes), `tier opinionated` (the limits above), or `tier full` (no edit cap, and a `Priority skip: <plan> — Main: "<reason>"` line with a reason of at least four words may skip an idle higher plan). Pushes stay owner-ruled in strict and opinionated as above; whatever the tier, guard files, the phone page, notify secrets and the unlock stay owner-only.
37
+ Autonomy tiers: the owner sets how much Main does unattended with one word — `tier strict` (edit cap `autonomy.strict_edit_limit`, at most `guards.main_max_calls` tool calls per turn; every `git push`, `glab mr merge` or `gh pr merge` also waits until the owner types the approve phrase from `autonomy.go_phrase` (default `go push`; a bare `go` is an ordinary message), which approves exactly one landing for `autonomy.go_minutes` minutes), `tier opinionated` (the limits above), or `tier full` (no edit cap or call cap, and a `Priority skip: <plan> — Main: "<reason>"` line with a reason of at least four words may skip an idle higher plan). Pushes stay owner-ruled in strict and opinionated as above; whatever the tier, guard files, the phone page, notify secrets and the unlock stay owner-only.
@@ -116,6 +116,9 @@ guards:
116
116
  sub_warn_calls: 90
117
117
  sub_max_calls: 100
118
118
  sub_max_calls_cap: 200
119
+ main_warn_calls: 12 # Main tool calls per turn that draw the wrap-up warning
120
+ main_max_calls: 15 # Main tool calls per turn before refusal; 0 = off
121
+ main_call_exempt_tools: [task, todo, ask, wait] # never counted, never refused at the cap: delegating, tracking and asking stay open
119
122
  main_edit_limit: 5
120
123
  main_window_min: 15
121
124
  unlock_minutes: 30
@@ -147,7 +150,7 @@ autonomy:
147
150
 
148
151
  review: # plan review gate (plan 20261028_1600): reuse lines now, reviewer PASS from P2 (docs/config.md)
149
152
  since: "2026-10-28" # plans stamped before this ISO date are exempt from the reuse-line and reviewer-PASS gates; "" = off
150
- 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
151
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
152
155
 
153
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