neurastream 0.3.26 → 0.3.28

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.
@@ -18,7 +18,10 @@ export function leafKeys(node: unknown, prefix: string[] = []): string[] {
18
18
 
19
19
  export function valueAt(cfg: unknown, key: string): unknown {
20
20
  let node = cfg;
21
- for (const seg of key.split(".")) node = (node as Record<string, unknown>)[seg];
21
+ for (const seg of key.split(".")) {
22
+ if (node === null || node === undefined || typeof node !== "object") return undefined;
23
+ node = (node as Record<string, unknown>)[seg];
24
+ }
22
25
  return node;
23
26
  }
24
27
 
@@ -71,6 +74,11 @@ function setPath(lines: string[], segs: string[], value: string, parent: number,
71
74
  if (k < 0) {
72
75
  k = afterLast(lines, lo, hi);
73
76
  lines.splice(k, 0, `${indent}${seg}:`);
77
+ } else {
78
+ // Expand an inline empty mapping (e.g. `profiles: {}`) before inserting nested keys below it.
79
+ const rest = re.exec(lines[k]!)![2]!;
80
+ const emptyMap = rest.match(/^\s*\{\s*\}(\s+#.*)?$/);
81
+ if (emptyMap) lines[k] = `${indent}${seg}:${emptyMap[1] ?? ""}`;
74
82
  }
75
83
  const end = blockEnd(lines, k + 1, indent.length);
76
84
  const child = lines.slice(k + 1, end).find((l) => !isBlank(l));
@@ -6,6 +6,7 @@ import { homedir } from "node:os";
6
6
  import { dirname, join } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import type { WriteCheckConfig } from "./write-check.ts";
9
+ import { SPAWN_ROLES, type SpawnDirection, type SpawnProfileConfig, type SpawnRole } from "./runner.ts";
9
10
  import { teamConfigError } from "./team-labels.ts";
10
11
 
11
12
  const HERE = dirname(fileURLToPath(import.meta.url));
@@ -21,6 +22,15 @@ export class ConfigError extends Error {
21
22
  export interface Config {
22
23
  /** Which adapter (src/adapters/index.ts) serves runs, traces, launch, install and doctor. The template ships the only one; a second harness adds its name here (docs/adapter.md). */
23
24
  harness: string;
25
+ /** Cross-harness helper spawn runner settings and per-agent overrides. */
26
+ spawn: {
27
+ default_runner: string;
28
+ fallback_harness: string;
29
+ direction: SpawnDirection;
30
+ start_timeout_ms: number;
31
+ timeout_ms: number;
32
+ profiles: Record<string, SpawnProfileConfig>;
33
+ };
24
34
  /** Live project rules (src/core/repo-rules.ts): a repo's own AGENTS.md, handed to the agent that works in it. */
25
35
  rules: {
26
36
  /** Largest rules text a hook injects; past it the text is cut and one line names the file. */
@@ -551,8 +561,77 @@ function applyEnv(cfg: Record<string, unknown>, env: NodeJS.ProcessEnv): void {
551
561
  }
552
562
  }
553
563
 
564
+ const SPAWN_PROFILE_KEYS = new Set(["harness", "fallback_harness", "runner", "model", "provider", "role", "direction", "start_timeout_ms", "timeout_ms", "args", "env"]);
565
+ const SPAWN_SLUG_RE = /^[a-z0-9][a-z0-9_-]*$/;
566
+
567
+ /** Validates the `spawn` configuration block and all configured helper profiles. */
568
+ function checkSpawnConfig(spawn: Config["spawn"]): void {
569
+ if (typeof spawn.default_runner !== "string" || !SPAWN_SLUG_RE.test(spawn.default_runner)) {
570
+ throw new ConfigError("spawn.default_runner must be a non-empty runner slug");
571
+ }
572
+ if (typeof spawn.fallback_harness !== "string" || (spawn.fallback_harness !== "" && !SPAWN_SLUG_RE.test(spawn.fallback_harness))) {
573
+ throw new ConfigError("spawn.fallback_harness must be empty or a valid harness slug");
574
+ }
575
+ if (spawn.direction !== "right" && spawn.direction !== "down") {
576
+ throw new ConfigError('spawn.direction must be "right" or "down"');
577
+ }
578
+ if (typeof spawn.start_timeout_ms !== "number" || !Number.isFinite(spawn.start_timeout_ms) || !(spawn.start_timeout_ms > 0)) {
579
+ throw new ConfigError("spawn.start_timeout_ms must be a number > 0");
580
+ }
581
+ if (typeof spawn.timeout_ms !== "number" || !Number.isFinite(spawn.timeout_ms) || !(spawn.timeout_ms > 0)) {
582
+ throw new ConfigError("spawn.timeout_ms must be a number > 0");
583
+ }
584
+ if (!isObj(spawn.profiles)) {
585
+ throw new ConfigError("spawn.profiles must be an object");
586
+ }
587
+ for (const [name, raw] of Object.entries(spawn.profiles)) {
588
+ const at = `spawn.profiles.${name}`;
589
+ if (!isObj(raw)) throw new ConfigError(`${at} must be an object`);
590
+ for (const key of Object.keys(raw)) {
591
+ if (!SPAWN_PROFILE_KEYS.has(key)) throw new ConfigError(`unknown key ${at}.${key}`);
592
+ }
593
+ if (raw.harness !== undefined && (typeof raw.harness !== "string" || !SPAWN_SLUG_RE.test(raw.harness))) {
594
+ throw new ConfigError(`${at}.harness must be a non-empty harness slug`);
595
+ }
596
+ if (
597
+ raw.fallback_harness !== undefined &&
598
+ (typeof raw.fallback_harness !== "string" || (raw.fallback_harness !== "" && !SPAWN_SLUG_RE.test(raw.fallback_harness)))
599
+ ) {
600
+ throw new ConfigError(`${at}.fallback_harness must be empty or a valid harness slug`);
601
+ }
602
+ if (raw.runner !== undefined && (typeof raw.runner !== "string" || !SPAWN_SLUG_RE.test(raw.runner))) {
603
+ throw new ConfigError(`${at}.runner must be a non-empty runner slug`);
604
+ }
605
+ if (raw.model !== undefined && typeof raw.model !== "string") {
606
+ throw new ConfigError(`${at}.model must be a string`);
607
+ }
608
+ if (raw.provider !== undefined && (typeof raw.provider !== "string" || !SPAWN_SLUG_RE.test(raw.provider))) {
609
+ throw new ConfigError(`${at}.provider must be a non-empty provider slug`);
610
+ }
611
+ if (raw.role !== undefined && (typeof raw.role !== "string" || !SPAWN_ROLES.includes(raw.role as SpawnRole))) {
612
+ throw new ConfigError(`${at}.role must be "implementer", "planner", or "reviewer"`);
613
+ }
614
+ if (raw.direction !== undefined && raw.direction !== "right" && raw.direction !== "down") {
615
+ throw new ConfigError(`${at}.direction must be "right" or "down"`);
616
+ }
617
+ if (raw.start_timeout_ms !== undefined && (typeof raw.start_timeout_ms !== "number" || !Number.isFinite(raw.start_timeout_ms) || !(raw.start_timeout_ms > 0))) {
618
+ throw new ConfigError(`${at}.start_timeout_ms must be a number > 0`);
619
+ }
620
+ if (raw.timeout_ms !== undefined && (typeof raw.timeout_ms !== "number" || !Number.isFinite(raw.timeout_ms) || !(raw.timeout_ms > 0))) {
621
+ throw new ConfigError(`${at}.timeout_ms must be a number > 0`);
622
+ }
623
+ if (raw.args !== undefined && (!Array.isArray(raw.args) || raw.args.some(a => typeof a !== "string"))) {
624
+ throw new ConfigError(`${at}.args must be a list of strings`);
625
+ }
626
+ if (raw.env !== undefined && (!isObj(raw.env) || Object.values(raw.env).some(v => typeof v !== "string"))) {
627
+ throw new ConfigError(`${at}.env must be an object mapping strings to strings`);
628
+ }
629
+ }
630
+ }
631
+
554
632
  function check(cfg: Config): void {
555
633
  if (typeof cfg.harness !== "string" || cfg.harness === "") throw new ConfigError("harness must be a non-empty string");
634
+ checkSpawnConfig(cfg.spawn);
556
635
  try {
557
636
  const pattern = cfg.quota.reset_pattern;
558
637
  new RegExp(pattern);
@@ -6,12 +6,12 @@ import type { Decision, RunSource, SpawnEvent } from "../adapter.ts";
6
6
  import { currentPlanner, currentTier } from "../autonomy.ts";
7
7
  import { lint } from "../brief-lint.ts";
8
8
  import { heldByOther, type ClaimStore } from "../claims.ts";
9
- import { nowSec } from "../clock.ts";
9
+ import { nowSec, strftime } from "../clock.ts";
10
10
  import type { Config } from "../config.ts";
11
11
  import { ownerSaid, readOwnerMessages, type OwnerMessage } from "../incidents.ts";
12
12
  import { defaultRunner, type CommandRunner } from "../mr-sweep.ts";
13
13
  import { approvalProblem } from "../plan-approval.ts";
14
- import { outUntil, pinModel, providerOfModel, readOut } from "../provider-state.ts";
14
+ import { agentProvider, agentRole, outUntil, reachableAgentsForRole, readOut } from "../provider-state.ts";
15
15
  import * as q from "../queue/lib.ts";
16
16
  import type { Plan } from "../queue/lib.ts";
17
17
  import { realGraphify, type ReuseGraph } from "../reuse-map.ts";
@@ -204,7 +204,7 @@ export function preferProblem(agent: string, brief: string, runningJobs: readonl
204
204
  if (/\bPick note:/i.test(brief)) return null;
205
205
  for (let j = 0; j < mine; j++) {
206
206
  const higher = prefer[j]!;
207
- const provider = providerOfModel(pinModel(cfg, higher));
207
+ const provider = agentProvider(cfg, higher);
208
208
  if (provider === null || outUntil(cfg, provider) !== null) continue; // unknown or out
209
209
  const running = (runningJobs ?? []).filter(l => l.toLowerCase().includes(higher.toLowerCase())).length;
210
210
  if (running >= cfg.ledger.max_running_per_provider) continue; // the higher pick is at its provider cap
@@ -213,11 +213,41 @@ export function preferProblem(agent: string, brief: string, runningJobs: readonl
213
213
  return null;
214
214
  }
215
215
 
216
+ /**
217
+ * Refuses spawning an agent whose resolved provider is recorded out in `provider-out.jsonl`,
218
+ * naming the provider, local reset time, and reachable same-role alternatives, unless the brief
219
+ * carries `Pick note: <why>`.
220
+ *
221
+ * Args:
222
+ * agent (string): Agent/profile name being spawned
223
+ * brief (string): Task brief text
224
+ * cfg (Config): Loaded configuration
225
+ * now (number): Current unix epoch seconds
226
+ *
227
+ * Returns:
228
+ * string | null: Refusal reason, or null when allowed or overridden
229
+ */
230
+ export function providerOutProblem(agent: string, brief: string, cfg: Config, now: number = nowSec()): string | null {
231
+ if (/\bPick note:/i.test(brief)) return null;
232
+ const provider = agentProvider(cfg, agent);
233
+ if (provider === null) return null;
234
+ const until = outUntil(cfg, provider, now);
235
+ if (until === null) return null;
236
+ const role = agentRole(cfg, agent);
237
+ const alts = reachableAgentsForRole(cfg, role, now).filter(a => a !== agent);
238
+ const when = strftime(until, "%Y-%m-%d %H:%M");
239
+ const altText =
240
+ alts.length > 0
241
+ ? ` — spawn ${alts.join(" or ")} (${role}) instead, or add "Pick note: <why>" to override.`
242
+ : ` — add "Pick note: <why>" to override.`;
243
+ return `provider ${provider} is out until ${when} (local)${altText}`;
244
+ }
245
+
216
246
  /** P4 (plan 20261031_1207): `agent-ledger --cap`'s FULL line at spawn time — the agent's provider already runs its full share of live subagents. Counted from the caller's running job labels, the live data preferProblem counts (a caller without job info counts 0). */
217
247
  function ledgerCapProblem(agent: string, runningJobs: readonly string[] | undefined, cfg: Config): string | null {
218
- const provider = providerOfModel(pinModel(cfg, agent));
248
+ const provider = agentProvider(cfg, agent);
219
249
  if (provider === null || outUntil(cfg, provider) !== null) return null;
220
- const sharers = [agent, ...cfg.ledger.prefer.filter(a => providerOfModel(pinModel(cfg, a)) === provider)];
250
+ const sharers = [agent, ...cfg.ledger.prefer.filter(a => agentProvider(cfg, a) === provider)];
221
251
  const running = (runningJobs ?? []).filter(l => sharers.some(n => l.toLowerCase().includes(n.toLowerCase()))).length;
222
252
  if (running < cfg.ledger.max_running_per_provider) return null;
223
253
  return `provider ${provider} is at its cap (${running} live of ${cfg.ledger.max_running_per_provider} running); stop or wait for one before spawning more.`;
@@ -255,8 +285,8 @@ export function providerClaimProblem(text: string, cfg: Config): string | null {
255
285
  const free = (provider: string | null): boolean => provider !== null && recorded.has(provider) && outUntil(cfg, provider) === null;
256
286
  const names = new Map<string, string>();
257
287
  for (const p of cfg.ledger.providers) if (free(p)) names.set(p, p);
258
- for (const agent of cfg.ledger.prefer) {
259
- const provider = providerOfModel(pinModel(cfg, agent));
288
+ for (const agent of new Set([...cfg.ledger.prefer, ...Object.keys(cfg.spawn.profiles)])) {
289
+ const provider = agentProvider(cfg, agent);
260
290
  if (free(provider) && !names.has(agent) && provider !== null) names.set(agent, provider);
261
291
  }
262
292
  if (!names.size || !/\bis\b/i.test(text)) return null;
@@ -529,8 +559,13 @@ export function spawnProblem(
529
559
  const claim = providerClaimProblem(joined, cfg);
530
560
  if (claim) problems.push(claim);
531
561
  for (const t of tasks) {
532
- const pick = preferProblem(String(t?.agent ?? "task"), `${context}\n${String(t?.task ?? "")}`, runningJobs, cfg);
533
- if (pick) problems.push(`${String(t?.name ?? t?.agent ?? "task")}: ${pick}`);
562
+ const agent = String(t?.agent ?? "task");
563
+ const taskLabel = String(t?.name ?? agent);
564
+ const taskBrief = `${context}\n${String(t?.task ?? "")}`;
565
+ const out = providerOutProblem(agent, taskBrief, cfg);
566
+ if (out) problems.push(`${taskLabel}: ${out}`);
567
+ const pick = preferProblem(agent, taskBrief, runningJobs, cfg);
568
+ if (pick) problems.push(`${taskLabel}: ${pick}`);
534
569
  }
535
570
  // Priority gate (20261025_0215 P3): once per `task` call, over the plans this call names; the
536
571
  // skip lines may sit in the shared context or any task text.
@@ -683,6 +718,8 @@ function checkSpawnRules(e: SpawnEvent, cfg: Config, runner: CommandRunner = def
683
718
  if (inc) problems.push(inc);
684
719
  const claim = providerClaimProblem(e.brief, cfg);
685
720
  if (claim) problems.push(`${e.agent}: ${claim}`);
721
+ const out = providerOutProblem(e.agent, e.brief, cfg);
722
+ if (out) problems.push(`${e.agent}: ${out}`);
686
723
  const pick = preferProblem(e.agent, e.brief, e.runningJobs, cfg);
687
724
  if (pick) problems.push(`${e.agent}: ${pick}`);
688
725
  const verdict = spawnVerdict(e.agent, problems, named.length ? named : briefPlans(e.brief, cfg).map(p => p.file), e.runningJobs, cfg);
@@ -700,7 +737,7 @@ function checkSpawnRules(e: SpawnEvent, cfg: Config, runner: CommandRunner = def
700
737
  }
701
738
  // The owner's pick order and live provider state (plan 20261025_1700 P3), before the spawn records.
702
739
  const staffing: Record<string, string[]> = {};
703
- for (const f of named) staffing[f] = [e.agent];
740
+ for (const f of named) staffing[f] = [e.name || e.agent];
704
741
  recordSpawns(named, cfg.paths, staffing);
705
742
  if (e.name) recordReviewSpawn(e.name, role.plan, cfg.paths);
706
743
  // planner mode P2 (b): the approved planner spawn binds its name to the plan its brief named.
@@ -4,6 +4,7 @@
4
4
  import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync } from "node:fs";
5
5
  import path from "node:path";
6
6
  import type { Decision } from "../adapter.ts";
7
+ import { currentTier } from "../autonomy.ts";
7
8
  import type { Claim, Unreachable } from "../claims.ts";
8
9
  import { nowSec, strftime } from "../clock.ts";
9
10
  import type { Config } from "../config.ts";
@@ -178,6 +179,28 @@ export function mainCallsResetMs(w: EditWindow): number | null {
178
179
  return w.mainCalls > 0 ? ((w.mainCallsStart ?? 0) + MAIN_CALLS_RESET_SEC) * 1000 : null;
179
180
  }
180
181
 
182
+ /**
183
+ * Returns the latest future reset timestamp (ms since epoch) of any Main call or edit-window cap
184
+ * currently holding Main at `now`, or `null` when no limit is holding Main.
185
+ *
186
+ * Args:
187
+ * cfg (Config): Loaded configuration
188
+ * now (number): Reference epoch timestamp in milliseconds
189
+ *
190
+ * Returns:
191
+ * number | null: Latest pending reset timestamp in ms, or null when uncapped
192
+ */
193
+ export function nextLimitResetMs(cfg: Config, now = Date.now()): number | null {
194
+ const w = readWindow(cfg.paths);
195
+ const tier = currentTier(cfg);
196
+ const resets: number[] = [];
197
+ const calls = mainCallsResetMs(w);
198
+ if (mainCallsCapOn(cfg, tier) && w.mainCalls >= cfg.guards.main_max_calls && calls !== null && calls > now) resets.push(calls);
199
+ const edits = editWindowEndMs(w, cfg);
200
+ if (w.used.length >= mainEditLimit(cfg, tier) && edits > now) resets.push(edits);
201
+ return resets.length > 0 ? Math.max(...resets) : null;
202
+ }
203
+
181
204
  /** Main's terminal hand-back (the adapter's agent_end without willContinue): the turn is over, so
182
205
  * the next one starts at 0 calls. The edit window keeps its own reset rules. */
183
206
  export function resetMainCalls(paths: Pick<q.QueuePaths, "queue_state">): void {
@@ -109,11 +109,13 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
109
109
  };
110
110
  }
111
111
 
112
- // Plans still responsible for: open plans (parked "WAITING on owner" excluded) plus queue problems.
112
+ // Plans still responsible for: open plans (parked "WAITING on owner", awaiting merge, or waiting on
113
+ // another open plan excluded) plus queue problems.
113
114
  export function openQueue(paths: q.QueuePaths, reviewAgents: string[] = []): string[] {
114
- const open = q
115
- .activePlans(paths)
116
- .filter(p => !p.waiting && !q.awaitingMerge(p, paths))
115
+ const plans = q.activePlans(paths);
116
+ const rank = new Map(plans.map((p, i) => [p.file, i + 1]));
117
+ const open = plans
118
+ .filter(p => !p.waiting && !q.awaitingMerge(p, paths) && q.openWaits(p, plans, rank).length === 0)
117
119
  .map(p => p.file);
118
120
  for (const prob of q.queueProblems(paths, reviewAgents)) open.push(`${prob.where}: ${prob.problem}`);
119
121
  const unique: string[] = [];
@@ -197,9 +199,10 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
197
199
  // running subagent's brief names it (staffing ∩ live ledger); unrelated live subagents release
198
200
  // nothing. Valve (20261031_2320): like the incident block above, empty stops count toward
199
201
  // cfg.guards.idle_stops; a stop with calls in between resets the count and re-locks.
202
+ const liveAll = [...new Set([...liveSubagents(e.ledgerText), ...(e.liveAgents ?? [])])];
200
203
  const locked = q.activePlans(cfg.paths).filter(p => p.status === "open" && q.autoCloseCandidate(p) && q.lastCloseFailed(p.file, cfg.paths));
201
204
  if (locked.length) {
202
- const staffed = staffedPlans(readStaffing(cfg.paths), liveSubagents(e.ledgerText));
205
+ const staffed = staffedPlans(readStaffing(cfg.paths), liveAll);
203
206
  const unworked = locked.filter(s => !staffed.includes(s.file));
204
207
  if (unworked.length) {
205
208
  if (state.callsSinceStop === 0) state.idleStops++;
@@ -222,9 +225,8 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
222
225
  }
223
226
  }
224
227
  if (open.length === 0) return { ...ALLOW, state };
225
- const live = liveSubagents(e.ledgerText);
226
- if (live.length > 0) {
227
- log(cfg.paths.guard_log, `ALLOW stop: live subagents: ${live.join(", ")}`);
228
+ if (liveAll.length > 0) {
229
+ log(cfg.paths.guard_log, `ALLOW stop: live subagents: ${liveAll.join(", ")}`);
228
230
  return { ...ALLOW, state };
229
231
  }
230
232
  if (state.callsSinceStop === 0) state.idleStops++;
@@ -101,6 +101,31 @@ function runsCloser(input: Record<string, unknown>): boolean {
101
101
  });
102
102
  }
103
103
 
104
+ /**
105
+ * Detects whether a tool input invokes `neurastream spawn` (launch or `stop`) in any shell
106
+ * segment, while allowing read-only `neurastream spawn list` and `neurastream spawn read`.
107
+ *
108
+ * Args:
109
+ * input (Record<string, unknown>): Tool input object to inspect
110
+ *
111
+ * Returns:
112
+ * boolean: True when any command segment invokes a mutating `neurastream spawn` command
113
+ */
114
+ function runsSpawner(input: Record<string, unknown>): boolean {
115
+ const text = Object.values(input).filter((v): v is string => typeof v === "string").join("\n");
116
+ return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
117
+ const words = seg.trim().split(/\s+/).filter(Boolean).map(w => w.replace(/^["'(]+|["')]+$/g, ""));
118
+ let i = 0;
119
+ while (i < words.length && (LAUNCHERS[words[i] ?? ""] === true || /^\w+=/.test(words[i] ?? "") || /(^|\/)main\.ts$/.test(words[i] ?? ""))) {
120
+ if (bin(words[i]) === "neurastream") break;
121
+ i++;
122
+ }
123
+ const seq = words.slice(i).map(bin);
124
+ if (seq[0] === "neurastream") seq.shift();
125
+ return seq[0] === "spawn" && seq[1] !== "list" && seq[1] !== "read";
126
+ });
127
+ }
128
+
104
129
  const bin = (w: string | undefined) => (w ?? "").replace(/^["']+|["']+$/g, "").split("/").pop() ?? "";
105
130
 
106
131
  // P5g (plan 20261027_0915): the shell text a call would really run — bash's command line, eval's
@@ -218,8 +243,21 @@ function pathArgs(input: Record<string, unknown>): Record<string, unknown> {
218
243
  return out;
219
244
  }
220
245
 
221
- // Subagent half of a tool call (the original plan-guard checkCall without the main return).
222
- // `cap` is the sub's hard call cap: its recorded per-spawn budget, else the global sub_max_calls.
246
+ /**
247
+ * Evaluates subagent-specific tool rules (commit diff-check, closer/spawner CLI blocks, redaction
248
+ * placeholder protection, delegated planner scope, call budget, and phase-0 blockers).
249
+ *
250
+ * Args:
251
+ * e (ToolEvent): Incoming pre-tool event for a subagent
252
+ * input (Record<string, unknown>): Normalized tool input arguments
253
+ * paths (string[]): Resolved paths referenced by the call
254
+ * writes (string[]): Resolved paths mutated by the call
255
+ * cfg (Config): Loaded configuration
256
+ * cap (number): Effective hard call cap for this subagent
257
+ *
258
+ * Returns:
259
+ * string | null: Refusal reason when blocked, or null when allowed
260
+ */
223
261
  function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[], writes: string[], cfg: Config, cap: number): string | null {
224
262
  // P6 (plan 20261024_1915): a sub's `git commit` is scanned first — its staged diff must not add
225
263
  // the removal comments diff-check flags. Detected through GIT_ADD_OR_COMMIT (the predicate
@@ -243,6 +281,9 @@ function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[],
243
281
  // Closing and cancelling are Main's decisions: a shell that runs the tool is refused; one that only names its path is not.
244
282
  if (cfg.guards.shell_tools.includes(e.tool) && runsCloser(input))
245
283
  return 'queue-close and queue-cancel are Main\'s; report in your plan\'s "## Progress" instead.';
284
+ // Spawning or stopping subagents is Main's responsibility only: subs cannot run `neurastream spawn` (except read-only list/read).
285
+ if (cfg.guards.shell_tools.includes(e.tool) && runsSpawner(input))
286
+ return 'only Main may spawn or stop subagents; report what is needed in your plan\'s "## Progress" instead.';
246
287
  // The read tool prints a placeholder for a value it hid, never the value (I-20261027-158,
247
288
  // I-20261027-160: one copy silently broke the shipped config template). Writing that text back
248
289
  // is refused; the file that produces one and the tests that exercise it are the exceptions.
@@ -425,6 +466,17 @@ export function checkTool(e: ToolEvent, cfg: Config, runs?: RunSource): Decision
425
466
  return tuned(checkToolRules(e, cfg, runs), cfg);
426
467
  }
427
468
 
469
+ /**
470
+ * Evaluates pre-tool guard rules for both Main and subagent callers.
471
+ *
472
+ * Args:
473
+ * e (ToolEvent): Incoming pre-tool event
474
+ * cfg (Config): Loaded configuration
475
+ * runs (RunSource | undefined): Optional run source for team-cap accounting
476
+ *
477
+ * Returns:
478
+ * Decision: Guard allow/deny decision with optional context injection
479
+ */
428
480
  function checkToolRules(e: ToolEvent, cfg: Config, runs?: RunSource): Decision {
429
481
  const lock = e.agent === "sub" ? reviewLockProblem(e, cfg) : null;
430
482
  if (lock) {
@@ -522,13 +574,17 @@ function checkToolRules(e: ToolEvent, cfg: Config, runs?: RunSource): Decision {
522
574
  log(cfg.paths.plan_guard_log, `BLOCK sub:${e.agentId} tool=${e.tool} ${why} rule=sub.rule`);
523
575
  return deny(`plan-guard: ${why}`, "sub.rule");
524
576
  }
525
- // A sub's own launch passes the same spawn gates as Main's (plan 20261028_1600 P4i).
526
- let launch: string | null = null;
527
- if (e.tool === "task") launch = taskLaunch(input, cfg, e.runningJobs, "sub", runs);
528
- else if (cfg.guards.shell_tools.includes(e.tool)) launch = bypassLaunch(String(input?.command ?? input?.code ?? ""), cfg, "sub", runs);
529
- if (launch) {
530
- log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} ${launch} rule=sub.launch`);
531
- return deny(`plan-guard: ${launch}`, "sub.launch");
577
+ // Subagents may never spawn nested subagents via `task` or `bypass_spawn` shell commands.
578
+ if (e.tool === "task") {
579
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} sub-spawn refused rule=sub.launch`);
580
+ return deny('plan-guard: only Main may spawn subagents; report what is needed in your plan\'s "## Progress" instead.', "sub.launch");
581
+ }
582
+ if (cfg.guards.shell_tools.includes(e.tool)) {
583
+ const cmd = String(input?.command ?? input?.code ?? "");
584
+ if (cfg.guards.bypass_spawn.some(entry => bypassRegExp(entry).test(cmd))) {
585
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} bypass-spawn refused rule=sub.launch`);
586
+ return deny('plan-guard: only Main may spawn subagents; report what is needed in your plan\'s "## Progress" instead.', "sub.launch");
587
+ }
532
588
  }
533
589
  const n = e.calls + 1;
534
590
  // The warn band has the global width (sub_max_calls - sub_warn_calls) ending at the cap;