neurastream 0.2.13 → 0.2.15

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
@@ -176,6 +176,20 @@ Guard rules around it:
176
176
 
177
177
  "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.
178
178
 
179
+ ## Provider rate limits
180
+
181
+ When a Main turn ends on a provider rate limit, neurastream waits it out instead of asking again straight into the limit. The stop guard sees the turn's error text, matches it against `guards.rate_limit.patterns` (default `["429", "rate_limit", "rate limit", "overloaded", "529"]`, case-insensitive) and, on a hit, allows the stop without consulting the normal stop rules or touching the idle-stop counters. The chat channels get one post per episode — `⏳ Main is rate limited by its provider until HH:MM (local); it resumes on its own.` — and exactly one resume timer is armed (replacing any earlier one). When the wait is over, the plugin gives Main a new turn: `main-guard: the provider rate limit is over (waited until HH:MM). Continue the queue where you stopped.`, and the guard log carries the whole story:
182
+
183
+ ```
184
+ RATE-LIMIT stop: resume at 08:12 (35s, attempt 1)
185
+ notify: posted (rate-limit)
186
+ RATE-LIMIT resume: new turn sent (waited until 08:12)
187
+ ```
188
+
189
+ The wait is the `retry-after-ms=<ms>` or `retry-after: <seconds>` the error text names (omp appends the provider's header to the error message), else `default_wait_s` (300). A turn the resume started that ends on a limit again is the same episode at attempt 2: the wait doubles, no second post. Any turn that ends without a limit ends the episode and disarms the timer. Every wait is clamped to `max_wait_s` (3600) before `slack_s` (15) is added on top. Your own message before expiry takes over and cancels the resume (`RATE-LIMIT resume cancelled: owner message`), and a rate-limited deferred hand-back (an `agent_end` while an async job is pending) arms the same timer instead of logging "no reply text". The words and the waits live in `config.yml` (`guards.rate_limit`, `docs/config.md`); turns that did not end on a rate limit are unaffected.
190
+
191
+ 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.
192
+
179
193
  ## Trace claims (`neurastream traces claims`)
180
194
 
181
195
  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.
@@ -188,6 +202,32 @@ neurastream traces claims --since 24h --json # machine-readable
188
202
 
189
203
  Known boundary: a report that cites other runs' work (Main quoting a subagent, a relaunched agent quoting its predecessor) can produce `claim-unbacked` findings that are true in this run's trace but provable only in the cited run's own trace.
190
204
 
205
+ ## Provider honesty
206
+
207
+ Five rules check what came back against what was asked for, over one run's trace, read-only (`src/core/trace-provider.ts`):
208
+
209
+ - `model-swap`: the run announced a model (`model_change`) but an assistant message shows another model or another provider, or the run resolved the request to a fallback (`resolvedModelIsFallback`).
210
+ - `odd-response-id`: an assistant message's `responseId` misses the regex configured for its provider (`traces.provider.id_patterns`; a provider without an entry is not checked, and a message without a responseId is not checked).
211
+ - `unoffered-tool`: a toolCall for a tool the session never showed as offered — not in `traces.provider.allow_tools`, not in the request's own tool list (an http dump), and no result anywhere in the run other than an unknown-tool refusal (`Tool <name> not found`, `No such tool`, `Unknown tool`). An error result such as a guard refusal still proves the tool exists.
212
+ - `phantom-output`: output tokens billed for an assistant message that wrote nothing. A message whose stream was aborted (owner interrupt) or errored is not judged: the harness drops its partial content but keeps the usage of what streamed.
213
+ - `cost-mismatch`: the run's `model_usage` cost misses the `traces.provider.prices` table ($ per million tokens) by more than ±20%, in either direction; a model without a price row is not checked.
214
+
215
+ `neurastream metrics report` ends with a weekly line — `Provider honesty over N runs: …` — counting the findings of every run touched in the window. Both config maps are open: an empty object in the template means "add your own keys" in your config. The id patterns below were sampled from real traces; paste them (or yours) into `~/.config/neurastream/config.yml`:
216
+
217
+ ```yaml
218
+ traces:
219
+ provider:
220
+ id_patterns:
221
+ anthropic: '^msg_[A-Za-z0-9]+$'
222
+ zai: '^[0-9]{14}[0-9a-f]+$'
223
+ openai-codex: '^resp_[0-9a-f]+$'
224
+ openrouter: '^gen-[0-9]+-[A-Za-z0-9]+$'
225
+ prices: {} # e.g. glm-test: { input: 2, output: 6, cache_read: 0.2, cache_write: 0.5 }
226
+ allow_tools: []
227
+ ```
228
+
229
+ 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.
230
+
191
231
  ## Self-metrics
192
232
 
193
233
  `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:
@@ -200,6 +240,8 @@ Known boundary: a report that cites other runs' work (Main quoting a subagent, a
200
240
 
201
241
  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.
202
242
 
243
+ 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.
244
+
203
245
  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`.
204
246
 
205
247
  ## Self-improvement
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.13",
3
+ "version": "0.2.15",
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",
@@ -21,16 +21,19 @@ import { basename, dirname, join } from "node:path";
21
21
  import type { Decision } from "../../core/adapter.ts";
22
22
  import { loadConfig, type Config } from "../../core/config.ts";
23
23
  import { nowSec, strftime } from "../../core/clock.ts";
24
- import { runDetectorsGated } from "../../core/incident-detectors.ts";
25
- import { checkInject, checkPlanEdit, checkStop, checkTool, MAIN_PLAN_FILE, recordMainResult, revertMainEdit, rekeySpawnFile } from "../../core/guards.ts";
24
+ import { runDetectors, runDetectorsGated, type DetectorInput } from "../../core/incident-detectors.ts";
25
+ import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, newProgressEntries, recordMainResult, revertMainEdit, rekeySpawnFile } from "../../core/guards.ts";
26
+ import { rateLimitWait } from "../../core/rate-limit.ts";
26
27
  import { notifyProviders, postReply } from "../../core/notify.ts";
