neurastream 0.2.4 → 0.2.6

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
@@ -25,7 +25,7 @@ flowchart LR
25
25
  |---|---|
26
26
  | Queue (`queue-check`, `queue-close`, `queue-cancel`) | Every open plan is a file in a main checkout, listed in the one main index (`paths.queue_index`, one absolute path per line — never repo directories) and follows a template; one plan = one worktree. A plan leaves the queue only when its branch is merged into remote main and its done check passes; a failing check reopens it. Closing removes the plan's worktree when it is clean and its branch landed — a plain `git worktree remove`; a dirty, unmerged or unremovable worktree and the repo's main checkout are kept with the reason. Branches leave only via `git branch -d`, so a branch whose merge git cannot see stays. |
27
27
  | Blockers | Each plan's phase 0 lists what helpers may not do: push, touch a path, run a command, or write a text. The guard judges the command that runs and the files it changes, not words inside commit messages, quoted text or heredoc bodies: `git commit -m "... push ..."` is allowed, `git push` is refused. |
28
- | Guards | Helpers may only edit their plan's `## Progress`; every new entry ends with a `Findings:` line (`Findings: none`, or one item per finding with `file:line` evidence) or the edit is refused and the file restored, and each item becomes an incident. Helpers get a warning at call 90 and are stopped at call 100. Protected files need an owner unlock (a file the owner touches, valid 30 minutes). |
28
+ | Guards | Helpers may only edit their plan's `## Progress`; every new entry ends with a `Findings:` line (`Findings: none`, or one item per finding with `file:line` evidence) or the edit is refused and the file restored, and each item becomes an incident. Helpers get a warning at call 90 and are stopped at call 100; Main can set a different stop for one run with a `Call budget: <N>` line in the task brief (see "Main reads the code for its plans" below). Protected files need an owner unlock (a file the owner touches, valid 30 minutes). |
29
29
  | Ledger (`agent-ledger`) | Tokens, cost, state and exit reason per agent; `--cap` refuses a spawn when a provider already runs 2. |
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). |
@@ -87,6 +87,7 @@ Owner rule: never write a plan when another agent is doing the research or readi
87
87
  - Cutoff: plans whose filename stamp is `20261021_0100` or later must carry a non-empty `## Code read by Main` section. Older plans are grandfathered.
88
88
  - Retention: entries older than 7 days are dropped on each write.
89
89
  - Spawn briefs: a brief must name an unticked phase id of the plan (for example `P4`). A brief that asks for research for a plan to be written is refused, quoting the owner rule.
90
+ - Call budget: a `Call budget: <N>` line in a task brief (the task's own text, or the shared `context` of the same `task` call; the task's own line wins) gives that run a hard stop at N calls, with the warning N − (`guards.sub_max_calls` − `guards.sub_warn_calls`) calls in, floored at 1. At the stop only plan Progress reads and edits pass, as at the global limit. N must be between 10 and `guards.sub_max_calls_cap` (default 200) and the task must carry a `name` — the budget is keyed by it in `<queue_state>/spawn-budgets.json` — or the spawn is refused with the allowed range. A task without the line keeps the global warn 90 / stop 100, and the ledger flags a still-running sub `OVER-BUDGET` past its own N.
90
91
 
91
92
  ## Queue holds
92
93
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
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": ["ai-agents", "coding-agents", "orchestration", "guardrails", "omp", "bun", "cli"],
6
6
  "homepage": "https://github.com/umiddey/neurastream#readme",
@@ -3,6 +3,7 @@ import { basename, join } from "node:path";
3
3
  import type { Config } from "../../core/config.ts";
4
4
  import type { MainSession, Run, RunMessage, RunSource, RunStatus } from "../../core/adapter.ts";
5
5
  import { nowSec } from "../../core/clock.ts";
6
+ import { readBudgets } from "../../core/guards.ts";
6
7
  import { pyDumps } from "../../core/pyjson.ts";
7
8
 
