neurastream 0.2.47 → 0.2.49

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
@@ -29,7 +29,9 @@ flowchart LR
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. |
32
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. |
34
+ | 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. |
33
35
  | Machine health (`machine-guard`, `main-start`, `heavy-run`) | Load, free memory, disk and `/tmp` limits; one heavy test run at a time. |
34
36
  | 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. |
35
37
  | 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`. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.47",
3
+ "version": "0.2.49",
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",
@@ -178,7 +178,7 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env,
178
178
  if (seen.has(file.live)) continue;
179
179
  seen.add(file.live);
180
180
  if (!existsSync(file.live)) {
181
- problems.push(`missing: ${file.live}`);
181
+ problems.push(`missing: ${file.live} — run: neurastream adapter install omp`);
182
182
  continue;
183
183
  }
184
184
  if (isPackageFile(file.live, file.source)) {
@@ -23,10 +23,10 @@ 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
25
  import { loadConfig, type Config } from "../../core/config.ts";
26
- import { checkWrite, type WriteCheckConfig } from "../../core/write-check.ts";
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 } 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";
@@ -579,6 +579,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
579
579
  const calls = new Map<string, number>(); // subagent call budget, by agent id
580
580
  const pending = new Map<string, Map<string, string>>(); // toolCallId -> plan snapshots
581
581
  const pendingWrite = new Map<string, Map<string, string | null>>(); // toolCallId -> write-check snapshots; null: the file did not exist
582
+ 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
582
583
  const pendingRules = new Set<string>(); // repos Main worked in, rules to hand over at the next prompt
583
584
  // Chat notify (plans 20261024_2155, 20261025_0130): the text a hand-back already posted
584
585
  // (attempted) — one post per distinct text, never a retry loop. The reply itself comes from
@@ -963,6 +964,18 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
963
964
  const r = checkWrite(file, before, after, cfg.write_check);
964
965
  if (r.allow) {
965
966
  if (r.note) adapterLog(cfg, r.note);
967
+ // Per session (Main's review): the turn-end follow-up judges this session's files from
968
+ // the state before the first deferred addition, and the note rides the result so the
969
+ // agent that made the edit learns of the deferral in-band.
970
+ if (r.deferred) {
971
+ const key = c.id ?? "main";
972
+ let files = deferredWrite.get(key);
973
+ if (!files) deferredWrite.set(key, files = new Map());
974
+ if (!files.has(file)) files.set(file, before);
975
+ if (r.note) notes.push(r.note);
976
+ }
977
+ // Parallel calls on one file: their "before" becomes this allowed result, so a later refusal restores to it.
978
+ for (const other of pendingWrite.values()) if (other.has(file)) other.set(file, after);
966
979
  continue;
967
980
  }
968
981
  try {
@@ -1303,6 +1316,38 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
1303
1316
  deliverOwnerInbox(pi, cfg);
1304
1317
  notifyWaitingPlans();
1305
1318
  });
1319
+ // Write-check deferral (I-20261028-166): at a session's own turn end its still-present deferred
1320
+ // findings go out — Main by steer (the only session sendUserMessage is proven to reach), a
1321
+ // subagent through the adapter log; cleared per session, so it is never repeated.
1322
+ pi.on("agent_end", (_e, ctx) => {
1323
+ const c = asCtx(ctx);
1324
+ const wc = cfg.write_check;
1325
+ const key = c.id ?? "main";
1326
+ const files = deferredWrite.get(key);
1327
+ if (!wc.enabled || (wc.applies_to !== "all" && c.kind !== "sub") || !files || files.size === 0) return;
1328
+ const steers: string[] = [];
1329
+ for (const [file, before] of files) {
1330
+ let after: string | null = null;
1331
+ try {
1332
+ after = readFileSync(file, "utf8");
1333
+ } catch {}
1334
+ const s = deferSteer(file, before, after, wc);
1335
+ if (s) steers.push(s);
1336
+ }
1337
+ deferredWrite.delete(key);
1338
+ if (steers.length === 0) return;
1339
+ if (!c.hasAgent || c.kind === "main") pi.sendUserMessage(steers.join("\n"));
1340
+ else adapterLog(cfg, `WRITE-CHECK deferred still present: ${steers.join(" | ")}`);
1341
+ });
1342
+
1343
+ // Terminal hand-back (plan 20261028_1545 P2): a willContinue agent_end keeps the turn going
1344
+ // (blocked stop, todo/plan-mode continuation, deferred hand-back), so only its absence ends
1345
+ // the turn — the per-turn call budget resets for the next one.
1346
+ pi.on("agent_end", (e, ctx) => {
1347
+ if (!isMain(ctx)) return;
1348
+ if (asRecord(e).willContinue === true) return;
1349
+ resetMainCalls();
1350
+ });
1306
1351
 
1307
1352
  // omp is really shutting down: the exit-grace fallback must not fire.
1308
1353
  pi.on("session_shutdown", () => clearGrace?.());
@@ -1,11 +1,11 @@
1
1
  import { existsSync, readFileSync, statSync } from "node:fs";
2
2
  import { basename, dirname } from "node:path";
3
3
  import type { Config } from "./config.ts";
4
- import { briefBudget } from "./guards.ts";
4
+ import { briefBudget, briefNamesPending } from "./guards.ts";
5
5
  import { exitText, helpDoc, printText } from "./help.ts";
6
- import { sections } from "./queue/lib.ts";
6
+ import { readIndex, sections } from "./queue/lib.ts";
7
7
 
8
- const OUTPUT_HINT = /(report|progress|review|handoff|log|brief)[\w\-]*\.(md|log|txt|json)$|\.log$/;
8
+ const OUTPUT_HINT = /(report|progress|review|handoff|log|brief)[\w-]*\.(md|log|txt|json)$|\.log$/;
9
9
  const TICKED_PHASE = /^\s*[-*]\s+\[[xX]\]/;
10
10
 
11
11
  // A plan's paths are live work only in the header lines, Goal, Forbidden, Blockers, unticked phase
@@ -34,6 +34,9 @@ function escapeReg(s: string): string {
34
34
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
35
35
  }
36
36
 
37
+ /** A scanned path without its trailing sentence punctuation (the path loop's cleaning). */
38
+ const clean = (raw: string): string => raw.replace(/[.,)]+$/, "");
39
+
37
40
  function lint(path: string, cfg: Config): { errs: string[]; warns: string[] } {
38
41
  const text = readFileSync(path, "utf8");
39
42
  const low = text.toLowerCase();
@@ -71,8 +74,8 @@ function lint(path: string, cfg: Config): { errs: string[]; warns: string[] } {
71
74
  const re = new RegExp(`(${escapeReg(prefix)}[\\w./\\-]+)`, "g");
72
75
  for (const hit of scan.matchAll(re)) paths.add(hit[1]!);
73
76
  }
74
- for (const raw of [...paths].sort()) {
75
- let p = raw.replace(/[.,)]+$/, "");
77
+ for (const raw of [...paths].toSorted()) {
78
+ const p = clean(raw);
76
79
  if (p.endsWith("-") || p.endsWith("_")) continue;
77
80
  if (existsSync(p) || OUTPUT_HINT.test(p)) continue;
78
81
  const parent = dirname(p);
@@ -83,6 +86,69 @@ function lint(path: string, cfg: Config): { errs: string[]; warns: string[] } {
83
86
  }
84
87
  }
85
88
 
89
+ // P4 (plan 20261028_1600): a spawn brief naming an open MR/PR in prose must carry the pending-work
90
+ // line for it, else the prose alone redoes the MR's work (INCIDENT I-20261028-125). Plans are
91
+ // exempt: the spawn-side gate (guards pendingWorkProblem) matches the brief's line against the
92
+ // plan's own MRs and branches instead.
93
+ if (!sections(text).has("progress")) {
94
+ const toks = new Set<string>();
95
+ for (const m of text.matchAll(/!\d+/g)) toks.add(m[0]); // GitLab MR !N is an MR reference alone
96
+ for (const m of text.matchAll(/\b(?:MR|PR) (#\d+)/g)) toks.add(m[1]!); // a bare #N is prose noise ("INDEX #2")
97
+ for (const tok of toks) {
98
+ need(
99
+ briefNamesPending(text, "MR", tok),
100
+ `MR ${tok} is named in prose; a spawn on its plan must carry the line "MR ${tok}: <what it holds> — this task: <why not overlapping>"`,
101
+ );
102
+ }
103
+ }
104
+
105
+ // P4b (INCIDENT I-20261028-149): a helper wrote its Progress into the worktree copy of the plan
106
+ // and committed it there. Worktrees share the work roots with main checkouts, so the plan's main
107
+ // checkout is wherever the queue index lists it (paths.queue_index, read with the queue's own
108
+ // readIndex): the brief must name an indexed plan path, and a same-basename docs/plans path is
109
+ // the worktree copy. (INCIDENT I-20261028-153): the plan's scope blocker did not allow a file
110
+ // the brief told the helper to change — when a plan blocker script carries ALLOWED='…', every
111
+ // src/tests path the brief names must be inside it.
112
+ if (/\bplans?\b/i.test(text)) {
113
+ const indexed = readIndex(cfg.paths.queue_index);
114
+ const noPlanLine = "no line names the plan's absolute path in its main checkout (paths.queue_index)";
115
+ const planPaths = [...paths].map(clean).filter(p => /\/docs\/plans\/[\w.-]+\.md$/.test(p));
116
+ const named = planPaths.filter(p => indexed.includes(p));
117
+ if (indexed.length && !named.length) {
118
+ const copy = planPaths[0];
119
+ if (copy) {
120
+ const main = indexed.find(p => basename(p) === basename(copy));
121
+ errs.push(
122
+ main
123
+ ? `worktree path ${copy} is the plan's copy; name the main checkout's copy ${main} (paths.queue_index)`
124
+ : noPlanLine,
125
+ );
126
+ } else errs.push(noPlanLine);
127
+ }
128
+ const planFile = named.find(p => existsSync(p));
129
+ if (planFile) {
130
+ const blockersDir = cfg.paths.blockers.replace(/\/+$/, "");
131
+ for (const line of (sections(readFileSync(planFile, "utf8")).get("blockers") ?? "").split("\n")) {
132
+ const name = /^[-*]\s+(\S+)\s*$/.exec(line.trim())?.[1];
133
+ if (!name) continue;
134
+ const script = `${blockersDir}/${name}`;
135
+ if (!existsSync(script)) continue;
136
+ const m = /^ALLOWED=['"](.+)['"]\s*$/m.exec(readFileSync(script, "utf8"));
137
+ if (!m) continue;
138
+ let allowed: RegExp;
139
+ try {
140
+ allowed = new RegExp(m[1]!);
141
+ } catch {
142
+ continue; // a blocker with a broken ALLOWED regex is that blocker's bug, not this brief's
143
+ }
144
+ for (const raw of paths) {
145
+ const rel = /\/((?:src|tests)\/[\w./-]+)$/.exec(clean(raw))?.[1];
146
+ if (rel && !allowed.test(rel)) errs.push(`plan blocker ${name} does not allow ${rel} (its ALLOWED regex rejects it)`);
147
+ }
148
+ }
149
+ }
150
+ }
151
+
86
152
  // The brief's call-budget rule: either the classic "stop within ~N calls" line or a Main-set
87
153
  // per-spawn `Call budget: <N>` line counts.
88
154
  need(
@@ -101,7 +167,7 @@ function lint(path: string, cfg: Config): { errs: string[]; warns: string[] } {
101
167
  const re = new RegExp(`(${escapeReg(prefix)}[\\w./\\-]*keys[\\w.\\-]*\\.txt)`, "g");
102
168
  for (const hit of text.matchAll(re)) keys.add(hit[1]!);
103
169
  }
104
- for (const p of [...keys].sort()) {
170
+ for (const p of [...keys].toSorted()) {
105
171
  if (!existsSync(p)) continue;
106
172
  const n = readFileSync(p, "utf8").split(/\r?\n/).filter(l => l.trim()).length;
107
173
  if (n > cfg.brief.max_keys) {
@@ -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;
@@ -159,6 +165,15 @@ export interface Config {
159
165
  };
160
166
  /** The owner's phone page (`neurastream ui`): binds the tailnet address only. */
161
167
  ui: { enabled: boolean; port: number; owner_login: string };
168
+ /** Plan review gate (plan 20261028_1600): reuse lines and, from P2 on, the reviewer PASS lock. */
169
+ review: {
170
+ /** Plans stamped before this ISO date are exempt from the reuse-line and reviewer-PASS gates; "" = off. */
171
+ since: string;
172
+ /** Agents a review spawn may run under: the PASS exemption needs one of these plus the brief's `Plan review: <plan>` line. */
173
+ agents: string[];
174
+ /** Minutes the spawn gate caches a repo's open-MR list in <queue_state>/mr-cache.json; 0 = no cache. */
175
+ mr_cache_minutes: number;
176
+ };
162
177
  /** Static pages hosted over the tailnet. */
163
178
  pages: { enabled: boolean; port: number; dir: string; keep_days: number };
164
179
  /** Repo-local HTML explainers under docs/knowledge/ (owner page Knowledge tab). */
@@ -437,6 +452,10 @@ function check(cfg: Config): void {
437
452
  if (cfg.guards.sub_warn_calls > cfg.guards.sub_max_calls) {
438
453
  throw new ConfigError("guards.sub_warn_calls must be <= guards.sub_max_calls");
439
454
  }
455
+ // 0 = off: the warn band has no cap to stay under, so the default warn loads untouched.
456
+ if (cfg.guards.main_max_calls > 0 && cfg.guards.main_warn_calls > cfg.guards.main_max_calls) {
457
+ throw new ConfigError("guards.main_warn_calls must be <= guards.main_max_calls");
458
+ }
440
459
  if (cfg.guards.sub_max_calls_cap < cfg.guards.sub_max_calls) {
441
460
  throw new ConfigError("guards.sub_max_calls_cap must be >= guards.sub_max_calls");
442
461
  }
@@ -447,6 +466,8 @@ function check(cfg: Config): void {
447
466
  if (wc.applies_to !== "sub" && wc.applies_to !== "all") throw new ConfigError('write_check.applies_to must be "sub" or "all"');
448
467
  if (!(wc.timeout_ms > 0)) throw new ConfigError("write_check.timeout_ms must be > 0");
449
468
  if (!Array.isArray(wc.linters)) throw new ConfigError("write_check.linters must be a list");
469
+ if (!Array.isArray(wc.defer_rules) || wc.defer_rules.some((r) => typeof r !== "string" || r === ""))
470
+ throw new ConfigError("write_check.defer_rules must be a list of non-empty rule names");
450
471
  const regexes: [string, unknown][] = [["write_check.suppress", wc.suppress]];
451
472
  for (const [i, l] of wc.linters.entries()) {
452
473
  const at = `write_check.linters[${i}]`;
@@ -472,6 +493,11 @@ function check(cfg: Config): void {
472
493
  throw new ConfigError(`guards.plan_offer: not a valid regex: ${cfg.guards.plan_offer}`);
473
494
  }
474
495
  if (!(cfg.rollover.max_session_mb > 0)) throw new ConfigError("rollover.max_session_mb must be > 0");
496
+ if (typeof cfg.review.since !== "string") throw new ConfigError("review.since must be an ISO date string (\"\" = off)");
497
+ if (!Array.isArray(cfg.review.agents) || cfg.review.agents.some(a => typeof a !== "string" || !a.trim()))
498
+ throw new ConfigError('review.agents must be a list of agent names allowed to run review spawns (default ["reviewer"])');
499
+ if (!Number.isInteger(cfg.review.mr_cache_minutes) || cfg.review.mr_cache_minutes < 0)
500
+ throw new ConfigError("review.mr_cache_minutes must be an integer >= 0 (minutes the spawn gate caches a repo's open-MR list; 0 = no cache)");
475
501
  if (cfg.autonomy.tier !== "strict" && cfg.autonomy.tier !== "opinionated" && cfg.autonomy.tier !== "full")
476
502
  throw new ConfigError('autonomy.tier must be "strict", "opinionated" or "full"');
477
503
  if (!Number.isInteger(cfg.autonomy.strict_edit_limit) || cfg.autonomy.strict_edit_limit < 1)
@@ -25,11 +25,13 @@ import { execFileSync } from "node:child_process";
25
25
  import { appendFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
26
26
  import path from "node:path";
27
27
  import type { Decision, InjectEvent, PlanEditEvent, SpawnEvent, StopEvent, ToolEvent } from "./adapter.ts";
28
- import { currentTier, takeGo, type Tier } from "./autonomy.ts";
28
+ import { currentTier, takeGo } from "./autonomy.ts";
29
29
  import { approvalProblem } from "./plan-approval.ts";
30
30
  import type { Config } from "./config.ts";
31
31
  import { addIncident, openIncidents, ownerMessagesFile, ownerSaid, readOwnerMessages, type IncidentView, type OwnerMessage } from "./incidents.ts";
32
32
  import { notifyProtectedPaths, notifySecretReadHit } from "./notify.ts";
33
+ import { defaultRunner, listOpenMrs, mentioned, type CommandRunner, type OpenMr } from "./mr-sweep.ts";
34
+ import { unlandedRows } from "./wip-check.ts";
33
35
  import * as q from "./queue/lib.ts";
34
36
  import type { Plan } from "./queue/lib.ts";
35
37
 
@@ -72,6 +74,8 @@ export const CANCEL_TODO =
72
74
  interface EditWindow {
73
75
  used: string[];
74
76
  windowStart: number;
77
+ /** Main tool calls since the last owner prompt or terminal hand-back (main_call_exempt_tools never count). */
78
+ mainCalls: number;
75
79
  }
76
80
 
77
81
  function windowFile(): string {
@@ -80,10 +84,11 @@ function windowFile(): string {
80
84
 
81
85
  export function readWindow(): EditWindow {
82
86
  try {
83
- const w = JSON.parse(readFileSync(windowFile(), "utf8")) as EditWindow;
84
- if (Array.isArray(w.used) && typeof w.windowStart === "number") return w;
87
+ const w = JSON.parse(readFileSync(windowFile(), "utf8")) as Partial<EditWindow>;
88
+ if (Array.isArray(w.used) && typeof w.windowStart === "number")
89
+ return { used: w.used, windowStart: w.windowStart, mainCalls: typeof w.mainCalls === "number" ? w.mainCalls : 0 };
85
90
  } catch {}
86
- return { used: [], windowStart: 0 };
91
+ return { used: [], windowStart: 0, mainCalls: 0 };
87
92
  }
88
93
 
89
94
  export function writeWindow(w: EditWindow): void {
@@ -95,6 +100,121 @@ export function writeWindow(w: EditWindow): void {
95
100
  }
96
101
  }
97
102
 
103
+ // --- plan review gate state (plan 20261028_1600): the open-MR cache beside the edit window ---
104
+
105
+ interface MrCache {
106
+ at: number;
107
+ repos: Record<string, OpenMr[]>;
108
+ }
109
+
110
+ function mrCacheFile(): string {
111
+ return path.join(q.STATE_DIR, "mr-cache.json");
112
+ }
113
+
114
+ function readMrCache(): MrCache {
115
+ try {
116
+ const c = JSON.parse(readFileSync(mrCacheFile(), "utf8")) as MrCache;
117
+ if (typeof c.at === "number" && c.repos && typeof c.repos === "object") return c;
118
+ } catch {}
119
+ return { at: 0, repos: {} };
120
+ }
121
+
122
+ function writeMrCache(c: MrCache, cfg: Config): void {
123
+ try {
124
+ mkdirSync(q.STATE_DIR, { recursive: true });
125
+ writeFileSync(mrCacheFile(), JSON.stringify(c, null, 1));
126
+ } catch (err) {
127
+ log(cfg.paths.guard_log, `cannot write ${mrCacheFile()}: ${err}`);
128
+ }
129
+ }
130
+
131
+ // --- plan review gate state (plan 20261028_1600): the reviewer PASS record beside the edit window ---
132
+
133
+ interface PlanReview {
134
+ verdict: "PASS" | "FAIL";
135
+ hash: string;
136
+ finding: string;
137
+ at: number;
138
+ }
139
+
140
+ function planReviewsFile(): string {
141
+ return path.join(q.STATE_DIR, "plan-reviews.json");
142
+ }
143
+
144
+ function readPlanReviews(): Record<string, PlanReview> {
145
+ try {
146
+ const r = JSON.parse(readFileSync(planReviewsFile(), "utf8")) as { reviews?: Record<string, PlanReview> };
147
+ if (r.reviews && typeof r.reviews === "object") return r.reviews;
148
+ } catch {}
149
+ return {};
150
+ }
151
+
152
+ function writePlanReviews(reviews: Record<string, PlanReview>, cfg: Config): void {
153
+ try {
154
+ mkdirSync(q.STATE_DIR, { recursive: true });
155
+ writeFileSync(planReviewsFile(), JSON.stringify({ reviews }, null, 1));
156
+ } catch (err) {
157
+ log(cfg.paths.plan_guard_log, `cannot write ${planReviewsFile()}: ${err}`);
158
+ }
159
+ }
160
+
161
+ /** What a PASS covers: the plan text outside "## Progress" without the Main-only lines, so progress notes never expire a review. */
162
+ export function reviewHash(text: string): string {
163
+ return q.sha(
164
+ q
165
+ .outsideProgress(text)
166
+ .split("\n")
167
+ .filter(l => !MAIN_ONLY_LINE.test(l))
168
+ .join("\n"),
169
+ );
170
+ }
171
+
172
+ /** The progress entry that records a review; only a subagent's edit can carry one. */
173
+ const REVIEW_LINE = /^- PLAN REVIEW: (PASS|FAIL)/;
174
+
175
+ /**
176
+ * P2 (plan 20261028_1600): a spawn on a plan needs a recorded reviewer PASS whose hash still
177
+ * matches the plan text — progress-only edits keep a PASS valid, any other change expires it,
178
+ * 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
180
+ * before `review.since` (P4c: same cutover as the reuse-line gate).
181
+ */
182
+ export function reviewPassProblem(named: string[], brief: string, agent: string, cfg: Config): string | null {
183
+ const reviews = readPlanReviews();
184
+ const reviewLines = brief.split("\n").filter(l => l.startsWith("Plan review:"));
185
+ for (const file of named) {
186
+ if (cfg.review.agents.includes(agent) && reviewLines.some(l => l.slice("Plan review:".length).trim() === file)) continue;
187
+ if (!q.reviewApplies(file, cfg.review.since)) continue;
188
+ const rec = reviews[file];
189
+ if (!rec) return `plan ${file} has no current reviewer PASS. Spawn a reviewer with templates/plan-review-brief.md.`;
190
+ if (rec.verdict === "FAIL")
191
+ return `plan ${file} has no current reviewer PASS (FAIL: ${rec.finding || "no finding recorded"}). Spawn a reviewer with templates/plan-review-brief.md.`;
192
+ let text = "";
193
+ try {
194
+ text = readFileSync(file, "utf8");
195
+ } catch {}
196
+ if (rec.hash !== reviewHash(text))
197
+ return `plan ${file} has no current reviewer PASS (changed since review). Spawn a reviewer with templates/plan-review-brief.md.`;
198
+ }
199
+ return null;
200
+ }
201
+
202
+ /** A subagent's `PLAN REVIEW: PASS|FAIL` entry records the review of the plan it edited; Main's edit path never reaches this. */
203
+ function recordReviews(e: PlanEditEvent, cfg: Config): void {
204
+ const entries = newProgressEntries(e.before, e.after).filter(b => REVIEW_LINE.test(b));
205
+ if (!entries.length) return;
206
+ const reviews = readPlanReviews();
207
+ 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
+ };
214
+ }
215
+ writePlanReviews(reviews, cfg);
216
+ }
217
+
98
218
  function spawnsFile(): string {
99
219
  return path.join(q.STATE_DIR, "spawns.json");
100
220
  }
@@ -316,7 +436,7 @@ function unticked(p: Plan): string[] {
316
436
 
317
437
  // Plans an implementer brief may run on; returns [reason, null] or [null, plan files].
318
438
  export function planGate(text: string, label: string, cfg?: Config): [string | null, string[]] {
319
- const plans = q.activePlans();
439
+ const plans = q.activePlans(undefined, undefined, cfg?.review.since ?? "");
320
440
  const unclosed = plans.filter(p => (p.status === "complete" || p.status === "cancelled") && !q.awaitingMerge(p));
321
441
  if (unclosed.length)
322
442
  return [
@@ -440,6 +560,70 @@ function priorityGate(named: string[], runningJobs: string[] | undefined, brief:
440
560
  return outcome?.problem ? `${label}: ${outcome.problem}` : null;
441
561
  }
442
562
 
563
+ /** The brief names pending work the P3 way: `MR !N: <what it holds> — this task: <why not overlapping>` (GitHub `#N`), `Branch <name>: …`. */
564
+ export function briefNamesPending(brief: string, prefix: "MR" | "Branch", token: string): boolean {
565
+ const esc = token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
566
+ return new RegExp(`^[ \\t]*(?:[-*][ \\t]+)?${prefix} ${esc}:[^\\n]*this task:`, "im").test(brief);
567
+ }
568
+
569
+ /** The branch a linked worktree has checked out, or null. */
570
+ function worktreeBranch(wt: string | null, run: CommandRunner): string | null {
571
+ if (!wt) return null;
572
+ const r = run(["git", "-C", wt, "rev-parse", "--abbrev-ref", "HEAD"], {});
573
+ return r.code === 0 ? r.stdout.trim() || null : null;
574
+ }
575
+
576
+ /**
577
+ * P3 (plan 20261028_1600): done-but-not-merged work must be named by the brief before a spawn
578
+ * runs on its plan. (a) open MRs of the plan's repo that the plan mentions (mr-sweep's lister and
579
+ * `mentioned`; the list is cached `review.mr_cache_minutes`); (b) the plan's `Branch:` line or its
580
+ * worktree's checked-out branch when wip-check reports it UNLANDED — still enforced when the forge
581
+ * is unreachable, whose degrade skips only (a), like the sweep. A repo with no origin remote has
582
+ * no merge target: both checks skip it with one guard-log line.
583
+ */
584
+ export function pendingWorkProblem(named: string[], brief: string, cfg: Config, run: CommandRunner = defaultRunner): string | null {
585
+ const plans = q.activePlans().filter(p => named.includes(p.file));
586
+ if (!plans.length) return null;
587
+ const cache = readMrCache();
588
+ const fresh = nowSec() - cache.at < cfg.review.mr_cache_minutes * 60;
589
+ const openMrs = new Map<string, OpenMr[]>();
590
+ const hasOrigin = new Set<string>();
591
+ let cacheDirty = false;
592
+ for (const repo of new Set(plans.map(p => p.repo))) {
593
+ if (fresh && cache.repos[repo]) {
594
+ openMrs.set(repo, cache.repos[repo]);
595
+ hasOrigin.add(repo);
596
+ continue;
597
+ }
598
+ const listed = listOpenMrs(repo, run);
599
+ if (!listed.ok) {
600
+ log(cfg.paths.guard_log, `pending-work: ${repo}: ${listed.why}; the open-MR check is skipped`);
601
+ if (listed.why !== "no origin remote") hasOrigin.add(repo); // forge down still enforces (b)
602
+ continue;
603
+ }
604
+ openMrs.set(repo, listed.mrs);
605
+ hasOrigin.add(repo);
606
+ cache.repos[repo] = listed.mrs;
607
+ cacheDirty = true;
608
+ }
609
+ if (cacheDirty) writeMrCache({ at: nowSec(), repos: cache.repos }, cfg);
610
+ const unlanded = hasOrigin.size ? new Set(unlandedRows(run(["wip-check"], {}).stdout).map(r => r.branch)) : null;
611
+ for (const p of plans) {
612
+ // (a) only MRs the plan itself mentions are pending work here: the sweep already flags
613
+ // unmentioned open MRs as UNTRACKED for the whole queue.
614
+ for (const mr of openMrs.get(p.repo) ?? []) {
615
+ if (!mentioned(mr.token, mr.branch, [p.text]) || briefNamesPending(brief, "MR", mr.token)) continue;
616
+ return `plan ${p.file} has pending work MR ${mr.token} not merged; say in the brief what it already holds and why this task does not redo it ("MR ${mr.token}: <what it holds> — this task: <why not overlapping>").`;
617
+ }
618
+ if (!unlanded || !hasOrigin.has(p.repo)) continue;
619
+ for (const b of [p.branch, worktreeBranch(p.worktree, run)]) {
620
+ if (!b || !unlanded.has(b) || briefNamesPending(brief, "Branch", b)) continue;
621
+ return `plan ${p.file} has pending work branch ${b} not merged; say in the brief what it already holds and why this task does not redo it ("Branch ${b}: <what it holds> — this task: <why not overlapping>").`;
622
+ }
623
+ }
624
+ return null;
625
+ }
626
+
443
627
  /**
444
628
  * The owner's pick order (plan 20261025_1700 P3): refuse a later `ledger.prefer` agent while an
445
629
  * earlier one is free and under its provider cap, unless the brief carries "Pick note: <why>".
@@ -480,8 +664,8 @@ export function providerClaimProblem(text: string, cfg: Config): string | null {
480
664
  if (free(provider) && !names.has(agent) && provider !== null) names.set(agent, provider);
481
665
  }
482
666
  if (!names.size || !/\bis\b/i.test(text)) return null;
483
- const esc = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
484
- const m = new RegExp(`\\b(${[...names.keys()].map(esc).join("|")})\\b[^.\\n]{0,80}?\\b(?:is|are)\\s+(?:still\\s+|now\\s+)?(?:rate[ -]?limited|rate limiting|throttled|out until|limited)`, "i").exec(text);
667
+
668
+ const m = new RegExp(`\\b(${[...names.keys()].map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})\\b[^.\\n]{0,80}?\\b(?:is|are)\\s+(?:still\\s+|now\\s+)?(?:rate[ -]?limited|rate limiting|throttled|out until|limited)`, "i").exec(text);
485
669
  if (!m) return null;
486
670
  const hit = [...names.entries()].find(([n]) => n.toLowerCase() === (m[1] ?? "").toLowerCase());
487
671
  if (hit === undefined) return null;
@@ -497,6 +681,7 @@ export function spawnProblem(
497
681
  budgets: Record<string, number | null> = {},
498
682
  staffing: Record<string, string[]> = {},
499
683
  runningJobs?: string[],
684
+ runner: CommandRunner = defaultRunner,
500
685
  ): string | null {
501
686
  const tasks = Array.isArray(input?.tasks) ? input.tasks : [];
502
687
  const context = String(input?.context ?? "");
@@ -509,7 +694,13 @@ export function spawnProblem(
509
694
  if (!allowed.has(agent)) return `${label}: agent "${agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`;
510
695
  const [why, plans] = planGate(`${context}\n${String(t?.task ?? "")}`, label, cfg);
511
696
  if (why) return why;
697
+ // P3 (plan 20261028_1600): the task tool is the live spawn path; every task carries its own
698
+ // pending-work check, before the call-wide gates below.
699
+ const pending = pendingWorkProblem(plans, `${context}\n${String(t?.task ?? "")}`, cfg, runner);
700
+ if (pending) return `${label}: ${pending}`;
512
701
  // 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);
703
+ if (review) return `${label}: ${review}`;
513
704
  const budget = briefBudget(String(t?.task ?? "")) ?? shared;
514
705
  if (budget !== null) {
515
706
  if (!t?.name) return `${label}: "Call budget: ${budget}" needs a task name (the budget is keyed by it).`;
@@ -628,9 +819,9 @@ const PLACEHOLDER = "[REDACTED:";
628
819
  const PLACEHOLDER_FILES = [/\/src\/core\/secret-redact\.ts$/, /\/tests\/secret-redact[^/]*\.test\.ts$/];
629
820
  /** What a write/edit/ast_edit call would add: every text argument but the targets and the replaced text. */
