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.
@@ -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,28 @@ 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 rules: provider honesty (src/core/trace-provider.ts) and what a scanned run may read, dial and write (src/core/trace-actions.ts). */
172
+ traces: {
173
+ /** What an honest provider answer looks like. */
174
+ provider: {
175
+ /** Provider -> regex every assistant responseId must match; a provider without an entry is not checked. */
176
+ id_patterns: Record<string, string>;
177
+ /** Tools a run may call even when no result in the run proves the tool was offered. */
178
+ allow_tools: string[];
179
+ /** Model -> $ per million tokens; a model without an entry is not priced, so its cost is not checked. Both maps are open: an empty object in the template means the user may add keys. */
180
+ prices: Record<string, { input: number; output: number; cache_read: number; cache_write: number }>;
181
+ };
182
+ allowed_hosts: string[];
183
+ /** Product names (docs/config.md) whose files another product's run may not read quietly. */
184
+ owned_repos: string[];
185
+ actions: {
186
+ secret_globs: string[];
187
+ net_tools: string[];
188
+ shell_patterns: string[];
189
+ write_roots: string[];
190
+ deny_globs: string[];
191
+ };
192
+ };
159
193
  /** Optional overlay written by adapter install. Absent until an adapter is installed. */
160
194
  adapter?: { name: string; sessions: string; pins: string; extensions: string };
161
195
  /** Notices about legacy keys in the user's config file; empty when there are none. */
@@ -222,6 +256,12 @@ function merge(base: unknown, over: unknown, path: string): unknown {
222
256
  out[key] = adapterOverlay(over[key], next);
223
257
  continue;
224
258
  }
259
+ // An empty object in the template is an open map: the user may add any keys
260
+ // (traces.provider.id_patterns, traces.provider.prices).
261
+ if (Object.keys(base).length === 0) {
262
+ out[key] = over[key];
263
+ continue;
264
+ }
225
265
  throw new ConfigError(`unknown key ${next}`);
226
266
  }
227
267
  out[key] = merge(base[key], over[key], next);
@@ -293,6 +333,12 @@ function check(cfg: Config): void {
293
333
  throw new ConfigError("guards.sub_max_calls_cap must be >= guards.sub_max_calls");
294
334
  }
295
335
  if (!(cfg.rollover.max_session_mb > 0)) throw new ConfigError("rollover.max_session_mb must be > 0");
336
+ if (!Array.isArray(cfg.guards.rate_limit.patterns) || cfg.guards.rate_limit.patterns.some(p => typeof p !== "string" || p === "")) {
337
+ throw new ConfigError("guards.rate_limit.patterns must be a list of non-empty strings");
338
+ }
339
+ if (!(cfg.guards.rate_limit.default_wait_s >= 1)) throw new ConfigError("guards.rate_limit.default_wait_s must be >= 1");
340
+ if (!(cfg.guards.rate_limit.max_wait_s >= 1)) throw new ConfigError("guards.rate_limit.max_wait_s must be >= 1");
341
+ if (!(cfg.guards.rate_limit.slack_s >= 0)) throw new ConfigError("guards.rate_limit.slack_s must be >= 0");
296
342
  if (!(cfg.rollover.exit_grace_s > 0)) throw new ConfigError("rollover.exit_grace_s must be > 0");
297
343
  if (!(cfg.metrics.report_days >= 1)) throw new ConfigError("metrics.report_days must be >= 1");
298
344
  if (!(cfg.ui.port >= 1 && cfg.ui.port <= 65535)) throw new ConfigError("ui.port must be between 1 and 65535");
@@ -303,6 +349,21 @@ function check(cfg: Config): void {
303
349
  throw new ConfigError(`metrics.correction_patterns: not a valid regex: ${p}`);
304
350
  }
305
351
  }
