@linxiraos/pi-stats 1.5.0 → 1.5.10

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 (66) hide show
  1. package/CHANGELOG.md +25 -2
  2. package/THIRD-PARTY-NOTICES.txt +22 -11
  3. package/dist/client/favicon.ico +0 -0
  4. package/dist/client/index.css +1 -1
  5. package/dist/client/index.js +95 -94
  6. package/dist/types/aggregator.d.ts +5 -0
  7. package/dist/types/client/api.d.ts +7 -1
  8. package/dist/types/client/app/nav.d.ts +1 -1
  9. package/dist/types/client/data/formatters.d.ts +2 -2
  10. package/dist/types/client/data/range.d.ts +5 -4
  11. package/dist/types/client/data/series.d.ts +14 -2
  12. package/dist/types/client/i18n/messages/costs.d.ts +4 -4
  13. package/dist/types/client/i18n/messages/en.d.ts +86 -6
  14. package/dist/types/client/i18n/messages/gain.d.ts +2 -2
  15. package/dist/types/client/i18n/messages/nav.d.ts +2 -0
  16. package/dist/types/client/i18n/messages/tracking.d.ts +89 -0
  17. package/dist/types/client/i18n/messages/zh-CN.d.ts +1 -1
  18. package/dist/types/client/routes/TrackingRoute.d.ts +10 -0
  19. package/dist/types/client/routes/index.d.ts +1 -0
  20. package/dist/types/db.d.ts +20 -0
  21. package/dist/types/index.d.ts +1 -1
  22. package/dist/types/parser.d.ts +7 -1
  23. package/dist/types/rollup.d.ts +4 -0
  24. package/dist/types/shared-types.d.ts +88 -0
  25. package/dist/types/spotlight-aggregator.d.ts +24 -5
  26. package/dist/types/spotlight-ingest.d.ts +48 -9
  27. package/dist/types/spotlight-worker.d.ts +27 -0
  28. package/dist/types/trace.d.ts +7 -1
  29. package/dist/types/tracking.d.ts +29 -0
  30. package/dist/types/types.d.ts +5 -5
  31. package/package.json +4 -4
  32. package/src/aggregator.ts +16 -0
  33. package/src/client/App.tsx +3 -0
  34. package/src/client/api.ts +11 -0
  35. package/src/client/app/nav.ts +3 -0
  36. package/src/client/data/formatters.ts +7 -7
  37. package/src/client/data/range.ts +22 -9
  38. package/src/client/data/series.ts +33 -14
  39. package/src/client/favicon.ico +0 -0
  40. package/src/client/i18n/messages/costs.ts +4 -4
  41. package/src/client/i18n/messages/en.ts +2 -0
  42. package/src/client/i18n/messages/gain.ts +2 -2
  43. package/src/client/i18n/messages/nav.ts +2 -0
  44. package/src/client/i18n/messages/tracking.ts +91 -0
  45. package/src/client/i18n/messages/zh-CN.ts +2 -0
  46. package/src/client/routes/CostsRoute.tsx +4 -4
  47. package/src/client/routes/GainRoute.tsx +5 -4
  48. package/src/client/routes/ProvidersRoute.tsx +4 -4
  49. package/src/client/routes/TrackingRoute.tsx +262 -0
  50. package/src/client/routes/index.ts +1 -0
  51. package/src/client/routes/tracking.css +94 -0
  52. package/src/client/spotlight/Overhead.tsx +46 -1
  53. package/src/db.ts +105 -21
  54. package/src/gain-aggregator.ts +3 -6
  55. package/src/index.ts +5 -1
  56. package/src/parser.ts +75 -10
  57. package/src/rollup.ts +67 -14
  58. package/src/server.ts +57 -16
  59. package/src/shared-types.ts +98 -0
  60. package/src/spotlight-aggregator.ts +207 -45
  61. package/src/spotlight-ingest.ts +141 -37
  62. package/src/spotlight-measures.ts +117 -85
  63. package/src/spotlight-worker.ts +45 -0
  64. package/src/trace.ts +56 -20
  65. package/src/tracking.ts +394 -0
  66. package/src/types.ts +5 -5
