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.
package/README.md CHANGED
@@ -23,14 +23,15 @@ flowchart LR
23
23
 
24
24
  | Part | What it enforces |
25
25
  |---|---|
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. |
26
+ | Queue (`queue-check`, `queue-close`, `queue-cancel`, `queue-finished`) | 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. `queue-check` also sweeps the forge: an open MR that no open plan mentions fails it (a missing forge CLI or remote only skips that repo). The summary shows `N/M done` per plan. `queue-finished <word>` searches the list of closed plans. |
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
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). With `guards.chat_unlock` on (default off), the owner's whole chat message `unlock` / `unlock N` / `lock` — typed in the terminal or through a collab guest prompt from a write peer — moves that file instead; nothing a model, a subagent or a tool produces can. |
29
29
  | Ledger (`agent-ledger`) | Tokens, cost, state and exit reason per agent; `--cap` refuses a spawn when a provider already runs `ledger.max_running_per_provider` (default 2), when a run is `OVER-BUDGET` (unless `--incident <id>`), or when a priority plan has no running agent (unless `--priority`). |
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). |
32
- | Plan review gate (`review.*`) | Every plan carries a `## Reuse` section (one checked line per new thing — a queue problem without it); no spawn on a plan without a current reviewer PASS, recorded by plan-guard only from a read-only reviewer subagent's `PLAN REVIEW: PASS` Progress edit (`templates/plan-review-brief.md`, `review.agents`) and expired when the plan text changes; and no spawn while the plan holds done-but-not-merged work — open MRs of its repo, branches with commits off main — that the brief does not name with an `MR !N:` / `Branch <name>:` line. brief-lint enforces the brief side: an MR named in prose without the line, a plan named only under a worktree path instead of its main checkout, and `src/tests` files the plan's blocker `ALLOWED` regex rejects are all refused. Plans stamped before `review.since` are exempt until audited. |
33
- | Write-time checks (`write_check`) | With `write_check.enabled` on, a subagent's write or edit to a file a configured linter covers is linted before and after the call. If the call adds a lint finding or a suppression comment (`noqa` and similar), the file is put back and the call returns an error. Main is left alone unless `applies_to: all`. Off by default. |
32
+ | Plan review gate (`review.*`) | Every plan carries a `## Reuse` section (one checked line per new thing — a queue problem without it); no spawn on a plan without a current reviewer PASS, recorded by plan-guard only from a read-only reviewer subagent's Progress line of the exact form `- [<date> <time> <name>: ]PLAN REVIEW: PASS|FAIL …` (any other `PLAN REVIEW` line is put back; `templates/plan-review-brief.md`, `review.agents`) and expired when the plan text changes — ticking a phase box does not count as a change; and no spawn while the plan holds done-but-not-merged work — open MRs of its repo, branches with commits off main — that the brief does not name with an `MR !N:` / `Branch <name>:` line. brief-lint enforces the brief side: an MR named in prose without the line, a plan named only under a worktree path instead of its main checkout, and `src/tests` files the plan's blocker `ALLOWED` regex rejects are all refused. Plans stamped before `review.since` are exempt until audited. |
33
+ | Review agents (`review.agents`) | `doctor` and `queue-check` fail when no `review.agents` entry is in `## Allowed` of `notes/subagents.md` (no review spawn could run), and warn for each entry that is not. The default `["reviewer"]` needs `neurastream agents allow reviewer`, or set e.g. `review.agents: ["glm"]` in `config.yml`. |
34
+ | Write-time checks (`write_check`) | With `write_check.enabled` on, a subagent's write or edit to a file a configured linter covers is linted before and after the call. If the call adds a lint finding or a suppression comment (`noqa` and similar), the file is put back and the call returns an error. Rules in `write_check.defer_rules` (default: unused names) are not refused at once: the turn's end re-lints and sends one reminder for what is still there, so declare-then-use edits work. Main is left alone unless `applies_to: all`. Off by default. |
34
35
  | Main call cap (`guards.main_max_calls`) | At most 15 tool calls per Main turn — counted since the owner's last message or Main's last hand-back, so answering or delegating wins over grinding. The wrap-up warning comes at `guards.main_warn_calls` (12); the tools in `guards.main_call_exempt_tools` (`task`, `todo`, `ask`, `wait`) are never counted and never refused; `0` switches it off and tier `full` ignores it. |
35
36
  | Machine health (`machine-guard`, `main-start`, `heavy-run`) | Load, free memory, disk and `/tmp` limits; one heavy test run at a time. |
36
37
  | Unlanded work (`wip-check`, `wip-snapshot`, `wip-backup`) | Lists branches on no remote and dirty worktrees; snapshots them as hidden commits; can push them to a backup repo. |
@@ -77,7 +78,7 @@ Check the merged result:
77
78
  neurastream config --json
