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.
@@ -0,0 +1,213 @@
1
+ // Provider-honesty rules (plan 20261024_0302): what came back must be what was asked for.
2
+ // Three checks over one run's TraceEvents, each a pure function so tests feed fixtures and the
3
+ // later detector/CLI wiring gathers real runs:
4
+ // model-swap the run announced a model (model_change) but an assistant message shows
5
+ // another model or another provider, or the run resolved to a fallback;
6
+ // odd-response-id an assistant message's responseId misses the shape configured for its
7
+ // provider (traces.provider.id_patterns);
8
+ // unoffered-tool a toolCall for a tool the session was never shown as offered (P2).
9
+ // Finding text passes through the shared mask: evidence holds at most 160 chars and long
10
+ // token-like runs (a responseId can look exactly like a credential) never survive verbatim.
11
+
12
+ import type { TraceEvent } from "./adapter.ts";
13
+ import type { Finding } from "./incident-detectors.ts";
14
+ import { maskEvidence } from "./trace-claims.ts";
15
+
16
+ /**
17
+ * Folds one finding into the list unless its fingerprint is already there, so repeats of the
18
+ * same dishonesty in one run stay one finding (first sighting wins the evidence). Every rule
19
+ * uses this, so masking and the evidence cap cannot be forgotten at a call site.
20
+ */
21
+ function fold(out: Finding[], seen: Set<string>, kind: string, summary: string, evidence: string, fingerprint: string): void {
22
+ if (seen.has(fingerprint)) return;
23
+ seen.add(fingerprint);
24
+ out.push({ kind, summary, evidence: maskEvidence(evidence), fingerprint });
25
+ }
26
+
27
+ /** Assistant-message events: the only lines that speak with a provider's voice. */
28
+ function isServed(e: TraceEvent): boolean {
29
+ return e.kind === "toolCall" || e.kind === "assistantText";
30
+ }
31
+
32
+ /**
33
+ * The run's announcements vs what the assistant messages show. The announced model is
34
+ * provider-prefixed ("<provider>/<model>") while a message's fields are bare, so the prefix is
35
+ * the promised provider and the rest the promised model; a model without a prefix promises no
36
+ * provider and only the model is judged. A run that never announced a model is not judged:
37
+ * without a claim there is nothing to be honest against. A `resolvedModelIsFallback`
38
+ * announcement is itself a swap — the run was asked for one model and served another.
39
+ */
40
+ export function modelSwaps(events: TraceEvent[]): Finding[] {
41
+ const out: Finding[] = [];
42
+ const seen = new Set<string>();
43
+ let announced: TraceEvent | undefined;
44
+ for (const e of events) {
45
+ if (e.kind === "modelChange") {
46
+ announced = e;
47
+ if (e.fallback) {
48
+ fold(out, seen, "model-swap", `run ${e.runId}: the requested model was resolved to a fallback`,
49
+ `run ${e.runId}: model_change for ${e.model ?? "?"} says resolvedModelIsFallback`,
50
+ `model-swap:${e.runId}:fallback`);
51
+ }
52
+ continue;
53
+ }
54
+ if (!isServed(e) || !announced?.model) continue;
55
+ const slash = announced.model.indexOf("/");
56
+ const askedModel = slash === -1 ? announced.model : announced.model.slice(slash + 1);
57
+ const askedProvider = slash === -1 ? undefined : announced.model.slice(0, slash);
58
+ if (e.model && e.model !== askedModel) {
59
+ fold(out, seen, "model-swap", `run ${e.runId}: asked for ${askedModel}, an assistant message says ${e.model}`,
60
+ `run ${e.runId}: model_change says ${announced.model}, message says model ${e.model} (provider ${e.provider ?? "?"})`,
61
+ `model-swap:${e.runId}:model:${askedModel}:${e.model}`);
62
+ }
63
+ if (askedProvider && e.provider && e.provider !== askedProvider) {
64
+ fold(out, seen, "model-swap", `run ${e.runId}: asked provider ${askedProvider}, an assistant message says ${e.provider}`,
65
+ `run ${e.runId}: model_change says ${announced.model}, message says provider ${e.provider} (model ${e.model ?? "?"})`,
66
+ `model-swap:${e.runId}:provider:${askedProvider}:${e.provider}`);
67
+ }
68
+ }
69
+ return out;
70
+ }
71
+
72
+ /**
73
+ * Response-id shapes per provider (traces.provider.id_patterns): an id that misses the
74
+ * configured shape is odd. An absent id is not checked — missing is not malformed, and the
75
+ * 7-day smoke showed absent ids on every run of some providers. A provider without an entry is
76
+ * not checked, and an unparseable pattern disables that one provider rather than guessing what
77
+ * its ids should look like. Repeats fold to one finding per run and provider.
78
+ */
79
+ export function oddResponseIds(events: TraceEvent[], idPatterns: Record<string, string>): Finding[] {
80
+ const out: Finding[] = [];
81
+ const seen = new Set<string>();
82
+ const shapes = new Map<string, RegExp | null>();
83
+ for (const e of events) {
84
+ if (!isServed(e) || !e.provider) continue;
85
+ const pattern = idPatterns[e.provider];
86
+ if (pattern === undefined) continue;
87
+ if (!shapes.has(e.provider)) {
88
+ let rx: RegExp | null;
89
+ try {
90
+ rx = new RegExp(pattern);
91
+ } catch {
92
+ rx = null;
93
+ }
94
+ shapes.set(e.provider, rx);
95
+ }
96
+ const rx = shapes.get(e.provider);
97
+ if (!rx) continue;
98
+ if (e.responseId === undefined || rx.test(e.responseId)) continue;
99
+ fold(out, seen, "odd-response-id", `run ${e.runId}: ${e.provider} answered with a responseId that misses its configured shape`,
100
+ `${e.provider} responseId "${e.responseId}" must match ${pattern}`,
101
+ `odd-response-id:${e.runId}:${e.provider}`);
102
+ }
103
+ return out;
104
+ }
105
+
106
+ /** A tool result that says the harness does not know the tool at all (the refusal of a made-up call). */
107
+ const UNKNOWN_TOOL = /^(tool \S+ not found|no such tool|unknown tool)\b/i;
108
+
109
+ /**
110
+ * Tool calls for tools the session was never shown as offered. The offered set is the config
111
+ * allow-list plus the names parsed from the request's own tool list (an http dump, passed in by
112
+ * the caller) plus every tool the run itself got a result for — except a result refusing the
113
+ * call as an unknown tool. The plan wording says "earlier successful tool names"; the check
114
+ * accepts any non-refusal result anywhere in the run on purpose: judging only what came earlier
115
+ * would flag the honest first use of every tool, and an error (a guard refusal, bad arguments)
116
+ * still means the harness ran the tool — the 7-day smoke had 14 such real tools flagged.
117
+ */
118
+ export function unofferedTools(events: TraceEvent[], allowTools: string[], offered: string[] = []): Finding[] {
119
+ const proven = new Set<string>([...allowTools, ...offered]);
120
+ for (const e of events) {
121
+ if (e.kind !== "toolResult" || !e.tool) continue;
122
+ if (e.isError === true && UNKNOWN_TOOL.test(e.text ?? "")) continue;
123
+ proven.add(e.tool);
124
+ }
125
+ const out: Finding[] = [];
126
+ const seen = new Set<string>();
127
+ for (const e of events) {
128
+ if (e.kind !== "toolCall" || !e.tool || e.tool === "?") continue;
129
+ if (proven.has(e.tool)) continue;
130
+ fold(out, seen, "unoffered-tool", `run ${e.runId}: toolCall "${e.tool}" was never offered to the session`,
131
+ `toolCall "${e.tool}" has no successful result in the run, is not allow-listed and is not in the request's tool list`,
132
+ `unoffered-tool:${e.runId}:${e.tool}`);
133
+ }
134
+ return out;
135
+ }
136
+
137
+ /**
138
+ * Output tokens billed for an assistant message that wrote nothing: the parser marks a
139
+ * content-less message as assistantText with empty text, and billed output with no content is
140
+ * phantom. A message without usage cannot be judged and a real reply never is. Each phantom
141
+ * message is its own finding, keyed by response id (or position when the line carries neither).
142
+ */
143
+ export function phantomOutput(events: TraceEvent[]): Finding[] {
144
+ const out: Finding[] = [];
145
+ const seen = new Set<string>();
146
+ for (let i = 0; i < events.length; i++) {
147
+ const e = events[i]!;
148
+ if (e.kind !== "assistantText" || e.text !== "" || !e.usage) continue;
149
+ if (!(e.usage.output > 0)) continue;
150
+ const id = e.responseId ?? (e.ts === null ? String(i) : String(e.ts));
151
+ fold(out, seen, "phantom-output", `run ${e.runId}: an assistant message billed ${e.usage.output} output tokens but wrote nothing`,
152
+ `assistant message billed ${e.usage.output} output tokens with empty content (responseId ${e.responseId ?? "<absent>"})`,
153
+ `phantom-output:${e.runId}:${id}`);
154
+ }
155
+ return out;
156
+ }
157
+
158
+ /**
159
+ * The run's own model_usage accounting vs the configured price table ($ per million tokens).
160
+ * Billed cost beyond ±20% of the table price is a mismatch in either direction — over-billing
161
+ * and under-billing both lie about what the run cost. A zero-priced model that still bills is
162
+ * a mismatch too (no percentage exists against zero). A model without an entry is not priced:
163
+ * a wrong guess would be worse than no check. Repeats fold per run and model.
164
+ */
165
+ export function costMismatch(events: TraceEvent[], prices: Record<string, ProviderPrice>): Finding[] {
166
+ const out: Finding[] = [];
167
+ const seen = new Set<string>();
168
+ for (const e of events) {
169
+ if (e.kind !== "usage" || !e.model || !e.usage) continue;
170
+ const u = e.usage;
171
+ if (!(u.totalTokens > 0)) continue;
172
+ const bare = e.model.includes("/") ? e.model.slice(e.model.indexOf("/") + 1) : e.model;
173
+ const price = prices[e.model] ?? prices[bare];
174
+ if (!price) continue;
175
+ const expected = (u.input * price.input + u.output * price.output + u.cacheRead * price.cache_read + u.cacheWrite * price.cache_write) / 1_000_000;
176
+ const billed = u.cost;
177
+ const off = expected > 0 ? Math.abs(billed - expected) / expected : Math.abs(billed);
178
+ if (!(off > 0.2)) continue;
179
+ const pct = expected > 0 ? ` (${Math.round((billed / expected - 1) * 100)}%)` : "";
180
+ fold(out, seen, "cost-mismatch", `run ${e.runId}: ${e.model} billed $${billed} but the price table says $${Number(expected.toFixed(6))}${pct}`,
181
+ `model_usage ${e.model}: billed $${billed}, tokens in ${u.input} out ${u.output} cacheRead ${u.cacheRead} cacheWrite ${u.cacheWrite}, table says $${Number(expected.toFixed(6))}${pct}`,
182
+ `cost-mismatch:${e.runId}:${e.model}`);
183
+ }
184
+ return out;
185
+ }
186
+
187
+ /** What the provider-honesty rules need from config (cfg.traces.provider). */
188
+ export interface ProviderRules {
189
+ id_patterns: Record<string, string>;
190
+ allow_tools: string[];
191
+ }
192
+
193
+ /** One model's price row: $ per million tokens (traces.provider.prices). */
194
+ export interface ProviderPrice {
195
+ input: number;
196
+ output: number;
197
+ cache_read: number;
198
+ cache_write: number;
199
+ }
200
+
201
+ /**
202
+ * Every rule at once over one run's events, in rule order (P1 swaps, P1 ids, P2 tools, P3
203
+ * phantom, P3 cost) — the shape the metrics report summary and the smoke scan both fold.
204
+ */
205
+ export function providerFindings(events: TraceEvent[], rules: ProviderRules, prices: Record<string, ProviderPrice> = {}, offered: string[] = []): Finding[] {
206
+ return [
207
+ ...modelSwaps(events),
208
+ ...oddResponseIds(events, rules.id_patterns),
209
+ ...unofferedTools(events, rules.allow_tools, offered),
210
+ ...phantomOutput(events),
211
+ ...costMismatch(events, prices),
212
+ ];
213
+ }
@@ -28,6 +28,7 @@ score:
28
28
  false-claim: 5