630
821
  function addedText(input: Record<string, unknown>): string {
631
- const skip = ["path", "file", "cwd", "old_string", "old", "oldText", "i"];
822
+ const skip = new Set(["path", "file", "cwd", "old_string", "old", "oldText", "i"]);
632
823
  return Object.entries(input)
633
- .filter(([key, value]) => typeof value === "string" && !skip.includes(key))
824
+ .filter(([key, value]) => typeof value === "string" && !skip.has(key))
634
825
  .map(([, value]) => value as string)
635
826
  .join("\n");
636
827
  }
@@ -809,6 +1000,47 @@ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): De
809
1000
  return editWindow(e, input, cfg);
810
1001
  }
811
1002
 
1003
+ // Main's per-turn call cap (plan 20261028_1545 P2): the sub call-cap shape — warn at
1004
+ // main_warn_calls, hard stop at main_max_calls — over calls counted in the window state file
1005
+ // since the last real owner prompt or Main's terminal hand-back. The file, not the adapter's
1006
+ // session memory, is the counter: one-shot CLI calls and a reloaded plugin must see the same
1007
+ // count, and the reset points (checkInject here, the adapter's terminal agent_end) already write
1008
+ // this file. Off in tier full (same gate as editWindow) and at main_max_calls 0.
1009
+
1010
+ /** The per-turn call cap applies to this call: on, not tier full, and the tool is not exempt. */
1011
+ function mainCallApplies(e: ToolEvent, cfg: Config): boolean {
1012
+ return cfg.guards.main_max_calls > 0 && currentTier(cfg) !== "full" && !cfg.guards.main_call_exempt_tools.includes(e.tool);
1013
+ }
1014
+
1015
+ /** Refusal once this turn has spent main_max_calls, or null. */
1016
+ function mainCallStop(e: ToolEvent, cfg: Config): string | null {
1017
+ if (!mainCallApplies(e, cfg)) return null;
1018
+ const w = readWindow();
1019
+ if (w.mainCalls >= cfg.guards.main_max_calls)
1020
+ 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.`;
1021
+ return null;
1022
+ }
1023
+
1024
+ /** Count one allowed, non-exempt call; returns the warn-band inject at main_warn_calls, "" below it. */
1025
+ function mainCallWarn(e: ToolEvent, cfg: Config): string {
1026
+ if (!mainCallApplies(e, cfg)) return "";
1027
+ const w = readWindow();
1028
+ w.mainCalls += 1;
1029
+ writeWindow(w);
1030
+ if (w.mainCalls >= cfg.guards.main_warn_calls)
1031
+ 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.`;
1032
+ return "";
1033
+ }
1034
+
1035
+ /** Main's terminal hand-back (the adapter's agent_end without willContinue): the turn is over, so
1036
+ * the next one starts at 0 calls. The edit window keeps its own reset rules. */
1037
+ export function resetMainCalls(): void {
1038
+ const w = readWindow();
1039
+ if (w.mainCalls === 0) return;
1040
+ w.mainCalls = 0;
1041
+ writeWindow(w);
1042
+ }
1043
+
812
1044
  /** A live plan file (archived plans excluded); Main's plan-text checks run on these. */
