neurastream 0.2.46 → 0.2.48

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,6 +29,7 @@ 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. |
33
34
  | Machine health (`machine-guard`, `main-start`, `heavy-run`) | Load, free memory, disk and `/tmp` limits; one heavy test run at a time. |
34
35
  | 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. |
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env bun
2
+ import { basename } from "node:path";
3
+ import { run } from "../src/cli/dispatch.ts";
4
+
5
+ const invoked = basename(process.argv[1] ?? "");
6
+ process.exit(await run(invoked, process.argv.slice(2)));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.46",
3
+ "version": "0.2.48",
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",
@@ -46,6 +46,7 @@
46
46
  "queue-check": "bin/queue-check",
47
47
  "queue-trim": "bin/queue-trim",
48
48
  "queue-close": "bin/queue-close",
49
+ "queue-finished": "bin/queue-finished",
49
50
  "queue-cancel": "bin/queue-cancel",
50
51
  "main-start": "bin/main-start",
51
52
  "machine-guard": "bin/machine-guard",
@@ -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,7 +23,7 @@ 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
29
  import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, newProgressEntries, planReadNote, recordMainResult, revertMainEdit, rekeySpawnFile } from "../../core/guards.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,29 @@ 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
+ });
1306
1342
 
1307
1343
  // omp is really shutting down: the exit-grace fallback must not fire.
