@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
package/src/db.ts CHANGED
@@ -13,7 +13,21 @@ import type { ModelCost } from "@linxiraos/pi-catalog/types";
13
13
  import { getConfigRootDir, getStatsDbPath, VERSION } from "@linxiraos/pi-utils";
14
14
  import { ChunkedInsert } from "./chunked-insert";
15
15
  import { classifyAgentType, type ParseSessionResult, type SessionParserState } from "./parser";
16
- import { ensureRollupSchema, getDailyActivityFromRollup } from "./rollup";
16
+ import {
17
+ ensureRollupSchema,
18
+ getDailyActivityFromRollup,
19
+ getModelDailyActivity,
20
+ getModelHourlyActivity,
21
+ } from "./rollup";
22
+ import {
23
+ mergeRanges,
24
+ type SpotlightCallResultLink,
25
+ type SpotlightCallRow,
26
+ type SpotlightNeedRow,
27
+ type SpotlightRequestRow,
28
+ type SpotlightSessionRow,
29
+ type SpotlightShapeRow,
30
+ } from "./spotlight-ingest";
17
31
  import type {
18
32
  AgentType,
19
33
  AssistantTextStats,
@@ -21,6 +35,8 @@ import type {
21
35
  FrustrationCounts,
22
36
  MessageStats,
23
37
  MessageStatsInput,
38
+ ModelDailyActivityPoint,
39
+ ModelHourlyActivityPoint,
24
40
  ModelSideCounts,
25
41
  ModelSideTimeSeriesPoint,
26
42
  ToolCallStats,
@@ -92,7 +108,7 @@ export function currentDb(): Database | null {
92
108
 
93
109
  const BACKFILL_COMPLETE = "complete";
94
110
  const BACKFILL_PENDING = "pending";
95
- const USER_MESSAGES_BACKFILL_KEY = "user_messages_v9";
111
+ const USER_MESSAGES_BACKFILL_KEY = "user_messages_v10";
96
112
  // Model-side analysis (`assistant_text`) was introduced after every existing
97
113
  // database had already burned its session backfills, so it needs its own
98
114
  // sentinel: a completed user-message backfill must never leave old sessions
@@ -128,6 +144,27 @@ const NO_CACHE_INPUT_BACKFILL_KEY = "cost_no_cache_input_v1";
128
144
  // value stored is the version that ran it), since only a catalog update can
129
145
  // price a model it could not price before.
130
146
  const CATALOG_COST_BACKFILL_KEY = "catalog_cost_backfill";
147
+ // The Spotlight tables are filled by the parser; transcripts ingested before
148
+ // they existed are re-parsed once. Only files modified since the experiment
149
+ // shipped can hold its entries, so older cursors stay put.
150
+ const SPOTLIGHT_BACKFILL_KEY = "spotlight_v1";
151
+ const SPOTLIGHT_SINCE_MS = Date.parse("2026-10-28T00:00:00Z");
152
+ // Experiment sessions parsed before `spotlight_calls.edits` existed are
153
+ // re-parsed once (only them: they are few) so recovery detection sees edits.
154
+ // (`v3`: a build that ran the `v2` pass may have had its sessions re-parsed
155
+ // again by an older build, which records no edits.)
156
+ const SPOTLIGHT_EDITS_BACKFILL_KEY = "spotlight_v3_edits";
157
+ // Experiment sessions parsed before results carried heat, kept runs, plain sizes
158
+ // and needed lines are re-parsed once (only them, never the whole history).
159
+ const SPOTLIGHT_NEEDS_BACKFILL_KEY = "spotlight_v4_needs";
160
+ // Experiment sessions parsed before calls carried argument tokens (the generic
161
+ // rerun rule for every tool beyond read and bash) are re-parsed once.
162
+ const SPOTLIGHT_ARG_TOKENS_BACKFILL_KEY = "spotlight_v5_arg_tokens";
163
+ // The experiment became a toggle: sessions are marked by `spotlight:session`
164
+ // (which older builds did not read) and legacy `spotlight:assignment` sessions
165
+ // count only with the arm that shipped. Every transcript that can hold
166
+ // Spotlight entries is re-parsed once by the new rules.
167
+ const SPOTLIGHT_TOGGLE_BACKFILL_KEY = "spotlight_v6_toggle";
131
168
  function shouldResetBackfill(value: string | undefined): boolean {
132
169
  return value !== BACKFILL_COMPLETE && value !== BACKFILL_PENDING;
133
170
  }
@@ -315,12 +352,128 @@ export async function initDb(): Promise<Database> {
315
352
  key TEXT PRIMARY KEY,
316
353
  value TEXT NOT NULL
317
354
  );
355
+
356
+ -- Spotlight experiment sessions: the first Spotlight marker of each transcript.
357
+ CREATE TABLE IF NOT EXISTS spotlight_sessions (
358
+ session_file TEXT PRIMARY KEY,
359
+ folder TEXT NOT NULL,
360
+ marked_at INTEGER NOT NULL,
361
+ cwd TEXT,
362
+ title TEXT
363
+ ) WITHOUT ROWID;
364
+
365
+ -- One evaluated tool result: its spotlight:shape entry and its result's details.spotlight, upserted.
366
+ CREATE TABLE IF NOT EXISTS spotlight_results (
367
+ session_file TEXT NOT NULL,
368
+ tool_call_id TEXT NOT NULL,
369
+ timestamp INTEGER NOT NULL,
370
+ tool TEXT NOT NULL,
371
+ in_chars INTEGER NOT NULL,
372
+ out_chars INTEGER NOT NULL,
373
+ in_tokens INTEGER NOT NULL,
374
+ out_tokens INTEGER NOT NULL,
375
+ steps TEXT NOT NULL,
376
+ has_details INTEGER NOT NULL,
377
+ holdout INTEGER NOT NULL DEFAULT 0,
378
+ original_url TEXT,
379
+ path TEXT,
380
+ start_line INTEGER,
381
+ lines INTEGER,
382
+ hidden TEXT,
383
+ hidden_lines INTEGER NOT NULL DEFAULT 0,
384
+ artifacts TEXT,
385
+ sp_calls INTEGER,
386
+ sp_failures INTEGER,
387
+ sp_ms REAL,
388
+ sp_cost REAL,
389
+ shape_ms REAL,
390
+ plain_chars INTEGER,
391
+ plain_tokens INTEGER,
392
+ capped_tokens INTEGER,
393
+ score_free INTEGER NOT NULL DEFAULT 0,
394
+ heat TEXT,
395
+ kept TEXT,
396
+ gated INTEGER NOT NULL DEFAULT 0,
397
+ PRIMARY KEY (session_file, tool_call_id)
398
+ ) WITHOUT ROWID;
399
+ CREATE INDEX IF NOT EXISTS idx_spotlight_results_call ON spotlight_results(tool_call_id);
400
+
401
+ -- Every tool call of an experiment session from its marker on, in order.
402
+ CREATE TABLE IF NOT EXISTS spotlight_calls (
403
+ session_file TEXT NOT NULL,
404
+ tool_call_id TEXT NOT NULL,
405
+ entry_id TEXT NOT NULL,
406
+ timestamp INTEGER NOT NULL,
407
+ seq INTEGER NOT NULL,
408
+ tool_name TEXT NOT NULL,
409
+ calls_in_turn INTEGER NOT NULL,
410
+ target TEXT NOT NULL,
411
+ result_chars INTEGER,
412
+ artifacts TEXT,
413
+ edits TEXT,
414
+ arg_tokens TEXT,
415
+ PRIMARY KEY (session_file, tool_call_id)
416
+ ) WITHOUT ROWID;
417
+ CREATE INDEX IF NOT EXISTS idx_spotlight_calls_entry ON spotlight_calls(entry_id, timestamp);
418
+
419
+ -- Main-loop requests of an experiment session (side requests journaled as model_usage excluded).
420
+ CREATE TABLE IF NOT EXISTS spotlight_requests (
421
+ session_file TEXT NOT NULL,
422
+ entry_id TEXT NOT NULL,
423
+ timestamp INTEGER NOT NULL,
424
+ PRIMARY KEY (session_file, entry_id)
425
+ ) WITHOUT ROWID;
426
+ CREATE INDEX IF NOT EXISTS idx_spotlight_requests_entry ON spotlight_requests(entry_id, timestamp);
427
+
428
+ -- Original lines (1-based positions) a shaped read's later calls needed; open while still collecting.
429
+ CREATE TABLE IF NOT EXISTS spotlight_needs (
430
+ session_file TEXT NOT NULL,
431
+ tool_call_id TEXT NOT NULL,
432
+ file TEXT NOT NULL,
433
+ open INTEGER NOT NULL,
434
+ reread TEXT NOT NULL,
435
+ edit TEXT NOT NULL,
436
+ PRIMARY KEY (session_file, tool_call_id)
437
+ ) WITHOUT ROWID;
318
438
  `);
319
439
 
320
440
  const offsetColumns = db.query("PRAGMA table_info(file_offsets)").all() as { name: string }[];
321
441
  if (!offsetColumns.some(column => column.name === "parser_state")) {
322
442
  db.run("ALTER TABLE file_offsets ADD COLUMN parser_state TEXT");
323
443
  }
444
+ dropSpotlightArms(db);
445
+ // No result was held out before this column existed, so the default is exact for old rows.
446
+ const spotlightResultColumns = db.query<{ name: string }, []>("PRAGMA table_info(spotlight_results)").all();
447
+ if (!spotlightResultColumns.some(column => column.name === "holdout")) {
448
+ db.run("ALTER TABLE spotlight_results ADD COLUMN holdout INTEGER NOT NULL DEFAULT 0");
449
+ }
450
+ // Filled for existing rows by the `spotlight_v4_needs` re-parse; until then plain sizes are estimated.
451
+ for (const [column, type] of [
452
+ ["plain_chars", "INTEGER"],
453
+ ["plain_tokens", "INTEGER"],
454
+ ["capped_tokens", "INTEGER"],
455
+ ["score_free", "INTEGER NOT NULL DEFAULT 0"],
456
+ ["heat", "TEXT"],
457
+ ["kept", "TEXT"],
458
+ // No read was gated before this existed: the default is exact.
459
+ ["gated", "INTEGER NOT NULL DEFAULT 0"],
460
+ ] as const) {
461
+ if (!spotlightResultColumns.some(existing => existing.name === column)) {
462
+ db.run(`ALTER TABLE spotlight_results ADD COLUMN ${column} ${type}`);
463
+ }
464
+ }
465
+ // pi's read mark went with its former edit gate.
466
+ if (spotlightResultColumns.some(column => column.name === "edit_likely")) {
467
+ db.run("ALTER TABLE spotlight_results DROP COLUMN edit_likely");
468
+ }
469
+ const spotlightCallColumns = db.query<{ name: string }, []>("PRAGMA table_info(spotlight_calls)").all();
470
+ if (!spotlightCallColumns.some(column => column.name === "edits")) {
471
+ db.run("ALTER TABLE spotlight_calls ADD COLUMN edits TEXT");
472
+ }
473
+ // Filled for existing rows by the `spotlight_v5_arg_tokens` re-parse; until then no generic rerun is detected.
474
+ if (!spotlightCallColumns.some(column => column.name === "arg_tokens")) {
475
+ db.run("ALTER TABLE spotlight_calls ADD COLUMN arg_tokens TEXT");
476
+ }
324
477
  const messageColumns = db.query("PRAGMA table_info(messages)").all() as { name: string }[];
325
478
  if (!messageColumns.some(column => column.name === "premium_requests")) {
326
479
  db.run("ALTER TABLE messages ADD COLUMN premium_requests REAL NOT NULL DEFAULT 0");
@@ -440,6 +593,11 @@ export async function initDb(): Promise<Database> {
440
593
  backfillMissingCatalogCosts(db);
441
594
  backfillNoCacheInputCosts(db);
442
595
  backfillForkDuplicates(db);
596
+ backfillSpotlight(db, SPOTLIGHT_BACKFILL_KEY);
597
+ reparseSpotlightSessions(db, SPOTLIGHT_EDITS_BACKFILL_KEY);
598
+ reparseSpotlightSessions(db, SPOTLIGHT_NEEDS_BACKFILL_KEY);
599
+ reparseSpotlightSessions(db, SPOTLIGHT_ARG_TOKENS_BACKFILL_KEY);
600
+ backfillSpotlight(db, SPOTLIGHT_TOGGLE_BACKFILL_KEY);
443
601
  ensureRollupSchema(db);
444
602
  return db;
445
603
  }
@@ -676,6 +834,67 @@ function backfillNoCacheInputCosts(database: Database): void {
676
834
  applyBackfill();
677
835
  }
678
836
 
837
+ /**
838
+ * Re-parse, once per key, the transcripts that can hold Spotlight entries
839
+ * (modified since {@link SPOTLIGHT_SINCE_MS}) by dropping their cursors; every
840
+ * older cursor stays, so this never triggers a full-history re-parse. The next
841
+ * sync rebuilds those files from byte zero, replacing their Spotlight rows.
842
+ * Keys: {@link SPOTLIGHT_BACKFILL_KEY} (the tables are new),
843
+ * {@link SPOTLIGHT_TOGGLE_BACKFILL_KEY} (the experiment became a toggle).
844
+ */
845
+ function backfillSpotlight(database: Database, key: string): void {
846
+ const row = database.query<{ value: string }, [string]>("SELECT value FROM meta WHERE key = ?").get(key);
847
+ if (row?.value === BACKFILL_COMPLETE) return;
848
+ database.transaction(() => {
849
+ database.query("DELETE FROM file_offsets WHERE last_modified >= ?").run(SPOTLIGHT_SINCE_MS);
850
+ database.query("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(key, BACKFILL_COMPLETE);
851
+ })();
852
+ }
853
+
854
+ /**
855
+ * Drop the arm columns of a database written while sessions drew arms, once
856
+ * (while `spotlight_sessions.arm` exists). Sessions of any arm but the one that shipped
857
+ * were never shaped with the shipped algorithm: their Spotlight rows go now,
858
+ * so the dashboard leaves them out before the {@link SPOTLIGHT_TOGGLE_BACKFILL_KEY}
859
+ * re-parse (which also clears their parser state) runs.
860
+ */
861
+ function dropSpotlightArms(database: Database): void {
862
+ const columns = database.query<{ name: string }, []>("PRAGMA table_info(spotlight_sessions)").all();
863
+ if (!columns.some(column => column.name === "arm")) return;
864
+ database.transaction(() => {
865
+ const legacy = "SELECT session_file FROM spotlight_sessions WHERE arm <> 'vylv5'";
866
+ // `spotlight_sessions` (first in the list) goes last: the other deletes select through it.
867
+ for (const table of SPOTLIGHT_TABLES.toReversed()) {
868
+ database.run(`DELETE FROM ${table} WHERE session_file IN (${legacy})`);
869
+ }
870
+ for (const column of ["arm", "find_ranker", "source"]) {
871
+ database.run(`ALTER TABLE spotlight_sessions DROP COLUMN ${column}`);
872
+ }
873
+ database.run("ALTER TABLE spotlight_sessions RENAME COLUMN assigned_at TO marked_at");
874
+ database.run("ALTER TABLE spotlight_results DROP COLUMN arm");
875
+ // The retired guard-rail comparison cached its history reference here.
876
+ database.run("DELETE FROM meta WHERE key LIKE 'spotlight_guard_history:%'");
877
+ })();
878
+ }
879
+
880
+ /**
881
+ * Re-parse, once per key, every experiment session (the transcripts
882
+ * `spotlight_sessions` names, never the whole history) by dropping their
883
+ * cursors; the next sync rebuilds them from byte zero, replacing their
884
+ * Spotlight rows. Keys: {@link SPOTLIGHT_EDITS_BACKFILL_KEY} (calls get
885
+ * `edits`), {@link SPOTLIGHT_NEEDS_BACKFILL_KEY} (results get heat, kept runs,
886
+ * plain sizes and the score-free flag, shaped reads needed lines),
887
+ * {@link SPOTLIGHT_ARG_TOKENS_BACKFILL_KEY} (calls get argument tokens).
888
+ */
889
+ function reparseSpotlightSessions(database: Database, key: string): void {
890
+ const row = database.query<{ value: string }, [string]>("SELECT value FROM meta WHERE key = ?").get(key);
891
+ if (row?.value === BACKFILL_COMPLETE) return;
892
+ database.transaction(() => {
893
+ database.run("DELETE FROM file_offsets WHERE session_file IN (SELECT session_file FROM spotlight_sessions)");
894
+ database.query("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(key, BACKFILL_COMPLETE);
895
+ })();
896
+ }
897
+
679
898
  /** Persisted transcript identity and parser cursor used to resume stats ingestion. */
680
899
  export interface FileOffset {
681
900
  offset: number;
@@ -914,6 +1133,9 @@ export function applySessionParseResults(sessions: ParsedSession[]): {
914
1133
  }
915
1134
  }
916
1135
  if (replace) {
1136
+ for (const table of SPOTLIGHT_TABLES) {
1137
+ changes += database.query(`DELETE FROM ${table} WHERE session_file = ?`).run(sessionFile).changes;
1138
+ }
917
1139
  if (messages.length > 0) {
918
1140
  changes += database.query("DELETE FROM messages WHERE session_file = ?").run(sessionFile).changes;
919
1141
  }
@@ -946,7 +1168,14 @@ export function applySessionParseResults(sessions: ParsedSession[]): {
946
1168
  insertAssistantText(parsedRows(writes, result => result.assistantTexts)) +
947
1169
  updateUserMessageLinks(parsedRows(writes, result => result.userLinks)) +
948
1170
  insertToolCalls(parsedRows(writes, result => result.toolCalls)) +
949
- updateToolResults(parsedRows(writes, result => result.toolResults));
1171
+ updateToolResults(parsedRows(writes, result => result.toolResults)) +
1172
+ insertSpotlightSessions(parsedRows(writes, result => result.spotlight.sessions)) +
1173
+ updateSpotlightTitles(parsedRows(writes, result => result.spotlight.titles)) +
1174
+ upsertSpotlightShapes(parsedRows(writes, result => result.spotlight.shapes)) +
1175
+ insertSpotlightCalls(parsedRows(writes, result => result.spotlight.calls)) +
1176
+ updateSpotlightCallResults(parsedRows(writes, result => result.spotlight.callResults)) +
1177
+ insertSpotlightRequests(parsedRows(writes, result => result.spotlight.requests)) +
1178
+ upsertSpotlightNeeds(parsedRows(writes, result => result.spotlight.needs));
950
1179
  for (const { sessionFile, result } of sessions) {
951
1180
  if (result.parserState) {
952
1181
  setFileOffset(sessionFile, result.newOffset, result.parserState.mtimeMs, result.parserState);
@@ -1172,9 +1401,9 @@ export function getMessageById(id: number): MessageStats | null {
1172
1401
  * {@link getProviderHourlyBurn}. Reads the hourly rollup, falling back to the
1173
1402
  * raw rows while its rebuild backlog is too large for exact reads.
1174
1403
  */
1175
- export async function getDailyActivity(days = 371): Promise<DailyActivityPoint[]> {
1404
+ export async function getDailyActivity(days = 371, now = Date.now()): Promise<DailyActivityPoint[]> {
1176
1405
  const database = await initDb();
1177
- const cutoff = Date.now() - days * 24 * 60 * 60 * 1000;
1406
+ const cutoff = now - days * 24 * 60 * 60 * 1000;
1178
1407
  const rolled = getDailyActivityFromRollup(cutoff);
1179
1408
  if (rolled) return rolled;
1180
1409
  const stmt = database.query(`
@@ -1202,6 +1431,48 @@ export async function getDailyActivity(days = 371): Promise<DailyActivityPoint[]
1202
1431
  }));