813
1045
  export const MAIN_PLAN_FILE = /\/docs\/plans\/(?!archive\/)[^/]+\.md$/;
814
1046
 
@@ -864,10 +1096,17 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
864
1096
  log(cfg.paths.plan_guard_log, `BLOCK main tool=${e.tool} shell write to plan ${shellPlan}`);
865
1097
  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).`);
866
1098
  }
1099
+ const stop = mainCallStop(e, cfg);
1100
+ if (stop) {
1101
+ log(cfg.paths.guard_log, `BLOCK tool=${e.tool} after ${readWindow().mainCalls} calls this turn`);
1102
+ return deny(stop);
1103
+ }
867
1104
  const d = mainTool(e, input, cfg);
1105
+ if (!d.allow) return d;
1106
+ const warn = mainCallWarn(e, cfg);
868
1107
  // A task brief names paths it does not read; only the other tools' paths count as reads.
869
- if (d.allow && e.tool !== "task") recordMainReads(paths.filter(p => !writes.includes(p)));
870
- return d;
1108
+ if (e.tool !== "task") recordMainReads(paths.filter(p => !writes.includes(p)));
1109
+ return warn ? { ...d, inject: d.inject ? `${d.inject}\n${warn}` : warn } : d;
871
1110
  }
872
1111
  const cap = subCallCap(e.agentId, cfg);
873
1112
  const why = subRules(e, input, paths, writes, cfg, cap);
@@ -974,7 +1213,7 @@ export function planReadNote(tool: string, input: Record<string, unknown>, cwd:
974
1213
  * spawn: the allow-list, task-only and open-plan gates for one implementer launch. Covers both
975
1214
  * original paths (the extension spawn event and a `task` tool call); the brief names the plan.
976
1215
  */
977
- export function checkSpawn(e: SpawnEvent, cfg: Config): Decision {
1216
+ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = defaultRunner): Decision {
978
1217
  const pending = q.cancelPending();
979
1218
  if (pending) {
980
1219
  log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: cancel pending (${pending.words})`);