1308
1344
  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) {
@@ -159,6 +159,15 @@ export interface Config {
159
159
  };
160
160
  /** The owner's phone page (`neurastream ui`): binds the tailnet address only. */
161
161
  ui: { enabled: boolean; port: number; owner_login: string };
162
+ /** Plan review gate (plan 20261028_1600): reuse lines and, from P2 on, the reviewer PASS lock. */
163
+ review: {
164
+ /** Plans stamped before this ISO date are exempt from the reuse-line and reviewer-PASS gates; "" = off. */
165
+ since: string;
166
+ /** Agents a review spawn may run under: the PASS exemption needs one of these plus the brief's `Plan review: <plan>` line. */
167
+ agents: string[];
168
+ /** Minutes the spawn gate caches a repo's open-MR list in <queue_state>/mr-cache.json; 0 = no cache. */
169
+ mr_cache_minutes: number;
170
+ };
162
171
  /** Static pages hosted over the tailnet. */
163
172
  pages: { enabled: boolean; port: number; dir: string; keep_days: number };
164
173
  /** Repo-local HTML explainers under docs/knowledge/ (owner page Knowledge tab). */
@@ -447,6 +456,8 @@ function check(cfg: Config): void {
447
456
  if (wc.applies_to !== "sub" && wc.applies_to !== "all") throw new ConfigError('write_check.applies_to must be "sub" or "all"');
448
457
  if (!(wc.timeout_ms > 0)) throw new ConfigError("write_check.timeout_ms must be > 0");
449
458
  if (!Array.isArray(wc.linters)) throw new ConfigError("write_check.linters must be a list");
459
+ if (!Array.isArray(wc.defer_rules) || wc.defer_rules.some((r) => typeof r !== "string" || r === ""))
460
+ throw new ConfigError("write_check.defer_rules must be a list of non-empty rule names");
450
461
  const regexes: [string, unknown][] = [["write_check.suppress", wc.suppress]];
451
462
  for (const [i, l] of wc.linters.entries()) {
452
463
  const at = `write_check.linters[${i}]`;
@@ -472,6 +483,11 @@ function check(cfg: Config): void {
472
483
  throw new ConfigError(`guards.plan_offer: not a valid regex: ${cfg.guards.plan_offer}`);
473
484
  }
474
485
  if (!(cfg.rollover.max_session_mb > 0)) throw new ConfigError("rollover.max_session_mb must be > 0");
486
+ if (typeof cfg.review.since !== "string") throw new ConfigError("review.since must be an ISO date string (\"\" = off)");
487
+ if (!Array.isArray(cfg.review.agents) || cfg.review.agents.some(a => typeof a !== "string" || !a.trim()))
488
+ throw new ConfigError('review.agents must be a list of agent names allowed to run review spawns (default ["reviewer"])');
489
+ if (!Number.isInteger(cfg.review.mr_cache_minutes) || cfg.review.mr_cache_minutes < 0)
490
+ 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
491
  if (cfg.autonomy.tier !== "strict" && cfg.autonomy.tier !== "opinionated" && cfg.autonomy.tier !== "full")
476
492
  throw new ConfigError('autonomy.tier must be "strict", "opinionated" or "full"');
477
493
  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
 
@@ -95,6 +97,121 @@ export function writeWindow(w: EditWindow): void {
95
97
  }
96
98
  }
97
99
 
100
+ // --- plan review gate state (plan 20261028_1600): the open-MR cache beside the edit window ---
101
+
102
+ interface MrCache {
103
+ at: number;
104
+ repos: Record<string, OpenMr[]>;
105
+ }
106
+
107
+ function mrCacheFile(): string {
108
+ return path.join(q.STATE_DIR, "mr-cache.json");
109
+ }
110
+
111
+ function readMrCache(): MrCache {
112
+ try {
113
+ const c = JSON.parse(readFileSync(mrCacheFile(), "utf8")) as MrCache;
114
+ if (typeof c.at === "number" && c.repos && typeof c.repos === "object") return c;
115
+ } catch {}
116
+ return { at: 0, repos: {} };
117
+ }
118
+
119
+ function writeMrCache(c: MrCache, cfg: Config): void {
120
+ try {
121
+ mkdirSync(q.STATE_DIR, { recursive: true });
122
+ writeFileSync(mrCacheFile(), JSON.stringify(c, null, 1));
123
+ } catch (err) {
124
+ log(cfg.paths.guard_log, `cannot write ${mrCacheFile()}: ${err}`);
125
+ }
126
+ }
127
+
128
+ // --- plan review gate state (plan 20261028_1600): the reviewer PASS record beside the edit window ---
129
+
130
+ interface PlanReview {
131
+ verdict: "PASS" | "FAIL";
132
+ hash: string;
133
+ finding: string;
134
+ at: number;
135
+ }
136
+
137
+ function planReviewsFile(): string {
138
+ return path.join(q.STATE_DIR, "plan-reviews.json");
139
+ }
140
+
141
+ function readPlanReviews(): Record<string, PlanReview> {
142
+ try {
143
+ const r = JSON.parse(readFileSync(planReviewsFile(), "utf8")) as { reviews?: Record<string, PlanReview> };
144
+ if (r.reviews && typeof r.reviews === "object") return r.reviews;
145
+ } catch {}
146
+ return {};
147
+ }
148
+
149
+ function writePlanReviews(reviews: Record<string, PlanReview>, cfg: Config): void {
150
+ try {
151
+ mkdirSync(q.STATE_DIR, { recursive: true });
152
+ writeFileSync(planReviewsFile(), JSON.stringify({ reviews }, null, 1));
153
+ } catch (err) {
154
+ log(cfg.paths.plan_guard_log, `cannot write ${planReviewsFile()}: ${err}`);
155
+ }
156
+ }
157
+
158
+ /** What a PASS covers: the plan text outside "## Progress" without the Main-only lines, so progress notes never expire a review. */
159
+ export function reviewHash(text: string): string {
160
+ return q.sha(
161
+ q
162
+ .outsideProgress(text)
163
+ .split("\n")
164
+ .filter(l => !MAIN_ONLY_LINE.test(l))
165
+ .join("\n"),
166
+ );
167
+ }
168
+
169
+ /** The progress entry that records a review; only a subagent's edit can carry one. */
170
+ const REVIEW_LINE = /^- PLAN REVIEW: (PASS|FAIL)/;
171
+
172
+ /**
173
+ * P2 (plan 20261028_1600): a spawn on a plan needs a recorded reviewer PASS whose hash still
174
+ * matches the plan text — progress-only edits keep a PASS valid, any other change expires it,
175
+ * 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
177
+ * before `review.since` (P4c: same cutover as the reuse-line gate).
178
+ */
179
+ export function reviewPassProblem(named: string[], brief: string, agent: string, cfg: Config): string | null {
180
+ const reviews = readPlanReviews();
181
+ const reviewLines = brief.split("\n").filter(l => l.startsWith("Plan review:"));
182
+ for (const file of named) {
183
+ if (cfg.review.agents.includes(agent) && reviewLines.some(l => l.slice("Plan review:".length).trim() === file)) continue;
184
+ if (!q.reviewApplies(file, cfg.review.since)) continue;
185
+ const rec = reviews[file];
186
+ if (!rec) return `plan ${file} has no current reviewer PASS. Spawn a reviewer with templates/plan-review-brief.md.`;
187
+ if (rec.verdict === "FAIL")
188
+ return `plan ${file} has no current reviewer PASS (FAIL: ${rec.finding || "no finding recorded"}). Spawn a reviewer with templates/plan-review-brief.md.`;
189
+ let text = "";
190
+ try {
191
+ text = readFileSync(file, "utf8");
192
+ } catch {}
193
+ if (rec.hash !== reviewHash(text))
194
+ return `plan ${file} has no current reviewer PASS (changed since review). Spawn a reviewer with templates/plan-review-brief.md.`;
195
+ }
196
+ return null;
197
+ }
198
+
199
+ /** A subagent's `PLAN REVIEW: PASS|FAIL` entry records the review of the plan it edited; Main's edit path never reaches this. */
200
+ function recordReviews(e: PlanEditEvent, cfg: Config): void {
201
+ const entries = newProgressEntries(e.before, e.after).filter(b => REVIEW_LINE.test(b));
202
+ if (!entries.length) return;
203
+ const reviews = readPlanReviews();
204
+ 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
+ };
211
+ }
212
+ writePlanReviews(reviews, cfg);
213
+ }
214
+
98
215
  function spawnsFile(): string {
99
216
  return path.join(q.STATE_DIR, "spawns.json");
100
217
  }