352
+ for (const [provider, pattern] of Object.entries(cfg.traces.provider.id_patterns)) {
353
+ if (typeof pattern !== "string") throw new ConfigError(`traces.provider.id_patterns.${provider} must be a string`);
354
+ try {
355
+ new RegExp(pattern);
356
+ } catch {
357
+ throw new ConfigError(`traces.provider.id_patterns.${provider}: not a valid regex: ${pattern}`);
358
+ }
359
+ }
360
+ for (const [model, row] of Object.entries(cfg.traces.provider.prices)) {
361
+ for (const key of ["input", "output", "cache_read", "cache_write"] as const) {
362
+ if (typeof row[key] !== "number" || !Number.isFinite(row[key])) {
363
+ throw new ConfigError(`traces.provider.prices.${model}.${key} must be a number`);
364
+ }
365
+ }
366
+ }
306
367
  for (const rule of cfg.brief.repo_rules) {
307
368
  for (const key of ["match", "require", "first", "unless"] as const) {
308
369
  const pattern = rule[key];
@@ -315,6 +376,11 @@ function check(cfg: Config): void {
315
376
  }
316
377
  if (!rule.message) throw new ConfigError("brief.repo_rules.message must be a non-empty string");
317
378
  }
379
+ 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]) {
380
+ if (list.some((v) => typeof v !== "string" || v === "")) {
381
+ throw new ConfigError("traces lists must be non-empty strings");
382
+ }
383
+ }
318
384
  for (const [key, value] of Object.entries(cfg.paths)) {
319
385
  if (key === "work_roots") {
320
386
  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).
@@ -13,6 +13,11 @@
13
13
  // D4 owner-correction: an owner message matching the M4 correction patterns.
14
14
  // D5 claim-unbacked: a run's final report claims something its own tool output never
15
15
  // showed (gathered by the traces claims CLI, src/cli/traces.ts).
16
+ // D6 suspicious-action: a high-severity suspicious tool action the run's trace shows
17
+ // (gathered by the traces actions CLI, src/cli/traces.ts).
18
+ // D7 unreported-finding: a subagent run read files of another owned repo (config
19
+ // traces.owned_repos) while its final report says "Findings: none"; folds as source
20
+ // "traces" and records an agent-score penalty event for that agent on the plan.
16
21
 
17
22
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
18
23
  import { dirname, join } from "node:path";
@@ -23,7 +28,9 @@ import { nowSec, strftime } from "./clock.ts";
23
28
  import { log } from "./guards.ts";
24
29
  import { addIncident, type IncidentView } from "./incidents.ts";
25
30
  import type { GuardBlock } from "./metrics.ts";
26
- import { verifyClaims, type Claim } from "./trace-claims.ts";
31
+ import { verifyClaims, type Claim, type RelatedRun } from "./trace-claims.ts";
32
+ import { recordPenalty } from "./agent-score.ts";
33
+ import type { SuspiciousAction, UnreportedFinding } from "./trace-actions.ts";
27
34
 
28
35
  const HERE = dirname(fileURLToPath(import.meta.url));
29
36
 
@@ -149,12 +156,14 @@ export function ownerCorrection(text: string, patterns: RegExp[], now: number):
149
156
  /**
150
157
  * Final-report claims (src/core/trace-claims.ts) with no backing activity in the same run's
151
158
  * trace: a "13 passed" no toolResult shows, a SHA no git command printed, a label never passed
152
- * to a heavy-run call, a path no edit/write call carried. Evidence is the claiming line, which
153
- * the extractor already masked and capped, so nothing secret reaches the incident store.
159
+ * to a heavy-run call, a path no edit/write call carried. `related` — the traces of the
160
+ * subagent runs under a Main run's session dir (INCIDENT I-20261025-23) — backs the pure
161
+ * result-line claims Main's report cites from its subagents. Evidence is the claiming line,
162
+ * which the extractor already masked and capped, so nothing secret reaches the incident store.
154
163
  */
155
- export function claimUnbacked(claims: Claim[], events: TraceEvent[]): Finding[] {
164
+ export function claimUnbacked(claims: Claim[], events: TraceEvent[], related: RelatedRun[] = []): Finding[] {
156
165
  const out: Finding[] = [];
157
- for (const v of verifyClaims(claims, events)) {
166
+ for (const v of verifyClaims(claims, events, related)) {
158
167
  if (v.backed) continue;
159
168
  const c = v.claim;
160
169
  const what = c.count !== undefined ? `${c.kind} ${c.count}` : `${c.kind} ${c.value ?? ""}`;
@@ -168,6 +177,25 @@ export function claimUnbacked(claims: Claim[], events: TraceEvent[]): Finding[]
168
177
  return out;
169
178
  }
170
179
 
180
+ // ---- D6: a high-severity suspicious tool action ----
181
+
182
+ /**
183
+ * Suspicious tool actions (src/core/trace-actions.ts) at severity high: secret-path reads and
184
+ * exfil-shaped network commands. Medium and low findings stay in the `traces actions` report;
185
+ * only the ones worth waking the owner for become incidents. Evidence is already masked and
186
+ * capped by the rule engine, so nothing secret reaches the incident store.
187
+ */
188
+ export function suspiciousAction(actions: SuspiciousAction[]): Finding[] {
189
+ return actions
190
+ .filter((a) => a.severity === "high")
191
+ .map((a) => ({
192
+ kind: "suspicious-action",
193
+ summary: `${a.runId}: ${a.summary}`,
194
+ evidence: a.evidence,
195
+ fingerprint: `suspicious-action:${a.rule}:${a.target}`,
196
+ }));
197
+ }
198
+
171
199
  // ---- the runner ----
172
200
 
173
201
  /** The plain inputs the callers gather; a detector without its input does not run. */
@@ -184,6 +212,10 @@ export interface DetectorInput {
184
212
  /** D5: one run's final-report claims plus the same run's trace events (the traces CLI gathers both). */
185
213
  claims?: Claim[];
186
214
  events?: TraceEvent[];
215
+ /** D6: suspicious tool actions from one or more scanned runs (the traces actions CLI gathers them). */
216
+ actions?: SuspiciousAction[];
217
+ /** D7: cross-product reads a subagent run hid behind a Findings: none line (src/core/trace-actions.ts). */
218
+ unreported?: UnreportedFinding[];
187
219
  }
188
220
 
189
221
  /**
@@ -231,6 +263,28 @@ export function runDetectors(cfg: Config, input: DetectorInput, now = nowSec()):
231
263
  if (input.claims && input.events) {
232
264
  attempt("claim-unbacked", () => claimUnbacked(input.claims!, input.events!));
233
265
  }
266
+ if (input.actions) {
267
+ attempt("suspicious-action", () => suspiciousAction(input.actions!));
268
+ }
269
+ if (input.unreported) {
270
+ for (const f of input.unreported!) {
271
+ try {
272
+ const { incident, deduped } = addIncident(
273
+ cfg,
274
+ { source: "traces", kind: "unreported-finding", summary: f.summary, evidence: f.evidence, fingerprint: `unreported-finding:${f.agent}:${f.target}` },
275
+ now,
276
+ );
277
+ if (!deduped) recordPenalty(cfg, { agent: f.agent, kind: "unreported-finding", plan: f.plan, note: f.summary });
278
+ log(
279
+ cfg.paths.guard_log,
280
+ `incident ${incident.id} [traces/${incident.kind}]${deduped ? ` sighting #${incident.count}` : " opened"}: ${incident.summary}`,
281
+ );
282
+ out.push(incident);
283
+ } catch (err) {
284
+ log(cfg.paths.guard_log, `detector unreported-finding failed: ${err instanceof Error ? err.message : String(err)}`);
285
+ }
286
+ }
287
+ }
234
288
  return out;
235
289
  }
236
290
 
@@ -14,7 +14,7 @@ import { nowSec, strftime } from "./clock.ts";
14
14
  import type { Config } from "./config.ts";
15
15
  import * as q from "./queue/lib.ts";
16
16
 
17
- export type IncidentSource = "realtime" | "daily" | "weekly" | "main" | "findings";
17
+ export type IncidentSource = "realtime" | "daily" | "weekly" | "main" | "findings" | "traces";
18
18
 
19
19
  export interface IncidentRec {
20
20
  id: string;
@@ -80,7 +80,7 @@ function parseLine(line: string): IncidentRec | ResolutionRec | null {
80
80
  if (rec.type !== undefined) return null;
81
81
  if (typeof rec.fingerprint !== "string" || typeof rec.kind !== "string" || typeof rec.summary !== "string" || typeof rec.ts !== "number")
82
82
  return null;
83
- const source = rec.source === "realtime" || rec.source === "daily" || rec.source === "weekly" || rec.source === "findings" ? rec.source : "main";
83
+ const source = rec.source === "realtime" || rec.source === "daily" || rec.source === "weekly" || rec.source === "findings" || rec.source === "traces" ? rec.source : "main";
84
84
  return {
85
85
  id: rec.id,
86
86
  fingerprint: rec.fingerprint,
@@ -0,0 +1,63 @@
1
+ // Provider rate limits (plan 20261025_0640): a turn that ended on one waits it out instead of
2
+ // asking again straight into the limit. Pure decisions only: what counts as a rate limit, and how
3
+ // long to wait. The words and the waits come from config (guards.rate_limit); the adapter supplies
4
+ // the turn's stop reason and error text and arms the timer.
5
+
6
+ export interface RateLimitConfig {
7
+ /** Case-insensitive substrings in the error text that mark a rate limit. */
8
+ patterns: string[];
9
+ /** Wait when the error text names no retry-after. */
10
+ default_wait_s: number;
11
+ /** Cap for the parsed (or doubled) wait, before slack. */
12
+ max_wait_s: number;
13
+ /** Added on top of every wait. */
14
+ slack_s: number;
15
+ }
16
+
17
+ export interface RateLimitWait {
18
+ /** Epoch ms when the next turn should start. */
19
+ untilMs: number;
20
+ /** Total wait in ms, slack included. */
21
+ waitMs: number;
22
+ }
23
+
24
+ const RETRY_AFTER_MS = /retry-after-ms[=:]\s*(\d+)/i;
25
+ const RETRY_AFTER_S = /retry-after[=:]\s*(\d+)/i;
26
+
27
+ function retryAfterMs(errorText: string, cfg: RateLimitConfig): number {
28
+ const ms = RETRY_AFTER_MS.exec(errorText);
29
+ if (ms) return Number(ms[1]);
30
+ const s = RETRY_AFTER_S.exec(errorText);
31
+ if (s) return Number(s[1]) * 1000;
32
+ return cfg.default_wait_s * 1000;
33
+ }
34
+
35
+ /**
36
+ * The wait for a turn that ended on a provider rate limit, or null when it did not: the stop
37
+ * reason must be "error" and the error text must contain one of the configured patterns
38
+ * (case-insensitive). The wait is the retry-after the text names (`retry-after-ms=<ms>` or
39
+ * `retry-after: <seconds>`, else default_wait_s); attempt >= 2 doubles the previous wait of the
40
+ * episode; every wait is clamped to max_wait_s, then slack_s is added.
41
+ */
42
+ export function rateLimitWait(
43
+ stopReason: string | null,
44
+ errorText: string | null,
45
+ now: number,
46
+ cfg: RateLimitConfig,
47
+ attempt: number,
48
+ ): RateLimitWait | null {
49
+ if (stopReason !== "error" || !errorText) return null;
50
+ const text = errorText.toLowerCase();
51
+ if (!cfg.patterns.some(p => text.includes(p.toLowerCase()))) return null;
52
+ const capMs = cfg.max_wait_s * 1000;
53
+ let baseMs = retryAfterMs(errorText, cfg);
54
+ for (let i = 1; i < Math.max(1, attempt); i++) {
55
+ baseMs *= 2;
56
+ if (baseMs >= capMs) {
57
+ baseMs = capMs;
58
+ break;
59
+ }
60
+ }
61
+ const waitMs = Math.min(baseMs, capMs) + cfg.slack_s * 1000;
62
+ return { untilMs: now + waitMs, waitMs };
63
+ }
@@ -172,7 +172,16 @@ export interface Report {
172
172
  worst: { key: string; name: string; cur: number | null; prev: number | null; change: number | null } | null;
173
173
  }
174
174
 
175
- export function buildReport(cfg: Config, source: RunSource, days: number, now: number): Report {
175
+ /** Weekly provider-honesty counts the report appends; the CLI caller builds them from the
176
+ * sessions root (core has no adapter), folding src/core/trace-provider.ts findings by kind. */
177
+ export interface ProviderSummary {
178
+ /** Runs scanned inside the window. */
179
+ runs: number;
180
+ /** Findings by rule kind over those runs. */
181
+ byKind: Record<string, number>;
182
+ }
183
+
184
+ export function buildReport(cfg: Config, source: RunSource, days: number, now: number, provider?: ProviderSummary): Report {
176
185
  const inp = loadInputs(cfg, source, now, days);
177
186
  const events = [...inp.events, ...readMetricEvents(cfg)];
178
187
  const blocks = readBlocks(cfg);
@@ -208,6 +217,16 @@ export function buildReport(cfg: Config, source: RunSource, days: number, now: n
208
217
  "",
209
218
  "Approved rules, before vs after:",
210
219
  ...ruleLines(cfg, source, events, blocks, incidents, days, now),
220
+ ...(provider
221
+ ? [
222
+ "",
223
+ `Provider honesty over ${provider.runs} runs: ` +
224
+ (Object.entries(provider.byKind)
225
+ .filter(([, n]) => n > 0)
226
+ .map(([k, n]) => `${n} ${k}`)
227
+ .join(", ") || "no findings"),
228
+ ]
229
+ : []),
211
230
  ].join("\n");
212
231
 
213
232
  const md = [