@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
@@ -1,6 +1,7 @@
1
1
  import { Database } from "bun:sqlite";
2
2
  import { type ParseSessionResult, type SessionParserState } from "./parser.js";
3
- import type { AssistantTextStats, DailyActivityPoint, FrustrationCounts, MessageStats, MessageStatsInput, ModelSideCounts, ModelSideTimeSeriesPoint, ToolCallStats, ToolResultLink, UserMessageLink, UserMessageStats } from "./types.js";
3
+ import { type SpotlightCallResultLink, type SpotlightCallRow, type SpotlightNeedRow, type SpotlightRequestRow, type SpotlightSessionRow, type SpotlightShapeRow } from "./spotlight-ingest.js";
4
+ import type { AssistantTextStats, DailyActivityPoint, FrustrationCounts, MessageStats, MessageStatsInput, ModelDailyActivityPoint, ModelHourlyActivityPoint, ModelSideCounts, ModelSideTimeSeriesPoint, ToolCallStats, ToolResultLink, UserMessageLink, UserMessageStats } from "./types.js";
4
5
  /**
5
6
  * Predicate counting one stored request as "unpriced" — the public rate card
6
7
  * has no charge for it, so its zero is unknown spend rather than free usage.
@@ -104,7 +105,35 @@ export declare function getMessageById(id: number): MessageStats | null;
104
105
  * {@link getProviderHourlyBurn}. Reads the hourly rollup, falling back to the
105
106
  * raw rows while its rebuild backlog is too large for exact reads.
106
107
  */
107
- export declare function getDailyActivity(days?: number): Promise<DailyActivityPoint[]>;
108
+ export declare function getDailyActivity(days?: number, now?: number): Promise<DailyActivityPoint[]>;
109
+ /**
110
+ * Lookback for the Studio home usage card. It renders a calendar-year heatmap
111
+ * plus a year-to-date model legend, so the window has to reach back past
112
+ * January 1st even in late December (the TUI heatmap reads 371 days for the
113
+ * same reason; 400 keeps a month of slack).
114
+ */
115
+ export declare const USAGE_HISTORY_DAYS = 400;
116
+ /** Everything the Studio home usage card reads from the stats DB. */
117
+ export interface UsageHistory {
118
+ /** Per-day totals for the last {@link USAGE_HISTORY_DAYS} days, oldest first. */
119
+ days: DailyActivityPoint[];
120
+ /** Per-day per-model totals over the same window, oldest day first. */
121
+ byModelDay: ModelDailyActivityPoint[];
122
+ /** Per-model totals for each local hour of `now`'s day. */
123
+ todayByHour: ModelHourlyActivityPoint[];
124
+ }
125
+ /**
126
+ * Read the Studio home card's usage history in one call: the daily totals the
127
+ * TUI heatmap already uses, the same window split per model, and today's
128
+ * per-model hourly series. One `initDb` per call; every read goes through the
129
+ * rollup union, so no session transcript is re-parsed here.
130
+ *
131
+ * "Today" starts on the stats database's own local calendar, not the JS clock:
132
+ * the hour buckets come from SQLite's `localtime`, and the two clocks can
133
+ * disagree (a process launched under a `TZ` the C library ignores — Bun's test
134
+ * runner is one), which would slide the strip off the day it summarizes.
135
+ */
136
+ export declare function getUsageHistory(now?: number, days?: number): Promise<UsageHistory>;
108
137
  /**
109
138
  * Settle every full-session backfill after a successful sync pass.
110
139
  */
@@ -221,3 +250,28 @@ export declare function insertToolCalls(calls: Iterable<ToolCallStats>): number;
221
250
  * never match.
222
251
  */
223
252
  export declare function updateToolResults(links: Iterable<ToolResultLink>): number;