@@ -316,7 +433,7 @@ function unticked(p: Plan): string[] {
316
433
 
317
434
  // Plans an implementer brief may run on; returns [reason, null] or [null, plan files].
318
435
  export function planGate(text: string, label: string, cfg?: Config): [string | null, string[]] {
319
- const plans = q.activePlans();
436
+ const plans = q.activePlans(undefined, undefined, cfg?.review.since ?? "");
320
437
  const unclosed = plans.filter(p => (p.status === "complete" || p.status === "cancelled") && !q.awaitingMerge(p));
321
438
  if (unclosed.length)
322
439
  return [
@@ -440,6 +557,70 @@ function priorityGate(named: string[], runningJobs: string[] | undefined, brief:
440
557
  return outcome?.problem ? `${label}: ${outcome.problem}` : null;
441
558
  }
442
559
 
560
+ /** The brief names pending work the P3 way: `MR !N: <what it holds> — this task: <why not overlapping>` (GitHub `#N`), `Branch <name>: …`. */
561
+ export function briefNamesPending(brief: string, prefix: "MR" | "Branch", token: string): boolean {
562
+ const esc = token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
563
+ return new RegExp(`^[ \\t]*(?:[-*][ \\t]+)?${prefix} ${esc}:[^\\n]*this task:`, "im").test(brief);
564
+ }
565
+
566
+ /** The branch a linked worktree has checked out, or null. */
567
+ function worktreeBranch(wt: string | null, run: CommandRunner): string | null {
568
+ if (!wt) return null;
569
+ const r = run(["git", "-C", wt, "rev-parse", "--abbrev-ref", "HEAD"], {});
570
+ return r.code === 0 ? r.stdout.trim() || null : null;
571
+ }
572
+
573
+ /**
574
+ * P3 (plan 20261028_1600): done-but-not-merged work must be named by the brief before a spawn
575
+ * runs on its plan. (a) open MRs of the plan's repo that the plan mentions (mr-sweep's lister and
576
+ * `mentioned`; the list is cached `review.mr_cache_minutes`); (b) the plan's `Branch:` line or its
577
+ * worktree's checked-out branch when wip-check reports it UNLANDED — still enforced when the forge
578
+ * is unreachable, whose degrade skips only (a), like the sweep. A repo with no origin remote has
579
+ * no merge target: both checks skip it with one guard-log line.
580
+ */
581
+ export function pendingWorkProblem(named: string[], brief: string, cfg: Config, run: CommandRunner = defaultRunner): string | null {
582
+ const plans = q.activePlans().filter(p => named.includes(p.file));
583
+ if (!plans.length) return null;
584
+ const cache = readMrCache();
585
+ const fresh = nowSec() - cache.at < cfg.review.mr_cache_minutes * 60;
586
+ const openMrs = new Map<string, OpenMr[]>();
587
+ const hasOrigin = new Set<string>();
588
+ let cacheDirty = false;
589
+ for (const repo of new Set(plans.map(p => p.repo))) {
590
+ if (fresh && cache.repos[repo]) {
591
+ openMrs.set(repo, cache.repos[repo]);
592
+ hasOrigin.add(repo);
593
+ continue;
594
+ }
595
+ const listed = listOpenMrs(repo, run);
596
+ if (!listed.ok) {
597
+ log(cfg.paths.guard_log, `pending-work: ${repo}: ${listed.why}; the open-MR check is skipped`);
598
+ if (listed.why !== "no origin remote") hasOrigin.add(repo); // forge down still enforces (b)
599
+ continue;
600
+ }
601
+ openMrs.set(repo, listed.mrs);
602
+ hasOrigin.add(repo);
603
+ cache.repos[repo] = listed.mrs;
604
+ cacheDirty = true;
605
+ }
606
+ if (cacheDirty) writeMrCache({ at: nowSec(), repos: cache.repos }, cfg);
607
+ const unlanded = hasOrigin.size ? new Set(unlandedRows(run(["wip-check"], {}).stdout).map(r => r.branch)) : null;
608
+ for (const p of plans) {
609
+ // (a) only MRs the plan itself mentions are pending work here: the sweep already flags
610
+ // unmentioned open MRs as UNTRACKED for the whole queue.
611
+ for (const mr of openMrs.get(p.repo) ?? []) {
612
+ if (!mentioned(mr.token, mr.branch, [p.text]) || briefNamesPending(brief, "MR", mr.token)) continue;
613
+ 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>").`;
614
+ }
615
+ if (!unlanded || !hasOrigin.has(p.repo)) continue;
616
+ for (const b of [p.branch, worktreeBranch(p.worktree, run)]) {
617
+ if (!b || !unlanded.has(b) || briefNamesPending(brief, "Branch", b)) continue;
618
+ 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>").`;
619
+ }
620
+ }
621
+ return null;
622
+ }
623
+
443
624
  /**
444
625
  * The owner's pick order (plan 20261025_1700 P3): refuse a later `ledger.prefer` agent while an
445
626
  * earlier one is free and under its provider cap, unless the brief carries "Pick note: <why>".
@@ -480,8 +661,8 @@ export function providerClaimProblem(text: string, cfg: Config): string | null {
480
661
  if (free(provider) && !names.has(agent) && provider !== null) names.set(agent, provider);
481
662
  }
482
663
  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);
664
+
665
+ 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
666
  if (!m) return null;
486
667
  const hit = [...names.entries()].find(([n]) => n.toLowerCase() === (m[1] ?? "").toLowerCase());
487
668
  if (hit === undefined) return null;
@@ -497,6 +678,7 @@ export function spawnProblem(
497
678
  budgets: Record<string, number | null> = {},
498
679
  staffing: Record<string, string[]> = {},
499
680
  runningJobs?: string[],
681
+ runner: CommandRunner = defaultRunner,
500
682
  ): string | null {
501
683
  const tasks = Array.isArray(input?.tasks) ? input.tasks : [];
502
684
  const context = String(input?.context ?? "");
@@ -509,7 +691,13 @@ export function spawnProblem(
509
691
  if (!allowed.has(agent)) return `${label}: agent "${agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`;
510
692
  const [why, plans] = planGate(`${context}\n${String(t?.task ?? "")}`, label, cfg);
511
693
  if (why) return why;
694
+ // P3 (plan 20261028_1600): the task tool is the live spawn path; every task carries its own
695
+ // pending-work check, before the call-wide gates below.
696
+ const pending = pendingWorkProblem(plans, `${context}\n${String(t?.task ?? "")}`, cfg, runner);
697
+ if (pending) return `${label}: ${pending}`;
512
698
  // 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);
700
+ if (review) return `${label}: ${review}`;
513
701
  const budget = briefBudget(String(t?.task ?? "")) ?? shared;
514
702
  if (budget !== null) {
515
703
  if (!t?.name) return `${label}: "Call budget: ${budget}" needs a task name (the budget is keyed by it).`;
@@ -628,9 +816,9 @@ const PLACEHOLDER = "[REDACTED:";
628
816
  const PLACEHOLDER_FILES = [/\/src\/core\/secret-redact\.ts$/, /\/tests\/secret-redact[^/]*\.test\.ts$/];
629
817
  /** What a write/edit/ast_edit call would add: every text argument but the targets and the replaced text. */
630
818
  function addedText(input: Record<string, unknown>): string {
631
- const skip = ["path", "file", "cwd", "old_string", "old", "oldText", "i"];
819
+ const skip = new Set(["path", "file", "cwd", "old_string", "old", "oldText", "i"]);
632
820
  return Object.entries(input)
633
- .filter(([key, value]) => typeof value === "string" && !skip.includes(key))
821
+ .filter(([key, value]) => typeof value === "string" && !skip.has(key))
634
822
  .map(([, value]) => value as string)
635
823
  .join("\n");
636
824
  }
@@ -974,7 +1162,7 @@ export function planReadNote(tool: string, input: Record<string, unknown>, cwd:
974
1162
  * spawn: the allow-list, task-only and open-plan gates for one implementer launch. Covers both
975
1163
  * original paths (the extension spawn event and a `task` tool call); the brief names the plan.
976
1164
  */
977
- export function checkSpawn(e: SpawnEvent, cfg: Config): Decision {
1165
+ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = defaultRunner): Decision {
978
1166
  const pending = q.cancelPending();
979
1167
  if (pending) {
980
1168
  log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: cancel pending (${pending.words})`);
@@ -995,6 +1183,16 @@ export function checkSpawn(e: SpawnEvent, cfg: Config): Decision {
995
1183
  log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${gate}`);
996
1184
  return deny(`main-guard: ${gate}`);
997
1185
  }
1186
+ const pendingWork = pendingWorkProblem(named, e.brief, cfg, runner);
1187
+ if (pendingWork) {
1188
+ log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${pendingWork}`)
1189
+ return deny(`main-guard: ${pendingWork}`)
1190
+ }
1191
+ const review = reviewPassProblem(named, e.brief, e.agent, cfg);
1192
+ if (review) {
1193
+ log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${review}`);
1194
+ return deny(`main-guard: ${review}`);
1195
+ }
998
1196
  const inc = incidentSpawnProblem(`spawn ${e.agent}`, e.brief, named, cfg);
999
1197
  if (inc) return deny(`main-guard: ${inc}`);
1000
1198
  // The owner's pick order and live provider state (plan 20261025_1700 P3), before the spawn records.
@@ -1048,7 +1246,7 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
1048
1246
  recordOwnerMessage(e.inject, cfg);
1049
1247
  let summary: string;
1050
1248
  try {
1051
- summary = q.queueSummary();
1249
+ summary = q.queueSummary(undefined, cfg.review.since);
1052
1250
  } catch (err) {
1053
1251
  summary = `Queue unreadable (${q.INDEX}): ${err}`;
1054
1252
  }
@@ -1106,6 +1304,7 @@ export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1106
1304
  };
1107
1305
  }
1108
1306
  recordFindings(e, cfg);
1307
+ recordReviews(e, cfg);
1109
1308
  return ALLOW;
1110
1309
  }
