neurastream 0.2.3 → 0.2.5

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.3",
3
+ "version": "0.2.5",
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");
@@ -1,9 +1,34 @@
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";
6
+ import { sections } from "./queue/lib.ts";
5
7
 
6
8
  const OUTPUT_HINT = /(report|progress|review|handoff|log|brief)[\w\-]*\.(md|log|txt|json)$|\.log$/;
9
+ const TICKED_PHASE = /^\s*[-*]\s+\[[xX]\]/;
10
+
11
+ // A plan's paths are live work only in the header lines, Goal, Forbidden, Blockers, unticked phase
12
+ // lines and Done check. Ticked phases and the history sections (Code read by Main, Progress,
13
+ // Background) cite worktrees removed after their work landed, so the path check skips them. A plain
14
+ // brief (no `## Phases`) is checked whole.
15
+ function liveText(text: string): string {
16
+ const secs = sections(text);
17
+ if (!secs.has("phases")) return text;
18
+ const header = text.slice(0, text.search(/^## /m));
19
+ const unticked = (secs.get("phases") ?? "")
20
+ .split("\n")
21
+ .filter(l => !TICKED_PHASE.test(l))
22
+ .join("\n");
23
+ return [
24
+ header,
25
+ secs.get("goal") ?? "",
26
+ secs.get("forbidden") ?? "",
27
+ secs.get("blockers") ?? "",
28
+ unticked,
29
+ secs.get("done check") ?? "",
30
+ ].join("\n");
31
+ }
7
32
 
8
33
  function escapeReg(s: string): string {
9
34
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -41,9 +66,10 @@ function lint(path: string, cfg: Config): { errs: string[]; warns: string[] } {
41
66
 
42
67
 
43
68
  const paths = new Set<string>();
69
+ const scan = liveText(text);
44
70
  for (const prefix of cfg.brief.path_prefixes) {
45
71
  const re = new RegExp(`(${escapeReg(prefix)}[\\w./\\-]+)`, "g");
46
- for (const hit of text.matchAll(re)) paths.add(hit[1]!);
72
+ for (const hit of scan.matchAll(re)) paths.add(hit[1]!);
47
73
  }
48
74
  for (const raw of [...paths].sort()) {
49
75
  let p = raw.replace(/[.,)]+$/, "");
@@ -57,8 +83,10 @@ function lint(path: string, cfg: Config): { errs: string[]; warns: string[] } {
57
83
  }
58
84
  }
59
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.
60
88
  need(
61
- /\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,
62
90
  "missing: call budget line ('stop and report within ~100 calls'); long agents reread huge contexts",
63
91
  );
64
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