27
28
  import { inboxPath } from "../../core/owner-ui.ts";
28
29
  import { realTailscale } from "../../core/tailscale.ts";
30
+ import { actionsRules, ownedRepoOf, suspiciousActions, unreportedFindings } from "../../core/trace-actions.ts";
29
31
  import { applyQueueEnv } from "../../core/queue/env.ts";
30
32
  import { mainStartText, runDailyCheck } from "../../core/main-start.ts";
31
33
  import { readBlocks } from "../../core/metrics.ts";
32
34
  import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, type RolloverState } from "../../core/rollover.ts";
33
- import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
35
+ import { defaultCompletedResults, defaultRunSource, runIdOf } from "./sessions.ts";
36
+ import { parseTraceFile } from "./traces.ts";
34
37
  import { packageJsonPath, packageVersion } from "./package-root.ts";
35
38
  import * as q from "../../core/queue/lib.ts";
36
39
  // Registers the plugin-command matcher into core's writeTargets (side effect).
@@ -70,6 +73,8 @@ interface EventReply {
70
73
  text: string;
71
74
  stopReason: string | null;
72
75
  toolCalls: number;
76
+ /** The provider's error text on a turn that ended on one (`429 … retry-after-ms=…`); null otherwise. */
77
+ errorMessage: string | null;
73
78
  }
74
79
 
75
80
  function lastAssistantIn(messages: unknown): EventReply | null {
@@ -87,6 +92,7 @@ function lastAssistantIn(messages: unknown): EventReply | null {
87
92
  text,
88
93
  stopReason: typeof m.stopReason === "string" ? m.stopReason : null,
89
94
  toolCalls: content.filter(c => asRecord(c).type === "toolCall").length,
95
+ errorMessage: typeof m.errorMessage === "string" ? m.errorMessage : null,
90
96
  };
91
97
  }
92
98
  return null;
