@linxiraos/pi-stats 1.4.6 → 1.4.9

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 (47) hide show
  1. package/CHANGELOG.md +15 -1
  2. package/README.md +18 -18
  3. package/dist/client/index.js +86 -86
  4. package/dist/types/chunked-insert.d.ts +32 -0
  5. package/dist/types/client/api.d.ts +4 -0
  6. package/dist/types/client/app/CloseButton.d.ts +7 -0
  7. package/dist/types/client/app/keys.d.ts +9 -0
  8. package/dist/types/client/traces/SpanDrawer.d.ts +9 -3
  9. package/dist/types/client/traces/TimelineCanvas.d.ts +3 -1
  10. package/dist/types/client/traces/TraceView.d.ts +13 -0
  11. package/dist/types/client/traces/index.d.ts +5 -0
  12. package/dist/types/client/traces/trace-colors.d.ts +3 -1
  13. package/dist/types/client/ui/SearchInput.d.ts +2 -1
  14. package/dist/types/db.d.ts +5 -5
  15. package/dist/types/index.d.ts +1 -1
  16. package/dist/types/parser.d.ts +1 -1
  17. package/dist/types/port-conflict.d.ts +9 -3
  18. package/dist/types/server.d.ts +14 -3
  19. package/dist/types/shared-types.d.ts +3 -2
  20. package/dist/types/trace.d.ts +27 -1
  21. package/dist/types/types.d.ts +6 -1
  22. package/package.json +12 -10
  23. package/src/chunked-insert.ts +89 -0
  24. package/src/client/api.ts +13 -0
  25. package/src/client/app/CloseButton.tsx +56 -0
  26. package/src/client/app/Shell.tsx +4 -11
  27. package/src/client/app/keys.ts +21 -0
  28. package/src/client/data/query.ts +12 -4
  29. package/src/client/react-css.d.ts +8 -0
  30. package/src/client/traces/SpanDrawer.tsx +58 -10
  31. package/src/client/traces/TimelineCanvas.tsx +13 -4
  32. package/src/client/traces/TraceView.tsx +171 -153
  33. package/src/client/traces/TranscriptList.tsx +1 -1
  34. package/src/client/traces/index.ts +5 -0
  35. package/src/client/traces/trace-colors.ts +14 -10
  36. package/src/client/ui/Card.tsx +2 -2
  37. package/src/client/ui/Drawer.tsx +2 -2
  38. package/src/client/ui/SearchInput.tsx +9 -1
  39. package/src/client/ui/Stat.tsx +2 -5
  40. package/src/db.ts +203 -151
  41. package/src/index.ts +1 -1
  42. package/src/parser.ts +22 -6
  43. package/src/port-conflict.ts +67 -30
  44. package/src/server.ts +63 -31
  45. package/src/shared-types.ts +3 -2
  46. package/src/trace.ts +119 -35
  47. package/src/types.ts +6 -1
@@ -1,4 +1,4 @@
1
- import type { CSSProperties, ReactNode } from "react";
1
+ import type { ReactNode } from "react";
2
2
 
