neurastream 0.2.60 → 0.2.62

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.60",
3
+ "version": "0.2.62",
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",
@@ -167,8 +167,14 @@ export interface Config {
167
167
  ui: { enabled: boolean; port: number; owner_login: string; allow_this_machine: boolean };
168
168
  /** Plan review gate (plan 20261028_1600): reuse lines and, from P2 on, the reviewer PASS lock. */
169
169
  review: {
170
- /** Agents a review spawn may run under: the PASS exemption needs one of these plus the brief's `Plan review: <plan>` line. An empty list turns both review gates off (P5c). */
170
+ /** Agents a review spawn may run under: the PASS exemption needs one of these plus the brief's `Plan review: <plan>` line. An empty list turns only the `## Reuse` requirement off; the PASS gate follows `plan` (P6). */
171
171
  agents: string[];
172
+ /** The reviewer PASS gate (P6): `false` skips it; an empty `agents` list no longer turns it off. */
173
+ plan: boolean;
174
+ /** The code review gate (P6): `true` refuses Main ticking a plan phase until a named review spawn's `CODE REVIEW: PASS` entry covers that phase. */
175
+ code: boolean;
176
+ /** Shell command prefixes (P7) a review spawn's bash may run: every `|`/`&&`/`||`/`;`/`&` segment starts with one, single-line, no redirects or substitution; eval is always denied. */
177
+ shell_allow: string[];
172
178
  /** Minutes the spawn gate caches a repo's open-MR list in <queue_state>/mr-cache.json; 0 = no cache. */
173
179
  mr_cache_minutes: number;
174
180
  };
@@ -523,6 +529,10 @@ function check(cfg: Config): void {
523
529
  if (!(cfg.rollover.max_session_mb > 0)) throw new ConfigError("rollover.max_session_mb must be > 0");
524
530
  if (!Array.isArray(cfg.review.agents) || cfg.review.agents.some(a => typeof a !== "string" || !a.trim()))
525
531
  throw new ConfigError('review.agents must be a list of agent names allowed to run review spawns (default ["reviewer"])');
532
+ if (typeof cfg.review.plan !== "boolean") throw new ConfigError("review.plan must be true or false (the reviewer PASS gate; default true)");
533
+ if (typeof cfg.review.code !== "boolean") throw new ConfigError("review.code must be true or false (the code review tick gate; default false)");
534
+ if (!Array.isArray(cfg.review.shell_allow) || cfg.review.shell_allow.some(a => typeof a !== "string" || !a.trim()))
535
+ throw new ConfigError("review.shell_allow must be a list of shell command prefixes a review spawn's bash may run (default: git show/log/diff/blame/rev-parse/ls-files/status/merge-base, grep, cat, head, tail, wc, ls, jq, glab mr list/view/diff, gh pr list/view/diff, date)");
526
536
  if (!Number.isInteger(cfg.review.mr_cache_minutes) || cfg.review.mr_cache_minutes < 0)
527
537
  throw new ConfigError("review.mr_cache_minutes must be an integer >= 0 (minutes the spawn gate caches a repo's open-MR list; 0 = no cache)");
528
538
  if (typeof cfg.approval.since !== "string" || (cfg.approval.since !== "" && !/^\d{8}_\d{4}$/.test(cfg.approval.since)))
@@ -149,6 +149,11 @@ interface PlanReview {
149
149
  by?: string;
150
150
  }
151
151
 
152
+ /** A CODE REVIEW record (P6): the plan phase ids (P1, P4a, …) the entry names, for the tick gate. */
153
+ interface CodeReview extends PlanReview {
154
+ phases: string[];
155
+ }
156
+
152
157
  function planReviewsFile(): string {
153
158
  return path.join(q.STATE_DIR, "plan-reviews.json");
154
159
  }
@@ -161,19 +166,27 @@ function readPlanReviews(): Record<string, PlanReview> {
161
166
  return {};
162
167
  }
163
168
 
164
- function writePlanReviews(reviews: Record<string, PlanReview>, cfg: Config): void {
169
+ function readCodeReviews(): Record<string, CodeReview> {
170
+ try {
171
+ const r = JSON.parse(readFileSync(planReviewsFile(), "utf8")) as { code?: Record<string, CodeReview> };
172
+ if (r.code && typeof r.code === "object") return r.code;
173
+ } catch {}
174
+ return {};
175
+ }
176
+
177
+ function writePlanReviews(reviews: Record<string, PlanReview>, code: Record<string, CodeReview>, cfg: Config): void {
165
178
  try {
166
179
  mkdirSync(q.STATE_DIR, { recursive: true });
167
- writeFileSync(planReviewsFile(), JSON.stringify({ reviews }, null, 1));
180
+ writeFileSync(planReviewsFile(), JSON.stringify({ reviews, code }, null, 1));
168
181
  } catch (err) {
169
182
  log(cfg.paths.plan_guard_log, `cannot write ${planReviewsFile()}: ${err}`);
170
183
  }
171
184
  }
172
185
 
173
- /** The progress entry that records a review; only a subagent's edit can carry one. The verdict is the match, never a substring. */
174
- const REVIEW_LINE = /^- (?:\d{4}-\d{2}-\d{2} \d{2}:\d{2} [^\s:]+: )?PLAN REVIEW: (PASS|FAIL)\b/;
186
+ /** The progress entry that records a review — PLAN for the spawn gate, CODE for the phase tick gate (P6); only a subagent's edit can carry one. The verdict is the match, never a substring. */
187
+ const REVIEW_LINE = /^- (?:\d{4}-\d{2}-\d{2} \d{2}:\d{2} [^\s:]+: )?(PLAN|CODE) REVIEW: (PASS|FAIL)\b/;
175
188
  /** Any entry that opens like a review line; one that REVIEW_LINE does not match is restored, not recorded. */
176
- const REVIEW_LOOKALIKE = /^- (?:\d{4}-\d{2}-\d{2} \d{2}:\d{2} [^\s:]+: )?PLAN REVIEW\b/;
189
+ const REVIEW_LOOKALIKE = /^- (?:\d{4}-\d{2}-\d{2} \d{2}:\d{2} [^\s:]+: )?(PLAN|CODE) REVIEW\b/;
177
190
 
178
191
  /** Who launches an agent: Main's launch may use a plan review's exemption, a sub's never may (plan 20261028_1600 P4i). */
179
192
  export type Spawner = "main" | "sub";
@@ -183,10 +196,11 @@ export type Spawner = "main" | "sub";
183
196
  * matches the plan text — progress-only edits keep a PASS valid, any other change expires it,
184
197
  * a FAIL is denied with its first finding. A review spawn itself — an agent from review.agents
185
198
  * whose brief has the `Plan review: <plan>` line — is exempt when Main launches it. P5 removed
186
- * the cutover: every named plan is gated.
199
+ * the cutover: every named plan is gated. review.plan: false skips the gate (P6); an empty
200
+ * review.agents list no longer turns it off.
187
201
  */
188
202
  export function reviewPassProblem(named: string[], brief: string, agent: string, cfg: Config, spawner: Spawner): string | null {
189
- if (!cfg.review.agents.length) return null; // P5c: an empty review.agents list turns both review gates off
203
+ if (!cfg.review.plan) return null; // P6: review.plan: false skips the PASS gate; an empty review.agents list no longer does
190
204
  const reviews = readPlanReviews();
191
205
  for (const file of named) {
192
206
  if (isReviewSpawn(file, brief, agent, cfg, spawner)) continue;
@@ -204,7 +218,7 @@ export function reviewPassProblem(named: string[], brief: string, agent: string,
204
218
  return null;
205
219
  }
206
220
 
207
- /** A subagent's `PLAN REVIEW: PASS|FAIL` entry records the review of the plan it edited; Main's edit path never reaches this. */
221
+ /** A subagent's `PLAN REVIEW` or `CODE REVIEW` (P6) entry records the review of the plan it edited; Main's edit path never reaches this. */
208
222
  function recordReviews(e: PlanEditEvent, cfg: Config): void {
209
223
  const entries = newProgressEntries(e.before, e.after).filter(b => REVIEW_LINE.test(b));
210
224
  if (!entries.length) return;
@@ -213,16 +227,25 @@ function recordReviews(e: PlanEditEvent, cfg: Config): void {
213
227
  if (!found) return;
214
228
  const { name, spawn } = found;
215
229
  const reviews = readPlanReviews();
230
+ const code = readCodeReviews();
216
231
  for (const block of entries) {
232
+ const kind = REVIEW_LINE.exec(block)![1];
217
233
  const repeat = spawn.verdicts > 0;
218
234
  spawn.verdicts++;
219
235
  const at = nowSec();
220
236
  // Judged against the plan as the spawn first saw it (P4k): a plan that moved during the review cannot pass.
221
- if (repeat) reviews[e.path] = { verdict: "FAIL", hash: spawn.hash, finding: "review spawn wrote 2 verdicts", at, by: name };
222
- else if (reviewHash(e.after) !== spawn.hash) reviews[e.path] = { verdict: "FAIL", hash: spawn.hash, finding: "plan changed during review", at, by: name };
223
- else reviews[e.path] = { verdict: REVIEW_LINE.exec(block)![1] === "PASS" ? "PASS" : "FAIL", hash: spawn.hash, finding: findingsValue(block) ?? "", at, by: name };
224
- }
225
- writePlanReviews(reviews, cfg);
237
+ const record: PlanReview = repeat
238
+ ? { verdict: "FAIL", hash: spawn.hash, finding: "review spawn wrote 2 verdicts", at, by: name }
239
+ : reviewHash(e.after) !== spawn.hash
240
+ ? { verdict: "FAIL", hash: spawn.hash, finding: "plan changed during review", at, by: name }
241
+ : { verdict: REVIEW_LINE.exec(block)![2] === "PASS" ? "PASS" : "FAIL", hash: spawn.hash, finding: findingsValue(block) ?? "", at, by: name };
242
+ // A CODE REVIEW record covers only the phases the verdict names before its Findings line: a phase in the Findings text ("see P2") is a reference, not coverage; an entry without a Findings line covers nothing.
243
+ if (kind === "CODE") {
244
+ const head = block.slice(0, Math.max(block.indexOf("Findings:"), 0));
245
+ code[e.path] = { ...record, phases: [...new Set([...head.matchAll(/\bP\d+[a-z]?\b/g)].map(m => m[0]))] };
246
+ } else reviews[e.path] = record;
247
+ }
248
+ writePlanReviews(reviews, code, cfg);
226
249
  writeReviewSpawns(spawns);
227
250
  }
228
251
 
@@ -316,6 +339,32 @@ function secretPath(p: string, cfg: Config, cwd: string): boolean {
316
339
  );
317
340
  }
318
341
 
342
+ // P7 (plan 20261028_1600): option tokens that write or execute on an otherwise allowed command;
343
+ // `-w`/`--web` are denied on gh/glab segments only (they open a browser), `-c` only right after
344
+ // `git` (config injection, e.g. core.pager=sh).
345
+ const SHELL_DENY_OPTS = ["--output", "--pre", "--ext-diff", "--textconv", "--open-files-in-pager", "--exec", "-O"];
346
+
347
+ /** P7 (plan 20261028_1600): why a review spawn's bash command is not allowed, or null. Single
348
+ * line, no `$(`/backtick/`<(`/`>(`, no `>` outside quotes (quoted text stripped the way
349
+ * withoutQuotedRedirects does), and every `|`/`&&`/`||`/`;`/`&` segment starts with a
350
+ * review.shell_allow entry followed by a word boundary. */
351
+ function reviewShellProblem(command: string, cfg: Config): string | null {
352
+ if (/[\r\n]/.test(command)) return "a multi-line command";
353
+ if (command.includes("`") || command.includes("$(") || command.includes("<(") || command.includes(">(")) return "command substitution";
354
+ if (q.withoutQuotedRedirects(command).includes(">")) return "a shell redirect";
355
+ for (const raw of command.split(/&&|\|\||[|;&]/)) {
356
+ const seg = raw.trim();
357
+ const toks = seg.split(/\s+/);
358
+ const pre = cfg.review.shell_allow.find(p => seg.startsWith(p) && (seg.length === p.length || /\s/.test(seg.charAt(p.length))));
359
+ if (!pre) return `${toks[0] || "an empty segment"} is not a review.shell_allow command`;
360
+ const opt = toks.find(t => SHELL_DENY_OPTS.some(o => t === o || t.startsWith(`${o}=`)));
361
+ if (opt) return `the writing/executing option ${opt}`;
362
+ if ((toks[0] === "gh" || toks[0] === "glab") && toks.some(t => t === "-w" || t === "--web")) return "gh/glab --web opens a browser";
363
+ if (toks.some((t, i) => i > 0 && t === "-c" && toks[i - 1] === "git")) return "git -c config injection";
364
+ }
365
+ return null;
366
+ }
367
+
319
368
  /** P4f: a named review spawn may read, use todo, and edit only its own plan. Shell, spawn, cancel and MCP tools are denied; so are secret reads. */
320
369
  function reviewLockProblem(e: ToolEvent, cfg: Config): string | null {
321
370
  const plan = matchReviewSpawn(readReviewSpawns(), e.agentId ?? "")?.spawn.plan ?? null;
@@ -330,12 +379,16 @@ function reviewLockProblem(e: ToolEvent, cfg: Config): string | null {
330
379
  const reads = [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)];
331
380
  return reads.some(p => secretPath(p, cfg, e.cwd)) ? `review spawn ${e.agentId} may not read credentials or env files.` : null;
332
381
  }
333
- // P5 (plan 20261031_1207): a shell call gets the read tools' deny — allowed when it writes
334
- // nothing and its text carries no landing/mutating/spawn command and no secret path.
382
+ // P7 (plan 20261028_1600): the reviewer's shell is an allow list, not a ban list — eval never
383
+ // (it runs code), and bash only when every |/&&/||/;/& segment starts with a review.shell_allow
384
+ // command: single-line, no substitution or redirect characters, no writing/executing option
385
+ // tokens. The secret-path deny stays. (I-20261031-348: the old MUTATING ban missed
386
+ // fs.renameSync-style writes; I-20261031-350: a reviewer's shell ran anything unlisted.)
335
387
  if (cfg.guards.shell_tools.includes(e.tool)) {
336
- const writes = [...(e.writes ?? []), ...q.writeTargets(e.tool, input, e.cwd, [])];
337
- if (writes.length || writesShellText(input, cfg))
338
- return `review spawn ${e.agentId} may only read, use todo, and edit its plan; shell writes, landing and mutating commands are denied.`;
388
+ if (e.tool === "eval")
389
+ return `review spawn ${e.agentId} may not run eval; use the read tools or a bash command from review.shell_allow.`;
390
+ const problem = reviewShellProblem(String(input.command ?? ""), cfg);
391
+ if (problem) return `review spawn ${e.agentId} may run only review.shell_allow commands: ${problem}.`;
339
392
  const reads = [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)];
340
393
  return reads.some(p => secretPath(p, cfg, e.cwd)) ? `review spawn ${e.agentId} may not read credentials or env files.` : null;
341
394
  }
@@ -566,6 +619,12 @@ function unticked(p: Plan): string[] {
566
619
  return [...phases.matchAll(/^\s*[-*]\s+\[ \]\s+(P\d+[a-z]?)\b/gm)].map(m => m[1]!);
567
620
  }
568
621
 
622
+ /** Phase ids an edit newly ticks: `[ ]` in `before`, `[x]` in `after` (P6, read from the Phases section like unticked). */
623
+ function newlyTicked(before: string, after: string): string[] {
624
+ const was = new Set([...(q.sections(before).get("phases") ?? "").matchAll(/^\s*[-*]\s+\[ \]\s+(P\d+[a-z]?)\b/gm)].map(m => m[1]!));
625
+ return [...(q.sections(after).get("phases") ?? "").matchAll(/^\s*[-*]\s+\[[xX]\]\s+(P\d+[a-z]?)\b/gm)].map(m => m[1]!).filter(id => was.has(id));
626
+ }
627
+
569
628
  /** The open plans the text names — a `Priority skip: <path> — <why>` line names a plan it does NOT run on (20261025_0215 P3), so only the remaining text decides. planGate's targeting, shared with the spawn verdict's brief-lint and cap notes (plan 20261031_1207 P4). */
570
629
  function briefPlans(text: string, cfg?: Config): Plan[] {
571
630
  const body = text.replace(/^\s*(?:[-*]\s+)?priority skip:.*$/gim, "");
@@ -706,9 +765,10 @@ export function priorityProblem(plans: Plan[], named: string[], staffed: string[
706
765
  return skips.length ? { skips } : null;
707
766
  }
708
767
 
709
- /** Load staffing and the owner's recorded words, run the pure priority gate and log its outcome; the refusal comes back with the caller's label, or null. */
710
- function priorityGate(named: string[], runningJobs: string[] | undefined, brief: string, cfg: Config, label: string): string | null {
711
- const outcome = priorityProblem(q.activePlans(), named, runningJobs === undefined ? undefined : staffedPlans(readStaffing(), runningJobs), brief, readOwnerMessages(), nowSec(), cfg);
768
+ /** Load staffing and the owner's recorded words, run the pure priority gate and log its outcome; the refusal comes back with the caller's label, or null. P8 (I-20261031-353): the plans a Main-authored brief reviews drop out first — a plan waiting for its reviewer is not a priority slot, so a call naming only reviewed plans passes with no skip line; implementer plans keep the gate. */
769
+ function priorityGate(named: string[], runningJobs: string[] | undefined, brief: string, cfg: Config, label: string, agent: string, spawner: Spawner): string | null {
770
+ const implementer = named.filter(f => !isReviewSpawn(f, brief, agent, cfg, spawner));
771
+ const outcome = priorityProblem(q.activePlans(), implementer, runningJobs === undefined ? undefined : staffedPlans(readStaffing(), runningJobs), brief, readOwnerMessages(), nowSec(), cfg);
712
772
  if (outcome?.unknown) log(cfg.paths.guard_log, "PRIORITY unknown jobs");
713
773
  for (const s of outcome?.skips ?? []) log(cfg.paths.guard_log, `PRIORITY skip ${s.plan}: ${s.why}`);
714
774
  return outcome?.problem ? `${label}: ${outcome.problem}` : null;
@@ -934,6 +994,8 @@ export function spawnProblem(
934
994
  joined,
935
995
  cfg,
936
996
  String((tasks[0] && (tasks[0].name ?? tasks[0].agent)) ?? "task"),
997
+ String((tasks[0] && tasks[0].agent) ?? "task"),
998
+ spawner,
937
999
  );
938
1000
  if (gate) problems.push(gate);
939
1001
  const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
@@ -1535,7 +1597,7 @@ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = d
1535
1597
  const problems: string[] = [];
1536
1598
  const [why, named] = planGate(e.brief, e.agent, cfg);
1537
1599
  if (why) problems.push(why);
1538
- const gate = priorityGate(named, e.runningJobs, e.brief, cfg, e.agent);
1600
+ const gate = priorityGate(named, e.runningJobs, e.brief, cfg, e.agent, e.agent, "main");
1539
1601
  if (gate) problems.push(gate);
1540
1602
  const pendingWork = pendingWorkProblem(named, e.brief, cfg, runner);
1541
1603
  if (pendingWork) problems.push(pendingWork);
@@ -1662,13 +1724,13 @@ export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1662
1724
  log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (review line)`);
1663
1725
  return {
1664
1726
  allow: false,
1665
- reason: `plan-guard: a PLAN REVIEW line in ${e.path} does not match "- [<date> <time> <name>: ]PLAN REVIEW: PASS|FAIL — …". The file was restored.`,
1727
+ reason: `plan-guard: a PLAN REVIEW or CODE REVIEW line in ${e.path} does not match "- [<date> <time> <name>: ]PLAN REVIEW|CODE REVIEW: PASS|FAIL — …". The file was restored.`,
1666
1728
  restore: { path: e.path, text: e.before },
1667
1729
  };
1668
1730
  }
1669
1731
  if (e.agent === "sub" && newProgressEntries(e.before, e.after).some(b => REVIEW_LINE.test(b)) && matchReviewSpawn(readReviewSpawns(), e.agentId ?? "")?.spawn.plan !== e.path) {
1670
1732
  log(cfg.paths.plan_guard_log, `RESTORE ${e.path} review line from a spawn that is not its named review spawn`);
1671
- return { allow: false, reason: `plan-guard: a PLAN REVIEW line counts only from the named review spawn of ${e.path}; the file was restored.`, restore: { path: e.path, text: e.before } };
1733
+ return { allow: false, reason: `plan-guard: a PLAN REVIEW or CODE REVIEW line counts only from the named review spawn of ${e.path}; the file was restored.`, restore: { path: e.path, text: e.before } };
1672
1734
  }
1673
1735
  recordReviews(e, cfg);
1674
1736
  return ALLOW;
@@ -1707,18 +1769,44 @@ export function findingsValue(block: string): string | null {
1707
1769
  return line.slice(line.lastIndexOf("Findings:") + "Findings:".length).trim() || null;
1708
1770
  }
1709
1771
 
1772
+ /** P6 (plan 20261028_1600): the refusal for ticking `ids` with review.code on. Each phase needs a recorded CODE REVIEW: PASS from a named review spawn (the `code` map of plan-reviews.json), and its entry must still be the plan's last Progress entry naming the phase — last by the entry's `<YYYY-MM-DD HH:MM>` stamp, not file order (live plans are newest-first or appended): implementer work after the review voids it. */
1773
+ function codeReviewProblem(file: string, after: string, ids: string[]): string | null {
1774
+ const rec = readCodeReviews()[file];
1775
+ // toSorted is stable: ties and unstamped entries ("") keep file order.
1776
+ const entries = progressEntries(after)
1777
+ .map(b => [b, /^\s*-\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2})/.exec(b)?.[1] ?? ""] as const)
1778
+ .toSorted((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0))
1779
+ .map(([b]) => b);
1780
+ for (const id of ids) {
1781
+ const last = entries.findLast(b => new RegExp(`\\b${id}\\b`).test(b));
1782
+ const valid = last !== undefined && REVIEW_LINE.test(last) && REVIEW_LINE.exec(last)![1] === "CODE" && REVIEW_LINE.exec(last)![2] === "PASS";
1783
+ if (!(rec?.verdict === "PASS" && rec.phases.includes(id) && valid))
1784
+ return `plan-guard: phase ${id} was ticked but has no current CODE REVIEW: PASS from a review spawn after its last implementer entry — spawn a code reviewer or set review.code: false. The file was restored.`;
1785
+ }
1786
+ return null;
1787
+ }
1788
+
1710
1789
  // Main's plan text outside "## Progress" must rest on files Main read itself (planReadProblems).
1711
1790
  // An empty `before` means the plan file did not exist yet; a refusal then deletes it.
1712
1791
  function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1713
- // A PLAN REVIEW line is a review spawn's verdict (P4k): Main writes none, so its edit is restored.
1792
+ // A PLAN REVIEW or CODE REVIEW line (P6) is a review spawn's verdict (P4k): Main writes none, so its edit is restored.
1714
1793
  if (newProgressEntries(e.before, e.after).some(b => REVIEW_LINE.test(b))) {
1715
1794
  log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (Main wrote a review line)`);
1716
1795
  return {
1717
1796
  allow: false,
1718
- reason: `plan-guard: a PLAN REVIEW line is written only by the named review spawn of ${e.path}, never by Main. The file was restored.`,
1797
+ reason: `plan-guard: a PLAN REVIEW or CODE REVIEW line is written only by the named review spawn of ${e.path}, never by Main. The file was restored.`,
1719
1798
  restore: { path: e.path, text: e.before || null },
1720
1799
  };
1721
1800
  }
1801
+ // P6 (plan 20261028_1600): with review.code on, ticking a phase needs a named review spawn's CODE REVIEW: PASS behind it — the recorded verdict counts, never Main's own line.
1802
+ if (cfg.review.code) {
1803
+ const ticks = newlyTicked(e.before, e.after);
1804
+ const problem = ticks.length ? codeReviewProblem(e.path, e.after, ticks) : null;
1805
+ if (problem) {
1806
+ log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (code review: ${ticks.join(", ")})`);
1807
+ return { allow: false, reason: problem, restore: { path: e.path, text: e.before || null } };
1808
+ }
1809
+ }
1722
1810
  if (q.outsideProgress(e.after) === q.outsideProgress(e.before)) {
1723
1811
  return ALLOW;
1724
1812
  }
@@ -1967,18 +2055,28 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
1967
2055
  }
1968
2056
  // P5 (plan 20261031_0911): a landed open plan whose auto-close failed holds the stop until a
1969
2057
  // running subagent's brief names it (staffing ∩ live ledger); unrelated live subagents release
1970
- // nothing, and there is no idle-stop valve — the lock lifts when the plan closes or is staffed.
2058
+ // nothing. Valve (20261031_2320): like the incident block above, empty stops count toward
2059
+ // cfg.guards.idle_stops; a stop with calls in between resets the count and re-locks.
1971
2060
  const locked = q.activePlans().filter(p => p.status === "open" && q.autoCloseCandidate(p) && q.lastCloseFailed(p.file));
1972
2061
  if (locked.length) {
1973
2062
  const staffed = staffedPlans(readStaffing(), liveSubagents(e.ledgerText));
1974
2063
  const unworked = locked.filter(s => !staffed.includes(s.file));
1975
2064
  if (unworked.length) {
2065
+ if (state.callsSinceStop === 0) state.idleStops++;
2066
+ else state.idleStops = 0;
2067
+ state.callsSinceStop = 0;
2068
+ if (state.idleStops >= cfg.guards.idle_stops) {
2069
+ log(cfg.paths.guard_log, `ALLOW stop after ${state.idleStops} idle stop attempts; locked: ${unworked.map(s => s.file).join(", ")}`);
2070
+ return { allow: true, reason: "", state: { callsSinceStop: 0, idleStops: 0 } };
2071
+ }
2072
+ const left = cfg.guards.idle_stops - state.idleStops;
1976
2073
  log(cfg.paths.guard_log, `BLOCK stop: landed but not closed: ${unworked.map(s => s.file).join(", ")}`);
1977
2074
  return {
1978
2075
  allow: false,
1979
2076
  reason:
1980
2077
  `main-guard: ${unworked.map(s => `${s.file} landed but its auto-close failed (${(q.lastCloseResult(s.file) ?? "").replace(/^queue-close: /, "")})`).join("; ")}. ` +
1981
- "The stop stays locked: spawn an agent whose brief names the plan, or fix the close.",
2078
+ "The stop stays locked: spawn an agent whose brief names the plan, or fix the close. " +
2079
+ `${left} idle stop ${left === 1 ? "attempt" : "attempts"} left before the stop is allowed.`,
1982
2080
  state,
1983
2081
  };
1984
2082
  }
@@ -159,7 +159,7 @@ export function approvalProblem(text: string, file: string, pagesDir: string, si
159
159
  if (since === "") return null;
160
160
  const page = pageOfPlan(pagesDir, file);
161
161
  const stamp = /^\d{8}_\d{4}/.exec(basename(file))?.[0] ?? null;
162
- const gated = since !== "" && (stamp === null || stamp >= since);
162
+ const gated = stamp === null || stamp >= since;
163
163
  if (page === null) {
164
164
  if (!gated) return null; // predates the convention
165
165
  return `plan ${file} has no page: publish its page with neurastream pages publish <page.html> --plan ${file}`;
@@ -65,10 +65,11 @@ function originBase(repo: string): string {
65
65
  return head.ok && head.out ? `refs/remotes/${head.out}` : "refs/remotes/origin/main";
66
66
  }
67
67
 
68
- /** P4: an open plan auto-close starts for — its branch exists and has landed, or it names no branch (a Main-only plan) and every phase is ticked. Shared by the adapter's autoClose filter and queueProblems' landed lock (P5); queue-close --auto re-checks authoritatively. */
68
+ /** P4 (plan 20261031_0911), tightened by 20261031_2320: an open plan auto-close starts for only when every phase is ticked AND (its branch exists and has landed, or it names no branch — a Main-only plan). An empty landed branch is not done: 0.2.60 held the queue on 0/N plans. Shared by the adapter's autoClose filter and queueProblems' landed lock (P5); queue-close --auto re-checks authoritatively. */
69
69
  export function autoCloseCandidate(p: Plan): boolean {
70
70
  if (p.status !== "open" || p.errors.length) return false;
71
- if (!p.branch) return p.phases.total > 0 && p.phases.done === p.phases.total;
71
+ if (!(p.phases.total > 0 && p.phases.done === p.phases.total)) return false;
72
+ if (!p.branch) return true;
72
73
  if (!gitOut(p.repo, "rev-parse", "--verify", "-q", `refs/heads/${p.branch}`).ok) return false;
73
74
  return landed(p.repo, p.branch, originBase(p.repo), p.text);
74
75
  }
@@ -553,7 +554,7 @@ export function touchedPaths(toolName: string, input: Record<string, unknown>, c
553
554
  }
554
555
 
555
556
  export const MUTATING =
556
- /(\brm\b|\bmv\b|\bcp\b|\btouch\b|\btruncate\b|\bchmod\b|\bln\b|\bsed\s+(-\w*\s+)*-i|\bperl\s+(-\w*\s+)*-[a-z]*i|\btee\b|(^|[^0-9&>=-])>{1,2}\s*[^\s&>]|\bgit\s+(rm|mv|checkout|restore|apply|am|stash|reset|clean)\b|\bpatch\b|\binstall\b|\bdd\b|writeFile|appendFile|Bun\.write|unlink|rmSync|\.write_text\(|\.write_bytes\(|\bopen\([^)]*,\s*["'][wax]b?\+?["']|shutil\.|os\.(remove|rename|replace|unlink|chmod)|\.writelines\()/;
557
+ /(\brm\b|\bmv\b|\bcp\b|\btouch\b|\btruncate\b|\bchmod\b|\bln\b|\bsed\s+(-\w*\s+)*-i|\bperl\s+(-\w*\s+)*-[a-z]*i|\btee\b|(^|[^0-9&>=-])>{1,2}\s*[^\s&>]|\bgit\s+(rm|mv|checkout|restore|apply|am|stash|reset|clean)\b|\bpatch\b|\binstall\b|\bdd\b|writeFile|appendFile|Bun\.write|unlink|rmSync|renameSync|cpSync|copyFileSync|linkSync|symlinkSync|mkdtempSync|mkdirSync|rmdirSync|\.write_text\(|\.write_bytes\(|\bopen\([^)]*,\s*["'][wax]b?\+?["']|shutil\.|os\.(remove|rename|replace|unlink|chmod)|\.writelines\()/;
557
558
 
558
559
  export function withoutQuotedRedirects(code: string): string {
559
560
  return code.replace(/'[^']*'/g, m => m.replace(/>/g, " ")).replace(/"(?:[^"\\]|\\.)*"/g, m => m.replace(/>/g, " "));
@@ -149,7 +149,10 @@ autonomy:
149
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
150
150
 
151
151
  review: # plan review gate (plan 20261028_1600): reuse lines now, reviewer PASS from P2 (docs/config.md)
152
- agents: ["reviewer"] # agents allowed to run a review spawn: one must be in "## Allowed" of notes/subagents.md (doctor and queue-check fail otherwise, e.g. ["glm"]); the PASS exemption needs one plus the brief's `Plan review:` line; an empty list turns both review gates off
152
+ plan: true # the reviewer PASS gate: false skips it (P6); an empty agents list no longer turns it off
153
+ code: false # the code review gate: true refuses Main ticking a phase until a review spawn's `CODE REVIEW: PASS` entry covers it (P6)
154
+ agents: ["reviewer"] # agents allowed to run a review spawn: one must be in "## Allowed" of notes/subagents.md (doctor and queue-check fail otherwise, e.g. ["glm"]); the PASS exemption needs one plus the brief's `Plan review:` line; an empty list only turns the `## Reuse` requirement off
155
+ shell_allow: ["git show", "git log", "git diff", "git blame", "git rev-parse", "git ls-files", "git status", "git merge-base", "grep", "cat", "head", "tail", "wc", "ls", "jq", "glab mr list", "glab mr view", "glab mr diff", "gh pr list", "gh pr view", "gh pr diff", "date"] # the bash prefixes a review spawn may run (P7): every |/&&/||/;/& segment starts with one, single-line, no redirects or substitution; eval is denied outright
153
156
  mr_cache_minutes: 10 # minutes the spawn gate caches a repo's open-MR list in <queue_state>/mr-cache.json; 0 = no cache
154
157
  approval: # plan approval hard gate (plan 20261029_1455 P3): docs/config.md
155
158
  since: "" # a plan stamped at or after this (YYYYMMDD_HHMM) needs a page and an approval record; "" = off