@@ -995,6 +1234,16 @@ export function checkSpawn(e: SpawnEvent, cfg: Config): Decision {
995
1234
  log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${gate}`);
996
1235
  return deny(`main-guard: ${gate}`);
997
1236
  }
1237
+ const pendingWork = pendingWorkProblem(named, e.brief, cfg, runner);
1238
+ if (pendingWork) {
1239
+ log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${pendingWork}`)
1240
+ return deny(`main-guard: ${pendingWork}`)
1241
+ }
1242
+ const review = reviewPassProblem(named, e.brief, e.agent, cfg);
1243
+ if (review) {
1244
+ log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${review}`);
1245
+ return deny(`main-guard: ${review}`);
1246
+ }
998
1247
  const inc = incidentSpawnProblem(`spawn ${e.agent}`, e.brief, named, cfg);
999
1248
  if (inc) return deny(`main-guard: ${inc}`);
1000
1249
  // The owner's pick order and live provider state (plan 20261025_1700 P3), before the spawn records.
@@ -1044,11 +1293,11 @@ export function flagCancel(text: string, cfg: Config): string {
1044
1293
  export function checkInject(e: InjectEvent, cfg: Config): Decision {
1045
1294
  if (e.agent !== "main") return ALLOW;
1046
1295
  const continuation = e.inject.trimStart().startsWith("main-guard:");
1047
- if (!continuation) writeWindow({ used: [], windowStart: 0 });
1296
+ if (!continuation) writeWindow({ used: [], windowStart: 0, mainCalls: 0 });
1048
1297
  recordOwnerMessage(e.inject, cfg);
1049
1298
  let summary: string;
1050
1299
  try {
1051
- summary = q.queueSummary();
1300
+ summary = q.queueSummary(undefined, cfg.review.since);
1052
1301
  } catch (err) {
1053
1302
  summary = `Queue unreadable (${q.INDEX}): ${err}`;
1054
1303
  }
@@ -1106,6 +1355,7 @@ export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1106
1355
  };
1107
1356
  }
1108
1357
  recordFindings(e, cfg);
1358
+ recordReviews(e, cfg);
1109
1359
  return ALLOW;
1110
1360
  }
1111
1361
 
@@ -1137,7 +1387,7 @@ function progressEntries(text: string): string[] {
1137
1387
  const lines = q.progressBody(text).split("\n");
1138
1388
  for (let i = 0; i < lines.length; i++) {
1139
1389
  const head = lines[i];
1140
- if (head === undefined || !/^- /.test(head) || MAIN_ONLY_LINE.test(head)) continue;
1390
+ if (head === undefined || !head.startsWith("- ") || MAIN_ONLY_LINE.test(head)) continue;
1141
1391
  const block = [head];
1142
1392
  while (i + 1 < lines.length) {
1143
1393
  const cont = lines[i + 1];
@@ -1331,12 +1581,12 @@ function readMainReads(): Record<string, string> {
1331
1581
  }
1332
1582
 
1333
1583
  // Plans still responsible for: open plans (parked "WAITING on owner" excluded) plus queue problems.
1334
- export function openQueue(): string[] {
1584
+ export function openQueue(reviewSince = ""): string[] {
1335
1585
  const open = q
1336
1586
  .activePlans()
1337
1587
  .filter(p => !p.waiting && !q.awaitingMerge(p))
1338
1588
  .map(p => p.file);
1339
- for (const prob of q.queueProblems()) open.push(`${prob.where}: ${prob.problem}`);
1589
+ for (const prob of q.queueProblems(undefined, undefined, reviewSince)) open.push(`${prob.where}: ${prob.problem}`);
1340
1590
  const unique: string[] = [];
1341
1591
  for (const item of open) if (!unique.includes(item)) unique.push(item);
1342
1592
  return unique;
@@ -1371,7 +1621,7 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
1371
1621
  }
1372
1622
  let open: string[];
1373
1623
  try {
1374
- open = openQueue();
1624
+ open = openQueue(cfg.review.since);
1375
1625
  } catch (err) {
1376
1626
  log(cfg.paths.guard_log, `BLOCK stop: cannot read queue: ${err}`);
1377
1627
  open = [`queue unreadable (${q.INDEX}): ${err}`];
@@ -198,6 +198,38 @@ function skip(repo: string, why: string): string {
198
198
  return `mr-sweep: skipped ${repo} (${why})`;
199
199
  }
200
200
 
201
+ export interface OpenMr {
202
+ forge: Forge;
203
+ number: number;
204
+ token: string;
205
+ branch: string;
206
+ }
207
+
208
+ /** `{ ok: false, why }` is the sweep's degrade: the caller logs it and never treats it as "no MRs". */
209
+ export type OpenMrs = { ok: true; mrs: OpenMr[] } | { ok: false; why: string };
210
+
211
+ /**
212
+ * Open MRs of one repo (the sweep's lister, single-repo): `!N` / `#N` token plus source branch.
213
+ * Everything — origin lookup included — goes through the runner, so callers can inject it.
214
+ */
215
+ export function listOpenMrs(repo: string, run: CommandRunner = defaultRunner, env?: NodeJS.ProcessEnv): OpenMrs {
216
+ const remote = run(["git", "-C", repo, "remote", "get-url", "origin"], { env });
217
+ const url = remote.code === 0 ? remote.stdout.trim() : "";
218
+ if (!url) return { ok: false, why: "no origin remote" };
219
+ const host = remoteHost(url);
220
+ const forge = host ? forgeOf(host) : null;
221
+ if (!forge) return { ok: false, why: "unknown forge" };
222
+ const listed = forge === "gitlab" ? listGitlab(repo, run, env) : listGithub(repo, run, env);
223
+ if (listed.missing) return { ok: false, why: "no forge CLI" };
224
+ if (listed.fail) return { ok: false, why: "forge unreachable" };
225
+ return {
226
+ ok: true,
227
+ mrs: listed.items
228
+ .map(item => ({ forge, number: item.number, token: forge === "gitlab" ? `!${item.number}` : `#${item.number}`, branch: item.branch }))
229
+ .toSorted((a, b) => a.number - b.number),
230
+ };
231
+ }
232
+
201
233
  /**
202
234
  * Open MRs of every repo in the index, marked tracked when an open plan of that repo contains
203
235
  * the `!N` / `#N` token (including `MR !N: ignored`) or the source branch name.
@@ -231,7 +231,41 @@ function headerField(text: string, name: string): string | null {
231
231
  return v ? v.replace(/`/g, "").trim() || null : null;
232
232
  }
233
233
 
234
- export function parsePlan(repo: string, file: string, text: string | null, blockersDir = blockersDirPath()): Plan {
234
+ /** A plan filename stamp (YYYYMMDD_HHMM) as an ISO-ish string ("2026-10-29T01:00") that sorts lexically; "" when unstamped. */
235
+ export function stampIso(file: string): string {
236
+ const m = /^(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})/.exec(path.basename(file));
237
+ return m ? `${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}` : "";
238
+ }
239
+
240
+ /**
241
+ * The review gates (P1 reuse lines, P2 reviewer PASS) apply to a plan stamped at or after the
242
+ * `review.since` cutover — a bare date counts as midnight; `since` "" switches them off.
243
+ */
244
+ export function reviewApplies(file: string, since: string): boolean {
245
+ const cutover = since.length === 10 ? `${since}T00:00` : since;
246
+ return cutover.length > 0 && stampIso(file) >= cutover;
247
+ }
248
+
249
+ /**
250
+ * P1 (plan 20261028_1600): every new thing a plan adds carries a reuse line with a checked
251
+ * `path:line` citation that exists relative to the plan's repo. Plans stamped before the
252
+ * `review.since` cutover are exempt.
253
+ */
254
+ function reuseProblems(repo: string, file: string, secs: Map<string, string>, since: string): string[] {
255
+ if (!reviewApplies(file, since)) return [];
256
+ const lines = items(secs.get("reuse") ?? "");
257
+ if (!lines.length)
258
+ return [`missing or empty "## Reuse" section (one line per new thing: - new: <thing> — checked: <path>:<line> — reuse: <how, or why not>; "- new: none — ..." when nothing is new)`];
259
+ const probs: string[] = [];
260
+ for (const line of lines) {
261
+ const m = /checked:\s*`?([^`\s—]+):(\d+)(?:-\d+)?`?/.exec(line);
262
+ if (!m) probs.push(`reuse line without "checked: <path>:<line>": ${line.slice(0, 80)}`);
263
+ else if (!existsSync(path.resolve(repo, m[1]!))) probs.push(`reuse citation does not exist: ${m[1]}`);
264
+ }
265
+ return probs;
266
+ }
267
+
268
+ export function parsePlan(repo: string, file: string, text: string | null, blockersDir = blockersDirPath(), reviewSince = ""): Plan {
235
269
  const empty = { repo, file, text: "", status: null, blockers: [], doneCheck: null, worktree: null, branch: null, appliesTo: [], waiting: false, waitingLine: null, waitingAsk: null, waitingBlocked: null, waitingWhy: null, waitsOn: [], priorityId: null, title: path.basename(file), goal: [], summary: null, phases: { done: 0, total: 0 }, started: false };
236
270
  if (text === null) return { ...empty, errors: ["plan file listed in the index does not exist"] };
237
271
  const errors: string[] = [];
@@ -243,7 +277,8 @@ export function parsePlan(repo: string, file: string, text: string | null, block
243
277
  const stamp = /^(\d{8}_\d{4})/.exec(path.basename(file))?.[1] ?? "";
244
278
  if (stamp >= READ_CUTOVER && !items(secs.get("code read by main") ?? "").length)
245
279
  errors.push(`missing or empty "## Code read by Main" section (plans stamped ${READ_CUTOVER} or later list each file they cite)`);
246
- const known = new Set([...REQUIRED, "applies to", "background", "code read by main"]);
280
+ for (const problem of reuseProblems(repo, file, secs, reviewSince)) errors.push(problem);
281
+ const known = new Set([...REQUIRED, "applies to", "background", "code read by main", "reuse"]);
247
282
  for (const s of secs.keys()) if (!known.has(s)) errors.push(`unknown section "## ${s}" (allowed: ${[...known].join(", ")})`);
248
283
  const status = statusOf(text);
249
284
  if (!status) errors.push('"## Progress" must start with a line "Status: open", "Status: complete" or "Status: cancelled"');
@@ -295,23 +330,27 @@ export function parsePlan(repo: string, file: string, text: string | null, block
295
330
  };
296
331
  }
297
332
 
298
- /** A plan's repo: the main checkout holding the plan file; a linked worktree resolves to its main repo. */
333
+ /** A plan's repo: the main checkout holding the plan file; a linked worktree resolves to its main repo; without git, an archived plan reports the repo dir above docs/plans/archive/<YYYYMM>, never the month folder. */
299
334
  export function planRepo(file: string): string {
300
- return repoRoot(file) ?? path.dirname(file);
335
+ const root = repoRoot(file);
336
+ if (root) return root;
337
+ const dir = path.dirname(file);
338
+ const m = /^(.*\/)docs\/plans\/archive\/\d{6}$/.exec(dir);
339
+ return m?.[1] ? m[1].replace(/\/$/, "") : dir;
301
340
  }
302
341
 
303
- export function readPlans(files: string[], blockersDir = blockersDirPath()): Plan[] {
342
+ export function readPlans(files: string[], blockersDir = blockersDirPath(), reviewSince = ""): Plan[] {
304
343
  return files.map(file => {
305
344
  let text: string | null = null;
306
345
  try {
307
346
  text = readFileSync(file, "utf8");
308
347
  } catch {}
309
- return parsePlan(planRepo(file), file, text, blockersDir);
348
+ return parsePlan(planRepo(file), file, text, blockersDir, reviewSince);
310
349
  });
311
350
  }
312
351
 
313
- export function activePlans(index = indexPath(), blockersDir = blockersDirPath()): Plan[] {
314
- return readPlans(readIndex(index), blockersDir);
352
+ export function activePlans(index = indexPath(), blockersDir = blockersDirPath(), reviewSince = ""): Plan[] {
353
+ return readPlans(readIndex(index), blockersDir, reviewSince);
315
354
  }
316
355
 
317
356
  /** Owner holds: one line per plan with a WAITING on owner line. The only real holds; the summary, the rollover context and the handoff all read them here. */
@@ -813,14 +852,21 @@ export function finishedEntry(plan: Plan, archived: string, date: string): strin
813
852
  return [`## ${date} · ${path.basename(plan.repo)} · ${plan.title}`, ...body].join("\n");
