neurastream 0.2.13 → 0.2.14

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.13",
3
+ "version": "0.2.14",
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
 
@@ -138,3 +139,29 @@ export function ompTraceSource(root: string): TraceSource {
138
139
  },
139
140
  };
140
141
  }
142
+
143
+ export interface RelatedTrace {
144
+ /** The subagent run's trace run id — the agent name. */
145
+ name: string;
146
+ mtimeSec: number;
147
+ events: TraceEvent[];
148
+ }
149
+
150
+ /**
151
+ * The subagent runs of one Main run: the depth-2 session files under the Main file's session
152
+ * dir (plan 20261024_0301 P5) — the runs Main spawned there, whose results Main's report cites.
153
+ * Non-Main run ids have none.
154
+ */
155
+ export function subagentTraces(root: string, mainRunId: string): RelatedTrace[] {
156
+ if (!mainRunId.startsWith("MAIN ")) return [];
157
+ const main = ompTraceRuns(root).find((r) => r.runId === mainRunId);
158
+ if (!main) return [];
159
+ return jsonlAt(dirname(main.file), 1).map((file) => {
160
+ const name = runIdOf(file);
161
+ let mtimeSec = 0;
162
+ try {
163
+ mtimeSec = statSync(file).mtimeMs / 1000;
164
+ } catch {}
165
+ return { name, mtimeSec, events: parseTraceFile(file, name) };
166
+ });
167
+ }
@@ -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,",
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;
@@ -45,6 +45,13 @@ function record(ev: Record<string, unknown>, cfg: Config): void {
45
45
  printText(`recorded: ${pyDumps(ev)}`);
46
46
  }
47
47
 
