@linxiraos/pi-stats 1.4.10 → 1.4.12

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.
Files changed (82) hide show
  1. package/CHANGELOG.md +12 -3
  2. package/THIRD-PARTY-NOTICES.txt +99 -0
  3. package/dist/client/index.css +1 -1
  4. package/dist/client/index.js +102 -99
  5. package/dist/types/client/api.d.ts +4 -1
  6. package/dist/types/client/app/nav.d.ts +1 -1
  7. package/dist/types/client/charts/Chart.d.ts +16 -8
  8. package/dist/types/client/charts/DotWhisker.d.ts +50 -0
  9. package/dist/types/client/charts/Sparkline.d.ts +1 -1
  10. package/dist/types/client/charts/Waterfall.d.ts +26 -0
  11. package/dist/types/client/charts/index.d.ts +2 -0
  12. package/dist/types/client/charts/types.d.ts +8 -2
  13. package/dist/types/client/i18n/messages/en.d.ts +2 -0
  14. package/dist/types/client/i18n/messages/nav.d.ts +2 -0
  15. package/dist/types/client/i18n/messages/zh-CN.d.ts +1 -1
  16. package/dist/types/client/routes/SpotlightRoute.d.ts +7 -0
  17. package/dist/types/client/routes/index.d.ts +1 -0
  18. package/dist/types/client/spotlight/Compounding.d.ts +8 -0
  19. package/dist/types/client/spotlight/Coverage.d.ts +6 -0
  20. package/dist/types/client/spotlight/Economics.d.ts +10 -0
  21. package/dist/types/client/spotlight/FetchBack.d.ts +9 -0
  22. package/dist/types/client/spotlight/Hero.d.ts +12 -0
  23. package/dist/types/client/spotlight/Overhead.d.ts +6 -0
  24. package/dist/types/client/spotlight/Ranking.d.ts +6 -0
  25. package/dist/types/client/spotlight/ResultsFeed.d.ts +6 -0
  26. package/dist/types/client/spotlight/Savings.d.ts +10 -0
  27. package/dist/types/client/spotlight/ShareTrend.d.ts +8 -0
  28. package/dist/types/client/spotlight/Steps.d.ts +6 -0
  29. package/dist/types/client/spotlight/TimeCost.d.ts +6 -0
  30. package/dist/types/client/spotlight/chips.d.ts +16 -0
  31. package/dist/types/client/spotlight/meta.d.ts +64 -0
  32. package/dist/types/db.d.ts +56 -2
  33. package/dist/types/index.d.ts +2 -1
  34. package/dist/types/parser.d.ts +4 -0
  35. package/dist/types/rollup.d.ts +37 -1
  36. package/dist/types/shared-types.d.ts +443 -0
  37. package/dist/types/spotlight-aggregator.d.ts +189 -0
  38. package/dist/types/spotlight-bootstrap.d.ts +32 -0
  39. package/dist/types/spotlight-ingest.d.ts +258 -0
  40. package/dist/types/spotlight-measures.d.ts +51 -0
  41. package/package.json +5 -5
  42. package/src/aggregator.ts +3 -1
  43. package/src/client/App.tsx +3 -0
  44. package/src/client/api.ts +21 -0
  45. package/src/client/app/nav.ts +4 -1
  46. package/src/client/charts/Chart.tsx +105 -22
  47. package/src/client/charts/DotWhisker.tsx +149 -0
  48. package/src/client/charts/Sparkline.tsx +3 -2
  49. package/src/client/charts/Waterfall.tsx +86 -0
  50. package/src/client/charts/index.ts +2 -0
  51. package/src/client/charts/types.ts +9 -2
  52. package/src/client/i18n/messages/nav.ts +2 -0
  53. package/src/client/react-css.d.ts +1 -1
  54. package/src/client/routes/SpotlightRoute.tsx +139 -0
  55. package/src/client/routes/index.ts +1 -0
  56. package/src/client/spotlight/Compounding.tsx +222 -0
  57. package/src/client/spotlight/Coverage.tsx +96 -0
  58. package/src/client/spotlight/Economics.tsx +167 -0
  59. package/src/client/spotlight/FetchBack.tsx +222 -0
  60. package/src/client/spotlight/Hero.tsx +177 -0
  61. package/src/client/spotlight/Overhead.tsx +135 -0
  62. package/src/client/spotlight/Ranking.tsx +248 -0
  63. package/src/client/spotlight/ResultsFeed.tsx +354 -0
  64. package/src/client/spotlight/Savings.tsx +355 -0
  65. package/src/client/spotlight/ShareTrend.tsx +103 -0
  66. package/src/client/spotlight/Steps.tsx +225 -0
  67. package/src/client/spotlight/TimeCost.tsx +64 -0
  68. package/src/client/spotlight/chips.tsx +63 -0
  69. package/src/client/spotlight/meta.ts +206 -0
  70. package/src/client/spotlight/spotlight.css +1387 -0
  71. package/src/client/styles.css +289 -1
  72. package/src/db.ts +538 -11
  73. package/src/index.ts +10 -1
  74. package/src/live.ts +21 -9
  75. package/src/parser.ts +36 -7
  76. package/src/rollup.ts +236 -10
  77. package/src/server.ts +42 -0
  78. package/src/shared-types.ts +479 -0
  79. package/src/spotlight-aggregator.ts +1738 -0
  80. package/src/spotlight-bootstrap.ts +110 -0
  81. package/src/spotlight-ingest.ts +981 -0
  82. package/src/spotlight-measures.ts +667 -0