@@ -148,6 +154,41 @@ function mainDetectors(cfg: Config, extra: { prompt?: string; bash?: { command:
148
154
  }
149
155
  }
150
156
 
157
+ /**
158
+ * D6 + D7 over a subagent's own trace, right after an allowed Progress edit (plan
159
+ * 20261024_0301 P6): the sub's session file (its harness session manager hands it out) is
160
+ * parsed as the run's trace, every high suspicious action folds as a D6 incident, and when the
161
+ * new Progress bullet claims `Findings: none` the cross-product reads hidden behind that claim
162
+ * fold as D7 (`unreported-finding`) with the agent-score penalty — the bullet is the claim
163
+ * source the owner named, so it replaces the final-text check. The newest added bullet decides
164
+ * (Progress runs newest-first). Best effort: a failure is logged, never thrown — a broken
165
+ * detector must not break the verified edit.
166
+ */
167
+ function subActionDetectors(cfg: Config, ctx: unknown, planFile: string, before: string, after: string): void {
168
+ try {
169
+ const entries = newProgressEntries(before, after);
170
+ if (entries.length === 0) return;
171
+ const sessionFile = call(asRecord(asRecord(ctx).sessionManager), "getSessionFile");
172
+ if (typeof sessionFile !== "string" || sessionFile === "") return;
173
+ const events = parseTraceFile(sessionFile, runIdOf(sessionFile));
174
+ const rules = actionsRules(cfg);
175
+ const input: DetectorInput = { actions: suspiciousActions(events, rules) };
176
+ if (/^none\.?$/i.test(findingsValue(entries[0]!) ?? "")) {
177
+ // The plan's repo spelled like its owned_repos entry: a checkout named "pm-mr196" is "pm",
178
+ // so the run's reads of its own repo never count as another product's.
179
+ const repoDir = q.planRepo(planFile);
180
+ input.unreported = unreportedFindings(events, rules, {
181
+ repo: ownedRepoOf(`${repoDir}/`, rules.owned_repos) ?? basename(repoDir),
182
+ plan: planFile,
183
+ claimedNone: true,
184
+ });
185
+ }
186
+ runDetectors(cfg, input);
187
+ } catch (err) {
188
+ adapterLog(cfg, `sub action detectors failed: ${err instanceof Error ? err.message : String(err)}`);
189
+ }
190
+ }
191
+
151
192
  // Background queue-close for every plan Main marked complete. Ported from the
152
193
  // original autoClose: same filter, same "--- auto-close attempt" log line, detached child with
153
194
  // stdio on the per-plan close log. QUEUE_CLOSE_BIN overrides the binary (tests); without it the
@@ -419,6 +460,48 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
419
460
  // emits (sessionStopWillContinue) consumes it and posts nothing — a blocked stop's reply is a
420
461
  // mid-work report, never a hand-back.
421
462
  let stopBlocked = false;
463
+ // Rate-limit wait-it-out (plan 20261025_0640): consecutive turn ends on a provider rate limit
464
+ // form one episode. The attempt doubles the wait, the owner chat is told once per episode, and
465
+ // ONE timer gives Main a new turn when the wait is over; an owner message before expiry takes
466
+ // over and cancels it. Any turn that ends without a limit resets the episode and disarms it.
467
+ let rateAttempt = 0;
468
+ let rateTimer: NodeJS.Timeout | null = null;
469
+ const rateClock = (ms: number): string => strftime(ms / 1000, "%H:%M");
470
+ const clearRateTimer = (): void => {
471
+ if (rateTimer !== null) {
472
+ clearTimeout(rateTimer);
473
+ rateTimer = null;
474
+ }
475
+ };
476
+ const disarmRateEpisode = (): void => {
477
+ clearRateTimer();
478
+ rateAttempt = 0;
479
+ };
480
+ // The one resume: replacing any armed timer, exactly one new user message when the wait is over.
481
+ const armRateResume = (untilMs: number): void => {
482
+ clearRateTimer();
483
+ rateTimer = setTimeout(() => {
484
+ rateTimer = null;
485
+ pi.sendUserMessage(`main-guard: the provider rate limit is over (waited until ${rateClock(untilMs)}). Continue the queue where you stopped.`);
486
+ adapterLog(cfg, `RATE-LIMIT resume: new turn sent (waited until ${rateClock(untilMs)})`);
487
+ }, untilMs - Date.now());
488
+ };
489
+ // A turn that ended on a rate limit: log, tell the owner once per episode, arm the resume.
490
+ const onRateLimitedStop = (untilMs: number, waitMs: number): void => {
491
+ rateAttempt++;
492
+ const at = rateClock(untilMs);
493
+ adapterLog(cfg, `RATE-LIMIT stop: resume at ${at} (${Math.round(waitMs / 1000)}s, attempt ${rateAttempt})`);
494
+ if (rateAttempt === 1) {
495
+ adapterLog(cfg, "notify: posted (rate-limit)");
496
+ void postReply(`⏳ Main is rate limited by its provider until ${at} (local); it resumes on its own.`, cfg).then(results => {
497
+ for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
498
+ });
499
+ }
500
+ armRateResume(untilMs);
501
+ };
502
+ // The rate-limit decision for one turn end, from the event's own last assistant message.
503
+ const rateLimitOf = (reply: EventReply | null): { untilMs: number; waitMs: number } | null =>
504
+ rateLimitWait(reply?.stopReason ?? null, reply?.errorMessage ?? null, Date.now(), cfg.guards.rate_limit, rateAttempt + 1);
422
505
  // One guard-log line per notify decision: `notify: posted|skipped (<why>)`. Fire-and-forget:
423
506
  // the decision never awaits the post; a failed or slow post logs one line and never blocks
424
507
  // or retries.
@@ -648,6 +731,8 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
648
731
  const note = trimProgress(file);
649
732
  if (note) notes.push(note);
650
733
  }
734
+ // Live D6+D7 over the sub's own session as soon as it reports into the plan (P6).
735
+ if (d.allow && c.kind === "sub") subActionDetectors(cfg, ctx, file, before, after);
651
736
  }
652
737
  }