@@ -0,0 +1,94 @@
1
+ .tracking-toolbar {
2
+ display: flex;
3
+ flex-direction: column;
4
+ gap: 10px;
5
+ padding: 14px 16px;
6
+ }
7
+
8
+ .tracking-project {
9
+ display: flex;
10
+ align-items: center;
11
+ gap: 12px;
12
+ flex-wrap: wrap;
13
+ }
14
+
15
+ .tracking-select {
16
+ min-width: min(560px, 100%);
17
+ max-width: 100%;
18
+ background: var(--raised);
19
+ color: var(--ink-1);
20
+ border: 1px solid var(--line-1);
21
+ border-radius: 8px;
22
+ padding: 7px 10px;
23
+ font: inherit;
24
+ }
25
+
26
+ .tracking-note {
27
+ margin: 0;
28
+ color: var(--ink-3);
29
+ font-size: 12px;
30
+ }
31
+
32
+ .tracking-panel {
33
+ padding: 14px 16px;
34
+ display: flex;
35
+ flex-direction: column;
36
+ gap: 10px;
37
+ }
38
+
39
+ .tracking-meta {
40
+ justify-content: space-between;
41
+ gap: 12px;
42
+ flex-wrap: wrap;
43
+ font-size: 12px;
44
+ }
45
+
46
+ .tracking-error {
47
+ margin: 0;
48
+ color: var(--bad);
49
+ font-size: 12px;
50
+ }
51
+
52
+ .tracking-doc {
53
+ margin: 0;
54
+ padding: 10px 12px;
55
+ max-height: 420px;
56
+ overflow: auto;
57
+ white-space: pre-wrap;
58
+ overflow-wrap: anywhere;
59
+ background: var(--raised);
60
+ border: 1px solid var(--line-1);
61
+ border-radius: 8px;
62
+ font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
63
+ font-size: 12px;
64
+ line-height: 1.55;
65
+ }
66
+
67
+ .tracking-list {
68
+ list-style: none;
69
+ margin: 0;
70
+ padding: 0;
71
+ display: flex;
72
+ flex-direction: column;
73
+ gap: 8px;
74
+ max-height: 420px;
75
+ overflow: auto;
76
+ }
77
+
78
+ .tracking-list-row {
79
+ display: flex;
80
+ gap: 10px;
81
+ align-items: baseline;
82
+ flex-wrap: wrap;
83
+ font-size: 12px;
84
+ }
85
+
86
+ .tracking-session summary {
87
+ cursor: pointer;
88
+ gap: 8px;
89
+ font-size: 12px;
90
+ }
91
+
92
+ .tracking-session[open] summary {
93
+ margin-bottom: 8px;
94
+ }
@@ -1,6 +1,7 @@
1
1
  import { TriangleAlert } from "lucide-react";
2
+ import { Fragment } from "react";
2
3
  import { formatCost, formatDurationMs, formatInteger } from "../data/formatters";
3
- import type { SpotlightDashboardStats, SpotlightOverhead } from "../types";
4
+ import type { SpotlightDashboardStats, SpotlightFailureCause, SpotlightOverhead } from "../types";
4
5
  import { Badge, Card, type Column, errorRateTone, Table } from "../ui";
5
6
  import { formatShare } from "./meta";
6
7
 
@@ -15,6 +16,33 @@ function Percentiles({ p50, p90 }: { p50: number | null; p90: number | null }) {
15
16
  );
16
17
  }
17
18
 