78
79
  ```
79
80
 
80
- Every tool is one program, selected by the name it was called with: `agent-score`, `agent-ledger`, `brief-lint`, `oc-run`, `wip-check`, `wip-backup`, `wip-snapshot`, `main-health`, `queue-check`, `queue-close`, `queue-cancel`, `queue-trim`, `main-start`, `machine-guard`, `quota-reset`, `priority-watch`, `resource-alerts`, `tmp-snapshot`, `heavy-run`.
81
+ Every tool is one program, selected by the name it was called with: `agent-score`, `agent-ledger`, `brief-lint`, `oc-run`, `wip-check`, `wip-backup`, `wip-snapshot`, `main-health`, `queue-check`, `queue-close`, `queue-cancel`, `queue-finished`, `queue-trim`, `main-start`, `machine-guard`, `quota-reset`, `priority-watch`, `resource-alerts`, `tmp-snapshot`, `heavy-run`.
81
82
 
82
83
  ## Skill pack
83
84
 
@@ -132,7 +133,7 @@ One setting decides how much Main does without asking: `autonomy.tier` in the co
132
133
 
133
134
  `neurastream ui on --login <tailscale login> [--port N]` does the whole setup in one sentence: it writes `ui.enabled: true` and `ui.owner_login` (plus `ui.port` with `--port`) into `~/.config/neurastream/config.yml` — every other line of the file is kept byte-for-byte — copies `templates/systemd/neurastream-ui.service` to `~/.config/systemd/user/neurastream-ui.service`, runs `systemctl --user daemon-reload`, `enable` and `restart`, then prints the phone link `http://<MagicDNS name>:<port>`. The login must be one the tailnet knows (`tailscale status --json`); when tailscale cannot answer, the check is skipped with a printed warning, never a refusal. `neurastream ui off` stops and disables the unit and sets `ui.enabled: false`, keeping `ui.owner_login` for the next `on`.
134
135
 
135
- With `ui.enabled: true` and `ui.owner_login` set (`neurastream config`, `docs/config.md`), `neurastream ui` serves one page bound to this machine's tailnet address only (port `ui.port`, default 7787; `templates/systemd/neurastream-ui.service` runs it as a user unit). A sticky top bar holds the "ns" logo, four pill tabs — Now, Queue, Agents, Spend, each a server-rendered view (`/?tab=…`, an unknown value falls back to Now) — and the lock pill ("🔒 Off" / "🔓 12 min") that opens the guard unlock ("Unlock 15 min", "Unlock 30 min", "Lock now"; when `guards.chat_unlock` is off it says so in plain words with the exact config line). Now is the home tab: a Today tile card over the last 24 h (needs-you count in warn color, list-price spend with a sparkline and the Main/agents split, agent runs with running/died counts and a sparkline, open plans), then one card per open `WAITING on owner:` plan that says why it needs him — the plan's `#` title, then Do (what to do), Stuck until then (what stays blocked, including plans this answer unblocks), and Why you (why Main cannot do it), with the goal folded into a Background block. A question ask gets "Yes"/"No"/"Reply…"; a task ask gets "Done". The answer shows as a one-time receipt ("Sent to Main · 08:12"); once the owner inbox already holds an answer for a plan, the card says so ("You answered ‘yes' · 14:19 — Main is on it") with a small change-answer link. The queue is one flat ranked list in `INDEX.md` order. Each card shows the plan title, a two-line summary from the plan's `Summary:` header (one or two plain sentences under Branch; if that line is missing, the first Goal bullet with a leading Owner or INCIDENT prefix cut off), and a status chip — waits you, waits on another plan, not started, phase K of N, or all N done. Drag a card by its ≡ handle, or tap "↑ top"/"↑"/"↓"; the drop rewrites `INDEX.md`, Main gets the move as a message and the page confirms "Moved to #2". Now shows the first 8 rows with a "Show all N ›" link to the Queue tab. The Agents tab lists working-now rows (a run that died before its first reply shows the model from the spawning agent's `model:` frontmatter, never "?"), the agent-score table, open incidents, recent merges/CI and machine health; the Spend tab pairs the spend tile with per-model spend over 24 h. The Now tab also has a "Tell Main" message box for a text note and up to four images; Main receives the text and pictures, and the page keeps a "Sent today" list for 12 hours before removing those messages and their image files. Light and dark follow the OS; there are no external assets and no build step — one server-rendered HTML string, inline CSS and one small inline script under a per-response CSP nonce (`bun scripts/ui-preview.ts <out.html> [--tab <name>]` renders a preview without a server). No chat, no plan editing, no shell.
136
+ With `ui.enabled: true` and `ui.owner_login` set (`neurastream config`, `docs/config.md`), `neurastream ui` serves one page bound to this machine's tailnet address only (port `ui.port`, default 7787; `templates/systemd/neurastream-ui.service` runs it as a user unit). A sticky top bar holds the "ns" logo, five pill tabs — Now, Queue, Agents, Spend, Base (see "Base tab" below), each a server-rendered view (`/?tab=…`, an unknown value falls back to Now) — and the lock pill ("🔒 Off" / "🔓 12 min") that opens the guard unlock ("Unlock 15 min", "Unlock 30 min", "Lock now"; when `guards.chat_unlock` is off it says so in plain words with the exact config line). Now is the home tab: a Today tile card over the last 24 h (needs-you count in warn color, list-price spend with a sparkline and the Main/agents split, agent runs with running/died counts and a sparkline, open plans), then one card per open `WAITING on owner:` plan that says why it needs him — the plan's `#` title, then Do (what to do), Stuck until then (what stays blocked, including plans this answer unblocks), and Why you (why Main cannot do it), with the goal folded into a Background block. A question ask gets "Yes"/"No"/"Reply…"; a task ask gets "Done". The answer shows as a one-time receipt ("Sent to Main · 08:12"); once the owner inbox already holds an answer for a plan, the card says so ("You answered ‘yes' · 14:19 — Main is on it") with a small change-answer link. The queue is one flat ranked list in `INDEX.md` order. Each card shows the plan title, a two-line summary from the plan's `Summary:` header (one or two plain sentences under Branch; if that line is missing, the first Goal bullet with a leading Owner or INCIDENT prefix cut off), and a status chip — waits you, waits on another plan, not started, phase K of N, or all N done. Drag a card by its ≡ handle, or tap "↑ top"/"↑"/"↓"; the drop rewrites `INDEX.md`, Main gets the move as a message and the page confirms "Moved to #2". Now shows the first 8 rows with a "Show all N ›" link to the Queue tab. The Agents tab lists working-now rows (a run that died before its first reply shows the model from the spawning agent's `model:` frontmatter, never "?"), the agent-score table, open incidents, recent merges/CI and machine health; the Spend tab pairs the spend tile with per-model spend over 24 h. The Now tab also has a "Tell Main" message box for a text note and up to four images; Main receives the text and pictures, and the page keeps a "Sent today" list for 12 hours before removing those messages and their image files. Light and dark follow the OS; there are no external assets and no build step — one server-rendered HTML string, inline CSS and one small inline script under a per-response CSP nonce (`bun scripts/ui-preview.ts <out.html> [--tab <name>]` renders a preview without a server). No chat, no plan editing, no shell.
136
137
 