3
3
  export interface CardProps {
4
4
  title?: ReactNode;
@@ -22,7 +22,7 @@ export function Card({ title, description, actions, flush, footer, className, in
22
22
  return (
23
23
  <section
24
24
  className={className ? `card rise ${className}` : "card rise"}
25
- style={index !== undefined ? ({ "--i": index } as CSSProperties) : undefined}
25
+ style={index !== undefined ? { "--i": index } : undefined}
26
26
  >
27
27
  {hasHeader && (
28
28
  <header className="card-header">
@@ -1,5 +1,5 @@
1
1
  import { X } from "lucide-react";
2
- import { type CSSProperties, type ReactNode, useEffect, useRef } from "react";
2
+ import { type ReactNode, useEffect, useRef } from "react";
3
3
  import { createPortal } from "react-dom";
4
4
 
5
5
  export interface DrawerProps {
@@ -50,7 +50,7 @@ export function Drawer({ open, onClose, title, subtitle, actions, width, childre
50
50
  role="dialog"
51
51
  aria-modal="true"
52
52
  tabIndex={-1}
53
- style={width !== undefined ? ({ "--drawer-w": `${width}px` } as CSSProperties) : undefined}
53
+ style={width !== undefined ? { "--drawer-w": `${width}px` } : undefined}
54
54
  >
55
55
  <header className="drawer-header">
56
56
  <div className="drawer-titles">
@@ -5,17 +5,25 @@ export interface SearchInputProps {
5
5
  value: string;
6
6
  onChange: (value: string) => void;
7
7
  placeholder?: string;
8
+ label?: string;
8
9
  width?: number;
9
10
  }
10
11
 
11
12
  /** Text filter with a leading search glyph. */
12
- export function SearchInput({ value, onChange, placeholder = t("common.filter"), width }: SearchInputProps) {
13
+ export function SearchInput({
14
+ value,
15
+ onChange,
16
+ placeholder = t("common.filter"),
17
+ label = "Filter",
18
+ width,
19
+ }: SearchInputProps) {
13
20
  return (
14
21
  <label className="search">
15
22
  <Search size={14} />
16
23
  <input
17
24
  className="input"
18
25
  type="search"
26
+ aria-label={label}
19
27
  value={value}
20
28
  placeholder={placeholder}
21
29
  onChange={e => onChange(e.target.value)}
@@ -1,4 +1,4 @@
1
- import { type CSSProperties, type ReactNode, useEffect, useRef, useState } from "react";
1
+ import { type ReactNode, useEffect, useRef, useState } from "react";
2
2
  import { Sparkline } from "../charts/Sparkline";
3
3
 
4
4
  export interface StatDelta {
@@ -58,10 +58,7 @@ export interface StatGridProps {
58
58
  /** Tiles sharing one card, separated by hairlines. */
59
59
  export function StatGrid({ min, children }: StatGridProps) {
60
60
  return (
61
- <div
62
- className="stat-grid rise"
63
- style={min !== undefined ? ({ "--stat-min": `${min}px` } as CSSProperties) : undefined}
64
- >
61
+ <div className="stat-grid rise" style={min !== undefined ? { "--stat-min": `${min}px` } : undefined}>
65
62
  {children}
66
63
  </div>
67
64
  );
package/src/db.ts CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  } from "@linxiraos/pi-catalog/models";
12
12
  import type { ModelCost } from "@linxiraos/pi-catalog/types";
13
13
  import { getConfigRootDir, getStatsDbPath, VERSION } from "@linxiraos/pi-utils";
14
+ import { ChunkedInsert } from "./chunked-insert";
14
15
  import { classifyAgentType, type ParseSessionResult, type SessionParserState } from "./parser";
15
16
  import { ensureRollupSchema, getDailyActivityFromRollup } from "./rollup";
16
17
  import type {
@@ -107,7 +108,8 @@ const FORK_DEDUPE_KEY = "fork_dedupe_v1";
107
108
  // v2: tool-name sanitization at ingest (see `sanitizeToolName` in parser.ts)
108
109
  // collapses provider-side garbage names; a full re-parse replaces the polluted
109
110
  // rows already stored in existing databases.
110
- const TOOL_CALLS_BACKFILL_KEY = "tool_calls_v2";
111
+ // v3: reclassify synthetic non-executions so historical tool error rates are corrected.
112
+ const TOOL_CALLS_BACKFILL_KEY = "tool_calls_v3";
111
113
  // Older ingests dropped `Usage.orchestration` (never a stored column) when
112
114
  // pricing, so subscription models billed on orchestration tokens — multi-agent
113
115
  // Grok most notably — were priced from conversation buckets alone and could not
@@ -143,6 +145,17 @@ export async function initDb(): Promise<Database> {
143
145
  // https://github.com/can1357/oh-my-pi/issues/2421.
144
146
  db.run("PRAGMA busy_timeout = 5000");
145
147
  db.run("PRAGMA journal_mode = WAL");
148
+ // The database is a derived cache of the transcripts, so WAL's NORMAL sync
149
+ // (fsync only at checkpoints) is safe: a crash can drop the newest batches,
150
+ // which the next sync re-ingests from their unchanged cursors. Rarer, larger
151
+ // checkpoints cut the F_FULLFSYNC stalls macOS pays per checkpoint. The
152
+ // statement journal and temp b-tree every trigger-carrying insert opens stay
153
+ // in memory instead of a temp file, and a 64 MiB page cache (default 8 MiB)
154
+ // keeps more index pages of a multi-GB database resident between batches.
155
+ db.run("PRAGMA synchronous = NORMAL");
156
+ db.run("PRAGMA temp_store = MEMORY");
157
+ db.run("PRAGMA cache_size = -65536");
158
+ db.run("PRAGMA wal_autocheckpoint = 16384");
146
159
 
147
160
  // Whether `messages` predates this init — drives the one-time agent_type
148
161
  // backfill below, so it must be sampled before CREATE TABLE adds the table.
@@ -182,11 +195,17 @@ export async function initDb(): Promise<Database> {
182
195
  UNIQUE(session_file, entry_id)
183
196
  );
184
197
 
185
- CREATE INDEX IF NOT EXISTS idx_messages_timestamp ON messages(timestamp);
186
- CREATE INDEX IF NOT EXISTS idx_messages_entry_timestamp ON messages(entry_id, timestamp);
198
+ -- Fork-guard identity lookups key on (entry_id, timestamp). Time-first
199
+ -- keeps one transcript's rows in a few neighbouring leaves; entry-first
200
+ -- scattered every insert, delete and lookup across the whole index. The
201
+ -- composite also serves every timestamp range scan.
202
+ DROP INDEX IF EXISTS idx_messages_timestamp;
203
+ DROP INDEX IF EXISTS idx_messages_entry_timestamp;
204
+ CREATE INDEX IF NOT EXISTS idx_messages_timestamp_entry ON messages(timestamp, entry_id);
187
205
  CREATE INDEX IF NOT EXISTS idx_messages_model ON messages(model);
188
206
  CREATE INDEX IF NOT EXISTS idx_messages_folder ON messages(folder);
189
- CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_file);
207
+ -- UNIQUE(session_file, entry_id) already indexes session_file lookups.
208
+ DROP INDEX IF EXISTS idx_messages_session;
190
209
  CREATE INDEX IF NOT EXISTS idx_messages_timestamp_model_provider ON messages(timestamp, model, provider);
191
210
  CREATE INDEX IF NOT EXISTS idx_messages_timestamp_folder ON messages(timestamp, folder);
192
211
  CREATE INDEX IF NOT EXISTS idx_messages_stop_reason_timestamp ON messages(stop_reason, timestamp);
@@ -221,8 +240,9 @@ export async function initDb(): Promise<Database> {
221
240
  UNIQUE(session_file, entry_id)
222
241
  );
223
242
 
224
- CREATE INDEX IF NOT EXISTS idx_user_messages_timestamp ON user_messages(timestamp);
225
- CREATE INDEX IF NOT EXISTS idx_user_messages_entry_timestamp ON user_messages(entry_id, timestamp);
243
+ DROP INDEX IF EXISTS idx_user_messages_timestamp;
244
+ DROP INDEX IF EXISTS idx_user_messages_entry_timestamp;
245
+ CREATE INDEX IF NOT EXISTS idx_user_messages_timestamp_entry ON user_messages(timestamp, entry_id);
226
246
  CREATE INDEX IF NOT EXISTS idx_user_messages_timestamp_model ON user_messages(timestamp, model, provider);
227
247
 
228
248
  -- Model-side analysis: one row per assistant turn that produced prose.
@@ -286,8 +306,9 @@ export async function initDb(): Promise<Database> {
286
306
  UNIQUE(session_file, tool_call_id)
287
307
  );
288
308
 
289
- CREATE INDEX IF NOT EXISTS idx_tool_calls_timestamp ON tool_calls(timestamp);
290
- CREATE INDEX IF NOT EXISTS idx_tool_calls_entry_timestamp ON tool_calls(entry_id, timestamp);
309
+ DROP INDEX IF EXISTS idx_tool_calls_timestamp;
310
+ DROP INDEX IF EXISTS idx_tool_calls_entry_timestamp;
311
+ CREATE INDEX IF NOT EXISTS idx_tool_calls_timestamp_entry ON tool_calls(timestamp, entry_id);
291
312
  CREATE INDEX IF NOT EXISTS idx_tool_calls_tool_timestamp ON tool_calls(tool_name, timestamp);
292
313
 
293
314
  CREATE TABLE IF NOT EXISTS meta (
@@ -398,7 +419,7 @@ export async function initDb(): Promise<Database> {
398
419
  prose_hash TEXT NOT NULL DEFAULT '',
399
420
  UNIQUE(session_file, entry_id)
400
421
  );
401
- CREATE INDEX IF NOT EXISTS idx_user_messages_timestamp ON user_messages(timestamp);
422
+ CREATE INDEX IF NOT EXISTS idx_user_messages_timestamp_entry ON user_messages(timestamp, entry_id);
402
423
  CREATE INDEX IF NOT EXISTS idx_user_messages_timestamp_model ON user_messages(timestamp, model, provider);
403
424
  `);
404
425
  } else if (!userMessageColumns.some(column => column.name === "prose")) {
@@ -725,6 +746,17 @@ export function setFileOffset(
725
746
  stmt.run(sessionFile, offset, lastModified, parserState ? JSON.stringify(parserState) : null);
726
747
  }
727
748
 
749
+ /**
750
+ * Run `fn` atomically: inline when the caller already holds a transaction,
751
+ * otherwise in a fresh one. Nesting `db.transaction` would open a savepoint,
752
+ * which copies every page the batch touches into the statement journal; each
753
+ * statement end then rewinds that ever-growing journal, so a long batch
754
+ * degrades quadratically.
755
+ */
756
+ function atomically<T>(database: Database, fn: () => T): T {
757
+ return database.inTransaction ? fn() : database.transaction(fn)();
758
+ }
759
+
728
760
  /** Parsed transcript queued by the sync loop for an atomic database batch. */
729
761
  export interface ParsedSession {
730
762
  sessionFile: string;
@@ -954,7 +986,7 @@ export function completeSessionSync(reconcile: boolean): void {
954
986
  * `provider`, token counts, and `responseId`. The `UNIQUE(session_file,
955
987
  * entry_id)` constraint alone keys each row by file, so without the guard
956
988
  * below the same provider request would land twice and inflate every
957
- * aggregate. The `WHERE NOT EXISTS` clause skips inserts whose
989
+ * aggregate. The {@link ChunkedInsert} fork guard skips inserts whose
958
990
  * `(entry_id, timestamp)` already exists under a different `session_file` —
959
991
  * first-write-wins across the lineage. Same-file re-syncs still hit the
960
992
  * `ON CONFLICT(session_file, entry_id)` upsert below, which re-derives the
@@ -963,21 +995,39 @@ export function completeSessionSync(reconcile: boolean): void {
963
995
  */
964
996
  export function insertMessageStats(stats: Iterable<MessageStatsInput>): number {
965
997
  if (!db) return 0;
966
-
967
- const stmt = db.query(`
968
- INSERT INTO messages (
969
- session_file, entry_id, folder, model, provider, api, timestamp,
970
- duration, ttft, stop_reason, error_message,
971
- input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, total_tokens, premium_requests,
972
- cost_input, cost_output, cost_cache_read, cost_cache_write, cost_total, cost_no_cache_input,
973
- cost_unpriced, agent_type, service_tier
974
- )
975
- SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
976
- WHERE NOT EXISTS (
977
- SELECT 1 FROM messages
978
- WHERE entry_id = ? AND timestamp = ? AND session_file <> ?
979
- )
980
- ON CONFLICT(session_file, entry_id) DO UPDATE SET
998
+ const writer = new ChunkedInsert(db, {
999
+ verb: "INSERT",
1000
+ table: "messages",
1001
+ columns: [
1002
+ "session_file",
1003
+ "entry_id",
1004
+ "folder",
1005
+ "model",
1006
+ "provider",
1007
+ "api",
1008
+ "timestamp",
1009
+ "duration",
1010
+ "ttft",
1011
+ "stop_reason",
1012
+ "error_message",
1013
+ "input_tokens",
1014
+ "output_tokens",
1015
+ "cache_read_tokens",
1016
+ "cache_write_tokens",
1017
+ "total_tokens",
1018
+ "premium_requests",
1019
+ "cost_input",
1020
+ "cost_output",
1021
+ "cost_cache_read",
1022
+ "cost_cache_write",
1023
+ "cost_total",
1024
+ "cost_no_cache_input",
1025
+ "cost_unpriced",
1026
+ "agent_type",
1027
+ "service_tier",
1028
+ ],
1029
+ identity: ["entry_id", "timestamp"],
1030
+ upsert: `ON CONFLICT(session_file, entry_id) DO UPDATE SET
981
1031
  premium_requests = MAX(messages.premium_requests, excluded.premium_requests),
982
1032
  cost_input = excluded.cost_input,
983
1033
  cost_output = excluded.cost_output,
@@ -986,53 +1036,47 @@ export function insertMessageStats(stats: Iterable<MessageStatsInput>): number {
986
1036
  cost_total = excluded.cost_total,
987
1037
  cost_no_cache_input = excluded.cost_no_cache_input,
988
1038
  cost_unpriced = excluded.cost_unpriced,
989
- service_tier = excluded.service_tier
990
- `);
991
-
992
- let inserted = 0;
993
- const insert = db.transaction(() => {
1039
+ service_tier = excluded.service_tier`,
1040
+ });
1041
+ return atomically(db, () => {
994
1042
  for (const s of stats) {
995
1043
  const { cost, unpriced } = resolveStoredCost(s);
996
1044
  const noCacheInputCost = calculateNoCacheInputCost(s.provider, s.model, s.usage, s.timestamp) ?? 0;
997
- const result = stmt.run(
998
- s.sessionFile,
999
- s.entryId,
1000
- s.folder,
1001
- s.model,
1002
- s.provider,
1003
- s.api,
1004
- s.timestamp,
1005
- s.duration,
1006
- s.ttft,
1007
- s.stopReason,
1008
- s.errorMessage,
1009
- s.usage.input,
1010
- s.usage.output,
1011
- s.usage.cacheRead,
1012
- s.usage.cacheWrite,
1013
- s.usage.totalTokens,
1014
- s.usage.premiumRequests ?? 0,
1015
- cost.input,
1016
- cost.output,
1017
- cost.cacheRead,
1018
- cost.cacheWrite,
1019
- cost.total,
1020
- noCacheInputCost,
1021
- unpriced ? 1 : 0,
1022
- s.agentType,
1023
- s.serviceTier ?? null,
1024
- // `WHERE NOT EXISTS` binds: skip when a different session_file
1025
- // already holds this (entry_id, timestamp).
1026
- s.entryId,
1027
- s.timestamp,
1045
+ writer.add(
1028
1046
  s.sessionFile,
1047
+ [s.entryId, s.timestamp],
1048
+ [
1049
+ s.sessionFile,
1050
+ s.entryId,
1051
+ s.folder,
1052
+ s.model,
1053
+ s.provider,
1054
+ s.api,
1055
+ s.timestamp,
1056
+ s.duration,
1057
+ s.ttft,
1058
+ s.stopReason,
1059
+ s.errorMessage,
1060
+ s.usage.input,
1061
+ s.usage.output,
1062
+ s.usage.cacheRead,
1063
+ s.usage.cacheWrite,
1064
+ s.usage.totalTokens,
1065
+ s.usage.premiumRequests ?? 0,
1066
+ cost.input,
1067
+ cost.output,
1068
+ cost.cacheRead,
1069
+ cost.cacheWrite,
1070
+ cost.total,
1071
+ noCacheInputCost,
1072
+ unpriced ? 1 : 0,
1073
+ s.agentType,
1074
+ s.serviceTier ?? null,
1075
+ ],
1029
1076
  );
1030
- if (result.changes > 0) inserted++;
1031
1077
  }
1078
+ return writer.finish();
1032
1079
  });
1033
-
1034
- insert();
1035
- return inserted;
1036
1080
  }
1037
1081
 
1038
1082
  /**
@@ -1446,60 +1490,66 @@ export function markSessionBackfillsComplete(): void {
1446
1490
 
1447
1491
  /**
1448
1492
  * Insert user-message stats. Idempotent via UNIQUE(session_file, entry_id).
1449
- * The `WHERE NOT EXISTS` clause matches {@link insertMessageStats}: forks
1450
- * copy user entries verbatim into the child JSONL, so the same
1451
- * `(entry_id, timestamp)` must not land twice across different session files.
1493
+ * The fork guard matches {@link insertMessageStats}: forks copy user entries
1494
+ * verbatim into the child JSONL, so the same `(entry_id, timestamp)` must not
1495
+ * land twice across different session files.
1452
1496
  */
1453
1497
  export function insertUserMessageStats(stats: Iterable<UserMessageStats>): number {
1454
1498
  if (!db) return 0;
1455
-
1456
- const stmt = db.query(`
1457
- INSERT OR IGNORE INTO user_messages (
1458
- session_file, entry_id, folder, timestamp, model, provider,
1459
- chars, words, yelling, profanity, anguish,
1460
- negation, repetition, blame, emphasis, unsupported_script,
1461
- prose, prose_hash
1462
- )
1463
- SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
1464
- WHERE NOT EXISTS (
1465
- SELECT 1 FROM user_messages
1466
- WHERE entry_id = ? AND timestamp = ? AND session_file <> ?
1467
- )
1468
- `);
1469
-
1470
- let inserted = 0;
1471
- const insert = db.transaction(() => {
1499
+ const writer = new ChunkedInsert(db, {
1500
+ verb: "INSERT OR IGNORE",
1501
+ table: "user_messages",
1502
+ columns: [
1503
+ "session_file",
1504
+ "entry_id",
1505
+ "folder",
1506
+ "timestamp",
1507
+ "model",
1508
+ "provider",
1509
+ "chars",
1510
+ "words",
1511
+ "yelling",
1512
+ "profanity",
1513
+ "anguish",
1514
+ "negation",
1515
+ "repetition",
1516
+ "blame",
1517
+ "emphasis",
1518
+ "unsupported_script",
1519
+ "prose",
1520
+ "prose_hash",
1521
+ ],
1522
+ identity: ["entry_id", "timestamp"],
1523
+ });
1524
+ return atomically(db, () => {
1472
1525
  for (const s of stats) {
1473
- const result = stmt.run(
1474
- s.sessionFile,
1475
- s.entryId,
1476
- s.folder,
1477
- s.timestamp,
1478
- s.model,
1479
- s.provider,
1480
- s.chars,
1481
- s.words,
1482
- s.yelling,
1483
- s.profanity,
1484
- s.anguish,
1485
- s.negation,
1486
- s.repetition,
1487
- s.blame,
1488
- s.emphasis,
1489
- s.unsupportedScript,
1490
- s.prose,
1491
- s.proseHash,
1492
- // `WHERE NOT EXISTS` binds: skip when a different session_file
1493
- // already holds this (entry_id, timestamp).
1494
- s.entryId,
1495
- s.timestamp,
1526
+ writer.add(
1496
1527
  s.sessionFile,
1528
+ [s.entryId, s.timestamp],
1529
+ [
1530
+ s.sessionFile,
1531
+ s.entryId,
1532
+ s.folder,
1533
+ s.timestamp,
1534
+ s.model,
1535
+ s.provider,
1536
+ s.chars,
1537
+ s.words,
1538
+ s.yelling,
1539
+ s.profanity,
1540
+ s.anguish,
1541
+ s.negation,
1542
+ s.repetition,
1543
+ s.blame,
1544
+ s.emphasis,
1545
+ s.unsupportedScript,
1546
+ s.prose,
1547
+ s.proseHash,
1548
+ ],
1497
1549
  );
1498
- if (result.changes > 0) inserted++;
1499
1550
  }
1551
+ return writer.finish();
1500
1552
  });
1501
- insert();
1502
- return inserted;
1503
1553
  }
1504
1554
 
1505
1555
  /**
@@ -1577,13 +1627,12 @@ export function updateUserMessageLinks(links: Iterable<UserMessageLink>): number
1577
1627
  `);
1578
1628
 
1579
1629
  let updated = 0;
1580
- const apply = db.transaction(() => {
1630
+ atomically(db, () => {
1581
1631
  for (const link of links) {
1582
1632
  const result = stmt.run(link.model, link.provider, link.sessionFile, link.entryId);
1583
1633
  if (result.changes > 0) updated++;
1584
1634
  }
1585
1635
  });
1586
- apply();
1587
1636
  return updated;
1588
1637
  }
1589
1638
 
@@ -1915,7 +1964,7 @@ export function upsertFrustrationVerdicts(verdicts: readonly FrustrationVerdict[
1915
1964
 
1916
1965
  /**
1917
1966
  * Insert tool-call rows. Idempotent via UNIQUE(session_file, tool_call_id);
1918
- * the `WHERE NOT EXISTS` guard mirrors {@link insertMessageStats}: forked
1967
+ * the fork guard mirrors {@link insertMessageStats}: forked
1919
1968
  * sessions deep-copy assistant entries (same `entry_id`, `timestamp`, and
1920
1969
  * tool-call ids under a new file), so first-write-wins across the lineage
1921
1970
  * keeps aggregates from double counting. Keyed on the assistant entry
@@ -1924,46 +1973,50 @@ export function upsertFrustrationVerdicts(verdicts: readonly FrustrationVerdict[
1924
1973
  */
1925
1974
  export function insertToolCalls(calls: Iterable<ToolCallStats>): number {
1926
1975
  if (!db) return 0;
1927
-
1928
- const stmt = db.query(`
1929
- INSERT OR IGNORE INTO tool_calls (
1930
- session_file, entry_id, tool_call_id, folder, tool_name,
1931
- model, provider, timestamp, agent_type, calls_in_turn, args_chars
1932
- )
1933
- SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
1934
- WHERE NOT EXISTS (
1935
- SELECT 1 FROM tool_calls
1936
- WHERE entry_id = ? AND timestamp = ? AND tool_call_id = ? AND session_file <> ?
1937
- )
1938
- `);
1939
-
1940
- let inserted = 0;
1941
- const insert = db.transaction(() => {
1976
+ const writer = new ChunkedInsert(db, {
1977
+ verb: "INSERT OR IGNORE",
1978
+ table: "tool_calls",
1979
+ columns: [
1980
+ "session_file",
1981
+ "entry_id",
1982
+ "tool_call_id",
1983
+ "folder",
1984
+ "tool_name",
1985
+ "model",
1986
+ "provider",
1987
+ "timestamp",
1988
+ "agent_type",
1989
+ "calls_in_turn",
1990
+ "args_chars",
1991
+ "result_chars",
1992
+ "is_error",
1993
+ ],
1994
+ identity: ["entry_id", "timestamp", "tool_call_id"],
1995
+ });
1996
+ return atomically(db, () => {
1942
1997
  for (const c of calls) {
1943
- const result = stmt.run(
1944
- c.sessionFile,
1945
- c.entryId,
1946
- c.toolCallId,
1947
- c.folder,
1948
- c.toolName,
1949
- c.model,
1950
- c.provider,
1951
- c.timestamp,
1952
- c.agentType,
1953
- c.callsInTurn,
1954
- c.argsChars,
1955
- // `WHERE NOT EXISTS` binds: skip when a different session_file
1956
- // already holds this (entry_id, timestamp, tool_call_id).
1957
- c.entryId,
1958
- c.timestamp,
1959
- c.toolCallId,
1998
+ writer.add(
1960
1999
  c.sessionFile,
2000
+ [c.entryId, c.timestamp, c.toolCallId],
2001
+ [
2002
+ c.sessionFile,
2003
+ c.entryId,
2004
+ c.toolCallId,
2005
+ c.folder,
2006
+ c.toolName,
2007
+ c.model,
2008
+ c.provider,
2009
+ c.timestamp,
2010
+ c.agentType,
2011
+ c.callsInTurn,
2012
+ c.argsChars,
2013
+ c.resultChars ?? null,
2014
+ c.isError === undefined ? null : c.isError ? 1 : 0,
2015
+ ],
1961
2016
  );
1962
- if (result.changes > 0) inserted++;
1963
2017
  }
2018
+ return writer.finish();
1964
2019
  });
1965
- insert();
1966
- return inserted;
1967
2020
  }
1968
2021
 
1969
2022
  /**
@@ -1983,12 +2036,11 @@ export function updateToolResults(links: Iterable<ToolResultLink>): number {
1983
2036
  `);
1984
2037
 
1985
2038
  let updated = 0;
1986
- const apply = db.transaction(() => {
2039
+ atomically(db, () => {
1987
2040
  for (const link of links) {
1988
2041
  const result = stmt.run(link.resultChars, link.isError ? 1 : 0, link.sessionFile, link.toolCallId);
1989
2042
  updated += result.changes;
1990
2043
  }
1991
2044
  });
1992
- apply();
1993
2045
  return updated;
1994
2046
  }
package/src/index.ts CHANGED
@@ -28,7 +28,7 @@ export { closeDb } from "./db";
28
28
  export { refreshRollups } from "./rollup";
29
29
  export type { StatsJudge, StatsJudgeProvider } from "./frustration";
30
30
  export { getGainDashboardStats } from "./gain-aggregator";
31
- export { formatStatsDashboardUrl, type StartServerOptions, startServer } from "./server";
31
+ export { formatStatsDashboardUrl, type StartServerOptions, setStatsCloseHandler, startServer } from "./server";
32
32
  export type { GainDashboardStats, GainSource, GainSourceTotals, GainTimeSeriesPoint } from "./shared-types";
33
33
  export type {
34
34
  AggregatedStats,
package/src/parser.ts CHANGED
@@ -481,6 +481,13 @@ function sanitizeToolName(name: string): string | null {
481
481
  return candidate.length > 0 ? candidate : null;
482
482
  }
483
483
 
484
+ /** A call the agent loop skipped carries a synthetic `executed: false` result: it never ran, so it is no tool error. */
485
+ function isToolExecutionError(message: { isError?: unknown; details?: unknown }): boolean {
486
+ if (message.isError !== true) return false;
487
+ const details = message.details as { __synthetic?: unknown; executed?: unknown } | null | undefined;
488
+ return !(details?.__synthetic === true && details.executed === false);
489
+ }
490
+
484
491
  /**
485
492
  * Build the result linkage for a `toolResult` entry: text characters fed back
486
493
  * into context plus the error flag, keyed to the originating call.
@@ -500,7 +507,7 @@ function extractToolResultLink(sessionFile: string, entry: SessionMessageEntry):
500
507
  sessionFile,
501
508
  toolCallId: msg.toolCallId,
502
509
  resultChars,
503
- isError: msg.isError === true,
510
+ isError: isToolExecutionError(msg),
504
511
  };
505
512
  }
506
513
 
@@ -620,6 +627,8 @@ export async function parseSessionFile(
620
627
  const userLinks: UserMessageLink[] = [];
621
628
  const toolCalls: ToolCallStats[] = [];
622
629
  const toolResults: ToolResultLink[] = [];
630
+ // First call per id: the row `INSERT OR IGNORE` keeps, so it can be written with its result.
631
+ const callsById = new Map<string, ToolCallStats>();
623
632
 
624
633
  // The previous user message, for the whole-message repetition signal. An
625
634
  // incremental parse starts mid-session, so the first message of a resumed
@@ -649,9 +658,13 @@ export async function parseSessionFile(
649
658
  }
650
659
  if (isToolResultMessage(entry)) {
651
660
  const link = extractToolResultLink(sessionPath, entry);
652
- if (link) {
653
- toolResults.push(link);
654
- if (link.isError) pendingToolErrors++;
661
+ if (!link) return;
662
+ toolResults.push(link);
663
+ if (link.isError) pendingToolErrors++;
664
+ const call = callsById.get(link.toolCallId);
665
+ if (call && call.resultChars === undefined) {
666
+ call.resultChars = link.resultChars;
667
+ call.isError = link.isError;
655
668
  }
656
669
  return;
657
670
  }
@@ -663,7 +676,10 @@ export async function parseSessionFile(
663
676
  if (isAssistantMessage(entry)) {
664
677
  const msgStats = extractStats(sessionPath, folder, entry, currentServiceTier, agentType);
665
678
  if (msgStats) stats.push(msgStats);
666
- toolCalls.push(...extractToolCalls(sessionPath, folder, entry, agentType));
679
+ for (const call of extractToolCalls(sessionPath, folder, entry, agentType)) {
680
+ toolCalls.push(call);
681
+ if (!callsById.has(call.toolCallId)) callsById.set(call.toolCallId, call);
682
+ }
667
683
  const textStats = extractAssistantTextStats(
668
684
  sessionPath,
669
685
  folder,
@@ -785,7 +801,7 @@ export async function listSessionFolders(): Promise<string[]> {
785
801
  * transcripts, never transcripts of their own; a killed run can leave one
786
802
  * behind until the next `zetacode gc --compress --apply` removes it.
787
803
  */
788
- export const COMPRESS_SCRATCH_PREFIX = ".omp-gc-compress-";
804
+ export const COMPRESS_SCRATCH_PREFIX = ".zeta-gc-compress-";
789
805
 
790
806
  /** Whether `relativePath` (from any ancestor directory) lies inside a compress scratch directory. */
791
807
  export function isCompressScratchPath(relativePath: string): boolean {