neurastream 0.2.18 → 0.2.20

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
@@ -80,6 +80,8 @@ Green is both exiting 0.
80
80
 
81
81
  `neurastream traces efficiency --since 7d` reports wasted tool calls from recent traces; pass a run id to inspect one run, or add `--json` for machine-readable per-run records (including step indexes and matched rules). Waste rules cover repeated reads and failed commands, failed edits, repeated guard blocks and idle polling. The agent-score board adds `Calls/acc` and `Waste` columns; `score.waste_weight` (default `0`) scales ranking by the wasted-call fraction while leaving the default ranking unchanged.
82
82
 
83
+ `neurastream traces briefs --since 30d` lists each spawn brief Main sent (shared context first, then the task's own text) with its features — length, a `file:line`, a verify command, a phase id, a plan path, a `Call budget` line, the number of acceptance lines — next to the spawned agent's waste and whether its work was accepted. `--json` gives the rows, `--report` compares the rows with and without each feature (a side with fewer than `traces.briefs.min_n` rows prints "n too small"). Brief text never prints. Read the report with care: a spawn without a plan is never accepted, and accept records exist only since scoring began, so all-time accept rates mostly measure when and for what an agent was spawned, not how good the brief was. Compare plan briefs from the same period before turning a gap into a rule; on 30 days of real briefs that comparison showed no feature strong enough for a brief-lint warning.
84
+
83
85
  `agent-score accept` records accepted work by commit; `agent-score validate <Agent> --plan <plan.md> --phase <P> --evidence <report.md> --section "<heading prefix>"` records a validation phase (checks/tests ran, report section written, no commits) with proof Main cannot fake by typing: the plan line must be ticked `- [x]`, the cited section body must name a heavy-run label run by that agent (from `paths.heavy_log`), and the phase must not be scored already. The ranking board counts it in `Accepted (diag/val)` as `N (d/v)`.
84
86
 
85
87
  ## Main reads the code for its plans
@@ -174,8 +176,8 @@ neurastream notify test # posts one line to every configured channel; exit 1 w
174
176
  Guard rules around it:
175
177
 
176
178
  - No agent (Main included) can read a configured secret file, list its directory, or glob over it — unlock or not. Writes to the secret files and to `~/.config/neurastream/config.yml` need the owner's unlock like any guard file.
177
- - A stop the guard blocks posts nothing; when Main continues and really hands back later, that later stop posts the final text. A subagent session never posts, and a relaunch (the launcher's rollover) posts nothing.
178
- - The post never delays the stop decision: it times out at 5 seconds per chunk, makes one attempt, and writes one guard-log line when a channel fails. Long replies are split per channel (Discord 2000, Slack 3000 characters) on line boundaries where possible.
179
+ - A blocked stop still posts its final reply once when it has text; agent_end skips that blocked stop to avoid a duplicate. Every post is serialized in call order; Discord 429 responses wait for `retry_after` (or `Retry-After`, default 1 s; capped at 10 s) and retry the chunk once.
180
+ - Posts time out at 5 seconds per attempt. Long replies are split per channel (Discord 2000, Slack 3000 characters) on line boundaries where possible; failures are logged without delaying the stop decision.
179
181
 
180
182
  "Needs you" pings use the same channels so the owner learns on the phone that a decision is his: when a Main turn ends with an open plan whose `WAITING on owner:` line was not pinged before, neurastream posts `🔔 Needs you — <plan>: <question>` (with the `neurastream ui` phone-page link when `ui.enabled: true`), and when the guard refuses a Main tool call because it touches a protected guard file, it posts `🔓 Main needs an unlock to continue (<file>)` — the unlock ping at most once per 30 minutes, each waiting question once until its line changes or disappears, remembered in `<queue_state>/notify-waiting.json`. Every decision logs one `notify: needs-you posted|skipped (<why>)` guard-log line.
181
183
 
@@ -193,6 +195,10 @@ The wait is the `retry-after-ms=<ms>` or `retry-after: <seconds>` the error text
193
195
 
194
196
  omp retries a 429 itself while the provider's wait fits its `retry.maxDelayMs` (300000 ms by default); only a longer wait ends the turn (`Retry failed after 1 attempts: Provider requested 731000ms wait, exceeds retry.maxDelayMs`), and that turn end is what neurastream waits out.
195
197
 
198
+ ## Provider reset times
199
+
200
+ Before Main reads a message, reset timestamps matching `quota.reset_pattern` are annotated with their local time, for example `reset at 2026-10-25 18:56:22 (= 2026-10-25 11:56:22 CET local)`. Set `quota.reset_tz` to the provider's time zone; an explicit zone or UTC offset in the message takes precedence.
201
+
196
202
  ## Trace claims (`neurastream traces claims`)
197
203
 
198
204
  Agents' final reports assert results — "530 passed", "exit 0", commit SHAs, heavy-run labels, changed files. This command reads a run's trace (its session file, read-only) and checks each claim in the run's last assistant message against what the run's own tool activity shows: a count or exit code must appear in some tool output, a commit SHA must be printed by the output of a git command the run itself ran, a heavy-run label must appear in a quoted heavy-run call, and a changed path must be carried by an edit/write call or a shell write in the path's own command segment. A claim nothing shows becomes a `claim-unbacked` finding.
@@ -231,6 +237,30 @@ traces:
231
237
 
232
238
  Finding evidence is masked (long token-like runs never survive verbatim) and capped at 160 characters, so a response id or a tool call line cannot carry a secret into the findings.
233
239
 
240
+ ## Prompt bloat (`neurastream traces bloat`)
241
+
242
+ `neurastream traces bloat [--since 24h] [--json]` (or one run by id) lists, per run, every model call's prompt — `usage.input + usage.cacheRead + usage.cacheWrite`, one row per call — and flags `prompt-bloat` when
243
+
244
+ - the run's FIRST call opens over `traces.bloat.first_call_max` (a run that starts huge stays huge), or
245
+ - any call passes `traces.bloat.ratio_of_limit` × its model's `traces.bloat.context_limits` entry (an open map; a model without an entry is not limit-checked).
246
+
247
+ A failed request dump under `~/.omp/logs/http-400-requests` (named `<epoch-ms>-<id>.json`) belongs to one run only: its trace window must cover the dump, its model must match, and among eligible runs the closest event timestamp at or before the dump wins. An exact tie—or no eligible run—leaves the dump unmatched; text and `--json` output list unmatched dumps once. For the owning run, the report shows what filled the prompt: system, messages and tool groups (tools grouped by the first capture of `traces.bloat.tool_group` on the tool name; no match = `builtin`) plus the five largest individual tools.
248
+
249
+ A rejected call never wrote usage, so a run can carry a 1.17M-token prompt with no usage row and no finding of its own. When a run has no usage finding, the matched dump's error response is read: a stated prompt size ("prompt is too long: 1172629 tokens > 1000000 maximum") becomes the flag, with the dump named as the source. A dump whose error response states no count flags nothing, and no size is ever guessed from bytes.
250
+
251
+ `neurastream metrics report` ends with a weekly line — `Prompt bloat over N runs: K flagged, largest first call X tokens (<run>)` — over every run touched in the window (largest first call = the run's usage, else the matched dump's stated prompt). The agent ledger shows a `tok/call` column: prompt tokens ÷ calls per run.
252
+
253
+ Config (defaults):
254
+
255
+ ```yaml
256
+ traces:
257
+ bloat:
258
+ first_call_max: 150000
259
+ ratio_of_limit: 0.8
260
+ context_limits: {} # e.g. claude-opus-5-5: 1000000
261
+ tool_group: '^_?mcp__([A-Za-z0-9]+)_'
262
+ ```
263
+
234
264
  ## Self-metrics
235
265
 
236
266
  `neurastream metrics report [--days N]` compares this window (the last `metrics.report_days`, default 7) with the one before it, writes `<paths.notes>/metrics.md`, and prints the same report. Worst change is marked `◀ worst`. The five numbers:
@@ -243,7 +273,7 @@ Finding evidence is masked (long token-like runs never survive verbatim) and cap
243
273
 
244
274
  Caveat: M4 is a whole-run measure. A main run counts entirely by its last write time, so a run that spans a window edge counts in the window it ends in.
245
275
 
246
- The report ends with a `Provider honesty over N runs: …` line — provider-honesty findings (see Provider honesty above) over every run touched in the window.
276
+ The report ends with a `Provider honesty over N runs: …` line — provider-honesty findings (see Provider honesty above) over every run touched in the window — and a `Prompt bloat over N runs: …` line (see Prompt bloat above) over the same runs.
247
277
 
248
278
  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`.
249
279
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.18",
3
+ "version": "0.2.20",
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",
@@ -36,6 +36,7 @@ import { defaultCompletedResults, defaultRunSource, runIdOf } from "./sessions.t
36
36
  import { parseTraceFile } from "./traces.ts";
37
37
  import { packageJsonPath, packageVersion } from "./package-root.ts";
38
38
  import * as q from "../../core/queue/lib.ts";
39
+ import { annotateResetTimes } from "../../core/reset-time.ts";
39
40
  // Registers the plugin-command matcher into core's writeTargets (side effect).
40
41
  import "./package-ops.ts";
41
42
 
@@ -577,10 +578,11 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
577
578
  adapterLog(cfg, "notify: needs-you skipped (no new waiting lines)");
578
579
  return;
579
580
  }
580
- for (const p of fresh) {
581
+ const lines = fresh.map(p => {
581
582
  const title = p.text.match(/^# (.+)$/m)?.[1] ?? basename(p.file);
582
- needsYouPost(`🔔 Needs you — ${title}: ${p.waitingLine}.${phonePage()}`, `waiting: ${basename(p.file)}`);
583
- }
583
+ return `- ${title}: ${p.waitingLine}`;
584
+ });
585
+ needsYouPost(`🔔 Needs you (${fresh.length}):\n${lines.join("\n")}${phonePage()}`, `waiting: ${fresh.length} plans`);
584
586
  };
585
587
  // UNLOCK: a protected-file refusal of a Main tool call means Main sits blocked until the owner
586
588
  // unlocks — ping, at most once per 30 min.
@@ -794,7 +796,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
794
796
  const snap = rolloverSnapshot(rc);
795
797
  if (snap.state === "need-note") {
796
798
  adapterLog(cfg, "BLOCK stop: rollover need-note");
797
- adapterLog(cfg, "notify: skipped (stop blocked: rollover need-note)");
799
+ notifyHandback(reply, "blocked session_stop");
798
800
  stopBlocked = true;
799
801
  return { decision: "block", reason: noteRequestFor(rc, snap) };
800
802
  }
@@ -815,7 +817,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
815
817
  notifyHandback(reply, "allowed session_stop");
816
818
  return undefined;
817
819
  }
818
- adapterLog(cfg, "notify: skipped (stop blocked by guard)");
820
+ notifyHandback(reply, "blocked session_stop");
819
821
  stopBlocked = true;
820
822
  return { decision: "block", reason: d.reason };
821
823
  });
@@ -1123,29 +1125,55 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
1123
1125
  const seenChatPrompts = new Set<string>();
1124
1126
  const CHAT_PROMPT_MAX_AGE_MS = 10 * 60_000;
1125
1127
  pi.on("context", (event, ctx) => {
1126
- if (!cfg.guards.chat_unlock || !isMain(ctx)) return undefined;
1128
+ if (!isMain(ctx)) return undefined;
1127
1129
  const messages = asRecord(event).messages;
1128
1130
  if (!Array.isArray(messages)) return undefined;
1129
- for (const raw of messages) {
1130
- const m = asRecord(raw);
1131
- if (m.role !== "custom" || m.customType !== "collab-prompt" || m.attribution !== "user") continue;
1132
- const from = asString(asRecord(m.details).from);
1133
- if (from === "") continue;
1134
- const text =
1135
- typeof m.content === "string"
1136
- ? m.content
1137
- : Array.isArray(m.content)
1138
- ? m.content.map(c => asString(asRecord(c).text)).join("")
1139
- : "";
1140
- const timestamp = typeof m.timestamp === "number" ? m.timestamp : 0;
1141
- if (Date.now() - timestamp > CHAT_PROMPT_MAX_AGE_MS) continue;
1142
- const key = `${timestamp}:${text}`;
1143
- if (seenChatPrompts.has(key)) continue;
1144
- seenChatPrompts.add(key);
1145
- const r = q.chatUnlock(text, cfg, `collab:${from}`);
1146
- if (r.applied) notifyUnlock(ctx, r);
1131
+ if (cfg.guards.chat_unlock) {
1132
+ for (const raw of messages) {
1133
+ const m = asRecord(raw);
1134
+ if (m.role !== "custom" || m.customType !== "collab-prompt" || m.attribution !== "user") continue;
1135
+ const from = asString(asRecord(m.details).from);
1136
+ if (from === "") continue;
1137
+ const text =
1138
+ typeof m.content === "string"
1139
+ ? m.content
1140
+ : Array.isArray(m.content)
1141
+ ? m.content.map(c => asString(asRecord(c).text)).join("")
1142
+ : "";
1143
+ const timestamp = typeof m.timestamp === "number" ? m.timestamp : 0;
1144
+ if (Date.now() - timestamp > CHAT_PROMPT_MAX_AGE_MS) continue;
1145
+ const key = `${timestamp}:${text}`;
1146
+ if (seenChatPrompts.has(key)) continue;
1147
+ seenChatPrompts.add(key);
1148
+ const r = q.chatUnlock(text, cfg, `collab:${from}`);
1149
+ if (r.applied) notifyUnlock(ctx, r);
1150
+ }
1147
1151
  }
1148
- return undefined;
1152
+ const rule = { pattern: cfg.quota.reset_pattern, zone: cfg.quota.reset_tz };
1153
+ let changed = false;
1154
+ const mapped = messages.map(raw => {
1155
+ const message = asRecord(raw);
1156
+ if (typeof message.content === "string") {
1157
+ const content = annotateResetTimes(message.content, rule);
1158
+ if (content === message.content) return raw;
1159
+ changed = true;
1160
+ return { ...message, content };
1161
+ }
1162
+ if (!Array.isArray(message.content)) return raw;
1163
+ let contentChanged = false;
1164
+ const content = message.content.map(part => {
1165
+ const block = asRecord(part);
1166
+ if (typeof block.text !== "string") return part;
1167
+ const text = annotateResetTimes(block.text, rule);
1168
+ if (text === block.text) return part;
1169
+ contentChanged = true;
1170
+ return { ...block, text };
1171
+ });
1172
+ if (!contentChanged) return raw;
1173
+ changed = true;
1174
+ return { ...message, content };
1175
+ });
1176
+ return changed ? { messages: mapped } : undefined;
1149
1177
  });
1150
1178
 
1151
1179
  // Under the launcher the relaunch is the only rollover path: a plain interactive message in the ready
@@ -94,6 +94,7 @@ function build(file: string, cfg: Config, mtime: number): Run | null {
94
94
  let first: number | null = null;
95
95
  let last: number | null = null;
96
96
  let inputTokens = 0;
97
+ let prefillTokens = 0;
97
98
  const messages: RunMessage[] = [];
98
99
 
99
100
  for (const line of text.split("\n")) {
@@ -153,6 +154,7 @@ function build(file: string, cfg: Config, mtime: number): Run | null {
153
154
  const cr = typeof u.cacheRead === "number" ? u.cacheRead : 0;
154
155
  const cw = typeof u.cacheWrite === "number" ? u.cacheWrite : 0;
155
156
  inputTokens = input + cr + cw;
157
+ prefillTokens += inputTokens;
156
158
  }
157
159
  if (typeof m.errorMessage === "string") {
158
160
  const head = m.errorMessage.split("\n")[0] ?? "";
@@ -197,6 +199,7 @@ function build(file: string, cfg: Config, mtime: number): Run | null {
197
199
  cacheRead: cache,
198
200
  cost,
199
201
  inputTokens,
202
+ prefillTokens,
200
203
  status,
201
204
  statusDetail: state,
202
205
  startedAt: first,
@@ -5,10 +5,12 @@
5
5
  // trace-relevant data is mapped; anything else (session banners, custom lines, compaction
6
6
  // notes, unparseable lines) is skipped.
7
7
 
8
- import { readFileSync, statSync } from "node:fs";
8
+ import { closeSync, openSync, readFileSync, readSync, readdirSync, statSync } from "node:fs";
9
9
  import { dirname, join } from "node:path";
10
10
  import type { Config } from "../../core/config.ts";
11
11
  import type { TraceEvent, TraceSource, TraceUsage } from "../../core/adapter.ts";
12
+ import type { DumpParts, DumpTokens } from "../../core/trace-bloat.ts";
13
+ import type { SpawnBrief } from "../../core/trace-briefs.ts";
12
14
  import { asObj, jsonlAt, parseTs, runIdOf } from "./sessions.ts";
13
15
 
14
16
  function str(v: unknown): string | undefined {
@@ -83,6 +85,7 @@ export function parseTraceFile(file: string, runId: string): TraceEvent[] {
83
85
  const role = str(m.role);
84
86
  const model = str(m.model);
85
87
  const provider = str(m.provider);
88
+ const api = str(m.api);
86
89
  const usage = usageOf(m.usage);
87
90
  if (role === "assistant") {
88
91
  const content = Array.isArray(m.content) ? m.content : [];
@@ -91,7 +94,7 @@ export function parseTraceFile(file: string, runId: string): TraceEvent[] {
91
94
  if (!p) continue;
92
95
  if (p.type === "text") {
93
96
  const t = String(p.text ?? "");
94
- if (t.trim()) out.push({ kind: "assistantText", ts, runId, text: t, model, provider, usage, responseId: str(m.responseId) });
97
+ if (t.trim()) out.push({ kind: "assistantText", ts, runId, text: t, model, provider, api, usage, responseId: str(m.responseId) });
95
98
  } else if (p.type === "toolCall") {
96
99
  out.push({
97
100
  kind: "toolCall",
@@ -102,6 +105,7 @@ export function parseTraceFile(file: string, runId: string): TraceEvent[] {
102
105
  callId: str(p.id),
103
106
  model,
104
107
  provider,
108
+ api,
105
109
  usage,
106
110
  responseId: str(m.responseId),
107
111
  });
@@ -112,7 +116,7 @@ export function parseTraceFile(file: string, runId: string): TraceEvent[] {
112
116
  // aborted or errored stream (owner interrupt, provider error) drops its partial content
113
117
  // while keeping the usage of what streamed, so it is not marked.
114
118
  if (content.length === 0 && m.stopReason !== "aborted" && m.stopReason !== "error") {
115
- out.push({ kind: "assistantText", ts, runId, text: "", model, provider, usage, responseId: str(m.responseId) });
119
+ out.push({ kind: "assistantText", ts, runId, text: "", model, provider, api, usage, responseId: str(m.responseId) });
116
120
  }
117
121
  } else if (role === "toolResult") {
118
122
  out.push({
@@ -148,6 +152,29 @@ export function ompTraceRuns(root: string): { runId: string; file: string; mtime
148
152
  return Object.entries(newest).map(([runId, v]) => ({ runId, file: v.file, mtimeSec: v.mtimeSec }));
149
153
  }
150
154
 
155
+ /** Read only the session banner at the start of a trace; null means it is unreadable. */
156
+ export function ompTraceStart(file: string): number | null {
157
+ let fd: number;
158
+ try {
159
+ fd = openSync(file, "r");
160
+ } catch {
161
+ return null;
162
+ }
163
+ const buffer = Buffer.allocUnsafe(4096);
164
+ try {
165
+ const bytes = readSync(fd, buffer, 0, buffer.length, 0);
166
+ for (const line of buffer.toString("utf8", 0, bytes).split("\n")) {
167
+ try {
168
+ const value = JSON.parse(line) as { type?: unknown; timestamp?: unknown };
169
+ if (value.type === "session" && typeof value.timestamp === "string") return parseTs(value.timestamp);
170
+ } catch {}
171
+ }
172
+ return null;
173
+ } finally {
174
+ closeSync(fd);
175
+ }
176
+ }
177
+
151
178
  /**
152
179
  * Tool names one dumped request offered: body.tools[].name of an http-4xx dump. A dump the
153
180
  * reader cannot open or parse offers nothing — a broken dump must not widen the offered set.
@@ -172,6 +199,110 @@ export function offeredFromDump(file: string): string[] {
172
199
  return tools.map((t) => str(asObj(t)?.name)).filter((n): n is string => n !== undefined);
173
200
  }
174
201
 
202
+ /** The harness log dir holding the whole failed requests (http-4xx dumps), named by epoch ms. */
203
+ export function ompDumpDir(home: string): string {
204
+ return join(home, ".omp", "logs", "http-400-requests");
205
+ }
206
+
207
+ /**
208
+ * Every request dump under the harness log dir, oldest first. Dumps are named
209
+ * `<epoch ms of the failed request>-<request id>.json`; anything else in the dir is not a dump.
210
+ */
211
+ export function ompDumps(home: string): { file: string; ms: number }[] {
212
+ let names: string[];
213
+ try {
214
+ names = readdirSync(ompDumpDir(home));
215
+ } catch {
216
+ return [];
217
+ }
218
+ const out: { file: string; ms: number }[] = [];
219
+ for (const name of names) {
220
+ const m = /^(\d+)-[A-Za-z0-9]+\.json$/.exec(name);
221
+ if (m) out.push({ file: join(ompDumpDir(home), name), ms: Number(m[1]) });
222
+ }
223
+ return out.sort((a, b) => a.ms - b.ms);
224
+ }
225
+
226
+ /** Model requested by a failed request dump, if the JSON contains one. */
227
+ export function dumpModel(file: string): string | undefined {
228
+ try {
229
+ const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
230
+ const o = asObj(parsed);
231
+ const body = asObj(o?.body);
232
+ return str(body?.model) ?? str(o?.model);
233
+ } catch {
234
+ return undefined;
235
+ }
236
+ }
237
+
238
+ /**
239
+ * What a dumped request's prompt is made of, in JSON.stringify characters: body.system,
240
+ * body.messages and every body.tools[] entry with its name (a nameless tool keeps its bytes
241
+ * as "?"). A dump the reader cannot open or parse breaks down to zeros — a broken dump must
242
+ * not look like a prompt that was mostly empty.
243
+ */
244
+ export function dumpParts(file: string): DumpParts {
245
+ let text: string;
246
+ try {
247
+ text = readFileSync(file, "utf8");
248
+ } catch {
249
+ return { system: 0, messages: 0, tools: [] };
250
+ }
251
+ let parsed: unknown;
252
+ try {
253
+ parsed = JSON.parse(text);
254
+ } catch {
255
+ return { system: 0, messages: 0, tools: [] };
256
+ }
257
+ const o = asObj(parsed);
258
+ const body = asObj(o?.body) ?? o ?? {};
259
+ const tools = Array.isArray(body.tools) ? body.tools : [];
260
+ return {
261
+ system: body.system === undefined ? 0 : JSON.stringify(body.system).length,
262
+ messages: body.messages === undefined ? 0 : JSON.stringify(body.messages).length,
263
+ tools: tools.map((t) => ({ name: str(asObj(t)?.name) ?? "?", bytes: JSON.stringify(t).length })),
264
+ };
265
+ }
266
+
267
+ /**
268
+ * What one dumped request's error response states about its own prompt: "<N> tokens > <M>
269
+ * maximum" (the provider's rejection line) — or, when that shape is missing, a bare
270
+ * "<N> tokens" — plus the request's model. A dump whose error response states no count, or a
271
+ * dump the reader cannot open or parse, states nothing: a flag must never be guessed from
272
+ * bytes alone.
273
+ */
274
+ export function dumpPromptTokens(file: string): DumpTokens | null {
275
+ let text: string;
276
+ try {
277
+ text = readFileSync(file, "utf8");
278
+ } catch {
279
+ return null;
280
+ }
281
+ let parsed: unknown;
282
+ try {
283
+ parsed = JSON.parse(text);
284
+ } catch {
285
+ return null;
286
+ }
287
+ const o = asObj(parsed);
288
+ const body = asObj(o?.body) ?? o ?? {};
289
+ const message = str(asObj(o?.errorResponse)?.message);
290
+ if (message === undefined) return null;
291
+ const count = (v: string | undefined) => {
292
+ const n = v === undefined ? NaN : Number(v.replaceAll(",", ""));
293
+ return Number.isFinite(n) ? n : undefined;
294
+ };
295
+ const m = /(\d[\d,]*)\s*tokens?\s*>\s*([\d,]+)\s*maximum/.exec(message);
296
+ const tokens = count(m?.[1]) ?? count(/(\d[\d,]*)\s*tokens?\b(?!\s*>)/.exec(message)?.[1]);
297
+ if (tokens === undefined) return null;
298
+ const out: DumpTokens = { tokens };
299
+ const limit = count(m?.[2]);
300
+ if (limit !== undefined) out.limit = limit;
301
+ const model = str(body.model);
302
+ if (model !== undefined) out.model = model;
303
+ return out;
304
+ }
305
+
175
306
  /** TraceSource over a sessions root: dated main files at depth 1, subagent files at depth 2. */
176
307
  export function ompTraceSource(root: string): TraceSource {
177
308
  return {
@@ -212,3 +343,39 @@ export function subagentTraces(root: string, mainRunId: string): RelatedTrace[]
212
343
  return { name, mtimeSec, events: parseTraceFile(file, name) };
213
344
  });
214
345
  }
346
+
347
+ /**
348
+ * The spawn briefs of one Main run (plan 20261024_0305 traces_06): each `task` spawn whose result
349
+ * is a success, one entry per spawned agent. A refused spawn (`main-guard:` error) spawned nothing.
350
+ * The brief is the shared context, then the task's own text, so the task's trailing sections (such as
351
+ * `# Acceptance`) end the brief. guards.briefBudget reads the first `Call budget` line of it.
352
+ */
353
+ export function spawnBriefs(root: string, mainRunId: string): SpawnBrief[] {
354
+ const main = ompTraceRuns(root).find((r) => r.runId === mainRunId);
355
+ return main ? spawnBriefsIn(main.file, mainRunId) : [];
356
+ }
357
+
358
+ /** The spawn briefs in one session file; the CLI calls this per file so it never rescans the root. */
359
+ export function spawnBriefsIn(file: string, runId: string): SpawnBrief[] {
360
+ const events = parseTraceFile(file, runId);
361
+ const results = new Map<string, TraceEvent>();
362
+ for (const e of events) if (e.kind === "toolResult" && e.callId) results.set(e.callId, e);
363
+ const out: SpawnBrief[] = [];
364
+ for (const e of events) {
365
+ if (e.kind !== "toolCall" || e.tool !== "task" || !e.callId) continue;
366
+ const res = results.get(e.callId);
367
+ if (!res || res.isError || !(res.text ?? "").startsWith("Spawned")) continue;
368
+ const named = new Set([...(res.text ?? "").matchAll(/`([^`]+)`/g)].map((m) => m[1] ?? ""));
369
+ const args = e.args ?? {};
370
+ const context = str(args.context) ?? "";
371
+ const tasks = Array.isArray(args.tasks) ? args.tasks : [];
372
+ for (const t of tasks) {
373
+ const task = asObj(t);
374
+ const name = str(task?.name);
375
+ if (!task || !name || !named.has(name)) continue;
376
+ const brief = [context, str(task.task) ?? ""].filter((s) => s !== "").join("\n\n");
377
+ out.push({ agent: name, brief, ts: e.ts });
378
+ }
379
+ }
380
+ return out;
381
+ }
@@ -8,10 +8,12 @@ import { ConfigError, loadConfig, type Config } from "../core/config.ts";
8
8
  import { appendMetric } from "../core/metrics.ts";
9
9
  import { nowSec } from "../core/clock.ts";
10
10
  import type { RunSource } from "../core/adapter.ts";
11
- import { buildReport, type ProviderSummary } from "../core/report.ts";
11
+ import { buildReport, type BloatSummary, type ProviderSummary } from "../core/report.ts";
12
12
  import { providerFindings } from "../core/trace-provider.ts";
13
+ import { bloatRules } from "../core/trace-bloat.ts";
13
14
  import { defaultRunSource } from "../adapters/omp/sessions.ts";
14
- import { ompTraceRuns, ompTraceSource } from "../adapters/omp/traces.ts";
15
+ import { ompDumps, ompTraceRuns, ompTraceSource } from "../adapters/omp/traces.ts";
16
+ import { assignDumps, bloatReport } from "./traces.ts";
15
17
 
16
18
  export const METRICS_USAGE = [
17
19
  "usage: neurastream metrics ci <repo-dir> <mr-id>",
@@ -108,6 +110,33 @@ function providerSummary(cfg: Config, now: number, days: number): ProviderSummar
108
110
  return { runs, byKind };
109
111
  }
110
112
 
113
+ /** Prompt-bloat counts over every run touched inside the window, folded from the
114
+ * src/core/trace-bloat.ts findings the same scans build (dump flag included, since a
115
+ * rejected call flags only through its dump). */
116
+ function bloatSummary(cfg: Config, now: number, days: number): BloatSummary {
117
+ const root = cfg.adapter?.sessions || join(cfg.paths.home, ".omp", "agent", "sessions");
118
+ const cutoff = now - days * 86400;
119
+ const src = ompTraceSource(root);
120
+ const rules = bloatRules(cfg);
121
+ const dumps = ompDumps(cfg.paths.home);
122
+ let runs = 0;
123
+ let flagged = 0;
124
+ let largest: BloatSummary["largest"] = null;
125
+ const allRuns = ompTraceRuns(root);
126
+ const { owners, events: assignmentEvents } = assignDumps(allRuns, src, dumps);
127
+ for (const r of allRuns) {
128
+ if (r.mtimeSec < cutoff) continue;
129
+ runs++;
130
+ const owned = dumps.filter((dump) => owners.get(dump.file) === r.runId);
131
+ const rep = bloatReport(src, r.runId, rules, cfg.traces.bloat.tool_group, owned, r.mtimeSec, assignmentEvents.get(r.runId));
132
+ if (rep.findings.length === 0) continue;
133
+ flagged++;
134
+ const firstCall = Math.max(rep.firstPrompt ?? 0, rep.dumpPrompt?.tokens ?? 0);
135
+ if (firstCall > 0 && (largest === null || firstCall > largest.firstCall)) largest = { runId: r.runId, firstCall };
136
+ }
137
+ return { runs, flagged, largest };
138
+ }
139
+
111
140
  /** Writes notes/metrics.md and prints the same report: this window against the previous one. */
112
141
  export function reportCmd(cfg: Config, source: RunSource, args: string[], now: number): number {
113
142
  const raw = flagValue(args, "--days");
@@ -116,7 +145,7 @@ export function reportCmd(cfg: Config, source: RunSource, args: string[], now: n
116
145
  console.error(METRICS_USAGE);
117
146
  return 2;
118
147
  }
119
- const { md, text } = buildReport(cfg, source, days, now, providerSummary(cfg, now, days));
148
+ const { md, text } = buildReport(cfg, source, days, now, providerSummary(cfg, now, days), bloatSummary(cfg, now, days));
120
149
  mkdirSync(cfg.paths.notes, { recursive: true });
121
150
  writeFileSync(join(cfg.paths.notes, "metrics.md"), md);
122
151
  console.log(text);