137
138
  A request is served only when the peer is a tailnet address that is neither loopback nor this machine's own tailnet IP, `tailscale whois` names the `ui.owner_login` login — and the Host header is this machine: the tailnet address or the MagicDNS name, with the served port. The Host check runs on every request before whois, and a POST's Origin must match it, so a DNS-rebinding page (foreign Host, matching Origin, owner's phone) gets a 403 like everyone else. Every request logs one `UI <method> <path> login=<l> → <code>` line to the guard log.
138
139
 
@@ -351,6 +352,8 @@ The report ends with a `Provider honesty over N runs: …` line — provider-hon
351
352
 
352
353
  Weekly loop: run `neurastream metrics report`, then propose ONE rule change to the owner. When the owner decides, record it with `neurastream metrics rule "<text>" --approved|--rejected`; approved rules get a before/after check once a full window has passed. Record CI with `neurastream metrics ci <repo-dir> <mr-id>` and guard false alarms with `neurastream metrics false-alarm <log-ts> --why "<text>"`. main-start shows the report as due when it is missing or older than `metrics.report_days`.
353
354
 
355
+ Feature results: `neurastream metrics features [--days N] [--json]` prints $ per finished feature — a feature is a plan plus every later plan whose Goal names its file stem, finished means every plan in the chain has a closing Progress status or is archived; each hour's Main cost splits evenly over the plan files that hour's messages name (nothing named → overhead), and a sub run's cost goes to the plan its first message names. `neurastream metrics releases [--days N] [--json]` prints, per release (a `v*` tag of this repo or another repo's `metrics ci` merge), the same numbers for the N days before vs after it — $/feature, features/day, main calls/feature, tokens/call, fix plans/feature — plus each configured product number (`metrics.product_cmds`, last value before vs first after). The owner page's Results tab draws the releases as a line chart: the y links pick the metric ($/feature, features/day, calls, tokens, fix rate, or one per product number), the x links switch between time (days on the axis, dashed release markers) and feature/release order; product numbers are neutral — the table marks their direction with ▲/▼ but never colors them better or worse.
356
+
354
357
  ## Self-improvement
355
358
 
356
359
  Bugs in neurastream itself are found by code, written to a persistent list, and pushed on Main until each one has a plan or a recorded dismissal — not remembered. The list is `<paths.queue_state>/incidents.jsonl`; `neurastream incident list [--open] [--json]` reads it.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.49",
3
+ "version": "0.2.51",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -13,7 +13,7 @@ import { stripBlock } from "../../core/agents-md.ts";
13
13
  import { loadConfig } from "../../core/config.ts";
14
14
  import { notifyFindings } from "../../core/notify.ts";
15
15
  import { loadKnownSecrets, proxyOnPath } from "../../core/secret-redact.ts";
16
- import { readIndex } from "../../core/queue/lib.ts";
16
+ import { allowedAgents, readIndex, reviewAgentsProblem } from "../../core/queue/lib.ts";
17
17
  import { realTailscale, type Tailscale } from "../../core/tailscale.ts";
18
18
 
19
19
  const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
@@ -218,6 +218,10 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env,
218
218
  const notify = notifyFindings(cfg);
219
219
  problems.push(...notify.problems);
220
220
  warnings.push(...notify.warnings);
221
+ // P4d (plan 20261028_1600): a review spawn needs a review.agents entry that Main may spawn.
222
+ const review = reviewAgentsProblem(cfg, allowedAgents(cfg.paths.subagents));
223
+ if (review.problem) problems.push(review.problem);
224
+ warnings.push(...review.warnings);
221
225
  // Secrets (plan 20261025_2204): the redactor's state and the second net, count only — doctor
222
226
  // never prints a value. A missing proxy binary is a warning, never a problem: the launch path
223
227
  // falls back to a plain harness start.
@@ -22,11 +22,11 @@ import type { Decision } from "../../core/adapter.ts";
22
22
  import { AGENTS_TEMPLATE, renderBlock } from "../../core/agents-md.ts";
23
23
  import { chatGo, chatTier, type Tier } from "../../core/autonomy.ts";
24
24
  import { burdenRule, repoRules, rulesChanged } from "../../core/repo-rules.ts";
25
- import { loadConfig, type Config } from "../../core/config.ts";
25
+ import { configFile, loadConfig, reloadingConfig, type Config } from "../../core/config.ts";
26
26
  import { checkWrite, deferSteer, type WriteCheckConfig } from "../../core/write-check.ts";
27
27
  import { nowSec, strftime } from "../../core/clock.ts";
28
28
  import { runDetectors, runDetectorsGated, type DetectorInput } from "../../core/incident-detectors.ts";
29
- import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, newProgressEntries, planReadNote, recordMainResult, resetMainCalls, revertMainEdit, rekeySpawnFile } from "../../core/guards.ts";
29
+ import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, newProgressEntries, planReadNote, recordMainResult, resetMainCalls, revertMainEdit, rekeySpawnFile, reviewSpawnEnd } from "../../core/guards.ts";
30
30
  import { rateLimitWait } from "../../core/rate-limit.ts";