814
853
  }
815
854
 
816
- /** Inserts the entry above older ones. Returns false when that Plan path is already listed. */
855
+ /** Identity of a finished entry: its repo name and archived plan file name. Worktrees of one repo share it. */
856
+ export function finishedKey(entry: string): string {
857
+ const lines = entry.split("\n");
858
+ const repo = (lines[0] ?? "").split(" · ")[1] ?? "";
859
+ return `${repo}\n${path.basename(lines.find(l => l.startsWith("Plan: ")) ?? "")}`;
860
+ }
861
+
862
+ /** Inserts the entry above older ones. Returns false when that repo's plan file is already listed. */
817
863
  export function prependFinished(entry: string, file = finishedPath()): boolean {
818
- const planLine = entry.split("\n").find(l => l.startsWith("Plan: "));
819
864
  let current = "";
820
865
  try {
821
866
  current = readFileSync(file, "utf8");
822
867
  } catch {}
823
- if (planLine && current.split("\n").includes(planLine)) return false;
868
+ const key = finishedKey(entry);
869
+ if (current.split(/^(?=## )/m).some(b => finishedKey(b) === key)) return false;
824
870
  mkdirSync(path.dirname(file), { recursive: true });
825
871
  const block = entry.endsWith("\n") ? entry : `${entry}\n`;
826
872
  if (!current.trim()) {
@@ -921,10 +967,10 @@ export interface QueueProblem {
921
967
  problem: string;
922
968
  }
923
969
 
924
- export function queueProblems(index = INDEX, blockersDir = BLOCKERS_DIR): QueueProblem[] {
970
+ export function queueProblems(index = INDEX, blockersDir = BLOCKERS_DIR, reviewSince = ""): QueueProblem[] {
925
971
  const probs: QueueProblem[] = [];
926
972
  if (!existsSync(index)) probs.push({ where: index, problem: "main index missing: create it (empty = no open work)" });
927
- const plans = readPlans(readIndex(index), blockersDir);
973
+ const plans = readPlans(readIndex(index), blockersDir, reviewSince);
928
974
  const byWorktree = new Map<string, Plan[]>();
929
975
  for (const p of plans) {
930
976
  for (const e of p.errors) probs.push({ where: p.file, problem: e });
@@ -951,7 +997,7 @@ export function queueProblems(index = INDEX, blockersDir = BLOCKERS_DIR): QueueP
951
997
  return probs;
952
998
  }
953
999
 
954
- export function queueSummary(index = INDEX): string {
1000
+ export function queueSummary(index = INDEX, reviewSince = ""): string {
955
1001
  // Index order IS priority (20261025_0215_index_priority): the list is flat and ranked,
956
1002
  // rank 1 = the index's top line; repos only surface through each plan's own path.
957
1003
  const plans = activePlans(index);
@@ -975,7 +1021,7 @@ export function queueSummary(index = INDEX): string {
975
1021
  });
976
1022
  const nCancelled = repos.reduce((n, repo) => n + readCancelled(repo).length, 0);
977
1023
  if (nCancelled) lines.push(`Cancelled rules: ${nCancelled}`);
978
- const probs = queueProblems(index);
1024
+ const probs = queueProblems(index, BLOCKERS_DIR, reviewSince);
979
1025
  if (probs.length) lines.push(`Problems (fix first):`, ...probs.map(q => ` - ${q.where}: ${q.problem}`));
980
1026
  return lines.join("\n");
981
1027
  }
@@ -12,9 +12,9 @@ export function queueCheck(args: string[], cfg: Config): number {
12
12
  for (const p of activePlans()) if (p.priorityId && !p.waiting && p.status === "open") console.log(p.priorityId);
13
13
  return 0;
14
14
  }
15
- console.log(queueSummary());
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
- let fail = queueProblems().length > 0;
17
+ let fail = queueProblems(undefined, undefined, cfg.review.since).length > 0;
18
18
  if (!args.includes("--no-mr-sweep")) {
19
19
  try {
20
20
  const sweep = mrSweep();
@@ -1,12 +1,12 @@
1
1
  // queue-finished: fill and search FINISHED.md. Backfill reads archived plans; a word prints matches.
2
2
 
3
- import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
3
+ import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
4
4
  import path from "node:path";
5
5
  import type { Config } from "./config.ts";
6
6
  import { applyQueueEnv } from "./queue/env.ts";
7
- import { finishedEntry, finishedPath, parsePlan, planRepo, prependFinished } from "./queue/lib.ts";
7
+ import { finishedEntry, finishedKey, finishedPath, parsePlan, planRepo, prependFinished, repoRoot } from "./queue/lib.ts";
8
8
 
9
- const USAGE = "usage: queue-finished --backfill | queue-finished <word>";
9
+ const USAGE = "usage: queue-finished --backfill | --dedupe | queue-finished <word>";
10
10
 
11
11
  function walkMd(dir: string, out: string[]): void {
12
12
  let names: string[];
@@ -63,7 +63,21 @@ function stampDate(file: string): string {
63
63
 
64
64
  function archivedPlans(roots: string[]): string[] {
65
65
  const files: string[] = [];
66
- for (const repo of repoRoots(roots)) walkMd(path.join(repo, "docs/plans/archive"), files);
66
+ const seen = new Set<string>();
67
+ // Main checkouts sort first; a linked worktree adds only plan file names the main checkout lacks.
68
+ const dirs = repoRoots(roots).map(dir => ({ dir, repo: repoRoot(dir) ?? dir }));
69
+ dirs.sort((a, b) => Number(b.repo === b.dir) - Number(a.repo === a.dir));
70
+ for (const { dir, repo } of dirs) {
71
+ const found: string[] = [];
72
+ walkMd(path.join(dir, "docs/plans/archive"), found);
73
+ for (const file of found) {
74
+ // Same repo + file name = the same plan seen through another worktree; across repos the name may repeat.
75
+ const key = `${repo}\0${path.basename(file)}`;
76
+ if (seen.has(key)) continue;
77
+ seen.add(key);
78
+ files.push(file);
79
+ }
80
+ }
67
81
  return files;
68
82
  }
69
83
 
@@ -91,6 +105,29 @@ function backfill(cfg: Config): number {
91
105
  return 0;
92
106
  }
93
107
 
108
+ /** Keeps the first entry for each finished key and drops later repeats. */
109
+ function dedupe(): number {
110
+ const file = finishedPath();
111
+ let text = "";
112
+ try {
113
+ text = readFileSync(file, "utf8");
114
+ } catch {}
115
+ const seen = new Set<string>();
116
+ const kept: string[] = [];
117
+ let removed = 0;
118
+ for (const block of text.split(/^(?=## )/m)) {
119
+ if (!block.startsWith("## ")) kept.push(block);
120
+ else if (seen.has(finishedKey(block))) removed++;
121
+ else {
122
+ seen.add(finishedKey(block));
123
+ kept.push(block);
124
+ }
125
+ }
126
+ if (removed) writeFileSync(file, kept.join(""));
127
+ console.log(`queue-finished: removed ${removed} duplicate entries`);
128
+ return 0;
129
+ }
130
+
94
131
  function entries(text: string): string[] {
95
132
  return text.split(/^(?=## )/m).filter(p => p.startsWith("## ")).map(p => p.trimEnd());
96
133
  }
@@ -117,6 +154,7 @@ export function queueFinished(args: string[], cfg: Config): number {
117
154
  return 0;
118
155
  }
119
156
  if (args.includes("--backfill")) return backfill(cfg);
157
+ if (args.includes("--dedupe")) return dedupe();
120
158
  const word = args.filter(a => !a.startsWith("-")).join(" ").trim();
121
159
  if (!word) {
122
160
  console.error(USAGE);
@@ -76,3 +76,20 @@ export function wipCheck(args: string[], cfg: Config): number {
76
76
  }
77
77
  return 0;
78
78
  }
79
+
80
+ /** One UNLANDED row of wip-check output: ` <repo-name> <branch> <sha> +<n> <age>h old` (the wipCheck printer owns this format). */
81
+ export function unlandedRows(output: string): { name: string; branch: string }[] {
82
+ const rows: { name: string; branch: string }[] = [];
83
+ let inBlock = false;
84
+ for (const line of output.split("\n")) {
85
+ if (line.startsWith("UNLANDED")) {
86
+ inBlock = true;
87
+ continue;
88
+ }
89
+ if (!inBlock) continue;
90
+ if (!line.startsWith(" ")) break; // the next summary line (DIRTY…) ends the block
91
+ const [name = "", branch = ""] = line.trim().split(/\s+/);
92
+ if (name && branch) rows.push({ name, branch });
93
+ }
94
+ return rows;
95
+ }
@@ -18,15 +18,19 @@ export interface WriteCheckConfig {
18
18
  applies_to: "sub" | "all";
19
19
  timeout_ms: number;
20
20
  suppress: string;
21
+ /** Rules whose new findings do not refuse an edit (I-20261028-166): allowed with a note, reported at turn end. */
22
+ defer_rules: string[];
21
23
  linters: WriteCheckLinter[];
22
24
  }
23
25
 
24
- export type WriteCheckResult = { allow: true; note?: string } | { allow: false; reason: string };
26
+ export type WriteCheckResult = { allow: true; note?: string; deferred?: true } | { allow: false; reason: string };
25
27
 
26
- // Counts per rule key; suppression comments count under SUPPRESSION.
28
+ // Counts per (rule, message) pair, so a rule's old debt never masquerades as the reason for a
29
+ // refusal (I-20261028-150); suppression comments count per matching line under SUPPRESSION.
27
30
  interface Findings {
28
31
  counts: Map<string, number>;
29
32
  samples: Map<string, string>;
33
+ rules: Map<string, string>;
30
34
  }
31
35
 
32
36
  const SUPPRESSION = "suppression";
@@ -34,9 +38,16 @@ const REASON_MAX = 2000;
34
38
  const SAMPLE_MAX = 300;
35
39
  const TAIL = "The file was restored to its state before this edit; fix it and edit again — do not add suppression comments.";
36
40
 
37
- function add(f: Findings, key: string, sample: string): void {
38
- f.counts.set(key, (f.counts.get(key) ?? 0) + 1);
39
- if (!f.samples.has(key)) f.samples.set(key, sample.trim().slice(0, SAMPLE_MAX));
41
+ // A pattern with a `message` group keys findings by (rule, message), so only a finding whose text
42
+ // is new counts as new; without it, counting stays per rule (the older config format).
43
+ function findingKey(rule: string, message: string | undefined): string {
44
+ return message === undefined ? rule : `${rule}\u0000${message}`;
45
+ }
46
+
47
+ function add(f: Findings, k: string, rule: string, sample: string): void {
48
+ f.counts.set(k, (f.counts.get(k) ?? 0) + 1);
49
+ if (!f.samples.has(k)) f.samples.set(k, sample.trim().slice(0, SAMPLE_MAX));
50
+ if (!f.rules.has(k)) f.rules.set(k, rule);
40
51
  }
41
52
 
42
53
  // Runs each linter on `path` and counts its findings. Throws when a linter did not finish
@@ -54,8 +65,9 @@ function lint(path: string, linters: WriteCheckLinter[], wc: WriteCheckConfig, f
54
65
  if (r.error || r.signal) throw new Error(`${cmd} did not finish (${r.error?.message ?? r.signal})`);
55
66
  const re = new RegExp(l.pattern);
56
67
  for (const line of r.stdout.split("\n")) {
57
- const rule = re.exec(line)?.groups?.rule;
58
- if (rule) add(f, rule, line);
68
+ const m = re.exec(line);
69
+ const rule = m?.groups?.rule;
70
+ if (rule) add(f, findingKey(rule, m?.groups?.message), rule, line);
59
71
  }
60
72
  }
61
73
  }
@@ -74,15 +86,12 @@ function lintText(file: string, text: string, linters: WriteCheckLinter[], wc: W
74
86
  }
75
87
 
76
88
  function suppressions(text: string, re: RegExp, f: Findings): void {
77
- for (const line of text.split("\n")) if (re.test(line)) add(f, SUPPRESSION, line);
89
+ for (const line of text.split("\n")) if (re.test(line)) add(f, findingKey(SUPPRESSION, line), SUPPRESSION, line);
78
90
  }
79
91
 
80
- function refusal(file: string, now: Findings, old: Findings): string {
92
+ function refusal(file: string, now: Findings, old: Findings, newKeys: string[]): string {
81
93
  const head = `write-check: this edit adds lint problems to ${file}:`;
82
- const rows = [...now.counts].flatMap(([key, n]) => {
83
- const delta = n - (old.counts.get(key) ?? 0);
84
- return delta > 0 ? [`- ${key} (+${delta}): ${now.samples.get(key)}`] : [];
85
- });
94
+ const rows = newKeys.map((k) => `- ${now.rules.get(k)} (+${(now.counts.get(k) ?? 0) - (old.counts.get(k) ?? 0)}): ${now.samples.get(k)}`);
86
95
  const room = REASON_MAX - head.length - TAIL.length - 2;
87
96
  let body = rows.join("\n");
88
97
  if (body.length > room) body = `${body.slice(0, room - 4)}\n...`;
@@ -93,8 +102,8 @@ export function checkWrite(file: string, before: string | null, after: string |
93
102
  if (after === null || before === after) return { allow: true };
94
103
  const linters = wc.linters.filter((l) => l.ext.includes(extname(file)));
95
104
  if (linters.length === 0) return { allow: true };
96
- const old: Findings = { counts: new Map(), samples: new Map() };
97
- const now: Findings = { counts: new Map(), samples: new Map() };
105
+ const old: Findings = { counts: new Map(), samples: new Map(), rules: new Map() };
106
+ const now: Findings = { counts: new Map(), samples: new Map(), rules: new Map() };
98
107
  try {
99
108
  const re = new RegExp(wc.suppress);
100
109
  if (before !== null) {
@@ -106,7 +115,42 @@ export function checkWrite(file: string, before: string | null, after: string |
106
115
  } catch (err) {
107
116
  return { allow: true, note: `write-check: ${file} not checked (${(err as Error).message}); the edit was allowed` };
108
117
  }
109
- const grew = [...now.counts].some(([key, n]) => n > (old.counts.get(key) ?? 0));
110
- if (!grew) return { allow: true };
111
- return { allow: false, reason: refusal(file, now, old) };
118
+ // A new finding of a deferred rule rides along mid-turn (I-20261028-166): declare-then-use
119
+ // refactors stay possible; the adapter reports what is still there at the turn's end (deferSteer).
120
+ const added = [...now.counts].filter(([k, n]) => n > (old.counts.get(k) ?? 0));
121
+ const real = added.filter(([k]) => !wc.defer_rules.includes(now.rules.get(k) ?? ""));
122
+ if (real.length > 0) return { allow: false, reason: refusal(file, now, old, real.map(([k]) => k)) };
123
+ if (added.length === 0) return { allow: true };
124
+ return {
125
+ allow: true,
126
+ deferred: true,
127
+ note: `write-check: ${file} adds findings under a deferred rule, allowed until turn end:\n${added
128
+ .map(([k]) => `- ${now.rules.get(k)}: ${now.samples.get(k)}`)
129
+ .join("\n")}`,
130
+ };
131
+ }
132
+
133
+ // Turn-end follow-up for deferred findings (I-20261028-166): the adapter holds each file's text from
134
+ // before the turn's first deferred finding and calls this at agent_end; a non-null return becomes
135
+ // one steer listing what is still there. Fixed, deleted, no matching linter, or a linter that did
136
+ // not finish: null — the edit-time rule holds, a missing or crashed linter never blocks.
137
+ export function deferSteer(file: string, before: string | null, after: string | null, wc: WriteCheckConfig): string | null {
138
+ if (after === null || before === after || wc.defer_rules.length === 0) return null;
139
+ const linters = wc.linters.filter((l) => l.ext.includes(extname(file)));
140
+ if (linters.length === 0) return null;
141
+ const old: Findings = { counts: new Map(), samples: new Map(), rules: new Map() };
142
+ const now: Findings = { counts: new Map(), samples: new Map(), rules: new Map() };
143
+ try {
144
+ if (before !== null) lintText(file, before, linters, wc, old);
145
+ lint(file, linters, wc, now);
146
+ } catch {
147
+ return null;
148
+ }
149
+ const rows = [...now.counts].flatMap(([k, n]) =>
150
+ n > (old.counts.get(k) ?? 0) && wc.defer_rules.includes(now.rules.get(k) ?? "")
151
+ ? [`- ${now.rules.get(k)}: ${now.samples.get(k)}`]
152
+ : [],
153
+ );
154
+ if (rows.length === 0) return null;
155
+ return `write-check: ${file} still holds deferred findings added this turn:\n${rows.join("\n")}`;
112
156
  }
@@ -11,6 +11,7 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
11
11
  - Entering a repo: read its AGENTS.md first.
12
12
  - Main writes every plan in `<repo>/docs/plans/`, shaped like `{{AGENT_DIR}}/queue/TEMPLATE.md`. Do the research yourself; never base a plan on another agent's findings.
13
13
  - Phase 0 of every plan: blocker scripts that stop the implementer from going against the plan. They must exist before any spawn.
14
+ - Every plan has `## Reuse`; no spawn without a current reviewer PASS (`templates/plan-review-brief.md`, recorded only from the reviewer's own Progress edit); a brief names every open MR of its plan with an `MR !N:` line.
14
15
  - An open plan gets an implementer subagent. When it claims done, verify (another subagent or yourself). Not done → spawn another implementer for the rest. Done → set `Status: complete`; `queue-close` then archives it and cleans the indexes.
15
16
  - Owner asks about a past plan → grep FINISHED.md first; open the archived plan only for details.
16
17
  - An implementer's new `## Progress` entry ends with a `Findings:` line — `Findings: none`, or one item per finding with `file:line` evidence; plan-guard restores an entry without it, and each item becomes an incident.
@@ -33,4 +34,4 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
33
34
 
34
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).
35
36
 
36
- 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
@@ -145,6 +148,11 @@ autonomy:
145
148
  go_minutes: 10 # minutes the approve phrase approves exactly one push/merge in tier strict
146
149
  go_phrase: "go push" # the whole chat message that approves one push/merge in tier strict (I-20261025-201); a bare `go` is an ordinary message
147
150
 
151
+ review: # plan review gate (plan 20261028_1600): reuse lines now, reviewer PASS from P2 (docs/config.md)
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
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
+
148
156
  ui:
149
157
  enabled: false # the owner's phone page (neurastream ui); binds the tailnet address only
150
158
  port: 7787
@@ -215,13 +223,14 @@ write_check: # write-time lint checks (src/core/write-check.ts):
215
223
  applies_to: sub # "sub" = subagents only; "all" = Main too
216
224
  timeout_ms: 5000 # per linter run; a timeout, crash or missing linter allows the edit and logs a note
217
225
  suppress: '(#|//|/\*)\s*(noqa|type:\s*ignore|oxlint-disable|eslint-disable|biome-ignore|@ts-ignore|@ts-expect-error|@ts-nocheck)' # a new match counts as a new problem; the word only counts inside a comment
226
+ defer_rules: ["no-unused-vars", "F401", "F841"] # a new finding of one of these rules is allowed with a logged note and only reported at turn end if still present (I-20261028-166); [] turns the deferral off
218
227
  linters:
219
228
  - ext: [".py"]
220
229
  argv: ["ruff", "check", "--no-cache", "--output-format=concise", "--select", "E,F,B,S,C90,PERF,SIM", "--ignore", "E501,S101", "{file}"]
221
- pattern: '^.+?:\d+:\d+: (?<rule>\S+) '
230
+ pattern: '^.+?:\d+:\d+: (?<rule>\S+) (?<message>.+)$'
222
231
  - ext: [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"]
223
232
  argv: ["oxlint", "-f", "unix", "-D", "correctness", "-D", "suspicious", "-D", "perf", "{file}"]
224
- pattern: '^.+?:\d+:\d+: .*\[(?:Error|Warning)/(?<rule>[^\]]+)\]'
233
+ pattern: '^.+?:\d+:\d+: (?<message>.+) \[(?:Error|Warning)/(?<rule>[^\]]+)\]'
225
234
 
226
235
  priority:
227
236
  sleep_sec: 120
@@ -0,0 +1,29 @@
1
+ # Plan review: <plan title>
2
+
3
+ Read opus-implementer-method.md first.
4
+ Plan review: <absolute plan path in its main checkout, e.g. <main checkout>/docs/plans/YYYYMMDD_HHMM_name.md>
5
+ Reviewer: read-only — you never edit code, never write repo files, never push, never open an MR. You may write only the plan's `## Progress`, once.
6
+ Stop and report within ~20 tool calls.
7
+
8
+ ## Goal
9
+ - Review P<n> of the plan against its phases: is it free of redundant, inefficient and insecure work before anyone is spawned on it? Name exactly one unticked phase here (the spawn gate requires it).
10
+
11
+ ## Forbidden
12
+ - never push, never open a PR, never edit a file (read-only review)
13
+
14
+ ## Task
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
+ 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).
20
+
21
+ ## Report
22
+ 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
+
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>
25
+
26
+ 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
+
28
+ ## Acceptance
29
+ - the plan's `## Progress` holds the one `PLAN REVIEW:` entry with all four fields and a `Findings:` line