1203
1432
  }
1204
1433
 
1434
+ /**
1435
+ * Lookback for the Studio home usage card. It renders a calendar-year heatmap
1436
+ * plus a year-to-date model legend, so the window has to reach back past
1437
+ * January 1st even in late December (the TUI heatmap reads 371 days for the
1438
+ * same reason; 400 keeps a month of slack).
1439
+ */
1440
+ export const USAGE_HISTORY_DAYS = 400;
1441
+
1442
+ /** Everything the Studio home usage card reads from the stats DB. */
1443
+ export interface UsageHistory {
1444
+ /** Per-day totals for the last {@link USAGE_HISTORY_DAYS} days, oldest first. */
1445
+ days: DailyActivityPoint[];
1446
+ /** Per-day per-model totals over the same window, oldest day first. */
1447
+ byModelDay: ModelDailyActivityPoint[];
1448
+ /** Per-model totals for each local hour of `now`'s day. */
1449
+ todayByHour: ModelHourlyActivityPoint[];
1450
+ }
1451
+
1452
+ /**
1453
+ * Read the Studio home card's usage history in one call: the daily totals the
1454
+ * TUI heatmap already uses, the same window split per model, and today's
1455
+ * per-model hourly series. One `initDb` per call; every read goes through the
1456
+ * rollup union, so no session transcript is re-parsed here.
1457
+ *
1458
+ * "Today" starts on the stats database's own local calendar, not the JS clock:
1459
+ * the hour buckets come from SQLite's `localtime`, and the two clocks can
1460
+ * disagree (a process launched under a `TZ` the C library ignores — Bun's test
1461
+ * runner is one), which would slide the strip off the day it summarizes.
1462
+ */
1463
+ export async function getUsageHistory(now = Date.now(), days = USAGE_HISTORY_DAYS): Promise<UsageHistory> {
1464
+ const database = await initDb();
1465
+ const cutoff = now - days * 24 * 60 * 60 * 1000;
1466
+ const today = database
1467
+ .query(`SELECT unixepoch(date(? / 1000, 'unixepoch', 'localtime'), 'utc') * 1000 AS start`)
1468
+ .get(now) as { start: number };
1469
+ return {
1470
+ days: await getDailyActivity(days, now),
1471
+ byModelDay: getModelDailyActivity(cutoff),
1472
+ todayByHour: getModelHourlyActivity(today.start),
1473
+ };
1474
+ }
1475
+
1205
1476
  /**
1206
1477
  * Reset `file_offsets` (and any existing `user_messages` rows) so the next
1207
1478
  * successful sync re-parses every session and re-derives behavioral metrics.
@@ -1241,12 +1512,14 @@ export async function getDailyActivity(days = 371): Promise<DailyActivityPoint[]
1241
1512
  * - v9: stored judge prose (`prose` / `prose_hash`) for the frustration
1242
1513
  * judge, so every session re-parses once to populate it. Verdicts live in
1243
1514
  * `frustration_verdicts`, keyed by prose hash, which this reset never touches.
1244
- * - v10: the Chinese and voice-input lexicon layer landed (boundary-free
1245
- * patterns, because speech transcription emits one unpunctuated line), plus
1246
- * two columns: `emphasis` (the shouting proxy capitalisation cannot see -
1247
- * full-width bursts, repeated Han runs, repeated denials) and
1248
- * `unsupported_script` (prose in a script no lexicon covers, which the
1249
- * dashboard reports as unscored instead of counting as not annoyed).
1515
+ * - v10: excluded agent-attributed user-role messages, which diluted user
1516
+ * frustration rates and could be judged as user complaints; the Chinese and
1517
+ * voice-input lexicon layer also landed (boundary-free patterns, because
1518
+ * speech transcription emits one unpunctuated line), plus two columns:
1519
+ * `emphasis` (the shouting proxy capitalisation cannot see - full-width
1520
+ * bursts, repeated Han runs, repeated denials) and `unsupported_script`
1521
+ * (prose in a script no lexicon covers, which the dashboard reports as
1522
+ * unscored instead of counting as not annoyed).
1250
1523
  *
1251
1524
  * Existing `messages` rows are unaffected - `INSERT OR IGNORE` keeps them.
1252
1525
  */