29
29
  rule-break: 2
30
30
  escaped-defect: 8
31
+ unreported-finding: 5
31
32
  diagnose_weight: 4
32
33
  gate_days: 7
33
34
  board_days: 7
@@ -107,6 +108,11 @@ guards:
107
108
  chat_unlock: false # the owner's whole chat message "unlock"/"unlock N"/"lock" moves the guard unlock file
108
109
  plan_read_max_hours: 24
109
110
  idle_stops: 3
111
+ rate_limit:
112
+ patterns: ["429", "rate_limit", "rate limit", "overloaded", "529"] # error-text substrings (case-insensitive) that mark a provider rate limit
113
+ default_wait_s: 300 # wait when the error text names no retry-after
114
+ max_wait_s: 3600 # cap for the parsed (or doubled) wait, before slack
115
+ slack_s: 15 # added on top of every wait
110
116
  blocker_timeout_ms: 10000
111
117
  skip_tools: [todo, wait, ask, web_search, job, cancel_job]
112
118
  read_tools: [read, grep, glob, find]
@@ -190,3 +196,36 @@ snapshot:
190
196
  - ".font-unix"
191
197
  - "snap-private-tmp"
192
198
  - "*.sock"
199
+
200
+ traces:
201
+ provider:
202
+ # Provider-honesty rules (src/core/trace-provider.ts). The maps below are open: an empty
203
+ # object here means "add your own keys" in your config. id_patterns maps a provider to the
204
+ # regex every assistant responseId must match (a provider without an entry is not checked);
205
+ # sampled defaults live in README.md. prices maps a model to $ per million tokens; a model
206
+ # without an entry is not priced. allow_tools: tools a run may call even when no result in
207
+ # the run proves the tool was offered.
208
+ id_patterns: {}
209
+ prices: {}
210
+ allow_tools: []
211
+ allowed_hosts: # hosts a network command may touch without a finding
212
+ - localhost
213
+ - 127.0.0.1
214
+ - "::1"
215
+ owned_repos: [] # product names another product's run may not read quietly; the intended list lives in docs/config.md
216
+ actions:
217
+ secret_globs: # a read matching any glob is a high finding; evidence is masked either way
218
+ - "~/.ssh/**"
219
+ - "**/*.env*"
220
+ - "**/*keys*.txt"
221
+ - "**/mcp.json"
222
+ - "**/keyring*/**"
223
+ - "**/.gnupg/**"
224
+ - "**/.password-store/**"
225
+ net_tools: [curl, wget, nc, ssh, scp] # commands that reach a host (word match inside shell tools)
226
+ shell_patterns: ['| sh', '| bash', 'eval "$('] # a command containing one feeds a shell from a pipe
227
+ write_roots: [] # prefixes a run may write (plan Worktree: roots); empty falls back to paths.work_roots; both empty = the scope check is off
228
+ deny_globs: # writes matching any glob are flagged wherever they land
229
+ - "~/.omp/**"
230
+ - "~/.local/bin/**"
231
+ - "~/.local/state/**"