neurastream 0.2.49 → 0.2.51

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.
@@ -55,6 +55,12 @@ function deny(reason: string): Decision {
55
55
  return { allow: false, reason };
56
56
  }
57
57
 
58
+ /** A raw target that names a plan: under a docs/plans/ directory, or a plan file name (YYYYMMDD_HHMM_*.md). */
59
+ function isPlanName(raw: string): boolean {
60
+ return /(^|\/)docs\/plans\//.test(raw) || /^\d{8}_\d{4}_[^/]*\.md$/.test(raw.split("/").pop() ?? "");
61
+ }
62
+ const PLAN_WRITE_TOOLS: Record<string, true> = { edit: true, write: true, ast_edit: true };
63
+
58
64
  /** Guard-log line, `<ISO UTC> <line>`; a failed append is swallowed. */
59
65
  export function log(file: string, line: string): void {
60
66
  try {
@@ -135,6 +141,7 @@ interface PlanReview {
135
141
  hash: string;
136
142
  finding: string;
137
143
  at: number;
144
+ by?: string;
138
145
  }
139
146
 
140
147
  function planReviewsFile(): string {
@@ -165,25 +172,30 @@ export function reviewHash(text: string): string {
165
172
  .outsideProgress(text)
166
173
  .split("\n")
167
174
  .filter(l => !MAIN_ONLY_LINE.test(l))
175
+ .map(l => l.replace(/^(\s*[-*]\s+)\[[xX]\]/, "$1[ ]")) // a ticked phase box hashes as unticked: ticking never expires a PASS
168
176
  .join("\n"),
169
177
  );
170
178
  }
171
179
 
172
- /** The progress entry that records a review; only a subagent's edit can carry one. */
173
- const REVIEW_LINE = /^- PLAN REVIEW: (PASS|FAIL)/;
180
+ /** The progress entry that records a review; only a subagent's edit can carry one. The verdict is the match, never a substring. */
181
+ const REVIEW_LINE = /^- (?:\d{4}-\d{2}-\d{2} \d{2}:\d{2} [^\s:]+: )?PLAN REVIEW: (PASS|FAIL)\b/;
182
+ /** Any entry that opens like a review line; one that REVIEW_LINE does not match is restored, not recorded. */
183
+ const REVIEW_LOOKALIKE = /^- (?:\d{4}-\d{2}-\d{2} \d{2}:\d{2} [^\s:]+: )?PLAN REVIEW\b/;
184
+
185
+ /** Who launches an agent: Main's launch may use a plan review's exemption, a sub's never may (plan 20261028_1600 P4i). */
186
+ export type Spawner = "main" | "sub";
174
187
 
175
188
  /**
176
189
  * P2 (plan 20261028_1600): a spawn on a plan needs a recorded reviewer PASS whose hash still
177
190
  * matches the plan text — progress-only edits keep a PASS valid, any other change expires it,
178
191
  * a FAIL is denied with its first finding. A review spawn itself — an agent from review.agents
179
- * whose brief has the `Plan review: <plan>` line — is exempt, and so is any plan stamped
192
+ * whose brief has the `Plan review: <plan>` line — is exempt when Main launches it, and so is any plan stamped
180
193
  * before `review.since` (P4c: same cutover as the reuse-line gate).
181
194
  */
182
- export function reviewPassProblem(named: string[], brief: string, agent: string, cfg: Config): string | null {
195
+ export function reviewPassProblem(named: string[], brief: string, agent: string, cfg: Config, spawner: Spawner): string | null {
183
196
  const reviews = readPlanReviews();
184
- const reviewLines = brief.split("\n").filter(l => l.startsWith("Plan review:"));
185
197
  for (const file of named) {
186
- if (cfg.review.agents.includes(agent) && reviewLines.some(l => l.slice("Plan review:".length).trim() === file)) continue;
198
+ if (isReviewSpawn(file, brief, agent, cfg, spawner)) continue;
187
199
  if (!q.reviewApplies(file, cfg.review.since)) continue;
188
200
  const rec = reviews[file];
189
201
  if (!rec) return `plan ${file} has no current reviewer PASS. Spawn a reviewer with templates/plan-review-brief.md.`;
@@ -203,16 +215,128 @@ export function reviewPassProblem(named: string[], brief: string, agent: string,
203
215
  function recordReviews(e: PlanEditEvent, cfg: Config): void {
204
216
  const entries = newProgressEntries(e.before, e.after).filter(b => REVIEW_LINE.test(b));
205
217
  if (!entries.length) return;
218
+ const spawns = readReviewSpawns();
219
+ const found = matchReviewSpawn(spawns, e.agentId ?? "");
220
+ if (!found) return;
221
+ const { name, spawn } = found;
206
222
  const reviews = readPlanReviews();
207
223
  for (const block of entries) {
208
- reviews[e.path] = {
209
- verdict: block.startsWith("- PLAN REVIEW: PASS") ? "PASS" : "FAIL",
210
- hash: reviewHash(e.after),
211
- finding: findingsValue(block) ?? "",
212
- at: nowSec(),
213
- };
224
+ const repeat = spawn.verdicts > 0;
225
+ spawn.verdicts++;
226
+ const at = nowSec();
227
+ // Judged against the plan as the spawn first saw it (P4k): a plan that moved during the review cannot pass.
228
+ if (repeat) reviews[e.path] = { verdict: "FAIL", hash: spawn.hash, finding: "review spawn wrote 2 verdicts", at, by: name };
229
+ else if (reviewHash(e.after) !== spawn.hash) reviews[e.path] = { verdict: "FAIL", hash: spawn.hash, finding: "plan changed during review", at, by: name };
230
+ else reviews[e.path] = { verdict: REVIEW_LINE.exec(block)![1] === "PASS" ? "PASS" : "FAIL", hash: spawn.hash, finding: findingsValue(block) ?? "", at, by: name };
214
231
  }
215
232
  writePlanReviews(reviews, cfg);
233
+ writeReviewSpawns(spawns);
234
+ }
235
+
236
+ /** P4k backstop, at a sub agent's end: a named review spawn whose PLAN REVIEW line reached no edit (a path the write targets miss) is recorded here. Returns Main's note when the spawn wrote no verdict at all. */
237
+ export function reviewSpawnEnd(agentId: string, cfg: Config): string | null {
238
+ const found = matchReviewSpawn(readReviewSpawns(), agentId);
239
+ if (!found || found.spawn.verdicts > 0) return null;
240
+ const { name, spawn } = found;
241
+ const after = readPlanText(spawn.plan);
242
+ if (newProgressEntries(spawn.text, after).some(b => REVIEW_LINE.test(b))) {
243
+ recordReviews({ path: spawn.plan, before: spawn.text, after, agent: "sub", agentId: name }, cfg);
244
+ return null;
245
+ }
246
+ return `${name} wrote no verdict on ${spawn.plan}.`;
247
+ }
248
+
249
+ /** P4f: a `Plan review: <plan>` brief from Main, by a configured review agent (the exemption from the plan gate). */
250
+ function isReviewSpawn(file: string, brief: string, agent: string, cfg: Config, spawner: Spawner): boolean {
251
+ const reviewLines = brief.split("\n").filter(l => l.startsWith("Plan review:"));
252
+ return spawner === "main" && cfg.review.agents.includes(agent) && reviewLines.some(l => l.slice("Plan review:".length).trim() === file);
253
+ }
254
+
255
+ /** P4f: the review role of one task: the plan it reviews (null for other spawns). A review spawn needs a name, the name keys its lock, and it reviews one plan. */
256
+ function reviewRole(name: string | undefined, named: string[], brief: string, agent: string, cfg: Config, spawner: Spawner): { plan: string | null; problem: string | null } {
257
+ const reviewed = named.filter(f => isReviewSpawn(f, brief, agent, cfg, spawner));
258
+ if (reviewed.length > 1) return { plan: null, problem: "a review spawn reviews one plan; split the spawn." };
259
+ if (reviewed.length && !name) return { plan: null, problem: "a review spawn needs a name (the task name keys its review lock)." };
260
+ return { plan: reviewed[0] ?? null, problem: null };
261
+ }
262
+
263
+ /** P4f/P4k: the named review spawns, spawn name → its review role: the plan, the plan text and hash as the spawn first saw them, and the verdicts it wrote (review-spawns.json in the state dir). */
264
+ interface ReviewSpawn {
265
+ plan: string;
266
+ text: string;
267
+ hash: string;
268
+ verdicts: number;
269
+ }
270
+
271
+ function reviewSpawnsFile(): string {
272
+ return path.join(q.STATE_DIR, "review-spawns.json");
273
+ }
274
+
275
+ function readReviewSpawns(): Record<string, ReviewSpawn> {
276
+ try {
277
+ const parsed = JSON.parse(readFileSync(reviewSpawnsFile(), "utf8"));
278
+ return parsed && typeof parsed === "object" ? parsed : {};
279
+ } catch {
280
+ return {};
281
+ }
282
+ }
283
+
284
+ function writeReviewSpawns(spawns: Record<string, ReviewSpawn>): void {
285
+ mkdirSync(q.STATE_DIR, { recursive: true });
286
+ writeFileSync(reviewSpawnsFile(), `${JSON.stringify(spawns, null, 2)}\n`);
287
+ }
288
+
289
+ function readPlanText(file: string): string {
290
+ try {
291
+ return readFileSync(file, "utf8");
292
+ } catch {
293
+ return "";
294
+ }
295
+ }
296
+
297
+ /** Set (plan) or drop (null) a named spawn's review role; a non-review spawn under the same name drops it. */
298
+ function recordReviewSpawn(name: string, plan: string | null): void {
299
+ const spawns = readReviewSpawns();
300
+ if (plan) {
301
+ const text = readPlanText(plan);
302
+ spawns[name] = { plan, text, hash: reviewHash(text), verdicts: 0 };
303
+ } else delete spawns[name];
304
+ writeReviewSpawns(spawns);
305
+ }
306
+
307
+ /** The review role an agent id belongs to: its spawn name, or the name without a -<digits> suffix (a sub agent's id, plan P4f gap). */
308
+ function matchReviewSpawn(spawns: Record<string, ReviewSpawn>, agentId: string): { name: string; spawn: ReviewSpawn } | null {
309
+ for (const name of [agentId, agentId.replace(/-\d+$/, "")]) {
310
+ const spawn = Object.hasOwn(spawns, name) ? spawns[name] : undefined;
311
+ if (spawn && typeof spawn.plan === "string") return { name, spawn };
312
+ }
313
+ return null;
314
+ }
315
+
316
+ /** P4f: the secret-read deny: credential dirs under home, and env files. */
317
+ function secretPath(p: string, cfg: Config, cwd: string): boolean {
318
+ const home = cfg.paths.home;
319
+ const abs = path.resolve(cwd, p.startsWith("~/") ? path.join(home, p.slice(2)) : p);
320
+ const base = path.basename(abs);
321
+ const inCredDir = [".config", ".ssh", ".gnupg", ".aws"].some(d => abs.startsWith(path.join(home, d) + path.sep));
322
+ return inCredDir || base.startsWith(".env") || base.endsWith(".env");
323
+ }
324
+
325
+ /** P4f: a named review spawn may read, use todo, and edit only its own plan. Shell, spawn, cancel and MCP tools are denied; so are secret reads. */
326
+ function reviewLockProblem(e: ToolEvent, cfg: Config): string | null {
327
+ const plan = matchReviewSpawn(readReviewSpawns(), e.agentId ?? "")?.spawn.plan ?? null;
328
+ if (!plan) return null;
329
+ const input = e.input ?? {};
330
+ if (cfg.guards.write_tools.includes(e.tool)) {
331
+ const writes = [...(e.writes ?? []), ...q.writeTargets(e.tool, input, e.cwd, [])];
332
+ if (writes.length && writes.every(w => path.resolve(e.cwd, w) === path.resolve(plan))) return null;
333
+ return `review spawn ${e.agentId} may edit only its plan ${plan}.`;
334
+ }
335
+ if (cfg.guards.read_tools.includes(e.tool) || e.tool === "todo") {
336
+ const reads = [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)];
337
+ return reads.some(p => secretPath(p, cfg, e.cwd)) ? `review spawn ${e.agentId} may not read credentials or env files.` : null;
338
+ }
339
+ return `review spawn ${e.agentId} may only read, use todo, and edit its plan; ${e.tool} is denied.`;
216
340
  }
217
341
 
218
342
  function spawnsFile(): string {
@@ -682,7 +806,9 @@ export function spawnProblem(
682
806
  staffing: Record<string, string[]> = {},
683
807
  runningJobs?: string[],
684
808
  runner: CommandRunner = defaultRunner,
809
+ spawner: Spawner = "main",
685
810
  ): string | null {
811
+ const roles: Record<string, string | null> = {};
686
812
  const tasks = Array.isArray(input?.tasks) ? input.tasks : [];
687
813
  const context = String(input?.context ?? "");
688
814
  const allowed = q.allowedAgents();
@@ -699,7 +825,10 @@ export function spawnProblem(
699
825
  const pending = pendingWorkProblem(plans, `${context}\n${String(t?.task ?? "")}`, cfg, runner);
700
826
  if (pending) return `${label}: ${pending}`;
701
827
  // The task's own `Call budget:` line wins over the shared context's.
702
- const review = reviewPassProblem(plans, `${context}\n${String(t?.task ?? "")}`, String(t?.agent ?? ""), cfg);
828
+ const role = reviewRole(t?.name, plans, `${context}\n${String(t?.task ?? "")}`, String(t?.agent ?? ""), cfg, spawner);
829
+ if (role.problem) return `${label}: ${role.problem}`;
830
+ if (t?.name) roles[label] = role.plan;
831
+ const review = reviewPassProblem(plans, `${context}\n${String(t?.task ?? "")}`, String(t?.agent ?? ""), cfg, spawner);
703
832
  if (review) return `${label}: ${review}`;
704
833
  const budget = briefBudget(String(t?.task ?? "")) ?? shared;
705
834
  if (budget !== null) {
@@ -731,7 +860,9 @@ export function spawnProblem(
731
860
  cfg,
732
861
  String((tasks[0] && (tasks[0].name ?? tasks[0].agent)) ?? "task"),
733
862
  );
734
- return gate;
863
+ if (gate) return gate;
864
+ for (const [name, plan] of Object.entries(roles)) recordReviewSpawn(name, plan);
865
+ return null;
735
866
  }
736
867
 
737
868
  function runBlockers(plan: Plan, hit: string[], e: ToolEvent, cfg: Config): string | null {
@@ -774,13 +905,14 @@ function runsCloser(input: Record<string, unknown>): boolean {
774
905
  });
775
906
  }
776
907
 
908
+ const bin = (w: string | undefined) => (w ?? "").replace(/^["']+|["']+$/g, "").split("/").pop() ?? "";
909
+
777
910
  // True when a command segment starts the owner page (plan 20261024_2230 P3c): `neurastream ui`
778
911
  // serves it and `systemctl --user start/restart/enable` of neurastream-ui relaunches it — the
779
912
  // owner's systemd moves, never an agent's, unlocked or not. Segment splitting and launcher
780
913
  // skipping match runsCloser, so `sh -c "neurastream ui"` and `sudo systemctl --user ...` are seen.
781
914
  function startsOwnerUi(input: Record<string, unknown>): boolean {
782
915
  const text = Object.values(input).filter((v): v is string => typeof v === "string").join("\n");
783
- const bin = (w: string | undefined) => (w ?? "").replace(/^["']+|["']+$/g, "").split("/").pop() ?? "";
784
916
  return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
785
917
  const words = seg.trim().split(/\s+/).filter(Boolean).map(w => w.replace(/^["'(]+|["')]+$/g, ""));
786
918
  let i = 0;
@@ -949,26 +1081,64 @@ function incidentSpawnProblem(label: string, brief: string, namedPlans: string[]
949
1081
  );
950
1082
  }
951
1083
 
952
- function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): Decision {
953
- if (e.tool === "task") {
1084
+ /**
1085
+ * A `task` launch: the cancel check, the spawn gates, then the records. Main's and a sub's launch
1086
+ * both come through here (plan 20261028_1600 P4i). Returns the refusal, or null.
1087
+ */
1088
+ function taskLaunch(input: Record<string, unknown>, cfg: Config, runningJobs: string[] | undefined, spawner: Spawner): string | null {
1089
+ const pending = q.cancelPending();
1090
+ if (pending) {
1091
+ log(cfg.paths.guard_log, `BLOCK spawn: cancel pending (${pending.words})`);
1092
+ return `${CANCEL_TODO} Flagged: "${pending.words}"`;
1093
+ }
1094
+ const files: string[] = [];
1095
+ const budgets: Record<string, number | null> = {};
1096
+ const staffing: Record<string, string[]> = {};
1097
+ const why = spawnProblem(input, cfg, files, budgets, staffing, runningJobs, defaultRunner, spawner);
1098
+ if (why) {
1099
+ log(cfg.paths.guard_log, `BLOCK spawn: ${why}`);
1100
+ return why;
1101
+ }
1102
+ const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
1103
+ if (inc) return inc;
1104
+ recordSpawns(files, staffing);
1105
+ recordBudgets(budgets);
1106
+ return null;
1107
+ }
1108
+
1109
+ /**
1110
+ * A shell launch of a bypass_spawn agent: the cancel check, the plan gate, the review PASS, the
1111
+ * incidents, then the record. Main's and a sub's launch both come through here (plan 20261028_1600 P4i).
1112
+ */
1113
+ function bypassLaunch(command: string, cfg: Config, spawner: Spawner): string | null {
1114
+ for (const entry of cfg.guards.bypass_spawn) {
1115
+ if (!bypassRegExp(entry).test(command)) continue;
954
1116
  const pending = q.cancelPending();
955
1117
  if (pending) {
956
- log(cfg.paths.guard_log, `BLOCK spawn: cancel pending (${pending.words})`);
957
- return deny(`main-guard: ${CANCEL_TODO} Flagged: "${pending.words}"`);
1118
+ log(cfg.paths.guard_log, `BLOCK bypass launch: cancel pending (${pending.words})`);
1119
+ return `${CANCEL_TODO} Flagged: "${pending.words}"`;
958
1120
  }
959
- const files: string[] = [];
960
- const budgets: Record<string, number | null> = {};
961
- const staffing: Record<string, string[]> = {};
962
- const why = spawnProblem(input, cfg, files, budgets, staffing, e.runningJobs);
1121
+ const [why, named] = planGate(command, entry, cfg);
963
1122
  if (why) {
964
- log(cfg.paths.guard_log, `BLOCK spawn: ${why}`);
965
- return deny(`main-guard: ${why}`);
1123
+ log(cfg.paths.guard_log, `BLOCK bypass launch: ${why}`);
1124
+ return why;
966
1125
  }
967
- const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
968
- if (inc) return deny(`main-guard: ${inc}`);
969
- recordSpawns(files, staffing);
970
- recordBudgets(budgets);
971
- return ALLOW;
1126
+ const review = reviewPassProblem(named, command, "", cfg, spawner);
1127
+ if (review) {
1128
+ log(cfg.paths.guard_log, `BLOCK bypass launch: ${review}`);
1129
+ return review;
1130
+ }
1131
+ const inc = incidentSpawnProblem("bypass launch", command, named, cfg);
1132
+ if (inc) return inc;
1133
+ if (named.length) recordSpawns(named);
1134
+ }
1135
+ return null;
1136
+ }
1137
+
1138
+ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): Decision {
1139
+ if (e.tool === "task") {
1140
+ const why = taskLaunch(input, cfg, e.runningJobs, "main");
1141
+ return why ? deny(`main-guard: ${why}`) : ALLOW;
972
1142
  }
973
1143
  if (cfg.guards.shell_tools.includes(e.tool)) {
974
1144
  // Strict landing gate (20261025_1940 P2, P5): in tier strict every push/merge waits for the
@@ -980,22 +1150,8 @@ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): De
980
1150
  return deny(`main-guard: tier strict — type "${cfg.autonomy.go_phrase}" to approve one push/merge`);
981
1151
  }
982
1152
  const command = String(input?.command ?? input?.code ?? "");
983
- for (const entry of cfg.guards.bypass_spawn) {
984
- if (!bypassRegExp(entry).test(command)) continue;
985
- const pending = q.cancelPending();
986
- if (pending) {
987
- log(cfg.paths.guard_log, `BLOCK bypass launch: cancel pending (${pending.words})`);
988
- return deny(`main-guard: ${CANCEL_TODO} Flagged: "${pending.words}"`);
989
- }
990
- const [why, named] = planGate(command, entry, cfg);
991
- if (why) {
992
- log(cfg.paths.guard_log, `BLOCK bypass launch: ${why}`);
993
- return deny(`main-guard: ${why}`);
994
- }
995
- const inc = incidentSpawnProblem("bypass launch", command, named, cfg);
996
- if (inc) return deny(`main-guard: ${inc}`);
997
- if (named.length) recordSpawns(named);
998
- }
1153
+ const why = bypassLaunch(command, cfg, "main");
1154
+ if (why) return deny(`main-guard: ${why}`);
999
1155
  }
1000
1156
  return editWindow(e, input, cfg);
1001
1157
  }
@@ -1049,6 +1205,11 @@ export const MAIN_PLAN_FILE = /\/docs\/plans\/(?!archive\/)[^/]+\.md$/;
1049
1205
  * plus, for Main, the spawn gates and the project-file edit window.
1050
1206
  */
1051
1207
  export function checkTool(e: ToolEvent, cfg: Config): Decision {
1208
+ const lock = e.agent === "sub" ? reviewLockProblem(e, cfg) : null;
1209
+ if (lock) {
1210
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} review lock: ${lock}`);
1211
+ return deny(`plan-guard: ${lock}`);
1212
+ }
1052
1213
  if (cfg.guards.skip_tools.includes(e.tool)) return ALLOW;
1053
1214
  const input = e.input ?? {};
1054
1215
  // Starting the owner page (plan 20261024_2230 P3c) is the owner's systemd move, never an
@@ -1063,7 +1224,15 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
1063
1224
  const paths: string[] = [];
1064
1225
  for (const p of [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)]) if (!paths.includes(p)) paths.push(p);
1065
1226
  const writes: string[] = [];
1066
- for (const p of [...(e.writes ?? []), ...q.writeTargets(e.tool, input, e.cwd)]) if (!writes.includes(p)) writes.push(p);
1227
+ const relative: string[] = [];
1228
+ for (const p of [...(e.writes ?? []), ...q.writeTargets(e.tool, input, e.cwd, relative)]) if (!writes.includes(p)) writes.push(p);
1229
+ // A relative plan path resolves against cwd to a file that does not exist, so the plan gate never
1230
+ // sees the edit (plan 20261028_1600 P4j). A plan is named by its absolute path, for every agent.
1231
+ const relPlan = PLAN_WRITE_TOOLS[e.tool] ? relative.find(isPlanName) : undefined;
1232
+ if (relPlan) {
1233
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} relative plan path: ${relPlan}`);
1234
+ return deny(`plan-guard: use the absolute plan path, not ${relPlan}. The plan gate cannot see a relative one.`);
1235
+ }
1067
1236
  // Notify secrets: no agent, main or sub, reads a webhook URL — with or without the unlock.
1068
1237
  // A call that changes a secret is not a read: its target goes through the protected-write
1069
1238
  // rule above, so the owner's unlock covers it like any guard file.
@@ -1114,6 +1283,14 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
1114
1283
  log(cfg.paths.plan_guard_log, `BLOCK sub:${e.agentId} tool=${e.tool} ${why}`);
1115
1284
  return deny(`plan-guard: ${why}`);
1116
1285
  }
1286
+ // A sub's own launch passes the same spawn gates as Main's (plan 20261028_1600 P4i).
1287
+ let launch: string | null = null;
1288
+ if (e.tool === "task") launch = taskLaunch(input, cfg, e.runningJobs, "sub");
1289
+ else if (cfg.guards.shell_tools.includes(e.tool)) launch = bypassLaunch(String(input?.command ?? input?.code ?? ""), cfg, "sub");
1290
+ if (launch) {
1291
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} ${launch}`);
1292
+ return deny(`plan-guard: ${launch}`);
1293
+ }
1117
1294
  const n = e.calls + 1;
1118
1295
  // The warn band has the global width (sub_max_calls - sub_warn_calls) ending at the cap;
1119
1296
  // unbudgeted subs keep sub_warn_calls exactly.
@@ -1239,7 +1416,12 @@ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = d
1239
1416
  log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${pendingWork}`)
1240
1417
  return deny(`main-guard: ${pendingWork}`)
1241
1418
  }
1242
- const review = reviewPassProblem(named, e.brief, e.agent, cfg);
1419
+ const role = reviewRole(e.name, named, e.brief, e.agent, cfg, "main");
1420
+ if (role.problem) {
1421
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent} ${e.name ?? "(unnamed)"} review spawn: ${role.problem}`);
1422
+ return deny(`main-guard: ${role.problem}`);
1423
+ }
1424
+ const review = reviewPassProblem(named, e.brief, e.agent, cfg, "main");
1243
1425
  if (review) {
1244
1426
  log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${review}`);
1245
1427
  return deny(`main-guard: ${review}`);
@@ -1260,6 +1442,7 @@ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = d
1260
1442
  const staffing: Record<string, string[]> = {};
1261
1443
  for (const f of named) staffing[f] = [e.agent];
1262
1444
  recordSpawns(named, staffing);
1445
+ if (e.name) recordReviewSpawn(e.name, role.plan);
1263
1446
  return ALLOW;
1264
1447
  }
1265
1448
 
@@ -1354,6 +1537,19 @@ export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1354
1537
  restore: { path: e.path, text: e.before },
1355
1538
  };
1356
1539
  }
1540
+ const loose = newProgressEntries(e.before, e.after).filter(b => REVIEW_LOOKALIKE.test(b) && !REVIEW_LINE.test(b));
1541
+ if (loose.length) {
1542
+ log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (review line)`);
1543
+ return {
1544
+ allow: false,
1545
+ reason: `plan-guard: a PLAN REVIEW line in ${e.path} does not match "- [<date> <time> <name>: ]PLAN REVIEW: PASS|FAIL — …". The file was restored.`,
1546
+ restore: { path: e.path, text: e.before },
1547
+ };
1548
+ }
1549
+ if (e.agent === "sub" && newProgressEntries(e.before, e.after).some(b => REVIEW_LINE.test(b)) && matchReviewSpawn(readReviewSpawns(), e.agentId ?? "")?.spawn.plan !== e.path) {
1550
+ log(cfg.paths.plan_guard_log, `RESTORE ${e.path} review line from a spawn that is not its named review spawn`);
1551
+ return { allow: false, reason: `plan-guard: a PLAN REVIEW line counts only from the named review spawn of ${e.path}; the file was restored.`, restore: { path: e.path, text: e.before } };
1552
+ }
1357
1553
  recordFindings(e, cfg);
1358
1554
  recordReviews(e, cfg);
1359
1555
  return ALLOW;
@@ -1417,6 +1613,15 @@ export function findingsValue(block: string): string | null {
1417
1613
  // Main's plan text outside "## Progress" must rest on files Main read itself (planReadProblems).
1418
1614
  // An empty `before` means the plan file did not exist yet; a refusal then deletes it.
1419
1615
  function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1616
+ // A PLAN REVIEW line is a review spawn's verdict (P4k): Main writes none, so its edit is restored.
1617
+ if (newProgressEntries(e.before, e.after).some(b => REVIEW_LINE.test(b))) {
1618
+ log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (Main wrote a review line)`);
1619
+ return {
1620
+ allow: false,
1621
+ reason: `plan-guard: a PLAN REVIEW line is written only by the named review spawn of ${e.path}, never by Main. The file was restored.`,
1622
+ restore: { path: e.path, text: e.before || null },
1623
+ };
1624
+ }
1420
1625
  if (q.outsideProgress(e.after) === q.outsideProgress(e.before)) {
1421
1626
  recordFindings(e, cfg, "main-finding");
1422
1627
  return ALLOW;
@@ -187,8 +187,8 @@ export interface M4 {
187
187
 
188
188
  /**
189
189
  * M4: user messages in main runs written in the window, how many match a correction pattern,
190
- * and assistant messages whose last text block ends in "?". RunMessage has no timestamp, so
191
- * a main run counts whole by its lastWriteAt.
190
+ * and assistant messages whose last text block ends in "?". Messages may carry ts, but M4
191
+ * keeps the whole-run measure: a main run counts by its lastWriteAt.
192
192
  */
193
193
  export function m4(runs: Run[], w: Window, patterns: RegExp[]): M4 {
194
194
  const out: M4 = { users: 0, corrections: 0, questions: 0 };