48
+ /** Append a penalty event silently: detector folds record these; the score CLI prints its own. */
49
+ export function recordPenalty(cfg: Config, p: { agent: string; kind: string; plan: string; note: string }): void {
50
+ const ev: Record<string, unknown> = { type: "penalty", agent: p.agent, kind: p.kind, plan: p.plan, note: p.note, ts: new PyFloat(nowSec()) };
51
+ mkdirSync(dirname(eventsPath(cfg)), { recursive: true });
52
+ appendFileSync(eventsPath(cfg), `${pyDumps(ev)}\n`);
53
+ }
54
+
48
55
  function expandCommits(repo: string, spec: string): string[] {
49
56
  const out: string[] = [];
50
57
  for (const raw of spec.split(",")) {
@@ -109,6 +109,18 @@ export interface Config {
109
109
  chat_unlock: boolean;
110
110
  plan_read_max_hours: number;
111
111
  idle_stops: number;
112
+ /** Provider rate limits (src/core/rate-limit.ts): a turn that ends on one waits it out instead of
113
+ * asking again straight into the limit. The words and the waits come from here. */
114
+ rate_limit: {
115
+ /** Case-insensitive substrings in the error text that mark a rate limit. */
116
+ patterns: string[];
117
+ /** Wait when the error text names no retry-after. */
118
+ default_wait_s: number;
119
+ /** Cap for the parsed (or doubled) wait, before slack. */
120
+ max_wait_s: number;
121
+ /** Added on top of every wait. */
122
+ slack_s: number;
123
+ };
112
124
  blocker_timeout_ms: number;
113
125
  skip_tools: string[];
114
126
  read_tools: string[];
@@ -156,6 +168,19 @@ export interface Config {
156
168
  priority: { sleep_sec: number };
157
169
  alerts: { temp_c: number; mem_psi: number; io_psi: number; cooldown_sec: number };
158
170
  snapshot: { tmp_dest: string; git_repo: string; git_backup: string; excludes: string[] };
171
+ /** Trace action rules (src/core/trace-actions.ts): what a scanned run may read, dial and write. */
172
+ traces: {
173
+ allowed_hosts: string[];
174
+ /** Product names (docs/config.md) whose files another product's run may not read quietly. */
175
+ owned_repos: string[];
176
+ actions: {
177
+ secret_globs: string[];
178
+ net_tools: string[];
179
+ shell_patterns: string[];
180
+ write_roots: string[];
181
+ deny_globs: string[];
182
+ };
183
+ };
159
184
  /** Optional overlay written by adapter install. Absent until an adapter is installed. */
160
185
  adapter?: { name: string; sessions: string; pins: string; extensions: string };
161
186
  /** Notices about legacy keys in the user's config file; empty when there are none. */
@@ -293,6 +318,12 @@ function check(cfg: Config): void {
293
318
  throw new ConfigError("guards.sub_max_calls_cap must be >= guards.sub_max_calls");
294
319
  }
295
320
  if (!(cfg.rollover.max_session_mb > 0)) throw new ConfigError("rollover.max_session_mb must be > 0");
321
+ if (!Array.isArray(cfg.guards.rate_limit.patterns) || cfg.guards.rate_limit.patterns.some(p => typeof p !== "string" || p === "")) {
322
+ throw new ConfigError("guards.rate_limit.patterns must be a list of non-empty strings");
323
+ }
324
+ if (!(cfg.guards.rate_limit.default_wait_s >= 1)) throw new ConfigError("guards.rate_limit.default_wait_s must be >= 1");
325
+ if (!(cfg.guards.rate_limit.max_wait_s >= 1)) throw new ConfigError("guards.rate_limit.max_wait_s must be >= 1");
326
+ if (!(cfg.guards.rate_limit.slack_s >= 0)) throw new ConfigError("guards.rate_limit.slack_s must be >= 0");
296
327
  if (!(cfg.rollover.exit_grace_s > 0)) throw new ConfigError("rollover.exit_grace_s must be > 0");
297
328
  if (!(cfg.metrics.report_days >= 1)) throw new ConfigError("metrics.report_days must be >= 1");
298
329
  if (!(cfg.ui.port >= 1 && cfg.ui.port <= 65535)) throw new ConfigError("ui.port must be between 1 and 65535");
@@ -315,6 +346,11 @@ function check(cfg: Config): void {
315
346
  }
316
347
  if (!rule.message) throw new ConfigError("brief.repo_rules.message must be a non-empty string");
317
348
  }
349
+ for (const list of [cfg.traces.allowed_hosts, cfg.traces.owned_repos, cfg.traces.actions.secret_globs, cfg.traces.actions.net_tools, cfg.traces.actions.shell_patterns, cfg.traces.actions.write_roots, cfg.traces.actions.deny_globs]) {
350
+ if (list.some((v) => typeof v !== "string" || v === "")) {
351
+ throw new ConfigError("traces lists must be non-empty strings");
352
+ }
353
+ }
318
354
  for (const [key, value] of Object.entries(cfg.paths)) {
319
355
  if (key === "work_roots") {
320
356
  if (!Array.isArray(value) || value.some(v => typeof v !== "string")) {
@@ -929,16 +929,17 @@ function progressEntries(text: string): string[] {
929
929
  }
930
930
 
931
931
  /** Entries an edit adds or rewrites: blocks whose text was not in the Progress section before. */
932
- function newProgressEntries(before: string, after: string): string[] {
932
+ export function newProgressEntries(before: string, after: string): string[] {
933
933
  const old = new Set(progressEntries(before));
934
934
  return progressEntries(after).filter(b => !old.has(b));
935
935
  }
936
936
 
937
- /** The value after "Findings:" in an entry, or null when the entry has no Findings line with content. */
938
- function findingsValue(block: string): string | null {
939
- const line = block.split("\n").find(l => l.includes("Findings:"));
937
+ /** The value after the entry's last "Findings:", or null when it has no Findings line with content. A "Findings:"
938
+ * quoted earlier in the entry (e.g. inside resume steps) is entry text, never the findings (I-20261025-51). */
939
+ export function findingsValue(block: string): string | null {
940
+ const line = block.split("\n").findLast(l => l.includes("Findings:"));
940
941
  if (!line) return null;
941
- return line.slice(line.indexOf("Findings:") + "Findings:".length).trim() || null;
942
+ return line.slice(line.lastIndexOf("Findings:") + "Findings:".length).trim() || null;
942
943
  }
943
944
 
944
945
  // Main's plan text outside "## Progress" must rest on files Main read itself (planReadProblems).