8
9
  function walk(dir: string, depth: number, out: string[]): void {
@@ -165,8 +166,9 @@ function build(file: string, cfg: Config, mtime: number): Run | null {
165
166
  state = (waiting || "RUNNING") + (idle >= cfg.ledger.idle_show_min ? ` (idle ${idle}m)` : "");
166
167
  } else if (id.startsWith("MAIN")) state = "done";
167
168
  else state = `DIED: ${err || "exited without a result"}`;
168
- if ((state.startsWith("RUNNING") || state.startsWith("WAITING")) && !id.startsWith("MAIN") && calls > cfg.guards.sub_max_calls) {
169
- state += ` OVER-BUDGET(${calls}>${cfg.guards.sub_max_calls} calls)`;
169
+ if ((state.startsWith("RUNNING") || state.startsWith("WAITING")) && !id.startsWith("MAIN")) {
170
+ const cap = readBudgets(cfg.paths.queue_state)[id] ?? cfg.guards.sub_max_calls;
171
+ if (calls > cap) state += ` OVER-BUDGET(${calls}>${cap} calls)`;
170
172
  }
171
173
  let status: RunStatus = "done";
172
174
  if (state.startsWith("WAITING")) status = "waiting";
@@ -85,9 +85,16 @@ export function agentLedger(args: string[], cfg: Config, source: RunSource): num
85
85
  }
86
86
  let full = Object.entries(live).filter(([, v]) => v.length >= cfg.ledger.max_running_per_provider).map(([k]) => k);
87
87
  for (const k of full) process.stdout.write(`FULL ${k}: ${live[k]!.join(", ")}\n`);
88
- const over = rows.filter(r => r.statusDetail.includes("OVER-BUDGET")).map(r => r.id);
88
+ const over = rows.filter(r => r.statusDetail.includes("OVER-BUDGET"));
89
89
  if (over.length) {
90
- process.stdout.write(`OVER-BUDGET: ${over.join(", ")} past ${cfg.guards.sub_max_calls} calls: stop them (report + fresh agent with tight brief) before spawning more\n`);
90
+ // Each run reports the cap it was spawned with (its own per-spawn budget, else the global
91
+ // one); the cap is part of the statusDetail the session parser wrote. When every cap is the
92
+ // global one the line stays exactly the original's (golden parity).
93
+ const caps = over.map(r => /OVER-BUDGET\(\d+>(\d+) calls\)/.exec(r.statusDetail)?.[1] ?? String(cfg.guards.sub_max_calls));
94
+ const list = caps.every(c => c === String(cfg.guards.sub_max_calls))
95
+ ? `${over.map(r => r.id).join(", ")} past ${cfg.guards.sub_max_calls} calls`
96
+ : `${over.map((r, i) => `${r!.id} (past ${caps[i]} calls)`).join(", ")}`;
97
+ process.stdout.write(`OVER-BUDGET: ${list}: stop them (report + fresh agent with tight brief) before spawning more\n`);
91
98
  }
92
99
  if (args.includes("--provider")) {
93
100
  const provider = opt(args, "--provider");
@@ -140,7 +140,8 @@ function matchesPath(p: string, glob: string, call: BlockerCall): boolean {
140
140
  // ---- Shell: a quote-aware splitter, not a shell parser ---------------------------------------
141
141
  // Splits on `;`, `&&`, `||`, `|`, `&`, `(`, `)` and newlines outside quotes. Each word keeps its
142
142
  // quote-removed text and whether any part was quoted; output-redirection targets are kept apart
143
- // from the words; heredoc bodies are dropped; the inside of `$(…)` and backticks becomes segments.
143
+ // from the words; heredoc bodies are kept on their opening segment; the inside of `$(…)` and
144
+ // backticks becomes segments.
144
145
 
145
146
  export interface ShellWord {
146
147
  /** Text with quotes and escapes removed; a substitution contributes nothing (its segments are listed). */
@@ -156,6 +157,8 @@ export interface ShellSegment {
156
157
  words: ShellWord[];
157
158
  /** Targets of output redirections: `>`, `>>`, `>|`, `&>`, `&>>`, `<>`, and `>&file`. */
158
159
  writes: string[];
160
+ /** Bodies of the heredocs this segment opens; for an interpreter they are its code. */
161
+ bodies: string[];
159
162
  }
160
163
 
161
164
  type WordBuf = { text: string; quoted: boolean; start: number };
@@ -176,7 +179,7 @@ function scan(src: string, out: ShellSegment[]): void {
176
179
  redir: RedirKind | null;
177
180
  tabs: boolean;
178
181
  heredocs: { delim: string; tabs: boolean }[];
179
- } = { seg: { words: [], writes: [] }, word: null, redir: null, tabs: false, heredocs: [] };
182
+ } = { seg: { words: [], writes: [], bodies: [] }, word: null, redir: null, tabs: false, heredocs: [] };
180
183
  let i = 0;
181
184
 
182
185
  const ensure = (): WordBuf => {
@@ -198,22 +201,27 @@ function scan(src: string, out: ShellSegment[]): void {
198
201
  if (kind === "write" || (kind === "dup" && !/^(\d+|-)$/.test(word.text))) st.seg.writes.push(word.text);
199
202
  else if (kind === "heredoc") st.heredocs.push({ delim: word.text, tabs: st.tabs });
200
203
  };
201
- const endSeg = (end: number): void => {
204
+ const endSeg = (end: number): ShellSegment | null => {
202
205
  endWord(end);
203
206
  st.redir = null;
204
- if (st.seg.words.length || st.seg.writes.length) out.push(st.seg);
205
- st.seg = { words: [], writes: [] };
207
+ const ended = st.seg.words.length || st.seg.writes.length ? st.seg : null;
208
+ if (ended) out.push(ended);
209
+ st.seg = { words: [], writes: [], bodies: [] };
210
+ return ended;
206
211
  };
207
- // Skips the bodies of the heredocs opened on the line before `from`; returns the index after them.
208
- const skipHeredocs = (from: number): number => {
212
+ // Skips the bodies of the heredocs opened on the line before `from`, keeping their text in
213
+ // `into`; returns the index after them.
214
+ const skipHeredocs = (from: number, into: string[]): number => {
209
215
  let j = from;
210
216
  for (const h of st.heredocs) {
217
+ const start = j;
211
218
  while (j < n) {
212
219
  const e = src.indexOf("\n", j);
213
220
  const line = src.slice(j, e < 0 ? n : e);
214
221
  j = e < 0 ? n : e + 1;
215
222
  if ((h.tabs ? line.replace(/^\t+/, "") : line) === h.delim) break;
216
223
  }
224
+ into.push(src.slice(start, j));
217
225
  }
218
226
  st.heredocs = [];
219
227
  return j;
@@ -281,8 +289,8 @@ function scan(src: string, out: ShellSegment[]): void {
281
289
  } else if (c === "#" && !st.word) {
282
290
  while (i < n && src.charAt(i) !== "\n") i++;
283
291
  } else if (c === "\n") {
284
- endSeg(i);
285
- i = skipHeredocs(i + 1);
292
+ const ended = endSeg(i);
293
+ i = skipHeredocs(i + 1, ended ? ended.bodies : []);
286
294
  } else if (c === ";" || c === "(" || c === ")") {
287
295
  endSeg(i);
288
296
  i++;
@@ -400,7 +408,10 @@ const INTERPRETERS: Record<string, true> = {
400
408
  const GIT_VALUE_OPTS: Record<string, true> = { "-C": true, "-c": true, "--git-dir": true, "--work-tree": true, "--namespace": true };
401
409
  const MUTATING_NAMES: Record<string, true> = { rm: true, mv: true, truncate: true, tee: true, patch: true };
402
410
  const GIT_MUTATING: Record<string, true> = { rm: true, mv: true, checkout: true, restore: true };
403
- const CODE_WRITE = /writeFile|Bun\.write|unlink/;
411
+ // Code-write forms, one list for shell and eval: the code parts of queue/lib.ts MUTATING plus
412
+ // Ruby's File.write. Never fork a second list.
413
+ const CODE_WRITE =
414
+ /writeFile|appendFile|Bun\.write|unlink|rmSync|\.write_text\(|\.write_bytes\(|\bopen\([^)]*,\s*["'][wax]b?\+?["']|shutil\.|os\.(remove|rename|replace|unlink|chmod)|\.writelines\(|File\.write/;
404
415
 
405
416
  interface ShellCommand {
406
417
  name: string;
@@ -490,7 +501,7 @@ function mutationTargets(seg: ShellSegment): string[] {
490
501
  if (mutating) out.push(...ops);
491
502
  else if (cmd.name === "cp" && ops.length) out.push(ops[ops.length - 1] ?? "");
492
503
  else if (cmd.name === "sed" && cmd.args.some((a) => /^-[a-zA-Z]*i|^--in-place/.test(a.text))) out.push(...ops.slice(1));
493
- const raw = seg.words.map((w) => w.raw).join(" ");
504
+ const raw = [...seg.words.map((w) => w.raw), ...seg.bodies].join(" ");
494
505
  if (INTERPRETERS[cmd.name] === true && CODE_WRITE.test(raw)) {
495
506
  out.push(...raw.split(/[\s;&|<>(),'"]+/).filter((t) => t !== "" && !t.startsWith("-")));
496
507
  }
@@ -585,7 +596,8 @@ export function denyPath(env: BlockerEnv): void {
585
596
  let targets: string[] = [];
586
597
  if (env.writes) targets = (env.call.paths ?? []).filter((p) => !MAIN_PLAN_FILE.test(p));
587
598
  else if (env.call.tool === "eval") {
588
- if (CODE_MUTATING.test(env.command)) targets = [...(env.call.paths ?? []), ...evalPaths(env)];
599
+ if (CODE_MUTATING.test(env.command) || CODE_WRITE.test(env.command))
600
+ targets = [...(env.call.paths ?? []), ...evalPaths(env)];
589
601
  } else if (env.shell) targets = shellTargets(env);
590
602
  for (const p of targets) {
591
603
  for (const g of env.args) {
@@ -1,6 +1,7 @@
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
5
  import { exitText, helpDoc, printText } from "./help.ts";
5
6
  import { sections } from "./queue/lib.ts";
6
7
 
@@ -82,8 +83,10 @@ function lint(path: string, cfg: Config): { errs: string[]; warns: string[] } {
82
83
  }
83
84
  }
84
85
 
86
+ // The brief's call-budget rule: either the classic "stop within ~N calls" line or a Main-set
87
+ // per-spawn `Call budget: <N>` line counts.
85
88
  need(
86
- /\b\d{1,3}\s*(tool\s*)?calls\b/.test(low),
89
+ /\b\d{1,3}\s*(tool\s*)?calls\b/.test(low) || briefBudget(text) !== null,
87
90
  "missing: call budget line ('stop and report within ~100 calls'); long agents reread huge contexts",
88
91
  );
89
92
 
@@ -100,6 +100,8 @@ export interface Config {
100
100
  guards: {
101
101
  sub_warn_calls: number;
102
102
  sub_max_calls: number;
103
+ /** Highest per-spawn `Call budget: <N>` a task brief may set. */
104
+ sub_max_calls_cap: number;
103
105
  main_edit_limit: number;
104
106
  main_window_min: number;
105
107
  unlock_minutes: number;
@@ -280,6 +282,9 @@ function check(cfg: Config): void {
280
282
  if (cfg.guards.sub_warn_calls > cfg.guards.sub_max_calls) {
281
283
  throw new ConfigError("guards.sub_warn_calls must be <= guards.sub_max_calls");
282
284
  }
285
+ if (cfg.guards.sub_max_calls_cap < cfg.guards.sub_max_calls) {
286
+ throw new ConfigError("guards.sub_max_calls_cap must be >= guards.sub_max_calls");
287
+ }
283
288
  if (!(cfg.rollover.max_session_mb > 0)) throw new ConfigError("rollover.max_session_mb must be > 0");
284
289
  if (!(cfg.rollover.exit_grace_s > 0)) throw new ConfigError("rollover.exit_grace_s must be > 0");
285
290
  if (!(cfg.metrics.report_days >= 1)) throw new ConfigError("metrics.report_days must be >= 1");
@@ -124,6 +124,57 @@ export function rekeySpawnFile(file: string, before: string, after: string): voi
124
124
  }
125
125
  }
126
126
 
127
+ // A per-spawn call budget: `Call budget: <N>` on its own line in a task brief (the task's own
128
+ // text wins over the shared context). Main sets it at spawn time; the run's hard stop is N and
129
+ // its warning band has the global width (sub_max_calls - sub_warn_calls), floored at 1.
130
+ const BUDGET_LINE = /^\s*(?:[-*]\s+)?call budget:\s*(\d{1,4})\s*$/im;
131
+
132
+ /** The first `Call budget: <N>` line of a brief, or null. */
133
+ export function briefBudget(brief: string): number | null {
134
+ const m = BUDGET_LINE.exec(brief);
135
+ return m ? Number(m[1]) : null;
136
+ }
137
+
138
+ function budgetsFile(): string {
139
+ return path.join(q.STATE_DIR, "spawn-budgets.json");
140
+ }
141
+
142
+ /** The budgets recorded at spawn: task name → calls (next to the spawn hashes). */
143
+ export function readBudgets(dir: string = q.STATE_DIR): Record<string, number> {
144
+ try {
145
+ const raw: unknown = JSON.parse(readFileSync(path.join(dir, "spawn-budgets.json"), "utf8"));
146
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
147
+ const out: Record<string, number> = {};
148
+ for (const [k, v] of Object.entries(raw)) if (typeof v === "number" && Number.isFinite(v)) out[k] = v;
149
+ return out;
150
+ } catch {
151
+ return {};
152
+ }
153
+ }
154
+
155
+ /** Remember the named tasks' call budgets; a name's old budget is replaced, a null one removed. */
156
+ export function recordBudgets(entries: Record<string, number | null>): void {
157
+ const names = Object.keys(entries);
158
+ if (!names.length) return;
159
+ const budgets = readBudgets();
160
+ for (const n of names) {
161
+ const b = entries[n];
162
+ if (b == null) delete budgets[n];
163
+ else budgets[n] = b;
164
+ }
165
+ try {
166
+ mkdirSync(q.STATE_DIR, { recursive: true });
167
+ writeFileSync(budgetsFile(), JSON.stringify(budgets, null, 1));
168
+ } catch (err) {
169
+ log(`${q.STATE_DIR}/../main-guard.log`, `cannot write ${budgetsFile()}: ${err}`);
170
+ }
171
+ }
172
+
173
+ /** A sub's hard call cap: the budget recorded for its task name at spawn, else the global cap. */
174
+ export function subCallCap(agentId: string, cfg: Config): number {
175
+ return readBudgets()[agentId] ?? cfg.guards.sub_max_calls;
176
+ }
177
+
127
178
  // --- shared pieces ---
128
179
 
129
180
  function unlocked(cfg: Config): boolean {
@@ -230,19 +281,35 @@ export function planGate(text: string, label: string): [string | null, string[]]
230
281
  return [null, named.map(p => p.file)];
231
282
  }
232
283
 
233
- /** Reason to refuse a `task` brief, or null; `files` receives the plans to record. */
234
- export function spawnProblem(input: Record<string, unknown>, files: string[] = []): string | null {
284
+ /** Reason to refuse a `task` brief, or null; `files` receives the plans to record, `budgets` every named task's call budget (null = none). */
285
+ export function spawnProblem(
286
+ input: Record<string, unknown>,
287
+ cfg: Config,
288
+ files: string[] = [],
289
+ budgets: Record<string, number | null> = {},
290
+ ): string | null {
235
291
  const tasks = Array.isArray(input?.tasks) ? input.tasks : [];
236
292
  const context = String(input?.context ?? "");
237
293
  const allowed = q.allowedAgents();
294
+ const shared = briefBudget(context);
295
+ const named: Record<string, number | null> = {};
238
296
  for (const t of tasks) {
239
297
  const agent = String(t?.agent ?? "task");
240
298
  const label = String(t?.name ?? agent);
241
299
  if (!allowed.has(agent)) return `${label}: agent "${agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`;
242
- const [why, named] = planGate(`${context}\n${String(t?.task ?? "")}`, label);
300
+ const [why, plans] = planGate(`${context}\n${String(t?.task ?? "")}`, label);
243
301
  if (why) return why;
244
- files.push(...named);
302
+ // The task's own `Call budget:` line wins over the shared context's.
303
+ const budget = briefBudget(String(t?.task ?? "")) ?? shared;
304
+ if (budget !== null) {
305
+ if (!t?.name) return `${label}: "Call budget: ${budget}" needs a task name (the budget is keyed by it).`;
306
+ if (budget < 10 || budget > cfg.guards.sub_max_calls_cap)
307
+ return `${label}: call budget ${budget} is outside the allowed range 10..${cfg.guards.sub_max_calls_cap}.`;
308
+ }
309
+ if (t?.name) named[label] = budget;
310
+ files.push(...plans);
245
311
  }
312
+ Object.assign(budgets, named);
246
313
  return null;
247
314
  }
248
315
 
@@ -282,16 +349,17 @@ function runsCloser(input: Record<string, unknown>): boolean {
282
349
  }
283
350
 
284
351
  // Subagent half of a tool call (the original plan-guard checkCall without the main return).
285
- function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[], writes: string[], cfg: Config): string | null {
352
+ // `cap` is the sub's hard call cap: its recorded per-spawn budget, else the global sub_max_calls.
353
+ function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[], writes: string[], cfg: Config, cap: number): string | null {
286
354
  // Closing and cancelling are Main's decisions: a shell that runs the tool is refused; one that only names its path is not.
287
355
  if (cfg.guards.shell_tools.includes(e.tool) && runsCloser(input))
288
356
  return 'queue-close and queue-cancel are Main\'s; report in your plan\'s "## Progress" instead.';
289
357
  const plans = q.activePlans();
290
- if (e.calls >= cfg.guards.sub_max_calls) {
358
+ if (e.calls >= cap) {
291
359
  const planEdit = (e.tool === "write" || e.tool === "edit") && writes.length > 0 && writes.every(p => q.planAt(p, plans));
292
360
  const planRead = cfg.guards.read_tools.includes(e.tool) && paths.length > 0 && paths.every(p => q.planAt(p, plans));
293
361
  if (!planEdit && !planRead)
294
- return `call budget spent (${e.calls}/${cfg.guards.sub_max_calls}). Only reading and editing your plan's "## Progress" is allowed now: write what you did, what is verified, what is next, then end your run.`;
362
+ return `call budget spent (${e.calls}/${cap}). Only reading and editing your plan's "## Progress" is allowed now: write what you did, what is verified, what is next, then end your run.`;
295
363
  }
296
364
  if (!plans.length || !paths.length) return null;
297
365
  for (const p of writes) {
@@ -393,7 +461,8 @@ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): De
393
461
  return deny(`main-guard: ${CANCEL_TODO} Flagged: "${pending.words}"`);
394
462
  }
395
463
  const files: string[] = [];
396
- const why = spawnProblem(input, files);
464
+ const budgets: Record<string, number | null> = {};
465
+ const why = spawnProblem(input, cfg, files, budgets);
397
466
  if (why) {
398
467
  log(cfg.paths.guard_log, `BLOCK spawn: ${why}`);
399
468
  return deny(`main-guard: ${why}`);
@@ -401,6 +470,7 @@ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): De
401
470
  const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
402
471
  if (inc) return deny(`main-guard: ${inc}`);
403
472
  recordSpawns(files);
473
+ recordBudgets(budgets);
404
474
  return ALLOW;
405
475
  }
406
476
  if (cfg.guards.shell_tools.includes(e.tool)) {
@@ -467,17 +537,21 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
467
537
  if (d.allow && e.tool !== "task") recordMainReads(paths.filter(p => !writes.includes(p)));
468
538
  return d;
469
539
  }
470
- const why = subRules(e, input, paths, writes, cfg);
540
+ const cap = subCallCap(e.agentId, cfg);
541
+ const why = subRules(e, input, paths, writes, cfg, cap);
471
542
  if (why) {
472
543
  log(cfg.paths.plan_guard_log, `BLOCK sub:${e.agentId} tool=${e.tool} ${why}`);
473
544
  return deny(`plan-guard: ${why}`);
474
545
  }
475
546
  const n = e.calls + 1;
476
- if (n >= cfg.guards.sub_warn_calls && n < cfg.guards.sub_max_calls)
547
+ // The warn band has the global width (sub_max_calls - sub_warn_calls) ending at the cap;
548
+ // unbudgeted subs keep sub_warn_calls exactly.
549
+ const warn = cap === cfg.guards.sub_max_calls ? cfg.guards.sub_warn_calls : Math.max(1, cap - (cfg.guards.sub_max_calls - cfg.guards.sub_warn_calls));
550
+ if (n >= warn && n < cap)
477
551
  return {
478
552
  allow: true,
479
553
  reason: "",
480
- inject: `plan-guard: call ${n}/${cfg.guards.sub_max_calls}. Update your plan's "## Progress" now (done, verified, next); at ${cfg.guards.sub_max_calls} only that edit is allowed.`,
554
+ inject: `plan-guard: call ${n}/${cap}. Update your plan's "## Progress" now (done, verified, next); at ${cap} only that edit is allowed.`,
481
555
  };
482
556
  return ALLOW;
483
557
  }
@@ -100,6 +100,7 @@ queue:
100
100
  guards:
101
101
  sub_warn_calls: 90
102
102
  sub_max_calls: 100
103
+ sub_max_calls_cap: 200
103
104
  main_edit_limit: 5
104
105
  main_window_min: 15
105
106
  unlock_minutes: 30