653
738
  if ((!c.hasAgent || c.kind === "main") && asString(e.toolName) === "bash" && !e.isError) {
@@ -686,6 +771,16 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
686
771
  // BEFORE agent_end, so a file read would lag a whole turn.
687
772
  const stopMsg = asRecord(e).last_assistant_message;
688
773
  const reply = stopMsg ? lastAssistantIn([stopMsg]) : lastAssistantIn(asRecord(e).messages);
774
+ // A turn that ended on a provider rate limit waits it out (plan 20261025_0640): ALLOW before
775
+ // the rollover and queue decisions — any block here would re-ask straight into the limit —
776
+ // and without touching the idle-stop counters: checkStop is not consulted.
777
+ const rl = rateLimitOf(reply);
778
+ if (rl) {
779
+ onRateLimitedStop(rl.untilMs, rl.waitMs);
780
+ return undefined;
781
+ }
782
+ // Any turn that ends without a rate limit ends the episode and disarms its resume timer.
783
+ disarmRateEpisode();
689
784
  // A pending rollover decides the stop and checkStop is not consulted: its queue, incident and cancel
690
785
  // blocks would hold Main at a wait the new session raises again through main-start, and its "spawn an
691
786
  // agent" text is refused while the rollover is pending.
@@ -921,13 +1016,24 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
921
1016
  adapterLog(cfg, "notify: skipped (stop blocked, agent_end)");
922
1017
  return;
923
1018
  }
1019
+ const reply = lastAssistantIn(asRecord(e).messages);
1020
+ // The same rate-limit check as session_stop (plan 20261025_0640): a rate-limited deferred
1021
+ // hand-back arms the resume timer instead of logging "no reply text" — its reply carries an
1022
+ // error, no text. A mid-run continuation (tool calls, auto-retry) is not a turn end: the
1023
+ // episode state stays as it is.
1024
+ const rl = rateLimitOf(reply);
1025
+ if (rl) {
1026
+ onRateLimitedStop(rl.untilMs, rl.waitMs);
1027
+ return;
1028
+ }
924
1029
  const jobCount = asRolloverCtx(ctx)?.runningJobs().length ?? 0;
925
1030
  if (jobCount === 0) {
926
1031
  adapterLog(cfg, "notify: skipped (no pending job, agent_end)");
927
1032
  return;
928
1033
  }
929
- const reply = lastAssistantIn(asRecord(e).messages);
930
1034
  if (!reply || !reply.text) {
1035
+ // A turn that ended on some other no-text outcome is a turn end without a rate limit.
1036
+ disarmRateEpisode();
931
1037
  adapterLog(cfg, "notify: skipped (no reply text, agent_end hand-back)");
932
1038
  return;
933
1039
  }
@@ -938,6 +1044,8 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
938
1044
  );
939
1045
  return;
940
1046
  }
1047
+ // A real hand-back: the turn ended without a rate limit — the episode is over.
1048
+ disarmRateEpisode();
941
1049
  notifyHandback(reply, "agent_end hand-back");
942
1050
  });
943
1051
  // Turn end: page answers that arrived during the turn go out (P3b), then open plans that now
@@ -977,6 +1085,16 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
977
1085
  return null;
978
1086
  };
979
1087
 
1088
+ // An owner message while a rate-limit resume is pending takes over: the resume timer is
1089
+ // cancelled (plan 20261025_0640). Registered before the chat-unlock input handler below, so it
1090
+ // sees every owner input even when the unlock short-circuits with { handled: true }.
1091
+ pi.on("input", (_event, ctx) => {
1092
+ if (!isMain(ctx)) return undefined;
1093
+ if (rateTimer === null) return undefined;
1094
+ clearRateTimer();
1095
+ adapterLog(cfg, "RATE-LIMIT resume cancelled: owner message");
1096
+ return undefined;
1097
+ });
980
1098
  // Chat unlock (guards.chat_unlock): the owner's whole message "unlock"/"unlock N"/"lock" moves
981
1099
  // the guard unlock file (src/core/queue/lib.ts chatUnlock). Only prompts the owner really typed
982
1100
  // count: the local terminal (input event, source "interactive") and collab guest prompts from
@@ -78,7 +78,7 @@ function copyPins(dest: string): { copied: string[]; kept: string[] } {
78
78
  return { copied, kept };
79
79
  }
80
80
 