@@ -2044,3 +2317,257 @@ export function updateToolResults(links: Iterable<ToolResultLink>): number {
2044
2317
  });
2045
2318
  return updated;
2046
2319
  }
2320
+
2321
+ /** Tables the parser fills for the Spotlight dashboard, all keyed by `session_file`. */
2322
+ const SPOTLIGHT_TABLES = [
2323
+ "spotlight_sessions",
2324
+ "spotlight_results",
2325
+ "spotlight_calls",
2326
+ "spotlight_requests",
2327
+ "spotlight_needs",
2328
+ ] as const;
2329
+
2330
+ /** Record each experiment session's first Spotlight marker; a later one (a resumed session) never replaces it. */
2331
+ export function insertSpotlightSessions(rows: Iterable<SpotlightSessionRow>): number {
2332
+ if (!db) return 0;
2333
+ const stmt = db.query(`
2334
+ INSERT OR IGNORE INTO spotlight_sessions (session_file, folder, marked_at, cwd, title)
2335
+ VALUES (?, ?, ?, ?, ?)
2336
+ `);
2337
+ let changes = 0;
2338
+ atomically(db, () => {
2339
+ for (const r of rows) {
2340
+ changes += stmt.run(r.sessionFile, r.folder, r.markedAt, r.cwd, r.title).changes;
2341
+ }
2342
+ });
2343
+ return changes;
2344
+ }
2345
+
2346
+ export function updateSpotlightTitles(rows: Iterable<{ sessionFile: string; title: string }>): number {
2347
+ if (!db) return 0;
2348
+ const stmt = db.query("UPDATE spotlight_sessions SET title = ? WHERE session_file = ?");
2349
+ let changes = 0;
2350
+ atomically(db, () => {
2351
+ for (const r of rows) changes += stmt.run(r.title, r.sessionFile).changes;
2352
+ });
2353
+ return changes;
2354
+ }
2355
+
2356
+ /**
2357
+ * Upsert evaluated results. The shape entry and the result message can land in
2358
+ * different tail parses: the shape entry brings Spotlight's usage and timing,
2359
+ * the result's details the hidden lines and named artifacts, and either may
2360
+ * come first. Fork copies of a call (same tool call id under another
2361
+ * transcript) are skipped, first writer wins.
2362
+ */
2363
+ export function upsertSpotlightShapes(rows: Iterable<SpotlightShapeRow>): number {
2364
+ if (!db) return 0;
2365
+ const fromDetails = (column: string) =>
2366
+ `${column} = CASE WHEN excluded.has_details = 1 THEN excluded.${column} ELSE spotlight_results.${column} END`;
2367
+ const coalesce = (column: string) => `${column} = COALESCE(excluded.${column}, spotlight_results.${column})`;
2368
+ const writer = new ChunkedInsert(db, {
2369
+ verb: "INSERT",
2370
+ table: "spotlight_results",
2371
+ columns: [
2372
+ "session_file",
2373
+ "tool_call_id",
2374
+ "timestamp",
2375
+ "tool",
2376
+ "in_chars",
2377
+ "out_chars",
2378
+ "in_tokens",
2379
+ "out_tokens",
2380
+ "steps",
2381
+ "has_details",
2382
+ "holdout",
2383
+ "original_url",
2384
+ "path",
2385
+ "start_line",
2386
+ "lines",
2387
+ "hidden",
2388
+ "hidden_lines",
2389
+ "artifacts",
2390
+ "sp_calls",
2391
+ "sp_failures",
2392
+ "sp_ms",
2393
+ "sp_cost",
2394
+ "shape_ms",
2395
+ "plain_chars",
2396
+ "plain_tokens",
2397
+ "capped_tokens",
2398
+ "score_free",
2399
+ "heat",
2400
+ "kept",
2401
+ "gated",
2402
+ ],
2403
+ identity: ["tool_call_id"],
2404
+ upsert: `ON CONFLICT(session_file, tool_call_id) DO UPDATE SET
2405
+ ${["tool", "in_chars", "out_chars", "in_tokens", "out_tokens", "steps", "hidden_lines"].map(fromDetails).join(",\n")},
2406
+ ${["original_url", "path", "start_line", "lines", "hidden", "artifacts", "sp_calls", "sp_failures", "sp_ms", "sp_cost", "shape_ms", "plain_chars", "plain_tokens", "capped_tokens", "heat", "kept"].map(coalesce).join(",\n")},
2407
+ has_details = MAX(spotlight_results.has_details, excluded.has_details),
2408
+ holdout = MAX(spotlight_results.holdout, excluded.holdout),
2409
+ score_free = MAX(spotlight_results.score_free, excluded.score_free),
2410
+ gated = MAX(spotlight_results.gated, excluded.gated)`,
2411
+ });
2412
+ return atomically(db, () => {
2413
+ for (const r of rows) {
2414
+ const o = r.original;
2415
+ writer.add(
2416
+ r.sessionFile,
2417
+ [r.toolCallId],
2418
+ [
2419
+ r.sessionFile,
2420
+ r.toolCallId,
2421
+ r.timestamp,
2422
+ r.tool,
2423
+ r.inChars,
2424
+ r.outChars,
2425
+ r.inTokens,
2426
+ r.outTokens,
2427
+ JSON.stringify(r.steps),
2428
+ r.hasDetails ? 1 : 0,
2429
+ r.holdout ? 1 : 0,
2430
+ o?.url ?? null,
2431
+ o?.path ?? null,
2432
+ o ? o.start : null,
2433
+ o ? o.lines : null,
2434
+ o ? JSON.stringify(o.hidden) : null,
2435
+ o?.hiddenLines ?? 0,
2436
+ r.artifacts ? JSON.stringify(r.artifacts) : null,
2437
+ r.spotlight?.calls ?? null,
2438
+ r.spotlight?.failures ?? null,
2439
+ r.spotlight?.ms ?? null,
2440
+ r.spotlight?.costUsd ?? null,
2441
+ r.shapeMs,
2442
+ r.plainChars,
2443
+ r.plainTokens,
2444
+ r.cappedTokens,
2445
+ r.scoreFree ? 1 : 0,
2446
+ o?.heat ?? null,
2447
+ o ? JSON.stringify(o.kept) : null,
2448
+ r.gated ? 1 : 0,
2449
+ ],
2450
+ );
2451
+ }
2452
+ return writer.finish();
2453
+ });
2454
+ }
2455
+
2456
+ /**
2457
+ * Merge needed lines of shaped reads: ranges add to the stored ones (a tail parse brings only its own calls'),
2458
+ * `open` takes the latest. A fork's copy of another transcript's read is skipped, first writer wins.
2459
+ */
2460
+ export function upsertSpotlightNeeds(rows: Iterable<SpotlightNeedRow>): number {
2461
+ if (!db) return 0;
2462
+ const database = db;
2463
+ const claimed = database.query<{ one: number }, [string, string]>(
2464
+ "SELECT 1 AS one FROM spotlight_needs WHERE tool_call_id = ? AND session_file <> ? LIMIT 1",
2465
+ );
2466
+ const stored = database.query<{ reread: string; edit: string }, [string, string]>(
2467
+ "SELECT reread, edit FROM spotlight_needs WHERE session_file = ? AND tool_call_id = ?",
2468
+ );
2469
+ const write = database.query(
2470
+ "INSERT OR REPLACE INTO spotlight_needs (session_file, tool_call_id, file, open, reread, edit) VALUES (?, ?, ?, ?, ?, ?)",
2471
+ );
2472
+ const ranges = (json: string | undefined): [number, number][] => {
2473
+ if (!json) return [];
2474
+ const value: unknown = JSON.parse(json);
2475
+ return Array.isArray(value)
2476
+ ? value.filter(
2477
+ (pair): pair is [number, number] =>
2478
+ Array.isArray(pair) && typeof pair[0] === "number" && typeof pair[1] === "number",
2479
+ )
2480
+ : [];
2481
+ };
2482
+ let changes = 0;
2483
+ atomically(database, () => {
2484
+ for (const r of rows) {
2485
+ if (claimed.get(r.toolCallId, r.sessionFile)) continue;
2486
+ const old = stored.get(r.sessionFile, r.toolCallId);
2487
+ changes += write.run(
2488
+ r.sessionFile,
2489
+ r.toolCallId,
2490
+ r.file,
2491
+ r.open ? 1 : 0,
2492
+ JSON.stringify(mergeRanges([...ranges(old?.reread), ...r.reread])),
2493
+ JSON.stringify(mergeRanges([...ranges(old?.edit), ...r.edit])),
2494
+ ).changes;
2495
+ }
2496
+ });
2497
+ return changes;
2498
+ }
2499
+
2500
+ /** Insert experiment-session tool calls; fork copies are skipped as for `tool_calls`. */
2501
+ export function insertSpotlightCalls(rows: Iterable<SpotlightCallRow>): number {
2502
+ if (!db) return 0;
2503
+ const writer = new ChunkedInsert(db, {
2504
+ verb: "INSERT OR IGNORE",
2505
+ table: "spotlight_calls",
2506
+ columns: [
2507
+ "session_file",
2508
+ "tool_call_id",
2509
+ "entry_id",
2510
+ "timestamp",
2511
+ "seq",
2512
+ "tool_name",
2513
+ "calls_in_turn",
2514
+ "target",
2515
+ "edits",
2516
+ "arg_tokens",
2517
+ ],
2518
+ identity: ["entry_id", "timestamp", "tool_call_id"],
2519
+ });
2520
+ return atomically(db, () => {
2521
+ for (const r of rows) {
2522
+ writer.add(
2523
+ r.sessionFile,
2524
+ [r.entryId, r.timestamp, r.toolCallId],
2525
+ [
2526
+ r.sessionFile,
2527
+ r.toolCallId,
2528
+ r.entryId,
2529
+ r.timestamp,
2530
+ r.seq,
2531
+ r.toolName,
2532
+ r.callsInTurn,
2533
+ r.target,
2534
+ r.edits ? JSON.stringify(r.edits) : null,
2535
+ r.argTokens ? JSON.stringify(r.argTokens) : null,
2536
+ ],
2537
+ );
2538
+ }
2539
+ return writer.finish();
2540
+ });
2541
+ }
2542
+
2543
+ /** Attach result size and named artifacts to recorded calls (results can land in a later tail parse). */
2544
+ export function updateSpotlightCallResults(links: Iterable<SpotlightCallResultLink>): number {
2545
+ if (!db) return 0;
2546
+ const stmt = db.query(`
2547
+ UPDATE spotlight_calls SET result_chars = ?, artifacts = ?
2548
+ WHERE session_file = ? AND tool_call_id = ? AND result_chars IS NULL
2549
+ `);
2550
+ let changes = 0;
2551
+ atomically(db, () => {
2552
+ for (const l of links) {
2553
+ changes += stmt.run(l.resultChars, JSON.stringify(l.artifacts), l.sessionFile, l.toolCallId).changes;
2554
+ }
2555
+ });
2556
+ return changes;
2557
+ }
2558
+
2559
+ /** Insert experiment-session main-loop requests; fork copies are skipped as for `messages`. */
2560
+ export function insertSpotlightRequests(rows: Iterable<SpotlightRequestRow>): number {
2561
+ if (!db) return 0;
2562
+ const writer = new ChunkedInsert(db, {
2563
+ verb: "INSERT OR IGNORE",
2564
+ table: "spotlight_requests",
2565
+ columns: ["session_file", "entry_id", "timestamp"],
2566
+ identity: ["entry_id", "timestamp"],
2567
+ });
2568
+ return atomically(db, () => {
2569
+ for (const r of rows)
2570
+ writer.add(r.sessionFile, [r.entryId, r.timestamp], [r.sessionFile, r.entryId, r.timestamp]);
2571
+ return writer.finish();
2572
+ });
2573
+ }
package/src/index.ts CHANGED
@@ -29,7 +29,16 @@ export { refreshRollups } from "./rollup";
29
29
  export type { StatsJudge, StatsJudgeProvider } from "./frustration";
30
30
  export { getGainDashboardStats } from "./gain-aggregator";
31
31
  export { formatStatsDashboardUrl, type StartServerOptions, setStatsCloseHandler, startServer } from "./server";
32
- export type { GainDashboardStats, GainSource, GainSourceTotals, GainTimeSeriesPoint } from "./shared-types";
32
+ export type {
33
+ GainDashboardStats,
34
+ GainSource,
35
+ GainSourceTotals,
36
+ GainTimeSeriesPoint,
37
+ SpotlightAgentScope,
38
+ SpotlightDashboardStats,
39
+ SpotlightSessionContext,
40
+ } from "./shared-types";
41
+ export { getSpotlightDashboardStats, getSpotlightSessionContext } from "./spotlight-aggregator";
33
42
  export type {
34
43
  AggregatedStats,
35
44
  DashboardStats,