@@ -0,0 +1,189 @@
1
+ /**
2
+ * The Spotlight dashboard: what tool-output shaping saved, measured four ways (see the doc comments of
3
+ * {@link SpotlightDashboardStats} and the types it references), from the tables `spotlight-ingest.ts` fills.
4
+ *
5
+ * Approximations, all named in the UI's captions:
6
+ * - token counts of results without a Spotlight trace are result characters / 4;
7
+ * - what pi would have shown unshaped (`plain`), on read/bash/eval traces written before pi recorded it, is the input
8
+ * scaled to pi's inline cap (see {@link estimatedPlainTokens});
9
+ * - a compaction is a request whose prompt (input + cache read + cache write) is under 60% of the previous one's;
10
+ * - a rerun is a bash command equal to, extending (pipe, redirect, `&&`), or ≥ 60% token-similar to a recent one;
11
+ * for any other tool but `read`, a call of the same tool whose argument tokens (`argumentTokens`) are ≥ 60%
12
+ * similar.
13
+ */
14
+ import type { Database } from "bun:sqlite";
15
+ import { type RangeWindow } from "./rollup.js";
16
+ import type { AgentType, SpotlightDashboardStats, SpotlightRecoveryKind, SpotlightAgentScope, SpotlightSessionContext, SpotlightSharePoint, SpotlightTool } from "./shared-types.js";
17
+ export interface SessionRow {
18
+ session_file: string;
19
+ folder: string;
20
+ marked_at: number;
21
+ cwd: string | null;
22
+ title: string | null;
23
+ }
24
+ export interface Result {
25
+ timestamp: number;
26
+ tool: string;
27
+ inTokens: number;
28
+ outTokens: number;
29
+ /** What `plain` would have shown: the trace's count, else {@link estimatedPlainTokens}. */
30
+ plainTokens: number;
31
+ plainEstimated: boolean;
32
+ /** plain − out of a cut or would-be cut (held out), negative when the cut was wider than plain; 0 if unchanged. */
33
+ savedTokens: number;
34
+ /** in − out of a cut or would-be cut: the saving against the full output. */
35
+ fullSavedTokens: number;
36
+ steps: string[];
37
+ /** Shaping changed it and the model saw the changed text (an applied cut). */
38
+ shortened: boolean;
39
+ /** Shaping would have shortened it, but it was held out: the model saw it unshaped. */
40
+ holdout: boolean;
41
+ /** The score-free coin skipped Spotlight: the no-score fallback rules shaped it. */
42
+ scoreFree: boolean;
43
+ /**
44
+ * A read pi's former edit gate (removed) kept whole: the model saw `plain`'s page, the counts describe the
45
+ * would-be cut. Only in transcripts journaled while the gate ran.
46
+ */
47
+ gated: boolean;
48
+ /**
49
+ * The cut (shown, or not applied because pi capped it at `plain`'s text) was wider than what `plain` would have
50
+ * shown.
51
+ */
52
+ widerThanPlain: boolean;
53
+ /** Some Spotlight call failed: the no-score fallback rules shaped it. */
54
+ failed: boolean;
55
+ /** Per-line heat (`0`–`9`, else unscored) and kept runs (1-based positions) of the original; see the trace. */
56
+ heat: string;
57
+ kept: [number, number][];
58
+ /** Original lines (1-based positions) later calls needed; null for results that collect none. */
59
+ needs: {
60
+ reread: [number, number][];
61
+ edit: [number, number][];
62
+ } | null;
63
+ path: string | null;
64
+ /** The original window (`details.spotlight.original`): first line and line count; 0 lines without one. */
65
+ start: number;
66
+ lines: number;
67
+ hidden: [number, number][];
68
+ hiddenLines: number;
69
+ spotlightCalls: number;
70
+ spotlightFailures: number;
71
+ spotlightMs: number;
72
+ spotlightUsd: number;
73
+ /** Wall time shaping took; null before its shape entry landed. */
74
+ shapeMs: number | null;
75
+ }
76
+ export interface Recovery {
77
+ kind: SpotlightRecoveryKind;
78
+ source: Call;
79
+ /** Tool calls between the source result and this call. */
80
+ after: number;
81
+ /** Every call of this call's request is a recovery. */
82
+ turn: boolean;
83
+ }
84
+ export interface Call {
85
+ id: string;
86
+ entryId: string;
87
+ timestamp: number;
88
+ seq: number;
89
+ tool: string;
90
+ target: string;
91
+ callsInTurn: number;
92
+ /** Tokens the result added to the context: the trace's `outTokens`, else result characters / 4. */
93
+ tokens: number;
94
+ artifacts: Set<number>;
95
+ result: Result | null;
96
+ recovery: Recovery | null;
97
+ /** Recoveries this call's result was the source of. */
98
+ recoveredBy: Call[];
99
+ /** Files the call edits, resolved against the session's working directory; empty for other calls. */
100
+ edits: string[];
101
+ /** The call's argument tokens (generic rerun rule); empty for `read`, `bash` and unrecorded calls. */
102
+ argTokens: Set<string>;
103
+ /** Calls from an evaluated result to the first call fetching more of it (the uniform rule); null for none. */
104
+ fetchBackGap: number | null;
105
+ /** Evaluated results this call is the first fetch-back of (the uniform rule). */
106
+ fetchesBack: Call[];
107
+ /** A held-out result's would-be recoveries: tokens of later calls that would have recovered the cut. */
108
+ baselineTokens: number;
109
+ /** A shortened result's saved tokens × the requests that carried them, and their price. */
110
+ savedCarry: number;
111
+ savedCarryUsd: number;
112
+ /** A recovery's tokens × the requests that carried them, and their price. */
113
+ recoveryCarry: number;
114
+ recoveryCarryUsd: number;
115
+ }
116
+ export interface Request {
117
+ entryId: string;
118
+ timestamp: number;
119
+ /** Model time of the request (ms). */
120
+ durationMs: number;
121
+ context: number;
122
+ costTotal: number;
123
+ compacted: boolean;
124
+ readRate: number;
125
+ writeRate: number;
126
+ }
127
+ export interface SessionAnalysis {
128
+ session: SessionRow;
129
+ cwd: string | null;
130
+ calls: Call[];
131
+ requests: Request[];
132
+ /** Request cost by assistant entry id (main-loop requests). */
133
+ costByEntry: Map<string, number>;
134
+ agentType: AgentType;
135
+ edits: EditLog;
136
+ }
137
+ /**
138
+ * What `plain` would have shown of a read/bash/eval result whose trace predates `plainTokens`: its input scaled to
139
+ * the inline cap ({@link PLAIN_CAP_BYTES}), in × min(1, cap / inChars). Null for any other tool: the generic path
140
+ * shapes the text `plain` shows, so its input is that text.
141
+ */
142
+ export declare function estimatedPlainTokens(tool: string, inTokens: number, inChars: number): number | null;
143
+ /** Whether bash command `next` repeats `previous`: equal, extended by a pipe/redirect/`&&`, or similar enough. */
144
+ export declare function isRerun(previous: string, next: string): boolean;
145
+ /** The session's file edits in call order: whether a file (or any file) changed between two calls. */
146
+ export declare class EditLog {
147
+ #private;
148
+ /** `calls` sorted by seq, their `edits` resolved. */
149
+ constructor(calls: readonly Call[]);
150
+ /** An edit strictly between calls `after` and `before`, of `file` (resolved) when given, else of any file. */
151
+ between(after: number, before: number, file?: string): boolean;
152
+ }
153
+ /** Raw per-bucket facts of one session over the range. */
154
+ interface SessionFacts {
155
+ /** bucket → [result chars, output tokens, user chars] */
156
+ buckets: Map<number, [number, number, number]>;
157
+ totalTokens: number;
158
+ promptTokens: number;
159
+ }
160
+ /** An experiment session as the share trend splits it: its activity from `markedAt` on is `shaped`. */
161
+ export interface ShareExperiment {
162
+ markedAt: number;
163
+ /** Prompt of its first request at or after the marker: the context shaping started from. */
164
+ firstPrompt: number;
165
+ /** Its facts from the marker (or the window start, if later) on. */
166
+ facts: SessionFacts;
167
+ }
168
+ /** Whether a transcript of `agentType` is in `scope`; advisors only count under `all`. */
169
+ export declare function inAgentScope(scope: SpotlightAgentScope, agentType: AgentType): boolean;
170
+ /**
171
+ * Strategy 4 over every transcript of `scope` in the window. Totals come from the rollups; experiment sessions are
172
+ * read raw (they are few) and subtracted to leave `outside`, so the cost does not grow with history. A transcript's
173
+ * activity before its marker stays `outside`.
174
+ */
175
+ export declare function computeShareSeries(database: Database, window: RangeWindow, experiments: ReadonlyMap<string, ShareExperiment>, scope?: SpotlightAgentScope, now?: number): SpotlightSharePoint[];
176
+ /** Build the dashboard payload for a window and agent scope; `now` pins the series end (tests). */
177
+ export declare function buildSpotlightDashboard(database: Database, window: RangeWindow, scope?: SpotlightAgentScope, now?: number): SpotlightDashboardStats;
178
+ /** An evaluated result in the range. */
179
+ export interface Evaluated {
180
+ call: Call;
181
+ result: Result;
182
+ analysis: SessionAnalysis;
183
+ tool: SpotlightTool;
184
+ }
185
+ /** `GET /api/stats/spotlight?range=&agent=`; an unknown `agent` measures every transcript. */
186
+ export declare function getSpotlightDashboardStats(range?: string | null, agent?: string | null): Promise<SpotlightDashboardStats>;
187
+ /** `GET /api/stats/spotlight/session?file=`; null when the file is not an experiment session. */
188
+ export declare function getSpotlightSessionContext(sessionFile: string): Promise<SpotlightSessionContext | null>;
189
+ export {};
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Seeded session-clustered bootstrap for the Spotlight dashboard's estimates: 1000 resamples (seeded per key, so
3
+ * every request returns the same interval), 5th and 95th percentiles, no interval under 3 sessions.
4
+ */
5
+ import type { SpotlightEstimate } from "./shared-types.js";
6
+ /** Fewest sessions an interval is drawn from. */
7
+ export declare const BOOTSTRAP_MIN_SESSIONS = 3;
8
+ /** Linear-interpolated quantile `p` of ascending `sorted` (non-empty). */
9
+ export declare function quantile(sorted: ArrayLike<number>, p: number): number;
10
+ /**
11
+ * The 90% interval of a statistic over seeded resamples: `resample` draws its own resample of the sessions with
12
+ * `random` (uniform in [0, 1)) and returns the statistic, or null when the resample cannot define it.
13
+ */
14
+ export declare function bootstrapInterval(key: string, resample: (random: () => number) => number | null): Pick<SpotlightEstimate, "lo" | "hi">;
15
+ /** 5th and 95th percentiles of bootstrap samples (sorted in place); null without any. */
16
+ export declare function percentileInterval(samples: number[] | Float64Array): Pick<SpotlightEstimate, "lo" | "hi">;
17
+ /**
18
+ * A joint bootstrap: one array of {@link BOOTSTRAP_RESAMPLES} seeded resample rounds that several statistics share.
19
+ * `round` draws one resample with `random` and stores each statistic of it at index `r` of that statistic's array
20
+ * (made by {@link jointSamples}); {@link percentileInterval} then turns every array into its interval. One pass
21
+ * replaces a {@link bootstrapInterval} per statistic.
22
+ */
23
+ export declare function bootstrapRounds(key: string, round: (random: () => number, r: number) => void): void;
24
+ /** One statistic's samples for {@link bootstrapRounds}. */
25
+ export declare function jointSamples(): Float64Array;
26
+ /**
27
+ * The means of seeded resamples of `values` (one per bootstrap round, in round order), so statistics of several
28
+ * groups can be combined round by round.
29
+ */
30
+ export declare function resampledMeans(values: readonly number[], key: string): Float64Array;
31
+ /** Ratio of sums over sessions (`[numerator, denominator]` per session) with its bootstrap interval. */
32
+ export declare function bootstrapRatio(pairs: readonly (readonly [number, number])[], key: string): SpotlightEstimate;
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Spotlight experiment facts the parser extracts from a session journal, for the Spotlight dashboard
3
+ * (`spotlight-aggregator.ts`).
4
+ *
5
+ * A session is an experiment session from its first Spotlight marker on (see {@link experimentMarker}); from then the
6
+ * parser records every evaluated result, every tool call (target, order, result size, the artifacts its result names)
7
+ * and every main-loop request, so recoveries of hidden output can be detected later. Evaluated results come from two
8
+ * entries that may land in different tail parses: the `spotlight:shape` journal entry (Spotlight's bill, timing) and
9
+ * the result message's `details.spotlight` (what the model saw, the hidden lines). Both upsert the same row.
10
+ *
11
+ * Each shaped read (applied, held out or score-free) also collects the original lines the agent needed later (see
12
+ * {@link SpotlightCollector}): its open reads ride in the parser state, so a later tail parse keeps collecting, and the
13
+ * lines land in `spotlight_needs`.
14
+ */
15
+ /**
16
+ * Whether a custom entry marks its session as a Spotlight experiment session: pi's `spotlight:session` entry, which
17
+ * every session with the experiment on writes. Journals from before the experiment became a toggle carry
18
+ * `spotlight:assignment` instead, naming the arm the session drew; only the arm that shipped shaped with the shipped
19
+ * algorithm, so sessions of any other arm (`native`, `plain`, …) are not experiment sessions.
20
+ */
21
+ export declare function experimentMarker(customType: unknown, data: Record<string, unknown>): boolean;
22
+ /** Longest stored call target. */
23
+ export declare const SPOTLIGHT_TARGET_CHARS = 500;
24
+ /** A shaped read still collecting the lines the agent needs later (see {@link SpotlightCollector}). */
25
+ export interface SpotlightOpenRead {
26
+ toolCallId: string;
27
+ /** The read file, resolved against the session's working directory. */
28
+ file: string;
29
+ /** First file line of the original and its line count. */
30
+ start: number;
31
+ lines: number;
32
+ /** `original.url`: the session artifact holding the original text. */
33
+ url: string | null;
34
+ }
35
+ /** Spotlight state a tail parse needs from earlier bytes of the same transcript. */
36
+ export interface SpotlightParserState {
37
+ /** A Spotlight marker was seen: results, calls and requests are recorded from here on. */
38
+ experiment: boolean;
39
+ /** Tool calls recorded so far (the next call's order). */
40
+ seq: number;
41
+ /** The session header's working directory, for resolving relative read paths. */
42
+ cwd: string | null;
43
+ /** Latest session title. */
44
+ title: string | null;
45
+ /** Shaped reads still collecting needed lines; absent in cursors persisted before them. */
46
+ open?: SpotlightOpenRead[];
47
+ }
48
+ export declare function emptySpotlightState(): SpotlightParserState;
49
+ /** `spotlight_sessions` row: the session's first Spotlight marker. */
50
+ export interface SpotlightSessionRow {
51
+ sessionFile: string;
52
+ folder: string;
53
+ markedAt: number;
54
+ cwd: string | null;
55
+ title: string | null;
56
+ }
57
+ /** `spotlight_results` row (upserted): one evaluated result, from its shape entry, its result details, or both. */
58
+ export interface SpotlightShapeRow {
59
+ sessionFile: string;
60
+ toolCallId: string;
61
+ timestamp: number;
62
+ tool: string;
63
+ inChars: number;
64
+ outChars: number;
65
+ inTokens: number;
66
+ outTokens: number;
67
+ /** What pi would have shown unshaped (`plain`) for the call; null on traces written before pi recorded it. */
68
+ plainChars: number | null;
69
+ plainTokens: number | null;
70
+ /**
71
+ * A cut wider than `plain` that pi did not apply (steps end with `plain-cap`): the would-be cut's tokens; the model
72
+ * got `plain`'s text (`outTokens`). Null otherwise.
73
+ */
74
+ cappedTokens: number | null;
75
+ /** The score-free coin skipped Spotlight: the no-score fallback rules shaped the result. */
76
+ scoreFree: boolean;
77
+ steps: string[];
78
+ /** The result message carried `details.spotlight`. */
79
+ hasDetails: boolean;
80
+ /**
81
+ * Held out at random: Spotlight would have shortened it, but the model saw it unshaped; the token counts and
82
+ * `original` describe the would-be cut.
83
+ */
84
+ holdout: boolean;
85
+ /**
86
+ * A read pi's former edit gate (removed) kept whole, in transcripts journaled while it ran: the model saw
87
+ * `plain`'s page; like a held-out result, the token counts and `original` describe the would-be cut.
88
+ */
89
+ gated: boolean;
90
+ /** `details.spotlight.original` (present only when shaping changed the text). */
91
+ original: SpotlightOriginalFacts | null;
92
+ /** Artifact ids the result names (its text's `artifact://N` plus `original.url`); null before the result lands. */
93
+ artifacts: number[] | null;
94
+ /** Spotlight's own usage, from the shape entry; null before it lands. */
95
+ spotlight: {
96
+ calls: number;
97
+ failures: number;
98
+ ms: number;
99
+ costUsd: number;
100
+ } | null;
101
+ /** Wall time shaping took, from the shape entry. */
102
+ shapeMs: number | null;
103
+ }
104
+ export interface SpotlightOriginalFacts {
105
+ url: string | null;
106
+ path: string | null;
107
+ /** First original line of the window (1-based file line for reads, else 1). */
108
+ start: number;
109
+ lines: number;
110
+ /** Hidden absolute line ranges, inclusive: the window minus the kept ranges. */
111
+ hidden: [number, number][];
112
+ hiddenLines: number;
113
+ /** Spotlight's per-line heat (`0`–`9`, `-` unscored) over the first lines; null when the trace has none. */
114
+ heat: string | null;
115
+ /** Kept runs, 1-based positions in the original (of a held-out result: what the cut would have kept). */
116
+ kept: [number, number][];
117
+ }
118
+ /**
119
+ * `spotlight_needs` row (merged on upsert): original lines (1-based positions in the original) a shaped read's later
120
+ * calls needed. Ranges of later parses are added to the stored ones; `open` is the latest.
121
+ */
122
+ export interface SpotlightNeedRow {
123
+ sessionFile: string;
124
+ toolCallId: string;
125
+ file: string;
126
+ /** Still collecting: no edit, whole-file read or later shaped read of the file yet. */
127
+ open: boolean;
128
+ /** Lines later `read` selections covered. */
129
+ reread: [number, number][];
130
+ /** Lines later `edit` Find blocks located in the original. */
131
+ edit: [number, number][];
132
+ }
133
+ /** `spotlight_calls` row: one tool call of an experiment session. */
134
+ export interface SpotlightCallRow {
135
+ sessionFile: string;
136
+ toolCallId: string;
137
+ entryId: string;
138
+ timestamp: number;
139
+ seq: number;
140
+ toolName: string;
141
+ callsInTurn: number;
142
+ target: string;
143
+ /** Files an `edit`/`write`/`ast_edit` call changes, as written (relative paths unresolved); null for other calls. */
144
+ edits: string[] | null;
145
+ /** {@link argumentTokens} of the call, for the generic rerun rule; null for `read` and `bash` (own rules). */
146
+ argTokens: string[] | null;
147
+ }
148
+ /** Result facts of a recorded call, applied as an update (the result can land in a later tail parse). */
149
+ export interface SpotlightCallResultLink {
150
+ sessionFile: string;
151
+ toolCallId: string;
152
+ resultChars: number;
153
+ artifacts: number[];
154
+ }
155
+ /** `spotlight_requests` row: a main-loop assistant message of an experiment session (side requests excluded). */
156
+ export interface SpotlightRequestRow {
157
+ sessionFile: string;
158
+ entryId: string;
159
+ timestamp: number;
160
+ }
161
+ /** Everything one parse extracted for the Spotlight tables. */
162
+ export interface SpotlightParseRows {
163
+ sessions: SpotlightSessionRow[];
164
+ /** Title changes of experiment sessions seen after their marker. */
165
+ titles: {
166
+ sessionFile: string;
167
+ title: string;
168
+ }[];
169
+ shapes: SpotlightShapeRow[];
170
+ calls: SpotlightCallRow[];
171
+ callResults: SpotlightCallResultLink[];
172
+ requests: SpotlightRequestRow[];
173
+ needs: SpotlightNeedRow[];
174
+ }
175
+ export declare function emptySpotlightRows(): SpotlightParseRows;
176
+ export declare function spotlightRowCount(rows: SpotlightParseRows): number;
177
+ /** Distinct `artifact://N` ids a text names, ascending. */
178
+ export declare function artifactIds(text: string): number[];
179
+ /**
180
+ * What a call asked for, as recovery detection compares it: a read's path with its selector, a bash command, a
181
+ * search pattern with its path, eval code. Clipped to {@link SPOTLIGHT_TARGET_CHARS}.
182
+ */
183
+ export declare function callTarget(toolName: string, args: unknown): string;
184
+ /**
185
+ * A call's arguments as a token set for the generic rerun rule (two calls of the same tool rerun when their sets'
186
+ * Jaccard similarity is high): every JSON leaf as `key=value`, the key being the nearest object key; strings split
187
+ * on whitespace except under path keys (`path`, `paths`, `file`, `cwd`, `url`, …), which stay whole; nulls dropped;
188
+ * the top-level intent note `i` left out. Distinct tokens in first-seen order, at most
189
+ * {@link ARGUMENT_TOKEN_LIMIT}, each clipped to {@link ARGUMENT_TOKEN_CHARS} chars.
190
+ */
191
+ export declare function argumentTokens(args: unknown): string[];
192
+ /**
193
+ * Files a call changes: an `edit`'s patch headers (or its `path`), a `write`'s `path`, an `ast_edit`'s `paths`
194
+ * (globs kept as written), also when `ast_edit` runs through `write xd://ast_edit`. Null when the call is no file
195
+ * edit (other tools, or a write to an internal URL such as `proc://…/kill`).
196
+ */
197
+ export declare function editedPaths(toolName: string, args: unknown): string[] | null;
198
+ /** A read target split into its path and selected lines. */
199
+ export interface ReadSelection {
200
+ path: string;
201
+ /** Selected inclusive line ranges; empty with `tail` null means the whole file. */
202
+ ranges: [number, number][];
203
+ /** `:-N`: the last N lines. */
204
+ tail: number | null;
205
+ }
206
+ /** Split a read path into the path and its selector (`file.ts:10-40`, `:50+20`, `:-30`, `:5-9,20`, `:raw`). */
207
+ export declare function parseReadSelection(target: string): ReadSelection;
208
+ /** A read selection's lines; null for the whole file. */
209
+ export declare function selectedLines(selection: ReadSelection): [number, number][] | null;
210
+ /** A path as written, resolved against the session's working directory (URLs and absolute paths kept). */
211
+ export declare function resolveReadPath(target: string, cwd: string | null): string;
212
+ /** One `*** Find` block of an `edit` input and the file its section edits (null: the call's `path`). */
213
+ export interface EditFindBlock {
214
+ file: string | null;
215
+ /** `*** Edit File: PATH all`: every occurrence is replaced. */
216
+ all: boolean;
217
+ lines: string[];
218
+ }
219
+ /** The `*** Find` blocks of an `edit` call's input, with the file each one's section edits. */
220
+ export declare function editFindBlocks(input: string): EditFindBlock[];
221
+ /**
222
+ * Where a Find block's text lies in `original` (lines): every match as 1-based inclusive `[first, last]` positions.
223
+ * A Find line ending in `…` (or a lone `…` line) may skip original lines before the next Find line matches; blank
224
+ * lines around the block are ignored.
225
+ */
226
+ export declare function locateFind(original: readonly string[], find: readonly string[]): [number, number][];
227
+ /** Union of inclusive ranges, sorted and merged (touching ranges join). */
228
+ export declare function mergeRanges(ranges: readonly (readonly [number, number])[]): [number, number][];
229
+ /** Hidden absolute ranges of a window `[start, start + lines - 1]` whose kept ranges are 1-based within it. */
230
+ export declare function hiddenRanges(start: number, lines: number, kept: readonly [number, number][]): [number, number][];
231
+ /** The row a `spotlight:shape` entry's data describes, or null when it names no call. */
232
+ export declare function shapeFromEntry(sessionFile: string, data: Record<string, unknown>, timestamp: number): SpotlightShapeRow | null;
233
+ /** The row a result message's `details.spotlight` describes, or null when it carries none. */
234
+ export declare function shapeFromDetails(sessionFile: string, toolCallId: string, details: unknown, text: string, timestamp: number): SpotlightShapeRow | null;
235
+ /**
236
+ * Reduces one transcript's entries to {@link SpotlightParseRows}, carrying {@link SpotlightParserState} across tail
237
+ * parses. With `record` false it only advances the state (a prefix scan that rebuilds the state of a cursor without
238
+ * one).
239
+ *
240
+ * Needed lines: once a shaped read's result lands (applied, held out or score-free: any read with
241
+ * `details.spotlight.original`), later calls of the session, all from later requests, add to its needs: a `read` of the
242
+ * same file with a line selection adds the selected lines; an `edit` of it adds the lines its `*** Find` blocks
243
+ * locate in the original (read from the session's artifact directory in {@link finish}). Collecting stops at the
244
+ * file's first edit (after recording its lines; any edit tool), a later whole-file read, or a later shaped read of
245
+ * the file (after recording its selection), which starts collecting for itself.
246
+ */
247
+ export declare class SpotlightCollector {
248
+ #private;
249
+ readonly rows: SpotlightParseRows;
250
+ readonly state: SpotlightParserState;
251
+ constructor(sessionFile: string, folder: string, state: SpotlightParserState, record?: boolean);
252
+ /**
253
+ * Locate the parse's edit Find blocks in their reads' originals (artifact files) and add the lines to the needs;
254
+ * an original that cannot be read adds none.
255
+ */
256
+ finish(): Promise<void>;
257
+ visit(entry: unknown): void;
258
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The Spotlight dashboard's round-2 measures over the analyzed sessions of `spotlight-aggregator.ts`: the
3
+ * holdout-adjusted net, ranking quality against the lines the agent needed later, step × size economics, time cost
4
+ * and tool-output coverage. Metric definitions live on the types in `shared-types.ts`.
5
+ */
6
+ import type { Database } from "bun:sqlite";
7
+ import type { SpotlightAdjusted, SpotlightCompounding, SpotlightCoverageRow, SpotlightRanking, SpotlightStepCell, SpotlightTimeCost, SpotlightTool } from "./shared-types.js";
8
+ import type { Evaluated, SessionAnalysis } from "./spotlight-aggregator.js";
9
+ /** One experiment session's share of the range's savings and costs, for the adjusted net's joint bootstrap. */
10
+ export interface SessionMoney {
11
+ sessionFile: string;
12
+ savedTokens: number;
13
+ savedUsd: number;
14
+ /** Recovery tokens carried and priced plus extra-turn cost (its share of compounding.recoveryUsd). */
15
+ recoveryUsd: number;
16
+ spotlightUsd: number;
17
+ }
18
+ /**
19
+ * Per-cut holdout baselines of the range's evaluated results (see {@link baselinePerCut}): what a cut of `tool`
20
+ * gets fetched back anyway.
21
+ */
22
+ export declare function holdoutBaselines(evaluated: readonly Evaluated[]): (tool: SpotlightTool) => number;
23
+ export declare function emptyAdjusted(): SpotlightAdjusted;
24
+ /**
25
+ * Holdout-adjusted net savings: each tool's applied cuts (scored and score-free) recover tokens; held-out would-be
26
+ * cuts of the same tool show how many the agent fetches back anyway. Intervals resample experiment sessions
27
+ * jointly. `byTool` lists `tools` in their order.
28
+ */
29
+ export declare function computeAdjusted(evaluated: readonly Evaluated[], money: readonly SessionMoney[], grossSavedTokens: number, compounding: SpotlightCompounding, tools: readonly SpotlightTool[]): SpotlightAdjusted;
30
+ export declare function emptyRanking(): SpotlightRanking;
31
+ /**
32
+ * Ranking quality per group over shaped reads with needed lines (see {@link SpotlightRankingCell}), mean heat by
33
+ * line position over every scored cut or would-be cut, and how the needs were observed.
34
+ */
35
+ export declare function computeRanking(evaluated: readonly Evaluated[]): SpotlightRanking;
36
+ /**
37
+ * What each step combination earns per tool and saved-token bin over the range's cuts; combinations with
38
+ * under {@link MIN_STEP_CUTS} cuts of a tool fold into `other`. The excess subtracts each cut's holdout baseline
39
+ * ({@link holdoutBaselines}). Cells follow `tools`' order, then the most common combination first.
40
+ */
41
+ export declare function computeSteps(evaluated: readonly Evaluated[], baselineOf: (tool: SpotlightTool) => number, tools: readonly SpotlightTool[]): SpotlightStepCell[];
42
+ /**
43
+ * Agent time of the experiment sessions in the range: the model time of their requests, of the requests that did
44
+ * nothing but fetch back cut output, and the time tool calls spent shaping.
45
+ */
46
+ export declare function computeTimeCost(active: readonly SessionAnalysis[], cutoff: number): SpotlightTimeCost;
47
+ /**
48
+ * Each tool's share of the tool output experiment sessions' models saw from their marker (and the range) on;
49
+ * `shaped` marks the tools with evaluated results in the range.
50
+ */
51
+ export declare function computeCoverage(database: Database, active: readonly SessionAnalysis[], cutoff: number, shaped: ReadonlySet<SpotlightTool>): SpotlightCoverageRow[];
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@linxiraos/pi-stats",
4
- "version": "1.4.10",
4
+ "version": "1.4.12",
5
5
  "description": "Local observability dashboard for omp AI usage statistics",
6
6
  "homepage": "https://linxira-os.github.io/zeta/",
7
7
  "author": "Linxira-OS",
@@ -33,15 +33,15 @@
33
33
  "build": "bun run build.ts",
34
34
  "dev": "bun run src/index.ts",
35
35
  "check": "oxlint . && oxfmt --check --no-error-on-unmatched-pattern 'src/**/*.{ts,tsx}' '{test,bench,examples,scripts}/**/*.ts' '*.ts' && bun run check:types",
36
- "check:types": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.client.json --noEmit",
36
+ "check:types": "bun check --no-script -p tsconfig.json && bun check --no-script -p tsconfig.client.json",
37
37
  "lint": "oxlint .",
38
38
  "fix": "oxlint --fix --fix-suggestions . && bun run fmt",
39
39
  "fmt": "oxfmt --no-error-on-unmatched-pattern 'src/**/*.{ts,tsx}' '{test,bench,examples,scripts}/**/*.ts' '*.ts'"
40
40
  },
41
41
  "dependencies": {
42
- "@linxiraos/pi-ai": "1.4.10",
43
- "@linxiraos/pi-catalog": "1.4.10",
44
- "@linxiraos/pi-utils": "1.4.10",
42
+ "@linxiraos/pi-ai": "1.4.12",
43
+ "@linxiraos/pi-catalog": "1.4.12",
44
+ "@linxiraos/pi-utils": "1.4.12",
45
45
  "lucide-react": "^1.24.0",
46
46
  "react": "19.2.7",
47
47
  "react-dom": "19.2.7"
package/src/aggregator.ts CHANGED
@@ -41,6 +41,7 @@ import {
41
41
  getToolTimeSeries,
42
42
  type RangeWindow,
43
43
  } from "./rollup";
44
+ import { spotlightRowCount } from "./spotlight-ingest";
44
45
  import type { SyncWorkerRequest, SyncWorkerResponse } from "./sync-worker";
45
46
  // Coding-agent binary/bundle workers route through the CLI entrypoint with a
46
47
  // hidden argv mode, so the compiled binary and npm bundle only need one
@@ -427,7 +428,8 @@ async function syncAllSessionsLocked(
427
428
  result.assistantTexts.length +
428
429
  result.userLinks.length +
429
430
  result.toolCalls.length +
430
- result.toolResults.length;
431
+ result.toolResults.length +
432
+ spotlightRowCount(result.spotlight);
431
433
  if (pending.length >= SYNC_BATCH_FILES || pendingRows >= SYNC_BATCH_ROWS) flush();
432
434
  };
433
435
 
@@ -14,6 +14,7 @@ import {
14
14
  ProjectsRoute,
15
15
  ProvidersRoute,
16
16
  RequestsRoute,
17
+ SpotlightRoute,
17
18
  ToolsRoute,
18
19
  TracesRoute,
19
20
  } from "./routes";
@@ -66,6 +67,8 @@ function Dashboard() {
66
67
  return <ProjectsRoute active={active} range={range} />;
67
68
  case "gain":
68
69
  return <GainRoute active={active} range={range} />;
70
+ case "spotlight":
71
+ return <SpotlightRoute active={active} range={range} />;
69
72
  }
70
73
  };
71
74
 
package/src/client/api.ts CHANGED
@@ -14,6 +14,9 @@ import type {
14
14
  RequestDetails,
15
15
  SessionSummary,
16
16
  SessionTrace,
17
+ SpotlightAgentScope,
18
+ SpotlightDashboardStats,
19
+ SpotlightSessionContext,
17
20
  TimeRange,
18
21
  ToolDashboardStats,
19
22
  } from "./types";
@@ -184,6 +187,24 @@ export async function getGainDashboardStats(
184
187
  return fetchJson<GainDashboardStats>(`${API_BASE}/stats/gain?${params}`, { signal });
185
188
  }
186
189
 
190
+ export async function getSpotlightDashboardStats(
191
+ range: TimeRange = "24h",
192
+ agent: SpotlightAgentScope = "all",
193
+ signal?: AbortSignal,
194
+ ): Promise<SpotlightDashboardStats> {
195
+ return fetchJson<SpotlightDashboardStats>(
196
+ `${API_BASE}/stats/spotlight?range=${encodeURIComponent(range)}&agent=${encodeURIComponent(agent)}`,
197
+ { signal },
198
+ );
199
+ }
200
+
201
+ /** One experiment session's context per request, with and without shaping. */
202
+ export async function getSpotlightSessionContext(file: string, signal?: AbortSignal): Promise<SpotlightSessionContext> {
203
+ return fetchJson<SpotlightSessionContext>(`${API_BASE}/stats/spotlight/session?file=${encodeURIComponent(file)}`, {
204
+ signal,
205
+ });
206
+ }
207
+
187
208
  export async function getToolDashboardStats(
188
209
  range: TimeRange = "24h",
189
210
  signal?: AbortSignal,
@@ -8,6 +8,7 @@ import {
8
8
  LayoutGrid,
9
9
  type LucideIcon,
10
10
  PlugZap,
11
+ ScanSearch,
11
12
  Sparkles,
12
13
  SquareChartGantt,
13
14
  Wrench,
@@ -25,7 +26,8 @@ export type DashboardSection =
25
26
  | "tools"
26
27
  | "frustration"
27
28
  | "projects"
28
- | "gain";
29
+ | "gain"
30
+ | "spotlight";
29
31
 
30
32
  export interface NavItem {
31
33
  id: DashboardSection;
@@ -68,6 +70,7 @@ export const NAV: readonly NavGroup[] = [
68
70
  { id: "frustration", labelKey: "nav.frustration", icon: Frown, hotkey: "f" },
69
71
  { id: "projects", labelKey: "nav.projects", icon: FolderGit2, hotkey: "j" },
70
72
  { id: "gain", labelKey: "nav.gain", icon: Sparkles, hotkey: "g" },
73
+ { id: "spotlight", labelKey: "nav.spotlight", icon: ScanSearch, hotkey: "s" },
71
74
  ],
72
75
  },
73
76
  ];