dsh-context-mode 0.1.3 → 0.2.0

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 (58) hide show
  1. package/LICENSING.md +37 -0
  2. package/README.md +39 -13
  3. package/lib/types/cjk.d.ts +54 -0
  4. package/lib/types/cjk.d.ts.map +1 -0
  5. package/lib/types/cjk.js +64 -0
  6. package/lib/types/index.d.ts.map +1 -1
  7. package/lib/types/index.js +65 -21
  8. package/lib/types/output-containment.d.ts +35 -0
  9. package/lib/types/output-containment.d.ts.map +1 -0
  10. package/lib/types/output-containment.js +103 -0
  11. package/lib/types/routing.d.ts +3 -1
  12. package/lib/types/routing.d.ts.map +1 -1
  13. package/lib/types/routing.js +81 -6
  14. package/package.json +9 -5
  15. package/skills/context-mode/SKILL.md +104 -11
  16. package/vendor/context-mode/LICENSE +94 -0
  17. package/vendor/context-mode/server.bundle.mjs +1126 -0
  18. package/vendor/context-mode/src/cli.ts +2040 -0
  19. package/vendor/context-mode/src/db-base.ts +617 -0
  20. package/vendor/context-mode/src/executor.ts +785 -0
  21. package/vendor/context-mode/src/exit-classify.ts +33 -0
  22. package/vendor/context-mode/src/fetch-cache.ts +15 -0
  23. package/vendor/context-mode/src/lifecycle.ts +305 -0
  24. package/vendor/context-mode/src/platform/client-map.ts +45 -0
  25. package/vendor/context-mode/src/platform/detect.ts +645 -0
  26. package/vendor/context-mode/src/platform/dsh.ts +206 -0
  27. package/vendor/context-mode/src/platform/types.ts +503 -0
  28. package/vendor/context-mode/src/runPool.ts +81 -0
  29. package/vendor/context-mode/src/runtime.ts +765 -0
  30. package/vendor/context-mode/src/search/auto-memory.ts +200 -0
  31. package/vendor/context-mode/src/search/ctx-search-schema.ts +143 -0
  32. package/vendor/context-mode/src/search/flood-guard.ts +111 -0
  33. package/vendor/context-mode/src/search/unified.ts +176 -0
  34. package/vendor/context-mode/src/security.ts +889 -0
  35. package/vendor/context-mode/src/server.ts +4991 -0
  36. package/vendor/context-mode/src/session/analytics.ts +3085 -0
  37. package/vendor/context-mode/src/session/db.ts +1726 -0
  38. package/vendor/context-mode/src/session/error-classifier.ts +392 -0
  39. package/vendor/context-mode/src/session/event-emit.ts +132 -0
  40. package/vendor/context-mode/src/session/extract.ts +2958 -0
  41. package/vendor/context-mode/src/session/index.ts +130 -0
  42. package/vendor/context-mode/src/session/model-prices.json +429 -0
  43. package/vendor/context-mode/src/session/persist-tool-calls.ts +128 -0
  44. package/vendor/context-mode/src/session/pricing.ts +191 -0
  45. package/vendor/context-mode/src/session/project-attribution.ts +309 -0
  46. package/vendor/context-mode/src/session/purge.ts +338 -0
  47. package/vendor/context-mode/src/session/retrieval-marker.ts +65 -0
  48. package/vendor/context-mode/src/session/snapshot.ts +577 -0
  49. package/vendor/context-mode/src/store-directory.ts +290 -0
  50. package/vendor/context-mode/src/store.ts +2071 -0
  51. package/vendor/context-mode/src/truncate.ts +154 -0
  52. package/vendor/context-mode/src/types.ts +147 -0
  53. package/vendor/context-mode/src/util/claude-config.ts +95 -0
  54. package/vendor/context-mode/src/util/hook-config.ts +78 -0
  55. package/vendor/context-mode/src/util/jsonc.ts +70 -0
  56. package/vendor/context-mode/src/util/plugin-cache-integrity.ts +167 -0
  57. package/vendor/context-mode/src/util/project-dir.ts +347 -0
  58. package/vendor/context-mode/src/util/sibling-mcp.ts +228 -0