253
+ /** Record each experiment session's first Spotlight marker; a later one (a resumed session) never replaces it. */
254
+ export declare function insertSpotlightSessions(rows: Iterable<SpotlightSessionRow>): number;
255
+ export declare function updateSpotlightTitles(rows: Iterable<{
256
+ sessionFile: string;
257
+ title: string;
258
+ }>): number;
259
+ /**
260
+ * Upsert evaluated results. The shape entry and the result message can land in
261
+ * different tail parses: the shape entry brings Spotlight's usage and timing,
262
+ * the result's details the hidden lines and named artifacts, and either may
263
+ * come first. Fork copies of a call (same tool call id under another
264
+ * transcript) are skipped, first writer wins.
265
+ */
266
+ export declare function upsertSpotlightShapes(rows: Iterable<SpotlightShapeRow>): number;
267
+ /**
268
+ * Merge needed lines of shaped reads: ranges add to the stored ones (a tail parse brings only its own calls'),
269
+ * `open` takes the latest. A fork's copy of another transcript's read is skipped, first writer wins.
270
+ */
271
+ export declare function upsertSpotlightNeeds(rows: Iterable<SpotlightNeedRow>): number;
272
+ /** Insert experiment-session tool calls; fork copies are skipped as for `tool_calls`. */
273
+ export declare function insertSpotlightCalls(rows: Iterable<SpotlightCallRow>): number;
274
+ /** Attach result size and named artifacts to recorded calls (results can land in a later tail parse). */
275
+ export declare function updateSpotlightCallResults(links: Iterable<SpotlightCallResultLink>): number;
276
+ /** Insert experiment-session main-loop requests; fork copies are skipped as for `messages`. */
277
+ export declare function insertSpotlightRequests(rows: Iterable<SpotlightRequestRow>): number;
@@ -5,7 +5,8 @@ export { refreshRollups } from "./rollup.js";
5
5
  export type { StatsJudge, StatsJudgeProvider } from "./frustration.js";
6
6
  export { getGainDashboardStats } from "./gain-aggregator.js";
7
7
  export { formatStatsDashboardUrl, type StartServerOptions, setStatsCloseHandler, startServer } from "./server.js";
8
- export type { GainDashboardStats, GainSource, GainSourceTotals, GainTimeSeriesPoint } from "./shared-types.js";
8
+ export type { GainDashboardStats, GainSource, GainSourceTotals, GainTimeSeriesPoint, SpotlightAgentScope, SpotlightDashboardStats, SpotlightSessionContext, } from "./shared-types.js";
9
+ export { getSpotlightDashboardStats, getSpotlightSessionContext } from "./spotlight-aggregator.js";
9
10
  export type { AggregatedStats, DashboardStats, FolderStats, MessageStats, ModelPerformancePoint, ModelStats, ModelTimeSeriesPoint, TimeSeriesPoint, ToolDashboardStats, ToolModelStats, ToolTimeSeriesPoint, ToolUsageStats, } from "./types.js";
10
11
  /**
11
12
  * Print the dashboard summary to the console. Shared by `zetacode stats --summary`
@@ -1,6 +1,7 @@
1
1
  import type * as nodeFs from "node:fs";
2
2
  import { type ServiceTierByFamily } from "@linxiraos/pi-ai";
3
3
  import type { AgentType, AssistantTextStats, MessageStatsInput, SessionEntry, ToolCallStats, ToolResultLink, UserMessageLink, UserMessageStats } from "./types.js";
4
+ import { type SpotlightParseRows, type SpotlightParserState } from "./spotlight-ingest.js";
4
5
  /**
5
6
  * Classify which agent produced a transcript from its path within the sessions
6
7
  * directory. Layout: `<sessionsDir>/<project>/<file>.jsonl` is the `main`
@@ -56,6 +57,8 @@ export interface SessionParserState {
56
57
  mtimeMs: number;
57
58
  checkpoint: string;
58
59
  serviceTier: ServiceTierByFamily | null;
60
+ /** Absent in cursors persisted before the Spotlight tables; such a tail parse starts from an empty state. */
61
+ spotlight?: SpotlightParserState;
59
62
  }
