neurastream 0.2.17 → 0.2.19

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,117 @@
1
+ import { spawnSync } from "node:child_process";
2
+
3
+ export interface WallTime {
4
+ y: number;
5
+ mo: number;
6
+ d: number;
7
+ h: number;
8
+ mi: number;
9
+ s: number;
10
+ }
11
+
12
+ // Offset in ms of `zone` from UTC at the instant `epochMs` (local wall clock minus UTC).
13
+ function zoneOffsetMs(epochMs: number, zone: string): number {
14
+ const parts = new Intl.DateTimeFormat("en-US", {
15
+ timeZone: zone,
16
+ hourCycle: "h23",
17
+ year: "numeric",
18
+ month: "numeric",
19
+ day: "numeric",
20
+ hour: "numeric",
21
+ minute: "numeric",
22
+ second: "numeric",
23
+ }).formatToParts(new Date(epochMs));
24
+ const get = (type: string): number => Number(parts.find((p) => p.type === type)?.value);
25
+ const wallAsUtc = Date.UTC(get("year"), get("month") - 1, get("day"), get("hour"), get("minute"), get("second"));
26
+ return wallAsUtc - Math.floor(epochMs / 1000) * 1000;
27
+ }
28
+
29
+ // Epoch seconds for a wall-clock time in `zone`; two passes settle the DST edge.
30
+ export function wallToEpoch(wall: WallTime, zone: string): number {
31
+ const wallUtc = Date.UTC(wall.y, wall.mo - 1, wall.d, wall.h, wall.mi, wall.s);
32
+ const first = wallUtc - zoneOffsetMs(wallUtc, zone);
33
+ const second = wallUtc - zoneOffsetMs(first, zone);
34
+ return Math.floor(second / 1000);
35
+ }
36
+
37
+ const WHEN = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?$/;
38
+
39
+ export function parseWhen(text: string): WallTime | null {
40
+ const m = WHEN.exec(text.trim());
41
+ if (!m) return null;
42
+ const [, ys = "", mos = "", ds = "", hs = "", mis = "", ss = ""] = m;
43
+ const wall = { y: +ys, mo: +mos, d: +ds, h: +hs, mi: +mis, s: ss ? +ss : 0 };
44
+ const check = new Date(Date.UTC(wall.y, wall.mo - 1, wall.d, wall.h, wall.mi, wall.s));
45
+ return check.getUTCFullYear() === wall.y && check.getUTCMonth() === wall.mo - 1 && check.getUTCDate() === wall.d &&
46
+ check.getUTCHours() === wall.h && check.getUTCMinutes() === wall.mi && check.getUTCSeconds() === wall.s ? wall : null;
47
+ }
48
+
49
+ function zoneAbbrev(epoch: number): string {
50
+ // Pass the zone Intl actually uses: Bun neither forwards a TZ set after startup by default
51
+ // nor enumerates it in process.env, so `date` would label the local time with the wrong zone.
52
+ const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
53
+ const opts = { encoding: "utf8" as const, env: { ...process.env, TZ: zone } };
54
+ const probe = process.platform === "darwin"
55
+ ? spawnSync("date", ["-r", String(epoch), "+%Z"], opts)
56
+ : spawnSync("date", ["-d", `@${epoch}`, "+%Z"], opts);
57
+ if (probe.status === 0 && probe.stdout?.trim()) return probe.stdout.trim();
58
+ const parts = new Intl.DateTimeFormat("en-US", { timeZoneName: "short" }).formatToParts(new Date(epoch * 1000));
59
+ return parts.find(p => p.type === "timeZoneName")?.value ?? "";
60
+ }
61
+
62
+ export function localStamp(epoch: number): string {
63
+ const parts = new Intl.DateTimeFormat("en-US", {
64
+ hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit",
65
+ hour: "2-digit", minute: "2-digit", second: "2-digit",
66
+ }).formatToParts(new Date(epoch * 1000));
67
+ const get = (type: string): string => parts.find(p => p.type === type)?.value ?? "";
68
+ return `${get("year")}-${get("month")}-${get("day")} ${get("hour")}:${get("minute")}:${get("second")} ${zoneAbbrev(epoch)}`;
69
+ }
70
+
71
+ function explicitZoneEpoch(wall: WallTime, zone: string): number {
72
+ if (zone === "Z" || zone === "UTC" || zone === "GMT") return wallToEpoch(wall, "UTC");
73
+ const offset = /^([+-])(\d{2}):?(\d{2})$/.exec(zone);
74
+ if (offset) {
75
+ const minutes = (Number(offset[2]) * 60 + Number(offset[3])) * (offset[1] === "+" ? 1 : -1);
76
+ return Math.floor((Date.UTC(wall.y, wall.mo - 1, wall.d, wall.h, wall.mi, wall.s) - minutes * 60_000) / 1000);
77
+ }
78
+ return wallToEpoch(wall, zone);
79
+ }
80
+
81
+ export function annotateResetTimes(text: string, rule: { pattern: string; zone: string }): string {
82
+ let pattern: RegExp;
83
+ try {
84
+ pattern = new RegExp(rule.pattern, "g");
85
+ } catch {
86
+ return text;
87
+ }
88
+ const matches = [...text.matchAll(pattern)];
89
+ if (matches.length === 0) return text;
90
+ let result = "";
91
+ let position = 0;
92
+ for (const match of matches) {
93
+ const full = match[0] ?? "";
94
+ const index = match.index ?? 0;
95
+ const wallText = match[1];
96
+ const explicitZone = match[2]?.trim();
97
+ const end = index + full.length;
98
+ const timestampEnd = index + full.trimEnd().length;
99
+ if (text.slice(timestampEnd).startsWith("(= ") || text.slice(timestampEnd).startsWith(" (= ")) {
100
+ result += text.slice(position, end);
101
+ position = end;
102
+ continue;
103
+ }
104
+ result += text.slice(position, timestampEnd);
105
+ position = timestampEnd;
106
+ if (!wallText) continue;
107
+ const wall = parseWhen(wallText);
108
+ if (!wall) continue;
109
+ try {
110
+ const epoch = explicitZone ? explicitZoneEpoch(wall, explicitZone) : wallToEpoch(wall, rule.zone);
111
+ result += ` (= ${localStamp(epoch)} local)`;
112
+ } catch {
113
+ // A zone we cannot resolve is not a basis for guessing.
114
+ }
115
+ }
116
+ return result + text.slice(position);
117
+ }
@@ -0,0 +1,199 @@
1
+ // Prompt bloat (plan 20261024_0303 P1): how big each model call's prompt was, and when a run
2
+ // is stuffing its context. A call's prompt is what the provider read before it wrote a token:
3
+ // usage.input + usage.cacheRead + usage.cacheWrite. Rows come from the usage assistant
4
+ // messages carry — one message is one call, and its content parts share the response id, so
5
+ // they fold into one row. The two look-alikes are not calls: the periodic model_usage lines are
6
+ // running totals of the accounting, not per-call rows, and a toolResult's usage belongs to no
7
+ // model call. A run flags prompt-bloat when its FIRST call opens over first_call_max (a run
8
+ // that starts huge stays huge), or any call passes ratio_of_limit × its model's
9
+ // context_limits entry — a model without an entry is not limit-checked, a wrong guess would be
10
+ // worse than no check. Finding text goes through the shared mask like every trace finding.
11
+
12
+ import type { TraceEvent } from "./adapter.ts";
13
+ import type { Config } from "./config.ts";
14
+ import type { Finding } from "./incident-detectors.ts";
15
+ import { foldFinding } from "./trace-provider.ts";
16
+
17
+ /** One model call's prompt size, in trace order. */
18
+ export interface CallSize {
19
+ ts: number | null;
20
+ model?: string;
21
+ /** usage.input + usage.cacheRead + usage.cacheWrite. */
22
+ prompt: number;
23
+ }
24
+
25
+ /** One row per non-aggregate model call: usage-bearing assistant messages, folded per response id. */
26
+ export function callSizes(events: TraceEvent[], aggregateApis: readonly string[] = []): CallSize[] {
27
+ const out: CallSize[] = [];
28
+ let last = "";
29
+ for (const e of events) {
30
+ if (e.kind !== "toolCall" && e.kind !== "assistantText") continue;
31
+ if (e.api !== undefined && aggregateApis.includes(e.api)) {
32
+ last = "";
33
+ continue;
34
+ }
35
+ const u = e.usage;
36
+ if (!u) continue;
37
+ // Parts of one assistant message share the response id and carry the same usage; a
38
+ // message without one folds only while the next usage-bearing event is identical.
39
+ const key = e.responseId ?? `${e.ts}|${e.model}|${u.input}|${u.output}|${u.cacheRead}|${u.cacheWrite}`;
40
+ if (key === last) continue;
41
+ last = key;
42
+ out.push({ ts: e.ts, model: e.model, prompt: u.input + u.cacheRead + u.cacheWrite });
43
+ }
44
+ return out;
45
+ }
46
+
47
+ /** What the bloat rules need from config (cfg.traces.bloat). */
48
+ export interface BloatRules {
49
+ /** The largest first-call prompt a healthy run may open with. */
50
+ first_call_max: number;
51
+ /** A call flags when its prompt passes ratio_of_limit × its model's context limit. */
52
+ ratio_of_limit: number;
53
+ /** Model -> context tokens; a model without an entry is not limit-checked. */
54
+ context_limits: Record<string, number>;
55
+ /** APIs whose usage aggregates several internal model calls. */
56
+ aggregate_apis?: string[];
57
+ }
58
+
59
+ /** Maps config onto the rule set (cfg.traces.bloat), the way actionsRules maps the traces lists. */
60
+ export function bloatRules(cfg: Config): BloatRules {
61
+ return {
62
+ first_call_max: cfg.traces.bloat.first_call_max,
63
+ ratio_of_limit: cfg.traces.bloat.ratio_of_limit,
64
+ context_limits: cfg.traces.bloat.context_limits,
65
+ aggregate_apis: cfg.traces.bloat.aggregate_apis,
66
+ };
67
+ }
68
+
69
+ /** The model's context_limits entry: the exact key wins, then the bare model without a provider prefix. */
70
+ function limitOf(model: string, limits: Record<string, number>): number | undefined {
71
+ if (limits[model] !== undefined) return limits[model];
72
+ const bare = model.includes("/") ? model.slice(model.indexOf("/") + 1) : model;
73
+ return limits[bare];
74
+ }
75
+
76
+ /**
77
+ * The prompt-bloat findings of one run's events: a first-call finding when the run opens over
78
+ * first_call_max, then one finding per call past its model's limit budget, each naming the
79
+ * call's 1-based index. Findings fold like every rule's (one per fingerprint, masked evidence).
80
+ */
81
+ export function bloatFindings(events: TraceEvent[], rules: BloatRules): Finding[] {
82
+ const out: Finding[] = [];
83
+ const seen = new Set<string>();
84
+ const runId = events[0]?.runId ?? "?";
85
+ const calls = callSizes(events, rules.aggregate_apis);
86
+ if (calls.length === 0) return out;
87
+ const first = calls[0]!;
88
+ if (first.prompt > rules.first_call_max) {
89
+ foldFinding(out, seen, "prompt-bloat",
90
+ `run ${runId}: the first call's prompt is ${first.prompt} tokens, over the ${rules.first_call_max} first-call ceiling`,
91
+ `first call (model ${first.model ?? "?"}) prompt ${first.prompt}; ceiling ${rules.first_call_max}`,
92
+ `prompt-bloat:${runId}:first`);
93
+ }
94
+ for (let i = 0; i < calls.length; i++) {
95
+ const c = calls[i]!;
96
+ if (!c.model) continue;
97
+ const limit = limitOf(c.model, rules.context_limits);
98
+ if (limit === undefined) continue;
99
+ const budget = rules.ratio_of_limit * limit;
100
+ if (c.prompt <= budget) continue;
101
+ const pct = Math.round((c.prompt / limit) * 100);
102
+ foldFinding(out, seen, "prompt-bloat",
103
+ `run ${runId}: call ${i + 1} (${c.model}) prompt ${c.prompt} tokens is ${pct}% of its ${limit} context limit`,
104
+ `call ${i + 1} of ${calls.length} (model ${c.model}) prompt ${c.prompt}; limit ${limit}, flag over ${rules.ratio_of_limit} × limit = ${budget}`,
105
+ `prompt-bloat:${runId}:${i + 1}:${c.model}`);
106
+ }
107
+ return out;
108
+ }
109
+
110
+ /** One named slice of a dumped request's prompt; bytes are the JSON.stringify length. */
111
+ export interface DumpPart {
112
+ name: string;
113
+ bytes: number;
114
+ }
115
+
116
+ /** The prompt pieces of one dumped request: body.system, body.messages, body.tools[] in dump order. */
117
+ export interface DumpParts {
118
+ system: number;
119
+ messages: number;
120
+ tools: DumpPart[];
121
+ }
122
+
123
+ export interface BloatBreakdown {
124
+ /** system, messages and every tool group, largest first. */
125
+ parts: DumpPart[];
126
+ /** The five largest individual tools, largest first. */
127
+ tools: DumpPart[];
128
+ }
129
+
130
+ /**
131
+ * Groups a dumped request's tools by the first capture of the group regex on the tool name (a
132
+ * name with no match — or a pattern with no capture, or an unparseable pattern, which disables
133
+ * grouping rather than guessing — lands in "builtin"), and returns the prompt parts sorted by
134
+ * bytes plus the five largest individual tools.
135
+ */
136
+ export function bloatBreakdown(parts: DumpParts, groupRegex: string): BloatBreakdown {
137
+ let rx: RegExp | null;
138
+ try {
139
+ rx = new RegExp(groupRegex);
140
+ } catch {
141
+ rx = null;
142
+ }
143
+ const groups = new Map<string, number>();
144
+ for (const t of parts.tools) {
145
+ const m = rx ? rx.exec(t.name) : null;
146
+ const group = m?.[1] ?? "builtin";
147
+ groups.set(group, (groups.get(group) ?? 0) + t.bytes);
148
+ }
149
+ const rows: DumpPart[] = [
150
+ { name: "system", bytes: parts.system },
151
+ { name: "messages", bytes: parts.messages },
152
+ ...[...groups].map(([name, bytes]) => ({ name, bytes })),
153
+ ];
154
+ rows.sort((a, b) => b.bytes - a.bytes);
155
+ const tools = [...parts.tools].sort((a, b) => b.bytes - a.bytes).slice(0, 5);
156
+ return { parts: rows, tools };
157
+ }
158
+
159
+ /** What a dumped failed request states about its own prompt, as the adapter reads it out. */
160
+ export interface DumpTokens {
161
+ /** The prompt token count the dump's error response states. */
162
+ tokens: number;
163
+ /** The context maximum the error response states, when it names one. */
164
+ limit?: number;
165
+ /** The model the request went out with. */
166
+ model?: string;
167
+ }
168
+
169
+ /**
170
+ * The dump-fed counterpart of the usage findings: a rejected request never produced a usage
171
+ * row, so its size exists only in the dump's error response (which is why the evidence names
172
+ * the dump, and why a count the dump does not state flags nothing — bytes are never turned
173
+ * into tokens by guessing). Flags when the stated prompt passes the first-call ceiling, or
174
+ * ratio_of_limit × the stated maximum (the provider's own number beats any config guess), or
175
+ * ratio_of_limit × the model's context_limits entry. Null when nothing crosses.
176
+ */
177
+ export function dumpFinding(runId: string, dump: DumpTokens, rules: BloatRules): Finding | null {
178
+ const over: string[] = [];
179
+ if (dump.tokens > rules.first_call_max) over.push(`over the ${rules.first_call_max} first-call ceiling`);
180
+ const stated = dump.limit;
181
+ const limit = stated ?? (dump.model !== undefined ? limitOf(dump.model, rules.context_limits) : undefined);
182
+ if (limit !== undefined && dump.tokens > rules.ratio_of_limit * limit) {
183
+ over.push(`${Math.round((dump.tokens / limit) * 100)}% of its ${limit} limit`);
184
+ }
185
+ if (over.length === 0) return null;
186
+ const out: Finding[] = [];
187
+ foldFinding(
188
+ out,
189
+ new Set(),
190
+ "prompt-bloat",
191
+ `run ${runId}: the request dumped inside this run's window was rejected with a ${dump.tokens} token prompt (${over.join(", ")})`,
192
+ `dumped request (model ${dump.model ?? "?"}) rejected: prompt ${dump.tokens}` +
193
+ (stated !== undefined ? ` > ${stated} maximum` : "") +
194
+ (limit !== undefined && stated === undefined ? `; limit ${limit} from traces.bloat.context_limits` : "") +
195
+ ", stated by the dump's error response",
196
+ `prompt-bloat:${runId}:dump`,
197
+ );
198
+ return out[0] ?? null;
199
+ }
@@ -0,0 +1,192 @@
1
+ // Brief quality (plan 20261024_0305 traces_06): what a spawn brief says, joined to how its run went.
2
+ // Plain data in, plain data out. The harness adapter (src/adapters/<harness>/) finds the spawns;
3
+ // every regex and threshold comes from `traces.briefs` and `traces.efficiency` in config.
4
+
5
+ import type { TraceSource } from "./adapter.ts";
6
+ import { briefBudget } from "./guards.ts";
7
+ import { type EfficiencyRules, runEfficiency } from "./trace-efficiency.ts";
8
+
9
+ export interface BriefRules {
10
+ verify_pattern: string;
11
+ phase_pattern: string;
12
+ plan_pattern: string;
13
+ }
14
+
15
+ export interface BriefJoinRules {
16
+ brief: BriefRules;
17
+ efficiency: EfficiencyRules;
18
+ }
19
+
20
+ export interface BriefFeatures {
21
+ /** Length of the brief text in characters. */
22
+ chars: number;
23
+ /** The brief names a `path:line` location. */
24
+ fileLines: boolean;
25
+ /** The brief names a verify command (`traces.briefs.verify_pattern`). */
26
+ verify: boolean;
27
+ /** The brief sets a `Call budget: <N>` line (guards.briefBudget). */
28
+ budget: boolean;
29
+ /** Non-empty lines under the brief's Acceptance headings, summed. */
30
+ acceptance: number;
31
+ /** The brief names a phase (`traces.briefs.phase_pattern`). */
32
+ phase: boolean;
33
+ /** The brief names a plan file (`traces.briefs.plan_pattern`). */
34
+ plan: boolean;
35
+ }
36
+
37
+ /** One spawned agent of a Main run and the brief it was spawned with. */
38
+ export interface SpawnBrief {
39
+ agent: string;
40
+ brief: string;
41
+ /** Unix seconds of the spawn call; null when the line carries no readable timestamp. */
42
+ ts: number | null;
43
+ }
44
+
45
+ export interface BriefRow {
46
+ agent: string;
47
+ ts: number | null;
48
+ features: BriefFeatures;
49
+ calls: number;
50
+ wasted: number;
51
+ /** null when the agent has no trace with calls: its waste is unknown, not zero. */
52
+ waste_pct: number | null;
53
+ accepted: boolean;
54
+ }
55
+
56
+ export interface BriefReportOpts {
57
+ min_n: number;
58
+ char_buckets: number[];
59
+ }
60
+
61
+ /** One side of a split: rows in the group, and the means that have at least min_n behind them. */
62
+ export interface SideStat {
63
+ /** Rows on this side. */
64
+ n: number;
65
+ /** Rows on this side with a known waste percentage. */
66
+ wasteN: number;
67
+ /** Mean waste fraction over wasteN rows; null when wasteN < min_n. */
68
+ waste: number | null;
69
+ /** Accepted fraction over n rows; null when n < min_n. */
70
+ accept: number | null;
71
+ }
72
+
73
+ export type BooleanFeature = "fileLines" | "verify" | "budget" | "phase" | "plan";
74
+
75
+ export interface FeatureReport {
76
+ feature: BooleanFeature;
77
+ with: SideStat;
78
+ without: SideStat;
79
+ }
80
+
81
+ export interface BucketReport {
82
+ label: string;
83
+ stat: SideStat;
84
+ }
85
+
86
+ export interface BriefReport {
87
+ features: FeatureReport[];
88
+ buckets: BucketReport[];
89
+ }
90
+
91
+ const BOOLEAN_FEATURES: BooleanFeature[] = ["fileLines", "verify", "budget", "phase", "plan"];
92
+ /** A `path.ext:line` location. */
93
+ const FILE_LINE = /[\w./-]+\.[A-Za-z]{1,8}:\d+/;
94
+ const ACCEPTANCE_HEADING = /^#{1,6}\s*acceptance\b/i;
95
+ const HEADING = /^#{1,6}\s/;
96
+ /** Trace-score event types that count as the agent's work being accepted. */
97
+ const ACCEPT_TYPES: Record<string, true> = { accept: true, validate: true, diagnose: true };
98
+
99
+ /** Non-empty lines under each Acceptance heading, up to the next markdown heading. */
100
+ function acceptanceLines(brief: string): number {
101
+ let inSection = false;
102
+ let count = 0;
103
+ for (const line of brief.split("\n")) {
104
+ if (ACCEPTANCE_HEADING.test(line)) {
105
+ inSection = true;
106
+ continue;
107
+ }
108
+ if (HEADING.test(line)) inSection = false;
109
+ else if (inSection && line.trim() !== "") count++;
110
+ }
111
+ return count;
112
+ }
113
+
114
+ export function briefFeatures(brief: string, rules: BriefRules): BriefFeatures {
115
+ return {
116
+ chars: brief.length,
117
+ fileLines: FILE_LINE.test(brief),
118
+ verify: new RegExp(rules.verify_pattern).test(brief),
119
+ budget: briefBudget(brief) !== null,
120
+ acceptance: acceptanceLines(brief),
121
+ phase: new RegExp(rules.phase_pattern).test(brief),
122
+ plan: new RegExp(rules.plan_pattern).test(brief),
123
+ };
124
+ }
125
+
126
+ /**
127
+ * One row per spawned agent. Waste comes from the agent's own trace (the run whose id is the
128
+ * agent name); accepted is true when any score event of an accept type names that agent.
129
+ */
130
+ export function briefRows(briefs: SpawnBrief[], traces: TraceSource, scores: Record<string, unknown>[], rules: BriefJoinRules): BriefRow[] {
131
+ const accepted = new Set<string>();
132
+ for (const e of scores) {
133
+ if (typeof e.type === "string" && ACCEPT_TYPES[e.type] === true && typeof e.agent === "string") accepted.add(e.agent);
134
+ }
135
+ return briefs.map((b) => {
136
+ const eff = runEfficiency(traces.events(b.agent), rules.efficiency);
137
+ return {
138
+ agent: b.agent,
139
+ ts: b.ts,
140
+ features: briefFeatures(b.brief, rules.brief),
141
+ calls: eff.calls,
142
+ wasted: eff.wasted,
143
+ waste_pct: eff.calls > 0 ? eff.wastePct : null,
144
+ accepted: accepted.has(b.agent),
145
+ };
146
+ });
147
+ }
148
+
149
+ function sideStat(rows: BriefRow[], minN: number): SideStat {
150
+ const wastes = rows.map((r) => r.waste_pct).filter((w): w is number => w !== null);
151
+ const accepted = rows.filter((r) => r.accepted).length;
152
+ return {
153
+ n: rows.length,
154
+ wasteN: wastes.length,
155
+ waste: wastes.length >= minN ? wastes.reduce((a, b) => a + b, 0) / wastes.length : null,
156
+ accept: rows.length >= minN ? accepted / rows.length : null,
157
+ };
158
+ }
159
+
160
+ /** Labels for the char buckets: `<e0`, `e0-(e1-1)`, ..., `>=eLast`; no edges means one bucket. */
161
+ function bucketLabels(edges: number[]): string[] {
162
+ if (edges.length === 0) return ["all"];
163
+ const labels = [`<${edges[0]}`];
164
+ edges.forEach((lo, i) => {
165
+ const hi = edges[i + 1];
166
+ labels.push(hi === undefined ? `>=${lo}` : `${lo}-${hi - 1}`);
167
+ });
168
+ return labels;
169
+ }
170
+
171
+ export function briefReport(rows: BriefRow[], opts: BriefReportOpts): BriefReport {
172
+ const features = BOOLEAN_FEATURES.map((feature) => ({
173
+ feature,
174
+ with: sideStat(
175
+ rows.filter((r) => r.features[feature]),
176
+ opts.min_n,
177
+ ),
178
+ without: sideStat(
179
+ rows.filter((r) => !r.features[feature]),
180
+ opts.min_n,
181
+ ),
182
+ }));
183
+ // Bucket index = number of edges at or below the row's char count (edges are ascending).
184
+ const buckets = bucketLabels(opts.char_buckets).map((label, i) => ({
185
+ label,
186
+ stat: sideStat(
187
+ rows.filter((r) => opts.char_buckets.filter((e) => r.features.chars >= e).length === i),
188
+ opts.min_n,
189
+ ),
190
+ }));
191
+ return { features, buckets };
192
+ }
@@ -18,7 +18,7 @@ import { maskEvidence } from "./trace-claims.ts";
18
18
  * same dishonesty in one run stay one finding (first sighting wins the evidence). Every rule
