@linxiraos/pi-stats 1.4.11 → 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 +7 -4
  2. package/THIRD-PARTY-NOTICES.txt +4 -5
  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 +26 -0
  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 +22 -1
  36. package/dist/types/shared-types.d.ts +419 -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 +486 -8
  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 +203 -10
  77. package/src/server.ts +42 -0
  78. package/src/shared-types.ts +453 -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
@@ -19,6 +19,15 @@ import {
19
19
  getModelDailyActivity,
20
20
  getModelHourlyActivity,
21
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";
22
31
  import type {
23
32
  AgentType,
24
33
  AssistantTextStats,
@@ -99,7 +108,7 @@ export function currentDb(): Database | null {
99
108
 
100
109
  const BACKFILL_COMPLETE = "complete";
101
110
  const BACKFILL_PENDING = "pending";
102
- const USER_MESSAGES_BACKFILL_KEY = "user_messages_v9";
111
+ const USER_MESSAGES_BACKFILL_KEY = "user_messages_v10";
103
112
  // Model-side analysis (`assistant_text`) was introduced after every existing
104
113
  // database had already burned its session backfills, so it needs its own
105
114
  // sentinel: a completed user-message backfill must never leave old sessions
@@ -135,6 +144,27 @@ const NO_CACHE_INPUT_BACKFILL_KEY = "cost_no_cache_input_v1";
135
144
  // value stored is the version that ran it), since only a catalog update can
136
145
  // price a model it could not price before.
137
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";
138
168
  function shouldResetBackfill(value: string | undefined): boolean {
139
169
  return value !== BACKFILL_COMPLETE && value !== BACKFILL_PENDING;
140
170
  }
@@ -322,12 +352,128 @@ export async function initDb(): Promise<Database> {
322
352
  key TEXT PRIMARY KEY,
323
353
  value TEXT NOT NULL
324
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;
325
438
  `);
326
439
 
327
440
  const offsetColumns = db.query("PRAGMA table_info(file_offsets)").all() as { name: string }[];
328
441
  if (!offsetColumns.some(column => column.name === "parser_state")) {
329
442
  db.run("ALTER TABLE file_offsets ADD COLUMN parser_state TEXT");
330
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
+ }
331
477
  const messageColumns = db.query("PRAGMA table_info(messages)").all() as { name: string }[];
332
478
  if (!messageColumns.some(column => column.name === "premium_requests")) {
333
479
  db.run("ALTER TABLE messages ADD COLUMN premium_requests REAL NOT NULL DEFAULT 0");
@@ -447,6 +593,11 @@ export async function initDb(): Promise<Database> {
447
593
  backfillMissingCatalogCosts(db);
448
594
  backfillNoCacheInputCosts(db);
449
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);
450
601
  ensureRollupSchema(db);
451
602
  return db;
452
603
  }
@@ -683,6 +834,67 @@ function backfillNoCacheInputCosts(database: Database): void {
683
834
  applyBackfill();
684
835
  }
685
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
+
686
898
  /** Persisted transcript identity and parser cursor used to resume stats ingestion. */
687
899
  export interface FileOffset {
688
900
  offset: number;
@@ -921,6 +1133,9 @@ export function applySessionParseResults(sessions: ParsedSession[]): {
921
1133
  }
922
1134
  }
923
1135
  if (replace) {
1136
+ for (const table of SPOTLIGHT_TABLES) {
1137
+ changes += database.query(`DELETE FROM ${table} WHERE session_file = ?`).run(sessionFile).changes;
1138
+ }
924
1139
  if (messages.length > 0) {
925
1140
  changes += database.query("DELETE FROM messages WHERE session_file = ?").run(sessionFile).changes;
926
1141
  }
@@ -953,7 +1168,14 @@ export function applySessionParseResults(sessions: ParsedSession[]): {
953
1168
  insertAssistantText(parsedRows(writes, result => result.assistantTexts)) +
954
1169
  updateUserMessageLinks(parsedRows(writes, result => result.userLinks)) +
955
1170
  insertToolCalls(parsedRows(writes, result => result.toolCalls)) +
956
- 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));
957
1179
  for (const { sessionFile, result } of sessions) {
958
1180
  if (result.parserState) {
959
1181
  setFileOffset(sessionFile, result.newOffset, result.parserState.mtimeMs, result.parserState);
@@ -1290,12 +1512,14 @@ export async function getUsageHistory(now = Date.now(), days = USAGE_HISTORY_DAY
1290
1512
  * - v9: stored judge prose (`prose` / `prose_hash`) for the frustration
1291
1513
  * judge, so every session re-parses once to populate it. Verdicts live in
1292
1514
  * `frustration_verdicts`, keyed by prose hash, which this reset never touches.
1293
- * - v10: the Chinese and voice-input lexicon layer landed (boundary-free
1294
- * patterns, because speech transcription emits one unpunctuated line), plus
1295
- * two columns: `emphasis` (the shouting proxy capitalisation cannot see -
1296
- * full-width bursts, repeated Han runs, repeated denials) and
1297
- * `unsupported_script` (prose in a script no lexicon covers, which the
1298
- * 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).
1299
1523
  *
1300
1524
  * Existing `messages` rows are unaffected - `INSERT OR IGNORE` keeps them.
1301
1525
  */
@@ -2093,3 +2317,257 @@ export function updateToolResults(links: Iterable<ToolResultLink>): number {
2093
2317
  });
2094
2318
  return updated;
2095
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,
package/src/live.ts CHANGED
@@ -25,6 +25,11 @@ const WATCH_DEBOUNCE_MS = 800;
25
25
  const FULL_SYNC_INTERVAL_MS = 5 * 60 * 1000;
26
26
  /** Minimum spacing of `version` bumps; each bump makes open pages refetch. */
27
27
  const VERSION_THROTTLE_MS = 1000;
28
+ /**
29
+ * The same while a full sync runs. Pages rebuild on the thread that ingests, so a catch-up over many transcripts would
30
+ * otherwise spend most of its time serving refetches; the held-back bump lands when the sync ends.
31
+ */
32
+ const SYNCING_VERSION_THROTTLE_MS = 15_000;
28
33
  /** Delay before retrying a failed sync (typically a lock held by another omp process). */
29
34
  const SYNC_RETRY_MS = 10_000;
30
35
  /** Minimum spacing of progress-only status events. */
@@ -169,6 +174,8 @@ export class StatsLive {
169
174
  }
170
175
  // Another process may have ingested too; its commits move SQLite's data_version.
171
176
  if (this.#externalWrites()) this.#changed();
177
+ // A full sync held its last bump back: show its data now rather than at the end of the throttle.
178
+ if (visible && this.#versionTimer) this.#advanceVersion();
172
179
  this.#emit();
173
180
  }
174
181
 
@@ -187,17 +194,22 @@ export class StatsLive {
187
194
  this.#bumpVersion();
188
195
  }
189
196
 
190
- /** Bump the data version (throttled), making open pages refetch. */
197
+ /** Bump the data version (throttled, more so during a full sync), making open pages refetch. */
191
198
  #bumpVersion(): void {
192
199
  if (this.#versionTimer) return;
193
- const wait = Math.max(0, this.#lastVersionAt + VERSION_THROTTLE_MS - Date.now());
194
- this.#versionTimer = setTimeout(() => {
195
- this.#versionTimer = null;
196
- this.#lastVersionAt = Date.now();
197
- this.#version++;
198
- this.#indexingHours = getRollupStatus().dirtyHours;
199
- this.#emit();
200
- }, wait);
200
+ const spacing = this.#sync.phase === "syncing" ? SYNCING_VERSION_THROTTLE_MS : VERSION_THROTTLE_MS;
201
+ const wait = Math.max(0, this.#lastVersionAt + spacing - Date.now());
202
+ this.#versionTimer = setTimeout(() => this.#advanceVersion(), wait);
203
+ }
204
+
205
+ /** Bump the data version now, cancelling a pending throttled bump. */
206
+ #advanceVersion(): void {
207
+ clearTimeout(this.#versionTimer ?? undefined);
208
+ this.#versionTimer = null;
209
+ this.#lastVersionAt = Date.now();
210
+ this.#version++;
211
+ this.#indexingHours = getRollupStatus().dirtyHours;
212
+ this.#emit();
201
213
  }
202
214
 
203
215
  async #refresh(): Promise<void> {