context-mode 1.0.168 → 2.0.0-next.5

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