19
19
  * uses this, so masking and the evidence cap cannot be forgotten at a call site.
20
20
  */
21
- function fold(out: Finding[], seen: Set<string>, kind: string, summary: string, evidence: string, fingerprint: string): void {
21
+ export function foldFinding(out: Finding[], seen: Set<string>, kind: string, summary: string, evidence: string, fingerprint: string): void {
22
22
  if (seen.has(fingerprint)) return;
23
23
  seen.add(fingerprint);
24
24
  out.push({ kind, summary, evidence: maskEvidence(evidence), fingerprint });
@@ -45,7 +45,7 @@ export function modelSwaps(events: TraceEvent[]): Finding[] {
45
45
  if (e.kind === "modelChange") {
46
46
  announced = e;
47
47
  if (e.fallback) {
48
- fold(out, seen, "model-swap", `run ${e.runId}: the requested model was resolved to a fallback`,
48
+ foldFinding(out, seen, "model-swap", `run ${e.runId}: the requested model was resolved to a fallback`,
49
49
  `run ${e.runId}: model_change for ${e.model ?? "?"} says resolvedModelIsFallback`,
50
50
  `model-swap:${e.runId}:fallback`);
51
51
  }
@@ -56,12 +56,12 @@ export function modelSwaps(events: TraceEvent[]): Finding[] {
56
56
  const askedModel = slash === -1 ? announced.model : announced.model.slice(slash + 1);
57
57
  const askedProvider = slash === -1 ? undefined : announced.model.slice(0, slash);
58
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}`,
59
+ foldFinding(out, seen, "model-swap", `run ${e.runId}: asked for ${askedModel}, an assistant message says ${e.model}`,
60
60
  `run ${e.runId}: model_change says ${announced.model}, message says model ${e.model} (provider ${e.provider ?? "?"})`,
61
61
  `model-swap:${e.runId}:model:${askedModel}:${e.model}`);
62
62
  }
63
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}`,
64
+ foldFinding(out, seen, "model-swap", `run ${e.runId}: asked provider ${askedProvider}, an assistant message says ${e.provider}`,
65
65
  `run ${e.runId}: model_change says ${announced.model}, message says provider ${e.provider} (model ${e.model ?? "?"})`,
66
66
  `model-swap:${e.runId}:provider:${askedProvider}:${e.provider}`);
67
67
  }
@@ -96,7 +96,7 @@ export function oddResponseIds(events: TraceEvent[], idPatterns: Record<string,
96
96
  const rx = shapes.get(e.provider);
97
97
  if (!rx) continue;
98
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`,
99
+ foldFinding(out, seen, "odd-response-id", `run ${e.runId}: ${e.provider} answered with a responseId that misses its configured shape`,
100
100
  `${e.provider} responseId "${e.responseId}" must match ${pattern}`,
101
101
  `odd-response-id:${e.runId}:${e.provider}`);
102
102
  }
@@ -127,7 +127,7 @@ export function unofferedTools(events: TraceEvent[], allowTools: string[], offer
127
127
  for (const e of events) {
128
128
  if (e.kind !== "toolCall" || !e.tool || e.tool === "?") continue;
129
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`,
130
+ foldFinding(out, seen, "unoffered-tool", `run ${e.runId}: toolCall "${e.tool}" was never offered to the session`,
131
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
132
  `unoffered-tool:${e.runId}:${e.tool}`);
133
133
  }
@@ -148,7 +148,7 @@ export function phantomOutput(events: TraceEvent[]): Finding[] {
148
148
  if (e.kind !== "assistantText" || e.text !== "" || !e.usage) continue;
149
149
  if (!(e.usage.output > 0)) continue;
150
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`,
151
+ foldFinding(out, seen, "phantom-output", `run ${e.runId}: an assistant message billed ${e.usage.output} output tokens but wrote nothing`,
152
152
  `assistant message billed ${e.usage.output} output tokens with empty content (responseId ${e.responseId ?? "<absent>"})`,
153
153
  `phantom-output:${e.runId}:${id}`);
154
154
  }
@@ -177,7 +177,7 @@ export function costMismatch(events: TraceEvent[], prices: Record<string, Provid
177
177
  const off = expected > 0 ? Math.abs(billed - expected) / expected : Math.abs(billed);
178
178
  if (!(off > 0.2)) continue;
179
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}`,
180
+ foldFinding(out, seen, "cost-mismatch", `run ${e.runId}: ${e.model} billed $${billed} but the price table says $${Number(expected.toFixed(6))}${pct}`,
181
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
182
  `cost-mismatch:${e.runId}:${e.model}`);
183
183
  }
@@ -167,6 +167,7 @@ machine:
167
167
 
168
168
  quota:
169
169
  reset_tz: "Asia/Shanghai"
170
+ reset_pattern: 'reset at (\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2})?)\s*(Z|UTC|GMT|[+-]\d{2}:?\d{2}|[A-Z]{2,5}\b)?'
170
171
  label: "quota"
171
172
 
172
173
  notify:
@@ -213,6 +214,19 @@ traces:
213
214
  - localhost
214
215
  - 127.0.0.1
215
216
  - "::1"
217
+ bloat:
218
+ # Prompt-size rules (src/core/trace-bloat.ts). first_call_max: the largest first-call
219
+ # prompt (input + cacheRead + cacheWrite tokens) a healthy run may open with. Any call
220
+ # whose prompt passes ratio_of_limit × its model's context_limits entry is bloat too; a
221
+ # model without an entry is not limit-checked (the map is open: add your models).
222
+ first_call_max: 150000
223
+ ratio_of_limit: 0.8
224
+ context_limits: {}
225
+ # APIs whose usage aggregates multiple internal calls; these are not per-call sizes.
226
+ aggregate_apis: ["cursor-agent"]
227
+ # Bloat breakdown: the first capture of this regex on a tool name names its group
228
+ # (no match = "builtin"). The leading _? keeps underscore-prefixed MCP names grouped.
229
+ tool_group: '^_?mcp__([A-Za-z0-9]+)_'
216
230
  owned_repos: [] # product names another product's run may not read quietly; the intended list lives in docs/config.md
217
231
  actions:
218
232
  secret_globs: # a read matching any glob is a high finding; evidence is masked either way
@@ -236,3 +250,9 @@ traces:
236
250
  - "plan-guard:"
237
251
  - "main-guard:"
238
252
  poll_pattern: '^\s*(sleep\s+\d|ps\b|pgrep\b)' # shell commands that poll while nothing else runs
253
+ briefs: # brief-quality rules (src/core/trace-briefs.ts): what a spawn brief names, and the report's length buckets
254
+ verify_pattern: '\b(?:bun test|bun run typecheck|pytest|npm test|go test|cargo test)\b'
255
+ phase_pattern: '\bP\d+[a-z]?\b'
256
+ plan_pattern: 'docs/plans/\S+\.md'
257
+ char_buckets: [1500, 4000] # brief length edges: <1500, 1500-3999, >=4000
258
+ min_n: 5 # the report shows a mean only with at least this many rows on that side