19
+ /** Causes whose code words don't read well; the rest show their code with spaces. */
20
+ const CAUSE_LABELS: Record<string, string> = { no_credential: "not signed in", transport: "network" };
21
+
22
+ /** A failure cause as the card names it: `http_502` reads "HTTP 502", any other code its words. */
23
+ function causeLabel(cause: string): string {
24
+ const http = /^http_(\d+)$/.exec(cause);
25
+ if (http) return `HTTP ${http[1]}`;
26
+ return CAUSE_LABELS[cause] ?? cause.replaceAll("_", " ");
27
+ }
28
+
29
+ /** Each cause with its share of the results that called Spotlight; its result count on hover. */
30
+ function FailureCauses({ causes }: { causes: readonly SpotlightFailureCause[] }) {
31
+ if (causes.length === 0) return <span className="dim">–</span>;
32
+ return (
33
+ <span>
34
+ {causes.map(({ cause, results, share }, i) => (
35
+ <Fragment key={cause}>
36
+ {i > 0 && <span className="dim"> · </span>}
37
+ <span className="spot-nowrap" title={`${formatInteger(results)} results`}>
38
+ {causeLabel(cause)} <span className="num">{formatShare(share)}</span>
39
+ </span>
40
+ </Fragment>
41
+ ))}
42
+ </span>
43
+ );
44
+ }
45
+
18
46
  const COLUMNS: Column<SpotlightOverhead>[] = [
19
47
  {
20
48
  key: "failures",
@@ -31,6 +59,15 @@ const COLUMNS: Column<SpotlightOverhead>[] = [
31
59
  </Badge>
32
60
  ),
33
61
  },
62
+ {
63
+ key: "causes",
64
+ header: "Failure causes",
65
+ align: "right",
66
+ sort: row => row.failureCauses[0]?.share ?? -1,
67
+ wrap: true,
68
+ title: "Why the calls failed, as shares of the results that called Spotlight. A result whose calls failed two ways counts under both; unrecorded results were journaled before pi recorded causes",
69
+ render: row => <FailureCauses causes={row.failureCauses} />,
70
+ },
34
71
  {
35
72
  key: "failedWait",
36
73
  header: "Waited on failures",
@@ -87,6 +124,7 @@ function FailureCallout({ overhead }: { overhead: SpotlightOverhead }) {
87
124
  const tone = errorRateTone(rate);
88
125
  if (tone === "ok") return null;
89
126
  const waitedMs = overhead.failedWaitMs;
127
+ const unsigned = overhead.failureCauses.find(c => c.cause === "no_credential");
90
128
  return (
91
129
  <div className="spot-callout" data-tone={tone} role="note">
92
130
  <TriangleAlert size={16} aria-hidden="true" />
@@ -103,6 +141,13 @@ function FailureCallout({ overhead }: { overhead: SpotlightOverhead }) {
103
141
  Tool calls waited <span className="num">{formatDurationMs(waitedMs)}</span> on those failures.
104
142
  </>
105
143
  )}
144
+ {unsigned && (
145
+ <>
146
+ {" "}
147
+ <span className="num">{formatShare(unsigned.share)}</span> had no Stencil sign-in: run{" "}
148
+ <code>/login</code> and choose Stencil, or set <code>STENCIL_API_KEY</code>, to restore ranking.
149
+ </>
150
+ )}
106
151
  </p>
107
152
  </div>
108
153
  </div>
package/src/db.ts CHANGED
@@ -114,7 +114,7 @@ const USER_MESSAGES_BACKFILL_KEY = "user_messages_v10";
114
114
  // sentinel: a completed user-message backfill must never leave old sessions
115
115
  // without assistant prose forever.
116
116
  const ASSISTANT_TEXT_BACKFILL_KEY = "assistant_text_v1";
117
- const USER_MESSAGE_LINKS_REPAIR_KEY = "user_message_links_v1";
117
+ const USER_MESSAGE_LINKS_REPAIR_KEY = "user_message_links_v2";
118
118
  // v2: the parser also records the served service tier per message, so a full
119
119
  // re-parse fills `service_tier` and re-derives ultrafast premium counts that the
120
120
  // v1 pass (priority only) left at zero.
@@ -384,6 +384,7 @@ export async function initDb(): Promise<Database> {
384
384
  artifacts TEXT,
385
385
  sp_calls INTEGER,
386
386
  sp_failures INTEGER,
387
+ sp_failure_causes TEXT,
387
388
  sp_ms REAL,
388
389
  sp_cost REAL,
389
390
  shape_ms REAL,
@@ -394,6 +395,7 @@ export async function initDb(): Promise<Database> {
394
395
  heat TEXT,
395
396
  kept TEXT,
396
397
  gated INTEGER NOT NULL DEFAULT 0,
398
+ windows TEXT,
397
399
  PRIMARY KEY (session_file, tool_call_id)
398
400
  ) WITHOUT ROWID;
399
401
  CREATE INDEX IF NOT EXISTS idx_spotlight_results_call ON spotlight_results(tool_call_id);
@@ -457,6 +459,10 @@ export async function initDb(): Promise<Database> {
457
459
  ["kept", "TEXT"],
458
460
  // No read was gated before this existed: the default is exact.
459
461
  ["gated", "INTEGER NOT NULL DEFAULT 0"],
462
+ // Failed calls by cause (JSON); shape entries before pi journaled it leave it NULL.
463
+ ["sp_failure_causes", "TEXT"],
464
+ // A `;`/`,` list read's windows (JSON); NULL for a single-window original, which the columns above describe.
465
+ ["windows", "TEXT"],
460
466
  ] as const) {
461
467
  if (!spotlightResultColumns.some(existing => existing.name === column)) {
462
468
  db.run(`ALTER TABLE spotlight_results ADD COLUMN ${column} ${type}`);
@@ -1698,23 +1704,24 @@ function backfillForkDuplicates(database: Database): void {
1698
1704
  }
1699
1705
 
1700
1706
  /**
1701
- * One-shot wipe of `file_offsets` to force `parseSessionFile` to re-parse
1702
- * every session from byte zero. We don't touch `user_messages`; the parser
1703
- * now emits a `UserMessageLink` for every assistant->parent pair, and the
1704
- * guarded `updateUserMessageLinks` UPDATE fixes any row whose `model` was
1705
- * left NULL by the old in-pass-only linking logic. Idempotent: gated by a
1706
- * sentinel row in `meta`.
1707
+ * Re-parse, once, every session holding a user message without a responding
1708
+ * model, by dropping its cursor; the next sync re-reads it from byte zero and
1709
+ * the guarded `updateUserMessageLinks` UPDATE fills each row whose reply is now
1710
+ * found. Every other cursor stays, so this never re-parses the whole history.
1707
1711
  */
1708
1712
  function repairUserMessageLinks(database: Database): void {
1709
- const row = database.query("SELECT value FROM meta WHERE key = ?").get(USER_MESSAGE_LINKS_REPAIR_KEY) as
1710
- | { value: string }
1711
- | undefined;
1712
- if (!shouldResetBackfill(row?.value)) return;
1713
-
1714
- database.run("DELETE FROM file_offsets");
1715
- database
1716
- .query("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)")
1717
- .run(USER_MESSAGE_LINKS_REPAIR_KEY, BACKFILL_PENDING);
1713
+ const row = database
1714
+ .query<{ value: string }, [string]>("SELECT value FROM meta WHERE key = ?")
1715
+ .get(USER_MESSAGE_LINKS_REPAIR_KEY);
1716
+ if (row?.value === BACKFILL_COMPLETE) return;
1717
+ database.transaction(() => {
1718
+ database.run(
1719
+ "DELETE FROM file_offsets WHERE session_file IN (SELECT session_file FROM user_messages WHERE model IS NULL)",
1720
+ );
1721
+ database
1722
+ .query("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)")
1723
+ .run(USER_MESSAGE_LINKS_REPAIR_KEY, BACKFILL_COMPLETE);
1724
+ })();
1718
1725
  }
1719
1726
 
1720
1727
  /**
@@ -1750,7 +1757,6 @@ export function markSessionBackfillsComplete(): void {
1750
1757
  USER_MESSAGES_BACKFILL_KEY,
1751
1758
  ASSISTANT_TEXT_BACKFILL_KEY,
1752
1759
  TOOL_CALLS_BACKFILL_KEY,
1753
- USER_MESSAGE_LINKS_REPAIR_KEY,
1754
1760
  PRIORITY_PREMIUM_REQUESTS_BACKFILL_KEY,
1755
1761
  COST_REINGEST_BACKFILL_KEY,
1756
1762
  COST_UNPRICED_BACKFILL_KEY,
@@ -1761,6 +1767,79 @@ export function markSessionBackfillsComplete(): void {
1761
1767
  apply();
1762
1768
  }
1763
1769
 
1770
+ /** Tables keyed by transcript path; orphans are purged from all of them. */
1771
+ const SESSION_FILE_TABLES = [
1772
+ "messages",
1773
+ "user_messages",
1774
+ "assistant_text",
1775
+ "tool_calls",
1776
+ "file_offsets",
1777
+ "spotlight_sessions",
1778
+ "spotlight_results",
1779
+ "spotlight_calls",
1780
+ "spotlight_requests",
1781
+ "spotlight_needs",
1782
+ ] as const;
1783
+
1784
+ export interface PruneOrphanResult {
1785
+ /** Distinct session files whose rows were removed. */
1786
+ prunedFiles: number;
1787
+ /** Total rows removed across all session-keyed tables. */
1788
+ deletedRows: number;
1789
+ }
1790
+
1791
+ /**
1792
+ * Comparison key for stored transcript paths: separators unified and case
1793
+ * folded on Windows, where lookups are case-insensitive.
1794
+ */
1795
+ function normalizeSessionFilePath(sessionFile: string): string {
1796
+ const unified = sessionFile.replaceAll("\\", "/");
1797
+ return process.platform === "win32" ? unified.toLowerCase() : unified;
1798
+ }
1799
+
1800
+ /**
1801
+ * Delete every row whose `session_file` no longer exists on disk. Deleted
1802
+ * projects (wiped transcripts, throwaway test suites) otherwise keep surfacing
1803
+ * in the feed and every aggregate, and a re-created transcript under a new
1804
+ * path would double-count the usage its predecessor recorded. Runs in one
1805
+ * transaction; the existing-file set is collected by the caller before any
1806
+ * DELETE so the comparison is a single in-memory set probe per stored path.
1807
+ */
1808
+ export function pruneOrphanSessionsInDb(database: Database, existingFiles: readonly string[]): PruneOrphanResult {
1809
+ const existing = new Set(existingFiles.map(normalizeSessionFilePath));
1810
+ const orphans = new Set<string>();
1811
+ for (const table of SESSION_FILE_TABLES) {
1812
+ const rows = database.prepare(`SELECT DISTINCT session_file FROM ${table}`).all() as {
1813
+ session_file: string;
1814
+ }[];
1815
+ for (const row of rows) {
1816
+ if (!existing.has(normalizeSessionFilePath(row.session_file))) orphans.add(row.session_file);
1817
+ }
1818
+ }
1819
+ if (orphans.size === 0) return { prunedFiles: 0, deletedRows: 0 };
1820
+
1821
+ let deletedRows = 0;
1822
+ const apply = database.transaction(() => {
1823
+ for (const sessionFile of orphans) {
1824
+ for (const table of SESSION_FILE_TABLES) {
1825
+ const result = database.prepare(`DELETE FROM ${table} WHERE session_file = ?`).run(sessionFile);
1826
+ deletedRows += Number(result.changes);
1827
+ }
1828
+ }
1829
+ });
1830
+ apply();
1831
+ return { prunedFiles: orphans.size, deletedRows };
1832
+ }
1833
+
1834
+ /**
1835
+ * {@link pruneOrphanSessionsInDb} against the module DB handle. No-op when
1836
+ * {@link initDb} has not run.
1837
+ */
1838
+ export function pruneOrphanSessions(existingFiles: readonly string[]): PruneOrphanResult {
1839
+ if (!db) return { prunedFiles: 0, deletedRows: 0 };
1840
+ return pruneOrphanSessionsInDb(db, existingFiles);
1841
+ }
1842
+
1764
1843
  /**
1765
1844
  * Insert user-message stats. Idempotent via UNIQUE(session_file, entry_id).
1766
1845
  * The fork guard matches {@link insertMessageStats}: forks copy user entries
@@ -2389,6 +2468,7 @@ export function upsertSpotlightShapes(rows: Iterable<SpotlightShapeRow>): number
2389
2468
  "artifacts",
2390
2469
  "sp_calls",
2391
2470
  "sp_failures",
2471
+ "sp_failure_causes",
2392
2472
  "sp_ms",
2393
2473
  "sp_cost",
2394
2474
  "shape_ms",
@@ -2399,11 +2479,12 @@ export function upsertSpotlightShapes(rows: Iterable<SpotlightShapeRow>): number
2399
2479
  "heat",
2400
2480
  "kept",
2401
2481
  "gated",
2482
+ "windows",
2402
2483
  ],
2403
2484
  identity: ["tool_call_id"],
2404
2485
  upsert: `ON CONFLICT(session_file, tool_call_id) DO UPDATE SET
2405
2486
  ${["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")},
2487
+ ${["original_url", "path", "start_line", "lines", "hidden", "artifacts", "sp_calls", "sp_failures", "sp_failure_causes", "sp_ms", "sp_cost", "shape_ms", "plain_chars", "plain_tokens", "capped_tokens", "heat", "kept", "windows"].map(coalesce).join(",\n")},
2407
2488
  has_details = MAX(spotlight_results.has_details, excluded.has_details),
2408
2489
  holdout = MAX(spotlight_results.holdout, excluded.holdout),
2409
2490
  score_free = MAX(spotlight_results.score_free, excluded.score_free),
@@ -2436,6 +2517,7 @@ export function upsertSpotlightShapes(rows: Iterable<SpotlightShapeRow>): number
2436
2517
  r.artifacts ? JSON.stringify(r.artifacts) : null,
2437
2518
  r.spotlight?.calls ?? null,
2438
2519
  r.spotlight?.failures ?? null,
2520
+ r.spotlight?.failureCauses ? JSON.stringify(r.spotlight.failureCauses) : null,
2439
2521
  r.spotlight?.ms ?? null,
2440
2522
  r.spotlight?.costUsd ?? null,
2441
2523
  r.shapeMs,
@@ -2446,6 +2528,7 @@ export function upsertSpotlightShapes(rows: Iterable<SpotlightShapeRow>): number
2446
2528
  o?.heat ?? null,
2447
2529
  o ? JSON.stringify(o.kept) : null,
2448
2530
  r.gated ? 1 : 0,
2531
+ o && o.windows.length > 1 ? JSON.stringify(o.windows) : null,
2449
2532
  ],
2450
2533
  );
2451
2534
  }
@@ -2463,8 +2546,8 @@ export function upsertSpotlightNeeds(rows: Iterable<SpotlightNeedRow>): number {
2463
2546
  const claimed = database.query<{ one: number }, [string, string]>(
2464
2547
  "SELECT 1 AS one FROM spotlight_needs WHERE tool_call_id = ? AND session_file <> ? LIMIT 1",
2465
2548
  );
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 = ?",
2549
+ const stored = database.query<{ file: string; reread: string; edit: string }, [string, string]>(
2550
+ "SELECT file, reread, edit FROM spotlight_needs WHERE session_file = ? AND tool_call_id = ?",
2468
2551
  );
2469
2552
  const write = database.query(
2470
2553
  "INSERT OR REPLACE INTO spotlight_needs (session_file, tool_call_id, file, open, reread, edit) VALUES (?, ?, ?, ?, ?, ?)",
@@ -2487,7 +2570,8 @@ export function upsertSpotlightNeeds(rows: Iterable<SpotlightNeedRow>): number {
2487
2570
  changes += write.run(
2488
2571
  r.sessionFile,
2489
2572
  r.toolCallId,
2490
- r.file,
2573
+ // A list read's later parse may first touch another window: the stored file stays.
2574
+ old?.file ?? r.file,
2491
2575
  r.open ? 1 : 0,
2492
2576
  JSON.stringify(mergeRanges([...ranges(old?.reread), ...r.reread])),
2493
2577
  JSON.stringify(mergeRanges([...ranges(old?.edit), ...r.edit])),
@@ -11,6 +11,7 @@ import type { Stats } from "node:fs";
11
11
  import * as fs from "node:fs/promises";
12
12
  import * as path from "node:path";
13
13
  import { getStatsDbPath, isEnoent, logger } from "@linxiraos/pi-utils";
14
+ import { format } from "@linxiraos/pi-utils/dates";
14
15
  import { getTimeRangeConfig } from "./aggregator";
15
16
  import { initDb } from "./db";
16
17
  import type { GainDashboardStats, GainSourceTotals, GainTimeSeriesPoint } from "./shared-types";
@@ -243,11 +244,6 @@ function emptyTotals(): GainSourceTotals {
243
244
  };
244
245
  }
245
246
 
246
- /** ISO date string from epoch ms, bucketed to the day. */
247
- function toDateBucket(epochMs: number): string {
248
- return new Date(epochMs).toISOString().slice(0, 10); // "YYYY-MM-DD"
249
- }
250
-
251
247
  // ---------------------------------------------------------------------------
252
248
  // Main aggregation function
253
249
  // ---------------------------------------------------------------------------
@@ -273,7 +269,8 @@ export async function getGainDashboardStats(
273
269
  snapcompactTotals.savedBytes += approxBytes;
274
270
  snapcompactTotals.hits += 1;
275
271
 
276
- const date = toDateBucket(rec.ts);
272
+ // Local calendar day, matching the dashboard's local day buckets.
273
+ const date = format(rec.ts, "yyyy-MM-dd");
277
274
  const bucket = timeMap.get(date) ?? { snapcompact: 0 };
278
275
  bucket.snapcompact += rec.savedTokens;
279
276
  timeMap.set(date, bucket);
package/src/index.ts CHANGED
@@ -38,7 +38,11 @@ export type {
38
38
  SpotlightDashboardStats,
39
39
  SpotlightSessionContext,
40
40
  } from "./shared-types";
41
- export { getSpotlightDashboardStats, getSpotlightSessionContext } from "./spotlight-aggregator";
41
+ export {
42
+ getSpotlightDashboardStats,
43
+ getSpotlightSessionContext,
44
+ smokeTestSpotlightWorker,
45
+ } from "./spotlight-aggregator";
42
46
  export type {
43
47
  AggregatedStats,
44
48
  DashboardStats,
package/src/parser.ts CHANGED
@@ -568,10 +568,66 @@ export function parseAllSessionEntries(bytes: Uint8Array): SessionEntry[] {
568
568
  return entries;
569
569
  }
570
570
 
571
- /** Rebuild the cursor state of `bytes` (a transcript prefix): the last service tier and the Spotlight state. */
572
- function scanPrefixState(bytes: Uint8Array, spotlight: SpotlightCollector): ServiceTierByFamily | undefined {
571
+ /**
572
+ * Entries that start a new request below a user message rather than lead to its reply: a `/clear` and the custom
573
+ * messages that open a user turn (a directly invoked skill, a collab peer's prompt), as pi-tui's
574
+ * `isUserTurnInitiator` defines them.
575
+ */
576
+ function startsNewRequest(entry: SessionEntry): boolean {
577
+ if (entry.type === "reset_boundary") return true;
578
+ if (entry.type !== "custom_message" || !("customType" in entry) || !("attribution" in entry)) return false;
579
+ return entry.attribution === "user" && (entry.customType === "skill-prompt" || entry.customType === "collab-prompt");
580
+ }
581
+
582
+ /**
583
+ * Links each user message to its reply across tail reads. The agent writes non-message entries (the system-prompt
584
+ * digest, extension notices, side-model usage, title changes) between a user message and its reply, so the reply is
585
+ * the first assistant message descending from the user message through such entries. Another message or a new
586
+ * request on the way ends that branch only; a sibling branch can still carry the reply.
587
+ */
588
+ class ReplyTracker {
589
+ /** User messages still awaiting a reply and the non-message entries beneath them, each to its user message. */
590
+ readonly #waiting: Map<string, string>;
591
+
592
+ constructor(waiting?: Record<string, string>) {
593
+ this.#waiting = new Map(waiting ? Object.entries(waiting) : undefined);
594
+ }
595
+
596
+ get state(): Record<string, string> {
597
+ return Object.fromEntries(this.#waiting);
598
+ }
599
+
600
+ /** The user message `entry` answers, if `entry` is an assistant message descending from it through non-message entries. */
601
+ visit(entry: SessionEntry): string | undefined {
602
+ if (isUserMessage(entry)) {
603
+ this.#waiting.set(entry.id, entry.id);
604
+ return undefined;
605
+ }
606
+ const parentId = "parentId" in entry ? entry.parentId : undefined;
607
+ const user = typeof parentId === "string" ? this.#waiting.get(parentId) : undefined;
608
+ if (!user) return undefined;
609
+ if (isAssistantMessage(entry)) {
610
+ for (const [waitingId, waitingUser] of this.#waiting) {
611
+ if (waitingUser === user) this.#waiting.delete(waitingId);
612
+ }
613
+ return user;
614
+ }
615
+ if (entry.type !== "message" && !startsNewRequest(entry) && "id" in entry && typeof entry.id === "string") {
616
+ this.#waiting.set(entry.id, user);
617
+ }
618
+ return undefined;
619
+ }
620
+ }
621
+
622
+ /** Rebuild the cursor state of `bytes` (a transcript prefix): the last service tier, the awaited replies and the Spotlight state. */
623
+ function scanPrefixState(
624
+ bytes: Uint8Array,
625
+ spotlight: SpotlightCollector,
626
+ replies: ReplyTracker,
627
+ ): ServiceTierByFamily | undefined {
573
628
  let currentServiceTier: ServiceTierByFamily | undefined;
574
629
  visitSessionEntriesLenient(bytes, entry => {
630
+ replies.visit(entry);
575
631
  if (isServiceTierChange(entry)) currentServiceTier = coerceServiceTierByFamily(entry.serviceTier);
576
632
  else spotlight.visit(entry);
577
633
  });
@@ -580,7 +636,6 @@ function scanPrefixState(bytes: Uint8Array, spotlight: SpotlightCollector): Serv
580
636
  export interface SessionParserState {
581
637
  version: 1;
582
638
  offset: number;
583
- dev: number;
584
639
  ino: number;
585
640
  birthtimeMs: number;
586
641
  size: number;
@@ -589,6 +644,8 @@ export interface SessionParserState {
589
644
  serviceTier: ServiceTierByFamily | null;
590
645
  /** Absent in cursors persisted before the Spotlight tables; such a tail parse starts from an empty state. */
591
646
  spotlight?: SpotlightParserState;
647
+ /** Absent in cursors persisted before replies were tracked; such a cursor is rebuilt from the transcript prefix. */
648
+ pendingReplies?: Record<string, string>;
592
649
  }
593
650
 
594
651
  export interface ParseSessionResult {
@@ -619,8 +676,13 @@ async function readCheckpoint(handle: fs.FileHandle, end: number): Promise<Uint8
619
676
  return bytes.subarray(0, read);
620
677
  }
621
678
 
679
+ /**
680
+ * Whether `info` is still the file a cursor was taken from. The device number is deliberately not part of
681
+ * this: ZFS and others renumber it across mounts and reboots while the transcript stays intact; `ino` +
682
+ * `birthtimeMs` (plus size/mtime at call sites) identify the file.
683
+ */
622
684
  export function matchesSessionFile(state: SessionParserState, info: nodeFs.Stats): boolean {
623
- return state.dev === info.dev && state.ino === info.ino && state.birthtimeMs === info.birthtimeMs;
685
+ return state.ino === info.ino && state.birthtimeMs === info.birthtimeMs;
624
686
  }
625
687
 
626
688
  /** Offset-only callers reconstruct service-tier state once; persisted cursors read only the appended tail. */
@@ -648,6 +710,7 @@ export async function parseSessionFile(
648
710
  // First call per id: the row `INSERT OR IGNORE` keeps, so it can be written with its result.
649
711
  const callsById = new Map<string, ToolCallStats>();
650
712
  let spotlight = new SpotlightCollector(sessionPath, folder, emptySpotlightState());
713
+ let replies = new ReplyTracker();
651
714
 
652
715
  // The previous user message, for the whole-message repetition signal. An
653
716
  // incremental parse starts mid-session, so the first message of a resumed
@@ -663,6 +726,7 @@ export async function parseSessionFile(
663
726
 
664
727
  // Reduce each entry immediately so full replays do not retain tool-output/message bodies.
665
728
  const visit = (entry: SessionEntry): void => {
729
+ const answered = replies.visit(entry);
666
730
  spotlight.visit(entry);
667
731
  if (isServiceTierChange(entry)) {
668
732
  currentServiceTier = coerceServiceTierByFamily(entry.serviceTier);
@@ -715,12 +779,11 @@ export async function parseSessionFile(
715
779
  // The next assistant turn starts a fresh failure chain.
716
780
  pendingToolErrors = 0;
717
781
  // Persist links even when the user entry was ingested in an earlier tail read.
718
- const parentId = entry.parentId;
719
782
  const msg = entry.message;
720
- if (parentId && msg.role === "assistant" && msg.model && msg.provider) {
783
+ if (answered && msg.role === "assistant" && msg.model && msg.provider) {
721
784
  userLinks.push({
722
785
  sessionFile: sessionPath,
723
- entryId: parentId,
786
+ entryId: answered,
724
787
  model: msg.model,
725
788
  provider: msg.provider,
726
789
  });
@@ -743,7 +806,8 @@ export async function parseSessionFile(
743
806
  const previous = await readCheckpoint(handle, fromOffset);
744
807
  reset = Bun.hash(previous).toString(16) !== state.checkpoint;
745
808
  }
746
- resume = !reset;
809
+ // A cursor written before replies were tracked rebuilds its state from the prefix instead.
810
+ resume = !reset && state.pendingReplies !== undefined;
747
811
  }
748
812
  if (fromOffset > info.size) reset = true;
749
813
  if (replay) resume = false;
@@ -753,9 +817,10 @@ export async function parseSessionFile(
753
817
  if (resume) {
754
818
  currentServiceTier = state?.serviceTier ?? undefined;
755
819
  spotlight = new SpotlightCollector(sessionPath, folder, state?.spotlight ?? emptySpotlightState());
820
+ replies = new ReplyTracker(state?.pendingReplies);
756
821
  } else {
757
822
  const prefix = new SpotlightCollector(sessionPath, folder, emptySpotlightState(), false);
758
- currentServiceTier = scanPrefixState(bytes.subarray(0, start), prefix);
823
+ currentServiceTier = scanPrefixState(bytes.subarray(0, start), prefix, replies);
759
824
  spotlight = new SpotlightCollector(sessionPath, folder, prefix.state);
760
825
  }
761
826
  read = visitSessionEntriesLenient(bytes.subarray(start - readStart), visit);
@@ -799,7 +864,6 @@ export async function parseSessionFile(
799
864
  parserState: {
800
865
  version: 1,
801
866
  offset: newOffset,
802
- dev: info.dev,
803
867
  ino: info.ino,
804
868
  birthtimeMs: info.birthtimeMs,
805
869
  size: info.size,
@@ -807,6 +871,7 @@ export async function parseSessionFile(
807
871
  checkpoint,
808
872
  serviceTier: currentServiceTier ?? null,
809
873
  spotlight: spotlight.state,
874
+ pendingReplies: replies.state,
810
875
  },
811
876
  };
812
877
  }