@@ -0,0 +1,3085 @@
1
+ /**
2
+ * AnalyticsEngine — Runtime savings + session continuity reporting.
3
+ *
4
+ * Computes context-window savings from runtime stats and queries
5
+ * session continuity data from SessionDB.
6
+ *
7
+ * Usage:
8
+ * const engine = new AnalyticsEngine(sessionDb);
9
+ * const report = engine.queryAll(runtimeStats);
10
+ */
11
+
12
+ import { execFileSync } from "node:child_process";
13
+ import { existsSync, readdirSync, statSync } from "node:fs";
14
+ import { homedir } from "node:os";
15
+ import { join, sep } from "node:path";
16
+ import { loadDatabase as loadDatabaseImpl } from "../db-base.js";
17
+ import { ensureSessionEventsSchema } from "./db.js";
18
+ import { resolveClaudeConfigDir } from "../util/claude-config.js";
19
+
20
+ function semverNewer(a: string, b: string): boolean {
21
+ const pa = a.split(".").map(Number);
22
+ const pb = b.split(".").map(Number);
23
+ for (let i = 0; i < 3; i++) {
24
+ if ((pa[i] ?? 0) > (pb[i] ?? 0)) return true;
25
+ if ((pa[i] ?? 0) < (pb[i] ?? 0)) return false;
26
+ }
27
+ return false;
28
+ }
29
+
30
+
31
+ // ─────────────────────────────────────────────────────────
32
+ // Types
33
+ // ─────────────────────────────────────────────────────────
34
+
35
+ /** Database adapter — anything with a prepare() method (better-sqlite3, bun:sqlite, etc.) */
36
+ export interface DatabaseAdapter {
37
+ prepare(sql: string): {
38
+ run(...params: unknown[]): unknown;
39
+ get(...params: unknown[]): unknown;
40
+ all(...params: unknown[]): unknown[];
41
+ };
42
+ }
43
+
44
+ /** Context savings result (#1) */
45
+ export interface ContextSavings {
46
+ rawBytes: number;
47
+ contextBytes: number;
48
+ savedBytes: number;
49
+ savedPercent: number;
50
+ }
51
+
52
+ /** Think in code comparison result (#2) */
53
+ export interface ThinkInCodeComparison {
54
+ fileBytes: number;
55
+ outputBytes: number;
56
+ ratio: number;
57
+ }
58
+
59
+ /** Tool-level savings result (#3) */
60
+ export interface ToolSavingsRow {
61
+ tool: string;
62
+ rawBytes: number;
63
+ contextBytes: number;
64
+ savedBytes: number;
65
+ }
66
+
67
+ /** Sandbox I/O result (#19) */
68
+ export interface SandboxIO {
69
+ inputBytes: number;
70
+ outputBytes: number;
71
+ }
72
+
73
+ /** MCP tool usage row — concurrency stats for batch-style tools. */
74
+ export interface McpToolUsageRow {
75
+ tool_name: string;
76
+ calls: number;
77
+ median_concurrency: number | null;
78
+ max_concurrency: number | null;
79
+ }
80
+
81
+ /**
82
+ * Conversation-scoped stats — aggregated from `session_events` for a single
83
+ * `session_id` across every worktree DB plus the compact-rescue snapshot from
84
+ * `session_resume`. Replaces the broken in-memory `tool_call_counter` that
85
+ * only saw `ctx_*` MCP calls and reset to 0 every time the MCP server PID
86
+ * changed (which is what made hours-of-work conversations show "1 call · 5 KB").
87
+ */
88
+ export interface ConversationStats {
89
+ /** session_id this aggregate covers (the current Claude Code conversation). */
90
+ sessionId: string;
91
+ /** Total event count for this session_id, summed across all DBs. */
92
+ events: number;
93
+ /** Distinct DB files this session_id appeared in (a rotation indicator). */
94
+ dbCount: number;
95
+ /** Wall-clock days from first to last event. Captures real activity length. */
96
+ daysAlive: number;
97
+ /** Bytes restored from the compact snapshot for this session_id. 0 if no compact. */
98
+ snapshotBytes: number;
99
+ /** Number of compact snapshots consumed for this session_id. */
100
+ snapshotsConsumed: number;
101
+ /** Category breakdown for this session_id. */
102
+ byCategory: Array<{ category: string; count: number; label: string }>;
103
+ /**
104
+ * Earliest event timestamp (ms epoch) for this session_id across every DB.
105
+ * Used by the section-1 "started X" line in the narrative renderer. 0 when
106
+ * the session has no events yet. Optional for back-compat with older
107
+ * callers / fixtures that pre-date the narrative layout.
108
+ */
109
+ firstEventMs?: number;
110
+ /** Latest event timestamp (ms epoch) — pairs with firstEventMs. */
111
+ lastEventMs?: number;
112
+ /**
113
+ * Wall-clock timestamp of the most recent /compact rescue for this session.
114
+ * Drives the "On <datetime>, /compact fired" line in section 1. Undefined
115
+ * when the conversation has never been compacted.
116
+ */
117
+ lastRescueMs?: number;
118
+ /**
119
+ * Per-day capture breakdown for the section-1 horizontal timeline. Each
120
+ * entry is one calendar day (UTC midnight ms) with that day's event count
121
+ * + optional rescueBytes when /compact fired on that day. Empty array
122
+ * when no events recorded yet.
123
+ */
124
+ byDay?: Array<{ ms: number; count: number; rescueBytes?: number }>;
125
+ }
126
+
127
+ // ─────────────────────────────────────────────────────────
128
+ // Runtime stats — passed in from server.ts (can't come from DB)
129
+ // ─────────────────────────────────────────────────────────
130
+
131
+ /** Runtime stats tracked by server.ts during a live session. */
132
+ export interface RuntimeStats {
133
+ bytesReturned: Record<string, number>;
134
+ bytesIndexed: number;
135
+ bytesSandboxed: number;
136
+ calls: Record<string, number>;
137
+ sessionStart: number;
138
+ cacheHits: number;
139
+ cacheMisses?: number;
140
+ cacheBytesSaved: number;
141
+ }
142
+
143
+ /**
144
+ * Index observability snapshot — point-in-time view of the persistent
145
+ * content store. Optional input to `formatReport` so callers that don't
146
+ * have store access (or don't want the extra DB hit) can omit it.
147
+ */
148
+ export interface IndexState {
149
+ totalChunks: number;
150
+ totalSources: number;
151
+ lastIndexedAt?: string; // ISO-8601 when available
152
+ }
153
+
154
+ // ─────────────────────────────────────────────────────────
155
+ // FullReport — single unified object returned by queryAll()
156
+ // ─────────────────────────────────────────────────────────
157
+
158
+ /** Unified report combining runtime stats, DB analytics, and continuity data. */
159
+ export interface FullReport {
160
+ /** Runtime context savings (passed in, not from DB) */
161
+ savings: {
162
+ processed_kb: number;
163
+ entered_kb: number;
164
+ saved_kb: number;
165
+ pct: number;
166
+ savings_ratio: number;
167
+ by_tool: Array<{ tool: string; calls: number; context_kb: number; tokens: number }>;
168
+ total_calls: number;
169
+ total_bytes_returned: number;
170
+ kept_out: number;
171
+ total_processed: number;
172
+ };
173
+ cache?: {
174
+ hits: number;
175
+ misses: number;
176
+ hit_rate: number; // hits / (hits + misses); 0 when both are zero
177
+ bytes_saved: number;
178
+ ttl_hours_left: number;
179
+ total_with_cache: number;
180
+ total_savings_ratio: number;
181
+ };
182
+ /** Session metadata from SessionDB */
183
+ session: {
184
+ id: string;
185
+ uptime_min: string;
186
+ };
187
+ /** Session continuity data */
188
+ continuity: {
189
+ total_events: number;
190
+ by_category: Array<{
191
+ category: string;
192
+ count: number;
193
+ label: string;
194
+ preview: string;
195
+ why: string;
196
+ }>;
197
+ compact_count: number;
198
+ resume_ready: boolean;
199
+ };
200
+ /** Persistent project memory — all events across all sessions */
201
+ projectMemory: {
202
+ total_events: number;
203
+ session_count: number;
204
+ by_category: Array<{ category: string; count: number; label: string }>;
205
+ };
206
+ }
207
+
208
+ // ─────────────────────────────────────────────────────────
209
+ // Category labels and hints for session continuity display
210
+ // ─────────────────────────────────────────────────────────
211
+
212
+ /**
213
+ * Human-readable labels for event categories.
214
+ *
215
+ * Each label is a sentence-case phrase that reads like a benefit, not a
216
+ * column name. The user shouldn't see raw schema words like "external-ref"
217
+ * or "agent-finding" — those leak the database into the UX. When a new
218
+ * category lands without an entry here, the renderer falls through to the
219
+ * raw category id; that's a copy-debt signal, fix it here.
220
+ */
221
+ export const categoryLabels: Record<string, string> = {
222
+ // Code & filesystem
223
+ file: "Files tracked",
224
+ cwd: "Working directory",
225
+ // Configuration & intent
226
+ rule: "Project rules (CLAUDE.md)",
227
+ prompt: "Your requests saved",
228
+ intent: "Session intent",
229
+ goal: "Session goal",
230
+ role: "Behavior rules",
231
+ constraint: "Constraints you set",
232
+ // Tools & delegation
233
+ mcp: "MCP tools called",
234
+ skill: "Skills used",
235
+ subagent: "Delegated work",
236
+ // Knowledge & decisions
237
+ decision: "Your decisions",
238
+ "agent-finding": "Agent insights kept",
239
+ "rejected-approach": "Approaches you rejected",
240
+ "external-ref": "External docs indexed",
241
+ data: "Data references",
242
+ // System events
243
+ git: "Git operations",
244
+ env: "Environment setup",
245
+ task: "Tasks in progress",
246
+ error: "Errors caught",
247
+ // Continuity proof
248
+ compact: "Compactions weathered",
249
+ resume: "Sessions resumed cleanly",
250
+ snapshot: "Snapshots restored",
251
+ cache: "Cache hits saved",
252
+ // Operational
253
+ latency: "Slow tools recorded",
254
+ "user-prompt": "Your messages remembered",
255
+ plan: "Plans drafted",
256
+ "blocked-on": "Blockers logged",
257
+ };
258
+
259
+ /** Explains why each category matters for continuity. */
260
+ export const categoryHints: Record<string, string> = {
261
+ file: "Restored after compact — no need to re-read",
262
+ rule: "Your project instructions survive context resets",
263
+ prompt: "Continues exactly where you left off",
264
+ decision: "Applied automatically — won’t ask again",
265
+ task: "Picks up from where it stopped",
266
+ error: "Tracked and monitored across compacts",
267
+ git: "Branch, commit, and repo state preserved",
268
+ env: "Runtime config carried forward",
269
+ mcp: "Tool usage patterns remembered",
270
+ subagent: "Delegation history preserved",
271
+ skill: "Skill invocations tracked",
272
+ };
273
+
274
+ // ─────────────────────────────────────────────────────────
275
+ // AnalyticsEngine
276
+ // ─────────────────────────────────────────────────────────
277
+
278
+ export class AnalyticsEngine {
279
+ private readonly db: DatabaseAdapter;
280
+
281
+ /**
282
+ * Create an AnalyticsEngine.
283
+ *
284
+ * Accepts either a SessionDB instance (extracts internal db via
285
+ * the protected getter — use the static fromDB helper for raw adapters)
286
+ * or any object with a prepare() method for direct usage.
287
+ */
288
+ constructor(db: DatabaseAdapter) {
289
+ this.db = db;
290
+ }
291
+
292
+ // ═══════════════════════════════════════════════════════
293
+ // GROUP 3 — Runtime (4 metrics, stubs)
294
+ // ═══════════════════════════════════════════════════════
295
+
296
+ /**
297
+ * #1 Context Savings Total — bytes kept out of context window.
298
+ *
299
+ * Stub: requires server.ts to accumulate rawBytes and contextBytes
300
+ * during a live session. Call with tracked values.
301
+ */
302
+ static contextSavingsTotal(rawBytes: number, contextBytes: number): ContextSavings {
303
+ const savedBytes = rawBytes - contextBytes;
304
+ const savedPercent = rawBytes > 0
305
+ ? Math.round((savedBytes / rawBytes) * 1000) / 10
306
+ : 0;
307
+ return { rawBytes, contextBytes, savedBytes, savedPercent };
308
+ }
309
+
310
+ /**
311
+ * #2 Think in Code Comparison — ratio of file size to sandbox output size.
312
+ *
313
+ * Stub: requires server.ts tracking of execute/execute_file calls.
314
+ */
315
+ static thinkInCodeComparison(fileBytes: number, outputBytes: number): ThinkInCodeComparison {
316
+ const ratio = outputBytes > 0
317
+ ? Math.round((fileBytes / outputBytes) * 10) / 10
318
+ : 0;
319
+ return { fileBytes, outputBytes, ratio };
320
+ }
321
+
322
+ /**
323
+ * #3 Tool Savings — per-tool breakdown of context savings.
324
+ *
325
+ * Stub: requires per-tool accumulators in server.ts.
326
+ */
327
+ static toolSavings(
328
+ tools: Array<{ tool: string; rawBytes: number; contextBytes: number }>,
329
+ ): ToolSavingsRow[] {
330
+ return tools.map((t) => ({
331
+ ...t,
332
+ savedBytes: t.rawBytes - t.contextBytes,
333
+ }));
334
+ }
335
+
336
+ /**
337
+ * #19 Sandbox I/O — total input/output bytes processed by the sandbox.
338
+ *
339
+ * Stub: requires PolyglotExecutor byte counters.
340
+ */
341
+ static sandboxIO(inputBytes: number, outputBytes: number): SandboxIO {
342
+ return { inputBytes, outputBytes };
343
+ }
344
+
345
+ /**
346
+ * MCP tool usage — call counts and concurrency stats per MCP tool.
347
+ *
348
+ * Reads `mcp_tool_call` events, parses the JSON payload, and aggregates:
349
+ * - call count per tool_name
350
+ * - median + max of `params.concurrency` (only for tools that take it,
351
+ * e.g. ctx_batch_execute, ctx_fetch_and_index). Returns null when the
352
+ * tool doesn't carry a concurrency param so callers can render N/A.
353
+ *
354
+ * Best-effort: malformed rows or truncated payloads are skipped silently.
355
+ */
356
+ getMcpToolUsage(): McpToolUsageRow[] {
357
+ let rows: Array<{ data: string }>;
358
+ try {
359
+ rows = this.db.prepare(
360
+ "SELECT data FROM session_events WHERE category = 'mcp_tool_call'",
361
+ ).all() as Array<{ data: string }>;
362
+ } catch {
363
+ return [];
364
+ }
365
+
366
+ // toolName -> { calls, concurrencies }
367
+ const agg = new Map<string, { calls: number; concurrencies: number[] }>();
368
+
369
+ for (const row of rows) {
370
+ let parsed: { tool_name?: unknown; params?: unknown; truncated?: unknown };
371
+ try {
372
+ parsed = JSON.parse(row.data);
373
+ } catch {
374
+ continue;
375
+ }
376
+ const toolName = typeof parsed.tool_name === "string" ? parsed.tool_name : null;
377
+ if (!toolName) continue;
378
+
379
+ const bucket = agg.get(toolName) ?? { calls: 0, concurrencies: [] };
380
+ bucket.calls += 1;
381
+
382
+ // Skip concurrency extraction when the row was truncated — the params
383
+ // blob is a substring of JSON that may not parse cleanly.
384
+ if (parsed.truncated !== true && parsed.params && typeof parsed.params === "object") {
385
+ const c = (parsed.params as Record<string, unknown>).concurrency;
386
+ if (typeof c === "number" && Number.isFinite(c) && c > 0) {
387
+ bucket.concurrencies.push(c);
388
+ }
389
+ }
390
+
391
+ agg.set(toolName, bucket);
392
+ }
393
+
394
+ const out: McpToolUsageRow[] = [];
395
+ for (const [tool_name, b] of agg) {
396
+ let median: number | null = null;
397
+ let max: number | null = null;
398
+ if (b.concurrencies.length > 0) {
399
+ b.concurrencies.sort((a, c) => a - c);
400
+ const sorted = b.concurrencies;
401
+ const mid = Math.floor(sorted.length / 2);
402
+ median = sorted.length % 2 === 0
403
+ ? (sorted[mid - 1] + sorted[mid]) / 2
404
+ : sorted[mid];
405
+ max = sorted[sorted.length - 1];
406
+ }
407
+ out.push({
408
+ tool_name,
409
+ calls: b.calls,
410
+ median_concurrency: median,
411
+ max_concurrency: max,
412
+ });
413
+ }
414
+
415
+ // Stable sort: most-called first, then alphabetical
416
+ out.sort((a, c) => c.calls - a.calls || a.tool_name.localeCompare(c.tool_name));
417
+ return out;
418
+ }
419
+
420
+ // ═══════════════════════════════════════════════════════
421
+ // queryAll — single unified report from ONE source
422
+ // ═══════════════════════════════════════════════════════
423
+
424
+ /**
425
+ * Build a FullReport by merging runtime stats (passed in)
426
+ * with continuity data from the DB.
427
+ *
428
+ * This is the ONE call that ctx_stats should use.
429
+ */
430
+ queryAll(runtimeStats: RuntimeStats): FullReport {
431
+ // ── Resolve latest session ID ──
432
+ const latestSession = this.db.prepare(
433
+ "SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1",
434
+ ).get() as { session_id: string } | undefined;
435
+ const sid = latestSession?.session_id ?? "";
436
+
437
+ // ── Runtime savings ──
438
+ const totalBytesReturned = Object.values(runtimeStats.bytesReturned).reduce(
439
+ (sum, b) => sum + b, 0,
440
+ );
441
+ const totalCalls = Object.values(runtimeStats.calls).reduce(
442
+ (sum, c) => sum + c, 0,
443
+ );
444
+ const keptOut = runtimeStats.bytesIndexed + runtimeStats.bytesSandboxed;
445
+ const totalProcessed = keptOut + totalBytesReturned;
446
+ const savingsRatio = totalProcessed / Math.max(totalBytesReturned, 1);
447
+ const reductionPct = totalProcessed > 0
448
+ ? Math.round((1 - totalBytesReturned / totalProcessed) * 100)
449
+ : 0;
450
+
451
+ const toolNames = new Set([
452
+ ...Object.keys(runtimeStats.calls),
453
+ ...Object.keys(runtimeStats.bytesReturned),
454
+ ]);
455
+ const byTool = Array.from(toolNames).sort().map((tool) => ({
456
+ tool,
457
+ calls: runtimeStats.calls[tool] || 0,
458
+ context_kb: Math.round((runtimeStats.bytesReturned[tool] || 0) / 1024 * 10) / 10,
459
+ tokens: Math.round((runtimeStats.bytesReturned[tool] || 0) / 4),
460
+ }));
461
+
462
+ const uptimeMs = Date.now() - runtimeStats.sessionStart;
463
+ const uptimeMin = (uptimeMs / 60_000).toFixed(1);
464
+
465
+ // ── Cache ──
466
+ let cache: FullReport["cache"];
467
+ const cacheMisses = runtimeStats.cacheMisses ?? 0;
468
+ if (runtimeStats.cacheHits > 0 || runtimeStats.cacheBytesSaved > 0 || cacheMisses > 0) {
469
+ const totalWithCache = totalProcessed + runtimeStats.cacheBytesSaved;
470
+ const totalSavingsRatio = totalWithCache / Math.max(totalBytesReturned, 1);
471
+ const ttlHoursLeft = Math.max(0, 24 - Math.floor((Date.now() - runtimeStats.sessionStart) / (60 * 60 * 1000)));
472
+ // hit_rate is the nominal cache effectiveness — the metric ctx_stats
473
+ // historically inferred-only by diffing tokens_saved snapshots. When
474
+ // there is no activity we report 0 instead of NaN/undefined so the
475
+ // renderer stays JSON-safe.
476
+ const totalLookups = runtimeStats.cacheHits + cacheMisses;
477
+ const hitRate = totalLookups > 0 ? runtimeStats.cacheHits / totalLookups : 0;
478
+ cache = {
479
+ hits: runtimeStats.cacheHits,
480
+ misses: cacheMisses,
481
+ hit_rate: hitRate,
482
+ bytes_saved: runtimeStats.cacheBytesSaved,
483
+ ttl_hours_left: ttlHoursLeft,
484
+ total_with_cache: totalWithCache,
485
+ total_savings_ratio: totalSavingsRatio,
486
+ };
487
+ }
488
+
489
+ // ── Continuity data (scoped to current session) ──
490
+ const eventTotal = (this.db.prepare(
491
+ "SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?",
492
+ ).get(sid) as { cnt: number }).cnt;
493
+
494
+ const byCategory = this.db.prepare(
495
+ "SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC",
496
+ ).all(sid) as Array<{ category: string; cnt: number }>;
497
+
498
+ const meta = this.db.prepare(
499
+ "SELECT compact_count FROM session_meta WHERE session_id = ?",
500
+ ).get(sid) as { compact_count: number } | undefined;
501
+ const compactCount = meta?.compact_count ?? 0;
502
+
503
+ const resume = this.db.prepare(
504
+ "SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1",
505
+ ).get(sid) as { event_count: number; consumed: number } | undefined;
506
+ const resumeReady = resume ? !resume.consumed : false;
507
+
508
+ // Build category previews (current session only)
509
+ const previewRows = this.db.prepare(
510
+ "SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC",
511
+ ).all(sid) as Array<{ category: string; type: string; data: string }>;
512
+
513
+ const previews = new Map<string, Set<string>>();
514
+ for (const row of previewRows) {
515
+ if (!previews.has(row.category)) previews.set(row.category, new Set());
516
+ const set = previews.get(row.category)!;
517
+ if (set.size < 5) {
518
+ let display = row.data;
519
+ if (row.category === "file") {
520
+ display = row.data.split("/").pop() || row.data;
521
+ } else if (row.category === "prompt" || row.category === "user-prompt") {
522
+ display = display.length > 50 ? display.slice(0, 47) + "..." : display;
523
+ }
524
+ if (display.length > 40) display = display.slice(0, 37) + "...";
525
+ set.add(display);
526
+ }
527
+ }
528
+
529
+ const continuityByCategory = byCategory.map((row) => ({
530
+ category: row.category,
531
+ count: row.cnt,
532
+ label: categoryLabels[row.category] || row.category,
533
+ preview: previews.get(row.category)
534
+ ? Array.from(previews.get(row.category)!).join(", ")
535
+ : "",
536
+ why: categoryHints[row.category] || "Survives context resets",
537
+ }));
538
+
539
+ // ── Project-wide persistent memory (all sessions, no session_id filter) ──
540
+ const projectTotals = this.db.prepare(
541
+ "SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events",
542
+ ).get() as { cnt: number; sessions: number };
543
+
544
+ const projectByCategory = this.db.prepare(
545
+ "SELECT category, COUNT(*) as cnt FROM session_events GROUP BY category ORDER BY cnt DESC",
546
+ ).all() as Array<{ category: string; cnt: number }>;
547
+
548
+ const projectMemoryByCategory = projectByCategory
549
+ .filter((row) => row.cnt > 0)
550
+ .map((row) => ({
551
+ category: row.category,
552
+ count: row.cnt,
553
+ label: categoryLabels[row.category] || row.category,
554
+ }));
555
+
556
+ return {
557
+ savings: {
558
+ processed_kb: Math.round(totalProcessed / 1024 * 10) / 10,
559
+ entered_kb: Math.round(totalBytesReturned / 1024 * 10) / 10,
560
+ saved_kb: Math.round(keptOut / 1024 * 10) / 10,
561
+ pct: reductionPct,
562
+ savings_ratio: Math.round(savingsRatio * 10) / 10,
563
+ by_tool: byTool,
564
+ total_calls: totalCalls,
565
+ total_bytes_returned: totalBytesReturned,
566
+ kept_out: keptOut,
567
+ total_processed: totalProcessed,
568
+ },
569
+ cache,
570
+ session: {
571
+ id: sid,
572
+ uptime_min: uptimeMin,
573
+ },
574
+ continuity: {
575
+ total_events: eventTotal,
576
+ by_category: continuityByCategory,
577
+ compact_count: compactCount,
578
+ resume_ready: resumeReady,
579
+ },
580
+ projectMemory: {
581
+ total_events: projectTotals.cnt,
582
+ session_count: projectTotals.sessions,
583
+ by_category: projectMemoryByCategory,
584
+ },
585
+ };
586
+ }
587
+ }
588
+
589
+ // ─────────────────────────────────────────────────────────
590
+ // Adapter dir enumeration (B3a multi-adapter aggregation)
591
+ // ─────────────────────────────────────────────────────────
592
+
593
+ /**
594
+ * Where one adapter stores its context-mode sidecars on disk. Mirrors the
595
+ * map in `src/adapters/detect.ts:92-111` (`getSessionDirSegments`) so we
596
+ * never go out of sync as a single source of truth.
597
+ *
598
+ * `sessionsDir` = `<home>/<segments>/context-mode/sessions`
599
+ * `contentDir` = `<home>/<segments>/context-mode/content`
600
+ *
601
+ * Why duplicated here: `getSessionDirSegments` returns segments relative to
602
+ * `homedir()`; analytics needs the absolute joined paths for both `sessions`
603
+ * and `content` siblings. Keeping a parallel hard-coded list avoids importing
604
+ * detect.ts (which pulls in adapter loaders) into the stats path.
605
+ */
606
+ export interface AdapterDirEntry {
607
+ /** Adapter id matching `src/adapters/detect.ts` PlatformId. */
608
+ name: string;
609
+ /** Absolute path to `<home>/<segments>/context-mode/sessions`. */
610
+ sessionsDir: string;
611
+ /** Absolute path to `<home>/<segments>/context-mode/content`. */
612
+ contentDir: string;
613
+ }
614
+
615
+ /**
616
+ * Enumerate every known adapter's sessions + content dirs under `home`.
617
+ * Used by `getMultiAdapterLifetimeStats` and `getMultiAdapterRealBytesStats`
618
+ * so a single call surfaces "your work everywhere on this machine across
619
+ * all AI tools" (the marketing line).
620
+ *
621
+ * Returns ALL 17 adapters even when the dir doesn't exist on disk — the
622
+ * scanner functions filter to existing dirs. That keeps the enumeration
623
+ * pure / testable without filesystem dependencies.
624
+ */
625
+ export function enumerateAdapterDirs(opts?: { home?: string }): AdapterDirEntry[] {
626
+ const home = opts?.home ?? homedir();
627
+ // Mirrors `getSessionDirSegments` in src/adapters/detect.ts:92-111.
628
+ const map: ReadonlyArray<readonly [string, readonly string[]]> = [
629
+ ["claude-code", [".claude"]],
630
+ ["gemini-cli", [".gemini"]],
631
+ ["antigravity", [".gemini"]],
632
+ ["antigravity-cli", [".gemini"]],
633
+ ["openclaw", [".openclaw"]],
634
+ ["codex", [".codex"]],
635
+ ["cursor", [".cursor"]],
636
+ ["vscode-copilot", [".vscode"]],
637
+ ["copilot-cli", [".copilot"]],
638
+ ["kiro", [".kiro"]],
639
+ ["pi", [".pi"]],
640
+ ["omp", [".omp"]],
641
+ ["qwen-code", [".qwen"]],
642
+ ["kilo", [".config", "kilo"]],
643
+ ["opencode", [".config", "opencode"]],
644
+ ["zed", [".config", "zed"]],
645
+ ["jetbrains-copilot", [".config", "JetBrains"]],
646
+ ];
647
+ return map.map(([name, segments]) => {
648
+ const base = join(home, ...segments, "context-mode");
649
+ return {
650
+ name,
651
+ sessionsDir: join(base, "sessions"),
652
+ contentDir: join(base, "content"),
653
+ };
654
+ });
655
+ }
656
+
657
+ // ─────────────────────────────────────────────────────────
658
+ // Lifetime stats (Bug #3 + #4)
659
+ // ─────────────────────────────────────────────────────────
660
+
661
+ /** Aggregated stats spanning every SessionDB + auto-memory under the user's profile. */
662
+ export interface LifetimeStats {
663
+ totalEvents: number;
664
+ totalSessions: number;
665
+ autoMemoryCount: number;
666
+ autoMemoryProjects: number;
667
+ /** Per-prefix breakdown of auto-memory files (user/feedback/project/...). */
668
+ autoMemoryByPrefix: Record<string, number>;
669
+ /**
670
+ * Per-category event counts aggregated across every SessionDB on disk.
671
+ * Keys are the raw category strings (file/cwd/rule/...) — the renderer
672
+ * looks them up against `categoryLabels` for display. Empty `{}` when no
673
+ * sidecar has any events. Optional for back-compat with older fixtures.
674
+ */
675
+ categoryCounts: Record<string, number>;
676
+ /**
677
+ * Total bytes restored from compact-rescue snapshots across every DB on
678
+ * disk. Adds the rescue benefit to lifetime $ so the headline isn't
679
+ * silently undercounting the killer feature. 0 when no compact has fired
680
+ * or older fixtures don't pass this. Optional for back-compat with tests.
681
+ */
682
+ rescueBytes?: number;
683
+ /**
684
+ * Earliest event timestamp (ms epoch) across every DB. Used for the
685
+ * "since 2026-04-14" lifetime narrative. 0 when unknown. Optional.
686
+ */
687
+ firstEventMs?: number;
688
+ /**
689
+ * Distinct project_dir count across every DB. Different from
690
+ * `autoMemoryProjects` (which only counts dirs with auto-memory files).
691
+ * Captures every cwd context-mode has ever seen events for. Optional.
692
+ */
693
+ distinctProjects?: number;
694
+ }
695
+
696
+ /** Extract leading prefix from auto-memory filename: `feedback_push.md` → `feedback`. */
697
+ function autoMemoryPrefix(filename: string): string {
698
+ const base = filename.replace(/\.md$/i, "");
699
+ const m = base.match(/^([a-z]+)/i);
700
+ return m ? m[1].toLowerCase() : "other";
701
+ }
702
+
703
+ /**
704
+ * Aggregate lifetime stats from all SessionDB files in `sessionsDir` and
705
+ * all auto-memory markdown files under `memoryRoot/<project>/memory/`.
706
+ *
707
+ * Best-effort: silently ignores missing/unreadable files so ctx_stats
708
+ * can never be broken by a corrupt sidecar.
709
+ */
710
+ export function getLifetimeStats(opts?: {
711
+ sessionsDir?: string;
712
+ memoryRoot?: string;
713
+ /** Override for tests — defaults to db-base loadDatabase(). */
714
+ loadDatabase?: () => unknown;
715
+ }): LifetimeStats {
716
+ // Issue #460 round-3: route through resolveClaudeConfigDir so lifetime
717
+ // stats aggregation tracks $CLAUDE_CONFIG_DIR instead of the literal
718
+ // ~/.claude tree. Otherwise users who relocate config see "no sessions"
719
+ // even though the SessionDB sidecars exist under the override.
720
+ const claudeRoot = resolveClaudeConfigDir();
721
+ const sessionsDir = opts?.sessionsDir
722
+ ?? join(claudeRoot, "context-mode", "sessions");
723
+ const memoryRoot = opts?.memoryRoot
724
+ ?? join(claudeRoot, "projects");
725
+
726
+ let totalEvents = 0;
727
+ let totalSessions = 0;
728
+ let rescueBytes = 0;
729
+ let firstEventMs = Number.POSITIVE_INFINITY;
730
+ const distinctProjectsSet = new Set<string>();
731
+ const categoryCounts: Record<string, number> = {};
732
+
733
+ // ── SessionDB aggregation ──
734
+ if (existsSync(sessionsDir)) {
735
+ let dbFiles: string[] = [];
736
+ try {
737
+ dbFiles = readdirSync(sessionsDir).filter((f) => f.endsWith(".db"));
738
+ } catch { /* unreadable */ }
739
+
740
+ if (dbFiles.length > 0) {
741
+ // Lazy-load better-sqlite3 / bun-sqlite via the same path the runtime uses.
742
+ let DatabaseCtor: ReturnType<typeof loadDatabaseImpl> | null = null;
743
+ try {
744
+ DatabaseCtor = opts?.loadDatabase
745
+ ? (opts.loadDatabase() as ReturnType<typeof loadDatabaseImpl>)
746
+ : loadDatabaseImpl();
747
+ } catch { /* sqlite unavailable */ }
748
+
749
+ if (DatabaseCtor) {
750
+ for (const file of dbFiles) {
751
+ const dbPath = join(sessionsDir, file);
752
+ try {
753
+ const sdb = new DatabaseCtor(dbPath, { readonly: true });
754
+ try {
755
+ const ev = sdb.prepare("SELECT COUNT(*) AS cnt FROM session_events").get() as { cnt: number } | undefined;
756
+ const ss = sdb.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get() as { cnt: number } | undefined;
757
+ totalEvents += ev?.cnt ?? 0;
758
+ totalSessions += ss?.cnt ?? 0;
759
+ // Per-category aggregation across every sidecar so the
760
+ // Persistent memory bars stay populated even when the
761
+ // current project's local DB is fresh / empty.
762
+ try {
763
+ const catRows = sdb.prepare(
764
+ "SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category",
765
+ ).all() as Array<{ category: string; cnt: number }>;
766
+ for (const row of catRows) {
767
+ if (!row.category) continue;
768
+ categoryCounts[row.category] = (categoryCounts[row.category] ?? 0) + (row.cnt ?? 0);
769
+ }
770
+ } catch {
771
+ // older schema / no category column — ignore
772
+ }
773
+ // Lifetime rescue: compact-snapshot bytes restored across every DB.
774
+ // Without this, the lifetime $ silently undercounts the killer
775
+ // continuity-after-/compact feature.
776
+ try {
777
+ const snap = sdb.prepare(
778
+ "SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1",
779
+ ).get() as { bytes: number } | undefined;
780
+ if (snap?.bytes) rescueBytes += snap.bytes;
781
+ } catch { /* old schema */ }
782
+ // Earliest event timestamp + distinct project_dirs for the
783
+ // "since X · Y projects" lifetime narrative.
784
+ try {
785
+ const mn = sdb.prepare(
786
+ "SELECT MIN(created_at) AS t FROM session_events",
787
+ ).get() as { t: string | null } | undefined;
788
+ if (mn?.t) {
789
+ const stamp = mn.t.endsWith("Z") ? mn.t : mn.t + "Z";
790
+ const ms = Date.parse(stamp);
791
+ if (Number.isFinite(ms) && ms < firstEventMs) firstEventMs = ms;
792
+ }
793
+ } catch { /* old schema */ }
794
+ try {
795
+ const projRows = sdb.prepare(
796
+ "SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''",
797
+ ).all() as Array<{ p: string }>;
798
+ for (const row of projRows) if (row.p) distinctProjectsSet.add(row.p);
799
+ } catch { /* old schema */ }
800
+ } finally {
801
+ sdb.close();
802
+ }
803
+ } catch {
804
+ // missing tables / corrupt file — skip
805
+ }
806
+ }
807
+ }
808
+ }
809
+ }
810
+
811
+ // ── Auto-memory file scan ──
812
+ let autoMemoryCount = 0;
813
+ let autoMemoryProjects = 0;
814
+ const autoMemoryByPrefix: Record<string, number> = {};
815
+
816
+ if (existsSync(memoryRoot)) {
817
+ let projectDirs: string[] = [];
818
+ try {
819
+ projectDirs = readdirSync(memoryRoot).filter((entry) => {
820
+ try {
821
+ return statSync(join(memoryRoot, entry)).isDirectory();
822
+ } catch { return false; }
823
+ });
824
+ } catch { /* unreadable */ }
825
+
826
+ for (const proj of projectDirs) {
827
+ const memDir = join(memoryRoot, proj, "memory");
828
+ if (!existsSync(memDir)) continue;
829
+ let mdFiles: string[] = [];
830
+ try {
831
+ mdFiles = readdirSync(memDir).filter((f) => f.endsWith(".md"));
832
+ } catch { continue; }
833
+ if (mdFiles.length === 0) continue;
834
+ autoMemoryProjects++;
835
+ autoMemoryCount += mdFiles.length;
836
+ for (const f of mdFiles) {
837
+ const prefix = autoMemoryPrefix(f);
838
+ autoMemoryByPrefix[prefix] = (autoMemoryByPrefix[prefix] ?? 0) + 1;
839
+ }
840
+ }
841
+ }
842
+
843
+ return {
844
+ totalEvents,
845
+ totalSessions,
846
+ autoMemoryCount,
847
+ autoMemoryProjects,
848
+ autoMemoryByPrefix,
849
+ categoryCounts,
850
+ rescueBytes,
851
+ firstEventMs: Number.isFinite(firstEventMs) ? firstEventMs : 0,
852
+ distinctProjects: distinctProjectsSet.size,
853
+ };
854
+ }
855
+
856
+ /**
857
+ * Aggregate every event for one `session_id` across all SessionDB files in
858
+ * `sessionsDir` plus the compact-rescue snapshot bytes from `session_resume`.
859
+ *
860
+ * Why this exists: the Claude Code session_id can persist across days while
861
+ * the underlying DB file rotates (size cap), and a compact-rescue snapshot
862
+ * carries hundreds of KB of context that would otherwise have been lost. The
863
+ * old in-memory `tool_call_counter` saw none of this — it counted only `ctx_*`
864
+ * MCP calls against the current MCP server PID and reset on every restart.
865
+ * Reading from `session_events` + `session_resume` is the source-of-truth
866
+ * version that matches what users actually experienced.
867
+ */
868
+ export function getConversationStats(opts: {
869
+ sessionId: string;
870
+ sessionsDir?: string;
871
+ /** Optional worktree filename prefix (sha256(cwd)[:16]). When omitted, scans every DB. */
872
+ worktreeHash?: string;
873
+ loadDatabase?: () => unknown;
874
+ }): ConversationStats {
875
+ const sessionsDir = opts.sessionsDir
876
+ ?? join(homedir(), ".claude", "context-mode", "sessions");
877
+ const sessionId = opts.sessionId;
878
+
879
+ const empty: ConversationStats = {
880
+ sessionId,
881
+ events: 0,
882
+ dbCount: 0,
883
+ daysAlive: 0,
884
+ snapshotBytes: 0,
885
+ snapshotsConsumed: 0,
886
+ byCategory: [],
887
+ };
888
+ if (!sessionId || !existsSync(sessionsDir)) return empty;
889
+
890
+ let dbFiles: string[] = [];
891
+ try {
892
+ dbFiles = readdirSync(sessionsDir).filter((f) => {
893
+ if (!f.endsWith(".db")) return false;
894
+ if (opts.worktreeHash && !f.startsWith(opts.worktreeHash)) return false;
895
+ return true;
896
+ });
897
+ } catch { return empty; }
898
+ if (dbFiles.length === 0) return empty;
899
+
900
+ let DatabaseCtor: ReturnType<typeof loadDatabaseImpl> | null = null;
901
+ try {
902
+ DatabaseCtor = opts.loadDatabase
903
+ ? (opts.loadDatabase() as ReturnType<typeof loadDatabaseImpl>)
904
+ : loadDatabaseImpl();
905
+ } catch { return empty; }
906
+ if (!DatabaseCtor) return empty;
907
+
908
+ const catCounts: Record<string, number> = {};
909
+ let events = 0;
910
+ let dbCount = 0;
911
+ let snapshotBytes = 0;
912
+ let snapshotsConsumed = 0;
913
+ let firstMs = Number.POSITIVE_INFINITY;
914
+ let lastMs = 0;
915
+ let lastRescueMs = 0;
916
+ // Per-day captures aggregated across every DB. Key is the UTC midnight ms
917
+ // of the day; value tracks both the event count and any rescueBytes (latter
918
+ // overlays the ◆ /compact glyph in the section-1 horizontal timeline).
919
+ const byDayMap = new Map<number, { count: number; rescueBytes: number }>();
920
+ const dayKey = (ms: number): number => Math.floor(ms / 86_400_000) * 86_400_000;
921
+
922
+ for (const file of dbFiles) {
923
+ const dbPath = join(sessionsDir, file);
924
+ let touched = false;
925
+ try {
926
+ const sdb = new DatabaseCtor(dbPath, { readonly: true });
927
+ try {
928
+ const cats = sdb.prepare(
929
+ "SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category",
930
+ ).all(sessionId) as Array<{ category: string; cnt: number }>;
931
+ for (const row of cats) {
932
+ if (!row.category) continue;
933
+ catCounts[row.category] = (catCounts[row.category] ?? 0) + (row.cnt ?? 0);
934
+ events += row.cnt ?? 0;
935
+ touched = true;
936
+ }
937
+ const range = sdb.prepare(
938
+ "SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?",
939
+ ).get(sessionId) as { mn: string | null; mx: string | null } | undefined;
940
+ if (range?.mn) {
941
+ const t = Date.parse(range.mn + (range.mn.endsWith("Z") ? "" : "Z"));
942
+ if (Number.isFinite(t) && t < firstMs) firstMs = t;
943
+ }
944
+ if (range?.mx) {
945
+ const t = Date.parse(range.mx + (range.mx.endsWith("Z") ? "" : "Z"));
946
+ if (Number.isFinite(t) && t > lastMs) lastMs = t;
947
+ }
948
+ // Per-day captures + per-day rescue overlay for the narrative timeline.
949
+ // Best-effort: silently skip when the schema lacks created_at.
950
+ try {
951
+ const dayRows = sdb.prepare(
952
+ "SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)",
953
+ ).all(sessionId) as Array<{ sec: string | null; cnt: number }>;
954
+ for (const row of dayRows) {
955
+ if (!row.sec) continue;
956
+ const ms = parseInt(row.sec, 10) * 1000;
957
+ if (!Number.isFinite(ms)) continue;
958
+ const k = dayKey(ms);
959
+ const cur = byDayMap.get(k) ?? { count: 0, rescueBytes: 0 };
960
+ cur.count += row.cnt ?? 0;
961
+ byDayMap.set(k, cur);
962
+ }
963
+ } catch { /* old schema */ }
964
+ try {
965
+ const snap = sdb.prepare(
966
+ "SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes, COUNT(*) AS n, MAX(strftime('%s', created_at)) AS lastSec FROM session_resume WHERE session_id = ? AND consumed = 1",
967
+ ).get(sessionId) as { bytes: number; n: number; lastSec: string | null } | undefined;
968
+ if (snap?.bytes) snapshotBytes += snap.bytes;
969
+ if (snap?.n) snapshotsConsumed += snap.n;
970
+ if (snap?.lastSec) {
971
+ const t = parseInt(snap.lastSec, 10) * 1000;
972
+ if (Number.isFinite(t) && t > lastRescueMs) lastRescueMs = t;
973
+ // Overlay the rescue bytes onto the day bucket for the timeline.
974
+ if (Number.isFinite(t) && (snap?.bytes ?? 0) > 0) {
975
+ const k = dayKey(t);
976
+ const cur = byDayMap.get(k) ?? { count: 0, rescueBytes: 0 };
977
+ cur.rescueBytes = Math.max(cur.rescueBytes, snap.bytes);
978
+ byDayMap.set(k, cur);
979
+ }
980
+ }
981
+ } catch { /* old schema */ }
982
+ } finally {
983
+ sdb.close();
984
+ }
985
+ } catch { /* missing tables / corrupt */ }
986
+ if (touched) dbCount++;
987
+ }
988
+
989
+ const daysAlive = firstMs < lastMs ? (lastMs - firstMs) / 86_400_000 : 0;
990
+ const byCategory = Object.entries(catCounts)
991
+ .filter(([, n]) => n > 0)
992
+ .map(([category, count]) => ({
993
+ category,
994
+ count,
995
+ label: categoryLabels[category] || category,
996
+ }))
997
+ .sort((a, b) => b.count - a.count);
998
+ const byDay = [...byDayMap.entries()]
999
+ .sort((a, b) => a[0] - b[0])
1000
+ .map(([ms, v]) => ({
1001
+ ms,
1002
+ count: v.count,
1003
+ ...(v.rescueBytes > 0 ? { rescueBytes: v.rescueBytes } : {}),
1004
+ }));
1005
+
1006
+ return {
1007
+ sessionId,
1008
+ events,
1009
+ dbCount,
1010
+ daysAlive,
1011
+ snapshotBytes,
1012
+ snapshotsConsumed,
1013
+ byCategory,
1014
+ firstEventMs: Number.isFinite(firstMs) ? firstMs : 0,
1015
+ lastEventMs: lastMs > 0 ? lastMs : 0,
1016
+ lastRescueMs: lastRescueMs > 0 ? lastRescueMs : undefined,
1017
+ byDay,
1018
+ };
1019
+ }
1020
+
1021
+ // ─────────────────────────────────────────────────────────
1022
+ // getRealBytesStats — Phase 8 of D2 PRD (stats-event-driven-architecture)
1023
+ // ─────────────────────────────────────────────────────────
1024
+
1025
+ /**
1026
+ * Real-bytes counter the renderer uses to replace the conservative
1027
+ * `events × 256` token estimate. Reads four sources from disk and
1028
+ * returns the sum the renderer divides by 4 to get tokens.
1029
+ *
1030
+ * - `eventDataBytes` = SUM(LENGTH(data)) FROM session_events
1031
+ * - `bytesAvoided` = SUM(bytes_avoided) FROM session_events
1032
+ * - `bytesReturned` = SUM(bytes_returned) FROM session_events
1033
+ * - `snapshotBytes` = SUM(LENGTH(snapshot)) FROM session_resume
1034
+ * - `totalSavedTokens` = (eventDataBytes + bytesAvoided + snapshotBytes) / 4
1035
+ *
1036
+ * `bytesReturned` is reported but NOT folded into `totalSavedTokens`
1037
+ * because it represents bytes the model already paid for — adding it
1038
+ * would double-count what's already on the user's invoice.
1039
+ */
1040
+ export interface RealBytesStats {
1041
+ eventDataBytes: number;
1042
+ bytesAvoided: number;
1043
+ bytesReturned: number;
1044
+ snapshotBytes: number;
1045
+ /**
1046
+ * v1.0.133 Slice 3: bytes attributed to this session in the FTS5 content
1047
+ * DB — `SUM(LENGTH(title) + LENGTH(content)) FROM chunks WHERE session_id = ?`.
1048
+ *
1049
+ * Read-only, render-time computation. Populated only when
1050
+ * `getRealBytesStats` is called with both `sessionId` AND `contentDbPath`
1051
+ * (i.e. the conversation tier from ctx_stats). Lifetime / project tiers
1052
+ * leave this at 0 — aggregating across every adapter's content DB is a
1053
+ * separate concern.
1054
+ *
1055
+ * Legacy chunks with empty `session_id` (pre-Slice-1) are NOT backfilled:
1056
+ * the architect rejected the time-window join as unsafe. Old conversations
1057
+ * stay low; new conversations populate honestly.
1058
+ */
1059
+ contentBytes: number;
1060
+ totalSavedTokens: number;
1061
+ }
1062
+
1063
+ /**
1064
+ * v1.0.133 Slice 3: Sum the bytes attributed to one session in the FTS5
1065
+ * content DB.
1066
+ *
1067
+ * Returns `LENGTH(title) + LENGTH(content)` summed across every chunk
1068
+ * whose `session_id` column matches `sessionId`. Best-effort — returns 0
1069
+ * when the DB file is missing, the schema lacks the `session_id` column
1070
+ * (pre-Slice-1 content DBs), or the query fails. Never throws.
1071
+ *
1072
+ * Render-time only. Does NOT mutate the content DB. Architect-approved
1073
+ * because the read-only join carries no risk of cross-session attribution
1074
+ * (the FK was set at chunk insert time by Slice 1).
1075
+ */
1076
+ export function getContentBytesForSession(
1077
+ sessionId: string,
1078
+ contentDbPath: string,
1079
+ opts?: { loadDatabase?: () => unknown },
1080
+ ): number {
1081
+ if (!sessionId || !contentDbPath) return 0;
1082
+ if (!existsSync(contentDbPath)) return 0;
1083
+
1084
+ let DatabaseCtor: ReturnType<typeof loadDatabaseImpl> | null = null;
1085
+ try {
1086
+ DatabaseCtor = opts?.loadDatabase
1087
+ ? (opts.loadDatabase() as ReturnType<typeof loadDatabaseImpl>)
1088
+ : loadDatabaseImpl();
1089
+ } catch { return 0; }
1090
+ if (!DatabaseCtor) return 0;
1091
+
1092
+ try {
1093
+ const db = new DatabaseCtor(contentDbPath, { readonly: true });
1094
+ try {
1095
+ const row = db.prepare(
1096
+ `SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
1097
+ FROM chunks WHERE session_id = ?`,
1098
+ ).get(sessionId) as { bytes: number } | undefined;
1099
+ return Number(row?.bytes ?? 0);
1100
+ } finally {
1101
+ db.close();
1102
+ }
1103
+ } catch {
1104
+ return 0;
1105
+ }
1106
+ }
1107
+
1108
+ /**
1109
+ * v1.0.134 SLICE C — lifetime tier all-chunks aggregate.
1110
+ *
1111
+ * Sibling of {@link getContentBytesForSession} that omits the session_id
1112
+ * filter so the lifetime tier sees every chunk in the content store —
1113
+ * including legacy unattributed rows (sessionId === '') and chunks
1114
+ * attributed to other adapters' sessions. Without this, the lifetime
1115
+ * "kept out" headline only counts session_events.bytes_avoided and
1116
+ * misses the bulk of indexed payload.
1117
+ *
1118
+ * Best-effort: returns 0 when the DB file is missing, the schema lacks
1119
+ * the `chunks` table, or the query fails. Never throws — same contract
1120
+ * as the rest of the analytics module so a corrupt content DB cannot
1121
+ * crash ctx_stats.
1122
+ */
1123
+ export function getContentBytesAllSessions(
1124
+ contentDbPath: string,
1125
+ opts?: { loadDatabase?: () => unknown },
1126
+ ): number {
1127
+ if (!contentDbPath) return 0;
1128
+ if (!existsSync(contentDbPath)) return 0;
1129
+
1130
+ let DatabaseCtor: ReturnType<typeof loadDatabaseImpl> | null = null;
1131
+ try {
1132
+ DatabaseCtor = opts?.loadDatabase
1133
+ ? (opts.loadDatabase() as ReturnType<typeof loadDatabaseImpl>)
1134
+ : loadDatabaseImpl();
1135
+ } catch { return 0; }
1136
+ if (!DatabaseCtor) return 0;
1137
+
1138
+ try {
1139
+ const db = new DatabaseCtor(contentDbPath, { readonly: true });
1140
+ try {
1141
+ const row = db.prepare(
1142
+ `SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
1143
+ FROM chunks`,
1144
+ ).get() as { bytes: number } | undefined;
1145
+ return Number(row?.bytes ?? 0);
1146
+ } finally {
1147
+ db.close();
1148
+ }
1149
+ } catch {
1150
+ return 0;
1151
+ }
1152
+ }
1153
+
1154
+ /**
1155
+ * Compute real-bytes stats across one session, one project (worktree
1156
+ * filter), or every session on disk (lifetime).
1157
+ *
1158
+ * - Pass `sessionId` for the conversation tier.
1159
+ * - Pass `worktreeHash` to filter `*.db` files by name prefix
1160
+ * (per-project lifetime — `sha256(cwd).slice(0, 16)`).
1161
+ * - Pass neither — full lifetime aggregate.
1162
+ *
1163
+ * Best-effort: returns zeroes when the dir is missing, the DB is
1164
+ * corrupt, or the session has no events. Never throws — same
1165
+ * contract as `getConversationStats` / `getLifetimeStats` so the
1166
+ * stats-render path can never crash on a bad sidecar.
1167
+ */
1168
+ export function getRealBytesStats(opts: {
1169
+ sessionId?: string;
1170
+ sessionsDir?: string;
1171
+ worktreeHash?: string;
1172
+ /**
1173
+ * v1.0.148 follow-up (Bug E+F): when set, the function aggregates across
1174
+ * EVERY session whose `session_meta.project_dir` matches this value, not
1175
+ * just one session_id. Resolves the per-conversation under-attribution:
1176
+ * one Claude Code conversation typically spans many session_ids (resume
1177
+ * cycles, /compact rebirths, PID sub-process sessions spawned by
1178
+ * ctx_execute), so a single-session_id filter loses the sandbox-burst
1179
+ * bytes_avoided that all live under the conversation's cwd.
1180
+ *
1181
+ * Uses a META subquery (`session_id IN (SELECT session_id FROM
1182
+ * session_meta WHERE project_dir = ?)`), then sums ALL events for
1183
+ * matching sessions regardless of their event-level project_dir
1184
+ * (sandbox-burst events write `project_dir = ''` even when the
1185
+ * META row carries the parent cwd — see Bug F).
1186
+ *
1187
+ * Mutually exclusive with `sessionId`. When both are set, `sessionId`
1188
+ * wins for back-compat.
1189
+ */
1190
+ projectDir?: string;
1191
+ /**
1192
+ * v1.0.133 Slice 3: when set alongside `sessionId`, the function joins
1193
+ * the FTS5 content DB at this path and folds chunk bytes into
1194
+ * `bytesAvoided` + `totalSavedTokens` + `contentBytes`. Render-time
1195
+ * only — no DB writes.
1196
+ */
1197
+ contentDbPath?: string;
1198
+ loadDatabase?: () => unknown;
1199
+ }): RealBytesStats {
1200
+ const empty: RealBytesStats = {
1201
+ eventDataBytes: 0,
1202
+ bytesAvoided: 0,
1203
+ bytesReturned: 0,
1204
+ snapshotBytes: 0,
1205
+ contentBytes: 0,
1206
+ totalSavedTokens: 0,
1207
+ };
1208
+
1209
+ const sessionsDir = opts.sessionsDir
1210
+ ?? join(homedir(), ".claude", "context-mode", "sessions");
1211
+ if (!existsSync(sessionsDir)) return empty;
1212
+
1213
+ let dbFiles: string[] = [];
1214
+ try {
1215
+ dbFiles = readdirSync(sessionsDir).filter((f) => {
1216
+ if (!f.endsWith(".db")) return false;
1217
+ if (opts.worktreeHash && !f.startsWith(opts.worktreeHash)) return false;
1218
+ return true;
1219
+ });
1220
+ } catch { return empty; }
1221
+ if (dbFiles.length === 0) return empty;
1222
+
1223
+ let DatabaseCtor: ReturnType<typeof loadDatabaseImpl> | null = null;
1224
+ try {
1225
+ DatabaseCtor = opts.loadDatabase
1226
+ ? (opts.loadDatabase() as ReturnType<typeof loadDatabaseImpl>)
1227
+ : loadDatabaseImpl();
1228
+ } catch { return empty; }
1229
+ if (!DatabaseCtor) return empty;
1230
+
1231
+ let eventDataBytes = 0;
1232
+ let bytesAvoided = 0;
1233
+ let bytesReturned = 0;
1234
+ let snapshotBytes = 0;
1235
+
1236
+ // Each branch returns the tuple in the SAME column order so callers
1237
+ // don't need to type-narrow per row.
1238
+ for (const file of dbFiles) {
1239
+ const dbPath = join(sessionsDir, file);
1240
+ // v1.0.148 hotfix: historical DBs were created with pre-v1.0.130
1241
+ // schema (no bytes_avoided / bytes_returned / project_dir columns).
1242
+ // The SELECT below references those columns, so without an in-place
1243
+ // migration the prepare() throws and the surrounding catch silently
1244
+ // skips the WHOLE DB — losing even the LENGTH(data) signal. Run the
1245
+ // shared migration helper before opening readonly. Idempotent: a
1246
+ // PRAGMA check inside the helper short-circuits when the DB is
1247
+ // already current, so post-first-read calls are cheap.
1248
+ ensureSessionEventsSchema(dbPath, DatabaseCtor as unknown as new (path: string, opts?: { readonly?: boolean }) => {
1249
+ pragma: (q: string) => Array<{ name: string }>;
1250
+ exec: (sql: string) => void;
1251
+ close: () => void;
1252
+ });
1253
+ try {
1254
+ const sdb = new DatabaseCtor(dbPath, { readonly: true });
1255
+ try {
1256
+ if (opts.sessionId) {
1257
+ const row = sdb.prepare(
1258
+ `SELECT
1259
+ COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
1260
+ COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
1261
+ COALESCE(SUM(bytes_returned), 0) AS bytes_returned
1262
+ FROM session_events WHERE session_id = ?`,
1263
+ ).get(opts.sessionId) as
1264
+ | { data_bytes: number; bytes_avoided: number; bytes_returned: number }
1265
+ | undefined;
1266
+ if (row) {
1267
+ eventDataBytes += Number(row.data_bytes ?? 0);
1268
+ bytesAvoided += Number(row.bytes_avoided ?? 0);
1269
+ bytesReturned += Number(row.bytes_returned ?? 0);
1270
+ }
1271
+ try {
1272
+ const snap = sdb.prepare(
1273
+ "SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume WHERE session_id = ?",
1274
+ ).get(opts.sessionId) as { bytes: number } | undefined;
1275
+ if (snap?.bytes) snapshotBytes += Number(snap.bytes);
1276
+ } catch { /* old schema */ }
1277
+ try {
1278
+ // "With context-mode" = the bytes the model paid to ACCESS the
1279
+ // kept-out content: ctx_search (query the index) + ctx_fetch_and_index
1280
+ // (fetch + index a URL). Sandbox compute (ctx_execute/batch/file) is
1281
+ // work-output the model would see regardless — NOT redirect savings —
1282
+ // so it is excluded; folding it crushed the bar to a false ~43%.
1283
+ const tc = sdb.prepare(
1284
+ `SELECT COALESCE(SUM(bytes_returned), 0) AS bytes FROM tool_calls
1285
+ WHERE session_id = ? AND tool IN ('ctx_search', 'ctx_fetch_and_index')`,
1286
+ ).get(opts.sessionId) as { bytes: number } | undefined;
1287
+ if (tc?.bytes) bytesReturned += Number(tc.bytes);
1288
+ } catch { /* old schema: no tool_calls table */ }
1289
+ } else if (opts.projectDir) {
1290
+ // Bug E+F: META-scoped aggregation. Take every session_id whose
1291
+ // session_meta.project_dir matches, then sum ALL of those
1292
+ // sessions' events regardless of the events' own project_dir
1293
+ // (sandbox-burst PID sessions write empty event-level project_dir
1294
+ // even when their META carries the parent cwd).
1295
+ const row = sdb.prepare(
1296
+ `SELECT
1297
+ COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
1298
+ COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
1299
+ COALESCE(SUM(bytes_returned), 0) AS bytes_returned
1300
+ FROM session_events
1301
+ WHERE session_id IN (
1302
+ SELECT session_id FROM session_meta WHERE project_dir = ?
1303
+ )`,
1304
+ ).get(opts.projectDir) as
1305
+ | { data_bytes: number; bytes_avoided: number; bytes_returned: number }
1306
+ | undefined;
1307
+ if (row) {
1308
+ eventDataBytes += Number(row.data_bytes ?? 0);
1309
+ bytesAvoided += Number(row.bytes_avoided ?? 0);
1310
+ bytesReturned += Number(row.bytes_returned ?? 0);
1311
+ }
1312
+ try {
1313
+ const snap = sdb.prepare(
1314
+ `SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes
1315
+ FROM session_resume
1316
+ WHERE session_id IN (
1317
+ SELECT session_id FROM session_meta WHERE project_dir = ?
1318
+ )`,
1319
+ ).get(opts.projectDir) as { bytes: number } | undefined;
1320
+ if (snap?.bytes) snapshotBytes += Number(snap.bytes);
1321
+ } catch { /* old schema */ }
1322
+ try {
1323
+ const tc = sdb.prepare(
1324
+ `SELECT COALESCE(SUM(bytes_returned), 0) AS bytes
1325
+ FROM tool_calls
1326
+ WHERE session_id IN (
1327
+ SELECT session_id FROM session_meta WHERE project_dir = ?
1328
+ )
1329
+ AND tool IN ('ctx_search', 'ctx_fetch_and_index')`,
1330
+ ).get(opts.projectDir) as { bytes: number } | undefined;
1331
+ if (tc?.bytes) bytesReturned += Number(tc.bytes);
1332
+ } catch { /* old schema: no tool_calls table */ }
1333
+ } else {
1334
+ const row = sdb.prepare(
1335
+ `SELECT
1336
+ COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
1337
+ COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
1338
+ COALESCE(SUM(bytes_returned), 0) AS bytes_returned
1339
+ FROM session_events`,
1340
+ ).get() as
1341
+ | { data_bytes: number; bytes_avoided: number; bytes_returned: number }
1342
+ | undefined;
1343
+ if (row) {
1344
+ eventDataBytes += Number(row.data_bytes ?? 0);
1345
+ bytesAvoided += Number(row.bytes_avoided ?? 0);
1346
+ bytesReturned += Number(row.bytes_returned ?? 0);
1347
+ }
1348
+ try {
1349
+ const snap = sdb.prepare(
1350
+ "SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume",
1351
+ ).get() as { bytes: number } | undefined;
1352
+ if (snap?.bytes) snapshotBytes += Number(snap.bytes);
1353
+ } catch { /* old schema */ }
1354
+ try {
1355
+ const tc = sdb.prepare(
1356
+ `SELECT COALESCE(SUM(bytes_returned), 0) AS bytes FROM tool_calls
1357
+ WHERE tool IN ('ctx_search', 'ctx_fetch_and_index')`,
1358
+ ).get() as { bytes: number } | undefined;
1359
+ if (tc?.bytes) bytesReturned += Number(tc.bytes);
1360
+ } catch { /* old schema: no tool_calls table */ }
1361
+ }
1362
+ } finally {
1363
+ sdb.close();
1364
+ }
1365
+ } catch { /* missing tables / corrupt — skip */ }
1366
+ }
1367
+
1368
+ // v1.0.133 Slice 3: fold content DB chunk bytes for this session into
1369
+ // bytesAvoided. Skipped silently when caller didn't pass contentDbPath
1370
+ // (lifetime / project tiers, or pre-Slice-3 callers). Treated as
1371
+ // "avoided" because indexed chunks are bytes that would have been
1372
+ // re-inflated into context on every search if the model had to
1373
+ // re-read raw files.
1374
+ let contentBytes = 0;
1375
+ if (opts.sessionId && opts.contentDbPath) {
1376
+ contentBytes = getContentBytesForSession(
1377
+ opts.sessionId,
1378
+ opts.contentDbPath,
1379
+ { loadDatabase: opts.loadDatabase },
1380
+ );
1381
+ bytesAvoided += contentBytes;
1382
+ }
1383
+
1384
+ const totalSavedTokens = Math.floor(
1385
+ (eventDataBytes + bytesAvoided + snapshotBytes) / 4,
1386
+ );
1387
+
1388
+ return { eventDataBytes, bytesAvoided, bytesReturned, snapshotBytes, contentBytes, totalSavedTokens };
1389
+ }
1390
+
1391
+ /**
1392
+ * v1.0.169 — Section 1 "Where you are now" = the LIVE conversation window.
1393
+ *
1394
+ * A single live conversation fans out into sub-agents and ctx_execute
1395
+ * sub-process sessions. Each runs in its OWN, disposable context window (its
1396
+ * own session_id) — but all under the SAME worktree DB, because the worktree
1397
+ * hash is sha256(cwd) and they share the cwd. Their retrieval (ctx_search /
1398
+ * ctx_fetch_and_index returns) entered THOSE windows and was thrown away when
1399
+ * each returned its short summary; it never touched the window the user is
1400
+ * reading now. So the live-window savings bar must split the worktree by
1401
+ * which retrieval actually landed in the user's window:
1402
+ *
1403
+ * bytesReturned ("With context-mode") = THIS session's retrieval only —
1404
+ * what genuinely entered the live window.
1405
+ * bytesAvoided ("kept out") = everything the whole worktree moved
1406
+ * (avoided + every session's retrieval) MINUS what landed in your window.
1407
+ *
1408
+ * Scoping by `worktreeHash` (not project-root + time) means the user's OTHER
1409
+ * parallel worktrees never bleed in — a different worktree is a different
1410
+ * cwd-hash, hence a different DB file the prefix filter excludes — while the
1411
+ * sub-agent fan-out this conversation actually spawned is fully credited.
1412
+ */
1413
+ export function getConversationWindowStats(opts: {
1414
+ sessionId: string;
1415
+ worktreeHash: string;
1416
+ sessionsDir?: string;
1417
+ contentDbPath?: string;
1418
+ }): RealBytesStats {
1419
+ // Whole current worktree: every session that shares this cwd-hash DB.
1420
+ const pool = getRealBytesStats({
1421
+ worktreeHash: opts.worktreeHash,
1422
+ sessionsDir: opts.sessionsDir,
1423
+ });
1424
+ // Just the live window: this session_id (folds its own ctx_search/ctx_fetch
1425
+ // retrieval + content chunks).
1426
+ const mine = getRealBytesStats({
1427
+ sessionId: opts.sessionId,
1428
+ worktreeHash: opts.worktreeHash,
1429
+ sessionsDir: opts.sessionsDir,
1430
+ contentDbPath: opts.contentDbPath,
1431
+ });
1432
+
1433
+ const windowReturned = mine.bytesReturned;
1434
+ const movedTotal = pool.bytesAvoided + pool.bytesReturned;
1435
+ // What context-mode kept OUT of the live window = everything moved across the
1436
+ // worktree minus the slice that actually entered this window. Clamp at 0 so a
1437
+ // stale/edge DB can never produce a negative bar.
1438
+ const keptOut = Math.max(0, movedTotal - windowReturned);
1439
+
1440
+ return {
1441
+ eventDataBytes: pool.eventDataBytes,
1442
+ bytesAvoided: keptOut,
1443
+ bytesReturned: windowReturned,
1444
+ snapshotBytes: pool.snapshotBytes,
1445
+ contentBytes: mine.contentBytes,
1446
+ totalSavedTokens: Math.floor(
1447
+ (pool.eventDataBytes + keptOut + pool.snapshotBytes) / 4,
1448
+ ),
1449
+ };
1450
+ }
1451
+
1452
+ // ─────────────────────────────────────────────────────────
1453
+ // Multi-adapter aggregation (B3a — "your work everywhere")
1454
+ // ─────────────────────────────────────────────────────────
1455
+
1456
+ /**
1457
+ * Real-usage filter thresholds. Decided in the B3a /diagnose conversation
1458
+ * to suppress fixture-noise dirs (test runs that touched ~/.X but never
1459
+ * carried real user work).
1460
+ *
1461
+ * An adapter is `isReal=true` iff ALL four hold:
1462
+ * eventCount >= 100
1463
+ * distinctProjects >= 5
1464
+ * lastActivity within 30 days
1465
+ * avgEventBytes >= 50
1466
+ *
1467
+ * Tuneable via `getMultiAdapterLifetimeStats({ filter })` for testing.
1468
+ */
1469
+ export interface RealUsageFilter {
1470
+ minEvents?: number;
1471
+ minProjects?: number;
1472
+ recencyMs?: number;
1473
+ minAvgBytes?: number;
1474
+ /** Fixed "now" timestamp for deterministic testing. Defaults to Date.now(). */
1475
+ nowMs?: number;
1476
+ }
1477
+
1478
+ const DEFAULT_REAL_USAGE_FILTER: Required<Omit<RealUsageFilter, "nowMs">> = {
1479
+ minEvents: 100,
1480
+ minProjects: 5,
1481
+ recencyMs: 30 * 86_400_000,
1482
+ minAvgBytes: 50,
1483
+ };
1484
+
1485
+ /** Per-adapter scan result returned by {@link scanOneAdapter}. */
1486
+ export interface AdapterScanResult {
1487
+ /** Adapter id (matches `enumerateAdapterDirs().name`). */
1488
+ name: string;
1489
+ /** Total event rows across every `*.db` in this adapter's sessions dir. */
1490
+ eventCount: number;
1491
+ /** Total distinct session_meta rows across every db. */
1492
+ sessionCount: number;
1493
+ /** Sum of LENGTH(data) across every session_event row. */
1494
+ dataBytes: number;
1495
+ /** Sum of LENGTH(snapshot) across consumed compact-rescue snapshots. */
1496
+ rescueBytes: number;
1497
+ /** Reserved for future content/ scan (B3b). 0 today. */
1498
+ contentBytes: number;
1499
+ /** Distinct session_id count across all dbs (alias of sessionCount). */
1500
+ uuidConvs: number;
1501
+ /** Distinct project_dir values across all session_events. */
1502
+ projectDirs: string[];
1503
+ /** Earliest event ms epoch (Number.POSITIVE_INFINITY when no events). */
1504
+ firstMs: number;
1505
+ /** Latest event ms epoch (0 when no events). */
1506
+ lastMs: number;
1507
+ /** Real-usage flag — see {@link RealUsageFilter}. */
1508
+ isReal: boolean;
1509
+ }
1510
+
1511
+ /**
1512
+ * Scan one adapter's sessions dir. Always returns a result — never throws.
1513
+ * When the dir is missing, the result has zeroed counts and `isReal=false`.
1514
+ *
1515
+ * Mirrors the inner SessionDB-walk inside `getLifetimeStats`
1516
+ * (analytics.ts:677-752) so the new multi-adapter path stays in lock-step
1517
+ * with the per-DB queries the single-dir path already trusts.
1518
+ */
1519
+ function scanOneAdapter(
1520
+ entry: AdapterDirEntry,
1521
+ loadDb: () => unknown,
1522
+ filter: Required<Omit<RealUsageFilter, "nowMs">> & { nowMs: number },
1523
+ ): AdapterScanResult {
1524
+ const result: AdapterScanResult = {
1525
+ name: entry.name,
1526
+ eventCount: 0,
1527
+ sessionCount: 0,
1528
+ dataBytes: 0,
1529
+ rescueBytes: 0,
1530
+ contentBytes: 0,
1531
+ uuidConvs: 0,
1532
+ projectDirs: [],
1533
+ firstMs: Number.POSITIVE_INFINITY,
1534
+ lastMs: 0,
1535
+ isReal: false,
1536
+ };
1537
+ if (!existsSync(entry.sessionsDir)) return result;
1538
+
1539
+ let dbFiles: string[] = [];
1540
+ try {
1541
+ dbFiles = readdirSync(entry.sessionsDir).filter((f) => f.endsWith(".db"));
1542
+ } catch { return result; }
1543
+ if (dbFiles.length === 0) return result;
1544
+
1545
+ let DatabaseCtor: ReturnType<typeof loadDatabaseImpl> | null = null;
1546
+ try {
1547
+ DatabaseCtor = loadDb() as ReturnType<typeof loadDatabaseImpl>;
1548
+ } catch { return result; }
1549
+ if (!DatabaseCtor) return result;
1550
+
1551
+ const projectsSet = new Set<string>();
1552
+ const sessionsSet = new Set<string>();
1553
+
1554
+ for (const file of dbFiles) {
1555
+ const dbPath = join(entry.sessionsDir, file);
1556
+ try {
1557
+ const sdb = new DatabaseCtor(dbPath, { readonly: true });
1558
+ try {
1559
+ const ev = sdb.prepare(
1560
+ "SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events",
1561
+ ).get() as { cnt: number; bytes: number } | undefined;
1562
+ if (ev) {
1563
+ result.eventCount += Number(ev.cnt ?? 0);
1564
+ result.dataBytes += Number(ev.bytes ?? 0);
1565
+ }
1566
+ try {
1567
+ const ss = sdb.prepare(
1568
+ "SELECT COUNT(*) AS cnt FROM session_meta",
1569
+ ).get() as { cnt: number } | undefined;
1570
+ result.sessionCount += Number(ss?.cnt ?? 0);
1571
+ } catch { /* old schema */ }
1572
+ try {
1573
+ const snap = sdb.prepare(
1574
+ "SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1",
1575
+ ).get() as { bytes: number } | undefined;
1576
+ if (snap?.bytes) result.rescueBytes += Number(snap.bytes);
1577
+ } catch { /* old schema */ }
1578
+ try {
1579
+ const range = sdb.prepare(
1580
+ "SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events",
1581
+ ).get() as { mn: string | null; mx: string | null } | undefined;
1582
+ if (range?.mn) {
1583
+ const t = Date.parse(range.mn + (range.mn.endsWith("Z") ? "" : "Z"));
1584
+ if (Number.isFinite(t) && t < result.firstMs) result.firstMs = t;
1585
+ }
1586
+ if (range?.mx) {
1587
+ const t = Date.parse(range.mx + (range.mx.endsWith("Z") ? "" : "Z"));
1588
+ if (Number.isFinite(t) && t > result.lastMs) result.lastMs = t;
1589
+ }
1590
+ } catch { /* old schema */ }
1591
+ try {
1592
+ const projRows = sdb.prepare(
1593
+ "SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''",
1594
+ ).all() as Array<{ p: string }>;
1595
+ for (const row of projRows) if (row.p) projectsSet.add(row.p);
1596
+ } catch { /* old schema */ }
1597
+ try {
1598
+ const sidRows = sdb.prepare(
1599
+ "SELECT DISTINCT session_id AS s FROM session_events",
1600
+ ).all() as Array<{ s: string }>;
1601
+ for (const row of sidRows) if (row.s) sessionsSet.add(row.s);
1602
+ } catch { /* old schema */ }
1603
+ } finally {
1604
+ sdb.close();
1605
+ }
1606
+ } catch { /* missing tables / corrupt — skip */ }
1607
+ }
1608
+
1609
+ result.projectDirs = Array.from(projectsSet);
1610
+ result.uuidConvs = sessionsSet.size;
1611
+
1612
+ // Real-usage filter — see RealUsageFilter docstring.
1613
+ const avgBytes = result.eventCount > 0 ? result.dataBytes / result.eventCount : 0;
1614
+ const recentEnough =
1615
+ result.lastMs > 0 && (filter.nowMs - result.lastMs) <= filter.recencyMs;
1616
+ result.isReal =
1617
+ result.eventCount >= filter.minEvents &&
1618
+ projectsSet.size >= filter.minProjects &&
1619
+ recentEnough &&
1620
+ avgBytes >= filter.minAvgBytes;
1621
+
1622
+ return result;
1623
+ }
1624
+
1625
+ /** Aggregated multi-adapter lifetime stats. */
1626
+ export interface MultiAdapterLifetimeStats {
1627
+ /** Sum of eventCount across every adapter that exists on disk. */
1628
+ totalEvents: number;
1629
+ /** Sum of sessionCount across every adapter. */
1630
+ totalSessions: number;
1631
+ /** Sum of dataBytes + rescueBytes across every adapter. */
1632
+ totalBytes: number;
1633
+ /** Per-adapter rows for adapters that have >= one .db file. */
1634
+ perAdapter: AdapterScanResult[];
1635
+ }
1636
+
1637
+ /**
1638
+ * Aggregate lifetime stats across every adapter dir under `home`.
1639
+ * The marketing line — "your work everywhere on this machine across all
1640
+ * AI tools" — depends on this. Existing `getLifetimeStats` (single dir)
1641
+ * is untouched; this is purely additive.
1642
+ */
1643
+ export function getMultiAdapterLifetimeStats(opts?: {
1644
+ home?: string;
1645
+ loadDatabase?: () => unknown;
1646
+ filter?: RealUsageFilter;
1647
+ }): MultiAdapterLifetimeStats {
1648
+ const dirs = enumerateAdapterDirs({ home: opts?.home });
1649
+ const loadDb = opts?.loadDatabase ?? loadDatabaseImpl;
1650
+ const filter = {
1651
+ ...DEFAULT_REAL_USAGE_FILTER,
1652
+ ...(opts?.filter ?? {}),
1653
+ nowMs: opts?.filter?.nowMs ?? Date.now(),
1654
+ };
1655
+
1656
+ const perAdapter: AdapterScanResult[] = [];
1657
+ let totalEvents = 0;
1658
+ let totalSessions = 0;
1659
+ let totalBytes = 0;
1660
+
1661
+ for (const entry of dirs) {
1662
+ if (!existsSync(entry.sessionsDir)) continue; // only surface adapters with a sessions dir
1663
+ const r = scanOneAdapter(entry, loadDb, filter);
1664
+ perAdapter.push(r);
1665
+ totalEvents += r.eventCount;
1666
+ totalSessions += r.sessionCount;
1667
+ totalBytes += r.dataBytes + r.rescueBytes;
1668
+ }
1669
+
1670
+ return { totalEvents, totalSessions, totalBytes, perAdapter };
1671
+ }
1672
+
1673
+ /** Aggregated multi-adapter real-bytes stats. */
1674
+ export interface MultiAdapterRealBytesStats extends RealBytesStats {
1675
+ /** Per-adapter row in the same shape as {@link RealBytesStats}, keyed by name. */
1676
+ perAdapter: Array<RealBytesStats & { name: string }>;
1677
+ }
1678
+
1679
+ /**
1680
+ * Aggregate real-bytes stats across every adapter dir under `home`.
1681
+ * Mirrors `getRealBytesStats` (single dir, analytics.ts:887-989) but
1682
+ * iterates {@link enumerateAdapterDirs}. Optional `sessionId` /
1683
+ * `worktreeHash` filters apply uniformly to every dir.
1684
+ */
1685
+ export function getMultiAdapterRealBytesStats(opts?: {
1686
+ home?: string;
1687
+ sessionId?: string;
1688
+ worktreeHash?: string;
1689
+ loadDatabase?: () => unknown;
1690
+ }): MultiAdapterRealBytesStats {
1691
+ const dirs = enumerateAdapterDirs({ home: opts?.home });
1692
+
1693
+ const sum: RealBytesStats = {
1694
+ eventDataBytes: 0,
1695
+ bytesAvoided: 0,
1696
+ bytesReturned: 0,
1697
+ snapshotBytes: 0,
1698
+ contentBytes: 0,
1699
+ totalSavedTokens: 0,
1700
+ };
1701
+ const perAdapter: MultiAdapterRealBytesStats["perAdapter"] = [];
1702
+
1703
+ for (const entry of dirs) {
1704
+ if (!existsSync(entry.sessionsDir)) continue;
1705
+ const one = getRealBytesStats({
1706
+ sessionsDir: entry.sessionsDir,
1707
+ sessionId: opts?.sessionId,
1708
+ worktreeHash: opts?.worktreeHash,
1709
+ loadDatabase: opts?.loadDatabase,
1710
+ });
1711
+ // ARCH-REVIEW-V134-ABC SLICE C: aggregate this adapter's content DB
1712
+ // bytes into the lifetime sum. `getRealBytesStats` operates on
1713
+ // session events only and never touches the sibling content/ tree —
1714
+ // without this step the lifetime tier in ctx_stats reports 0 for
1715
+ // every adapter except whichever one happens to share the
1716
+ // sessionsDir of the caller. Lifetime tier ignores sessionId so
1717
+ // the all-sessions aggregator is the right helper here.
1718
+ if (!opts?.sessionId) {
1719
+ const contentDbPath = join(entry.contentDir, "content.db");
1720
+ const adapterContentBytes = getContentBytesAllSessions(contentDbPath, {
1721
+ loadDatabase: opts?.loadDatabase as (() => unknown) | undefined,
1722
+ });
1723
+ one.contentBytes += adapterContentBytes;
1724
+ sum.contentBytes += adapterContentBytes;
1725
+ }
1726
+ perAdapter.push({ name: entry.name, ...one });
1727
+ sum.eventDataBytes += one.eventDataBytes;
1728
+ sum.bytesAvoided += one.bytesAvoided;
1729
+ sum.bytesReturned += one.bytesReturned;
1730
+ sum.snapshotBytes += one.snapshotBytes;
1731
+ }
1732
+ sum.totalSavedTokens = Math.floor(
1733
+ (sum.eventDataBytes + sum.bytesAvoided + sum.snapshotBytes) / 4,
1734
+ );
1735
+
1736
+ return { ...sum, perAdapter };
1737
+ }
1738
+
1739
+ /**
1740
+ * Marketing-grade labels for auto-memory file prefixes. The renderer sees raw
1741
+ * filename prefixes (`project_codex_hooks.md` → `project`) — without this map
1742
+ * the user gets schema words in the UI, which leaks the database into UX.
1743
+ */
1744
+ export const autoMemoryLabels: Record<string, string> = {
1745
+ project: "What you're building",
1746
+ feedback: "How you work",
1747
+ user: "Who you are",
1748
+ reference: "Where to look",
1749
+ memory: "Long-term context",
1750
+ other: "Other notes",
1751
+ };
1752
+
1753
+ /**
1754
+ * Marketing-grade labels for adapter ids surfaced by
1755
+ * {@link enumerateAdapterDirs} / {@link getMultiAdapterLifetimeStats}.
1756
+ * The renderer never shows raw IDs — UX uses the names users see in
1757
+ * each tool's own surface area.
1758
+ */
1759
+ export const adapterLabels: Record<string, string> = {
1760
+ "claude-code": "Claude Code",
1761
+ "gemini-cli": "Gemini CLI",
1762
+ "antigravity": "Antigravity",
1763
+ "antigravity-cli": "Antigravity CLI",
1764
+ "openclaw": "Openclaw",
1765
+ "codex": "Codex CLI",
1766
+ "cursor": "Cursor",
1767
+ "vscode-copilot": "VS Code Copilot",
1768
+ "copilot-cli": "GitHub Copilot CLI",
1769
+ "kiro": "Kiro",
1770
+ "pi": "Pi",
1771
+ "omp": "OMP",
1772
+ "qwen-code": "Qwen Code",
1773
+ "kilo": "Kilo",
1774
+ "opencode": "OpenCode",
1775
+ "zed": "Zed",
1776
+ "jetbrains-copilot": "JetBrains",
1777
+ };
1778
+
1779
+ /** Look up an adapter's marketing label. Falls back to the raw id. */
1780
+ function adapterLabel(name: string): string {
1781
+ return adapterLabels[name] ?? name;
1782
+ }
1783
+
1784
+ // ─────────────────────────────────────────────────────────
1785
+ // formatReport — renders FullReport as sales-grade savings dashboard
1786
+ // ─────────────────────────────────────────────────────────
1787
+
1788
+ /**
1789
+ * Format a byte count for the narrative dashboard.
1790
+ *
1791
+ * Single-unit auto-scale (Grafana / CloudWatch / Datadog convention).
1792
+ * Decimals shrink as the integer part grows so the number stays readable
1793
+ * at every magnitude. Max output width is 8 characters which fits the
1794
+ * existing `padStart(8)` callsites in Sections 1, 3, 4.
1795
+ *
1796
+ * < 1 KB → "X B" e.g. "100 B"
1797
+ * 1 KB – < 100 KB → "X.Y KB" e.g. "4.7 KB", "92.8 KB"
1798
+ * 100 KB – < 1 MB → "X KB" e.g. "227 KB", "976 KB"
1799
+ * 1 MB – < 100 MB → "X.Y MB" e.g. "4.5 MB", "11.6 MB"
1800
+ * 100 MB – < 1 GB → "X MB" e.g. "178 MB", "906 MB"
1801
+ * 1 GB – < 100 GB → "X.YY GB" e.g. "1.00 GB", "11.36 GB"
1802
+ * ≥ 100 GB → "X.Y GB" e.g. "216.6 GB"
1803
+ *
1804
+ * Replaced the dual-unit "X KB (0.YY MB)" form because the parenthetical
1805
+ * rounded to 0.00 / 0.01 in the common range and added noise without
1806
+ * information. Scale awareness comes from the unit jump between rows.
1807
+ */
1808
+ export function kb(b: number): string {
1809
+ if (!Number.isFinite(b) || b <= 0) return "0 B";
1810
+ if (b < 1024) return `${Math.round(b)} B`;
1811
+
1812
+ const KB = b / 1024;
1813
+ if (KB < 1024) {
1814
+ return KB < 100 ? `${KB.toFixed(1)} KB` : `${Math.round(KB)} KB`;
1815
+ }
1816
+
1817
+ const MB = KB / 1024;
1818
+ if (MB < 1024) {
1819
+ return MB < 100 ? `${MB.toFixed(1)} MB` : `${Math.round(MB)} MB`;
1820
+ }
1821
+
1822
+ const GB = MB / 1024;
1823
+ return GB < 100 ? `${GB.toFixed(2)} GB` : `${GB.toFixed(1)} GB`;
1824
+ }
1825
+
1826
+ /** Format session uptime as human-readable duration. */
1827
+ function formatDuration(uptimeMin: string): string {
1828
+ const min = parseFloat(uptimeMin);
1829
+ if (isNaN(min) || min < 1) return "< 1 min";
1830
+ if (min < 60) return `${Math.round(min)} min`;
1831
+ const h = Math.floor(min / 60);
1832
+ const m = Math.round(min % 60);
1833
+ return m > 0 ? `${h}h ${m}m` : `${h}h`;
1834
+ }
1835
+
1836
+ /**
1837
+ * Locale + IANA-timezone detection for the narrative renderer.
1838
+ *
1839
+ * Cascade (each level overrides the next):
1840
+ * 1. CONTEXT_MODE_LOCALE / CONTEXT_MODE_TZ env overrides
1841
+ * (used by tests + by users who want to pin output regardless of OS).
1842
+ * 2. macOS `defaults read -g AppleLocale` → `en_TR` style → `en-TR`.
1843
+ * 3. Linux `LANG` / `LC_TIME` env vars.
1844
+ * 4. Fallback: `Intl.DateTimeFormat().resolvedOptions().locale`.
1845
+ *
1846
+ * Timezone always uses `Intl.DateTimeFormat().resolvedOptions().timeZone`
1847
+ * — that one's always available and correct regardless of platform.
1848
+ */
1849
+ /**
1850
+ * Validate that a locale string is a usable BCP 47 tag.
1851
+ *
1852
+ * Ubuntu GHA runners default to `LANG=C.UTF-8`. The extractor below strips
1853
+ * that to `"C"` — a valid POSIX locale identifier but NOT a BCP 47 tag.
1854
+ * On macOS / Node 20, `new Intl.DateTimeFormat("C", …)` throws RangeError
1855
+ * outright. CI run 25887250971 caught this via the v1.0.134 SLICE B test.
1856
+ *
1857
+ * Earlier fix attempt used a permissive `supportedLocalesOf || construction`
1858
+ * OR check — that was wrong: on Linux + Node 22.5, `new Intl.DateTimeFormat
1859
+ * ("POSIX")` does NOT throw, it silently falls back to the root locale and
1860
+ * still emits garbage at format time. CI run 25904838577 surfaced that —
1861
+ * "POSIX" round-tripped through the validator unchanged.
1862
+ *
1863
+ * Strict gate: `Intl.DateTimeFormat.supportedLocalesOf(tag)` returns `[]` for
1864
+ * any tag that doesn't map to a real language (regardless of whether
1865
+ * construction with that tag throws). That's the contract we want — "is this
1866
+ * a BCP 47 tag the host actually has data for". Construction is an explicit
1867
+ * sanity check; both must pass.
1868
+ */
1869
+ function isUsableBcp47Locale(raw: string): boolean {
1870
+ if (!raw) return false;
1871
+ try {
1872
+ if (Intl.DateTimeFormat.supportedLocalesOf(raw).length === 0) return false;
1873
+ // Belt: confirm construction doesn't throw on this host either.
1874
+ new Intl.DateTimeFormat(raw);
1875
+ return true;
1876
+ } catch {
1877
+ return false;
1878
+ }
1879
+ }
1880
+
1881
+ export function detectLocaleAndTz(): { locale: string; tz: string } {
1882
+ const env = (process.env ?? {}) as Record<string, string | undefined>;
1883
+ let locale = env.CONTEXT_MODE_LOCALE ?? "";
1884
+ if (locale && !isUsableBcp47Locale(locale)) locale = "";
1885
+ if (!locale) {
1886
+ if (process.platform === "darwin") {
1887
+ try {
1888
+ // Top-level import — `require()` throws "Dynamic require ... not
1889
+ // supported" under esbuild's ESM shim and pure ESM Node, which silently
1890
+ // dropped this branch and forced en-US fallback in production.
1891
+ const out = execFileSync("defaults", ["read", "-g", "AppleLocale"], {
1892
+ encoding: "utf8",
1893
+ timeout: 500,
1894
+ }).trim();
1895
+ if (out) locale = out.replace(/_/g, "-");
1896
+ } catch { /* defaults missing or sandbox */ }
1897
+ if (locale && !isUsableBcp47Locale(locale)) locale = "";
1898
+ }
1899
+ if (!locale && (env.LC_TIME || env.LANG)) {
1900
+ const raw = (env.LC_TIME || env.LANG || "").split(".")[0];
1901
+ if (raw) locale = raw.replace(/_/g, "-");
1902
+ // POSIX locale identifiers (`C`, `POSIX`) survive the simple extraction
1903
+ // above but blow up `new Intl.DateTimeFormat(locale, ...)`. Drop and
1904
+ // fall through to the host-default branch below.
1905
+ if (locale && !isUsableBcp47Locale(locale)) locale = "";
1906
+ }
1907
+ if (!locale) {
1908
+ try {
1909
+ locale = new Intl.DateTimeFormat().resolvedOptions().locale;
1910
+ } catch { locale = "en-US"; }
1911
+ }
1912
+ }
1913
+
1914
+ let tz = env.CONTEXT_MODE_TZ ?? "";
1915
+ if (!tz) {
1916
+ try {
1917
+ tz = new Intl.DateTimeFormat().resolvedOptions().timeZone;
1918
+ } catch { tz = "UTC"; }
1919
+ }
1920
+ // Final belt-and-suspenders: if the locale we settled on is somehow still
1921
+ // unusable (env mutation between detection and return, contributor adding
1922
+ // a new extraction path that skips the validator), fall back to en-US so
1923
+ // formatLocalDateTime / monthDay / weekdayCap never throw at render time.
1924
+ if (!isUsableBcp47Locale(locale)) locale = "en-US";
1925
+ return { locale, tz: tz || "UTC" };
1926
+ }
1927
+
1928
+ /**
1929
+ * Format an absolute path as a human-friendly display string by
1930
+ * collapsing `$HOME` → `~`. Returns the input unchanged when no home
1931
+ * prefix matches (e.g. for paths outside $HOME on a CI box).
1932
+ */
1933
+ function shortPath(abs: string): string {
1934
+ const home = homedir();
1935
+ if (!home) return abs;
1936
+ if (abs === home) return "~";
1937
+ // Use platform separator so `C:\Users\Mert\projects\x` collapses to `~\projects\x`
1938
+ // on Windows; previous `home + "/"` check was vacuously false on Windows and
1939
+ // left full absolute paths in the Section 1 narrative opener (round-5 finding).
1940
+ if (abs.startsWith(home + sep)) return "~" + abs.slice(home.length);
1941
+ return abs;
1942
+ }
1943
+
1944
+ /**
1945
+ * Render the section-4 "For example: what would that cost?" block.
1946
+ *
1947
+ * Translates a lifetime token total into a relatable Opus-4 dollar figure
1948
+ * + 3 tangible comparisons (Cursor Pro / Claude Max / weekends of API
1949
+ * coding) + 10-dev team scale projection + alternate-model scale row,
1950
+ * capped with an EXAMPLES disclaimer. The renderer is intentionally
1951
+ * liberal with rounding (whole-month Cursor counts, integer weekends)
1952
+ * because this section is illustrative — the EXAMPLES line tells users
1953
+ * not to confuse it for a bill.
1954
+ *
1955
+ * Returns [] when there's nothing to scale (lifetimeTokens === 0) so
1956
+ * the section disappears cleanly on a fresh install.
1957
+ *
1958
+ * Math constants:
1959
+ * Opus 4.7/4.8 = $5.00 per 1M input tokens (fallback when PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN not set)
1960
+ * Sonnet 4.6 = $3.00 per 1M input tokens
1961
+ * GPT-4o = $2.50 per 1M input tokens
1962
+ * Gemini 2 = $1.25 per 1M input tokens
1963
+ * Haiku 4.5 = $1.00 per 1M input tokens
1964
+ * Cursor Pro = $20 / month → "X months of Cursor Pro"
1965
+ * Claude Max = $200 / month → "X.X months of Claude Max"
1966
+ * Weekend coding ≈ $73.67 → "X weekends of nonstop API coding"
1967
+ * Team multiplier = 10× → "At a 10-dev team scale: ~$X over Y days, or ~$Z/year"
1968
+ */
1969
+ export function renderCostExample(
1970
+ lifetimeBytes: number,
1971
+ lifetimeTokens: number,
1972
+ lifetimeDays: number,
1973
+ ): string[] {
1974
+ if (!Number.isFinite(lifetimeTokens) || lifetimeTokens <= 0) return [];
1975
+
1976
+ const lifetimeUsd = lifetimeTokens * pricePerToken();
1977
+ const usdStr = (n: number, dp: number = 2): string => n.toFixed(dp);
1978
+
1979
+ // Comparison units — kept locally so they're easy to tune without touching
1980
+ // the renderer logic. Cursor Pro & Claude Max are public list prices; the
1981
+ // weekend constant is an intentional approximation calibrated to make
1982
+ // $1399.73 → "19 weekends" line up with the demo target.
1983
+ const cursorMonths = Math.round(lifetimeUsd / 20);
1984
+ const claudeMaxMonths = (lifetimeUsd / 200).toFixed(1);
1985
+ const weekendCount = Math.round(lifetimeUsd / 73.67);
1986
+ const teamUsd = Math.round(lifetimeUsd * 10);
1987
+ const teamYearUsd = lifetimeDays > 0
1988
+ ? Math.round((lifetimeUsd * 10) / lifetimeDays * 365)
1989
+ : 0;
1990
+
1991
+ // Alternate-model scale row — same token count, different per-1M rates.
1992
+ // (Kept for internal reference but unreachable per Mert directive.)
1993
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1994
+ const _sonnetUsd = ((lifetimeTokens * 3.0) / 1_000_000).toFixed(2);
1995
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1996
+ const _gpt4oUsd = ((lifetimeTokens * 2.5) / 1_000_000).toFixed(2);
1997
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1998
+ const _geminiUsd = ((lifetimeTokens * 1.25) / 1_000_000).toFixed(2);
1999
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
2000
+ const _haikuUsd = ((lifetimeTokens * 1.0) / 1_000_000).toFixed(2);
2001
+
2002
+ const usingDynamicPrice =
2003
+ process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN !== undefined;
2004
+ const modelId = process.env.PI_CONTEXT_MODE_MODEL_ID;
2005
+
2006
+ // Mert: "daha marketing ve business value e vermeli, math hesaplamalari ile
2007
+ // kalabalik yapma" — collapse the old 4-block render into ONE headline
2008
+ // number, ONE relatable comparison, ONE team-scale callout.
2009
+ const out: string[] = [];
2010
+
2011
+ if (usingDynamicPrice && modelId) {
2012
+ out.push(
2013
+ ` $${usdStr(lifetimeUsd)} of ${modelId} tokens your team didn't burn.`,
2014
+ );
2015
+ } else if (usingDynamicPrice) {
2016
+ out.push(
2017
+ ` $${usdStr(lifetimeUsd)} of tokens your team didn't burn.`,
2018
+ );
2019
+ } else {
2020
+ out.push(
2021
+ ` $${usdStr(lifetimeUsd)} of Opus 4.7 tokens your team didn't burn.`,
2022
+ );
2023
+ }
2024
+
2025
+ out.push(
2026
+ ` context-mode kept ${kb(lifetimeBytes)} out of context — that's ${cursorMonths} months of Cursor Pro paid for itself.`,
2027
+ );
2028
+ if (teamUsd > 0 && teamYearUsd > 0) {
2029
+ out.push("");
2030
+ out.push(
2031
+ ` Scale across a 10-dev team and that's ~$${teamYearUsd.toLocaleString("en-US")}/year saved.`,
2032
+ );
2033
+ }
2034
+
2035
+ if (!usingDynamicPrice) {
2036
+ out.push("");
2037
+ out.push(
2038
+ ` (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)`,
2039
+ );
2040
+ }
2041
+ return out;
2042
+ }
2043
+
2044
+ /**
2045
+ * Render the full 5-section narrative ("kitap gibi") layout — the
2046
+ * Mert-approved screenshot format the production ctx_stats handler
2047
+ * produces for users with conversation + lifetime + multi-adapter data.
2048
+ *
2049
+ * Order:
2050
+ * Opener
2051
+ * Section 1 — Where you are now (datetime, /compact, timeline)
2052
+ * Section 2 — What this chat captured (per-category bars)
2053
+ * Section 3 — The receipt — getting wider (this conv vs all-work)
2054
+ * Section 4 — For example: what would that cost?
2055
+ * Section 5 — What context-mode learned about how you work (auto-memory)
2056
+ * Footer
2057
+ *
2058
+ * Pure renderer: every input arrives via the args object so this
2059
+ * function is trivially testable end-to-end without mocking process or
2060
+ * Date. The caller (formatReport) is responsible for choosing a `now`
2061
+ * value that matches the conversation's age math and a `cwd` that
2062
+ * matches the user's project — defaults are sensible for production.
2063
+ */
2064
+ function renderNarrative5Section(args: {
2065
+ conversation: ConversationStats;
2066
+ lifetime?: LifetimeStats;
2067
+ multiAdapter?: MultiAdapterLifetimeStats;
2068
+ realBytes?: { lifetime?: RealBytesStats; conversation?: RealBytesStats };
2069
+ cwd: string;
2070
+ locale: string;
2071
+ tz: string;
2072
+ now: number;
2073
+ version?: string;
2074
+ latestVersion?: string | null;
2075
+ }): string[] {
2076
+ const { conversation, lifetime, multiAdapter, realBytes, cwd, locale, tz, now, version, latestVersion } = args;
2077
+ const out: string[] = [];
2078
+
2079
+ // ── Token math (same monotonic-growth invariant as the legacy branch).
2080
+ const convEventsTokens = conversation.events * TOKENS_PER_EVENT;
2081
+ const convRescueTokens = Math.round((conversation.snapshotBytes ?? 0) / 4);
2082
+ const convLegacyTokens = convEventsTokens + convRescueTokens;
2083
+ const convRealTokens = realBytes?.conversation?.totalSavedTokens ?? 0;
2084
+ const conversationTokens = Math.max(convLegacyTokens, convRealTokens);
2085
+
2086
+ const lifetimeEventsTokens = (lifetime?.totalEvents ?? 0) * TOKENS_PER_EVENT;
2087
+ const lifetimeRescueTokens = Math.round((lifetime?.rescueBytes ?? 0) / 4);
2088
+ const lifetimeLegacyTokens = lifetimeEventsTokens + lifetimeRescueTokens;
2089
+ const lifetimeRealTokens = realBytes?.lifetime?.totalSavedTokens ?? 0;
2090
+ const lifetimeTokensWithout = Math.max(lifetimeLegacyTokens, lifetimeRealTokens);
2091
+ // Lifetime "with" — measured when available, else legacy 0.02 fallback.
2092
+ // Honest definition (matches conversation bar below):
2093
+ // "with" = bytes_returned (what the model actually re-saw)
2094
+ // "without" = bytes_returned + bytes_avoided
2095
+ // When the schema has measurement, derive `with` from `bytes_returned/4`.
2096
+ const lifeRet = realBytes?.lifetime?.bytesReturned ?? 0;
2097
+ const lifeAv = realBytes?.lifetime?.bytesAvoided ?? 0;
2098
+ const lifetimeTokensWith = (lifeRet + lifeAv) > 0
2099
+ ? Math.max(1, Math.floor(lifeRet / 4))
2100
+ : Math.max(1, Math.round(lifetimeTokensWithout * 0.02));
2101
+
2102
+ // Bytes from realBytes when present, else derive from tokens (×4 — same
2103
+ // ratio Phase 8 uses everywhere). All-work bytes drives the opener tally
2104
+ // + the section-3 receipt + section-4 cost example.
2105
+ const lifetimeBytes = (multiAdapter?.totalBytes && multiAdapter.totalBytes > 0)
2106
+ ? multiAdapter.totalBytes
2107
+ : lifetimeTokensWithout * 4;
2108
+ const convBytes = realBytes?.conversation
2109
+ ? (realBytes.conversation.eventDataBytes + realBytes.conversation.bytesAvoided + realBytes.conversation.snapshotBytes)
2110
+ : conversationTokens * 4;
2111
+
2112
+ // ── Days alive of THE CONVERSATION (section 1).
2113
+ const convDays = conversation.daysAlive >= 1
2114
+ ? `${conversation.daysAlive.toFixed(1)} days alive · still going`
2115
+ : `${Math.max(1, Math.round(conversation.daysAlive * 24))} hr alive · still going`;
2116
+
2117
+ // ── Lifetime span (opener + receipt) — across every adapter / DB on disk.
2118
+ const sinceMs = lifetime?.firstEventMs ?? multiAdapter?.perAdapter?.[0]?.firstMs ?? 0;
2119
+ const lifetimeDays = sinceMs > 0
2120
+ ? Math.max(1, Math.round((now - sinceMs) / 86_400_000))
2121
+ : 0;
2122
+ const totalConversations = multiAdapter?.totalSessions ?? lifetime?.totalSessions ?? 1;
2123
+ const realAdapterCount = multiAdapter?.perAdapter.filter((a) => a.isReal).length ?? 0;
2124
+ let where: string;
2125
+ if (multiAdapter && realAdapterCount >= 2) {
2126
+ where = `across ${realAdapterCount} AI tools`;
2127
+ } else if (multiAdapter && realAdapterCount === 1) {
2128
+ const onlyReal = multiAdapter.perAdapter.find((a) => a.isReal);
2129
+ where = `in ${onlyReal ? adapterLabel(onlyReal.name) : "Claude Code"}`;
2130
+ } else {
2131
+ where = "in Claude Code";
2132
+ }
2133
+
2134
+ // ── Opener.
2135
+ if (lifetimeDays > 0) {
2136
+ out.push(` Across ${lifetimeDays} days you ran ${fmtNum(totalConversations)} conversations ${where}.`);
2137
+ } else {
2138
+ out.push(` You ran ${fmtNum(totalConversations)} conversations ${where}.`);
2139
+ }
2140
+ // Daily-average sub-line — never tease users with a tiny number when the
2141
+ // average is sub-MB (still informative); fall back to KB display.
2142
+ const dailyBytes = lifetimeDays > 0 ? lifetimeBytes / lifetimeDays : 0;
2143
+ out.push(` context-mode kept ${kb(lifetimeBytes)} out of your context window — about ${kb(dailyBytes)} every single day.`);
2144
+ out.push("");
2145
+ out.push("");
2146
+
2147
+ // ── Section 1 — Where you are now.
2148
+ out.push(" ─── 1. Where you are now ───");
2149
+ out.push("");
2150
+ const startedStr = conversation.firstEventMs && conversation.firstEventMs > 0
2151
+ ? formatLocalDateTime(conversation.firstEventMs, locale, tz)
2152
+ : "";
2153
+ if (startedStr) {
2154
+ out.push(` This conversation started ${startedStr} in ${shortPath(cwd)}.`);
2155
+ } else {
2156
+ out.push(` This conversation lives in ${shortPath(cwd)}.`);
2157
+ }
2158
+ out.push(` ${convDays}.`);
2159
+ if (conversation.snapshotsConsumed > 0 && conversation.snapshotBytes > 0) {
2160
+ const rescueAt = conversation.lastRescueMs && conversation.lastRescueMs > 0
2161
+ ? formatLocalDateTime(conversation.lastRescueMs, locale, tz)
2162
+ : "";
2163
+ const rescueKb = Math.round(conversation.snapshotBytes / 1024);
2164
+ if (rescueAt) {
2165
+ out.push(` On ${rescueAt}, /compact fired — ${rescueKb} KB rescued from snapshot.`);
2166
+ } else {
2167
+ out.push(` /compact fired — ${rescueKb} KB rescued from snapshot.`);
2168
+ }
2169
+ out.push(` Without that, you'd be re-explaining everything to a blank model right now.`);
2170
+ }
2171
+ out.push("");
2172
+
2173
+ // Without/With bars — strict compression (v1.0.148, Bug G / ADR-0004).
2174
+ //
2175
+ // Honest definitions:
2176
+ // Without = bytes the model WOULD have re-seen if context-mode
2177
+ // had not diverted them
2178
+ // = bytesAvoided + bytesReturned
2179
+ // With = bytes the model ACTUALLY re-saw after context-mode
2180
+ // = max(1, bytesReturned)
2181
+ //
2182
+ // Why eventDataBytes is excluded from this ratio:
2183
+ // `eventDataBytes` is the raw hook payload (tool args, prompt
2184
+ // body) we captured for the knowledge base. Those bytes are
2185
+ // analytics infrastructure — they NEVER enter the model context
2186
+ // window. Including them on either side (as v1.0.134 SLICE B did
2187
+ // to dodge a degenerate 100% bar) misrepresents context cost.
2188
+ // SLICE B was an incidental fix that crushed the displayed
2189
+ // percentage from ~95% (the true compression ratio) to ~56% on
2190
+ // live conversations. eventDataBytes is rendered in Section 2
2191
+ // (captures count), not in this Section 1 Without/With bar.
2192
+ //
2193
+ // Empty-state branch:
2194
+ // If neither bytesAvoided nor bytesReturned has been measured yet
2195
+ // (early in a session, schema-migration recovery in progress, or
2196
+ // tool-heavy work that hasn't re-hit the index), we do NOT draw
2197
+ // a degenerate 0% / 100% bar. We emit one honest hint line and
2198
+ // skip the bar — honesty over decoration.
2199
+ const realConv = realBytes?.conversation;
2200
+ const measuredAvoided = realConv?.bytesAvoided ?? 0;
2201
+ const measuredReturned = realConv?.bytesReturned ?? 0;
2202
+
2203
+ if (measuredAvoided + measuredReturned === 0) {
2204
+ // No measurable redirect activity yet — captures may exist, but
2205
+ // nothing has been diverted from the model context window.
2206
+ out.push(" No measurable redirect activity captured yet — bars will appear once context-mode diverts its first payload.");
2207
+ out.push("");
2208
+ } else {
2209
+ const convBytesWithout = measuredAvoided + measuredReturned;
2210
+ const convBytesWith = Math.max(1, measuredReturned);
2211
+ const convTokensWithout = Math.max(1, Math.floor(convBytesWithout / 4));
2212
+ const convTokensWith = Math.max(1, Math.floor(convBytesWith / 4));
2213
+ const withoutBar = dataBar(convTokensWithout, convTokensWithout, 32);
2214
+ const withBar = dataBar(convTokensWith, convTokensWithout, 32);
2215
+ const convPct = (1 - convTokensWith / convTokensWithout) * 100;
2216
+ const convMult = Math.max(1, Math.round(convTokensWithout / convTokensWith));
2217
+ out.push(` Without context-mode ${kb(convBytesWithout).padStart(8)} ${withoutBar} ${fmtNum(convTokensWithout).padStart(7)} tokens`);
2218
+ out.push(` With context-mode ${kb(convBytesWith).padStart(8)} ${withBar} ${fmtNum(convTokensWith).padStart(7)} tokens`);
2219
+ out.push(` ${convPct.toFixed(1)}% kept out of context · your AI ran ${convMult}× longer before /compact fired`);
2220
+ out.push("");
2221
+ }
2222
+
2223
+ // Timeline — drop-in if conversation has byDay.
2224
+ if (conversation.byDay && conversation.byDay.length > 0) {
2225
+ const totalConvDays = conversation.lastEventMs && conversation.firstEventMs
2226
+ ? Math.max(1, Math.round((conversation.lastEventMs - conversation.firstEventMs) / 86_400_000) + 1)
2227
+ : conversation.byDay.length;
2228
+ out.push(` How that ${kb(convBytes)} built up — ${totalConvDays} days, ${conversation.byDay.length} active:`);
2229
+ out.push("");
2230
+ out.push(...renderHorizontalTimeline(conversation.byDay, locale, tz));
2231
+ }
2232
+ out.push("");
2233
+ out.push("");
2234
+
2235
+ // ── Section 2 — What this chat captured.
2236
+ out.push(" ─── 2. What this chat captured (used when you --continue or /resume here) ───");
2237
+ out.push("");
2238
+ const capturedTotal = conversation.byCategory.reduce((s, c) => s + c.count, 0);
2239
+ // Format with locale separator (en-* → "1,277"; en-TR → "1.277").
2240
+ const totalStr = capturedTotal.toLocaleString(locale);
2241
+ out.push(` ${totalStr} things — files, errors, decisions, agent runs:`);
2242
+ out.push("");
2243
+ // ALL categories, no truncation (Slice 5).
2244
+ const max = conversation.byCategory[0]?.count ?? 1;
2245
+ for (const cat of conversation.byCategory) {
2246
+ out.push(` ${cat.label.padEnd(26)} ${String(cat.count).padStart(5)} ${dataBar(cat.count, max, 28)}`);
2247
+ }
2248
+ out.push("");
2249
+ out.push("");
2250
+
2251
+ // ── Section 3 — Scope ladder, prose form (Mert: "cok daginik" → drop columns).
2252
+ // Two short sentences instead of a 4-column table — the same numbers framed
2253
+ // as "this chat" → "all your work" so the reader sees the scope getting wider
2254
+ // without being asked to scan a wide grid.
2255
+ out.push(" ─── 3. The scope, getting wider ───");
2256
+ out.push("");
2257
+ const convStartedYMD = conversation.firstEventMs && conversation.firstEventMs > 0
2258
+ ? new Intl.DateTimeFormat(locale, { timeZone: tz, year: "numeric", month: "short", day: "numeric" })
2259
+ .format(new Date(conversation.firstEventMs))
2260
+ : "";
2261
+ const lifeStartedYMD = sinceMs > 0
2262
+ ? new Intl.DateTimeFormat(locale, { timeZone: tz, year: "numeric", month: "short", day: "numeric" })
2263
+ .format(new Date(sinceMs))
2264
+ : "";
2265
+ const distinctProj = lifetime?.distinctProjects ?? 0;
2266
+ const allCaps = lifetime?.totalEvents ?? multiAdapter?.totalEvents ?? 0;
2267
+ out.push(
2268
+ ` This chat: ${kb(convBytes)} kept out · ${conversation.events.toLocaleString(locale)} captures${convStartedYMD ? ` · started ${convStartedYMD}` : ""}.`,
2269
+ );
2270
+ out.push(
2271
+ ` All your work: ${kb(lifetimeBytes)} kept out · ${allCaps.toLocaleString(locale)} captures across ${distinctProj} project${distinctProj === 1 ? "" : "s"}${lifeStartedYMD ? ` · since ${lifeStartedYMD}` : ""}.`,
2272
+ );
2273
+ out.push("");
2274
+ out.push("");
2275
+
2276
+ // ── Section 4 — Marketing-grade cost framing (Mert: "math hesaplamalari ile
2277
+ // kalabalik yapma" → less math, more business value). One headline, one
2278
+ // optional team-scale callout, no scaling table, no math footnotes.
2279
+ out.push(" ─── 4. The bottom line ───");
2280
+ out.push("");
2281
+ out.push(...renderCostExample(lifetimeBytes, lifetimeTokensWithout, lifetimeDays));
2282
+ out.push("");
2283
+ out.push("");
2284
+
2285
+ // ── Section 5 — What context-mode learned about how you work.
2286
+ out.push(" ─── 5. What context-mode learned about how you work ───");
2287
+ out.push("");
2288
+ if (lifetime && lifetime.autoMemoryCount > 0) {
2289
+ out.push(` ${lifetime.autoMemoryCount} preferences picked up across ${lifetime.autoMemoryProjects} project${lifetime.autoMemoryProjects === 1 ? "" : "s"}:`);
2290
+ const entries = Object.entries(lifetime.autoMemoryByPrefix).sort((a, b) => b[1] - a[1]);
2291
+ const maxAm = entries.length > 0 ? entries[0][1] : 1;
2292
+ for (const [prefix, count] of entries) {
2293
+ const label = autoMemoryLabels[prefix] ?? prefix;
2294
+ out.push(` ${label.padEnd(26)} ${String(count).padStart(2)} ${dataBar(count, maxAm, 20)}`);
2295
+ }
2296
+ } else {
2297
+ out.push(" No preferences learned yet — context-mode picks them up automatically.");
2298
+ }
2299
+ out.push("");
2300
+ out.push("");
2301
+
2302
+ // ── Footer.
2303
+ out.push(" Your AI talks less, remembers more, costs less.");
2304
+ out.push(` Locale ${locale} · timezone ${tz} · pricing examples for illustration only.`);
2305
+ out.push("");
2306
+ const versionStr = version ? `v${version}` : "context-mode";
2307
+ out.push(` ${versionStr}`);
2308
+ if (version && latestVersion && latestVersion !== "unknown" && semverNewer(latestVersion, version)) {
2309
+ out.push(` Update available: v${version} -> v${latestVersion} | ctx_upgrade`);
2310
+ }
2311
+
2312
+ // Suppress consecutive blank lines / leading blanks for tidier output —
2313
+ // we use `push("")` liberally above as paragraph separators, easier to
2314
+ // collapse here than to track flag state inline.
2315
+ return collapseBlanks(out);
2316
+ }
2317
+
2318
+ /** Drop runs of >2 consecutive blank strings so the renderer never emits visual gaps. */
2319
+ function collapseBlanks(lines: string[]): string[] {
2320
+ const out: string[] = [];
2321
+ let blankRun = 0;
2322
+ for (const ln of lines) {
2323
+ if (ln === "") {
2324
+ blankRun++;
2325
+ if (blankRun <= 2) out.push(ln);
2326
+ } else {
2327
+ blankRun = 0;
2328
+ out.push(ln);
2329
+ }
2330
+ }
2331
+ // Trim trailing blanks.
2332
+ while (out.length > 0 && out[out.length - 1] === "") out.pop();
2333
+ return out;
2334
+ }
2335
+
2336
+ /**
2337
+ * One day on the horizontal narrative timeline. `ms` is midnight-UTC of
2338
+ * the day (caller is responsible for normalising); `count` is captures
2339
+ * for that day; `rescueBytes` (when >0) overlays the ◆ /compact glyph.
2340
+ */
2341
+ export interface TimelineDay {
2342
+ ms: number;
2343
+ count: number;
2344
+ rescueBytes?: number;
2345
+ }
2346
+
2347
+ /**
2348
+ * Render the proportional-spacing horizontal day strip used in section 1
2349
+ * of the 5-section narrative. Returns the lines verbatim ready to splice
2350
+ * into the formatReport line buffer:
2351
+ *
2352
+ * apr 28 ●──────────────────────●────█──────────────────────◆────● may 10
2353
+ *
2354
+ * apr 28 277 captures
2355
+ * may 4 438 captures ← peak
2356
+ * may 9 261 captures ◆ /compact rescued 1552 KB
2357
+ * may 10 100 captures
2358
+ *
2359
+ * ● active day █ peak day ◆ /compact rescue
2360
+ *
2361
+ * The strip body is exactly 56 chars wide. Day positions are computed as
2362
+ * `round((day - first) / (last - first) * 55)`. Glyph priority for a
2363
+ * column: rescue (◆) > peak (█) > active (●). Filler is the box-drawing
2364
+ * `─` character so the strip reads cleanly in monospace terminals.
2365
+ */
2366
+ export function renderHorizontalTimeline(
2367
+ days: TimelineDay[],
2368
+ locale: string,
2369
+ tz: string,
2370
+ ): string[] {
2371
+ if (days.length === 0) return [];
2372
+ // Sort ascending so first/last bookends + bar positions are stable.
2373
+ const sorted = [...days].sort((a, b) => a.ms - b.ms);
2374
+ const first = sorted[0];
2375
+ const last = sorted[sorted.length - 1];
2376
+ const span = Math.max(1, last.ms - first.ms);
2377
+
2378
+ // Locate the peak day (max count). Ties: earliest wins so the visual
2379
+ // pin matches the chronologically first big day.
2380
+ let peak = sorted[0];
2381
+ for (const d of sorted) if (d.count > peak.count) peak = d;
2382
+
2383
+ // Build the 56-char strip body.
2384
+ const WIDTH = 56;
2385
+ const body = Array.from({ length: WIDTH }, () => "─");
2386
+ for (const d of sorted) {
2387
+ const col = Math.round(((d.ms - first.ms) / span) * (WIDTH - 1));
2388
+ let glyph = "●";
2389
+ if (d === peak) glyph = "█";
2390
+ if ((d.rescueBytes ?? 0) > 0) glyph = "◆"; // rescue beats peak
2391
+ body[col] = glyph;
2392
+ }
2393
+
2394
+ // Lowercase short month names ("apr"/"may"/"jan") matching the target.
2395
+ const monthDay = (ms: number): string => {
2396
+ const dt = new Intl.DateTimeFormat(locale, {
2397
+ timeZone: tz,
2398
+ month: "short",
2399
+ day: "numeric",
2400
+ }).formatToParts(new Date(ms));
2401
+ const month = (dt.find((p) => p.type === "month")?.value ?? "").toLowerCase();
2402
+ const day = dt.find((p) => p.type === "day")?.value ?? "";
2403
+ return `${month} ${day}`;
2404
+ };
2405
+
2406
+ const out: string[] = [];
2407
+ out.push(` ${monthDay(first.ms)} ${body.join("")} ${monthDay(last.ms)}`);
2408
+ out.push("");
2409
+
2410
+ // Daily detail rows — count + " ← peak" + "◆ /compact rescued N KB".
2411
+ for (const d of sorted) {
2412
+ const label = monthDay(d.ms).padEnd(7);
2413
+ const captures = `${d.count} captures`;
2414
+ const peakStr = d === peak ? " ← peak" : "";
2415
+ const rescue = (d.rescueBytes ?? 0) > 0
2416
+ ? ` ◆ /compact rescued ${Math.round((d.rescueBytes ?? 0) / 1024)} KB`
2417
+ : "";
2418
+ out.push(` ${label} ${captures}${peakStr}${rescue}`);
2419
+ }
2420
+ out.push("");
2421
+ out.push(" ● active day █ peak day ◆ /compact rescue");
2422
+ return out;
2423
+ }
2424
+
2425
+ /**
2426
+ * Render a UTC ms timestamp as a human-readable local datetime string in
2427
+ * the canonical Mert-approved format:
2428
+ *
2429
+ * "28 Apr 2026 at 12:16 (Europe/Istanbul)"
2430
+ *
2431
+ * Used by the 5-section narrative renderer (formatReport) so users see
2432
+ * exactly when their conversation started + when /compact rescues fired
2433
+ * in their wall-clock timezone — never UTC, never ambiguous.
2434
+ *
2435
+ * - 24-hour clock with zero-padded minutes ("20:54", not "8:54 PM").
2436
+ * - Day is NOT zero-padded ("9 May", not "09 May") to match the target.
2437
+ * - IANA timezone is appended verbatim in parentheses regardless of
2438
+ * locale so users never misread Istanbul-time as UTC.
2439
+ * - Returns "" for ms === 0 or NaN so callers can guard the rendered
2440
+ * line ("started …") without an extra timestamp-validity check.
2441
+ */
2442
+ export function formatLocalDateTime(ms: number, locale: string, tz: string): string {
2443
+ if (!Number.isFinite(ms) || ms <= 0) return "";
2444
+ const date = new Date(ms);
2445
+ if (Number.isNaN(date.getTime())) return "";
2446
+ // Intl.DateTimeFormat's "day"/"month"/"year" parts give us the locale's
2447
+ // ordering (en-* → "DD MMM YYYY"), and the explicit numeric hour/minute
2448
+ // forces 24-hour with leading zero on minute when in en-* with hour12=false.
2449
+ const dt = new Intl.DateTimeFormat(locale, {
2450
+ timeZone: tz,
2451
+ year: "numeric",
2452
+ month: "short",
2453
+ day: "numeric",
2454
+ hour: "2-digit",
2455
+ minute: "2-digit",
2456
+ hour12: false,
2457
+ }).formatToParts(date);
2458
+ const get = (type: Intl.DateTimeFormatPartTypes): string =>
2459
+ dt.find((p) => p.type === type)?.value ?? "";
2460
+ const day = get("day");
2461
+ const month = get("month");
2462
+ const year = get("year");
2463
+ let hour = get("hour");
2464
+ const min = get("minute");
2465
+ // Some locales / some Node versions emit "24" for midnight under hour12=false.
2466
+ // Coerce back to "00" so the displayed time is always wall-clock-correct.
2467
+ if (hour === "24") hour = "00";
2468
+ return `${day} ${month} ${year} at ${hour}:${min} (${tz})`;
2469
+ }
2470
+
2471
+ /** Format large numbers with K/M suffixes */
2472
+ function fmtNum(n: number): string {
2473
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
2474
+ if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
2475
+ return String(n);
2476
+ }
2477
+
2478
+ // ─────────────────────────────────────────────────────────
2479
+ // Pricing (Bug #6) — Anthropic Opus input rate
2480
+ // ─────────────────────────────────────────────────────────
2481
+
2482
+ // ── Pricing (Bug #6) — per-token USD rate ─────────────────
2483
+ // Reads PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN when set by a Pi host;
2484
+ // falls back to the Opus 4.7/4.8 input rate ($5/1M) for all other adapters.
2485
+ // Verified against platform.claude.com/docs/en/about-claude/pricing 2026-06.
2486
+ //
2487
+ // IMPORTANT: this is a FUNCTION, not a const. Pi sets the env var
2488
+ // AFTER the MCP server has been imported (the bridge spawns the server
2489
+ // child, then the child reads its own env on every render). A
2490
+ // module-load-time const would freeze to the fallback because
2491
+ // process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN is unset at
2492
+ // import time. Resolving on every call keeps the dynamic-pricing
2493
+ // contract honest — the env var works without an MCP restart.
2494
+ // (Reverted module-load const semantics, PR #741 follow-up.)
2495
+
2496
+ /**
2497
+ * Per-token USD rate — resolves on every call.
2498
+ * Dynamic when PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN is set, Opus 4.7/4.8 input
2499
+ * ($5 per 1M tokens) otherwise.
2500
+ */
2501
+ export function pricePerToken(): number {
2502
+ const env = process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN;
2503
+ if (env !== undefined && env !== "") {
2504
+ const parsed = Number(env);
2505
+ if (Number.isFinite(parsed) && parsed > 0) return parsed;
2506
+ }
2507
+ return 5 / 1_000_000; // Opus 4.7/4.8 input fallback
2508
+ }
2509
+
2510
+ /**
2511
+ * Back-compat alias for the original Opus-rate const (PR #401 architect
2512
+ * P1.1 — single source of truth). Kept as a literal so any third-party
2513
+ * consumer importing the named constant still resolves to the same
2514
+ * fallback rate. New code should call pricePerToken() to pick up the
2515
+ * dynamic Pi env override.
2516
+ *
2517
+ * @deprecated Use pricePerToken() to honor PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN.
2518
+ */
2519
+ export const OPUS_INPUT_PRICE_PER_TOKEN = 5 / 1_000_000;
2520
+
2521
+ /** Convert a token count to a USD string at the current per-token rate. */
2522
+ export function tokensToUsd(tokens: number): string {
2523
+ const safe = Number.isFinite(tokens) && tokens > 0 ? tokens : 0;
2524
+ return `$${(safe * pricePerToken()).toFixed(2)}`;
2525
+ }
2526
+
2527
+ /**
2528
+ * Build a proportional bar using █ chars, scaled to a fixed width.
2529
+ * Returns e.g. "████████████████████████████████████████" for full width.
2530
+ */
2531
+ function dataBar(bytes: number, maxBytes: number, width: number = 40): string {
2532
+ if (maxBytes <= 0) return "░".repeat(width);
2533
+ const filled = Math.max(1, Math.round((bytes / maxBytes) * width));
2534
+ return "█".repeat(Math.min(filled, width)) + "░".repeat(Math.max(0, width - filled));
2535
+ }
2536
+
2537
+ /**
2538
+ * Render project memory section with category bars.
2539
+ *
2540
+ * Shows persistent event data, and — when supplied — lifetime totals
2541
+ * across every project's SessionDB so users see the cumulative value
2542
+ * (Bug #3).
2543
+ *
2544
+ * Caps the category list at `topN` and prints "N more categories" with the
2545
+ * actual remaining count (Bug #5 — was hardcoded "9 more").
2546
+ */
2547
+ function renderProjectMemory(
2548
+ pm: FullReport["projectMemory"],
2549
+ opts?: {
2550
+ lifetime?: LifetimeStats;
2551
+ topN?: number;
2552
+ sessionTokensSaved?: number;
2553
+ /**
2554
+ * B3b Slice 3.6 — when supplied, the "All your work" header is
2555
+ * promoted to "All your work everywhere" and the lifetime totals
2556
+ * use the multi-adapter sums (events / sessions / bytes aggregated
2557
+ * across every adapter dir on disk) instead of the single-dir
2558
+ * lifetime numbers. The category bars still come from the single-dir
2559
+ * lifetime.categoryCounts because the multi-adapter scan today does
2560
+ * not bucket categories.
2561
+ */
2562
+ multiAdapter?: MultiAdapterLifetimeStats;
2563
+ },
2564
+ ): string[] {
2565
+ const sessionTokensSaved = opts?.sessionTokensSaved ?? 0;
2566
+ // Render when EITHER disk has data OR current session has earnings.
2567
+ if (
2568
+ pm.total_events === 0 &&
2569
+ (opts?.lifetime?.totalEvents ?? 0) === 0 &&
2570
+ sessionTokensSaved === 0 &&
2571
+ (opts?.multiAdapter?.totalEvents ?? 0) === 0
2572
+ ) {
2573
+ return [];
2574
+ }
2575
+ // Slice 5 — Mert: "honest, no tease". Show ALL categories. The legacy
2576
+ // topN cap silently hid real data; users would screenshot a stats card
2577
+ // missing half their work. The opts.topN parameter stays in the signature
2578
+ // for back-compat with any external caller that explicitly passes a cap.
2579
+ const topN = opts?.topN ?? Number.POSITIVE_INFINITY;
2580
+ const out: string[] = [];
2581
+ out.push("");
2582
+ // Header switches based on whether we have rich lifetime data from the new
2583
+ // pipeline. With it: forward-leaning "All your work" framing. Without it:
2584
+ // legacy "Persistent memory" line for back-compat with older fixtures + tests.
2585
+ // Slice 3.6: promote to "All your work everywhere" when multi-adapter
2586
+ // aggregation is supplied so the receipt scope matches the rendered totals.
2587
+ const ma = opts?.multiAdapter;
2588
+ const realAdapters = ma?.perAdapter.filter((a) => a.isReal).length ?? 0;
2589
+ const lifeEvents = ma?.totalEvents
2590
+ ?? opts?.lifetime?.totalEvents
2591
+ ?? pm.total_events;
2592
+ const lifeSessions = ma?.totalSessions
2593
+ ?? opts?.lifetime?.totalSessions
2594
+ ?? pm.session_count;
2595
+ const distinctProj = opts?.lifetime?.distinctProjects;
2596
+ if (lifeEvents > 0 && distinctProj && distinctProj > 0) {
2597
+ const everywhere = realAdapters >= 2 ? " everywhere" : "";
2598
+ out.push(` All your work${everywhere} · ${fmtNum(lifeEvents)} events captured across ${distinctProj} project${distinctProj === 1 ? "" : "s"} · ${fmtNum(lifeSessions)} conversations`);
2599
+ } else {
2600
+ out.push("Persistent memory ✓ preserved across compact, restart & upgrade");
2601
+ // Current session counts as 1 when no prior session has been recorded yet.
2602
+ const effectiveSessions =
2603
+ lifeSessions === 0 && sessionTokensSaved > 0 ? 1 : lifeSessions;
2604
+ const sessionLabel =
2605
+ effectiveSessions === 1 ? "1 session" : `${fmtNum(effectiveSessions)} sessions`;
2606
+ // Estimate lifetime savings: ~1KB per event → ~256 tokens/event at Opus rates,
2607
+ // plus current session's already-tracked token savings (in-memory).
2608
+ const lifetimeTokens = lifeEvents * 256 + sessionTokensSaved;
2609
+ out.push(` ${fmtNum(lifeEvents)} events · ${sessionLabel} · ~${tokensToUsd(lifetimeTokens)} saved lifetime`);
2610
+ }
2611
+ out.push("");
2612
+
2613
+ // Prefer lifetime categoryCounts (aggregated across every SessionDB) so
2614
+ // the bar block matches the lifetime header above. Falls back to the
2615
+ // project-local pm.by_category when lifetime data is absent (tests, older
2616
+ // callers) or when no sidecar has any events yet.
2617
+ const lifetimeCats = opts?.lifetime?.categoryCounts;
2618
+ let cats: Array<{ category: string; count: number; label: string }>;
2619
+ if (lifetimeCats && Object.keys(lifetimeCats).length > 0) {
2620
+ cats = Object.entries(lifetimeCats)
2621
+ .filter(([, c]) => c > 0)
2622
+ .map(([category, count]) => ({
2623
+ category,
2624
+ count,
2625
+ label: categoryLabels[category] || category,
2626
+ }))
2627
+ .sort((a, b) => b.count - a.count);
2628
+ } else {
2629
+ // Defensive: filter zero/null counts on the fallback path too — bumping
2630
+ // topN to 15 made any leaked empty rows visible as "label 0 ░░░░░░".
2631
+ cats = (pm.by_category ?? []).filter((c) => c && c.count > 0);
2632
+ }
2633
+ const visible = cats.slice(0, topN);
2634
+ const maxCount = visible.length > 0 ? visible[0].count : 1;
2635
+ for (const cat of visible) {
2636
+ out.push(` ${cat.label.padEnd(26)} ${String(cat.count).padStart(5)} ${dataBar(cat.count, maxCount, 30)}`);
2637
+ }
2638
+
2639
+ // Bug #5: real overflow count, not hardcoded.
2640
+ const remaining = Math.max(0, cats.length - topN);
2641
+ if (remaining > 0) {
2642
+ out.push(` ... ${remaining} more categor${remaining === 1 ? "y" : "ies"}`);
2643
+ }
2644
+ return out;
2645
+ }
2646
+
2647
+ /**
2648
+ * Render the auto-memory section (Bug #4) — files Claude Code captured
2649
+ * under ~/.claude/projects/<project>/memory/ across the user's machine.
2650
+ */
2651
+ function renderAutoMemory(lifetime: LifetimeStats | undefined): string[] {
2652
+ if (!lifetime || lifetime.autoMemoryCount === 0) return [];
2653
+ const out: string[] = [];
2654
+ out.push("");
2655
+ out.push(
2656
+ ` Preferences learned · ${lifetime.autoMemoryCount} across ${lifetime.autoMemoryProjects} project${lifetime.autoMemoryProjects === 1 ? "" : "s"}`,
2657
+ );
2658
+
2659
+ const entries = Object.entries(lifetime.autoMemoryByPrefix)
2660
+ .sort((a, b) => b[1] - a[1])
2661
+ .slice(0, 6);
2662
+ // Top entry sets the bar scale so the visual stays proportional even when
2663
+ // the absolute counts are tiny. Entries are pre-sorted desc.
2664
+ const maxCount = entries.length > 0 ? entries[0][1] : 1;
2665
+ for (const [prefix, count] of entries) {
2666
+ const label = autoMemoryLabels[prefix] ?? prefix;
2667
+ out.push(
2668
+ ` ${label.padEnd(26)} ${String(count).padStart(2)} ${dataBar(count, maxCount, 20)}`,
2669
+ );
2670
+ }
2671
+ return out;
2672
+ }
2673
+
2674
+ /** Render the closing "Bottom line" footer (Bug #8). */
2675
+ function renderBottomLine(sessionTokensSaved: number, lifetime: LifetimeStats | undefined): string[] {
2676
+ const out: string[] = [];
2677
+ const sessionUsd = tokensToUsd(sessionTokensSaved);
2678
+ // Lifetime = disk-aggregated events × 256 tokens + current session's
2679
+ // in-memory token savings. Two pipelines unified at the render edge so
2680
+ // lifetime ≥ session always (never the surprising "$X session · $0 lifetime"
2681
+ // a fresh user sees pre-flush).
2682
+ const lifetimeTokens = (lifetime?.totalEvents ?? 0) * 256 + sessionTokensSaved;
2683
+ const lifetimeUsd = tokensToUsd(lifetimeTokens);
2684
+ out.push("");
2685
+ out.push("─".repeat(65));
2686
+ out.push("Your AI talks less, remembers more, costs less.");
2687
+ out.push(`${sessionUsd} this session · ${lifetimeUsd} lifetime`);
2688
+ out.push("─".repeat(65));
2689
+ return out;
2690
+ }
2691
+
2692
+ /**
2693
+ * Constant token-per-event used everywhere we estimate session/lifetime $.
2694
+ * Kept in lockstep with `bin/statusline.mjs`'s persisted lifetime conversion.
2695
+ */
2696
+ const TOKENS_PER_EVENT = 256;
2697
+
2698
+ /**
2699
+ * Render the LIFETIME Without/With hero — the screenshottable receipt.
2700
+ *
2701
+ * Why lifetime and not session: the "$X saved this session" framing is
2702
+ * arbitrary (a fresh PID can show $0 even while the user has weeks of work
2703
+ * banked). Lifetime is real, accumulating, and the number worth screenshotting.
2704
+ * The current conversation's contribution still shows below as a sub-block.
2705
+ */
2706
+ function renderHero(args: {
2707
+ lifetimeTokensWithout: number;
2708
+ lifetimeTokensWith: number;
2709
+ lifetimeUsd: string;
2710
+ lifetimeWithUsd: string;
2711
+ savedPct: number;
2712
+ totalConversations: number;
2713
+ firstDate?: string;
2714
+ }): string[] {
2715
+ const { lifetimeTokensWithout, lifetimeTokensWith, lifetimeUsd, lifetimeWithUsd, savedPct, totalConversations, firstDate } = args;
2716
+ const out: string[] = [];
2717
+ const since = firstDate ? ` · since ${firstDate}` : "";
2718
+ out.push(` ${lifetimeUsd} saved with context-mode · ${savedPct.toFixed(1)}% reduction${since}`);
2719
+ out.push("");
2720
+ const withoutBar = dataBar(lifetimeTokensWithout, lifetimeTokensWithout, 32);
2721
+ const withBar = dataBar(lifetimeTokensWith, lifetimeTokensWithout, 32);
2722
+ out.push(` Without context-mode ${fmtNum(lifetimeTokensWithout).padStart(7)} tokens ${withoutBar} ${lifetimeUsd}`);
2723
+ out.push(` With context-mode ${fmtNum(lifetimeTokensWith).padStart(7)} tokens ${withBar} ${lifetimeWithUsd}`);
2724
+ const kept = lifetimeTokensWithout - lifetimeTokensWith;
2725
+ out.push(` ${fmtNum(kept).padStart(7)} tokens kept out · across ${totalConversations.toLocaleString("en-US")} conversations`);
2726
+ return out;
2727
+ }
2728
+
2729
+ /**
2730
+ * Render the current conversation as a contribution narrative — not a hero.
2731
+ * Highlights the slice of lifetime savings this chat earned + concrete proof
2732
+ * (events, days alive, compact rescues).
2733
+ */
2734
+ function renderConversation(c: ConversationStats, conversationUsd: string, contribPct: number): string[] {
2735
+ const out: string[] = [];
2736
+ const daysStr = c.daysAlive >= 1 ? `${c.daysAlive.toFixed(1)} days` : `${Math.max(1, Math.round(c.daysAlive * 24))} hr`;
2737
+ const pctStr = contribPct >= 1 ? `${contribPct.toFixed(0)}% of all-time` : `<1% of all-time`;
2738
+ out.push(` This conversation contributed ${conversationUsd} · ${pctStr}`);
2739
+ out.push(` ${c.events.toLocaleString("en-US")} events · ${daysStr} alive`);
2740
+ if (c.snapshotsConsumed > 0 && c.snapshotBytes > 0) {
2741
+ const rescuedTokens = Math.round(c.snapshotBytes / 4);
2742
+ out.push(` ${c.snapshotsConsumed} compact weathered · ${fmtNum(rescuedTokens)} tokens rescued from a ${(c.snapshotBytes / 1024).toFixed(0)} KB snapshot`);
2743
+ }
2744
+ out.push("");
2745
+ if (c.byCategory.length === 0) return out;
2746
+ const max = c.byCategory[0].count || 1;
2747
+ for (const cat of c.byCategory) {
2748
+ out.push(` ${cat.label.padEnd(26)} ${String(cat.count).padStart(5)} ${dataBar(cat.count, max, 28)}`);
2749
+ }
2750
+ return out;
2751
+ }
2752
+
2753
+ /**
2754
+ * B3b Slice 3.2/3.3 — render the "Where it came from" sub-block from a
2755
+ * `MultiAdapterLifetimeStats` (analytics.ts:1231-1240). Two layers:
2756
+ *
2757
+ * 1. Real adapters (`isReal=true`) become a table row each:
2758
+ * Tool Captures Indexed Total kept out
2759
+ * Claude Code 17.4K 276.7 MB 291.1 MB
2760
+ * JetBrains — 8.6 MB 8.6 MB
2761
+ *
2762
+ * 2. Filtered adapters (`isReal=false` but with at least one .db on disk)
2763
+ * become a single "Skipped (N): name1, name2, ..." disclosure line so
2764
+ * the user sees that fixtures/probes were intentionally hidden.
2765
+ *
2766
+ * Returns [] when `multiAdapter` is undefined OR when there are no real
2767
+ * adapters AND nothing skipped — keeping the renderer additive (Slice 3.5).
2768
+ */
2769
+ function renderMultiAdapter(multiAdapter: MultiAdapterLifetimeStats | undefined): string[] {
2770
+ if (!multiAdapter) return [];
2771
+ const real: typeof multiAdapter.perAdapter = [];
2772
+ const skipped: typeof multiAdapter.perAdapter = [];
2773
+ for (const a of multiAdapter.perAdapter) (a.isReal ? real : skipped).push(a);
2774
+ if (real.length === 0 && skipped.length === 0) return [];
2775
+
2776
+ const out: string[] = [];
2777
+ if (real.length > 0) {
2778
+ out.push("");
2779
+ out.push("Where it came from (tools you actually used — fixtures + probes filtered):");
2780
+ out.push("");
2781
+ // Column widths chosen so the demo render stays visually aligned even
2782
+ // for adapters with very long marketing names. Right-aligned numerics.
2783
+ const NAME_W = 16;
2784
+ const CAP_W = 10;
2785
+ const IDX_W = 10;
2786
+ const TOT_W = 16;
2787
+ out.push(
2788
+ ` ${"Tool".padEnd(NAME_W)}${"Captures".padStart(CAP_W)}${"Indexed".padStart(IDX_W)}${"Total kept out".padStart(TOT_W)}`,
2789
+ );
2790
+ // Sort by total kept out desc — biggest contributor first.
2791
+ const sorted = [...real].sort(
2792
+ (a, b) => (b.dataBytes + b.rescueBytes) - (a.dataBytes + a.rescueBytes),
2793
+ );
2794
+ for (const a of sorted) {
2795
+ const total = a.dataBytes + a.rescueBytes;
2796
+ // Em-dash for zero captures so the column reads "—" not "0".
2797
+ const captures = a.eventCount > 0 ? fmtNum(a.eventCount) : "—";
2798
+ const indexed = kb(a.dataBytes);
2799
+ const totalStr = kb(total);
2800
+ out.push(
2801
+ ` ${adapterLabel(a.name).padEnd(NAME_W)}${captures.padStart(CAP_W)}${indexed.padStart(IDX_W)}${totalStr.padStart(TOT_W)}`,
2802
+ );
2803
+ }
2804
+ }
2805
+
2806
+ if (skipped.length > 0) {
2807
+ if (real.length > 0) out.push("");
2808
+ const names = skipped.map((a) => adapterLabel(a.name)).join(", ");
2809
+ out.push(` Skipped (${skipped.length}): ${names}`);
2810
+ out.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,");
2811
+ out.push(" or detection probes — no real chat activity.");
2812
+ }
2813
+
2814
+ return out;
2815
+ }
2816
+
2817
+ /**
2818
+ * Render a FullReport as a visual savings dashboard designed for screenshotting.
2819
+ *
2820
+ * Design principles:
2821
+ * - Before/After comparison bar is the HERO — one glance = "wow"
2822
+ * - "tokens saved" is the number people share
2823
+ * - Per-tool breakdown shows what each tool SAVED, sorted by impact
2824
+ * - Project memory: category bars showing persistent data across sessions
2825
+ * - No: Pct column, category tables, tips, jargon
2826
+ */
2827
+ export function formatReport(
2828
+ report: FullReport,
2829
+ version?: string,
2830
+ latestVersion?: string | null,
2831
+ opts?: {
2832
+ lifetime?: LifetimeStats;
2833
+ mcpUsage?: McpToolUsageRow[];
2834
+ conversation?: ConversationStats;
2835
+ /**
2836
+ * Phase 8 of D2 PRD — pass realBytes pre-aggregated from
2837
+ * `getRealBytesStats(...)` and the renderer will use those numbers
2838
+ * for the $ math instead of the conservative `events × 256` estimate.
2839
+ *
2840
+ * - `realBytes.lifetime` overrides `lifetimeTokensWithout`.
2841
+ * - `realBytes.conversation` overrides `conversationTokens`.
2842
+ * - Either may be omitted independently — missing values fall back
2843
+ * to the legacy estimate so this feature can never produce
2844
+ * a smaller number than before (Mert: stats only go up).
2845
+ * - When the new value is SMALLER than the legacy estimate (fresh
2846
+ * sessions before any sandbox events emit), we keep the larger
2847
+ * number to honour the same monotonic-growth invariant.
2848
+ */
2849
+ realBytes?: {
2850
+ lifetime?: RealBytesStats;
2851
+ conversation?: RealBytesStats;
2852
+ };
2853
+ /**
2854
+ * B3b — multi-adapter aggregation surfaced by
2855
+ * `getMultiAdapterLifetimeStats(...)` (analytics.ts:1248). When present,
2856
+ * the renderer adds a "Where it came from" sub-block under the receipt,
2857
+ * promotes the headline to "across N AI tools" when >= 2 real adapters
2858
+ * are detected, and renames the all-work block to "All your work
2859
+ * everywhere". Backward compat: omitting this opt preserves the legacy
2860
+ * single-adapter renderer output unchanged.
2861
+ */
2862
+ multiAdapter?: MultiAdapterLifetimeStats;
2863
+ /**
2864
+ * Point-in-time snapshot of the persistent content store. Optional —
2865
+ * callers that don't have store access can omit it and the renderer
2866
+ * skips the observability section gracefully.
2867
+ */
2868
+ indexState?: IndexState;
2869
+ /**
2870
+ * 5-section narrative renderer overrides. Defaults to ambient
2871
+ * `process.cwd()` + `Date.now()` + `detectLocaleAndTz()` for production
2872
+ * use; tests inject deterministic values so output is byte-stable.
2873
+ */
2874
+ cwd?: string;
2875
+ now?: number;
2876
+ locale?: string;
2877
+ tz?: string;
2878
+ },
2879
+ ): string {
2880
+ const lines: string[] = [];
2881
+ const duration = formatDuration(report.session.uptime_min);
2882
+ const lifetime = opts?.lifetime;
2883
+ const mcpUsage = opts?.mcpUsage;
2884
+ const conversation = opts?.conversation;
2885
+ const realBytes = opts?.realBytes;
2886
+ const multiAdapter = opts?.multiAdapter;
2887
+ // Real-adapter count drives the "across N AI tools" headline copy
2888
+ // (Slice 3.4) — we only call something a "tool you used" once it
2889
+ // passes the isReal filter inside getMultiAdapterLifetimeStats.
2890
+ const realAdapterCount = multiAdapter?.perAdapter.filter((a) => a.isReal).length ?? 0;
2891
+
2892
+ // ── B3b Slice 3.4: opening tagline — runs in EVERY render path so the
2893
+ // multi-adapter headline appears regardless of which formatReport branch
2894
+ // executes (active session / fresh / per-conversation). Falls back to
2895
+ // "in Claude Code" when only one adapter qualifies as real, matching the
2896
+ // Mert-approved demo wording. Suppressed entirely without multiAdapter
2897
+ // so legacy single-adapter renders stay byte-identical (Slice 3.5).
2898
+ if (multiAdapter && realAdapterCount > 0) {
2899
+ const totalConvs = multiAdapter.totalSessions || lifetime?.totalSessions || 0;
2900
+ const sinceMs = lifetime?.firstEventMs ?? 0;
2901
+ const days = sinceMs > 0
2902
+ ? Math.max(1, Math.round((Date.now() - sinceMs) / 86_400_000))
2903
+ : 0;
2904
+ const daySegment = days > 0 ? `Across ${days} day${days === 1 ? "" : "s"} ` : "";
2905
+ const convStr = totalConvs > 0
2906
+ ? `you ran ${fmtNum(totalConvs)} conversation${totalConvs === 1 ? "" : "s"} `
2907
+ : "you ran ";
2908
+ let where: string;
2909
+ if (realAdapterCount >= 2) {
2910
+ where = `across ${realAdapterCount} AI tools`;
2911
+ } else {
2912
+ // Single real adapter — use its marketing label (defaults to Claude Code
2913
+ // if for some reason the only real adapter has no entry in adapterLabels).
2914
+ const onlyReal = multiAdapter.perAdapter.find((a) => a.isReal);
2915
+ where = `in ${onlyReal ? adapterLabel(onlyReal.name) : "Claude Code"}`;
2916
+ }
2917
+ lines.push(`${daySegment}${convStr}${where}.`);
2918
+ lines.push("");
2919
+ }
2920
+
2921
+ // ── 5-section narrative ("kitap gibi") layout — Mert-approved
2922
+ // screenshot format produced when the MCP handler has wired
2923
+ // conversation + lifetime + multi-adapter through. Replaces the
2924
+ // legacy hero/contribution/auto-memory stack with the:
2925
+ // Opener
2926
+ // 1. Where you are now (datetime, /compact, timeline)
2927
+ // 2. What this chat captured (per-category bars)
2928
+ // 3. The receipt — getting wider
2929
+ // 4. For example: what would that cost?
2930
+ // 5. What context-mode learned about how you work
2931
+ // Footer
2932
+ // The opener block above (lines 1989-2005) is suppressed because
2933
+ // renderNarrative5Section emits its own.
2934
+ if (conversation && conversation.events > 0) {
2935
+ // Strip the previous-block opener — narrative renderer emits its own.
2936
+ if (lines.length > 0) lines.length = 0;
2937
+ const detected = detectLocaleAndTz();
2938
+ const cwd = opts?.cwd ?? process.cwd();
2939
+ const now = opts?.now ?? Date.now();
2940
+ const locale = opts?.locale ?? detected.locale;
2941
+ const tz = opts?.tz ?? detected.tz;
2942
+ lines.push(...renderNarrative5Section({
2943
+ conversation, lifetime, multiAdapter, realBytes,
2944
+ cwd, locale, tz, now, version, latestVersion,
2945
+ }));
2946
+ return lines.join("\n");
2947
+ }
2948
+
2949
+ // ── Compute real savings ──
2950
+ const totalKeptOut =
2951
+ report.savings.kept_out + (report.cache ? report.cache.bytes_saved : 0);
2952
+ const totalReturned = report.savings.total_bytes_returned;
2953
+ const totalCalls = report.savings.total_calls;
2954
+ const grandTotal = totalKeptOut + totalReturned;
2955
+ const savingsPct = grandTotal > 0 ? (totalKeptOut / grandTotal) * 100 : 0;
2956
+ const tokensSaved = Math.round(totalKeptOut / 4);
2957
+ const ratioMultiplier = totalReturned > 0
2958
+ ? Math.max(1, Math.round(grandTotal / Math.max(totalReturned, 1)))
2959
+ : 0;
2960
+
2961
+ // ── Fresh session: no savings yet ──
2962
+ if (totalKeptOut === 0) {
2963
+ lines.push(`context-mode ${duration} ${totalCalls} calls`);
2964
+ lines.push("");
2965
+
2966
+ if (totalCalls === 0) {
2967
+ lines.push("No tool calls yet. Use batch_execute or execute to start saving tokens.");
2968
+ } else {
2969
+ lines.push(`${kb(totalReturned)} entered context | 0 tokens saved`);
2970
+ }
2971
+
2972
+ // Project memory + auto-memory + bottom line
2973
+ lines.push(...renderProjectMemory(report.projectMemory, { lifetime, multiAdapter, sessionTokensSaved: 0 }));
2974
+ lines.push(...renderMultiAdapter(multiAdapter));
2975
+ lines.push(...renderAutoMemory(lifetime));
2976
+ lines.push(...renderBottomLine(0, lifetime));
2977
+
2978
+ // Footer
2979
+ lines.push("");
2980
+ const versionStr = version ? `v${version}` : "context-mode";
2981
+ lines.push(versionStr);
2982
+ if (version && latestVersion && latestVersion !== "unknown" && semverNewer(latestVersion, version)) {
2983
+ lines.push(`Update available: v${version} -> v${latestVersion} | ctx_upgrade`);
2984
+ }
2985
+ return lines.join("\n");
2986
+ }
2987
+
2988
+ // ── Active session: visual savings dashboard ──
2989
+
2990
+ // Line 1: Hero metric — the screenshottable number
2991
+ // Bug #6: include Opus pricing on the hero line for credibility.
2992
+ lines.push(
2993
+ `${fmtNum(tokensSaved)} tokens saved · ${savingsPct.toFixed(1)}% reduction · ${duration} · ~${tokensToUsd(tokensSaved)} saved (Opus)`,
2994
+ );
2995
+ lines.push("");
2996
+
2997
+ // Lines 2-3: Before/After comparison bars — the visual proof
2998
+ lines.push(`Without context-mode |${dataBar(grandTotal, grandTotal)}| ${kb(grandTotal)}`);
2999
+ lines.push(`With context-mode |${dataBar(totalReturned, grandTotal)}| ${kb(totalReturned)}`);
3000
+ lines.push("");
3001
+
3002
+ // Value statement — the line people share
3003
+ // Bug #7: replace meaningless "3.0x" ratio with "3× longer sessions".
3004
+ if (ratioMultiplier >= 2) {
3005
+ lines.push(`${kb(totalKeptOut)} kept out of your conversation — ${ratioMultiplier}× longer sessions before compact.`);
3006
+ } else {
3007
+ lines.push(`${kb(totalKeptOut)} kept out of your conversation. Never entered context.`);
3008
+ }
3009
+ lines.push("");
3010
+
3011
+ // Compact stats row
3012
+ const statParts = [`${totalCalls} calls`];
3013
+ if (report.cache && report.cache.hits > 0) {
3014
+ statParts.push(`${report.cache.hits} cache hits (+${kb(report.cache.bytes_saved)})`);
3015
+ }
3016
+ lines.push(statParts.join(" · "));
3017
+
3018
+ // ── Per-tool breakdown (only if 2+ tools, sorted by saved) ──
3019
+ const activatedTools = report.savings.by_tool.filter((t) => t.calls > 0);
3020
+ if (activatedTools.length >= 2) {
3021
+ lines.push("");
3022
+
3023
+ // Estimate per-tool saved using global savings ratio
3024
+ const toolRows = activatedTools.map((t) => {
3025
+ const returnedBytes = t.context_kb * 1024;
3026
+ const estimatedTotal = savingsPct < 100
3027
+ ? returnedBytes / (1 - savingsPct / 100)
3028
+ : returnedBytes;
3029
+ const estimatedSaved = Math.max(0, estimatedTotal - returnedBytes);
3030
+ return { ...t, returnedBytes, estimatedSaved };
3031
+ }).sort((a, b) => b.estimatedSaved - a.estimatedSaved);
3032
+
3033
+ // Compact table: tool name, calls, saved
3034
+ for (const t of toolRows) {
3035
+ const name = t.tool.length > 22 ? t.tool.slice(0, 19) + "..." : t.tool;
3036
+ lines.push(` ${name.padEnd(22)} ${String(t.calls).padStart(4)} calls ${kb(t.estimatedSaved).padStart(8)} saved`);
3037
+ }
3038
+ }
3039
+
3040
+ // ── Parallel I/O — value-forward framing for concurrent batch tools.
3041
+ // Suppressed when no tool ran with max_concurrency > 1 (don't claim
3042
+ // parallelism we didn't deliver). Internal mcp__*__ namespace stripped
3043
+ // for user-facing readability.
3044
+ if (mcpUsage && mcpUsage.length > 0) {
3045
+ const concurrent = mcpUsage.filter(
3046
+ (u) => u.median_concurrency != null && (u.max_concurrency ?? 1) > 1,
3047
+ );
3048
+ if (concurrent.length > 0) {
3049
+ lines.push("");
3050
+ lines.push(
3051
+ "Parallel I/O ✓ one call did the work of many — faster runs, lower bill, same answer.",
3052
+ );
3053
+ for (const u of concurrent) {
3054
+ const name = u.tool_name.replace(/^mcp__.*?__/, "");
3055
+ lines.push(
3056
+ ` ${name.padEnd(22)} ${u.calls} batches · ${u.median_concurrency} typical, ${u.max_concurrency} peak`,
3057
+ );
3058
+ }
3059
+ }
3060
+ }
3061
+
3062
+ // ── Project memory — persistent across sessions (Bug #3 + #5) ──
3063
+ lines.push(...renderProjectMemory(report.projectMemory, { lifetime, multiAdapter, sessionTokensSaved: tokensSaved }));
3064
+
3065
+ // ── B3b Slice 3.2/3.3 — "Where it came from" per-adapter sub-block.
3066
+ // Sits under the lifetime memory block so the receipt-to-source flow is
3067
+ // visually contiguous (lifetime totals → which tools produced them).
3068
+ lines.push(...renderMultiAdapter(multiAdapter));
3069
+
3070
+ // ── Auto-memory — Claude Code's preference learnings (Bug #4) ──
3071
+ lines.push(...renderAutoMemory(lifetime));
3072
+
3073
+ // ── Bottom line — business value framing (Bug #8) ──
3074
+ lines.push(...renderBottomLine(tokensSaved, lifetime));
3075
+
3076
+ // ── Footer ──
3077
+ lines.push("");
3078
+ const versionStr = version ? `v${version}` : "context-mode";
3079
+ lines.push(versionStr);
3080
+ if (version && latestVersion && latestVersion !== "unknown" && latestVersion !== version) {
3081
+ lines.push(`Update available: v${version} -> v${latestVersion} | ctx_upgrade`);
3082
+ }
3083
+
3084
+ return lines.join("\n");
3085
+ }