31
31
  import { notifyProviders, postReply } from "../../core/notify.ts";
32
32
  import { loadKnownSecrets, redactSecrets, redactSummary } from "../../core/secret-redact.ts";
@@ -565,8 +565,10 @@ export function deliverOwnerInbox(pi: ExtensionHost, cfg: Config): void {
565
565
  adapterLog(cfg, `owner inbox: delivered ${delivered} answer(s) (cursor ${cursor} → ${next})`);
566
566
  }
567
567
 
568
- /** Register the guard handlers on one extension host. `cfg` is injectable for tests. */
569
- export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
568
+ /** Register the guard handlers on one extension host. `initial` is injectable for tests; `freshConfig` re-reads the config per guarded call. */
569
+ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig: () => Config = () => initial): void {
570
+ // Guarded handlers take `cfg = freshConfig()` first, so an edited config.yml reaches the next call (P4e).
571
+ let cfg = initial;
570
572
  // The queue library resolves its paths from env snapshots; point them at this config first.
571
573
  applyQueueEnv(cfg);
572
574
  // Main's rules ride its system prompt each turn; they are never written into the owner's AGENTS.md.
@@ -575,12 +577,12 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
575
577
  let callsSinceStop = 0;
576
578
  let idleStops = 0;
577
579
  let timer: unknown;
578
- let inboxTimer: unknown;
579
580
  const calls = new Map<string, number>(); // subagent call budget, by agent id
580
581
  const pending = new Map<string, Map<string, string>>(); // toolCallId -> plan snapshots
581
582
  const pendingWrite = new Map<string, Map<string, string | null>>(); // toolCallId -> write-check snapshots; null: the file did not exist
582
583
  const deferredWrite = new Map<string, Map<string, string | null>>(); // agent id -> files that added deferred findings this turn -> text before the first one (null: new file); judged at that session's own agent_end
583
584
  const pendingRules = new Set<string>(); // repos Main worked in, rules to hand over at the next prompt
585
+ const pendingReviewNotes: string[] = []; // P4k: review spawns that ended with no verdict; Main hears at its next prompt
584
586
  // Chat notify (plans 20261024_2155, 20261025_0130): the text a hand-back already posted
585
587
  // (attempted) — one post per distinct text, never a retry loop. The reply itself comes from
586
588
  // the stop/agent_end event, never the session file (session_stop fires BEFORE agent_end, and
@@ -747,7 +749,6 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
747
749
  ? c.setInterval(() => deliverOwnerInbox(pi, cfg), OWNER_INBOX_POLL_MS)
748
750
  : setInterval(() => deliverOwnerInbox(pi, cfg), OWNER_INBOX_POLL_MS);
749
751
  if (it && typeof it === "object" && "unref" in it && typeof it.unref === "function") it.unref();
750
- inboxTimer = it;
751
752
  });
752
753
 
753
754
  // What a subagent is still missing (plan 20261027_1530 P2): the rules of the repo its plan is
@@ -786,6 +787,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
786
787
  };
787
788
 
