pi-lens 4.2.1 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (671) hide show
  1. package/CHANGELOG.md +1562 -0
  2. package/README.md +157 -24
  3. package/config/dependency-cruiser-eager-allowlist.json +6 -2
  4. package/dist/chunk-22AVIGXS.js +560 -0
  5. package/dist/chunk-27BBHSZC.js +106 -0
  6. package/dist/chunk-2BEMIWEW.js +51 -0
  7. package/dist/chunk-2EECBNC5.js +89 -0
  8. package/dist/chunk-34U7PLGE.js +23 -0
  9. package/dist/chunk-3I5QFT3N.js +181 -0
  10. package/dist/chunk-3MED75HT.js +37 -0
  11. package/dist/chunk-47D2BO4S.js +87 -0
  12. package/dist/chunk-4RERDEXR.js +348 -0
  13. package/dist/chunk-4W2PLC4J.js +27 -0
  14. package/dist/chunk-52H5B5TC.js +202 -0
  15. package/dist/chunk-54B42YRX.js +27 -0
  16. package/dist/chunk-5RXBNSW2.js +266 -0
  17. package/dist/chunk-5THXD6X5.js +201 -0
  18. package/dist/chunk-5W3R6LFT.js +24 -0
  19. package/dist/chunk-5ZEJHV35.js +341 -0
  20. package/dist/chunk-6P62QVEA.js +118 -0
  21. package/dist/chunk-6QIUX4EP.js +459 -0
  22. package/dist/chunk-6VCD4VKZ.js +78 -0
  23. package/dist/chunk-7F72PXY2.js +326 -0
  24. package/dist/chunk-7FBF7NPR.js +998 -0
  25. package/dist/chunk-7U2IDNXN.js +37 -0
  26. package/dist/chunk-ABBOA7UD.js +157 -0
  27. package/dist/chunk-AHDW3GPE.js +50 -0
  28. package/dist/chunk-AJ3QXTRQ.js +756 -0
  29. package/dist/chunk-AJVLWNFN.js +1610 -0
  30. package/dist/chunk-AJXODZY6.js +112 -0
  31. package/dist/chunk-ARFCXG7S.js +84 -0
  32. package/dist/chunk-AS44CFQ4.js +708 -0
  33. package/dist/chunk-AWE5TMPO.js +38 -0
  34. package/dist/chunk-B3I2UUT4.js +4692 -0
  35. package/dist/chunk-BRJKOBZP.js +331 -0
  36. package/dist/chunk-BW5KFIQC.js +59 -0
  37. package/dist/chunk-C2AUYXQH.js +149 -0
  38. package/dist/chunk-CGGAIP7J.js +29 -0
  39. package/dist/chunk-D6QS3U6M.js +30 -0
  40. package/dist/chunk-DFVMIKMQ.js +349 -0
  41. package/dist/chunk-DIULIWKU.js +169 -0
  42. package/dist/chunk-DQ2NZ7C4.js +2317 -0
  43. package/dist/chunk-E2WFBRHM.js +213 -0
  44. package/dist/chunk-E4MAEDPM.js +50 -0
  45. package/dist/chunk-EOKRQ3SA.js +30 -0
  46. package/dist/chunk-F3AU2TMM.js +2626 -0
  47. package/dist/chunk-F3P7VQ7H.js +170 -0
  48. package/dist/chunk-FC4RP4I2.js +12 -0
  49. package/dist/chunk-FJNKANOS.js +32 -0
  50. package/dist/chunk-GUOGVTCQ.js +146 -0
  51. package/dist/chunk-GVXA6CCE.js +18 -0
  52. package/dist/chunk-HHYAELLJ.js +2334 -0
  53. package/dist/chunk-HMFXILPV.js +83 -0
  54. package/dist/chunk-HVUZXSWK.js +421 -0
  55. package/dist/chunk-HWBZIGMJ.js +62 -0
  56. package/dist/chunk-I3R7GKDR.js +17 -0
  57. package/dist/chunk-I7SPGOWI.js +55 -0
  58. package/dist/chunk-IIXOAGHR.js +38 -0
  59. package/dist/chunk-IVP5KAB7.js +2250 -0
  60. package/dist/chunk-IXEBJSUE.js +22 -0
  61. package/dist/chunk-JOLITGCC.js +27 -0
  62. package/dist/chunk-K6VYLB2U.js +145 -0
  63. package/dist/chunk-LJDODBBZ.js +78 -0
  64. package/dist/chunk-LNAKEO63.js +78 -0
  65. package/dist/chunk-LSMJ6KBE.js +4139 -0
  66. package/dist/chunk-LW6XKDZQ.js +5565 -0
  67. package/dist/chunk-N3YQJI6O.js +899 -0
  68. package/dist/chunk-NABLC7W3.js +148 -0
  69. package/dist/chunk-NKOUFPQF.js +659 -0
  70. package/dist/chunk-NL5GLMFI.js +211 -0
  71. package/dist/chunk-NMABWBZN.js +327 -0
  72. package/dist/chunk-NTHH2J74.js +27 -0
  73. package/dist/chunk-NTUJEGDZ.js +59 -0
  74. package/dist/chunk-NXL4FFQQ.js +47 -0
  75. package/dist/chunk-NXPS2L6U.js +466 -0
  76. package/dist/chunk-O5WILGMI.js +42 -0
  77. package/dist/chunk-O6TQT6RI.js +48 -0
  78. package/dist/chunk-OAXNDZJ7.js +323 -0
  79. package/dist/chunk-ODEEOXPH.js +44 -0
  80. package/dist/chunk-OQGFCZJ4.js +4533 -0
  81. package/dist/chunk-ORTMY4Q4.js +282 -0
  82. package/dist/chunk-OS32RNR2.js +442 -0
  83. package/dist/chunk-PAK6IDME.js +189 -0
  84. package/dist/chunk-PWFHBTSF.js +406 -0
  85. package/dist/chunk-Q5U6FMDI.js +2352 -0
  86. package/dist/chunk-QOZXJ4NA.js +3364 -0
  87. package/dist/chunk-QYF5S6P6.js +45 -0
  88. package/dist/chunk-RIISMHKN.js +36 -0
  89. package/dist/chunk-RPD4ZSB7.js +25 -0
  90. package/dist/chunk-RPD5K5NC.js +79 -0
  91. package/dist/chunk-RUOG5D2C.js +262 -0
  92. package/dist/chunk-T4ERT73Y.js +599 -0
  93. package/dist/chunk-T6D4Q4AQ.js +54 -0
  94. package/dist/chunk-TGPXLY2J.js +391 -0
  95. package/dist/chunk-TLGFBM3F.js +12116 -0
  96. package/dist/chunk-TO6WL3GM.js +88 -0
  97. package/dist/chunk-TT22N74J.js +517 -0
  98. package/dist/chunk-TVN5N6GY.js +21216 -0
  99. package/dist/chunk-U3VGR4VU.js +308 -0
  100. package/dist/chunk-UK3CMEAL.js +1250 -0
  101. package/dist/chunk-UOPVJQ4N.js +103 -0
  102. package/dist/chunk-UXVNL3D7.js +23 -0
  103. package/dist/chunk-UY752QSN.js +45 -0
  104. package/dist/chunk-V5PXFSZK.js +188 -0
  105. package/dist/chunk-V7R425XG.js +398 -0
  106. package/dist/chunk-VCSRSYLF.js +81 -0
  107. package/dist/chunk-VD4JQCQC.js +162 -0
  108. package/dist/chunk-VDBPVIKD.js +62 -0
  109. package/dist/chunk-VHQLPIRJ.js +114 -0
  110. package/dist/chunk-VN2AXLEX.js +5414 -0
  111. package/dist/chunk-VNMT7C64.js +478 -0
  112. package/dist/chunk-WONERJTP.js +309 -0
  113. package/dist/chunk-XECLWQZN.js +85 -0
  114. package/dist/chunk-XIMYZ3JA.js +27 -0
  115. package/dist/chunk-XK4CIILI.js +144 -0
  116. package/dist/chunk-Y4T27COV.js +562 -0
  117. package/dist/chunk-YGVYKNSN.js +1860 -0
  118. package/dist/chunk-YLF3PPT5.js +308 -0
  119. package/dist/chunk-YSNFMJKN.js +14 -0
  120. package/dist/chunk-Z3CCVDUB.js +76 -0
  121. package/dist/chunk-Z54ZSOBZ.js +61 -0
  122. package/dist/chunk-ZAWW3AF6.js +97 -0
  123. package/dist/chunk-ZMOL6RQC.js +167 -0
  124. package/dist/index.js +19039 -8956
  125. package/dist/mcp/analyze-cli.js +186 -228
  126. package/dist/mcp/cli.js +137 -98
  127. package/dist/mcp/server.js +22592 -1564
  128. package/dist/mcp/worker.js +97 -38
  129. package/dist/probes/installer.js +135 -0
  130. package/dist/workers/project-snapshot-persist-worker.js +22 -0
  131. package/dist/workers/review-graph-persist-worker.js +15 -0
  132. package/docs/adr/0001-stale-advisory-live-arm.md +29 -0
  133. package/docs/adr/0002-workspace-hash-rendezvous.md +30 -0
  134. package/docs/adr/0003-git-guard-latch-writer.md +203 -0
  135. package/docs/adr/0004-disposition-policy-seam.md +38 -0
  136. package/docs/adr/0005-tool-availability-enforcement-seam.md +29 -0
  137. package/docs/adr/0006-derived-state-benchmark-first.md +31 -0
  138. package/docs/adr/0007-end-to-end-witness-per-seam-slice.md +38 -0
  139. package/docs/adr/0008-turn-end-lane-interface.md +165 -0
  140. package/docs/adr/0009-reported-path-attribution.md +114 -0
  141. package/docs/adr/README.md +26 -0
  142. package/docs/agent-guide.md +13 -4
  143. package/docs/agent-tools.md +60 -1
  144. package/docs/ast-grep_rules_catalog.md +6 -4
  145. package/docs/configuration.md +75 -2
  146. package/docs/engineering-principles.md +202 -0
  147. package/docs/environment-variables.md +113 -6
  148. package/docs/features.md +10 -6
  149. package/docs/globalconfig.md +7 -1
  150. package/docs/io-bridge-v2-migration.md +94 -0
  151. package/docs/language-coverage.md +17 -0
  152. package/docs/lsp-capability-matrix.md +131 -32
  153. package/docs/lsp-idle-eviction.md +124 -0
  154. package/docs/mcp.md +21 -5
  155. package/docs/merge-queue-rollout.md +77 -0
  156. package/docs/pi-lens-fixer.md +161 -39
  157. package/docs/pi-lens-investigator.md +77 -20
  158. package/docs/pi-lens-merge-policy.md +694 -0
  159. package/docs/pi-lens-monitor.md +73 -7
  160. package/docs/pi-lens-retro.md +6 -4
  161. package/docs/pi-lens-reviewer.md +190 -34
  162. package/docs/pi-lens-subagent.md +247 -37
  163. package/docs/pi-lens-warden.md +18 -7
  164. package/docs/public-api-stability.md +56 -0
  165. package/docs/release-qa-baseline.md +86 -17
  166. package/docs/rfcs/3654-unified-io-bridge-v2.md +316 -0
  167. package/docs/servercapabilities.md +66 -52
  168. package/docs/settings.md +13 -3
  169. package/docs/subagent-compat.md +1 -1
  170. package/docs/usage.md +5 -1
  171. package/grammars/tree-sitter-bash.wasm +0 -0
  172. package/grammars/tree-sitter-bash.wasm.json +3 -3
  173. package/package.json +23 -9
  174. package/rules/ast-grep-rules/rule-tests/advisory-registry-subset-test.yml +41 -0
  175. package/rules/ast-grep-rules/rule-tests/no-assert-tuple-test.yml +13 -0
  176. package/rules/ast-grep-rules/rule-tests/no-boolean-in-except-test.yml +26 -0
  177. package/rules/ast-grep-rules/rule-tests/no-http-headers-bracket-access-test.yml +10 -0
  178. package/rules/ast-grep-rules/rule-tests/unchecked-numeric-parse-python-test.yml +18 -0
  179. package/rules/ast-grep-rules/rule-tests/unchecked-throwing-call-python-test.yml +4 -3
  180. package/rules/ast-grep-rules/rules/advisory-registry-subset.yml +50 -0
  181. package/rules/ast-grep-rules/rules/go-no-fmt-println.yml +2 -2
  182. package/rules/ast-grep-rules/rules/no-assert-tuple.yml +23 -13
  183. package/rules/ast-grep-rules/rules/no-boolean-in-except.yml +7 -3
  184. package/rules/ast-grep-rules/rules/no-console-except-error-js.yml +2 -2
  185. package/rules/ast-grep-rules/rules/no-console-except-error.yml +2 -2
  186. package/rules/ast-grep-rules/rules/no-http-headers-bracket-access.yml +12 -7
  187. package/rules/ast-grep-rules/rules/unchecked-numeric-parse-python.yml +44 -0
  188. package/rules/ast-grep-rules/rules/unchecked-throwing-call-python.yml +5 -3
  189. package/rules/tree-sitter-queries/typescript/console-statement.yml +2 -2
  190. package/scripts/analyze-pi-lens-logs.mjs +1275 -62
  191. package/scripts/download-grammars.js +5 -0
  192. package/scripts/grammars.lock.json +6 -1
  193. package/scripts/install-selftest.mjs +38 -35
  194. package/scripts/lib/host-provided-deps.mjs +13 -4
  195. package/scripts/lib/web-tree-sitter-dir.mjs +141 -0
  196. package/dist/clients/actionable-warnings-logger.js +0 -35
  197. package/dist/clients/actionable-warnings.js +0 -1594
  198. package/dist/clients/advisory-provenance.js +0 -457
  199. package/dist/clients/agent-behavior-client.js +0 -147
  200. package/dist/clients/agent-nudge.js +0 -325
  201. package/dist/clients/analysed-root.js +0 -1
  202. package/dist/clients/ast-grep-client.js +0 -731
  203. package/dist/clients/ast-grep-rule-manager.js +0 -146
  204. package/dist/clients/ast-grep-tool-logger.js +0 -118
  205. package/dist/clients/ast-grep-types.js +0 -10
  206. package/dist/clients/ast-grep-yaml-synth.js +0 -154
  207. package/dist/clients/atomic-write-staging.js +0 -75
  208. package/dist/clients/atomic-write.js +0 -189
  209. package/dist/clients/availability-probe-flight.js +0 -12
  210. package/dist/clients/bash-file-access.js +0 -1056
  211. package/dist/clients/biome-client.js +0 -357
  212. package/dist/clients/blocker-freshness.js +0 -837
  213. package/dist/clients/blocker-past-eof.js +0 -129
  214. package/dist/clients/bootstrap.js +0 -569
  215. package/dist/clients/bounded-cache.js +0 -190
  216. package/dist/clients/bounded-pid-file-lock.js +0 -202
  217. package/dist/clients/bounded-telemetry.js +0 -295
  218. package/dist/clients/build-identity.js +0 -95
  219. package/dist/clients/bundled-resource-health.js +0 -113
  220. package/dist/clients/bus-events-logger.js +0 -105
  221. package/dist/clients/bus-publish.js +0 -171
  222. package/dist/clients/cache/rule-cache.js +0 -190
  223. package/dist/clients/cache-manager.js +0 -465
  224. package/dist/clients/cache-observability.js +0 -1313
  225. package/dist/clients/call-graph.js +0 -852
  226. package/dist/clients/cargo-manifest.js +0 -422
  227. package/dist/clients/cascade-budget.js +0 -196
  228. package/dist/clients/cascade-format.js +0 -315
  229. package/dist/clients/cascade-logger.js +0 -31
  230. package/dist/clients/cascade-types.js +0 -9
  231. package/dist/clients/child-unref.js +0 -115
  232. package/dist/clients/code-quality-warnings.js +0 -286
  233. package/dist/clients/codebase-model.js +0 -173
  234. package/dist/clients/collateral-test-role.js +0 -40
  235. package/dist/clients/complexity-client.js +0 -462
  236. package/dist/clients/config-core/deny.js +0 -221
  237. package/dist/clients/config-core/index.js +0 -50
  238. package/dist/clients/config-core/merge.js +0 -357
  239. package/dist/clients/config-core/normalize.js +0 -340
  240. package/dist/clients/config-core/process-spec.js +0 -248
  241. package/dist/clients/config-core/provenance.js +0 -164
  242. package/dist/clients/config-core/records.js +0 -218
  243. package/dist/clients/config-core/resolve.js +0 -125
  244. package/dist/clients/config-core/safe-object.js +0 -78
  245. package/dist/clients/config-core/schema.js +0 -165
  246. package/dist/clients/config-diagnostic-codes.js +0 -283
  247. package/dist/clients/config-locations.js +0 -160
  248. package/dist/clients/config-resolve.js +0 -792
  249. package/dist/clients/config-schema.js +0 -251
  250. package/dist/clients/config-warn.js +0 -407
  251. package/dist/clients/console-guard-install.js +0 -26
  252. package/dist/clients/cooperative-budget.js +0 -42
  253. package/dist/clients/dead-code-client.js +0 -510
  254. package/dist/clients/dead-code-logger.js +0 -30
  255. package/dist/clients/deadline-utils.js +0 -280
  256. package/dist/clients/debug-handles.js +0 -211
  257. package/dist/clients/debug-heap.js +0 -174
  258. package/dist/clients/deferred-lsp-work.js +0 -106
  259. package/dist/clients/degradation-ledger.js +0 -396
  260. package/dist/clients/demoted-finding-render.js +0 -169
  261. package/dist/clients/dependency-checker.js +0 -862
  262. package/dist/clients/deps/ast-grep-napi.js +0 -22
  263. package/dist/clients/deps/js-yaml.js +0 -9
  264. package/dist/clients/deps/minimatch.js +0 -4
  265. package/dist/clients/deps/pi-tui.js +0 -14
  266. package/dist/clients/deps/typebox.js +0 -14
  267. package/dist/clients/deps/vscode-jsonrpc.js +0 -1
  268. package/dist/clients/deps/web-tree-sitter.js +0 -24
  269. package/dist/clients/diagnostic-dispositions.js +0 -594
  270. package/dist/clients/diagnostic-line-freshness.js +0 -305
  271. package/dist/clients/diagnostic-logger.js +0 -73
  272. package/dist/clients/diagnostic-tracker.js +0 -105
  273. package/dist/clients/diagnostics-publish.js +0 -230
  274. package/dist/clients/dispatch/ast-grep-catalog.js +0 -65
  275. package/dist/clients/dispatch/auxiliary-lsp.js +0 -343
  276. package/dist/clients/dispatch/collect-later-tier.js +0 -35
  277. package/dist/clients/dispatch/diagnostic-taxonomy.js +0 -66
  278. package/dist/clients/dispatch/dispatcher.js +0 -1269
  279. package/dist/clients/dispatch/fact-provider-types.js +0 -1
  280. package/dist/clients/dispatch/fact-rule-runner.js +0 -17
  281. package/dist/clients/dispatch/fact-runner.js +0 -30
  282. package/dist/clients/dispatch/fact-scheduler.js +0 -68
  283. package/dist/clients/dispatch/fact-store.js +0 -377
  284. package/dist/clients/dispatch/facts/comment-facts.js +0 -22
  285. package/dist/clients/dispatch/facts/file-content.js +0 -19
  286. package/dist/clients/dispatch/facts/function-facts.js +0 -348
  287. package/dist/clients/dispatch/facts/import-facts.js +0 -204
  288. package/dist/clients/dispatch/facts/tree-sitter-facts.js +0 -34
  289. package/dist/clients/dispatch/facts/try-catch-facts.js +0 -119
  290. package/dist/clients/dispatch/finding-policy.js +0 -222
  291. package/dist/clients/dispatch/indent-detect.js +0 -411
  292. package/dist/clients/dispatch/inline-suppressions.js +0 -70
  293. package/dist/clients/dispatch/integration.js +0 -2377
  294. package/dist/clients/dispatch/lazy.js +0 -11
  295. package/dist/clients/dispatch/pending-runner-findings.js +0 -87
  296. package/dist/clients/dispatch/plan.js +0 -278
  297. package/dist/clients/dispatch/priorities.js +0 -20
  298. package/dist/clients/dispatch/rule-id-normalize.js +0 -50
  299. package/dist/clients/dispatch/rule-ignores.js +0 -62
  300. package/dist/clients/dispatch/rule-policy.js +0 -135
  301. package/dist/clients/dispatch/rules/async-noise.js +0 -40
  302. package/dist/clients/dispatch/rules/async-unnecessary-wrapper.js +0 -27
  303. package/dist/clients/dispatch/rules/cors-wildcard.js +0 -54
  304. package/dist/clients/dispatch/rules/error-obscuring.js +0 -32
  305. package/dist/clients/dispatch/rules/error-swallowing.js +0 -31
  306. package/dist/clients/dispatch/rules/framework-call-noise.js +0 -67
  307. package/dist/clients/dispatch/rules/high-complexity.js +0 -72
  308. package/dist/clients/dispatch/rules/high-fan-out.js +0 -74
  309. package/dist/clients/dispatch/rules/high-import-coupling.js +0 -37
  310. package/dist/clients/dispatch/rules/missing-error-propagation.js +0 -62
  311. package/dist/clients/dispatch/rules/no-commented-credentials.js +0 -52
  312. package/dist/clients/dispatch/rules/pass-through-wrappers.js +0 -42
  313. package/dist/clients/dispatch/rules/placeholder-comments.js +0 -40
  314. package/dist/clients/dispatch/rules/unsafe-boundary.js +0 -126
  315. package/dist/clients/dispatch/runner-context.js +0 -52
  316. package/dist/clients/dispatch/runners/actionlint.js +0 -113
  317. package/dist/clients/dispatch/runners/ast-grep-napi.js +0 -1196
  318. package/dist/clients/dispatch/runners/biome-check.js +0 -283
  319. package/dist/clients/dispatch/runners/cpp-check.js +0 -236
  320. package/dist/clients/dispatch/runners/credo.js +0 -80
  321. package/dist/clients/dispatch/runners/cue-vet.js +0 -398
  322. package/dist/clients/dispatch/runners/dart-analyze.js +0 -202
  323. package/dist/clients/dispatch/runners/detekt.js +0 -169
  324. package/dist/clients/dispatch/runners/dotnet-build.js +0 -159
  325. package/dist/clients/dispatch/runners/elixir-check.js +0 -210
  326. package/dist/clients/dispatch/runners/eslint.js +0 -154
  327. package/dist/clients/dispatch/runners/fact-rules.js +0 -29
  328. package/dist/clients/dispatch/runners/fish-indent.js +0 -69
  329. package/dist/clients/dispatch/runners/gleam-check.js +0 -87
  330. package/dist/clients/dispatch/runners/go-vet.js +0 -90
  331. package/dist/clients/dispatch/runners/golangci-lint.js +0 -120
  332. package/dist/clients/dispatch/runners/hadolint.js +0 -79
  333. package/dist/clients/dispatch/runners/helm-lint.js +0 -171
  334. package/dist/clients/dispatch/runners/helm-render.js +0 -940
  335. package/dist/clients/dispatch/runners/htmlhint.js +0 -108
  336. package/dist/clients/dispatch/runners/index.js +0 -108
  337. package/dist/clients/dispatch/runners/javac.js +0 -89
  338. package/dist/clients/dispatch/runners/ktlint.js +0 -136
  339. package/dist/clients/dispatch/runners/lsp.js +0 -378
  340. package/dist/clients/dispatch/runners/markdownlint.js +0 -160
  341. package/dist/clients/dispatch/runners/mypy.js +0 -101
  342. package/dist/clients/dispatch/runners/oxlint.js +0 -398
  343. package/dist/clients/dispatch/runners/php-lint.js +0 -62
  344. package/dist/clients/dispatch/runners/phpstan.js +0 -120
  345. package/dist/clients/dispatch/runners/prisma-validate.js +0 -62
  346. package/dist/clients/dispatch/runners/psscriptanalyzer.js +0 -445
  347. package/dist/clients/dispatch/runners/pyright.js +0 -169
  348. package/dist/clients/dispatch/runners/rubocop.js +0 -90
  349. package/dist/clients/dispatch/runners/ruff.js +0 -89
  350. package/dist/clients/dispatch/runners/rust-clippy.js +0 -251
  351. package/dist/clients/dispatch/runners/shellcheck.js +0 -169
  352. package/dist/clients/dispatch/runners/shfmt.js +0 -102
  353. package/dist/clients/dispatch/runners/spellcheck.js +0 -121
  354. package/dist/clients/dispatch/runners/spotbugs.js +0 -259
  355. package/dist/clients/dispatch/runners/sqlfluff.js +0 -174
  356. package/dist/clients/dispatch/runners/stylelint.js +0 -158
  357. package/dist/clients/dispatch/runners/swiftlint.js +0 -154
  358. package/dist/clients/dispatch/runners/taplo.js +0 -168
  359. package/dist/clients/dispatch/runners/terragrunt.js +0 -168
  360. package/dist/clients/dispatch/runners/tflint.js +0 -110
  361. package/dist/clients/dispatch/runners/tree-sitter.js +0 -620
  362. package/dist/clients/dispatch/runners/trivy-config.js +0 -247
  363. package/dist/clients/dispatch/runners/utils/availability-policy.js +0 -496
  364. package/dist/clients/dispatch/runners/utils/candidate-probe.js +0 -90
  365. package/dist/clients/dispatch/runners/utils/diagnostic-parsers.js +0 -85
  366. package/dist/clients/dispatch/runners/utils/lazy-installer.js +0 -274
  367. package/dist/clients/dispatch/runners/utils/runner-helpers.js +0 -1701
  368. package/dist/clients/dispatch/runners/utils/spawn-outcome.js +0 -101
  369. package/dist/clients/dispatch/runners/utils/tool-failure.js +0 -235
  370. package/dist/clients/dispatch/runners/utils/toolchain-availability.js +0 -169
  371. package/dist/clients/dispatch/runners/utils.js +0 -15
  372. package/dist/clients/dispatch/runners/vale.js +0 -116
  373. package/dist/clients/dispatch/runners/yaml-rule-parser.js +0 -242
  374. package/dist/clients/dispatch/runners/yamllint.js +0 -85
  375. package/dist/clients/dispatch/runners/zig-check.js +0 -91
  376. package/dist/clients/dispatch/suppress-writer.js +0 -69
  377. package/dist/clients/dispatch/tool-profile.js +0 -30
  378. package/dist/clients/dispatch/types.js +0 -21
  379. package/dist/clients/dispatch/utils/format-utils.js +0 -45
  380. package/dist/clients/dispatch/utils/lsp-diagnostics.js +0 -35
  381. package/dist/clients/disposition-logger.js +0 -32
  382. package/dist/clients/disposition-publish.js +0 -124
  383. package/dist/clients/durable-store.js +0 -97
  384. package/dist/clients/effective-config.js +0 -413
  385. package/dist/clients/env-utils.js +0 -83
  386. package/dist/clients/error-class.js +0 -23
  387. package/dist/clients/eval-timestamp.js +0 -17
  388. package/dist/clients/event-loop-hold.js +0 -274
  389. package/dist/clients/event-loop-monitor.js +0 -250
  390. package/dist/clients/extension-log.js +0 -504
  391. package/dist/clients/extension-mode.js +0 -73
  392. package/dist/clients/feature-hints.js +0 -103
  393. package/dist/clients/file-kinds.js +0 -412
  394. package/dist/clients/file-role.js +0 -134
  395. package/dist/clients/file-time.js +0 -160
  396. package/dist/clients/file-utils.js +0 -1032
  397. package/dist/clients/finding-delivery-gate.js +0 -463
  398. package/dist/clients/finding-identity.js +0 -88
  399. package/dist/clients/fix-worklog.js +0 -103
  400. package/dist/clients/format-events-publish.js +0 -343
  401. package/dist/clients/format-service.js +0 -222
  402. package/dist/clients/formatters-lazy.js +0 -9
  403. package/dist/clients/formatters.js +0 -1994
  404. package/dist/clients/freshness-cadence.js +0 -17
  405. package/dist/clients/freshness.js +0 -38
  406. package/dist/clients/generated-artifacts.js +0 -394
  407. package/dist/clients/generation-guard.js +0 -215
  408. package/dist/clients/git-guard.js +0 -923
  409. package/dist/clients/git-tracked-ignore.js +0 -243
  410. package/dist/clients/gitleaks-client.js +0 -509
  411. package/dist/clients/go-client.js +0 -104
  412. package/dist/clients/govulncheck-client.js +0 -605
  413. package/dist/clients/gradle-ktfmt-style.js +0 -252
  414. package/dist/clients/grammar-source.js +0 -465
  415. package/dist/clients/gzip-stage-write.js +0 -135
  416. package/dist/clients/hashline-anchor.js +0 -424
  417. package/dist/clients/hook-budgets.js +0 -76
  418. package/dist/clients/host-edit-normalize.js +0 -140
  419. package/dist/clients/host-ports.js +0 -39
  420. package/dist/clients/indent-retarget.js +0 -154
  421. package/dist/clients/install-diagnostics.js +0 -143
  422. package/dist/clients/installer/index.js +0 -5167
  423. package/dist/clients/installer/managed-tool-refresh-session.js +0 -58
  424. package/dist/clients/installer/managed-tool-refresh.js +0 -783
  425. package/dist/clients/instance-reaper-state.js +0 -7
  426. package/dist/clients/instance-reaper.js +0 -1137
  427. package/dist/clients/instance-registry-lock.js +0 -145
  428. package/dist/clients/instance-registry.js +0 -773
  429. package/dist/clients/jscpd-client.js +0 -370
  430. package/dist/clients/json-cache-read.js +0 -65
  431. package/dist/clients/knip-client.js +0 -788
  432. package/dist/clients/language-policy.js +0 -252
  433. package/dist/clients/language-profile.js +0 -361
  434. package/dist/clients/language-registry.js +0 -603
  435. package/dist/clients/latency-logger.js +0 -719
  436. package/dist/clients/lazy-import.js +0 -21
  437. package/dist/clients/ledger-bounds.js +0 -54
  438. package/dist/clients/lens-config.js +0 -346
  439. package/dist/clients/lens-engine.js +0 -358
  440. package/dist/clients/lens-events.js +0 -125
  441. package/dist/clients/lens-flag-registry.js +0 -467
  442. package/dist/clients/lens-map.js +0 -1156
  443. package/dist/clients/live-bus-emitter.js +0 -74
  444. package/dist/clients/log-cleanup.js +0 -222
  445. package/dist/clients/lsp/aggregation.js +0 -178
  446. package/dist/clients/lsp/cascade-tier.js +0 -421
  447. package/dist/clients/lsp/client.js +0 -4465
  448. package/dist/clients/lsp/config.js +0 -689
  449. package/dist/clients/lsp/diagnostic-binding.js +0 -225
  450. package/dist/clients/lsp/document-drift.js +0 -467
  451. package/dist/clients/lsp/edits.js +0 -1219
  452. package/dist/clients/lsp/index.js +0 -8305
  453. package/dist/clients/lsp/inferred-project.js +0 -216
  454. package/dist/clients/lsp/jvm-runtime.js +0 -298
  455. package/dist/clients/lsp/language.js +0 -63
  456. package/dist/clients/lsp/launch.js +0 -725
  457. package/dist/clients/lsp/lombok.js +0 -158
  458. package/dist/clients/lsp/path-utils.js +0 -5
  459. package/dist/clients/lsp/pending-aux-coverage.js +0 -251
  460. package/dist/clients/lsp/position-encoding.js +0 -61
  461. package/dist/clients/lsp/ruby-drive-dirs.js +0 -83
  462. package/dist/clients/lsp/server.js +0 -3209
  463. package/dist/clients/lsp/session-roots.js +0 -192
  464. package/dist/clients/lsp/spawn-history.js +0 -17
  465. package/dist/clients/lsp/sync-kind.js +0 -42
  466. package/dist/clients/lsp/tsserver-sync.js +0 -332
  467. package/dist/clients/lsp/wait-policy/capability-snapshot.js +0 -1
  468. package/dist/clients/lsp/wait-policy/classification.js +0 -85
  469. package/dist/clients/lsp/wait-policy/index.js +0 -10
  470. package/dist/clients/lsp/wait-policy/strategies.js +0 -303
  471. package/dist/clients/lsp/watch-queue.js +0 -61
  472. package/dist/clients/lsp/workspace-diagnostics-cache.js +0 -639
  473. package/dist/clients/lsp/workspace-diagnostics-session.js +0 -30
  474. package/dist/clients/lsp/workspace-sweep-hold.js +0 -184
  475. package/dist/clients/lsp-budget.js +0 -186
  476. package/dist/clients/lsp-document-symbols.js +0 -110
  477. package/dist/clients/lsp-lazy.js +0 -9
  478. package/dist/clients/lsp-mutation.js +0 -396
  479. package/dist/clients/lsp-status.js +0 -59
  480. package/dist/clients/map-with-concurrency.js +0 -40
  481. package/dist/clients/mcp/analyze.js +0 -420
  482. package/dist/clients/mcp/host-shim.js +0 -31
  483. package/dist/clients/mcp/ipc.js +0 -335
  484. package/dist/clients/mcp/review.js +0 -151
  485. package/dist/clients/mcp/session.js +0 -412
  486. package/dist/clients/memory-sampler.js +0 -208
  487. package/dist/clients/message-end-attribution.js +0 -30
  488. package/dist/clients/metrics-client.js +0 -107
  489. package/dist/clients/metrics-history.js +0 -327
  490. package/dist/clients/middle-man-analysis.js +0 -263
  491. package/dist/clients/model-provider.js +0 -53
  492. package/dist/clients/module-report-lsp.js +0 -189
  493. package/dist/clients/module-report.js +0 -2150
  494. package/dist/clients/mutating-tool.js +0 -651
  495. package/dist/clients/mutation-attribution.js +0 -368
  496. package/dist/clients/mutation-bridge.js +0 -240
  497. package/dist/clients/ndjson-logger.js +0 -734
  498. package/dist/clients/observed-mutation-sources.js +0 -101
  499. package/dist/clients/observed-mutation.js +0 -1253
  500. package/dist/clients/oldtext-autopatch.js +0 -128
  501. package/dist/clients/opaque-mutation-scan.js +0 -496
  502. package/dist/clients/opengrep-client.js +0 -328
  503. package/dist/clients/opengrep-config.js +0 -76
  504. package/dist/clients/package-manager.js +0 -607
  505. package/dist/clients/package-root.js +0 -38
  506. package/dist/clients/partial-edit-apply.js +0 -439
  507. package/dist/clients/path-attribution-telemetry.js +0 -43
  508. package/dist/clients/path-keyed-map.js +0 -108
  509. package/dist/clients/path-utils.js +0 -1244
  510. package/dist/clients/performance-report.js +0 -331
  511. package/dist/clients/persist-debounce.js +0 -70
  512. package/dist/clients/persistent-reverify.js +0 -271
  513. package/dist/clients/php-cs-fixer-config.js +0 -119
  514. package/dist/clients/pipeline.js +0 -1425
  515. package/dist/clients/post-autofix-notice.js +0 -37
  516. package/dist/clients/print-mode.js +0 -21
  517. package/dist/clients/probe-home-state.js +0 -228
  518. package/dist/clients/process-bridge.js +0 -66
  519. package/dist/clients/process-singletons.js +0 -210
  520. package/dist/clients/process-snapshot.js +0 -68
  521. package/dist/clients/project-changes.js +0 -181
  522. package/dist/clients/project-conventions.js +0 -171
  523. package/dist/clients/project-diagnostics/cache.js +0 -137
  524. package/dist/clients/project-diagnostics/extractors.js +0 -109
  525. package/dist/clients/project-diagnostics/fresh-fetch.js +0 -650
  526. package/dist/clients/project-diagnostics/runner-adapters/call-graph-impact.js +0 -118
  527. package/dist/clients/project-diagnostics/runner-adapters/dead-code.js +0 -47
  528. package/dist/clients/project-diagnostics/runner-adapters/gitleaks.js +0 -40
  529. package/dist/clients/project-diagnostics/runner-adapters/govulncheck.js +0 -34
  530. package/dist/clients/project-diagnostics/runner-adapters/jscpd.js +0 -38
  531. package/dist/clients/project-diagnostics/runner-adapters/knip.js +0 -47
  532. package/dist/clients/project-diagnostics/runner-adapters/madge.js +0 -48
  533. package/dist/clients/project-diagnostics/runner-adapters/opengrep.js +0 -40
  534. package/dist/clients/project-diagnostics/runner-adapters/runner-findings.js +0 -127
  535. package/dist/clients/project-diagnostics/runner-adapters/trivy.js +0 -81
  536. package/dist/clients/project-diagnostics/scanner.js +0 -520
  537. package/dist/clients/project-diagnostics/types.js +0 -1
  538. package/dist/clients/project-lens-config.js +0 -799
  539. package/dist/clients/project-report.js +0 -701
  540. package/dist/clients/project-scale.js +0 -237
  541. package/dist/clients/project-scan-policy.js +0 -11
  542. package/dist/clients/project-snapshot-fingerprint.js +0 -48
  543. package/dist/clients/project-snapshot-persist-worker.js +0 -20
  544. package/dist/clients/project-snapshot.js +0 -1653
  545. package/dist/clients/project-trust.js +0 -181
  546. package/dist/clients/python-environment.js +0 -217
  547. package/dist/clients/python-provenance.js +0 -639
  548. package/dist/clients/quiet-window-config.js +0 -47
  549. package/dist/clients/quiet-window.js +0 -236
  550. package/dist/clients/read-bridge.js +0 -139
  551. package/dist/clients/read-expansion.js +0 -266
  552. package/dist/clients/read-guard-logger.js +0 -251
  553. package/dist/clients/read-guard-tool-lines.js +0 -1306
  554. package/dist/clients/read-guard.js +0 -1561
  555. package/dist/clients/recent-touches.js +0 -240
  556. package/dist/clients/redact/secrets.js +0 -449
  557. package/dist/clients/resource-sampler.js +0 -628
  558. package/dist/clients/reverse-deps.js +0 -270
  559. package/dist/clients/review-graph/builder.js +0 -5118
  560. package/dist/clients/review-graph/format.js +0 -33
  561. package/dist/clients/review-graph/git-identity.js +0 -157
  562. package/dist/clients/review-graph/import-resolvers.js +0 -481
  563. package/dist/clients/review-graph/persist-worker.js +0 -10
  564. package/dist/clients/review-graph/query.js +0 -244
  565. package/dist/clients/review-graph/revision-drift.js +0 -21
  566. package/dist/clients/review-graph/service.js +0 -96
  567. package/dist/clients/review-graph/shared-extraction-ir.js +0 -82
  568. package/dist/clients/review-graph/symbol-id.js +0 -103
  569. package/dist/clients/review-graph/tsconfig-paths.js +0 -299
  570. package/dist/clients/review-graph/types.js +0 -1
  571. package/dist/clients/review-graph/workspace-modules.js +0 -449
  572. package/dist/clients/review-graph-logger.js +0 -81
  573. package/dist/clients/ruff-client.js +0 -152
  574. package/dist/clients/rules-scanner.js +0 -131
  575. package/dist/clients/run-duration.js +0 -55
  576. package/dist/clients/runtime-agent-end.js +0 -746
  577. package/dist/clients/runtime-config.js +0 -77
  578. package/dist/clients/runtime-context.js +0 -211
  579. package/dist/clients/runtime-coordinator.js +0 -1290
  580. package/dist/clients/runtime-session.js +0 -2485
  581. package/dist/clients/runtime-tool-call.js +0 -1284
  582. package/dist/clients/runtime-tool-result.js +0 -2034
  583. package/dist/clients/runtime-turn.js +0 -3600
  584. package/dist/clients/rust-client.js +0 -97
  585. package/dist/clients/safe-spawn.js +0 -2166
  586. package/dist/clients/sanitize.js +0 -286
  587. package/dist/clients/scan-utils.js +0 -25
  588. package/dist/clients/scratch-tree-policy.js +0 -165
  589. package/dist/clients/search-read-registration.js +0 -94
  590. package/dist/clients/secret-findings.js +0 -114
  591. package/dist/clients/security-scan-client.js +0 -352
  592. package/dist/clients/session-event-guard.js +0 -297
  593. package/dist/clients/session-lifecycle.js +0 -484
  594. package/dist/clients/session-start-observability.js +0 -94
  595. package/dist/clients/session-state-store.js +0 -101
  596. package/dist/clients/session-summary.js +0 -15
  597. package/dist/clients/sessionstart-logger.js +0 -27
  598. package/dist/clients/sg-runner.js +0 -876
  599. package/dist/clients/sgconfig.js +0 -347
  600. package/dist/clients/shared-checkout-guard.js +0 -338
  601. package/dist/clients/single-flight.js +0 -158
  602. package/dist/clients/situational-tool-telemetry.js +0 -108
  603. package/dist/clients/skills-resolver.js +0 -141
  604. package/dist/clients/slow-fs.js +0 -138
  605. package/dist/clients/smells-rollup.js +0 -231
  606. package/dist/clients/source-filter.js +0 -596
  607. package/dist/clients/source-walker.js +0 -211
  608. package/dist/clients/spawn-output-cap.js +0 -37
  609. package/dist/clients/spawn-timeout-cooldown.js +0 -110
  610. package/dist/clients/stale-marker.js +0 -17
  611. package/dist/clients/startup-scan.js +0 -400
  612. package/dist/clients/startup-timing.js +0 -130
  613. package/dist/clients/string-utils.js +0 -33
  614. package/dist/clients/subagent-mode.js +0 -111
  615. package/dist/clients/symbol-containment.js +0 -24
  616. package/dist/clients/symbol-types.js +0 -5
  617. package/dist/clients/test-runner-client.js +0 -2507
  618. package/dist/clients/test-runner-delivery.js +0 -287
  619. package/dist/clients/todo-scanner.js +0 -229
  620. package/dist/clients/tool-agreement.js +0 -423
  621. package/dist/clients/tool-config.js +0 -249
  622. package/dist/clients/tool-cwd.js +0 -270
  623. package/dist/clients/tool-definition.js +0 -47
  624. package/dist/clients/tool-event.js +0 -105
  625. package/dist/clients/tool-policy.js +0 -2755
  626. package/dist/clients/tool-probe.js +0 -53
  627. package/dist/clients/tool-render.js +0 -156
  628. package/dist/clients/tool-set-policy.js +0 -118
  629. package/dist/clients/tree-sitter-cache.js +0 -364
  630. package/dist/clients/tree-sitter-client.js +0 -4134
  631. package/dist/clients/tree-sitter-logger.js +0 -100
  632. package/dist/clients/tree-sitter-navigator.js +0 -269
  633. package/dist/clients/tree-sitter-query-loader.js +0 -569
  634. package/dist/clients/tree-sitter-shared.js +0 -158
  635. package/dist/clients/tree-sitter-symbol-extractor.js +0 -1265
  636. package/dist/clients/trivy-client.js +0 -467
  637. package/dist/clients/tui-fit.js +0 -50
  638. package/dist/clients/turn-context.js +0 -52
  639. package/dist/clients/turn-summary-render.js +0 -72
  640. package/dist/clients/turn-summary.js +0 -132
  641. package/dist/clients/typos-config.js +0 -29
  642. package/dist/clients/user-notify.js +0 -51
  643. package/dist/clients/vanished-instance-marker.js +0 -57
  644. package/dist/clients/warm-attach.js +0 -246
  645. package/dist/clients/widget-state.js +0 -1677
  646. package/dist/clients/word-index-logger.js +0 -49
  647. package/dist/clients/word-index-store.js +0 -459
  648. package/dist/clients/word-index.js +0 -2080
  649. package/dist/clients/workspace-topology.js +0 -389
  650. package/dist/clients/write-ordering-guard.js +0 -65
  651. package/dist/clients/zizmor-config.js +0 -327
  652. package/dist/i18n.js +0 -69
  653. package/dist/mcp/build-staleness.js +0 -124
  654. package/dist/scripts/lib/process-scan.mjs +0 -583
  655. package/dist/scripts/lib/skills-predicate.mjs +0 -129
  656. package/dist/tools/activate-tools.js +0 -87
  657. package/dist/tools/ast-grep-outline.js +0 -137
  658. package/dist/tools/ast-grep-replace.js +0 -244
  659. package/dist/tools/ast-grep-search.js +0 -762
  660. package/dist/tools/effective-config.js +0 -90
  661. package/dist/tools/lens-diagnostic-mark.js +0 -375
  662. package/dist/tools/lens-diagnostics.js +0 -2544
  663. package/dist/tools/lsp-diagnostics.js +0 -1634
  664. package/dist/tools/lsp-navigation.js +0 -1367
  665. package/dist/tools/lsp-structured-output.js +0 -294
  666. package/dist/tools/module-report.js +0 -382
  667. package/dist/tools/project-report.js +0 -86
  668. package/dist/tools/render-compact.js +0 -374
  669. package/dist/tools/scan-progress.js +0 -53
  670. package/dist/tools/shared.js +0 -29
  671. package/dist/tools/symbol-search.js +0 -155