81
- function writeOverlay(file: string): "written" | "unchanged" {
81
+ export function writeOverlay(file: string): "written" | "unchanged" {
82
82
  let text = readFileSync(file, "utf8");
83
83
  let changed = false;
84
84
  if (!/^adapter:/m.test(text)) {
@@ -88,13 +88,20 @@ function writeOverlay(file: string): "written" | "unchanged" {
88
88
  }
89
89
  const missing = PROTECTED.filter(p => !text.includes(p));
90
90
  if (missing.length) {
91
- const lines = missing.map(p => ` - "${p}"`).join("\n");
92
- if (text.includes(" protected: []")) {
93
- text = text.replace(" protected: []", ` protected:\n${lines}`);
94
- } else if (text.includes("\n ledger_command:")) {
95
- text = text.replace("\n ledger_command:", `\n${lines}\n ledger_command:`);
91
+ const lines = missing.map(p => ` - "${p}"\n`).join("");
92
+ // The items always go under their own `protected:` key: the empty list becomes a block
93
+ // list, an existing block list gains them under its header, a missing key is added at
94
+ // the top of `guards:`. Any other form (a flow list with items) is the owner's to fix.
95
+ if (/^ {2}protected: \[\][ \t]*$/m.test(text)) {
96
+ text = text.replace(/^ {2}protected: \[\][ \t]*\n?/m, ` protected:\n${lines}`);
97
+ } else if (/^ {2}protected:[ \t]*\n/m.test(text)) {
98
+ text = text.replace(/^ {2}protected:[ \t]*\n/m, ` protected:\n${lines}`);
99
+ } else if (/^ {2}protected:/m.test(text)) {
100
+ throw new Error(`${file}: guards.protected is not a block list; list it as " protected:" with " - " items, then rerun`);
101
+ } else if (/^guards:[ \t]*\n/m.test(text)) {
102
+ text = text.replace(/^guards:[ \t]*\n/m, `guards:\n protected:\n${lines}`);
96
103
  } else {
97
- throw new Error(`${file} has no guards.protected list to extend`);
104
+ throw new Error(`${file} has no guards: section to extend`);
98
105
  }
99
106
  changed = true;
100
107
  }
@@ -6,6 +6,7 @@
6
6
  // notes, unparseable lines) is skipped.
7
7
 
8
8
  import { readFileSync, statSync } from "node:fs";
9
+ import { dirname } from "node:path";
9
10
  import type { TraceEvent, TraceSource, TraceUsage } from "../../core/adapter.ts";
10
11
  import { asObj, jsonlAt, parseTs, runIdOf } from "./sessions.ts";
11
12
 
@@ -61,7 +62,14 @@ export function parseTraceFile(file: string, runId: string): TraceEvent[] {
61
62
  if (!d) continue;
62
63
  const ts = typeof d.timestamp === "string" ? parseTs(d.timestamp) : null;
63
64
  if (d.type === "model_change") {
64
- out.push({ kind: "modelChange", ts, runId, model: str(d.model), provider: str(d.provider) });
65
+ out.push({
66
+ kind: "modelChange",
67
+ ts,
68
+ runId,
69
+ model: str(d.model),
70
+ provider: str(d.provider),
71
+ fallback: d.resolvedModelIsFallback === true ? true : undefined,
72
+ });
65
73
  continue;
66
74
  }
67
75
  if (d.type === "model_usage") {
@@ -82,7 +90,7 @@ export function parseTraceFile(file: string, runId: string): TraceEvent[] {
82
90
  if (!p) continue;
83
91
  if (p.type === "text") {
84
92
  const t = String(p.text ?? "");
85
- if (t.trim()) out.push({ kind: "assistantText", ts, runId, text: t, model, provider, usage });
93
+ if (t.trim()) out.push({ kind: "assistantText", ts, runId, text: t, model, provider, usage, responseId: str(m.responseId) });
86
94
  } else if (p.type === "toolCall") {
87
95
  out.push({
88
96
  kind: "toolCall",
@@ -93,9 +101,17 @@ export function parseTraceFile(file: string, runId: string): TraceEvent[] {
93
101
  model,
94
102
  provider,
95
103
  usage,
104
+ responseId: str(m.responseId),
96
105
  });
97
106
  }
98
107
  }
108
+ // An assistant message with no content at all would vanish (nothing to map); an empty
109
+ // text marks it so the phantom-output rule can see billed tokens with no words. An
110
+ // aborted or errored stream (owner interrupt, provider error) drops its partial content
111
+ // while keeping the usage of what streamed, so it is not marked.
112
+ if (content.length === 0 && m.stopReason !== "aborted" && m.stopReason !== "error") {
113
+ out.push({ kind: "assistantText", ts, runId, text: "", model, provider, usage, responseId: str(m.responseId) });
114
+ }
99
115
  } else if (role === "toolResult") {
100
116
  out.push({
101
117
  kind: "toolResult",
@@ -129,6 +145,30 @@ export function ompTraceRuns(root: string): { runId: string; file: string; mtime
129
145
  return Object.entries(newest).map(([runId, v]) => ({ runId, file: v.file, mtimeSec: v.mtimeSec }));
130
146
  }
131
147
 
148
+ /**
149
+ * Tool names one dumped request offered: body.tools[].name of an http-4xx dump. A dump the
150
+ * reader cannot open or parse offers nothing — a broken dump must not widen the offered set.
151
+ */
152
+ export function offeredFromDump(file: string): string[] {
153
+ let text: string;
154
+ try {
155
+ text = readFileSync(file, "utf8");
156
+ } catch {
157
+ return [];
158
+ }
159
+ let parsed: unknown;
160
+ try {
161
+ parsed = JSON.parse(text);
162
+ } catch {
163
+ return [];
164
+ }
165
+ const o = asObj(parsed);
166
+ const body = asObj(o?.body) ?? o;
167
+ const tools = body?.tools;
168
+ if (!Array.isArray(tools)) return [];
169
+ return tools.map((t) => str(asObj(t)?.name)).filter((n): n is string => n !== undefined);
170
+ }
171
+
132
172
  /** TraceSource over a sessions root: dated main files at depth 1, subagent files at depth 2. */
133
173
  export function ompTraceSource(root: string): TraceSource {
134
174
  return {
@@ -138,3 +178,29 @@ export function ompTraceSource(root: string): TraceSource {
138
178
  },
139
179
  };
140
180
  }
181
+
182
+ export interface RelatedTrace {
183
+ /** The subagent run's trace run id — the agent name. */
184
+ name: string;
185
+ mtimeSec: number;
186
+ events: TraceEvent[];
187
+ }
188
+
189
+ /**
190
+ * The subagent runs of one Main run: the depth-2 session files under the Main file's session
191
+ * dir (plan 20261024_0301 P5) — the runs Main spawned there, whose results Main's report cites.
192
+ * Non-Main run ids have none.
193
+ */
194
+ export function subagentTraces(root: string, mainRunId: string): RelatedTrace[] {
195
+ if (!mainRunId.startsWith("MAIN ")) return [];
196
+ const main = ompTraceRuns(root).find((r) => r.runId === mainRunId);
197
+ if (!main) return [];
198
+ return jsonlAt(dirname(main.file), 1).map((file) => {
199
+ const name = runIdOf(file);
200
+ let mtimeSec = 0;
201
+ try {
202
+ mtimeSec = statSync(file).mtimeMs / 1000;
203
+ } catch {}
204
+ return { name, mtimeSec, events: parseTraceFile(file, name) };
205
+ });
206
+ }
@@ -66,6 +66,11 @@ export function helpText(): string {
66
66
  " check a run's final-report claims (test counts, exit codes,",
67
67
  " SHAs, heavy-run labels, changed paths) against the run's own",
68
68
  " tool activity; unmatched ones print as claim-unbacked findings",
69
+ " neurastream traces actions <runId|--since 24h> [--json]",
70
+ " list the suspicious tool actions a run's trace shows (secret-",
71
+ " path reads, network commands to unknown hosts, writes outside",
72
+ " the allowed roots or on deny paths, pipes into a shell); the",
73
+ " high ones also open realtime suspicious-action incidents",
69
74
  " neurastream ui serve the owner's phone page on the tailnet address (ui.enabled, ui.owner_login)",
70
75
  " neurastream ui on --login <tailscale login> [--port N]",
71
76
  " one go: writes ui.enabled/owner_login (and port) into the config,",
@@ -8,8 +8,10 @@ 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 } from "../core/report.ts";
11
+ import { buildReport, type ProviderSummary } from "../core/report.ts";
12
+ import { providerFindings } from "../core/trace-provider.ts";
12
13
  import { defaultRunSource } from "../adapters/omp/sessions.ts";
14
+ import { ompTraceRuns, ompTraceSource } from "../adapters/omp/traces.ts";
13
15
 
14
16
  export const METRICS_USAGE = [
15
17
  "usage: neurastream metrics ci <repo-dir> <mr-id>",
@@ -89,6 +91,23 @@ export function recordRule(cfg: Config, text: string, decision: "approved" | "re
89
91
  return 0;
90
92
  }
91
93
 
94
+ /** Provider-honesty counts over every run touched inside the window, folded from the five
95
+ * rules of src/core/trace-provider.ts under the config's provider rules and price table. */
96
+ function providerSummary(cfg: Config, now: number, days: number): ProviderSummary {
97
+ const root = cfg.adapter?.sessions || join(cfg.paths.home, ".omp", "agent", "sessions");
98
+ const cutoff = now - days * 86400;
99
+ const src = ompTraceSource(root);
100
+ const rules = cfg.traces.provider;
101
+ const byKind: Record<string, number> = {};
102
+ let runs = 0;
103
+ for (const r of ompTraceRuns(root)) {
104
+ if (r.mtimeSec < cutoff) continue;
105
+ runs++;
106
+ for (const f of providerFindings(src.events(r.runId), rules, rules.prices)) byKind[f.kind] = (byKind[f.kind] ?? 0) + 1;
107
+ }
108
+ return { runs, byKind };
109
+ }
110
+
92
111
  /** Writes notes/metrics.md and prints the same report: this window against the previous one. */
93
112
  export function reportCmd(cfg: Config, source: RunSource, args: string[], now: number): number {
94
113
  const raw = flagValue(args, "--days");
@@ -97,7 +116,7 @@ export function reportCmd(cfg: Config, source: RunSource, args: string[], now: n
97
116
  console.error(METRICS_USAGE);
98
117
  return 2;
99
118
  }
100
- const { md, text } = buildReport(cfg, source, days, now);
119
+ const { md, text } = buildReport(cfg, source, days, now, providerSummary(cfg, now, days));
101
120
  mkdirSync(cfg.paths.notes, { recursive: true });
102
121
  writeFileSync(join(cfg.paths.notes, "metrics.md"), md);
103
122
  console.log(text);
package/src/cli/traces.ts CHANGED
@@ -1,20 +1,26 @@
1
1
  // `neurastream traces claims …` (plan 20261024_0300 P3): check what a run's final report CLAIMS
2
2
  // against what the same run's tool activity shows. Claims come from the run's last assistant
3
3
  // message; a claim with no backing toolResult line, git output, heavy-run call or edit/write is
4
- // reported as a claim-unbacked finding (src/core/incident-detectors.ts D5). Read-only over the
5
- // sessions root; --json prints machine-readable records.
4
+ // reported as a claim-unbacked finding (src/core/incident-detectors.ts D5).
5
+ // `neurastream traces actions …` (plan 20261024_0301 P2): list the suspicious tool actions a
6
+ // run's trace shows (src/core/trace-actions.ts); the high ones fold into the incident store as
7
+ // realtime `suspicious-action` incidents (D6). Read-only over the sessions root; --json prints
8
+ // machine-readable records.
6
9
 
7
10
  import { join } from "node:path";
8
11
  import { nowSec } from "../core/clock.ts";
9
12
  import type { TraceSource } from "../core/adapter.ts";
10
13
  import { ConfigError, loadConfig, type Config } from "../core/config.ts";
11
14
  import { claimUnbacked } from "../core/incident-detectors.ts";
12
- import { claimsFromEvents } from "../core/trace-claims.ts";
13
- import { ompTraceRuns, ompTraceSource } from "../adapters/omp/traces.ts";
15
+ import { claimsFromEvents, type RelatedRun } from "../core/trace-claims.ts";
16
+ import { actionsRules, suspiciousActions, type ActionsRules, type SuspiciousAction } from "../core/trace-actions.ts";
17
+ import { ompTraceRuns, ompTraceSource, subagentTraces } from "../adapters/omp/traces.ts";
14
18
 
15
19
  export const TRACES_USAGE = [
16
20
  "usage: neurastream traces claims <runId> [--json]",
17
21
  " neurastream traces claims --since <N m|h|d> [--json]",
22
+ " neurastream traces actions <runId> [--json]",
23
+ " neurastream traces actions --since <N m|h|d> [--json]",
18
24
  ].join("\n");
19
25
 
20
26
  const SINCE = /^(\d+)(m|h|d)$/;
@@ -26,11 +32,14 @@ export interface RunClaimsReport {
26
32
  unbacked: { kind: string; summary: string; evidence?: string }[];
27
33
  }
28
34
 
29
- /** Verify one run: claims from its final report, findings for the ones no tool output backs. */
30
- export function claimsReport(src: TraceSource, runId: string): RunClaimsReport {
35
+ /** Verify one run: claims from its final report, findings for the ones no tool output backs. A
36
+ * Main run's report also checks the toolResult text of the subagent runs under its session dir
37
+ * (`related`, INCIDENT I-20261025-23): the evidence for a cited subagent result lives in the
38
+ * subagent's own session, and a match there backs the claim as `subagent:<name>`. */
39
+ export function claimsReport(src: TraceSource, runId: string, related: RelatedRun[] = []): RunClaimsReport {
31
40
  const events = src.events(runId);
32
41
  const claims = claimsFromEvents(events);
33
- const findings = claimUnbacked(claims, events);
42
+ const findings = claimUnbacked(claims, events, related);
34
43
  return {
35
44
  runId,
36
45
  claims: claims.length,
@@ -39,15 +48,27 @@ export function claimsReport(src: TraceSource, runId: string): RunClaimsReport {
39
48
  };
40
49
  }
41
50
 
42
- /** `neurastream traces claims`: one run by id, or every run touched inside a --since window. */
43
- export async function runTraces(args: string[]): Promise<number> {
44
- if (args[0] !== "claims") {
51
+ export interface RunActionsReport {
52
+ runId: string;
53
+ /** Every suspicious tool action the run's trace shows, evidence masked and capped. */
54
+ actions: SuspiciousAction[];
55
+ }
56
+
57
+ /** Scan one run: every suspicious tool action its trace shows, under the config's rules. */
58
+ export function actionsReport(src: TraceSource, runId: string, rules: ActionsRules): RunActionsReport {
59
+ return { runId, actions: suspiciousActions(src.events(runId), rules) };
60
+ }
61
+
62
+ /** `neurastream traces claims|actions`: one run by id, or every run touched inside a --since window. */
63
+ export async function runTraces(args: string[], opts: { home?: string } = {}): Promise<number> {
64
+ const sub = args[0];
65
+ if (sub !== "claims" && sub !== "actions") {
45
66
  console.error(TRACES_USAGE);
46
67
  return 2;
47
68
  }
48
69
  let cfg: Config;
49
70
  try {
50
- cfg = loadConfig();
71
+ cfg = loadConfig(opts.home === undefined ? undefined : { home: opts.home });
51
72
  } catch (err) {
52
73
  console.error(err instanceof ConfigError ? err.message : String(err));
53
74
  return 1;
@@ -82,33 +103,54 @@ export async function runTraces(args: string[]): Promise<number> {
82
103
  }
83
104
  const runs = ompTraceRuns(root);
84
105
  const src = ompTraceSource(root);
85
- const reports: RunClaimsReport[] = [];
106
+ const rules = sub === "actions" ? actionsRules(cfg) : null;
107
+ // A Main run's report cites its subagents' results: their traces under the Main session dir
108
+ // back the pure result-line claims (P5). No time filter — the text match is the guard, and
109
+ // a sub's file keeps being written while its Main run lives, inside whatever window.
110
+ const relatedOf = (id: string): RelatedRun[] =>
111
+ sub === "claims" ? subagentTraces(root, id).map(({ name, events }) => ({ name, events })) : [];
112
+ const reports: (RunClaimsReport | RunActionsReport)[] = [];
113
+ const reportOf = (id: string): RunClaimsReport | RunActionsReport =>
114
+ sub === "claims" ? claimsReport(src, id, relatedOf(id)) : actionsReport(src, id, rules!);
86
115
  if (windowSec !== undefined) {
87
116
  const cutoff = nowSec() - windowSec;
88
117
  for (const r of runs) {
89
118
  if (r.mtimeSec < cutoff) continue;
90
- reports.push(claimsReport(src, r.runId));
119
+ reports.push(reportOf(r.runId));
91
120
  }
92
121
  } else {
93
122
  if (!runs.some((r) => r.runId === runId)) {
94
123
  console.error(`no trace for run ${runId}`);
95
124
  return 1;
96
125
  }
97
- reports.push(claimsReport(src, runId!));
126
+ reports.push(reportOf(runId!));
98
127
  }
99
128
  if (json) {
100
129
  console.log(JSON.stringify(reports, null, 2));
101
130
  return 0;
102
131
  }
103
132
  for (const r of reports) {
104
- if (r.claims === 0) {
105
- console.log(`${r.runId}: no verifiable claims in the final report`);
106
- continue;
107
- }
108
- console.log(`${r.runId}: ${r.claims} claims, ${r.backed} backed, ${r.unbacked.length} unbacked`);
109
- for (const u of r.unbacked) {
110
- console.log(` ${u.kind}: ${u.summary}`);
111
- if (u.evidence) console.log(` evidence: ${u.evidence}`);
133
+ if ("claims" in r) {
134
+ if (r.claims === 0) {
135
+ console.log(`${r.runId}: no verifiable claims in the final report`);
136
+ continue;
137
+ }
138
+ console.log(`${r.runId}: ${r.claims} claims, ${r.backed} backed, ${r.unbacked.length} unbacked`);
139
+ for (const u of r.unbacked) {
140
+ console.log(` ${u.kind}: ${u.summary}`);
141
+ if (u.evidence) console.log(` evidence: ${u.evidence}`);
142
+ }
143
+ } else {
144
+ if (r.actions.length === 0) {
145
+ console.log(`${r.runId}: no suspicious actions in the trace`);
146
+ continue;
147
+ }
148
+ const high = r.actions.filter((a) => a.severity === "high").length;
149
+ console.log(`${r.runId}: ${r.actions.length} suspicious actions (${high} high)`);
150
+ for (const a of r.actions) {
151
+ console.log(` [${a.severity}] ${a.rule}: ${a.summary}`);
152
+ if (a.evidence) console.log(` evidence: ${a.evidence}`);
153
+ }
112
154
  }
113
155
  }
114
156
  return 0;
@@ -68,6 +68,10 @@ export interface TraceEvent {
68
68
  model?: string;
69
69
  provider?: string;
70
70
  usage?: TraceUsage;
71
+ /** Provider response id of the assistant message; absent when the line carries none. */
72
+ responseId?: string;
73
+ /** modelChange only: the run resolved the requested model to a fallback. */
74
+ fallback?: boolean;
71
75
  }
72
76
 
73
77
  export interface TraceSource {