1111
1310
 
@@ -1137,7 +1336,7 @@ function progressEntries(text: string): string[] {
1137
1336
  const lines = q.progressBody(text).split("\n");
1138
1337
  for (let i = 0; i < lines.length; i++) {
1139
1338
  const head = lines[i];
1140
- if (head === undefined || !/^- /.test(head) || MAIN_ONLY_LINE.test(head)) continue;
1339
+ if (head === undefined || !head.startsWith("- ") || MAIN_ONLY_LINE.test(head)) continue;
1141
1340
  const block = [head];
1142
1341
  while (i + 1 < lines.length) {
1143
1342
  const cont = lines[i + 1];
@@ -1331,12 +1530,12 @@ function readMainReads(): Record<string, string> {
1331
1530
  }
1332
1531
 
1333
1532
  // Plans still responsible for: open plans (parked "WAITING on owner" excluded) plus queue problems.
1334
- export function openQueue(): string[] {
1533
+ export function openQueue(reviewSince = ""): string[] {
1335
1534
  const open = q
1336
1535
  .activePlans()
1337
1536
  .filter(p => !p.waiting && !q.awaitingMerge(p))
1338
1537
  .map(p => p.file);
1339
- for (const prob of q.queueProblems()) open.push(`${prob.where}: ${prob.problem}`);
1538
+ for (const prob of q.queueProblems(undefined, undefined, reviewSince)) open.push(`${prob.where}: ${prob.problem}`);
1340
1539
  const unique: string[] = [];
1341
1540
  for (const item of open) if (!unique.includes(item)) unique.push(item);
1342
1541
  return unique;
@@ -1371,7 +1570,7 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
1371
1570
  }
1372
1571
  let open: string[];
1373
1572
  try {
1374
- open = openQueue();
1573
+ open = openQueue(cfg.review.since);
1375
1574
  } catch (err) {
1376
1575
  log(cfg.paths.guard_log, `BLOCK stop: cannot read queue: ${err}`);
1377
1576
  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.
@@ -145,6 +145,11 @@ autonomy:
145
145
  go_minutes: 10 # minutes the approve phrase approves exactly one push/merge in tier strict
146
146
  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
147
 
148
+ review: # plan review gate (plan 20261028_1600): reuse lines now, reviewer PASS from P2 (docs/config.md)
149
+ 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
151
+ 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
+
148
153
  ui:
149
154
  enabled: false # the owner's phone page (neurastream ui); binds the tailnet address only
150
155
  port: 7787
@@ -215,13 +220,14 @@ write_check: # write-time lint checks (src/core/write-check.ts):
215
220
  applies_to: sub # "sub" = subagents only; "all" = Main too
216
221
  timeout_ms: 5000 # per linter run; a timeout, crash or missing linter allows the edit and logs a note
217
222
  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
223
+ 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
224
  linters:
219
225
  - ext: [".py"]
220
226
  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+) '
227
+ pattern: '^.+?:\d+:\d+: (?<rule>\S+) (?<message>.+)$'
222
228
  - ext: [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"]
223
229
  argv: ["oxlint", "-f", "unix", "-D", "correctness", "-D", "suspicious", "-D", "perf", "{file}"]
224
- pattern: '^.+?:\d+:\d+: .*\[(?:Error|Warning)/(?<rule>[^\]]+)\]'
230
+ pattern: '^.+?:\d+:\d+: (?<message>.+) \[(?:Error|Warning)/(?<rule>[^\]]+)\]'
225
231
 
226
232
  priority:
227
233
  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