788
789
  pi.on("before_agent_start", (event, ctx) => {
790
+ cfg = freshConfig();
789
791
  const c = asCtx(ctx);
790
792
  const prompt = asString(asRecord(event).prompt);
791
793
  if (c.kind !== "main") {
@@ -816,12 +818,13 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
816
818
  if (r && rulesChanged(cfg, asString(c.id) || "main", r.path, r.text)) rules.push(`Repo rules (${r.path}):\n${r.text}`);
817
819
  }
818
820
  pendingRules.clear();
821
+ const reviewNotes = isMain(ctx) ? pendingReviewNotes.splice(0) : [];
819
822
  const hostPrompt = asRecord(event).systemPrompt;
820
823
  return {
821
824
  systemPrompt: [...(Array.isArray(hostPrompt) ? hostPrompt : []), mainRules],
822
825
  message: {
823
826
  customType: "main-guard.queue",
824
- content: [d.inject, notice, ...rules].filter(Boolean).join("\n\n"),
827
+ content: [d.inject, notice, ...reviewNotes, ...rules].filter(Boolean).join("\n\n"),
825
828
  display: false,
826
829
  },
827
830
  };
@@ -830,7 +833,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
830
833
  // The spawn event carries no brief, so the plan gate runs at the task tool call (original
831
834
  // behaviour); here only the allow-list and the task-only rule apply, with the original texts.
832
835
  pi.on("before_subagent_spawn", (event, ctx) => {
833
- if (asCtx(ctx).kind === "sub") return;
836
+ cfg = freshConfig();
834
837
  const agent = asString(asRecord(event).agent);
835
838
  const kind = asString(asRecord(event).invocationKind);
836
839
  if (!q.allowedAgents().has(agent))
@@ -840,7 +843,10 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
840
843
  return undefined;
841
844
  });
842
845
 
846
+ let lastMainRc: RolloverCtx | null = null;
847
+
843
848
  pi.on("tool_call", (event, ctx) => {
849
+ cfg = freshConfig();
844
850
  const c = asCtx(ctx);
845
851
  const e = asRecord(event);
846
852
  const tool = asString(e.toolName);
@@ -859,8 +865,10 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
859
865
  // running ones finish first. Subagents' own tool calls are unaffected. Main's task calls
860
866
  // also carry the running job labels for the priority gate (20261025_0215 P2).
861
867
  let runningJobs: string[] | undefined;
862
- if (!isSub && tool === "task") {
863
- const rc = asRolloverCtx(ctx);
868
+ if (!isSub) lastMainRc = asRolloverCtx(ctx);
869
+ if (tool === "task") {
870
+ // A subagent's task call drains and labels by Main's rollover context: its own ctx has none.
871
+ const rc = lastMainRc;
864
872
  runningJobs = rc?.runningJobs();
865
873
  if (cfg.rollover.enabled && rc) {
866
874
  const why = spawnRefusal(rolloverSnapshot(rc).state, runningJobs ?? []);
@@ -902,6 +910,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
902
910
  };
903
911
 
904
912
  pi.on("tool_result", (event, ctx) => {
913
+ cfg = freshConfig();
905
914
  onSizeCheck("tool_result", event, ctx);
906
915
  const e = asRecord(event);
907
916
  const c = asCtx(ctx);
@@ -928,7 +937,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
928
937
  try {
929
938
  after = readFileSync(file, "utf8");
930
939
  } catch {}
931
- const d = checkPlanEdit({ path: file, before, after, agent: c.kind === "sub" ? "sub" : "main" }, cfg);
940
+ const d = checkPlanEdit({ path: file, before, after, agent: c.kind === "sub" ? "sub" : "main", agentId: id }, cfg);
932
941
  if (!d.allow && d.restore) {
933
942
  try {
934
943
  if (d.restore.text === null) rmSync(d.restore.path, { force: true });
@@ -1012,6 +1021,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
1012
1021
  });
1013
1022
 
1014
1023
  pi.on("session_stop", (e, ctx) => {
1024
+ cfg = freshConfig();
1015
1025
  const c = asCtx(ctx);
1016
1026
  if (c.hasAgent && c.kind !== "main") return;
1017
1027
  // A relaunch is requested: omp shuts down at the next idle, so the stop must not be continued.
@@ -1348,6 +1358,13 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
1348
1358
  if (asRecord(e).willContinue === true) return;
1349
1359
  resetMainCalls();
1350
1360
  });
1361
+ // P4k backstop (plan 20261028_1600): a named review spawn that ends with no verdict recorded at its edit is judged here, from its own plan file; the note tells Main at its next prompt.
1362
+ pi.on("agent_end", (_e, ctx) => {
1363
+ const c = asCtx(ctx);
1364
+ if (c.kind !== "sub" || !c.id) return;
1365
+ const note = reviewSpawnEnd(c.id, cfg);
1366
+ if (note) pendingReviewNotes.push(note);
1367
+ });
1351
1368
 
1352
1369
  // omp is really shutting down: the exit-grace fallback must not fire.
1353
1370
  pi.on("session_shutdown", () => clearGrace?.());
@@ -1535,5 +1552,6 @@ export default function ompExtension(pi: ExtensionHost): void {
1535
1552
  // no config read. `neurastream main` sets it for its child (launch.ts), so anything the Main
1536
1553
  // session spawns inherits it and stays guarded.
1537
1554
  if (process.env[MAIN_ENV] !== "1") return;
1538
- createOmpAdapter(pi, loadConfig());
1555
+ const initial = loadConfig();
1556
+ createOmpAdapter(pi, initial, reloadingConfig(initial, configFile(), () => loadConfig(), line => adapterLog(initial, line)));
1539
1557
  }
@@ -158,13 +158,10 @@ function build(file: string, cfg: Config, mtime: number, agentsDir: string): Run
158
158
  } catch {
159
159
  continue;
160
160
  }
161
- const ts = d.timestamp;
162
- if (typeof ts === "string") {
163
- const t = parseTs(ts);
164
- if (t !== null) {
165
- first = first ?? t;
166
- last = t;
167
- }
161
+ const ts = typeof d.timestamp === "string" ? parseTs(d.timestamp) : null;
162
+ if (ts !== null) {
163
+ first = first ?? ts;
164
+ last = ts;
168
165
  }
169
166
  if (d.customType === "session_exit") exited = true;
170
167
  if (d.customType === "tool_execution_start") {
@@ -222,7 +219,12 @@ function build(file: string, cfg: Config, mtime: number, agentsDir: string): Run
222
219
  role: typeof m.role === "string" ? m.role : "",
223
220
  cost: lineCost,
224
221
  text: pyDumps(m.content ?? "").slice(0, 20000),
222
+ ts,
225
223
  });
224
+ } else if (m.role === "user" && !messages.length) {
225
+ // A sub keeps only its first user message: results (src/core/results.ts) price the run
226
+ // by the plan path that message names.
227
+ messages.push({ role: "user", cost: lineCost, text: pyDumps(m.content ?? "").slice(0, 20000), ts });
226
228
  }
227
229
  }
228
230
 
@@ -271,7 +273,8 @@ function build(file: string, cfg: Config, mtime: number, agentsDir: string): Run
271
273
  startedAt: first,
272
274
  lastWriteAt: mtime,
273
275
  endedAt: last,
274
- messages: isMain ? messages : [],
276
+ // Subs: build() above keeps only the first user message, which results.ts prices by.
277
+ messages,
275
278
  scoreModel,
276
279
  scoreCost,
277
280
  scoreHours: ((last ?? 0) - (first ?? 0)) / 3600,
@@ -68,7 +68,7 @@ export function helpText(): string {
68
68
  " neurastream guard <event> --json",
69
69
  ` (${GUARD_USAGE.slice(GUARD_USAGE.indexOf("(") + 1, -1)})`,
70
70
  " neurastream main [args] run omp under the launcher (automatic session rollover)",
71
- " neurastream metrics <cmd> self-metrics: report, ci, false-alarm, rule (see README)",
71
+ " neurastream metrics <cmd> self-metrics: report, features, releases, ci, false-alarm, rule (see README)",
72
72
  " neurastream incident <cmd> incidents Main must act on: list, add, plan, dismiss (see README)",
73
73
  " neurastream traces claims <runId|--since 24h> [--json]",
74
74
  " check a run's final-report claims (test counts, exit codes,",
package/src/cli/guard.ts CHANGED
@@ -65,11 +65,18 @@ function decide(event: string, p: Record<string, unknown>, cfg: Config): Decisio
65
65
  invocationKind: asString(p.invocationKind, "task"),
66
66
  brief: asString(p.brief ?? p.context ?? p.task),
67
67
  ...(p.runningJobs === undefined ? {} : { runningJobs: asStringList(p.runningJobs) }),
68
+ ...(p.name === undefined ? {} : { name: asString(p.name) }),
68
69
  };
69
70
  return checkSpawn(e, cfg);
70
71
  }
71
72
  case "plan-edit": {
72
- const e: PlanEditEvent = { path: asString(p.path), before: asString(p.before), after: asString(p.after), agent: asAgent(p.agent) };
73
+ const e: PlanEditEvent = {
74
+ path: asString(p.path),
75
+ before: asString(p.before),
76
+ after: asString(p.after),
77
+ agent: asAgent(p.agent),
78
+ ...(p.agentId === undefined ? {} : { agentId: asString(p.agentId) }),
79
+ };
73
80
  return checkPlanEdit(e, cfg);
74
81
  }
75
82
  case "stop": {
@@ -5,13 +5,15 @@
5
5
  import { existsSync, mkdirSync, writeFileSync } from "node:fs";
6
6
  import { join } from "node:path";
7
7
  import { ConfigError, loadConfig, type Config } from "../core/config.ts";
8
- import { appendMetric } from "../core/metrics.ts";
8
+ import { appendMetric, readMetricEvents } from "../core/metrics.ts";
9
9
  import { nowSec } from "../core/clock.ts";
10
10
  import type { RunSource } from "../core/adapter.ts";
11
11
  import { buildReport, type BloatSummary, type ProviderSummary } from "../core/report.ts";
12
12
  import { providerFindings } from "../core/trace-provider.ts";
13
13
  import { bloatRules } from "../core/trace-bloat.ts";
14
14
  import { getAdapter } from "../adapters/index.ts";
15
+ import { featuresReport, gatherTags, loadPlans, releasesReport, type FeaturesReport, type ReleasesReport } from "../core/results.ts";
16
+ import { gitTop } from "../core/queue/lib.ts";
15
17
  import { assignDumps, bloatReport } from "./traces.ts";
16
18
 
17
19
  export const METRICS_USAGE = [
@@ -19,6 +21,8 @@ export const METRICS_USAGE = [
19
21
  ' neurastream metrics false-alarm <log-ts> --why "<text>"',
20
22
  ' neurastream metrics rule "<text>" --approved|--rejected',
21
23
  " neurastream metrics report [--days N]",
24
+ " neurastream metrics features [--days N] [--json]",
25
+ " neurastream metrics releases [--days N] [--json]",
22
26
  ].join("\n");
23
27
 
24
28
  function flagValue(args: string[], name: string): string | undefined {
@@ -67,9 +71,31 @@ export function recordCi(cfg: Config, repoDir: string, mr: string, now: number):
67
71
  }
68
72
  appendMetric(cfg, { type: "ci", mr, repo: repoDir, tries: pipelines.length, ts: now });
69
73
  console.log(`ci: ${mr} needed ${pipelines.length} pipeline(s)`);
74
+ recordProducts(cfg, repoDir, now);
70
75
  return 0;
71
76
  }
72
77
 
78
+ const PRODUCT_TIMEOUT_MS = 10_000;
79
+
80
+ /**
81
+ * Runs the repo's configured product numbers once each (metrics.product_cmds) and appends one
82
+ * product record per number. A command that fails, times out or prints anything but one finite
83
+ * number is skipped with a stderr line; the ci record itself never fails on a product number.
84
+ */
85
+ function recordProducts(cfg: Config, repoDir: string, now: number): void {
86
+ for (const [name, cmd] of Object.entries(cfg.metrics.product_cmds[repoDir] ?? {})) {
87
+ const proc = Bun.spawnSync(["sh", "-c", cmd], { cwd: repoDir, stdout: "pipe", stderr: "pipe", timeout: PRODUCT_TIMEOUT_MS });
88
+ const out = proc.stdout.toString().trim();
89
+ const value = Number(out);
90
+ if (proc.exitCode !== 0 || out === "" || !Number.isFinite(value)) {
91
+ const why = proc.exitCode !== 0 ? `exit ${proc.exitCode ?? "signal"}` : `not one number: "${out.slice(0, 40)}"`;
92
+ console.error(`product_cmds.${name}: skipped (${why})`);
93
+ continue;
94
+ }
95
+ appendMetric(cfg, { type: "product", repo: repoDir, name, value, ts: now });
96
+ }
97
+ }
98
+
73
99
  /** Marks one guard BLOCK line (by its ISO timestamp) as a false alarm. */
74
100
  export function recordFalseAlarm(cfg: Config, logTs: string, why: string, now: number): number {
75
101
  if (!logTs || !why) {
@@ -153,6 +179,102 @@ export function reportCmd(cfg: Config, source: RunSource, args: string[], now: n
153
179
  return 0;
154
180
  }
155
181
 
182
+ /** Local `YYYY-MM-DD HH:MM`, the stamp style Progress entries use. */
183
+ function localStamp(ts: number): string {
184
+ const d = new Date(ts * 1000);
185
+ const two = (n: number) => String(n).padStart(2, "0");
186
+ return `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}`;
187
+ }
188
+
189
+ function featuresTable(r: FeaturesReport): string {
190
+ const out = [`Results: last ${r.days} days [${localStamp(r.from)} to ${localStamp(r.to)})`];
191
+ out.push("stem kind plans fix $total $first closed at");
192
+ for (const row of r.rows) {
193
+ out.push(
194
+ `${row.stem.padEnd(30)} ${row.kind.padEnd(11)} ${String(row.plans).padEnd(5)} ${String(row.fixPlans).padEnd(4)} ` +
195
+ `${row.total.toFixed(2).padEnd(7)} ${row.first.toFixed(2).padEnd(7)} ${localStamp(row.closedAt)}`,
196
+ );
197
+ }
198
+ for (const s of r.summaries) {
199
+ const perFeature = s.perFeature === null ? "n/a" : `$${s.perFeature.toFixed(2)}`;
200
+ const firstPass = s.firstPass === null ? "n/a" : `$${s.firstPass.toFixed(2)}`;
201
+ const overhead = s.overheadPct === null ? "n/a" : `${s.overheadPct.toFixed(0)}%`;
202
+ out.push(
203
+ `${s.kind}: finished ${s.finished} (${s.perDay.toFixed(2)}/day), ${perFeature}/feature, first-pass ${firstPass}, ` +
204
+ `overhead ${overhead}, open chains ${s.openChains} ($${s.openSunk.toFixed(2)} sunk)`,
205
+ );
206
+ }
207
+ return out.join("\n");
208
+ }
209
+
210
+ /** `metrics features`: $ per finished feature over the queue's own plan chains. */
211
+ export function featuresCmd(cfg: Config, source: RunSource, args: string[], now: number): number {
212
+ const raw = flagValue(args, "--days");
213
+ const days = raw === undefined ? cfg.metrics.report_days : Number(raw);
214
+ if (!Number.isInteger(days) || days < 1) {
215
+ console.error(METRICS_USAGE);
216
+ return 2;
217
+ }
218
+ const report = featuresReport(source.listRuns(now - days * 86400), loadPlans(cfg), gitTop(import.meta.dir)?.repo ?? null, now - days * 86400, now);
219
+ if (args.includes("--json")) {
220
+ console.log(JSON.stringify(report, null, 2));
221
+ return 0;
222
+ }
223
+ console.log(featuresTable(report));
224
+ return 0;
225
+ }
226
+
227
+ function releasesTable(r: ReleasesReport): string {
228
+ const out = [
229
+ `Releases: per release, ${r.days} days before vs after (measuring = the after window is still filling); ` +
230
+ "columns: $/feature, features/day, main calls/feature, tokens/call, fix plans/feature, product numbers",
231
+ ];
232
+ for (const row of r.rows) {
233
+ // Five columns share the before→after cell shape; digits differ per column.
234
+ const pair = (a: number | null, b: number | null, digits = 2) =>
235
+ `${a === null ? "n/a" : a.toFixed(digits)}→${b === null ? "n/a" : b.toFixed(digits)}`;
236
+ const products = row.before.products.map((p, i) => {
237
+ const after = row.after.products[i]?.value ?? null;
238
+ return `${p.name} ${p.value === null ? "-" : String(p.value)}→${after === null ? "-" : String(after)}`;
239
+ });
240
+ out.push(
241
+ `${row.name.padEnd(20)} ${row.kind.padEnd(12)} ${localStamp(row.ts)} ` +
242
+ `${pair(row.before.perFeature, row.after.perFeature)} ` +
243
+ `${pair(row.before.featuresPerDay, row.after.featuresPerDay)} ` +
244
+ `${pair(row.before.callsPerFeature, row.after.callsPerFeature, 1)} ` +
245
+ `${pair(row.before.tokensPerCall, row.after.tokensPerCall, 1)} ` +
246
+ `${pair(row.before.fixPlansPerFeature, row.after.fixPlansPerFeature)} ` +
247
+ products.join(" ") +
248
+ (row.measuring ? " measuring" : ""),
249
+ );
250
+ }
251
+ return out.join("\n");
252
+ }
253
+
254
+ /** `metrics releases`: per release — a self `v*` tag or another repo's `metrics ci` merge — the
255
+ * same ledger metrics for the N days before vs after it. */
256
+ export function releasesCmd(cfg: Config, source: RunSource, args: string[], now: number): number {
257
+ const raw = flagValue(args, "--days");
258
+ const days = raw === undefined ? 7 : Number(raw);
259
+ if (!Number.isInteger(days) || days < 1) {
260
+ console.error(METRICS_USAGE);
261
+ return 2;
262
+ }
263
+ const selfRepo = gitTop(import.meta.dir)?.repo ?? null;
264
+ const tags = gatherTags(selfRepo);
265
+ const events = readMetricEvents(cfg);
266
+ // A release's before window reaches back past the features window, so ask for runs since the
267
+ // oldest release's window start.
268
+ const oldest = Math.min(now, ...tags.map(t => t.ts), ...events.filter(e => e.type === "ci").map(e => Number(e.ts)));
269
+ const report = releasesReport(source.listRuns(oldest - days * 86400), loadPlans(cfg), selfRepo, days, now, tags, events);
270
+ if (args.includes("--json")) {
271
+ console.log(JSON.stringify(report, null, 2));
272
+ return 0;
273
+ }
274
+ console.log(releasesTable(report));
275
+ return 0;
276
+ }
277
+
156
278
  export async function runMetrics(args: string[]): Promise<number> {
157
279
  let cfg: Config;
158
280
  try {
@@ -165,6 +287,8 @@ export async function runMetrics(args: string[]): Promise<number> {
165
287
  const now = nowSec();
166
288
  if (sub === "ci") return recordCi(cfg, rest[0] ?? "", rest[1] ?? "", now);
167
289
  if (sub === "report") return reportCmd(cfg, getAdapter(cfg).runSource(cfg), rest, now);
290
+ if (sub === "features") return featuresCmd(cfg, getAdapter(cfg).runSource(cfg), rest, now);
291
+ if (sub === "releases") return releasesCmd(cfg, getAdapter(cfg).runSource(cfg), rest, now);
168
292
  if (sub === "false-alarm") return recordFalseAlarm(cfg, rest[0] ?? "", flagValue(rest, "--why") ?? "", now);
169
293
  if (sub === "rule") {
170
294
  const approved = rest.includes("--approved");
@@ -8,6 +8,8 @@ export interface RunMessage {
8
8
  role: string;
9
9
  cost: number;
10
10
  text: string;
11
+ /** Unix seconds the line was written at; null when the line carried no readable timestamp. */
12
+ ts: number | null;
11
13
  }
12
14
 
13
15
  export interface Run {
@@ -116,6 +118,8 @@ export interface SpawnEvent {
116
118
  brief: string;
117
119
  /** Labels of the harness's own running background jobs; undefined when the caller has no job info. */
118
120
  runningJobs?: string[];
121
+ /** The spawn's name (its task name); keys the review lock of a named review spawn (P4f). */
122
+ name?: string;
119
123
  }
120
124
 
121
125
  export interface InjectEvent {
@@ -128,6 +132,8 @@ export interface PlanEditEvent {
128
132
  before: string;
129
133
  after: string;
130
134
  agent: "main" | "sub";
135
+ /** The sub's agent id; a review spawn's PLAN REVIEW line counts only from its own id (P4f). */
136
+ agentId?: string;
131
137
  }
132
138
 
133
139
  export interface StopEvent {
@@ -1,7 +1,7 @@
1
1
  // Loads ~/.config/neurastream/config.yml over templates/config.yml.
2
2
  // Values (paths, names, prices) live in the template, not in this file.
3
3
 
4
- import { existsSync, readFileSync } from "node:fs";
4
+ import { existsSync, readFileSync, statSync } from "node:fs";
5
5
  import { homedir } from "node:os";
6
6
  import { dirname, join } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
@@ -179,7 +179,7 @@ export interface Config {
179
179
  /** Repo-local HTML explainers under docs/knowledge/ (owner page Knowledge tab). */
180
180
  knowledge: { roots: string[]; max_age_s: number };
181
181
  rollover: { enabled: boolean; max_session_mb: number; exit_grace_s: number };
182
- metrics: { report_days: number; correction_patterns: string[]; ci_pipelines_cmd: string };
182
+ metrics: { report_days: number; correction_patterns: string[]; ci_pipelines_cmd: string; product_cmds: Record<string, Record<string, string>> };
183
183
  /** Incident detectors (src/core/incident-detectors.ts): when a sighting becomes an incident. */
184
184
  incidents: {
185
185
  /** Minutes after a finished task-result before a RUNNING/WAITING ledger row contradicts it. */
@@ -319,6 +319,32 @@ export function configFile(home = homedir()): string {
319
319
  return join(home, ".config", "neurastream", "config.yml");
320
320
  }
321
321
 
322
+ /**
323
+ * The config as of now. Each call stats `file`; when its mtime changed it calls `load()`.
324
+ * A failed reload keeps the last good config and reports one line through `onError`, so a
325
+ * broken edit never fails open or crashes a running guard. Used by a harness adapter per guarded call.
326
+ */
327
+ export function reloadingConfig(
328
+ initial: Config,
329
+ file: string,
330
+ load: () => Config,
331
+ onError: (line: string) => void,
332
+ ): () => Config {
333
+ let cfg = initial;
334
+ let seen = statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? 0;
335
+ return () => {
336
+ const now = statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? 0;
337
+ if (now === seen) return cfg;
338
+ seen = now;
339
+ try {
340
+ cfg = load();
341
+ } catch (err) {
342
+ onError(`config reload refused, keeping the last good config: ${err instanceof Error ? err.message : String(err)}`);
343
+ }
344
+ return cfg;
345
+ };
346
+ }
347
+
322
348
  function isObj(v: unknown): v is Record<string, unknown> {
323
349
  return typeof v === "object" && v !== null && !Array.isArray(v);
324
350
  }
@@ -530,6 +556,15 @@ function check(cfg: Config): void {
530
556
  throw new ConfigError(`metrics.correction_patterns: not a valid regex: ${p}`);
531
557
  }
532
558
  }
559
+ if (typeof cfg.metrics.product_cmds !== "object" || cfg.metrics.product_cmds === null || Array.isArray(cfg.metrics.product_cmds))
560
+ throw new ConfigError("metrics.product_cmds must map a repo path to {name: command}");
561
+ for (const [repo, cmds] of Object.entries(cfg.metrics.product_cmds)) {
562
+ if (typeof cmds !== "object" || cmds === null || Array.isArray(cmds)) throw new ConfigError(`metrics.product_cmds.${repo} must map a name to a command`);
563
+ for (const [name, cmd] of Object.entries(cmds)) {
564
+ if (name === "") throw new ConfigError(`metrics.product_cmds.${repo}: command names must be non-empty`);
565
+ if (typeof cmd !== "string" || cmd.trim() === "") throw new ConfigError(`metrics.product_cmds.${repo}.${name} must be a non-empty shell command`);
566
+ }
567
+ }
533
568
  for (const [provider, pattern] of Object.entries(cfg.traces.provider.id_patterns)) {
534
569
  if (typeof pattern !== "string") throw new ConfigError(`traces.provider.id_patterns.${provider} must be a string`);
535
570
  try {