60
63
  export interface ParseSessionResult {
61
64
  stats: MessageStatsInput[];
@@ -64,6 +67,7 @@ export interface ParseSessionResult {
64
67
  userLinks: UserMessageLink[];
65
68
  toolCalls: ToolCallStats[];
66
69
  toolResults: ToolResultLink[];
70
+ spotlight: SpotlightParseRows;
67
71
  newOffset: number;
68
72
  parserState?: SessionParserState;
69
73
  reset?: boolean;
@@ -25,7 +25,7 @@
25
25
  * (an hour of data is small and indexed by timestamp).
26
26
  */
27
27
  import type { Database } from "bun:sqlite";
28
- import type { AgentTypeStats, AggregatedStats, CostTimeSeriesPoint, DailyActivityPoint, FolderStats, ModelPerformancePoint, ModelStats, ModelTimeSeriesPoint, ProviderAggregate, ProviderHourlyPoint, ProviderTimeSeriesPoint, TimeSeriesPoint, ToolModelStats, ToolTimeSeriesPoint, ToolUsageStats } from "./types.js";
28
+ import type { AgentType, AgentTypeStats, AggregatedStats, CostTimeSeriesPoint, DailyActivityPoint, FolderStats, ModelDailyActivityPoint, ModelHourlyActivityPoint, ModelPerformancePoint, ModelStats, ModelTimeSeriesPoint, ProviderAggregate, ProviderHourlyPoint, ProviderTimeSeriesPoint, TimeSeriesPoint, ToolModelStats, ToolTimeSeriesPoint, ToolUsageStats } from "./types.js";
29
29
  /**
30
30
  * Create (or rebuild after a version bump) the rollup tables and the triggers
31
31
  * that mark hours dirty. Called from `initDb` after the raw tables exist.
@@ -95,6 +95,21 @@ export declare function getProviderHourlyBurn(cutoff?: number | null): ProviderH
95
95
  * aggregate the raw rows instead.
96
96
  */
97
97
  export declare function getDailyActivityFromRollup(cutoff: number): DailyActivityPoint[] | null;
98
+ /**
99
+ * Per-model token totals per local day since `cutoff`, oldest day first. Same
100
+ * exactness rules as every range read (clean rollup hours plus raw rows for the
101
+ * partial hour and dirty hours), so a live ingest shows up before its hour is
102
+ * re-rolled. Hourly buckets are attributed by their start, so a half-hour UTC
103
+ * offset can move up to 30 minutes of burn onto the neighbouring day — the same
104
+ * caveat {@link getProviderHourlyBurn} documents for local hours.
105
+ */
106
+ export declare function getModelDailyActivity(cutoff?: number | null): ModelDailyActivityPoint[];
107
+ /**
108
+ * Per-model token totals per local hour of day (`0`–`23`) since `cutoff`. Used
109
+ * with today's local midnight so the result is today's hourly series. Same
110
+ * attribution caveat as {@link getProviderHourlyBurn}.
111
+ */
112
+ export declare function getModelHourlyActivity(cutoff?: number | null): ModelHourlyActivityPoint[];
98
113
  /** Tokens/cost per bucket per provider. */
99
114
  export declare function getProviderTimeSeries({ cutoff, bucketMs }: RangeWindow): ProviderTimeSeriesPoint[];
100
115
  /** Per-transcript-file rollup for the Traces session list. */
@@ -121,3 +136,24 @@ export declare function getToolStats(cutoff?: number | null): ToolUsageStats[];
121
136
  export declare function getToolStatsByModel(cutoff?: number | null): ToolModelStats[];
122
137
  /** Calls and errors per bucket per tool. */
123
138
  export declare function getToolTimeSeries({ cutoff, bucketMs }: RangeWindow): ToolTimeSeriesPoint[];
139
+ /** Per-bucket context facts of every transcript of one agent type: tool-result characters and output tokens. */
140
+ export interface ContextFactPoint {
141
+ bucket: number;
142
+ agentType: AgentType;
143
+ resultChars: number;
144
+ outputTokens: number;
145
+ }
146
+ /** {@link ContextFactPoint}s over a window, from the rollups (exact while few hours are dirty). */
147
+ export declare function getContextFactSeries(database: Database, { cutoff, bucketMs }: RangeWindow): ContextFactPoint[];
148
+ /** A transcript's request span and its first request's prompt (input + cache read + cache write). */
149
+ export interface SessionSpan {
150
+ sessionFile: string;
151
+ startedAt: number;
152
+ endedAt: number;
153
+ firstPrompt: number;
154
+ }
155
+ /**
156
+ * Spans of the transcripts with a request at or after `endedAfter` (all when null), from `session_rollup` with
157
+ * the same exactness rule as {@link getSessionRollups}.
158
+ */
159
+ export declare function getSessionSpans(database: Database, endedAfter: number | null): SessionSpan[];
@@ -141,6 +141,30 @@ export interface DailyActivityPoint {
141
141
  /** Total tokens (input + output + cache) for the day. */
142
142
  totalTokens: number;
143
143
  }
144
+ /**
145
+ * One local calendar day of token usage for one model, for the Studio home
146
+ * card's per-model heatmap. Days with no usage are absent, not zeroed.
147
+ */
148
+ export interface ModelDailyActivityPoint {
149
+ /** Local calendar date, `YYYY-MM-DD`. */
150
+ day: string;
151
+ /** Model id as recorded on the assistant turn. */
152
+ model: string;
153
+ /** Total tokens (input + output + cache) for the day. */
154
+ totalTokens: number;
155
+ }
156
+ /**
157
+ * Per-model token usage for one local hour of the day, for the Studio home
158
+ * card's "today" view.
159
+ */
160
+ export interface ModelHourlyActivityPoint {
161
+ /** Local hour of day, `0`–`23`. */
162
+ hour: number;
163
+ /** Model id as recorded on the assistant turn. */
164
+ model: string;
165
+ /** Total tokens (input + output + cache) for the hour. */
166
+ totalTokens: number;
167
+ }
144
168
  /**
145
169
  * Overall dashboard stats.
146
170
  */
@@ -395,6 +419,425 @@ export interface GainDashboardStats {
395
419
  /** All distinct projects seen in the data, for the selector. */
396
420
  projects: string[];
397
421
  }
422
+ /**
423
+ * A tool the Spotlight experiment shaped, by the name it was called with (`read`, `grep`, an MCP tool's name, …).
424
+ * Every tool's results are shaped (`spotlight.experiment.tools`, default all); read, bash and eval have their own
425
+ * paths in pi, every other tool goes through the generic one.
426
+ */
427
+ export type SpotlightTool = string;
428
+ /** One tool's totals, for lists ordered by the tool's saving. */
429
+ export interface SpotlightToolRow extends SpotlightToolTotals {
430
+ tool: SpotlightTool;
431
+ }
432
+ /**
433
+ * How the model got back output a shortened result hid:
434
+ * - `artifact`: a later call read or searched an artifact the shortened result named (`artifact://N`);
435
+ * - `reread`: a later `read` of the same file whose selection overlaps the hidden lines, or the whole file again;
436
+ * - `rerun`: a later call of the same tool repeating the shortened one: a bash command with a pipe, redirect or
437
+ * changed flags; any other tool with near-identical arguments (same tool, argument tokens' Jaccard ≥ 0.6).
438
+ */
439
+ export type SpotlightRecoveryKind = "artifact" | "reread" | "rerun";
440
+ /** A ratio over sessions with its bootstrap 90% interval (`lo`/`hi` null under 3 sessions; `value` null with none). */
441
+ export interface SpotlightEstimate {
442
+ value: number | null;
443
+ lo: number | null;
444
+ hi: number | null;
445
+ }
446
+ /**
447
+ * Token totals of one tool's evaluated results. Savings are measured against the `plain` text pi would have shown
448
+ * unshaped for the same call (its inline cap and read page), not against the full output shaping reads.
449
+ */
450
+ export interface SpotlightToolTotals {
451
+ /** Results the experiment evaluated. */
452
+ results: number;
453
+ /** Results it shortened. */
454
+ shaped: number;
455
+ /** The full output shaping read (a spilled bash output's whole artifact, a whole file up to 2 MiB). */
456
+ inTokens: number;
457
+ /**
458
+ * What `plain` would have shown: the trace's `plainTokens`, else (read, bash and eval traces written before pi
459
+ * recorded it) estimated from the inline cap.
460
+ */
461
+ plainTokens: number;
462
+ outTokens: number;
463
+ /**
464
+ * Σ (plainTokens − outTokens) over shortened results; a cut that showed more than `plain` would have counts
465
+ * negative (see {@link SpotlightGross.widerThanPlain}).
466
+ */
467
+ savedTokens: number;
468
+ /** Σ (inTokens − outTokens): the saving against the full output, which overstates what the model was spared. */
469
+ fullSavedTokens: number;
470
+ }
471
+ /** Strategy 1, gross savings: what the cuts removed. */
472
+ export interface SpotlightGross extends SpotlightToolTotals {
473
+ /** savedTokens / (savedTokens + every tool-output token the model saw in the same sessions). */
474
+ ofToolOutput: number | null;
475
+ /** savedTokens / every token of the same sessions' requests (input + output + cache read + cache write). */
476
+ ofSessionTokens: number | null;
477
+ /** Every tool with an evaluated result in the range, the largest saving first. */
478
+ byTool: SpotlightToolRow[];
479
+ /** Shortened results whose `plainTokens` is estimated (journaled before pi recorded it). */
480
+ estimatedPlain: number;
481
+ /**
482
+ * Shortened results whose cut was wider than what `plain` would have shown (out > plain): a loss where the cut
483
+ * was shown, a saving of 0 where pi capped it at `plain`'s text (counted by the would-be cut).
484
+ */
485
+ widerThanPlain: number;
486
+ }
487
+ /** Recovery totals of one kind. */
488
+ export interface SpotlightRecoveryTotals {
489
+ events: number;
490
+ /** Tokens of the recovery calls' results, which re-enter the context. */
491
+ tokens: number;
492
+ /** Requests that issued nothing but recovery calls. */
493
+ turns: number;
494
+ /** Provider cost of those requests. */
495
+ turnsUsd: number;
496
+ /**
497
+ * The recovery tokens carried through later requests, priced like {@link SpotlightCompounding.savedUsd}
498
+ * (excluding `turnsUsd`); Σ over kinds + clawback.turnsUsd = compounding.recoveryUsd.
499
+ */
500
+ usd: number;
501
+ }
502
+ /** Strategy 2, clawback: what getting hidden output back cost. */
503
+ export interface SpotlightClawback extends SpotlightRecoveryTotals {
504
+ /** Shortened results with hidden lines: the ones a recovery can follow. */
505
+ withHidden: number;
506
+ /** Of those, the results at least one recovery followed. */
507
+ recovered: number;
508
+ byKind: Record<SpotlightRecoveryKind, SpotlightRecoveryTotals>;
509
+ /** gross.savedTokens − tokens. */
510
+ netTokens: number;
511
+ }
512
+ /** Strategy 3, compounding: savings as every later request of the session would have re-read them. */
513
+ export interface SpotlightCompounding {
514
+ /** Σ over shortened results of saved tokens × later requests of the session until a compaction. */
515
+ avoidedTokens: number;
516
+ /** Recovery tokens carried the same way: they undo what the cut avoided. */
517
+ recoveredCarriedTokens: number;
518
+ /** Prompt tokens the same sessions' requests processed (input + cache read + cache write). */
519
+ promptTokens: number;
520
+ /** (avoided − recoveredCarried) / (promptTokens + avoided − recoveredCarried). */
521
+ avoidedShare: number | null;
522
+ /** Avoided tokens priced at each later request's own cache-read rate, plus one cache write. */
523
+ savedUsd: number;
524
+ /** recoveredCarriedTokens priced the same way, plus clawback.turnsUsd. */
525
+ recoveryUsd: number;
526
+ /** Spotlight's own bill (`spotlight:shape` costUsd). */
527
+ spotlightUsd: number;
528
+ /** savedUsd − recoveryUsd − spotlightUsd. */
529
+ netUsd: number;
530
+ /** Wall time shaping added to tool calls (Σ `spotlight:shape` ms). */
531
+ shapeMs: number;
532
+ }
533
+ /** Strategy 4: one bucket of the tool-output share of context, per session group. */
534
+ export interface SpotlightSharePoint {
535
+ /** Bucket start (the range's bucket size, as every time series). */
536
+ timestamp: number;
537
+ /** `shaped`: an experiment session from its marker on; `outside`: everything else. */
538
+ group: "shaped" | "outside";
539
+ sessions: number;
540
+ /** Tool-result tokens the model saw. */
541
+ toolTokens: number;
542
+ /** Everything that entered the context: tool results, assistant output, user prompts and the first request's prompt. */
543
+ contextTokens: number;
544
+ }
545
+ /** One bucket of savings over time. */
546
+ export interface SpotlightBucket {
547
+ timestamp: number;
548
+ results: number;
549
+ shaped: number;
550
+ savedTokens: number;
551
+ recoveries: number;
552
+ recoveredTokens: number;
553
+ netTokens: number;
554
+ savedUsd: number;
555
+ netUsd: number;
556
+ }
557
+ /** A recovery attributed to the latest shortened result it fetches from. */
558
+ export interface SpotlightRecovery {
559
+ kind: SpotlightRecoveryKind;
560
+ toolCallId: string;
561
+ tool: string;
562
+ /** The call's command, path or pattern, clipped to 200 chars. */
563
+ target: string;
564
+ timestamp: number;
565
+ tokens: number;
566
+ /** Tool calls between the shortened result and this one. */
567
+ after: number;
568
+ /** Its request issued nothing but recovery calls. */
569
+ turn: boolean;
570
+ }
571
+ /** One evaluated result that changed the output, or would have (`holdout`). */
572
+ export interface SpotlightResultRow {
573
+ sessionFile: string;
574
+ toolCallId: string;
575
+ timestamp: number;
576
+ tool: SpotlightTool;
577
+ /** Held out: the model saw the result unshaped; `savedTokens` is what the cut would have saved. */
578
+ holdout: boolean;
579
+ /** Command, path (with selector) or eval code head, clipped to 200 chars. */
580
+ target: string;
581
+ inTokens: number;
582
+ outTokens: number;
583
+ savedTokens: number;
584
+ hiddenLines: number;
585
+ steps: string[];
586
+ spotlightUsd: number;
587
+ shapeMs: number;
588
+ /** What `plain` would have shown (see {@link SpotlightToolTotals.plainTokens}). */
589
+ plainTokens: number;
590
+ /** Cut by the no-score fallback rules because the score-free coin skipped Spotlight. */
591
+ scoreFree: boolean;
592
+ recoveries: SpotlightRecovery[];
593
+ /** savedTokens − Σ recovery tokens. */
594
+ netTokens: number;
595
+ }
596
+ /**
597
+ * Who saw what for a result in the fetch-back comparison:
598
+ * - `applied`: Spotlight shortened it and the model saw the shortened text;
599
+ * - `holdout`: Spotlight would have shortened it, but the result was held out at random and the model saw it
600
+ * unshaped (the experiment's true counterfactual);
601
+ * - `reference`: shaping left it unchanged (results of the same tool and sessions, standardized to the applied
602
+ * cuts' original-size mix), the stand-in until held-out results accumulate;
603
+ * - `scoreFree`: shortened by the no-score fallback rules because a random coin skipped Spotlight
604
+ * (`spotlight.experiment.scoreFree`), the model saw the cut: against `applied`, what Spotlight's scores add;
605
+ * - `gated`: a read pi's former edit gate (removed) kept whole, the model saw plain's page; only in transcripts
606
+ * journaled while the gate ran.
607
+ * `applied` holds only cuts Spotlight scored (score-free cuts and cuts whose Spotlight calls failed are not in it).
608
+ */
609
+ export type SpotlightCutGroup = "applied" | "holdout" | "reference" | "scoreFree" | "gated";
610
+ /**
611
+ * Share of results the agent fetched more of within 12 calls, by one rule for every group: a later `read` of the
612
+ * same path overlapping the result's own window (the whole file without a selector), a rerun (see
613
+ * {@link SpotlightRecoveryKind}), or a read of an artifact the result named; not counted after an edit of that path
614
+ * (reads) or any edit (reruns), nor from the same request.
615
+ */
616
+ export interface SpotlightFetchBackCell {
617
+ tool: SpotlightTool;
618
+ group: SpotlightCutGroup;
619
+ results: number;
620
+ sessions: number;
621
+ /** Session-clustered bootstrap over the group's results. */
622
+ rate: SpotlightEstimate;
623
+ }
624
+ /** What the cuts of one tool earned, in tokens and dollars (applied cuts only; held-out results save nothing). */
625
+ export interface SpotlightCutEconomics {
626
+ tool: SpotlightTool;
627
+ cuts: number;
628
+ savedTokens: number;
629
+ recoveredTokens: number;
630
+ /** Requests that did nothing but fetch back output these cuts hid. */
631
+ extraTurns: number;
632
+ savedUsd: number;
633
+ /** Recovered tokens carried through later requests, priced like the savings. */
634
+ recoveryUsd: number;
635
+ /** Provider cost of the extra turns. */
636
+ turnUsd: number;
637
+ /** savedUsd − recoveryUsd − turnUsd − this cell's Spotlight bill. */
638
+ netUsd: number;
639
+ extraTurnsPer100Cuts: number;
640
+ netUsdPer100Cuts: number;
641
+ }
642
+ /** Calls between a cut (or held-out result) and the first fetch-back after it. */
643
+ export type SpotlightGapBin = "1" | "2" | "3" | "4–6" | "7–12";
644
+ /** Fetch-backs per gap bin and tool, for applied and held-out results: every bin of each tool with at least one. */
645
+ export interface SpotlightGapCount {
646
+ tool: SpotlightTool;
647
+ gap: SpotlightGapBin;
648
+ applied: number;
649
+ holdout: number;
650
+ }
651
+ /** What shaping costs in time and reliability (all evaluated results, held-out ones included). */
652
+ export interface SpotlightOverhead {
653
+ results: number;
654
+ /** Wall time shaping added to a tool call. */
655
+ shapeMsP50: number | null;
656
+ shapeMsP90: number | null;
657
+ /** Spotlight's own request time, over results whose calls all answered. */
658
+ spotlightMsP50: number | null;
659
+ spotlightMsP90: number | null;
660
+ /** Results whose Spotlight calls failed or timed out (shaped by the no-score fallback). */
661
+ failureRate: number | null;
662
+ /** Wall time tool calls spent shaping results whose Spotlight calls failed (mostly the 5 s timeout per call). */
663
+ failedWaitMs: number;
664
+ spotlightUsd: number;
665
+ }
666
+ /**
667
+ * The net once fetch-backs that would have happened anyway are taken out: held-out results (the model saw them
668
+ * unshaped) show how much of a would-be cut's output the agent reads again regardless, per tool; only recoveries
669
+ * beyond that baseline are the cut's cost. A tool's baseline is thin while it has fewer than `minHoldouts`.
670
+ */
671
+ export interface SpotlightAdjustedTool {
672
+ tool: SpotlightTool;
673
+ /** Applied cuts (scored and score-free) and their recovered tokens. */
674
+ cuts: number;
675
+ recoveredTokens: number;
676
+ /** Held-out would-be cuts the baseline is measured on. */
677
+ holdouts: number;
678
+ /** Recovered tokens per held-out would-be cut, over all the tool's holdouts (session-clustered bootstrap). */
679
+ baselinePerCut: SpotlightEstimate;
680
+ /** max(0, recovered − baseline per cut × cuts). */
681
+ excessTokens: SpotlightEstimate;
682
+ }
683
+ /** Holdout-adjusted net savings (tokens, against the `plain` baseline). */
684
+ export interface SpotlightAdjusted {
685
+ byTool: SpotlightAdjustedTool[];
686
+ /** Σ tools' excess (bootstrapped jointly over sessions). */
687
+ excessTokens: SpotlightEstimate;
688
+ /** gross.savedTokens − excessTokens. */
689
+ netTokens: SpotlightEstimate;
690
+ /** compounding.savedUsd − recoveryUsd × (excess / recovered) − spotlightUsd. */
691
+ netUsd: SpotlightEstimate;
692
+ /** Holdouts per tool below which its baseline is too thin to trust (the UI marks the tool). */
693
+ minHoldouts: number;
694
+ }
695
+ /**
696
+ * Lines of a shaped read's original the agent needed later: lines a later `read` of the same file selected, and lines
697
+ * a later `edit` of it changed (located by its Find text in the original), until the file's first edit or a later
698
+ * whole-file read.
699
+ */
700
+ export type SpotlightNeedSource = "reread" | "edit";
701
+ /**
702
+ * How well a group's per-line choices match what the agent needed later, over shaped reads with at least one needed
703
+ * line. Applied and score-free cuts are biased alike (the agent re-reads what it lacks), so compare them with each
704
+ * other; held-out would-be cuts are the unbiased measure.
705
+ */
706
+ export interface SpotlightRankingCell {
707
+ group: "applied" | "holdout" | "scoreFree";
708
+ results: number;
709
+ neededLines: number;
710
+ /** P(heat of a needed line > heat of an unneeded line of the same result), ties half; 0.5 is chance. Null for `scoreFree` (no heat). */
711
+ auc: SpotlightEstimate;
712
+ /** Needed-line rate among each result's hottest 10% of lines over its rate among all lines; 1 is no better than chance. */
713
+ topLift: SpotlightEstimate;
714
+ /** Share of needed lines the cut kept over the share of all lines it kept; 1 is a random cut of the same size. */
715
+ keptLift: SpotlightEstimate;
716
+ }
717
+ /** Mean heat (0–9) of one line position over shaped results of at least 40 lines. */
718
+ export interface SpotlightHeatPosition {
719
+ /** `line 1`, `lines 2–3`, then `0–10%` … `90–100%` of the output. */
720
+ label: string;
721
+ meanHeat: number;
722
+ lines: number;
723
+ }
724
+ /** Ranking quality: does Spotlight keep the lines the agent comes back for? */
725
+ export interface SpotlightRanking {
726
+ cells: SpotlightRankingCell[];
727
+ position: SpotlightHeatPosition[];
728
+ /** Results with needed lines, by how the need was observed (a result can count under both). */
729
+ sources: Record<SpotlightNeedSource, number>;
730
+ }
731
+ /** Saved-token bins (against `plain`) the step economics split cuts by; a negative saving falls in `<250`. */
732
+ export type SpotlightSizeBin = "<250" | "250–1k" | "1k–4k" | "≥4k";
733
+ /** What one shaping step (or combination) earns at one cut size: applied cuts of one tool. */
734
+ export interface SpotlightStepCell {
735
+ tool: SpotlightTool;
736
+ /** The cut's shaping steps joined with `+` (`outline+window`); combinations under 10 cuts in the range fold into `other`. */
737
+ steps: string;
738
+ size: SpotlightSizeBin;
739
+ cuts: number;
740
+ fetchBackRate: SpotlightEstimate;
741
+ /** Σ (plain − out), negative cuts (wider than `plain`) included. */
742
+ savedTokens: number;
743
+ recoveredTokens: number;
744
+ /** max(0, recovered − Σ each cut's holdout baseline (its tool's)). */
745
+ excessTokens: number;
746
+ /** (saved − excess) / saved: the share of the saving that stays saved; null when the cell saved nothing (≤ 0). */
747
+ keptShare: number | null;
748
+ }
749
+ /** What the experiment costs in agent time. */
750
+ export interface SpotlightTimeCost {
751
+ /** Model time of the experiment sessions' requests (Σ request duration). */
752
+ agentMs: number;
753
+ /** Requests that did nothing but fetch back cut output, and their model time. */
754
+ fetchBackTurns: number;
755
+ fetchBackMs: number;
756
+ /** Wall time tool calls spent shaping (Spotlight requests included). */
757
+ shapeMs: number;
758
+ /** (fetchBackMs + shapeMs) / agentMs. */
759
+ share: number | null;
760
+ }
761
+ /** One tool's share of the tool output experiment sessions' models saw (chars ÷ 4). */
762
+ export interface SpotlightCoverageRow {
763
+ tool: string;
764
+ /** The experiment evaluated results of it in the range. */
765
+ shaped: boolean;
766
+ calls: number;
767
+ tokens: number;
768
+ share: number;
769
+ }
770
+ /**
771
+ * Which transcripts the Spotlight dashboard measures (`GET /api/stats/spotlight?agent=`, default `all`): `main`
772
+ * agents only, task `subagent`s only, or everything (advisors appear only under `all`). Every metric, the share
773
+ * trend's `outside` group included, is filtered the same way.
774
+ */
775
+ export type SpotlightAgentScope = "all" | "main" | "subagent";
776
+ /** An experiment session, for the context chart's picker. */
777
+ export interface SpotlightSessionSummary {
778
+ sessionFile: string;
779
+ title: string | null;
780
+ folder: string;
781
+ /** Which agent wrote the transcript (each subagent transcript is its own experiment session). */
782
+ agentType: AgentType;
783
+ /** The session's first Spotlight marker: activity before it (a resumed pre-experiment session) is not measured. */
784
+ startedAt: number;
785
+ requests: number;
786
+ savedTokens: number;
787
+ netUsd: number;
788
+ }
789
+ /**
790
+ * Spotlight dashboard payload (`GET /api/stats/spotlight?range=&agent=`). Every experiment session shapes tool
791
+ * output; held-out results within them are the counterfactual. Only activity at or after a session's Spotlight
792
+ * marker is the experiment's; earlier activity of the same transcript counts as `outside` in the share trend and is
793
+ * left out of every other metric.
794
+ */
795
+ export interface SpotlightDashboardStats {
796
+ /** Experiment sessions with activity in the range. */
797
+ sessions: number;
798
+ /** First Spotlight marker ever seen (not range-bound), for the trend's marker; null before the experiment. */
799
+ experimentStart: number | null;
800
+ gross: SpotlightGross;
801
+ clawback: SpotlightClawback;
802
+ compounding: SpotlightCompounding;
803
+ series: SpotlightBucket[];
804
+ share: SpotlightSharePoint[];
805
+ /** Latest 60 shortened results, newest first. */
806
+ recent: SpotlightResultRow[];
807
+ /** Latest 30 experiment sessions in the range, newest first. */
808
+ sessionList: SpotlightSessionSummary[];
809
+ /** Held-out results in the range (would-be cuts the model saw unshaped). */
810
+ holdouts: number;
811
+ /** Score-free cuts in the range (shortened without Spotlight by the fallback rules). */
812
+ scoreFree: number;
813
+ adjusted: SpotlightAdjusted;
814
+ ranking: SpotlightRanking;
815
+ steps: SpotlightStepCell[];
816
+ timeCost: SpotlightTimeCost;
817
+ coverage: SpotlightCoverageRow[];
818
+ fetchBack: SpotlightFetchBackCell[];
819
+ economics: SpotlightCutEconomics[];
820
+ gaps: SpotlightGapCount[];
821
+ overhead: SpotlightOverhead;
822
+ }
823
+ /** One request of a session's context chart. */
824
+ export interface SpotlightContextPoint {
825
+ timestamp: number;
826
+ /** input + cache read + cache write of this request. */
827
+ contextTokens: number;
828
+ /** The context without shaping: contextTokens + net tokens saved so far (reset at a compaction). */
829
+ withoutTokens: number;
830
+ /** The context shrank sharply before this request (a compaction). */
831
+ compacted: boolean;
832
+ /** Tokens saved and recovered by results that landed since the previous request. */
833
+ saved: number;
834
+ recovered: number;
835
+ }
836
+ /** A session's context with and without shaping (`GET /api/stats/spotlight/session?file=`). */
837
+ export interface SpotlightSessionContext {
838
+ session: SpotlightSessionSummary;
839
+ points: SpotlightContextPoint[];
840
+ }
398
841
  /**
399
842
  * Aggregated usage for a single tool over the active range.
400
843
  *