@@ -1,1313 +0,0 @@
1
- /**
2
- * Prompt-cache observability (#1018).
3
- *
4
- * Two provider-independent signals, both sinking into ~/.pi-lens/latency.log
5
- * via {@link logLatency} (matching the neighboring `type: "phase"` records):
6
- *
7
- * 1. Response-side cache usage (`cache_usage`) — on each assistant
8
- * `message_end`, record the provider-reported token/cost breakdown so a
9
- * session's actual cacheRead/cacheWrite behavior is queryable after the
10
- * fact. This is what the provider DID, not what we hoped it would do.
11
- *
12
- * 2. Request-side context observations (`cache_context`) — one bounded record
13
- * for every `context` call, describing pi-lens's own before/after message
14
- * transformation, placement, injection sources, and privacy-preserving
15
- * hashes. This is what pi-lens observed locally, not the final provider
16
- * request after other context handlers have run and not a provider cache
17
- * result. #1938: this record used to also carry a `prefixObservation` /
18
- * `firstMessageChange` pair derived from a SEPARATE bounded hash of the
19
- * pre-injection prefix (capped at `MAX_HASHED_MESSAGES` messages /
20
- * `MAX_HASHED_CONTENT_CHARS` chars). Every real session's transcript
21
- * exceeds that cap almost immediately, so the pair reported "unknown" on
22
- * 97% of records — dead weight in every record, answering nothing. The
23
- * pair is removed; signal 3 below (`cache_prefix_break`) already covers
24
- * first-message stability with an unbounded hash and never truncates.
25
- *
26
- * 3. Request-side prefix stability (`cache_prefix_break`) — a content hash of
27
- * `messages[0]` observed on every `context` call. After #1016 the first
28
- * message must stay byte-stable across a whole session; a logged CHANGE
29
- * flags that something (pi-lens or otherwise) broke the cache prefix. This
30
- * remains a local observation, never a provider cache-miss claim.
31
- *
32
- * #1071 adds miss ATTRIBUTION on top of those three. Each `cache_usage` record
33
- * carries the inter-turn gap and a `cacheMissCause` verdict, and each
34
- * `cache_context` record splits a mixed injection payload by contributing
35
- * source. #1996 makes every unexplained miss name the absent/conflicting
36
- * evidence and emits one fixed-key `cache_usage_summary` at session shutdown.
37
- * Heuristic causes require complete request hashing and full provider/model
38
- * identity evidence. Identity comparison uses SHA-256 over the full normalized
39
- * value while logs retain only a bounded display prefix; malformed numeric
40
- * usage is sanitized before it reaches JSON metadata.
41
- * The per-turn records still ride events that already fire once per turn, and
42
- * all attribution derives from bounded in-process state — nothing reads
43
- * latency.log back or serializes transcript content.
44
- *
45
- * All paths are defensive: `usage` (and its fields) may be absent on older
46
- * hosts or non-assistant messages, so every access is guarded and the handlers
47
- * never throw — on error they `dbg(...)` and no-op, like the other index.ts
48
- * event handlers.
49
- */
50
- import { createHash } from "node:crypto";
51
- import { BoundedFifoMap, BoundedLruCache } from "./bounded-cache.js";
52
- import { lazyEnvNumber } from "./env-utils.js";
53
- import { logLatency } from "./latency-logger.js";
54
- import { compareOrdinal } from "./string-utils.js";
55
- /** RuntimeCoordinator's counter is process-global when sessions share a host. */
56
- const PROCESS_TURN_SCOPE = "process-global-runtime";
57
- const SECONDARY_TURN_SCOPE = "unavailable-concurrent-secondary";
58
- /**
59
- * Keep context telemetry bounded even when a tool result or user message is
60
- * unexpectedly large. This is a hash input only; none of the sampled text is
61
- * written to the log.
62
- */
63
- const MAX_HASHED_MESSAGES = 64;
64
- const MAX_HASHED_CONTENT_CHARS = 2048;
65
- const MAX_REPORTED_MESSAGES = 10_000;
66
- const MAX_INJECTED_CHARS = 16_384;
67
- const MAX_INJECTED_BYTES = 65_536;
68
- let contextObservationCounter = 0;
69
- /**
70
- * Documented deterministic char→token estimate. Four characters per token is
71
- * the same ratio #1071's issue body used to size the sampled injections. It is
72
- * an ESTIMATE: never present a value derived from it as provider-measured
73
- * usage.
74
- */
75
- const CHARS_PER_ESTIMATED_TOKEN = 4;
76
- /**
77
- * Idle gap after which a provider prompt cache entry is assumed expired.
78
- *
79
- * The gap this is compared against is measured to REQUEST time, not to the
80
- * `message_end` that follows it — see {@link resolveInterTurnGap}. The provider
81
- * looks the cache up when the request arrives, so the response's own generation
82
- * time is not idle time and must not count toward expiry.
83
- *
84
- * Evidence (2026-08-21 KV-cache investigation, 63 sessions, 2,288 turns): the
85
- * 34 zero-`cacheRead` turns had a MEDIAN inter-turn gap of 166s, against 9s for
86
- * every other turn. Those 34 turns carried 6.96M fresh input tokens, 35.1% of
87
- * all fresh input in the window. 60s sits between the two populations and
88
- * matches the documented 5-minute-minus-safety-margin behavior of the shortest
89
- * provider TTL tier we run against. Override with
90
- * `PI_LENS_PROVIDER_CACHE_TTL_MS` when a provider's TTL differs.
91
- */
92
- export const DEFAULT_PROVIDER_CACHE_TTL_MS = 60_000;
93
- const _providerCacheTtl = lazyEnvNumber("PI_LENS_PROVIDER_CACHE_TTL_MS", DEFAULT_PROVIDER_CACHE_TTL_MS);
94
- const getProviderCacheTtlMs = _providerCacheTtl.get;
95
- export const _resetProviderCacheTtlForTests = _providerCacheTtl._resetForTests;
96
- /**
97
- * A turn counts as "anomalously low" when it reads back less than half of what
98
- * the previous turn read. The investigation's partial-break population (90
99
- * turns, upper-bounded at 2.7M tokens) was selected by exactly this shape: a
100
- * non-zero `cacheRead` well below the prior turn's, which a zero-read filter
101
- * misses entirely.
102
- */
103
- const LOW_CACHE_READ_RATIO = 0.5;
104
- /**
105
- * Fresh input must exceed the estimated new content by this factor before a
106
- * shortfall reads as provider-side eviction rather than as our own payload.
107
- * The investigation upper-bounds a whole session's injections at ~2.7 tokens
108
- * per turn, so fresh input several times the measured new content cannot be
109
- * explained by what pi-lens added.
110
- */
111
- const PARTIAL_EVICTION_INPUT_FACTOR = 4;
112
- /**
113
- * Floor for the same rule, so a turn with almost no new content does not read
114
- * as eviction on a handful of tokens.
115
- */
116
- const PARTIAL_EVICTION_MIN_FRESH_TOKENS = 512;
117
- /**
118
- * Cap on the per-session character accumulators used for attribution, and on a
119
- * single transcript-growth measurement feeding them.
120
- *
121
- * This is deliberately NOT `MAX_INJECTED_CHARS`. That 16 KiB cap exists to keep
122
- * the reported injection size small, and pi-lens injections average about 2.7
123
- * estimated tokens per turn, so it is never reached in practice. Transcript
124
- * growth is a different population: one ordinary tool result can add 20,000
125
- * characters in a single turn. Measuring growth through the injection cap
126
- * latched `attributionCharsCapped` on a routine turn and suppressed the
127
- * `partial-eviction` verdict, which made the verdict near-unreachable (#1071
128
- * review round 1, F2).
129
- */
130
- const MAX_ATTRIBUTION_CHARS = 262_144;
131
- /** Byte companion to {@link MAX_ATTRIBUTION_CHARS}, at four bytes per char. */
132
- const MAX_ATTRIBUTION_BYTES = 1_048_576;
133
- function emptyCacheMissCauses() {
134
- return {
135
- "ttl-expired": 0,
136
- "prefix-broke": 0,
137
- "partial-eviction": 0,
138
- "model-provider-changed": 0,
139
- unknown: 0,
140
- };
141
- }
142
- function emptyUnknownEvidenceReasons() {
143
- return {
144
- "no-prior-sample": 0,
145
- "cache-read-unavailable": 0,
146
- "malformed-provider-usage": 0,
147
- "request-correlation-unavailable": 0,
148
- "request-evidence-incomplete": 0,
149
- "sequence-hash-truncated": 0,
150
- "model-provider-unavailable": 0,
151
- "provider-reported-zero-stable-prefix": 0,
152
- "provider-reported-low-read-stable-prefix": 0,
153
- "no-local-explanation": 0,
154
- };
155
- }
156
- function newCacheUsageSummary() {
157
- return {
158
- usageRecords: 0,
159
- cacheHits: 0,
160
- missObservations: 0,
161
- cacheMissCauses: emptyCacheMissCauses(),
162
- unknownEvidenceReasons: emptyUnknownEvidenceReasons(),
163
- };
164
- }
165
- // Shared cap for every per-session bounded map in this module (also used by
166
- // `prefixHashBySession` below) — a long-lived process cycling through many
167
- // sessions cannot grow any of them without limit.
168
- export const MAX_TRACKED_SESSIONS = 32;
169
- const attributionBySession = new BoundedLruCache(MAX_TRACKED_SESSIONS);
170
- function newAttributionState() {
171
- return {
172
- prefixBrokeSinceLastUsage: false,
173
- prefixStableSinceLastUsage: false,
174
- sequenceHashTruncatedSinceLastUsage: false,
175
- requestEvidenceIncompleteSinceLastUsage: false,
176
- injectedCharsSinceLastUsage: 0,
177
- newTranscriptCharsSinceLastUsage: 0,
178
- attributionCharsCapped: false,
179
- injectedBytes: emptyInjectedBytes(),
180
- injectedFindingsRepeated: 0,
181
- findingIdentities: new Set(),
182
- findingIdentityCapRecorded: false,
183
- turnEndAdvisoryBytes: 0,
184
- toolResultBytes: 0,
185
- toolResultsTruncated: 0,
186
- summary: newCacheUsageSummary(),
187
- };
188
- }
189
- const MAX_FINDING_IDENTITIES = 2_000;
190
- function emptyInjectedBytes() {
191
- return {
192
- sessionGuidance: 0,
193
- turnFindings: 0,
194
- testFindings: 0,
195
- agentNudge: 0,
196
- turnEndAdvisory: 0,
197
- other: 0,
198
- };
199
- }
200
- function sourceKey(source) {
201
- return {
202
- "session-guidance": "sessionGuidance",
203
- "turn-findings": "turnFindings",
204
- "test-findings": "testFindings",
205
- "agent-nudge": "agentNudge",
206
- }[source];
207
- }
208
- /** Best-effort, language-neutral identity extraction from rendered findings. */
209
- function findingIdentities(text) {
210
- const out = [];
211
- for (const line of text.split(/\r?\n/)) {
212
- const location = line.match(/(?:^|\s)([^\s:]+):(\d+)(?::\d+)?/);
213
- if (!location)
214
- continue;
215
- const rule = line.match(/(?:rule|code)\s*[:=]\s*([\w./-]+)/i)?.[1] ??
216
- line.match(/\(([\w./-]+)\)\s*$/)?.[1] ??
217
- line.match(/:\d+(?::\d+)?\s+([\w./-]+)/)?.[1];
218
- if (rule)
219
- out.push(`${location[1]}:${location[2]}:${rule}`);
220
- }
221
- return out;
222
- }
223
- /**
224
- * Fetch (creating if absent) one session's attribution state, refreshing LRU
225
- * recency and evicting the oldest entries past the cap — same bounding as
226
- * {@link recordSessionHash}, so a long-lived process cycling through sessions
227
- * cannot grow this map without limit.
228
- */
229
- function attributionFor(key) {
230
- const existing = attributionBySession.get(key);
231
- const state = existing ?? newAttributionState();
232
- // `get` above already moved an existing entry to MRU; `set` below also
233
- // refreshes recency on a create, so every fetch counts as a touch.
234
- attributionBySession.set(key, state);
235
- return state;
236
- }
237
- /**
238
- * Fold one `context` observation into the session's attribution state: how much
239
- * pi-lens injected, and how much the transcript itself grew since the previous
240
- * observation. The transcript delta is what the "far above the injected and new
241
- * content" rule measures fresh input against. The first observation in a
242
- * session only anchors the message-count baseline, because there is no earlier
243
- * point to measure growth from.
244
- */
245
- function recordContextAttribution(key, existingMessages, injectedSize) {
246
- const state = attributionFor(key);
247
- const baseline = Math.min(state.lastObservedMessageCount ?? existingMessages.length, existingMessages.length);
248
- const grown = measureTranscriptGrowth(existingMessages.slice(baseline));
249
- state.injectedCharsSinceLastUsage = Math.min(MAX_ATTRIBUTION_CHARS, state.injectedCharsSinceLastUsage + injectedSize.chars);
250
- state.newTranscriptCharsSinceLastUsage = Math.min(MAX_ATTRIBUTION_CHARS, state.newTranscriptCharsSinceLastUsage + grown.chars);
251
- if (injectedSize.capped ||
252
- grown.capped ||
253
- state.injectedCharsSinceLastUsage >= MAX_ATTRIBUTION_CHARS ||
254
- state.newTranscriptCharsSinceLastUsage >= MAX_ATTRIBUTION_CHARS) {
255
- // The accumulators are now floors, not totals. The verdict rules must not
256
- // treat a floor as a measured value.
257
- state.attributionCharsCapped = true;
258
- }
259
- state.lastObservedMessageCount = existingMessages.length;
260
- // #1071 review round 1, F1: this handler runs at REQUEST time, which is when
261
- // the provider looks the prompt cache up. Stamping it here is what lets the
262
- // gap exclude the response's own generation time.
263
- state.lastContextAtMs = Date.now();
264
- }
265
- /**
266
- * Idle milliseconds before this turn's provider request.
267
- *
268
- * Measuring `message_end` to `message_end` would fold the response's own
269
- * generation time into the gap, and generation dominates: over a real corpus
270
- * the median generation time is 7,407 ms against a median true idle of 228 ms,
271
- * a factor of 30. At the 60s threshold, 8.7% of consecutive pairs measure over
272
- * on the message-end basis while only 3.3% were truly idle over. That is a 3.4x
273
- * inflation of `ttl-expired`, which would have confirmed the investigation's
274
- * hypothesis by construction (#1071 review round 1, F1).
275
- */
276
- function resolveInterTurnGap(state, nowMs) {
277
- if (state.lastUsageAtMs === undefined) {
278
- return { gapMs: null, basis: "no-prior-turn" };
279
- }
280
- if (state.lastContextAtMs !== undefined) {
281
- return {
282
- gapMs: Math.max(0, state.lastContextAtMs - state.lastUsageAtMs),
283
- basis: "request-time",
284
- };
285
- }
286
- return {
287
- gapMs: Math.max(0, nowMs - state.lastUsageAtMs),
288
- basis: "message-end-fallback",
289
- };
290
- }
291
- function estimateTokens(chars) {
292
- return Math.ceil(chars / CHARS_PER_ESTIMATED_TOKEN);
293
- }
294
- function readableTokenCount(value) {
295
- return typeof value === "number" && Number.isFinite(value) && value >= 0
296
- ? value
297
- : undefined;
298
- }
299
- function readNumericEvidence(record, key) {
300
- let raw;
301
- try {
302
- raw = record[key];
303
- }
304
- catch {
305
- return { status: "malformed" };
306
- }
307
- if (raw === undefined)
308
- return { status: "absent" };
309
- const value = readableTokenCount(raw);
310
- return value === undefined
311
- ? { status: "malformed" }
312
- : { status: "available", value };
313
- }
314
- const MAX_LOGGED_IDENTITY_CHARS = 200;
315
- /**
316
- * Keep the human-readable identity bounded while comparing a SHA-256 digest of
317
- * the FULL normalized value. Comparing the display prefix would make two long
318
- * provider/model ids that differ after the cap collide (#1996 review).
319
- */
320
- function identityEvidence(value) {
321
- if (typeof value !== "string")
322
- return { status: "unavailable" };
323
- const normalized = value.trim();
324
- if (!normalized)
325
- return { status: "unavailable" };
326
- const truncated = normalized.length > MAX_LOGGED_IDENTITY_CHARS;
327
- return {
328
- display: normalized.slice(0, MAX_LOGGED_IDENTITY_CHARS),
329
- hash: createHash("sha256").update(normalized).digest("hex"),
330
- status: truncated ? "truncated" : "complete",
331
- };
332
- }
333
- /**
334
- * Classify a turn's prompt-cache shortfall. Returns `null` when no comparable
335
- * miss exists: no prior readable usage record or a healthy read. The caller
336
- * separately records why an unreadable/first zero sample could not be
337
- * classified, so those evidence gaps remain visible in the session summary.
338
- *
339
- * Rules, in the order they are applied, each stated with the evidence behind
340
- * it (2026-08-21 investigation, 63 sessions, 2,288 turns, 94.2% overall hit
341
- * rate):
342
- *
343
- * 1. `prefix-broke` — a `cache_prefix_break` CHANGE fired in this session
344
- * since the previous usage record. This is a DIRECT local observation of
345
- * the cause, so it outranks the timing heuristics below. The window was
346
- * byte-stable throughout, so this verdict should stay rare; if it does
347
- * not, #1016's fix has regressed.
348
- * 2. `model-provider-changed` — both adjacent identities were present and
349
- * differ. This is direct local evidence and outranks timing heuristics.
350
- * 3. Evidence gates — heuristic causes require a REQUEST-time observation,
351
- * a complete bounded sequence hash, adjacent full provider/model identity,
352
- * and well-formed provider usage numbers.
353
- * Missing evidence returns a specific unknown reason; it never lets a
354
- * plausible but unproved heuristic win.
355
- * 4. `ttl-expired` — a REQUEST-time gap reached the configured provider TTL.
356
- * A message-end fallback includes generation time and cannot prove this.
357
- * 5. `partial-eviction` — a non-zero but low read, where fresh input runs far
358
- * above the new content we measured. pi-lens injections average ~2.7
359
- * estimated tokens per turn, so they cannot account for a multiple of the
360
- * measured content; the remainder is provider-side eviction, typically at
361
- * a context limit. Suppressed when the character accumulators were capped,
362
- * because a floor estimate would manufacture the verdict.
363
- * 6. `unknown` — a real shortfall with no local explanation. A bounded
364
- * `cacheMissUnknownReason` names the missing or conflicting evidence;
365
- * provider behavior is never guessed.
366
- */
367
- function classifyCacheMiss(args) {
368
- const cacheRead = readableTokenCount(args.cacheRead);
369
- if (cacheRead === undefined)
370
- return null;
371
- // No baseline turn in this session: a first turn reads zero because nothing
372
- // is cached yet, not because anything went wrong.
373
- const priorCacheRead = readableTokenCount(args.priorCacheRead);
374
- if (priorCacheRead === undefined) {
375
- return null;
376
- }
377
- let kind;
378
- if (cacheRead === 0) {
379
- kind = "zero-read";
380
- }
381
- else if (priorCacheRead > 0 &&
382
- cacheRead < priorCacheRead * LOW_CACHE_READ_RATIO) {
383
- kind = "low-read";
384
- }
385
- else {
386
- return null;
387
- }
388
- // A missing stable session id makes every cross-event baseline ambiguous. Do
389
- // not let the shared fallback bucket turn another session's evidence into a
390
- // cause claim (#1996 concurrent primary/secondary invariant).
391
- if (!args.stableSessionIdentity) {
392
- return {
393
- kind,
394
- cause: "unknown",
395
- unknownReason: "request-correlation-unavailable",
396
- };
397
- }
398
- if (args.prefixBroke)
399
- return { kind, cause: "prefix-broke" };
400
- if (args.modelProviderChanged) {
401
- return { kind, cause: "model-provider-changed" };
402
- }
403
- // TTL and transcript-growth claims need the request-side context observation.
404
- // A response-time fallback includes generation and can only explain why the
405
- // verdict stayed unknown; it cannot establish cache expiry.
406
- if (args.gapBasis !== "request-time") {
407
- return {
408
- kind,
409
- cause: "unknown",
410
- unknownReason: "request-correlation-unavailable",
411
- };
412
- }
413
- // TTL and eviction are heuristics. They are only evidence-backed if the
414
- // bounded request observation is complete and both adjacent usage records
415
- // identify the same provider/model. Otherwise an unseen prompt or identity
416
- // change remains a competing explanation, so classification must fail closed.
417
- if (args.requestEvidenceIncomplete) {
418
- return {
419
- kind,
420
- cause: "unknown",
421
- unknownReason: "request-evidence-incomplete",
422
- };
423
- }
424
- if (args.sequenceHashTruncated) {
425
- return {
426
- kind,
427
- cause: "unknown",
428
- unknownReason: "sequence-hash-truncated",
429
- };
430
- }
431
- if (args.providerUsageMalformed) {
432
- return {
433
- kind,
434
- cause: "unknown",
435
- unknownReason: "malformed-provider-usage",
436
- };
437
- }
438
- if (!args.modelProviderEvidenceAvailable) {
439
- return {
440
- kind,
441
- cause: "unknown",
442
- unknownReason: "model-provider-unavailable",
443
- };
444
- }
445
- if (args.interTurnGapMs !== null && args.interTurnGapMs >= args.ttlMs) {
446
- return { kind, cause: "ttl-expired" };
447
- }
448
- if (kind === "low-read" &&
449
- !args.attributionCharsCapped &&
450
- args.input >
451
- Math.max(PARTIAL_EVICTION_MIN_FRESH_TOKENS, args.estimatedNewTokens * PARTIAL_EVICTION_INPUT_FACTOR)) {
452
- return { kind, cause: "partial-eviction" };
453
- }
454
- if (args.prefixStable) {
455
- return {
456
- kind,
457
- cause: "unknown",
458
- unknownReason: kind === "zero-read"
459
- ? "provider-reported-zero-stable-prefix"
460
- : "provider-reported-low-read-stable-prefix",
461
- };
462
- }
463
- return {
464
- kind,
465
- cause: "unknown",
466
- unknownReason: "no-local-explanation",
467
- };
468
- }
469
- function recordCacheUsageSummary(args) {
470
- const summary = args.state.summary;
471
- summary.usageRecords += 1;
472
- let unknownReasonRecorded = false;
473
- if (args.unknownReason === "malformed-provider-usage") {
474
- summary.unknownEvidenceReasons["malformed-provider-usage"] += 1;
475
- unknownReasonRecorded = true;
476
- }
477
- if (args.cacheRead === undefined) {
478
- if (!unknownReasonRecorded) {
479
- summary.unknownEvidenceReasons["cache-read-unavailable"] += 1;
480
- }
481
- return;
482
- }
483
- if (args.priorCacheRead === undefined) {
484
- if (args.cacheRead === 0) {
485
- summary.missObservations += 1;
486
- if (!unknownReasonRecorded) {
487
- summary.unknownEvidenceReasons["no-prior-sample"] += 1;
488
- }
489
- }
490
- else {
491
- summary.cacheHits += 1;
492
- }
493
- return;
494
- }
495
- if (!args.verdict) {
496
- summary.cacheHits += 1;
497
- return;
498
- }
499
- summary.missObservations += 1;
500
- summary.cacheMissCauses[args.verdict.cause] += 1;
501
- if (args.verdict.cause === "unknown" &&
502
- args.unknownReason &&
503
- !unknownReasonRecorded) {
504
- summary.unknownEvidenceReasons[args.unknownReason] += 1;
505
- }
506
- }
507
- function boundedHashScalar(value, state) {
508
- if (value === null)
509
- return "null";
510
- if (value === undefined)
511
- return "undefined";
512
- if (typeof value === "string") {
513
- const truncated = value.length > MAX_HASHED_CONTENT_CHARS;
514
- if (truncated)
515
- state.contentTruncated = true;
516
- const suffix = truncated ? ":content-truncated" : "";
517
- return `string:${value.length}:${value.slice(0, MAX_HASHED_CONTENT_CHARS)}${suffix}`;
518
- }
519
- if (typeof value === "number" ||
520
- typeof value === "boolean" ||
521
- typeof value === "bigint") {
522
- return `${typeof value}:${String(value)}`;
523
- }
524
- return typeof value;
525
- }
526
- function boundedHashArray(value, depth, seen, state) {
527
- if (value.length > 12)
528
- state.contentTruncated = true;
529
- const items = value
530
- .slice(0, 12)
531
- .map((item) => boundedHashValue(item, depth + 1, seen, state));
532
- return `array:${value.length}:[${items.join(",")}]`;
533
- }
534
- function boundedHashObject(value, depth, seen, state) {
535
- const keys = Object.keys(value).sort((left, right) => compareOrdinal(left, right));
536
- if (keys.length > 24)
537
- state.contentTruncated = true;
538
- const fields = keys
539
- .slice(0, 24)
540
- .map((key) => `${key}:${boundedHashValue(value[key], depth + 1, seen, state)}`);
541
- return `object:${keys.length}:{${fields.join(",")}}`;
542
- }
543
- function boundedHashValue(value, depth = 0, seen = new Set(), state) {
544
- const hashState = state ?? { contentTruncated: false, incomplete: false };
545
- if (value === null || typeof value !== "object") {
546
- return boundedHashScalar(value, hashState);
547
- }
548
- if (depth >= 3) {
549
- hashState.contentTruncated = true;
550
- return "[depth-limit]";
551
- }
552
- if (seen.has(value)) {
553
- hashState.incomplete = true;
554
- return "[cycle]";
555
- }
556
- seen.add(value);
557
- try {
558
- if (Array.isArray(value)) {
559
- return boundedHashArray(value, depth, seen, hashState);
560
- }
561
- return boundedHashObject(value, depth, seen, hashState);
562
- }
563
- catch {
564
- hashState.incomplete = true;
565
- return "[unreadable]";
566
- }
567
- finally {
568
- seen.delete(value);
569
- }
570
- }
571
- function hashMessageSequence(messages) {
572
- const hash = createHash("sha256");
573
- const state = {
574
- contentTruncated: false,
575
- incomplete: false,
576
- };
577
- let messageCount;
578
- try {
579
- messageCount = messages.length;
580
- if (!Number.isSafeInteger(messageCount) || messageCount < 0) {
581
- throw new Error("invalid message count");
582
- }
583
- }
584
- catch {
585
- state.incomplete = true;
586
- hash.update("message-count:[unreadable];");
587
- return {
588
- hash: hash.digest("hex"),
589
- truncated: false,
590
- contentTruncated: false,
591
- incomplete: true,
592
- };
593
- }
594
- hash.update(`message-count:${messageCount};`);
595
- const sampled = Math.min(messageCount, MAX_HASHED_MESSAGES);
596
- for (let i = 0; i < sampled; i++) {
597
- const seen = new Set();
598
- let role;
599
- let content;
600
- try {
601
- const message = messages[i];
602
- role = message?.role;
603
- content = message?.content;
604
- }
605
- catch {
606
- state.incomplete = true;
607
- role = "[unreadable]";
608
- content = "[unreadable]";
609
- }
610
- hash.update(`${i}|role:${boundedHashValue(role, 0, seen, state)}|content:${boundedHashValue(content, 0, seen, state)};`);
611
- }
612
- const truncated = messageCount > sampled;
613
- if (truncated)
614
- hash.update(`truncated-after:${sampled};`);
615
- return {
616
- hash: hash.digest("hex"),
617
- truncated,
618
- contentTruncated: state.contentTruncated,
619
- incomplete: state.incomplete,
620
- };
621
- }
622
- /** Bounds for reporting an injected payload's size in the record. */
623
- const INJECTED_LIMITS = {
624
- maxChars: MAX_INJECTED_CHARS,
625
- maxBytes: MAX_INJECTED_BYTES,
626
- };
627
- /** Bounds for the transcript-growth accumulator that feeds the verdict. */
628
- const TRANSCRIPT_LIMITS = {
629
- maxChars: MAX_ATTRIBUTION_CHARS,
630
- maxBytes: MAX_ATTRIBUTION_BYTES,
631
- };
632
- function messageTextSize(content, limits) {
633
- if (typeof content === "string") {
634
- const chars = Math.min(content.length, limits.maxChars);
635
- return {
636
- chars,
637
- bytes: Math.min(Buffer.byteLength(content.slice(0, chars), "utf8"), limits.maxBytes),
638
- };
639
- }
640
- const bounded = boundedHashValue(content, 0, new Set(), {
641
- contentTruncated: false,
642
- incomplete: false,
643
- });
644
- return {
645
- chars: Math.min(bounded.length, limits.maxChars),
646
- bytes: Math.min(Buffer.byteLength(bounded.slice(0, limits.maxChars), "utf8"), limits.maxBytes),
647
- };
648
- }
649
- function measureMessages(messages, limits) {
650
- let chars = 0;
651
- let bytes = 0;
652
- const measuredCount = Math.min(messages.length, MAX_REPORTED_MESSAGES);
653
- for (let i = 0; i < measuredCount; i++) {
654
- const message = messages[i];
655
- const size = messageTextSize(message?.content, limits);
656
- chars = Math.min(limits.maxChars, chars + size.chars);
657
- bytes = Math.min(limits.maxBytes, bytes + size.bytes);
658
- if (chars === limits.maxChars || bytes === limits.maxBytes)
659
- break;
660
- }
661
- return {
662
- chars,
663
- bytes,
664
- capped: chars >= limits.maxChars || bytes >= limits.maxBytes,
665
- };
666
- }
667
- /** Size of an injected payload, bounded for reporting. */
668
- function measureInjectedMessages(messages) {
669
- return measureMessages(messages, INJECTED_LIMITS);
670
- }
671
- /**
672
- * Size of the transcript's own growth, bounded far higher. A routine tool
673
- * result is an order of magnitude past the injection cap, and measuring it
674
- * through that cap made `partial-eviction` near-unreachable (#1071 review
675
- * round 1, F2).
676
- */
677
- function measureTranscriptGrowth(messages) {
678
- return measureMessages(messages, TRANSCRIPT_LIMITS);
679
- }
680
- function sessionKey(sessionId) {
681
- return sessionId?.trim() ? sessionId.trim() : NO_SESSION_KEY;
682
- }
683
- /**
684
- * A stable host session id is the only safe cross-event identity. When it is
685
- * absent, keep primary and concurrent-secondary observations in separate
686
- * buckets and let classification fail closed instead of allowing a secondary
687
- * to overwrite the primary's baseline.
688
- */
689
- function attributionKey(sessionId, sessionRole) {
690
- const key = sessionKey(sessionId);
691
- if (key !== NO_SESSION_KEY)
692
- return key;
693
- return `${sessionRole ?? "unknown"}:${key}`;
694
- }
695
- /**
696
- * Log one bounded request-side observation for every `context` call. This is
697
- * deliberately a separate phase from `cache_prefix_break`: it describes the
698
- * messages pi-lens saw and returned from its own context handler, not the final
699
- * provider request after other context handlers and not whether a provider
700
- * reused or missed a prompt cache. `observationId` is local to this process; the
701
- * host currently exposes no request id on ContextEvent/MessageEndEvent. A
702
- * RuntimeCoordinator turn is process-global, so it is explicitly scoped as
703
- * such and is omitted for concurrent secondary sessions.
704
- */
705
- export function observeCacheContext(args) {
706
- try {
707
- const existingMessages = args.existingMessages ?? [];
708
- const resultMessages = args.resultMessages ?? existingMessages;
709
- // Drop empty slices before deriving anything: a source that contributed
710
- // no message is not a contributor, and listing it would overstate the
711
- // payload's provenance.
712
- const injectionSlices = (args.injectionSlices ?? []).filter((slice) => slice.messages.length > 0);
713
- const injectedMessages = injectionSlices.flatMap((slice) => slice.messages);
714
- const placement = args.placement ?? "none";
715
- const beforeSequence = hashMessageSequence(existingMessages);
716
- const afterSequence = hashMessageSequence(resultMessages);
717
- const sizes = measureInjectedMessages(injectedMessages);
718
- // Per-source split of a mixed payload (#1071 AC 2). The old record named
719
- // which sources fired but attributed cost by CALL, so a turn carrying
720
- // turn-findings plus an agent nudge was one undivided number.
721
- const sourceBreakdown = injectionSlices.map((slice) => {
722
- const sliceSize = measureInjectedMessages(slice.messages);
723
- return {
724
- source: slice.source,
725
- messageCount: Math.min(slice.messages.length, MAX_REPORTED_MESSAGES),
726
- chars: sliceSize.chars,
727
- bytes: sliceSize.bytes,
728
- estimatedTokens: estimateTokens(sliceSize.chars),
729
- countsCapped: sliceSize.capped,
730
- };
731
- });
732
- const state = attributionFor(attributionKey(args.sessionId, args.sessionRole));
733
- for (const slice of injectionSlices) {
734
- const key = sourceKey(slice.source);
735
- const bytes = measureInjectedMessages(slice.messages).bytes;
736
- state.injectedBytes[key] += bytes;
737
- for (const message of slice.messages) {
738
- for (const identity of findingIdentities(typeof message.content === "string" ? message.content : "")) {
739
- if (state.findingIdentities.has(identity)) {
740
- state.injectedFindingsRepeated += 1;
741
- continue;
742
- }
743
- if (state.findingIdentities.size >= MAX_FINDING_IDENTITIES) {
744
- if (!state.findingIdentityCapRecorded) {
745
- state.findingIdentityCapRecorded = true;
746
- logLatency({
747
- type: "phase",
748
- filePath: "<pi-lens>",
749
- phase: "injected_finding_identity_cap",
750
- durationMs: 0,
751
- metadata: { cap: MAX_FINDING_IDENTITIES },
752
- });
753
- }
754
- continue;
755
- }
756
- state.findingIdentities.add(identity);
757
- }
758
- }
759
- }
760
- const messageCountCapped = existingMessages.length > MAX_REPORTED_MESSAGES ||
761
- resultMessages.length > MAX_REPORTED_MESSAGES;
762
- recordContextAttribution(attributionKey(args.sessionId, args.sessionRole), existingMessages, sizes);
763
- state.sequenceHashTruncatedSinceLastUsage ||=
764
- beforeSequence.truncated ||
765
- beforeSequence.contentTruncated ||
766
- afterSequence.truncated ||
767
- afterSequence.contentTruncated;
768
- state.requestEvidenceIncompleteSinceLastUsage ||=
769
- beforeSequence.incomplete || afterSequence.incomplete;
770
- logLatency({
771
- type: "phase",
772
- filePath: "<pi-lens>",
773
- phase: "cache_context",
774
- durationMs: 0,
775
- metadata: {
776
- version: 1,
777
- observedStage: "pi-lens-context-handler",
778
- observationId: `ctx-${(++contextObservationCounter).toString(36)}`,
779
- sessionId: sessionKey(args.sessionId),
780
- sessionRole: args.sessionRole,
781
- ...(args.sessionRole === "concurrent-secondary"
782
- ? { turnScope: SECONDARY_TURN_SCOPE }
783
- : { turnIndex: args.turnIndex, turnScope: PROCESS_TURN_SCOPE }),
784
- injectionEnabled: args.injectionEnabled,
785
- injectionSources: sourceBreakdown.map((entry) => entry.source),
786
- injectionSourceBreakdown: sourceBreakdown,
787
- injectionOccurred: injectedMessages.length > 0,
788
- injectedMessageCount: Math.min(injectedMessages.length, MAX_REPORTED_MESSAGES),
789
- injectedMessageCountCapped: injectedMessages.length > MAX_REPORTED_MESSAGES,
790
- injectedChars: sizes.chars,
791
- injectedBytes: sizes.bytes,
792
- injectedBytesBySource: Object.fromEntries(sourceBreakdown.map((entry) => [
793
- sourceKey(entry.source),
794
- entry.bytes,
795
- ])),
796
- injectedEstimatedTokens: estimateTokens(sizes.chars),
797
- injectedTokenBasis: "chars-per-token-4-estimate-not-provider-measured",
798
- injectedCountsCapped: sizes.capped,
799
- existingMessageCount: Math.min(existingMessages.length, MAX_REPORTED_MESSAGES),
800
- resultMessageCount: Math.min(resultMessages.length, MAX_REPORTED_MESSAGES),
801
- messageCountCapped,
802
- placement,
803
- beforeSequenceHash: beforeSequence.hash,
804
- afterSequenceHash: afterSequence.hash,
805
- sequenceHashTruncated: beforeSequence.truncated ||
806
- afterSequence.truncated ||
807
- beforeSequence.contentTruncated ||
808
- afterSequence.contentTruncated,
809
- sequenceMessageCountTruncated: beforeSequence.truncated || afterSequence.truncated,
810
- sequenceContentHashTruncated: beforeSequence.contentTruncated || afterSequence.contentTruncated,
811
- sequenceHashIncomplete: beforeSequence.incomplete || afterSequence.incomplete,
812
- },
813
- });
814
- }
815
- catch (err) {
816
- // The context event still occurred at request time. Preserve that clock but
817
- // fail the evidence closed so a later usage row cannot infer TTL/eviction
818
- // from an observation whose hashing/measurement never completed.
819
- try {
820
- const state = attributionFor(attributionKey(args.sessionId, args.sessionRole));
821
- state.lastContextAtMs = Date.now();
822
- state.requestEvidenceIncompleteSinceLastUsage = true;
823
- }
824
- catch {
825
- // The outer contract is no-throw; there is no safe attribution key left.
826
- }
827
- args.dbg?.(`cache-context: failed to log context observation: ${err}`);
828
- }
829
- }
830
- /**
831
- * Part 1 — log one `cache_usage` record for an assistant `message_end` that
832
- * carries a `usage`. Provider/model come straight off the message itself
833
- * (`AssistantMessage.provider` / `.model` in pi-ai) — no dependency on the
834
- * runtime telemetry identity. Skips silently (no record) when the message is
835
- * not an assistant message or has no usage; never logs a zeros-only record for
836
- * a message that simply lacks usage.
837
- */
838
- export function logCacheUsage(message, dbg, context) {
839
- try {
840
- if (!message || typeof message !== "object")
841
- return;
842
- const msg = message;
843
- // Only assistant messages carry LLM usage; tool-result / user messages
844
- // (and unknown custom AgentMessage variants) are skipped.
845
- if (msg.role !== "assistant")
846
- return;
847
- const usage = msg.usage;
848
- if (!usage || typeof usage !== "object")
849
- return;
850
- // SAFETY: `usage` is verified non-null object above; widening to an
851
- // indexable record is only so the numeric-evidence readers can probe
852
- // each field defensively. Every read re-validates its own type.
853
- const usageRecord = usage;
854
- // #1071: attribute the shortfall in-process, from state this module already
855
- // keeps, so nothing re-reads latency.log.
856
- const stateKey = attributionKey(context?.sessionId, context?.sessionRole);
857
- const state = attributionFor(stateKey);
858
- const nowMs = Date.now();
859
- const gap = resolveInterTurnGap(state, nowMs);
860
- const interTurnGapMs = gap.gapMs;
861
- const ttlMs = getProviderCacheTtlMs();
862
- const inputEvidence = readNumericEvidence(usageRecord, "input");
863
- const outputEvidence = readNumericEvidence(usageRecord, "output");
864
- const cacheReadEvidence = readNumericEvidence(usageRecord, "cacheRead");
865
- const cacheWriteEvidence = readNumericEvidence(usageRecord, "cacheWrite");
866
- let costEvidence;
867
- try {
868
- const cost = usageRecord.cost;
869
- costEvidence =
870
- cost === undefined
871
- ? { status: "absent" }
872
- : cost && typeof cost === "object"
873
- ? readNumericEvidence(cost, "total")
874
- : { status: "malformed" };
875
- }
876
- catch {
877
- costEvidence = { status: "malformed" };
878
- }
879
- const usageEvidenceFields = [
880
- ["input", inputEvidence],
881
- ["output", outputEvidence],
882
- ["cacheRead", cacheReadEvidence],
883
- ["cacheWrite", cacheWriteEvidence],
884
- ["cost.total", costEvidence],
885
- ];
886
- const malformedProviderUsageFields = usageEvidenceFields
887
- .filter(([, evidence]) => evidence.status === "malformed")
888
- .map(([field]) => field);
889
- const providerUsageMalformed = malformedProviderUsageFields.length > 0;
890
- const cacheRead = cacheReadEvidence.value;
891
- const priorCacheReadValue = readableTokenCount(state.lastCacheRead);
892
- // SAFETY: `msg` passed the AssistantMessageLike role check above; the
893
- // record view backs only the guarded identity-field probes below, each
894
- // re-validated by `identityEvidence` at its own boundary.
895
- const messageRecord = msg;
896
- const safeMessageField = (key) => {
897
- try {
898
- return identityEvidence(messageRecord[key]);
899
- }
900
- catch {
901
- return { status: "unavailable" };
902
- }
903
- };
904
- const currentProvider = safeMessageField("provider");
905
- const responseModel = safeMessageField("responseModel");
906
- const currentModel = responseModel.hash !== undefined
907
- ? responseModel
908
- : safeMessageField("model");
909
- const modelProviderEvidenceAvailable = Boolean(currentProvider.hash &&
910
- currentModel.hash &&
911
- state.lastProviderIdentityHash &&
912
- state.lastModelIdentityHash);
913
- const modelProviderChanged = Boolean(modelProviderEvidenceAvailable &&
914
- (currentProvider.hash !== state.lastProviderIdentityHash ||
915
- currentModel.hash !== state.lastModelIdentityHash));
916
- const estimatedNewTokens = estimateTokens(state.injectedCharsSinceLastUsage +
917
- state.newTranscriptCharsSinceLastUsage);
918
- const verdict = classifyCacheMiss({
919
- cacheRead,
920
- // Missing/malformed input cannot prove fresh-input pressure. The explicit
921
- // malformed gate below also keeps every heuristic fail-closed.
922
- input: inputEvidence.value ?? 0,
923
- priorCacheRead: priorCacheReadValue,
924
- interTurnGapMs,
925
- gapBasis: gap.basis,
926
- ttlMs,
927
- prefixBroke: state.prefixBrokeSinceLastUsage,
928
- prefixStable: state.prefixStableSinceLastUsage,
929
- sequenceHashTruncated: state.sequenceHashTruncatedSinceLastUsage,
930
- requestEvidenceIncomplete: state.requestEvidenceIncompleteSinceLastUsage,
931
- stableSessionIdentity: sessionKey(context?.sessionId) !== NO_SESSION_KEY,
932
- modelProviderChanged,
933
- modelProviderEvidenceAvailable,
934
- providerUsageMalformed,
935
- estimatedNewTokens,
936
- attributionCharsCapped: state.attributionCharsCapped,
937
- });
938
- const unknownReason = providerUsageMalformed
939
- ? "malformed-provider-usage"
940
- : cacheRead === undefined
941
- ? "cache-read-unavailable"
942
- : priorCacheReadValue === undefined && cacheRead === 0
943
- ? "no-prior-sample"
944
- : verdict?.unknownReason;
945
- recordCacheUsageSummary({
946
- state,
947
- cacheRead,
948
- priorCacheRead: priorCacheReadValue,
949
- verdict,
950
- unknownReason,
951
- });
952
- const priorCacheRead = priorCacheReadValue ?? null;
953
- const injectedCharsSinceLastTurn = state.injectedCharsSinceLastUsage;
954
- const newTranscriptCharsSinceLastTurn = state.newTranscriptCharsSinceLastUsage;
955
- const attributionCharsCapped = state.attributionCharsCapped;
956
- const injectedBytes = {
957
- ...state.injectedBytes,
958
- turnEndAdvisory: state.turnEndAdvisoryBytes + state.injectedBytes.turnEndAdvisory,
959
- };
960
- const injectedFindingsRepeated = state.injectedFindingsRepeated;
961
- const toolResultBytes = state.toolResultBytes;
962
- const toolResultsTruncated = state.toolResultsTruncated;
963
- // This record is the turn boundary: reset the per-turn accumulators and
964
- // re-arm the prefix-break flag so the next verdict describes the NEXT gap.
965
- state.lastUsageAtMs = nowMs;
966
- // A record whose `cacheRead` is absent or non-finite carries no baseline.
967
- // Clear the stored one rather than keeping it: the next turn's gap would be
968
- // one turn long while its baseline was two turns old, and a verdict built
969
- // on that mismatch is worse than no verdict (#1071 review round 1, F4).
970
- state.lastCacheRead = cacheRead;
971
- state.lastProviderIdentityHash = currentProvider.hash;
972
- state.lastModelIdentityHash = currentModel.hash;
973
- state.prefixBrokeSinceLastUsage = false;
974
- state.prefixStableSinceLastUsage = false;
975
- state.sequenceHashTruncatedSinceLastUsage = false;
976
- state.requestEvidenceIncompleteSinceLastUsage = false;
977
- state.injectedCharsSinceLastUsage = 0;
978
- state.newTranscriptCharsSinceLastUsage = 0;
979
- state.attributionCharsCapped = false;
980
- state.injectedBytes = emptyInjectedBytes();
981
- state.injectedFindingsRepeated = 0;
982
- state.turnEndAdvisoryBytes = 0;
983
- state.toolResultBytes = 0;
984
- state.toolResultsTruncated = 0;
985
- // Clear the request stamp too: the next turn measures from ITS request, and
986
- // a turn whose `context` call pi-lens never saw must fall back rather than
987
- // reuse this one.
988
- state.lastContextAtMs = undefined;
989
- logLatency({
990
- type: "phase",
991
- filePath: "<pi-lens>",
992
- phase: "cache_usage",
993
- durationMs: 0,
994
- metadata: {
995
- provider: currentProvider.display,
996
- model: currentModel.display,
997
- providerIdentityHash: currentProvider.hash,
998
- modelIdentityHash: currentModel.hash,
999
- providerIdentityStatus: currentProvider.status,
1000
- modelIdentityStatus: currentModel.status,
1001
- providerIdentityTruncated: currentProvider.status === "truncated",
1002
- modelIdentityTruncated: currentModel.status === "truncated",
1003
- cacheRead: cacheReadEvidence.value ?? null,
1004
- cacheWrite: cacheWriteEvidence.value ?? null,
1005
- input: inputEvidence.value ?? null,
1006
- output: outputEvidence.value ?? null,
1007
- // `Usage.cost` is a breakdown object; the total is the headline number.
1008
- cost: costEvidence.value ?? null,
1009
- providerUsageMalformedFields: malformedProviderUsageFields,
1010
- // Idle milliseconds before this turn's request, or null for the first
1011
- // record in the session. This is the field the 2026-08-21
1012
- // investigation had to reconstruct by hand-joining timestamps.
1013
- interTurnGapMs,
1014
- gapBasis: gap.basis,
1015
- // null means "nothing to explain", not "cause unknown"; `unknown` is
1016
- // the explicit no-local-explanation verdict.
1017
- cacheMissCause: verdict?.cause ?? null,
1018
- cacheMissKind: verdict?.kind ?? null,
1019
- cacheMissUnknownReason: unknownReason ?? null,
1020
- modelProviderChanged,
1021
- cacheTtlThresholdMs: ttlMs,
1022
- priorCacheRead,
1023
- injectedCharsSinceLastTurn,
1024
- newTranscriptCharsSinceLastTurn,
1025
- attributionCharsCapped,
1026
- injectedBytes,
1027
- injectedFindingsRepeated,
1028
- // Delivered tool-result aggregation over the turn (#2800 item 7):
1029
- // the sum of each delivered footer's bytes= figure and the count
1030
- // of results whose bound fired.
1031
- toolResultBytes,
1032
- toolResultsTruncated,
1033
- ...(context
1034
- ? {
1035
- // MessageEndEvent has no request/context id in the host API. These
1036
- // fields permit session correlation without inventing an exact
1037
- // provider-request linkage. The process-global turn is omitted
1038
- // for a concurrent secondary session.
1039
- sessionId: sessionKey(context.sessionId),
1040
- ...(context.sessionRole === "concurrent-secondary"
1041
- ? { turnScope: SECONDARY_TURN_SCOPE }
1042
- : {
1043
- turnIndex: context.turnIndex,
1044
- turnScope: PROCESS_TURN_SCOPE,
1045
- }),
1046
- contextCorrelation: context.sessionId
1047
- ? "session-only-no-request-id"
1048
- : "no-stable-session-id",
1049
- }
1050
- : {}),
1051
- },
1052
- });
1053
- }
1054
- catch (err) {
1055
- dbg?.(`cache-usage: failed to log message_end usage: ${err}`);
1056
- }
1057
- }
1058
- /**
1059
- * Content hash of the first transcript message. Stable for identical content
1060
- * (role + content are serialized in a fixed order), so a changing hash means
1061
- * `messages[0]` actually changed byte-for-byte.
1062
- */
1063
- function hashFirstMessage(first) {
1064
- // Keep the original full local hash semantics for the existing
1065
- // `cache_prefix_break` signal. The new `cache_context` hashes above are the
1066
- // bounded hashes; this signal must not silently miss a suffix-only change.
1067
- const serialized = JSON.stringify({
1068
- role: first.role,
1069
- content: first.content,
1070
- });
1071
- return createHash("sha256").update(serialized).digest("hex");
1072
- }
1073
- /**
1074
- * Per-session baseline hash of `messages[0]`, keyed by the STABLE pi session id
1075
- * (`ctx.sessionManager.getSessionId()`). A single module-scoped var was wrong:
1076
- * in ONE process, multiple logical conversations touch this module, and they
1077
- * must not share a baseline —
1078
- * - new / fork / a concurrent in-process subagent (#473) is a DIFFERENT id →
1079
- * its OWN independent baseline, never compared against another id's (else a
1080
- * benign session boundary logs a spurious `cache_prefix_break`, and a
1081
- * concurrent subagent + its parent stomp each other's baseline, each
1082
- * emitting a false positive — fatal for a signal whose value is trust);
1083
- * - an IN-PROCESS reload / resume reuses the SAME id → the baseline is still in
1084
- * this map, so a genuine break is caught (no blinding reset). NOTE: a full
1085
- * process restart (quit → `pi --session <id>`) starts a NEW process with an
1086
- * empty map, so the first post-restart `context` re-anchors a fresh baseline
1087
- * rather than comparing across the restart. That's acceptable here — this is a
1088
- * pure observability signal (at worst a missed `cache_prefix_break` log on the
1089
- * first post-restart turn, never a user-facing action) — unlike genuine
1090
- * session state (read guard #1041, widget #190) which IS rehydrated from the
1091
- * sidecar.
1092
- *
1093
- * Bounded as insertion-ordered FIFO (evict oldest-inserted past the cap,
1094
- * refreshed on every WRITE by {@link recordSessionHash}'s delete+set — a
1095
- * plain read never reorders) so a long-lived process cycling through many
1096
- * sessions can't grow this unbounded. Shares {@link MAX_TRACKED_SESSIONS}
1097
- * with `attributionBySession` above.
1098
- */
1099
- const prefixHashBySession = new BoundedFifoMap(MAX_TRACKED_SESSIONS);
1100
- /**
1101
- * Reported key used when no session id is available (undefined/empty). Internal
1102
- * attribution additionally separates primary and concurrent-secondary roles;
1103
- * neither role may overwrite the other's baseline when stable identity is
1104
- * absent.
1105
- */
1106
- const NO_SESSION_KEY = "<no-session>";
1107
- /**
1108
- * Store `hash` for `key`, refreshing its LRU recency (re-insert moves it to the
1109
- * newest position since `Map` preserves insertion order) and evicting the
1110
- * oldest-inserted entries once the cap is exceeded.
1111
- */
1112
- function recordSessionHash(key, hash) {
1113
- prefixHashBySession.delete(key);
1114
- prefixHashBySession.set(key, hash);
1115
- }
1116
- /**
1117
- * Part 2 — observe `messages[0]` stability turn-over-turn, keyed by session id.
1118
- * Logs a baseline the first time it sees a non-empty transcript FOR A GIVEN
1119
- * session id, then logs a `cache_prefix_break` whenever that same session's
1120
- * first-message hash changes. Pure observation: it never inspects or mutates
1121
- * anything but its own per-session hash map, and never throws.
1122
- *
1123
- * `sessionId` should be pi's STABLE id (`ctx.sessionManager.getSessionId()`),
1124
- * which uniquely identifies the CURRENTLY-firing session: a concurrent
1125
- * in-process subagent runs its own `AgentSession`/`sessionManager`, so its
1126
- * `context` calls carry a DIFFERENT id than the parent's and get their own
1127
- * baseline. (`runtime.telemetrySessionId` cannot be used here: per the #473
1128
- * guard a concurrent secondary skips `updateRuntimeIdentityFromEvent`, so that
1129
- * process-global singleton stays pinned to the PARENT — it would collapse
1130
- * parent and subagent onto one baseline.) If the host does NOT supply a stable
1131
- * id, primary and secondary roles still use separate fallback buckets, but
1132
- * multiple same-role sessions cannot be correlated. Miss attribution therefore
1133
- * fails closed with `request-correlation-unavailable`.
1134
- *
1135
- * Does nothing on an empty transcript (nothing to anchor a prefix to yet).
1136
- */
1137
- export function observeCachePrefix(messages, turnIndex, sessionId, sessionRole, dbg) {
1138
- try {
1139
- if (!messages || messages.length === 0)
1140
- return "empty";
1141
- const first = messages[0];
1142
- if (!first || typeof first !== "object")
1143
- return "empty";
1144
- const key = attributionKey(sessionId, sessionRole);
1145
- const reportedSessionId = sessionKey(sessionId);
1146
- const currentHash = hashFirstMessage(first);
1147
- const previousHash = prefixHashBySession.get(key);
1148
- const state = attributionFor(key);
1149
- if (previousHash === undefined) {
1150
- // Baseline: record this session's starting prefix so a later break has a
1151
- // reference point in the log. `previousHash: null` marks the baseline.
1152
- recordSessionHash(key, currentHash);
1153
- state.prefixStableSinceLastUsage = true;
1154
- logLatency({
1155
- type: "phase",
1156
- filePath: "<pi-lens>",
1157
- phase: "cache_prefix_break",
1158
- durationMs: 0,
1159
- metadata: {
1160
- ...(sessionRole === "concurrent-secondary"
1161
- ? { turnScope: SECONDARY_TURN_SCOPE }
1162
- : { turnIndex, turnScope: PROCESS_TURN_SCOPE }),
1163
- previousHash: null,
1164
- currentHash,
1165
- baseline: true,
1166
- sessionId: reportedSessionId,
1167
- sessionRole,
1168
- },
1169
- });
1170
- return "baseline";
1171
- }
1172
- if (currentHash !== previousHash) {
1173
- // #1071: arm the direct-cause flag the next `cache_usage` verdict reads.
1174
- // A locally observed prefix change outranks the timing heuristics.
1175
- state.prefixBrokeSinceLastUsage = true;
1176
- state.prefixStableSinceLastUsage = false;
1177
- logLatency({
1178
- type: "phase",
1179
- filePath: "<pi-lens>",
1180
- phase: "cache_prefix_break",
1181
- durationMs: 0,
1182
- metadata: {
1183
- ...(sessionRole === "concurrent-secondary"
1184
- ? { turnScope: SECONDARY_TURN_SCOPE }
1185
- : { turnIndex, turnScope: PROCESS_TURN_SCOPE }),
1186
- previousHash,
1187
- currentHash,
1188
- sessionId: reportedSessionId,
1189
- sessionRole,
1190
- },
1191
- });
1192
- }
1193
- if (currentHash === previousHash) {
1194
- state.prefixStableSinceLastUsage = true;
1195
- }
1196
- // Refresh recency (and update the stored hash after a break) so an active
1197
- // session stays warm in the LRU and isn't evicted while still in use.
1198
- recordSessionHash(key, currentHash);
1199
- return currentHash === previousHash ? "unchanged" : "changed";
1200
- }
1201
- catch (err) {
1202
- dbg?.(`cache-prefix: failed to observe messages[0]: ${err}`);
1203
- return "empty";
1204
- }
1205
- }
1206
- /**
1207
- * Drop a single session's prefix baseline and attribution state. Called from
1208
- * both role-specific `session_shutdown` paths so an ended conversation is
1209
- * reclaimed promptly rather than only when the LRU evicts it. Idempotent and
1210
- * never throws.
1211
- */
1212
- export function clearCachePrefixSession(sessionId, sessionRole) {
1213
- const key = attributionKey(sessionId, sessionRole);
1214
- prefixHashBySession.delete(key);
1215
- // The miss-attribution state has the same lifetime and the same reason to be
1216
- // reclaimed at session end; leaving it would let a reused session id inherit
1217
- // a stale gap baseline and a stale prefix-break flag.
1218
- attributionBySession.delete(key);
1219
- }
1220
- /** Record the exact quiet-window summary content handed to pi.sendMessage. */
1221
- export function recordTurnEndAdvisoryBytes(sessionId, bytes, sessionRole = "primary") {
1222
- const state = attributionFor(attributionKey(sessionId, sessionRole));
1223
- state.turnEndAdvisoryBytes = Math.min(MAX_INJECTED_BYTES, state.turnEndAdvisoryBytes + Math.max(0, bytes));
1224
- }
1225
- /**
1226
- * Fold one delivered tool result into the per-turn aggregation the
1227
- * `cache_usage` row reports as `toolResultBytes` / `toolResultsTruncated`
1228
- * (#2800 item 7). `bytes` is the delivered payload's UTF-8 byte count as
1229
- * stamped in the result's own footer, and `truncated` is the footer's
1230
- * truncated flag. Called from each host adapter's delivery seam; the row is
1231
- * emitted by `logCacheUsage`, which resets both figures at the turn boundary.
1232
- * The byte sum saturates at the attribution bound so the row stays bounded.
1233
- */
1234
- export function recordToolResultDelivery(args) {
1235
- const state = attributionFor(attributionKey(args.sessionId, args.sessionRole));
1236
- const bytes = Number.isFinite(args.bytes)
1237
- ? Math.max(0, Math.floor(args.bytes))
1238
- : 0;
1239
- state.toolResultBytes = Math.min(MAX_ATTRIBUTION_BYTES, state.toolResultBytes + bytes);
1240
- if (args.truncated === true)
1241
- state.toolResultsTruncated += 1;
1242
- }
1243
- /**
1244
- * Emit one bounded session summary and retire its attribution state. The
1245
- * summary contains fixed-key counters only; it never serializes transcript or
1246
- * context content. A session with no usage records emits nothing.
1247
- */
1248
- export function emitCacheUsageSummaryAtSessionEnd(sessionId, sessionRole) {
1249
- const key = attributionKey(sessionId, sessionRole);
1250
- const state = attributionBySession.get(key);
1251
- if (!state || state.summary.usageRecords === 0)
1252
- return;
1253
- logLatency({
1254
- type: "phase",
1255
- filePath: "<pi-lens>",
1256
- phase: "cache_usage_summary",
1257
- durationMs: 0,
1258
- metadata: {
1259
- version: 1,
1260
- sessionId: sessionKey(sessionId),
1261
- sessionRole,
1262
- usageRecords: state.summary.usageRecords,
1263
- cacheHits: state.summary.cacheHits,
1264
- missObservations: state.summary.missObservations,
1265
- cacheMissCauses: { ...state.summary.cacheMissCauses },
1266
- unknownEvidenceReasons: {
1267
- ...state.summary.unknownEvidenceReasons,
1268
- },
1269
- },
1270
- });
1271
- attributionBySession.delete(key);
1272
- }
1273
- /**
1274
- * Clear all per-session prefix hashes and miss-attribution state. For tests and
1275
- * session boundaries. Both maps are cleared together so a test can never start
1276
- * with a half-reset session.
1277
- */
1278
- export function resetCachePrefixObservation() {
1279
- prefixHashBySession.clear();
1280
- attributionBySession.clear();
1281
- }
1282
- export function resetCacheFindingIdentitiesSession(sessionId, sessionRole) {
1283
- const state = attributionBySession.get(attributionKey(sessionId, sessionRole));
1284
- if (!state)
1285
- return;
1286
- state.findingIdentities.clear();
1287
- state.findingIdentityCapRecorded = false;
1288
- }
1289
- export function _attributionBySessionHasForTests(key) {
1290
- return attributionBySession.has(key);
1291
- }
1292
- export function _prefixHashBySessionHasForTests(key) {
1293
- return prefixHashBySession.has(key);
1294
- }
1295
- /** #2442 test-only: drive attributionFor's fetch-or-create touch directly
1296
- * (every call refreshes LRU recency, matching production — see
1297
- * attributionFor's own doc comment). */
1298
- export function _touchAttributionForTests(key) {
1299
- attributionFor(key);
1300
- }
1301
- /** #2442 test-only: drive recordSessionHash's write-refresh directly. */
1302
- export function _recordSessionHashForTests(key, hash) {
1303
- recordSessionHash(key, hash);
1304
- }
1305
- /**
1306
- * #2442 test-only: the exact `prefixHashBySession.get(key)` that
1307
- * `observeCachePrefix` performs to fetch a session's previous hash. A
1308
- * `.has()` reorders nothing on either bounded class, so only a real `get`
1309
- * can pin FIFO-vs-LRU behavior (#2442 review F4).
1310
- */
1311
- export function _prefixHashBySessionGetForTests(key) {
1312
- return prefixHashBySession.get(key);
1313
- }