pi-lens 4.3.0 → 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 (650) hide show
  1. package/CHANGELOG.md +1064 -0
  2. package/README.md +115 -25
  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 +16456 -8335
  125. package/dist/mcp/analyze-cli.js +186 -232
  126. package/dist/mcp/cli.js +137 -98
  127. package/dist/mcp/server.js +22589 -1573
  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/agent-guide.md +13 -4
  133. package/docs/agent-tools.md +42 -0
  134. package/docs/ast-grep_rules_catalog.md +3 -2
  135. package/docs/configuration.md +20 -1
  136. package/docs/environment-variables.md +52 -2
  137. package/docs/features.md +8 -4
  138. package/docs/globalconfig.md +1 -0
  139. package/docs/io-bridge-v2-migration.md +94 -0
  140. package/docs/lsp-capability-matrix.md +36 -4
  141. package/docs/lsp-idle-eviction.md +124 -0
  142. package/docs/mcp.md +21 -5
  143. package/docs/merge-queue-rollout.md +77 -0
  144. package/docs/pi-lens-fixer.md +156 -88
  145. package/docs/pi-lens-investigator.md +74 -26
  146. package/docs/pi-lens-merge-policy.md +694 -0
  147. package/docs/pi-lens-monitor.md +73 -7
  148. package/docs/pi-lens-retro.md +6 -4
  149. package/docs/pi-lens-reviewer.md +188 -48
  150. package/docs/pi-lens-subagent.md +246 -45
  151. package/docs/pi-lens-warden.md +18 -7
  152. package/docs/public-api-stability.md +55 -0
  153. package/docs/release-qa-baseline.md +84 -17
  154. package/docs/rfcs/3654-unified-io-bridge-v2.md +316 -0
  155. package/docs/servercapabilities.md +53 -49
  156. package/docs/settings.md +1 -0
  157. package/docs/usage.md +5 -1
  158. package/grammars/tree-sitter-bash.wasm +0 -0
  159. package/grammars/tree-sitter-bash.wasm.json +3 -3
  160. package/package.json +19 -7
  161. package/rules/ast-grep-rules/rule-tests/advisory-registry-subset-test.yml +41 -0
  162. package/rules/ast-grep-rules/rules/advisory-registry-subset.yml +50 -0
  163. package/scripts/analyze-pi-lens-logs.mjs +1275 -62
  164. package/scripts/download-grammars.js +5 -0
  165. package/scripts/grammars.lock.json +6 -1
  166. package/scripts/install-selftest.mjs +33 -34
  167. package/scripts/lib/host-provided-deps.mjs +13 -4
  168. package/scripts/lib/web-tree-sitter-dir.mjs +18 -0
  169. package/dist/clients/actionable-warnings-logger.js +0 -35
  170. package/dist/clients/actionable-warnings.js +0 -1610
  171. package/dist/clients/advisory-provenance.js +0 -593
  172. package/dist/clients/agent-behavior-client.js +0 -147
  173. package/dist/clients/agent-nudge.js +0 -325
  174. package/dist/clients/analysed-root.js +0 -1
  175. package/dist/clients/ast-grep-client.js +0 -731
  176. package/dist/clients/ast-grep-rule-manager.js +0 -146
  177. package/dist/clients/ast-grep-tool-logger.js +0 -118
  178. package/dist/clients/ast-grep-types.js +0 -10
  179. package/dist/clients/ast-grep-yaml-synth.js +0 -154
  180. package/dist/clients/atomic-write-staging.js +0 -75
  181. package/dist/clients/atomic-write.js +0 -189
  182. package/dist/clients/availability-probe-flight.js +0 -12
  183. package/dist/clients/bash-file-access.js +0 -1056
  184. package/dist/clients/biome-client.js +0 -357
  185. package/dist/clients/blocker-freshness.js +0 -837
  186. package/dist/clients/blocker-past-eof.js +0 -129
  187. package/dist/clients/bootstrap.js +0 -569
  188. package/dist/clients/bounded-cache.js +0 -190
  189. package/dist/clients/bounded-pid-file-lock.js +0 -202
  190. package/dist/clients/bounded-telemetry.js +0 -295
  191. package/dist/clients/build-identity.js +0 -95
  192. package/dist/clients/bundled-resource-health.js +0 -113
  193. package/dist/clients/bus-events-logger.js +0 -105
  194. package/dist/clients/bus-publish.js +0 -171
  195. package/dist/clients/cache/rule-cache.js +0 -190
  196. package/dist/clients/cache-manager.js +0 -524
  197. package/dist/clients/cache-observability.js +0 -1313
  198. package/dist/clients/call-graph.js +0 -852
  199. package/dist/clients/cargo-manifest.js +0 -422
  200. package/dist/clients/cascade-budget.js +0 -196
  201. package/dist/clients/cascade-format.js +0 -315
  202. package/dist/clients/cascade-logger.js +0 -31
  203. package/dist/clients/cascade-types.js +0 -9
  204. package/dist/clients/child-unref.js +0 -124
  205. package/dist/clients/code-quality-warnings.js +0 -286
  206. package/dist/clients/codebase-model.js +0 -173
  207. package/dist/clients/collateral-test-role.js +0 -40
  208. package/dist/clients/complexity-client.js +0 -462
  209. package/dist/clients/config-core/deny.js +0 -221
  210. package/dist/clients/config-core/index.js +0 -50
  211. package/dist/clients/config-core/merge.js +0 -357
  212. package/dist/clients/config-core/normalize.js +0 -340
  213. package/dist/clients/config-core/process-spec.js +0 -248
  214. package/dist/clients/config-core/provenance.js +0 -164
  215. package/dist/clients/config-core/records.js +0 -218
  216. package/dist/clients/config-core/resolve.js +0 -125
  217. package/dist/clients/config-core/safe-object.js +0 -78
  218. package/dist/clients/config-core/schema.js +0 -165
  219. package/dist/clients/config-diagnostic-codes.js +0 -285
  220. package/dist/clients/config-locations.js +0 -388
  221. package/dist/clients/config-resolve.js +0 -798
  222. package/dist/clients/config-schema.js +0 -251
  223. package/dist/clients/config-warn.js +0 -407
  224. package/dist/clients/console-guard-install.js +0 -26
  225. package/dist/clients/cooperative-budget.js +0 -42
  226. package/dist/clients/dead-code-client.js +0 -510
  227. package/dist/clients/dead-code-logger.js +0 -30
  228. package/dist/clients/deadline-utils.js +0 -280
  229. package/dist/clients/debug-handles.js +0 -211
  230. package/dist/clients/debug-heap.js +0 -174
  231. package/dist/clients/deferred-lsp-work.js +0 -106
  232. package/dist/clients/degradation-ledger.js +0 -426
  233. package/dist/clients/demoted-finding-render.js +0 -169
  234. package/dist/clients/dependency-checker.js +0 -885
  235. package/dist/clients/deps/ast-grep-napi.js +0 -22
  236. package/dist/clients/deps/js-yaml.js +0 -9
  237. package/dist/clients/deps/minimatch.js +0 -4
  238. package/dist/clients/deps/pi-tui.js +0 -14
  239. package/dist/clients/deps/typebox.js +0 -14
  240. package/dist/clients/deps/vscode-jsonrpc.js +0 -1
  241. package/dist/clients/deps/web-tree-sitter.js +0 -24
  242. package/dist/clients/diagnostic-dispositions.js +0 -630
  243. package/dist/clients/diagnostic-line-freshness.js +0 -305
  244. package/dist/clients/diagnostic-logger.js +0 -73
  245. package/dist/clients/diagnostic-tracker.js +0 -105
  246. package/dist/clients/diagnostics-publish.js +0 -230
  247. package/dist/clients/dispatch/ast-grep-catalog.js +0 -65
  248. package/dist/clients/dispatch/auxiliary-lsp.js +0 -343
  249. package/dist/clients/dispatch/collect-later-tier.js +0 -35
  250. package/dist/clients/dispatch/diagnostic-taxonomy.js +0 -66
  251. package/dist/clients/dispatch/dispatcher.js +0 -1269
  252. package/dist/clients/dispatch/fact-provider-types.js +0 -1
  253. package/dist/clients/dispatch/fact-rule-runner.js +0 -17
  254. package/dist/clients/dispatch/fact-runner.js +0 -30
  255. package/dist/clients/dispatch/fact-scheduler.js +0 -68
  256. package/dist/clients/dispatch/fact-store.js +0 -377
  257. package/dist/clients/dispatch/facts/comment-facts.js +0 -22
  258. package/dist/clients/dispatch/facts/file-content.js +0 -19
  259. package/dist/clients/dispatch/facts/function-facts.js +0 -348
  260. package/dist/clients/dispatch/facts/import-facts.js +0 -204
  261. package/dist/clients/dispatch/facts/tree-sitter-facts.js +0 -34
  262. package/dist/clients/dispatch/facts/try-catch-facts.js +0 -119
  263. package/dist/clients/dispatch/finding-policy.js +0 -339
  264. package/dist/clients/dispatch/indent-detect.js +0 -417
  265. package/dist/clients/dispatch/inline-suppressions.js +0 -89
  266. package/dist/clients/dispatch/integration.js +0 -2377
  267. package/dist/clients/dispatch/lazy.js +0 -11
  268. package/dist/clients/dispatch/pending-runner-findings.js +0 -87
  269. package/dist/clients/dispatch/plan.js +0 -278
  270. package/dist/clients/dispatch/priorities.js +0 -20
  271. package/dist/clients/dispatch/rule-id-normalize.js +0 -50
  272. package/dist/clients/dispatch/rule-ignores.js +0 -69
  273. package/dist/clients/dispatch/rule-policy.js +0 -135
  274. package/dist/clients/dispatch/rules/async-noise.js +0 -40
  275. package/dist/clients/dispatch/rules/async-unnecessary-wrapper.js +0 -27
  276. package/dist/clients/dispatch/rules/cors-wildcard.js +0 -54
  277. package/dist/clients/dispatch/rules/error-obscuring.js +0 -32
  278. package/dist/clients/dispatch/rules/error-swallowing.js +0 -31
  279. package/dist/clients/dispatch/rules/framework-call-noise.js +0 -67
  280. package/dist/clients/dispatch/rules/high-complexity.js +0 -72
  281. package/dist/clients/dispatch/rules/high-fan-out.js +0 -74
  282. package/dist/clients/dispatch/rules/high-import-coupling.js +0 -37
  283. package/dist/clients/dispatch/rules/missing-error-propagation.js +0 -62
  284. package/dist/clients/dispatch/rules/no-commented-credentials.js +0 -52
  285. package/dist/clients/dispatch/rules/pass-through-wrappers.js +0 -42
  286. package/dist/clients/dispatch/rules/placeholder-comments.js +0 -40
  287. package/dist/clients/dispatch/rules/unsafe-boundary.js +0 -126
  288. package/dist/clients/dispatch/runner-context.js +0 -52
  289. package/dist/clients/dispatch/runners/actionlint.js +0 -111
  290. package/dist/clients/dispatch/runners/ast-grep-napi.js +0 -1196
  291. package/dist/clients/dispatch/runners/biome-check.js +0 -296
  292. package/dist/clients/dispatch/runners/cpp-check.js +0 -219
  293. package/dist/clients/dispatch/runners/credo.js +0 -82
  294. package/dist/clients/dispatch/runners/cue-vet.js +0 -416
  295. package/dist/clients/dispatch/runners/dart-analyze.js +0 -183
  296. package/dist/clients/dispatch/runners/detekt.js +0 -176
  297. package/dist/clients/dispatch/runners/dotnet-build.js +0 -164
  298. package/dist/clients/dispatch/runners/elixir-check.js +0 -195
  299. package/dist/clients/dispatch/runners/eslint.js +0 -137
  300. package/dist/clients/dispatch/runners/fact-rules.js +0 -29
  301. package/dist/clients/dispatch/runners/fish-indent.js +0 -69
  302. package/dist/clients/dispatch/runners/gleam-check.js +0 -167
  303. package/dist/clients/dispatch/runners/go-vet.js +0 -104
  304. package/dist/clients/dispatch/runners/golangci-lint.js +0 -135
  305. package/dist/clients/dispatch/runners/hadolint.js +0 -91
  306. package/dist/clients/dispatch/runners/helm-lint.js +0 -171
  307. package/dist/clients/dispatch/runners/helm-render.js +0 -940
  308. package/dist/clients/dispatch/runners/htmlhint.js +0 -117
  309. package/dist/clients/dispatch/runners/index.js +0 -108
  310. package/dist/clients/dispatch/runners/javac.js +0 -99
  311. package/dist/clients/dispatch/runners/ktlint.js +0 -110
  312. package/dist/clients/dispatch/runners/lsp.js +0 -379
  313. package/dist/clients/dispatch/runners/markdownlint.js +0 -167
  314. package/dist/clients/dispatch/runners/mypy.js +0 -102
  315. package/dist/clients/dispatch/runners/oxlint.js +0 -414
  316. package/dist/clients/dispatch/runners/php-lint.js +0 -85
  317. package/dist/clients/dispatch/runners/phpstan.js +0 -120
  318. package/dist/clients/dispatch/runners/prisma-validate.js +0 -62
  319. package/dist/clients/dispatch/runners/psscriptanalyzer.js +0 -445
  320. package/dist/clients/dispatch/runners/pyright.js +0 -169
  321. package/dist/clients/dispatch/runners/rubocop.js +0 -99
  322. package/dist/clients/dispatch/runners/ruff.js +0 -88
  323. package/dist/clients/dispatch/runners/rust-clippy.js +0 -256
  324. package/dist/clients/dispatch/runners/shellcheck.js +0 -173
  325. package/dist/clients/dispatch/runners/shfmt.js +0 -102
  326. package/dist/clients/dispatch/runners/spellcheck.js +0 -128
  327. package/dist/clients/dispatch/runners/spotbugs.js +0 -259
  328. package/dist/clients/dispatch/runners/sqlfluff.js +0 -183
  329. package/dist/clients/dispatch/runners/stylelint.js +0 -166
  330. package/dist/clients/dispatch/runners/swiftlint.js +0 -163
  331. package/dist/clients/dispatch/runners/taplo.js +0 -174
  332. package/dist/clients/dispatch/runners/terragrunt.js +0 -168
  333. package/dist/clients/dispatch/runners/tflint.js +0 -125
  334. package/dist/clients/dispatch/runners/tree-sitter.js +0 -643
  335. package/dist/clients/dispatch/runners/trivy-config.js +0 -253
  336. package/dist/clients/dispatch/runners/utils/availability-policy.js +0 -496
  337. package/dist/clients/dispatch/runners/utils/candidate-probe.js +0 -90
  338. package/dist/clients/dispatch/runners/utils/diagnostic-parsers.js +0 -95
  339. package/dist/clients/dispatch/runners/utils/lazy-installer.js +0 -274
  340. package/dist/clients/dispatch/runners/utils/runner-helpers.js +0 -1701
  341. package/dist/clients/dispatch/runners/utils/spawn-outcome.js +0 -101
  342. package/dist/clients/dispatch/runners/utils/tool-failure.js +0 -235
  343. package/dist/clients/dispatch/runners/utils/toolchain-availability.js +0 -169
  344. package/dist/clients/dispatch/runners/utils.js +0 -15
  345. package/dist/clients/dispatch/runners/vale.js +0 -128
  346. package/dist/clients/dispatch/runners/yaml-rule-parser.js +0 -242
  347. package/dist/clients/dispatch/runners/yamllint.js +0 -95
  348. package/dist/clients/dispatch/runners/zig-check.js +0 -79
  349. package/dist/clients/dispatch/suppress-writer.js +0 -79
  350. package/dist/clients/dispatch/tool-profile.js +0 -30
  351. package/dist/clients/dispatch/types.js +0 -21
  352. package/dist/clients/dispatch/utils/format-utils.js +0 -45
  353. package/dist/clients/dispatch/utils/lsp-diagnostics.js +0 -35
  354. package/dist/clients/disposition-logger.js +0 -32
  355. package/dist/clients/disposition-publish.js +0 -124
  356. package/dist/clients/durable-store.js +0 -97
  357. package/dist/clients/effective-config.js +0 -415
  358. package/dist/clients/env-utils.js +0 -83
  359. package/dist/clients/error-class.js +0 -23
  360. package/dist/clients/eval-timestamp.js +0 -17
  361. package/dist/clients/event-loop-hold.js +0 -274
  362. package/dist/clients/event-loop-monitor.js +0 -250
  363. package/dist/clients/extension-log.js +0 -504
  364. package/dist/clients/extension-mode.js +0 -73
  365. package/dist/clients/feature-hints.js +0 -103
  366. package/dist/clients/file-kinds.js +0 -412
  367. package/dist/clients/file-role.js +0 -134
  368. package/dist/clients/file-time.js +0 -160
  369. package/dist/clients/file-utils.js +0 -1032
  370. package/dist/clients/finding-delivery-gate.js +0 -494
  371. package/dist/clients/finding-identity.js +0 -88
  372. package/dist/clients/fix-worklog.js +0 -103
  373. package/dist/clients/format-events-publish.js +0 -343
  374. package/dist/clients/format-service.js +0 -222
  375. package/dist/clients/formatters-lazy.js +0 -9
  376. package/dist/clients/formatters.js +0 -2032
  377. package/dist/clients/freshness-cadence.js +0 -17
  378. package/dist/clients/freshness.js +0 -38
  379. package/dist/clients/generated-artifacts.js +0 -394
  380. package/dist/clients/generation-guard.js +0 -215
  381. package/dist/clients/git-guard.js +0 -1136
  382. package/dist/clients/git-tracked-ignore.js +0 -243
  383. package/dist/clients/gitleaks-client.js +0 -509
  384. package/dist/clients/go-client.js +0 -104
  385. package/dist/clients/govulncheck-client.js +0 -605
  386. package/dist/clients/gradle-ktfmt-style.js +0 -348
  387. package/dist/clients/grammar-source.js +0 -465
  388. package/dist/clients/gzip-stage-write.js +0 -135
  389. package/dist/clients/hashline-anchor.js +0 -424
  390. package/dist/clients/hook-budgets.js +0 -76
  391. package/dist/clients/host-edit-normalize.js +0 -140
  392. package/dist/clients/host-ports.js +0 -39
  393. package/dist/clients/indent-retarget.js +0 -154
  394. package/dist/clients/inline-blocker-dispositions.js +0 -186
  395. package/dist/clients/install-diagnostics.js +0 -156
  396. package/dist/clients/installer/index.js +0 -5416
  397. package/dist/clients/installer/managed-tool-refresh-session.js +0 -58
  398. package/dist/clients/installer/managed-tool-refresh.js +0 -783
  399. package/dist/clients/instance-reaper-state.js +0 -7
  400. package/dist/clients/instance-reaper.js +0 -1137
  401. package/dist/clients/instance-registry-lock.js +0 -145
  402. package/dist/clients/instance-registry.js +0 -773
  403. package/dist/clients/jscpd-client.js +0 -378
  404. package/dist/clients/json-cache-read.js +0 -65
  405. package/dist/clients/knip-client.js +0 -788
  406. package/dist/clients/language-policy.js +0 -252
  407. package/dist/clients/language-profile.js +0 -361
  408. package/dist/clients/language-registry.js +0 -603
  409. package/dist/clients/latency-logger.js +0 -727
  410. package/dist/clients/lazy-import.js +0 -21
  411. package/dist/clients/ledger-bounds.js +0 -54
  412. package/dist/clients/lens-config.js +0 -404
  413. package/dist/clients/lens-engine.js +0 -358
  414. package/dist/clients/lens-events.js +0 -125
  415. package/dist/clients/lens-flag-registry.js +0 -467
  416. package/dist/clients/lens-map.js +0 -1156
  417. package/dist/clients/live-bus-emitter.js +0 -74
  418. package/dist/clients/log-cleanup.js +0 -222
  419. package/dist/clients/lsp/aggregation.js +0 -178
  420. package/dist/clients/lsp/cascade-tier.js +0 -421
  421. package/dist/clients/lsp/client.js +0 -4593
  422. package/dist/clients/lsp/config.js +0 -691
  423. package/dist/clients/lsp/content-limits.js +0 -41
  424. package/dist/clients/lsp/diagnostic-binding.js +0 -225
  425. package/dist/clients/lsp/document-drift.js +0 -467
  426. package/dist/clients/lsp/edits.js +0 -1219
  427. package/dist/clients/lsp/index.js +0 -8305
  428. package/dist/clients/lsp/inferred-project.js +0 -216
  429. package/dist/clients/lsp/jvm-runtime.js +0 -298
  430. package/dist/clients/lsp/language.js +0 -63
  431. package/dist/clients/lsp/launch.js +0 -746
  432. package/dist/clients/lsp/lombok.js +0 -158
  433. package/dist/clients/lsp/path-utils.js +0 -5
  434. package/dist/clients/lsp/pending-aux-coverage.js +0 -251
  435. package/dist/clients/lsp/position-encoding.js +0 -61
  436. package/dist/clients/lsp/ruby-drive-dirs.js +0 -83
  437. package/dist/clients/lsp/server.js +0 -3290
  438. package/dist/clients/lsp/session-roots.js +0 -192
  439. package/dist/clients/lsp/spawn-history.js +0 -17
  440. package/dist/clients/lsp/sync-kind.js +0 -56
  441. package/dist/clients/lsp/tsserver-sync.js +0 -332
  442. package/dist/clients/lsp/wait-policy/capability-snapshot.js +0 -1
  443. package/dist/clients/lsp/wait-policy/classification.js +0 -85
  444. package/dist/clients/lsp/wait-policy/index.js +0 -10
  445. package/dist/clients/lsp/wait-policy/strategies.js +0 -392
  446. package/dist/clients/lsp/watch-queue.js +0 -61
  447. package/dist/clients/lsp/workspace-diagnostics-cache.js +0 -639
  448. package/dist/clients/lsp/workspace-diagnostics-session.js +0 -30
  449. package/dist/clients/lsp/workspace-sweep-hold.js +0 -184
  450. package/dist/clients/lsp-budget.js +0 -186
  451. package/dist/clients/lsp-document-symbols.js +0 -110
  452. package/dist/clients/lsp-lazy.js +0 -9
  453. package/dist/clients/lsp-mutation.js +0 -396
  454. package/dist/clients/lsp-status.js +0 -59
  455. package/dist/clients/map-with-concurrency.js +0 -40
  456. package/dist/clients/mcp/analyze.js +0 -420
  457. package/dist/clients/mcp/host-shim.js +0 -31
  458. package/dist/clients/mcp/ipc.js +0 -523
  459. package/dist/clients/mcp/review.js +0 -197
  460. package/dist/clients/mcp/session.js +0 -412
  461. package/dist/clients/memory-sampler.js +0 -208
  462. package/dist/clients/message-end-attribution.js +0 -30
  463. package/dist/clients/metrics-client.js +0 -107
  464. package/dist/clients/metrics-history.js +0 -327
  465. package/dist/clients/middle-man-analysis.js +0 -263
  466. package/dist/clients/model-provider.js +0 -53
  467. package/dist/clients/module-report-lsp.js +0 -189
  468. package/dist/clients/module-report.js +0 -2150
  469. package/dist/clients/mutating-tool.js +0 -651
  470. package/dist/clients/mutation-attribution.js +0 -368
  471. package/dist/clients/mutation-bridge.js +0 -240
  472. package/dist/clients/ndjson-logger.js +0 -734
  473. package/dist/clients/observed-mutation-sources.js +0 -101
  474. package/dist/clients/observed-mutation.js +0 -1253
  475. package/dist/clients/oldtext-autopatch.js +0 -128
  476. package/dist/clients/opaque-mutation-scan.js +0 -496
  477. package/dist/clients/opengrep-client.js +0 -333
  478. package/dist/clients/opengrep-config.js +0 -76
  479. package/dist/clients/package-manager.js +0 -607
  480. package/dist/clients/package-root.js +0 -38
  481. package/dist/clients/partial-edit-apply.js +0 -439
  482. package/dist/clients/path-attribution-telemetry.js +0 -43
  483. package/dist/clients/path-keyed-map.js +0 -108
  484. package/dist/clients/path-utils.js +0 -1244
  485. package/dist/clients/performance-report.js +0 -331
  486. package/dist/clients/persist-debounce.js +0 -70
  487. package/dist/clients/persistent-reverify.js +0 -271
  488. package/dist/clients/php-cs-fixer-config.js +0 -119
  489. package/dist/clients/pipeline.js +0 -1480
  490. package/dist/clients/post-autofix-notice.js +0 -37
  491. package/dist/clients/print-mode.js +0 -21
  492. package/dist/clients/probe-home-state.js +0 -228
  493. package/dist/clients/process-bridge.js +0 -66
  494. package/dist/clients/process-singletons.js +0 -210
  495. package/dist/clients/process-snapshot.js +0 -68
  496. package/dist/clients/project-changes.js +0 -181
  497. package/dist/clients/project-conventions.js +0 -171
  498. package/dist/clients/project-diagnostics/cache.js +0 -137
  499. package/dist/clients/project-diagnostics/extractors.js +0 -109
  500. package/dist/clients/project-diagnostics/fresh-fetch.js +0 -668
  501. package/dist/clients/project-diagnostics/runner-adapters/call-graph-impact.js +0 -118
  502. package/dist/clients/project-diagnostics/runner-adapters/dead-code.js +0 -47
  503. package/dist/clients/project-diagnostics/runner-adapters/gitleaks.js +0 -40
  504. package/dist/clients/project-diagnostics/runner-adapters/govulncheck.js +0 -34
  505. package/dist/clients/project-diagnostics/runner-adapters/jscpd.js +0 -38
  506. package/dist/clients/project-diagnostics/runner-adapters/knip.js +0 -47
  507. package/dist/clients/project-diagnostics/runner-adapters/madge.js +0 -48
  508. package/dist/clients/project-diagnostics/runner-adapters/opengrep.js +0 -40
  509. package/dist/clients/project-diagnostics/runner-adapters/runner-findings.js +0 -127
  510. package/dist/clients/project-diagnostics/runner-adapters/trivy.js +0 -81
  511. package/dist/clients/project-diagnostics/scanner.js +0 -520
  512. package/dist/clients/project-diagnostics/types.js +0 -1
  513. package/dist/clients/project-lens-config.js +0 -807
  514. package/dist/clients/project-report.js +0 -701
  515. package/dist/clients/project-scale.js +0 -237
  516. package/dist/clients/project-scan-policy.js +0 -11
  517. package/dist/clients/project-snapshot-fingerprint.js +0 -48
  518. package/dist/clients/project-snapshot-persist-worker.js +0 -20
  519. package/dist/clients/project-snapshot.js +0 -1653
  520. package/dist/clients/project-trust.js +0 -181
  521. package/dist/clients/python-environment.js +0 -217
  522. package/dist/clients/python-provenance.js +0 -639
  523. package/dist/clients/quiet-window-config.js +0 -47
  524. package/dist/clients/quiet-window.js +0 -236
  525. package/dist/clients/read-bridge.js +0 -139
  526. package/dist/clients/read-expansion.js +0 -266
  527. package/dist/clients/read-guard-logger.js +0 -251
  528. package/dist/clients/read-guard-tool-lines.js +0 -1306
  529. package/dist/clients/read-guard.js +0 -1561
  530. package/dist/clients/recent-touches.js +0 -240
  531. package/dist/clients/redact/secrets.js +0 -449
  532. package/dist/clients/resource-sampler.js +0 -628
  533. package/dist/clients/reverse-deps.js +0 -270
  534. package/dist/clients/review-graph/builder.js +0 -5126
  535. package/dist/clients/review-graph/format.js +0 -33
  536. package/dist/clients/review-graph/git-identity.js +0 -163
  537. package/dist/clients/review-graph/import-resolvers.js +0 -481
  538. package/dist/clients/review-graph/persist-worker.js +0 -10
  539. package/dist/clients/review-graph/query.js +0 -244
  540. package/dist/clients/review-graph/revision-drift.js +0 -21
  541. package/dist/clients/review-graph/service.js +0 -96
  542. package/dist/clients/review-graph/shared-extraction-ir.js +0 -82
  543. package/dist/clients/review-graph/symbol-id.js +0 -103
  544. package/dist/clients/review-graph/tsconfig-paths.js +0 -299
  545. package/dist/clients/review-graph/types.js +0 -1
  546. package/dist/clients/review-graph/workspace-modules.js +0 -449
  547. package/dist/clients/review-graph-logger.js +0 -81
  548. package/dist/clients/ruff-client.js +0 -179
  549. package/dist/clients/rules-scanner.js +0 -131
  550. package/dist/clients/run-duration.js +0 -55
  551. package/dist/clients/runtime-agent-end.js +0 -746
  552. package/dist/clients/runtime-config.js +0 -77
  553. package/dist/clients/runtime-context.js +0 -211
  554. package/dist/clients/runtime-coordinator.js +0 -1324
  555. package/dist/clients/runtime-session.js +0 -2485
  556. package/dist/clients/runtime-tool-call.js +0 -1295
  557. package/dist/clients/runtime-tool-result.js +0 -2049
  558. package/dist/clients/runtime-turn.js +0 -3767
  559. package/dist/clients/rust-client.js +0 -97
  560. package/dist/clients/safe-spawn.js +0 -2357
  561. package/dist/clients/sanitize.js +0 -286
  562. package/dist/clients/scan-utils.js +0 -25
  563. package/dist/clients/scratch-tree-policy.js +0 -165
  564. package/dist/clients/search-read-registration.js +0 -94
  565. package/dist/clients/secret-findings.js +0 -114
  566. package/dist/clients/security-scan-client.js +0 -352
  567. package/dist/clients/session-event-guard.js +0 -297
  568. package/dist/clients/session-lifecycle.js +0 -484
  569. package/dist/clients/session-start-observability.js +0 -94
  570. package/dist/clients/session-state-store.js +0 -101
  571. package/dist/clients/session-summary.js +0 -15
  572. package/dist/clients/sessionstart-logger.js +0 -27
  573. package/dist/clients/sg-runner.js +0 -876
  574. package/dist/clients/sgconfig.js +0 -347
  575. package/dist/clients/shared-checkout-guard.js +0 -338
  576. package/dist/clients/single-flight.js +0 -158
  577. package/dist/clients/situational-tool-telemetry.js +0 -108
  578. package/dist/clients/skills-resolver.js +0 -141
  579. package/dist/clients/slow-fs.js +0 -138
  580. package/dist/clients/smells-rollup.js +0 -231
  581. package/dist/clients/source-filter.js +0 -596
  582. package/dist/clients/source-walker.js +0 -211
  583. package/dist/clients/spawn-output-cap.js +0 -120
  584. package/dist/clients/spawn-timeout-cooldown.js +0 -110
  585. package/dist/clients/stale-marker.js +0 -17
  586. package/dist/clients/startup-scan.js +0 -400
  587. package/dist/clients/startup-timing.js +0 -130
  588. package/dist/clients/string-utils.js +0 -33
  589. package/dist/clients/subagent-mode.js +0 -111
  590. package/dist/clients/symbol-containment.js +0 -24
  591. package/dist/clients/symbol-types.js +0 -5
  592. package/dist/clients/test-runner-client.js +0 -2507
  593. package/dist/clients/test-runner-delivery.js +0 -287
  594. package/dist/clients/todo-scanner.js +0 -229
  595. package/dist/clients/tool-agreement.js +0 -423
  596. package/dist/clients/tool-config.js +0 -249
  597. package/dist/clients/tool-cwd.js +0 -270
  598. package/dist/clients/tool-definition.js +0 -47
  599. package/dist/clients/tool-event.js +0 -105
  600. package/dist/clients/tool-policy.js +0 -2755
  601. package/dist/clients/tool-probe.js +0 -53
  602. package/dist/clients/tool-render.js +0 -156
  603. package/dist/clients/tool-set-policy.js +0 -118
  604. package/dist/clients/tree-sitter-cache.js +0 -364
  605. package/dist/clients/tree-sitter-client.js +0 -4195
  606. package/dist/clients/tree-sitter-logger.js +0 -100
  607. package/dist/clients/tree-sitter-navigator.js +0 -269
  608. package/dist/clients/tree-sitter-query-loader.js +0 -569
  609. package/dist/clients/tree-sitter-shared.js +0 -158
  610. package/dist/clients/tree-sitter-symbol-extractor.js +0 -1265
  611. package/dist/clients/trivy-client.js +0 -467
  612. package/dist/clients/tui-fit.js +0 -50
  613. package/dist/clients/turn-context.js +0 -52
  614. package/dist/clients/turn-end/lane.js +0 -51
  615. package/dist/clients/turn-end/lanes/govulncheck.js +0 -112
  616. package/dist/clients/turn-end/lanes/secrets.js +0 -204
  617. package/dist/clients/turn-summary-render.js +0 -72
  618. package/dist/clients/turn-summary.js +0 -132
  619. package/dist/clients/typos-config.js +0 -29
  620. package/dist/clients/user-notify.js +0 -51
  621. package/dist/clients/vanished-instance-marker.js +0 -57
  622. package/dist/clients/warm-attach.js +0 -305
  623. package/dist/clients/widget-state.js +0 -1808
  624. package/dist/clients/word-index-logger.js +0 -49
  625. package/dist/clients/word-index-store.js +0 -459
  626. package/dist/clients/word-index.js +0 -2080
  627. package/dist/clients/workspace-topology.js +0 -443
  628. package/dist/clients/write-ordering-guard.js +0 -65
  629. package/dist/clients/zizmor-config.js +0 -340
  630. package/dist/i18n.js +0 -69
  631. package/dist/mcp/build-staleness.js +0 -124
  632. package/dist/scripts/lib/process-scan.mjs +0 -583
  633. package/dist/scripts/lib/skills-predicate.mjs +0 -129
  634. package/dist/scripts/lib/web-tree-sitter-dir.mjs +0 -123
  635. package/dist/tools/activate-tools.js +0 -87
  636. package/dist/tools/ast-grep-outline.js +0 -137
  637. package/dist/tools/ast-grep-replace.js +0 -244
  638. package/dist/tools/ast-grep-search.js +0 -762
  639. package/dist/tools/effective-config.js +0 -90
  640. package/dist/tools/lens-diagnostic-mark.js +0 -375
  641. package/dist/tools/lens-diagnostics.js +0 -2571
  642. package/dist/tools/lsp-diagnostics.js +0 -1745
  643. package/dist/tools/lsp-navigation.js +0 -1367
  644. package/dist/tools/lsp-structured-output.js +0 -294
  645. package/dist/tools/module-report.js +0 -382
  646. package/dist/tools/project-report.js +0 -86
  647. package/dist/tools/render-compact.js +0 -374
  648. package/dist/tools/scan-progress.js +0 -53
  649. package/dist/tools/shared.js +0 -29
  650. package/dist/tools/symbol-search.js +0 -155
@@ -1,1032 +0,0 @@
1
- /**
2
- * Shared file path utilities for pi-lens
3
- */
4
- import * as fs from "node:fs";
5
- import { createHash } from "node:crypto";
6
- import * as os from "node:os";
7
- import * as path from "node:path";
8
- import { Minimatch } from "./deps/minimatch.js";
9
- import { detectFileRole } from "./file-role.js";
10
- import { FRESHNESS_CADENCE_MS } from "./freshness-cadence.js";
11
- import { isInSpawnTimeoutCooldown, noteSpawnTimeout, } from "./spawn-timeout-cooldown.js";
12
- import { collectTrackedFiles, getTrackedFilesSnapshot, } from "./git-tracked-ignore.js";
13
- import { getGlobalIgnorePatterns, getPiLensGlobalConfigPath, } from "./lens-config.js";
14
- import { homeRelativePath, isExternalOrVendorFile, isUnderDir, normalizeEphemeralMapKey, normalizeFilePath, toProjectRelativePath, } from "./path-utils.js";
15
- import { findPiLensConfigInDir, findPiLensProjectConfig, loadPiLensConfigInDir, loadPiLensProjectConfig, } from "./project-lens-config.js";
16
- import { safeSpawnAsync } from "./safe-spawn.js";
17
- /**
18
- * Return the directory where pi-lens stores project-specific data
19
- * (caches, indexes, worklogs, etc.).
20
- *
21
- * Default: reuse <project>/.pi-lens if it already exists, otherwise use
22
- * ~/.pi-lens/projects/<project-slug>
23
- *
24
- * Override: set PILENS_DATA_DIR=/some/path — each project gets its own
25
- * subdirectory named after a sanitized form of its absolute path, e.g.
26
- * PILENS_DATA_DIR=~/.pi-lens/projects
27
- * → ~/.pi-lens/projects/home-user-myapp-<8-hex-hash>/
28
- *
29
- * This keeps project folders clean and avoids creating .pi-lens folders
30
- * inside user projects.
31
- */
32
- export function getProjectDataDir(cwd) {
33
- const legacyProjectDir = path.join(cwd, ".pi-lens");
34
- const configuredBase = process.env.PILENS_DATA_DIR?.trim();
35
- if (!configuredBase && fs.existsSync(legacyProjectDir)) {
36
- return legacyProjectDir;
37
- }
38
- const base = configuredBase || path.join(getGlobalPiLensDir(), "projects");
39
- const resolvedBase = base.trim();
40
- const memoKey = `${resolvedBase}\0${path.resolve(cwd)}`;
41
- const cached = settledDataDirs.get(memoKey);
42
- if (cached !== undefined)
43
- return cached;
44
- const canonical = canonicalProjectRoot(cwd);
45
- const readable = projectDataDirReadableSlug(canonical.root);
46
- const hash = projectDataDirRootHash(canonical.root);
47
- const slug = `${readable || "default"}-${hash}`;
48
- const dir = path.join(resolvedBase, slug);
49
- const settled = settleProjectDataDir(resolvedBase, readable || "default", dir, memoKey, canonical.fallback);
50
- return settled;
51
- }
52
- /**
53
- * The human-readable half of the project data-dir slug: the absolute root
54
- * with separators folded to dashes and anything else stripped.
55
- *
56
- * #2874: this form ALONE is not an identity — `src/pi-lens` and
57
- * `src/pi/lens` fold to the same string. It is only ever combined with
58
- * {@link projectDataDirRootHash}. Never use it as a directory name alone.
59
- */
60
- function projectDataDirReadableSlug(canonicalRoot) {
61
- const normalized = normalizeFilePath(canonicalRoot);
62
- return normalized
63
- .replace(/^[a-z]:/i, "") // strip Windows drive letter
64
- .replace(/\/+/g, "-") // separators → dashes
65
- .replace(/[^A-Za-z0-9-]/g, "") // strip anything else
66
- .replace(/^-+/, "") // trim leading dashes
67
- .replace(/-+$/, ""); // trim trailing dashes
68
- }
69
- /**
70
- * The canonical root is the resolved absolute path for both slug halves.
71
- * `realpathSync` is probed only to expose a fallback boundary failure; using
72
- * its result would let one root spelling change identity when the boundary
73
- * recovers. The hash is the first 8 hex chars of SHA-256 over that root. A
74
- * collision needs the same readable slug and the same 32-bit prefix, so the
75
- * practical collision population is readable-slug twin pairs. Pinned on
76
- * purpose because changing it renames every directory.
77
- */
78
- function canonicalProjectRoot(cwd) {
79
- const resolved = path.resolve(cwd);
80
- try {
81
- // Probe the root, but keep the resolved spelling as the identity in both
82
- // success and fallback cases. Resolving only on success would let a
83
- // transient boundary failure choose a second data directory.
84
- fs.realpathSync(resolved);
85
- }
86
- catch {
87
- // Best-effort: the root may not exist yet.
88
- return { root: resolved, fallback: true };
89
- }
90
- return { root: resolved, fallback: false };
91
- }
92
- function projectDataDirRootHash(canonicalRoot) {
93
- return createHash("sha256").update(canonicalRoot).digest("hex").slice(0, 8);
94
- }
95
- const pendingDataDirMigrations = [];
96
- const settledDataDirs = new Map();
97
- export function resetProjectDataDirSessionState() {
98
- pendingDataDirMigrations.splice(0);
99
- }
100
- /**
101
- * One-time upgrade from a pre-#2874 slug directory to its hashed name.
102
- * When the old directory exists and the new one does not, the state moves
103
- * with one atomic `renameSync` (same parent, so same filesystem). When both
104
- * exist the new one wins and nothing moves. Either case queues one
105
- * {@link ProjectDataDirMigration} for the session-start drain, which emits
106
- * the `data_dir_migrated` record. Best-effort throughout: on any failure the
107
- * caller gets the pre-existing directory and behavior is unchanged.
108
- *
109
- * No ledger import here on purpose: `probe-home-state.ts` documents that a
110
- * direct edge between this module and `degradation-ledger.ts` in either
111
- * direction adds `no-client-cycles` violations, so the record is emitted by
112
- * the drain site in `runtime-session.ts` instead.
113
- */
114
- function settleProjectDataDir(base, oldSlug, dir, memoKey, identityFallback) {
115
- const oldDir = path.join(base, oldSlug);
116
- const newExists = fs.existsSync(dir);
117
- const oldExists = fs.existsSync(oldDir);
118
- if (!oldExists) {
119
- if (identityFallback && pendingDataDirMigrations.length < 32) {
120
- pendingDataDirMigrations.push({
121
- to: dir,
122
- outcome: "identity-fallback",
123
- });
124
- }
125
- // Steady state: nothing to migrate from.
126
- settledDataDirs.set(memoKey, dir);
127
- return dir;
128
- }
129
- if (!newExists) {
130
- try {
131
- fs.renameSync(oldDir, dir);
132
- }
133
- catch (error) {
134
- if (error.code === "ENOENT") {
135
- if (fs.existsSync(dir)) {
136
- settledDataDirs.set(memoKey, dir);
137
- return dir;
138
- }
139
- if (fs.existsSync(oldDir))
140
- return oldDir;
141
- return dir;
142
- }
143
- // Best-effort: retain the old directory and publish one bounded
144
- // failure notice for this process's memo key.
145
- if (pendingDataDirMigrations.length < 32) {
146
- pendingDataDirMigrations.push({
147
- to: dir,
148
- outcome: "rename-failed",
149
- });
150
- }
151
- settledDataDirs.set(memoKey, oldDir);
152
- return oldDir;
153
- }
154
- }
155
- // Either the rename just moved the state, or both directories already
156
- // existed and the new one wins. Queue one migration for the drain.
157
- settledDataDirs.set(memoKey, dir);
158
- if (pendingDataDirMigrations.length < 32) {
159
- pendingDataDirMigrations.push({
160
- to: dir,
161
- outcome: newExists ? "coexisting" : "renamed",
162
- });
163
- }
164
- return dir;
165
- }
166
- /**
167
- * Drain the queued {@link ProjectDataDirMigration}s, clearing the queue.
168
- * Called once per session start by `handleSessionStart`; each queued outcome is
169
- * therefore recorded at most once per session. Test-only callers must not rely
170
- * on queue depth across drains.
171
- */
172
- export function drainProjectDataDirMigrations() {
173
- return pendingDataDirMigrations.splice(0);
174
- }
175
- /**
176
- * Test-only reset for the settled-directory memo. The memo is a pure
177
- * performance cache (one `existsSync` pair saved per latched directory), so
178
- * clearing it changes no observable behavior — it lets a test stage an
179
- * old-slug directory AFTER learning the new name, then resolve again.
180
- */
181
- export function _resetProjectDataDirMemoForTests() {
182
- settledDataDirs.clear();
183
- }
184
- /**
185
- * The project-data path to SHOW an agent or a human, for a file that
186
- * {@link getProjectDataDir} owns.
187
- *
188
- * #2521: the turn-end actionable-warnings advisory told the agent to read a
189
- * hardcoded `.pi-lens/cache/actionable-warnings.json`, but that spelling is
190
- * only correct in the LEGACY arm of `getProjectDataDir` — a project with no
191
- * `.pi-lens/` directory (the common case) stores the report under
192
- * `~/.pi-lens/projects/<slug>/cache/`, and a `PILENS_DATA_DIR` project stores
193
- * it somewhere else again. Agents followed the advisory literally and got
194
- * `cat: .pi-lens/cache/actionable-warnings.json: No such file or directory`.
195
- *
196
- * Any instructional string that NAMES a project-data location must be built
197
- * here, so the displayed path and the written path can never disagree. Guarded
198
- * by `tests/clients/data-dir-display-path-sweep.test.ts`.
199
- *
200
- * Two output shapes, matching `toRunnerDisplayPath`'s convention
201
- * (`clients/dispatch/runner-context.ts`) so one advisory never mixes styles:
202
- * - under `cwd` → a `/`-separated path relative to it
203
- * (`.pi-lens/cache/actionable-warnings.json`), which is what the legacy
204
- * arm produces and what an agent can paste straight into a shell.
205
- * - anywhere else → absolute, `/`-separated, and `~`-folded via
206
- * {@link homeRelativePath} so the default `~/.pi-lens/projects/...` store
207
- * does not leak the account name into agent context (#2440 F5).
208
- *
209
- * Pure string work on top of `getProjectDataDir`'s own resolution: it never
210
- * stats the target, so it is safe to call for a file that has not been written
211
- * yet and cannot throw on a surface whose whole job is to render a hint.
212
- *
213
- * The relative-or-absolute decision reuses `toProjectRelativePath`
214
- * (`clients/path-utils.ts`) — the same shape-aware, non-stat'ing primitive
215
- * `toRunnerDisplayPath` (`clients/dispatch/runner-context.ts`) composes for
216
- * the analogous "relative path if under this root, else something else"
217
- * decision — rather than a second hand-rolled `path.relative` fold. It is NOT
218
- * `toRunnerDisplayPath` itself: that helper routes its result through
219
- * `normalizeMapKey`, which on win32 calls `realpathSync.native()` (or, for a
220
- * not-yet-existing path, lowercases the unresolved tail) — exactly the
221
- * stat-and-mutate-casing behavior this function's contract above rules out.
222
- */
223
- export function displayProjectDataPath(cwd, ...segments) {
224
- const absolute = path.resolve(getProjectDataDir(cwd), ...segments);
225
- const absolutePosix = absolute.replace(/\\/g, "/");
226
- const relative = toProjectRelativePath(absolute, cwd);
227
- if (relative !== absolutePosix) {
228
- return relative;
229
- }
230
- // `toProjectRelativePath` fell back to the (posix-ified) absolute path —
231
- // `absolute` is not under `cwd`. Fold `~` so the default
232
- // `~/.pi-lens/projects/...` store does not leak the account name into
233
- // agent context (#2440 F5). Posix-ify BEFORE the fold: `homeRelativePath`
234
- // deliberately returns a path that is not under `$HOME` unchanged,
235
- // separators included, so a `PILENS_DATA_DIR=D:\lens-data` store would
236
- // otherwise render with backslashes while the legacy arm above renders
237
- // with forward ones — `absolutePosix` is already folded, so this is a
238
- // no-op fold, not a second one.
239
- return homeRelativePath(absolutePosix);
240
- }
241
- /**
242
- * Machine-global pi-lens directory: `~/.pi-lens/` by default.
243
- *
244
- * Used for tool binaries (`~/.pi-lens/tools/`, `~/.pi-lens/bin/`), the
245
- * cross-process instance registry (`instances.json`, #449/#525) and the
246
- * orphan-backstop lease beside it, the auto-install probe cache, the
247
- * canonical global config (`config.json`), LSP server storage (intelephense's
248
- * index, PSES's per-PID session dir) and JVM runtimes — state that is
249
- * intentionally NOT project-scoped, because it spans every project pi-lens
250
- * has touched.
251
- *
252
- * Override: set `PI_LENS_HOME=/some/path` to relocate this ENTIRE root (every
253
- * caller routes through this one function, so one env var covers all of
254
- * them — see #525). Tests MUST set this to a per-worker temp dir in
255
- * `tests/support/vitest-setup.ts` rather than mocking each caller separately;
256
- * otherwise a test that exercises `registerInstance`/`sweepOrphans` or any
257
- * logger writes into the developer's REAL `~/.pi-lens` (dogfooded live: a
258
- * test-fixture instance survived in the real `instances.json` for 17h).
259
- *
260
- * DELIBERATELY cwd-INDEPENDENT (#2506 round 3). Its sibling
261
- * `getGlobalPiLensLogDir()` (`probe-home-state.ts`) carries the probe-home
262
- * redirect; this one must not, because the things resolved here are shared
263
- * machine state a session needs to KEEP: a pi session running from an agent
264
- * worktree or a throwaway temp project must still find the tools it already
265
- * installed and must still register in the one `instances.json` every other
266
- * pi-lens process on the box reads. Redirecting THIS function (as round 2 of
267
- * #2506 did) would silently give every worktree its own empty tool tree and
268
- * its own private registry, so the reaper could never see across them — a
269
- * worse defect than the telemetry pollution the redirect exists to stop.
270
- *
271
- * Distinct from `getProjectDataDir(cwd)`, which respects `PILENS_DATA_DIR`
272
- * (project-scoped) and produces per-project subdirectories. Callers writing
273
- * project caches, snapshots, or worklogs should use `getProjectDataDir(cwd)`
274
- * instead — `PI_LENS_HOME` is the MACHINE-scoped sibling of that override.
275
- * `getProjectDataDir` composes through THIS function, not the log one: a
276
- * probe's project caches are already isolated by its own path slug, and a
277
- * worktree session keeping its warm caches is the same "do not break the
278
- * session" argument as the tools above.
279
- */
280
- export function getGlobalPiLensDir() {
281
- const override = process.env.PI_LENS_HOME?.trim();
282
- if (override)
283
- return path.resolve(override);
284
- return path.join(os.homedir(), ".pi-lens");
285
- }
286
- /**
287
- * Directories to exclude from all scans (build outputs, dependencies, caches).
288
- * Used consistently across all scanners to avoid noise from generated files.
289
- */
290
- export const EXCLUDED_DIRS = [
291
- "node_modules",
292
- ".git",
293
- "dist",
294
- "build",
295
- ".turbo",
296
- ".cache",
297
- "target",
298
- "out",
299
- ".parcel-cache",
300
- ".svelte-kit",
301
- ".nuxt",
302
- ".yarn",
303
- ".pnpm-store",
304
- ".gradle",
305
- ".next",
306
- ".pi-lens",
307
- ".pi", // pi agent directory
308
- // The SAME agent, rebranded: pi derives its config-dir name as
309
- // `pkg.piConfig?.configDir || ".pi"` (pi-coding-agent 0.85.1,
310
- // `dist/bundle/chunks/chunk-JVUZSMYM.js`), so a redistribution spells its
311
- // `<configDir>/agent/sessions` history `.omp/agent/sessions` instead.
312
- // #3112: a project-local one was walked entry-by-entry and spent the whole
313
- // startup-scan entry budget, so a five-file project reported
314
- // `too-many-entries` and never warmed its caches.
315
- ".omp",
316
- ".ruff_cache", // Python linter cache
317
- ".worktrees",
318
- ".claude",
319
- ".codex",
320
- ".rescue",
321
- ".agents",
322
- ".gstack",
323
- ".superpowers",
324
- ".guardrails",
325
- ".playwright-cli",
326
- ".playwright-mcp",
327
- ".vscode",
328
- "venv",
329
- ".venv",
330
- "coverage",
331
- "__pycache__",
332
- ".tox",
333
- ".pytest_cache",
334
- "*.dSYM",
335
- // Vendored upstream source conventions — universally too large to scan
336
- "vendor", // Go modules, PHP Composer, Ruby Bundler
337
- "third_party", // Chromium/Google convention (llama.cpp, sherpa-onnx, gRPC, TF)
338
- "third-party",
339
- "vendors",
340
- ];
341
- function resolveGitIgnoreRoot(startDir) {
342
- const fallback = path.resolve(startDir);
343
- let current = fallback;
344
- while (true) {
345
- if (fs.existsSync(path.join(current, ".git")))
346
- return current;
347
- const parent = path.dirname(current);
348
- if (parent === current)
349
- return fallback;
350
- current = parent;
351
- }
352
- }
353
- function collapseSlashes(value) {
354
- let out = "";
355
- let previousWasSlash = false;
356
- for (const ch of value) {
357
- if (ch === "/") {
358
- if (!previousWasSlash)
359
- out += ch;
360
- previousWasSlash = true;
361
- continue;
362
- }
363
- out += ch === "\\" ? "/" : ch;
364
- previousWasSlash = false;
365
- }
366
- return out;
367
- }
368
- function stripLeadingDotSlash(value) {
369
- return value.startsWith("./") ? value.slice(2) : value;
370
- }
371
- function stripTrailingSlashes(value) {
372
- let end = value.length;
373
- while (end > 0 && value[end - 1] === "/")
374
- end -= 1;
375
- return value.slice(0, end);
376
- }
377
- function stripLeadingSlashes(value) {
378
- let start = 0;
379
- while (start < value.length && value[start] === "/")
380
- start += 1;
381
- return value.slice(start);
382
- }
383
- function normalizeIgnorePath(value) {
384
- return collapseSlashes(stripLeadingDotSlash(value));
385
- }
386
- function stripTrailingSpaces(value) {
387
- // Good-enough gitignore whitespace handling: unescaped trailing spaces are ignored.
388
- let end = value.length;
389
- while (end > 0 && value[end - 1] === " " && value[end - 2] !== "\\")
390
- end -= 1;
391
- return value.slice(0, end).replace(/\\ /g, " ");
392
- }
393
- function parseGitignoreContent(content, layer) {
394
- const patterns = [];
395
- for (const rawLine of content.split(/\r?\n/)) {
396
- let line = stripTrailingSpaces(rawLine.trimStart());
397
- if (!line || line.startsWith("#"))
398
- continue;
399
- let negated = false;
400
- if (line.startsWith("!")) {
401
- negated = true;
402
- line = line.slice(1);
403
- }
404
- line = normalizeIgnorePath(line);
405
- if (!line)
406
- continue;
407
- const directoryOnly = line.endsWith("/");
408
- if (directoryOnly)
409
- line = stripTrailingSlashes(line);
410
- const rooted = line.startsWith("/");
411
- if (rooted)
412
- line = stripLeadingSlashes(line);
413
- if (!line)
414
- continue;
415
- patterns.push({
416
- pattern: line,
417
- negated,
418
- directoryOnly,
419
- rooted,
420
- hasSlash: line.includes("/"),
421
- layer,
422
- });
423
- }
424
- return patterns;
425
- }
426
- function expandGitignorePattern(pattern) {
427
- const body = pattern.pattern;
428
- if (pattern.directoryOnly) {
429
- if (pattern.rooted || pattern.hasSlash)
430
- return [body, `${body}/**`];
431
- return [body, `${body}/**`, `**/${body}`, `**/${body}/**`];
432
- }
433
- if (pattern.rooted || pattern.hasSlash)
434
- return [body];
435
- return [body, `**/${body}`];
436
- }
437
- function matchesGitignorePattern(pattern, relativePath, isDirectory, matchExpanded) {
438
- const candidate = stripLeadingSlashes(normalizeIgnorePath(relativePath));
439
- if (!candidate)
440
- return false;
441
- const candidates = isDirectory ? [candidate, `${candidate}/`] : [candidate];
442
- return expandGitignorePattern(pattern).some((expanded) => {
443
- if (isDirectory && expanded.endsWith("/**")) {
444
- const prefix = expanded.slice(0, -3);
445
- if (candidate === prefix || candidate.startsWith(`${prefix}/`))
446
- return true;
447
- }
448
- return candidates.some((value) => matchExpanded(value, expanded));
449
- });
450
- }
451
- function readGitignorePatterns(rootDir, layer = "gitignore") {
452
- const gitignorePath = path.join(rootDir, ".gitignore");
453
- try {
454
- return parseGitignoreContent(fs.readFileSync(gitignorePath, "utf-8"), layer);
455
- }
456
- catch {
457
- return [];
458
- }
459
- }
460
- function ancestorDirsBetween(rootDir, targetDir) {
461
- const relative = path.relative(rootDir, targetDir);
462
- if (relative.startsWith("..") || path.isAbsolute(relative))
463
- return [];
464
- const dirs = [rootDir];
465
- if (!relative)
466
- return dirs;
467
- let current = rootDir;
468
- for (const segment of relative.split(path.sep).filter(Boolean)) {
469
- current = path.join(current, segment);
470
- dirs.push(current);
471
- }
472
- return dirs;
473
- }
474
- function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
475
- const consumedIgnoreSources = new Map();
476
- // `signature` lets a caller that already statted the file reuse that one
477
- // stat (#2016's class on this seam: never re-derive a value you just
478
- // computed). Callers with no signature in hand still pay their own stat.
479
- const rememberIgnoreSource = (filePath, signature = fileFreshnessSignature(filePath)) => {
480
- consumedIgnoreSources.set(filePath, { path: filePath, ...signature });
481
- };
482
- rememberIgnoreSource(path.join(resolvedRoot, ".gitignore"));
483
- const nestedCache = new Map();
484
- // #783: layer a NESTED `.pi-lens.json`'s `ignore` field the same way a
485
- // nested `.gitignore` is already layered — each ancestor directory between
486
- // `resolvedRoot` and the target is checked for its OWN config file (no
487
- // upward walk; `findPiLensConfigInDir`/`loadPiLensConfigInDir` look only
488
- // directly in `dir`), and its `ignore` patterns are anchored to `dir` (same
489
- // anchoring semantics as a `.gitignore` living in that directory) and
490
- // tagged `"pilens"` so #703's tracked-file-rescue rule still skips them.
491
- // `loadPiLensConfigInDir` reuses `project-lens-config.ts`'s own
492
- // path+mtime cache, so this never re-reads/re-parses JSON that some other
493
- // caller (or the root-config lookup above) already loaded.
494
- const patternsForDir = (dir) => {
495
- if (dir === resolvedRoot)
496
- return patterns;
497
- const cached = nestedCache.get(dir);
498
- const now = Date.now();
499
- // #2071: inside the cadence window this directory's rules are frozen, so
500
- // no stat runs and every verdict already memoized under `dir` stays
501
- // derivable from exactly these patterns. Before this gate the freshness
502
- // check ran per call while `patternMemo` did not, which is what let a
503
- // fresh path and a memoized path in the same directory return opposite
504
- // verdicts for the same rule. Externally edited nested sources are
505
- // therefore picked up within PROJECT_IGNORE_FRESHNESS_CADENCE_MS, the
506
- // same bound #2159 already accepted for the root sources.
507
- // pi-authored `.gitignore` writes keep their instant path through
508
- // `invalidateProjectIgnoreMatcherForPath`.
509
- if (cached !== undefined &&
510
- now - cached.checkedAtMs < PROJECT_IGNORE_FRESHNESS_CADENCE_MS) {
511
- return cached.patterns;
512
- }
513
- const gitignoreSig = gitignoreSignature(dir);
514
- // One stat, two consumers. `rememberIgnoreSource` used to stat the same
515
- // file a second time on the line below this one.
516
- rememberIgnoreSource(path.join(dir, ".gitignore"), gitignoreSig);
517
- // #1105: gate on size too. `findPiLensConfigInDir` returns `size` alongside
518
- // `mtimeMs` (both from one stat), and `gitignoreSignature` reads both for
519
- // the nested `.gitignore`, so an mtime-preserving, length-changing edit to
520
- // EITHER nested source can no longer replay stale patterns for this subtree.
521
- const pilensInfo = findPiLensConfigInDir(dir);
522
- const pilensMtime = pilensInfo?.mtimeMs ?? -1;
523
- const pilensSize = pilensInfo?.size ?? -1;
524
- if (cached?.gitignoreMtimeMs === gitignoreSig.mtimeMs &&
525
- cached?.gitignoreSize === gitignoreSig.size &&
526
- cached?.pilensMtimeMs === pilensMtime &&
527
- cached?.pilensSize === pilensSize) {
528
- // Unchanged: re-arm the shared clock so the next window is measured
529
- // from this check, not from the build that first populated the entry.
530
- cached.checkedAtMs = now;
531
- return cached.patterns;
532
- }
533
- const nestedConfig = loadPiLensConfigInDir(dir);
534
- const nextPatterns = [
535
- ...readGitignorePatterns(dir),
536
- ...parseGitignoreContent(nestedConfig.ignore.join("\n"), "pilens"),
537
- ];
538
- nestedCache.set(dir, {
539
- checkedAtMs: now,
540
- gitignoreMtimeMs: gitignoreSig.mtimeMs,
541
- gitignoreSize: gitignoreSig.size,
542
- pilensMtimeMs: pilensMtime,
543
- pilensSize: pilensSize,
544
- patterns: nextPatterns,
545
- });
546
- // #2071: drift is the SINGLE trigger. The rules under `dir` just changed,
547
- // so every verdict computed under the superseded rules dies in the same
548
- // step that supersedes them. `cached === undefined` is a first build, not
549
- // a change, and has no verdicts to drop.
550
- if (cached !== undefined)
551
- dropVerdictsUnder(dir);
552
- return nextPatterns;
553
- };
554
- // Per-matcher path → pattern-verdict memo. The matcher itself is cached by
555
- // `getProjectIgnoreMatcher` keyed on `.gitignore` size+mtime (#1105), so this
556
- // Map's lifetime is bounded to a single set of ignore rules — when any
557
- // `.gitignore` changes, the matcher is rebuilt and the memo is dropped
558
- // with it. Without this memo, every background scan (comment scan, knip,
559
- // jscpd, call-graph, source-filter, pipeline) recomputes O(ancestorDirs ×
560
- // patterns) per file, multiplying into 2-3s of pure CPU on a 2k-file
561
- // project. With it, the second visitor of the same path is O(1).
562
- //
563
- // #703: this memoizes only the PATTERN verdict (which is deterministic —
564
- // it never changes for a given matcher instance), NOT the tracked-aware
565
- // final verdict. The tracked-files set can transition from "not yet
566
- // primed" to "primed" mid-process (a walker calls `ensureTrackedIndex()`
567
- // partway through the matcher's lifetime), so baking the tracked check
568
- // into this memo would let an early, pre-priming call poison every later
569
- // lookup of the same path for this matcher's entire cache lifetime. The
570
- // tracked-set lookup itself is a cheap Set#has over syntactically-folded
571
- // keys (see `isTrackedAndRescued` — no `realpathSync` anywhere in this
572
- // function), and — critically — it's only ever paid for paths a pattern
573
- // already flagged as ignored, so it doesn't reintroduce the per-file cost
574
- // this memo exists to avoid for the common (not-ignored) case.
575
- const patternMemo = new Map();
576
- /**
577
- * Drop every memoized verdict at or below `subtree`, leaving `nestedCache`
578
- * alone. `patternsForDir` calls this the moment it rebuilds a directory's
579
- * patterns, which is why it must NOT evict the entry that rebuild just
580
- * wrote. `invalidateSubtree` layers the eviction on top for the write-hook
581
- * path, where the caller knows the source changed but has not re-read it.
582
- */
583
- function dropVerdictsUnder(subtree) {
584
- const resolvedSubtree = path.resolve(subtree);
585
- for (const key of patternMemo.keys()) {
586
- const memoPath = key.slice(2);
587
- const relative = path.relative(resolvedSubtree, memoPath);
588
- if (!relative ||
589
- (!relative.startsWith("..") && !path.isAbsolute(relative))) {
590
- patternMemo.delete(key);
591
- }
592
- }
593
- }
594
- const invalidateSubtree = (subtree) => {
595
- dropVerdictsUnder(subtree);
596
- nestedCache.delete(path.resolve(subtree));
597
- };
598
- // Compile expanded gitignore globs once per matcher instance. Relative-path
599
- // resolution remains outside this cache, so nested ignore scopes cannot leak
600
- // verdicts between sibling trees. The instance lifetime bounds this map.
601
- const gitignoreGlobOptions = {
602
- dot: true,
603
- nocase: process.platform === "win32",
604
- };
605
- const compiledGlobs = new Map();
606
- const matchExpanded = (value, expanded) => {
607
- let compiled = compiledGlobs.get(expanded);
608
- if (compiled === undefined) {
609
- compiled = new Minimatch(expanded, gitignoreGlobOptions);
610
- compiledGlobs.set(expanded, compiled);
611
- }
612
- return compiled.match(value);
613
- };
614
- // #703 perf follow-up: `normalizeEphemeralMapKey` (cheap slash-fold +
615
- // Windows-lowercase, zero fs I/O), NOT `normalizeMapKey` (realpath-backed).
616
- // This runs on every `isIgnored` call that reaches this branch — walks
617
- // over this repo alone visit thousands of pattern-ignored compiled
618
- // `*.js`/`*.d.ts` files, and `dispatch/integration.ts`'s per-edit cascade
619
- // check hits it too — so a `realpathSync` here would violate the
620
- // event-loop/slow-FS discipline `isIgnored` is required to keep (#462: 75x
621
- // slower on 9p/drvfs). Both `resolved` (this matcher's own `path.resolve`,
622
- // never realpath'd) and the tracked-set's keys (`git-tracked-ignore.ts`,
623
- // realpath'd ONCE per fetch on the shared root, not per file) are
624
- // self-consistent within one process/session, which is exactly
625
- // `normalizeEphemeralMapKey`'s contract — see that function's doc and
626
- // `git-tracked-ignore.ts`'s module doc for the full reasoning. Accepted
627
- // edge case: a symlinked or 8.3-short-name project root can make the cheap
628
- // fold miss even after the fetch side's one realpath — the file then stays
629
- // pattern-ignored, i.e. degrades to today's (pre-#703) behavior, which is
630
- // consistent with this whole feature's fail-open contract.
631
- function isTrackedAndRescued(resolved) {
632
- const snapshot = getTrackedFilesSnapshot(resolvedRoot);
633
- if (!snapshot)
634
- return false; // never primed / git unavailable: fail-open to pattern-only
635
- return snapshot.has(normalizeEphemeralMapKey(resolved));
636
- }
637
- return {
638
- rootDir: resolvedRoot,
639
- patterns,
640
- getConsumedIgnoreSources: () => [...consumedIgnoreSources.values()],
641
- refreshConsumedIgnoreSource(filePath) {
642
- // The freshness sweep refreshes this baseline after invalidation.
643
- if (consumedIgnoreSources.has(filePath))
644
- rememberIgnoreSource(filePath);
645
- },
646
- invalidateSubtree,
647
- ensureTrackedIndex() {
648
- return collectTrackedFiles(resolvedRoot).then(() => undefined);
649
- },
650
- isIgnored(filePath, isDirectory = false) {
651
- const resolved = path.resolve(filePath);
652
- // Two namespaces (D: for directory queries, F: for file queries)
653
- // because gitignore semantics differ for trailing-slash patterns.
654
- const memoKey = (isDirectory ? "D:" : "F:") + resolved;
655
- let verdict = patternMemo.get(memoKey);
656
- if (verdict === undefined) {
657
- const rootRelative = path.relative(resolvedRoot, resolved);
658
- if (!rootRelative ||
659
- rootRelative.startsWith("..") ||
660
- path.isAbsolute(rootRelative)) {
661
- verdict = { ignored: false, layer: undefined };
662
- }
663
- else {
664
- let ignored = false;
665
- let layer;
666
- const patternDirs = ancestorDirsBetween(resolvedRoot, path.dirname(resolved));
667
- for (const dir of patternDirs) {
668
- const dirPatterns = patternsForDir(dir);
669
- if (dirPatterns.length === 0)
670
- continue;
671
- const relative = path.relative(dir, resolved);
672
- const normalized = normalizeIgnorePath(relative);
673
- for (const pattern of dirPatterns) {
674
- if (!matchesGitignorePattern(pattern, normalized, isDirectory, matchExpanded))
675
- continue;
676
- ignored = !pattern.negated;
677
- layer = pattern.layer;
678
- }
679
- }
680
- verdict = { ignored, layer };
681
- }
682
- patternMemo.set(memoKey, verdict);
683
- }
684
- if (!verdict.ignored)
685
- return false;
686
- // #703 layer semantics: a winning positive match from `global` or
687
- // `gitignore` emulates git, so it inherits git's "a tracked file is
688
- // never ignored" rule. A winning match from `pilens` is pi-lens-native
689
- // intent and stays excluded regardless of tracked status. Directory
690
- // queries are never tracked-rescued — the tracked set is a file-id
691
- // set, not a directory set.
692
- if (!isDirectory &&
693
- verdict.layer !== "pilens" &&
694
- isTrackedAndRescued(resolved)) {
695
- return false;
696
- }
697
- return true;
698
- },
699
- };
700
- }
701
- export function createProjectIgnoreMatcher(rootDir, extraPatterns = [], globalPatterns = []) {
702
- const resolvedRoot = resolveGitIgnoreRoot(rootDir);
703
- // Precedence is gitignore order: LATER patterns override earlier ones. So
704
- // global (lowest) → project .gitignore → project .pi-lens.json (highest),
705
- // which lets a project `!negation` re-include a globally-ignored path (#252).
706
- // Each layer is tagged (#703) so `isIgnored` can tell a git-emulating match
707
- // (`global`/`gitignore` — subject to "a tracked file is never ignored")
708
- // apart from pi-lens-native intent (`pilens` — excludes regardless).
709
- const patterns = [
710
- ...parseGitignoreContent(globalPatterns.join("\n"), "global"),
711
- ...readGitignorePatterns(resolvedRoot, "gitignore"),
712
- ...parseGitignoreContent(extraPatterns.join("\n"), "pilens"),
713
- ];
714
- return buildProjectIgnoreMatcher(resolvedRoot, patterns);
715
- }
716
- const projectIgnoreMatcherCache = new Map();
717
- /**
718
- * Nested ignore sources are checked at most once per root per cadence window.
719
- * Sourced from the shared leaf (`freshness-cadence.ts`) rather than owning the
720
- * value: `project-lens-config.ts`'s no-config discovery cache (#2483 round 2)
721
- * needs the same cadence and cannot import it FROM here, because this module
722
- * already imports `project-lens-config.ts` (the `clients/` acyclic-imports
723
- * rule would reject the reverse edge). Re-exported under this name so the
724
- * existing test imports (`tests/clients/project-ignore-freshness.test.ts` and
725
- * siblings) are unaffected.
726
- */
727
- export const PROJECT_IGNORE_FRESHNESS_CADENCE_MS = FRESHNESS_CADENCE_MS;
728
- function fileFreshnessSignature(filePath) {
729
- try {
730
- const stat = fs.statSync(filePath);
731
- return { mtimeMs: stat.mtimeMs, size: stat.size };
732
- }
733
- catch {
734
- return { mtimeMs: -1, size: -1 };
735
- }
736
- }
737
- function globalConfigSignature() {
738
- return fileFreshnessSignature(getPiLensGlobalConfigPath());
739
- }
740
- function gitignoreSignature(rootDir) {
741
- return fileFreshnessSignature(path.join(rootDir, ".gitignore"));
742
- }
743
- function hasIgnoreSourceDrift(sources) {
744
- return sources.some((source) => {
745
- const current = fileFreshnessSignature(source.path);
746
- return current.mtimeMs !== source.mtimeMs || current.size !== source.size;
747
- });
748
- }
749
- /**
750
- * The project config file found by the same upward walk as the loader. Cache
751
- * invalidation must track the actual file found, not only a file directly under
752
- * the git root: nested worktrees/submodules can legitimately inherit a
753
- * `.pi-lens.json` from a parent directory.
754
- */
755
- function lensConfigInfo(rootDir) {
756
- const info = findPiLensProjectConfig(rootDir);
757
- return info
758
- ? { info, path: info.path, mtimeMs: info.mtimeMs, size: info.size }
759
- : { info, path: undefined, mtimeMs: -1, size: -1 };
760
- }
761
- export function getProjectIgnoreMatcher(rootDir) {
762
- const resolvedRoot = resolveGitIgnoreRoot(rootDir);
763
- const gitignoreSig = gitignoreSignature(resolvedRoot);
764
- const lensConfig = lensConfigInfo(resolvedRoot);
765
- const globalSig = globalConfigSignature();
766
- const cached = projectIgnoreMatcherCache.get(resolvedRoot);
767
- // A path can be discovered during the previous matcher lookup. Publish only
768
- // previously unseen sources so a walk cannot replace a pre-edit baseline.
769
- //
770
- // This runs BEFORE the sweep below, and the order is load-bearing. A nested
771
- // source can only be published on a call AFTER the one that consumed it.
772
- // With the publish second, the sweep never saw a source during the window in
773
- // which it was discovered, yet still reset `lastIgnoreFreshnessCheckMs`, so
774
- // the first sweep that could see it ran a FULL cadence later. Pickup was up
775
- // to 2x cadence, not 1x: measured stale at 2 s and 3 s, fresh at 4 s. The
776
- // baseline is protected by the `known` set, not by the ordering, so moving
777
- // the publish earlier cannot let a walk overwrite a pre-edit baseline.
778
- if (cached) {
779
- const known = new Set(cached.ignoreSources.map((source) => source.path));
780
- for (const source of cached.matcher.getConsumedIgnoreSources()) {
781
- if (!known.has(source.path))
782
- cached.ignoreSources.push(source);
783
- }
784
- }
785
- if (cached &&
786
- Date.now() - cached.lastIgnoreFreshnessCheckMs >=
787
- PROJECT_IGNORE_FRESHNESS_CADENCE_MS) {
788
- cached.lastIgnoreFreshnessCheckMs = Date.now();
789
- if (hasIgnoreSourceDrift(cached.ignoreSources)) {
790
- for (const source of cached.ignoreSources) {
791
- if (hasIgnoreSourceDrift([source])) {
792
- const sourceIndex = cached.ignoreSources.findIndex((cachedSource) => cachedSource.path === source.path);
793
- invalidateProjectIgnoreMatcherForPath(source.path);
794
- cached.matcher.refreshConsumedIgnoreSource(source.path);
795
- const refreshedSource = cached.matcher
796
- .getConsumedIgnoreSources()
797
- .find((current) => current.path === source.path);
798
- if (sourceIndex !== -1 && refreshedSource !== undefined) {
799
- cached.ignoreSources.splice(sourceIndex, 1, refreshedSource);
800
- }
801
- }
802
- }
803
- }
804
- }
805
- if (cached?.gitignoreMtimeMs === gitignoreSig.mtimeMs &&
806
- cached?.gitignoreSize === gitignoreSig.size &&
807
- cached?.lensConfigPath === lensConfig.path &&
808
- cached?.lensConfigMtimeMs === lensConfig.mtimeMs &&
809
- cached?.lensConfigSize === lensConfig.size &&
810
- cached?.globalConfigMtimeMs === globalSig.mtimeMs &&
811
- cached?.globalConfigSize === globalSig.size) {
812
- return cached.matcher;
813
- }
814
- // Load both configs fresh on cache miss. On a cache HIT (the common case)
815
- // none of this runs — the only per-call cost is the size:mtimeMs stats above
816
- // (size is free from the same stat). The project loader is itself
817
- // size:mtimeMs-cached; the global loader re-parses, but only here on miss
818
- // (when some tracked signature changed).
819
- const projectConfig = loadPiLensProjectConfig(resolvedRoot, lensConfig.info);
820
- const matcher = createProjectIgnoreMatcher(resolvedRoot, projectConfig.ignore, getGlobalIgnorePatterns());
821
- projectIgnoreMatcherCache.set(resolvedRoot, {
822
- ignoreSources: [...matcher.getConsumedIgnoreSources()],
823
- lastIgnoreFreshnessCheckMs: Date.now(),
824
- gitignoreMtimeMs: gitignoreSig.mtimeMs,
825
- gitignoreSize: gitignoreSig.size,
826
- lensConfigPath: lensConfig.path,
827
- lensConfigMtimeMs: lensConfig.mtimeMs,
828
- lensConfigSize: lensConfig.size,
829
- globalConfigMtimeMs: globalSig.mtimeMs,
830
- globalConfigSize: globalSig.size,
831
- matcher,
832
- });
833
- return matcher;
834
- }
835
- /**
836
- * Invalidate the cached matcher state affected by a written `.gitignore`.
837
- *
838
- * Root changes discard the whole matcher because they change its base pattern
839
- * set. Nested changes evict only verdicts in that directory's subtree; the
840
- * matcher and compiled-glob memo remain reusable for unrelated trees.
841
- */
842
- export function invalidateProjectIgnoreMatcherForPath(filePath) {
843
- const resolvedPath = path.resolve(filePath);
844
- if (path.basename(resolvedPath).toLowerCase() !== ".gitignore")
845
- return;
846
- for (const [cachedRoot, cached] of projectIgnoreMatcherCache) {
847
- if (!isUnderDir(resolvedPath, cachedRoot))
848
- continue;
849
- if (normalizeFilePath(resolvedPath) ===
850
- normalizeFilePath(path.join(cachedRoot, ".gitignore"))) {
851
- projectIgnoreMatcherCache.delete(cachedRoot);
852
- continue;
853
- }
854
- cached.matcher.invalidateSubtree(path.dirname(resolvedPath));
855
- }
856
- }
857
- export function isPathIgnoredByProject(filePath, rootDir, isDirectory = false) {
858
- return getProjectIgnoreMatcher(rootDir).isIgnored(filePath, isDirectory);
859
- }
860
- /**
861
- * "Is this a project-source path pi-lens's bookkeeping should care about" —
862
- * the `isPathIgnoredByProject` + `isExternalOrVendorFile` pair, previously
863
- * hand-duplicated at each of its 2 call sites (`registerReadBridge` and
864
- * `registerMutationBridge` in `index.ts`, both #2423). Consolidated here
865
- * (#2450 review round 2, F4) when a THIRD call site — `tools/lsp-navigation.ts`
866
- * threading the same gate onto its directly-threaded `LspMutationContext`, so
867
- * the direct LSP-mutation path and the mutation-bridge fallback path apply
868
- * the identical gate instead of the fallback silently being narrower. A
869
- * caller still layers its own `no-read-guard`-style flag check on top; that
870
- * flag has no file path to check against, so it stays outside this helper.
871
- */
872
- export function isRecordableProjectPath(filePath, projectRoot) {
873
- if (isPathIgnoredByProject(filePath, projectRoot, false))
874
- return false;
875
- if (isExternalOrVendorFile(filePath, projectRoot))
876
- return false;
877
- return true;
878
- }
879
- const projectIgnoreGlobsCache = new Map();
880
- export function getProjectIgnoreGlobs(rootDir) {
881
- const resolvedRoot = path.resolve(rootDir);
882
- const signature = gitignoreSignature(resolvedRoot);
883
- const cached = projectIgnoreGlobsCache.get(resolvedRoot);
884
- if (cached &&
885
- cached.mtimeMs === signature.mtimeMs &&
886
- cached.size === signature.size) {
887
- return cached.globs;
888
- }
889
- const globs = readGitignorePatterns(resolvedRoot)
890
- .filter((pattern) => !pattern.negated)
891
- .flatMap((pattern) => expandGitignorePattern(pattern));
892
- projectIgnoreGlobsCache.set(resolvedRoot, { ...signature, globs });
893
- return globs;
894
- }
895
- /**
896
- * Read simple directory-name entries from a root .gitignore.
897
- *
898
- * Prefer createProjectIgnoreMatcher() for path-aware gitignore matching. This
899
- * helper is kept for callers/tests that only need simple directory names.
900
- */
901
- export function readGitignoreDirs(rootDir) {
902
- return readGitignorePatterns(rootDir)
903
- .filter((entry) => !entry.negated &&
904
- !entry.pattern.includes("*") &&
905
- !entry.pattern.includes("?") &&
906
- !entry.pattern.includes("[") &&
907
- !entry.pattern.includes("/"))
908
- .map((entry) => entry.pattern);
909
- }
910
- function globToRegExp(glob) {
911
- // Directory names use the same `*`-only dialect as read-guard exemptions.
912
- // Collapse adjacent stars before compiling to avoid nullable-group
913
- // backtracking on a non-matching name (#2622).
914
- const escaped = glob
915
- .replace(/\*+/g, "*")
916
- .replace(/[.+^${}()|[\]\\]/g, "\\$&")
917
- .replace(/\*/g, ".*")
918
- .replace(/\?/g, ".");
919
- return new RegExp(`^${escaped}$`, "i");
920
- }
921
- /**
922
- * Match directory name against exclusion patterns.
923
- * Supports exact names and lightweight glob patterns (for example `*.dSYM`).
924
- */
925
- export function isExcludedDirName(dirName, extraPatterns = []) {
926
- const candidate = dirName.trim();
927
- if (!candidate)
928
- return false;
929
- const patterns = [...EXCLUDED_DIRS, ...extraPatterns]
930
- .map((p) => p.trim())
931
- .filter((p) => p.length > 0);
932
- const candidateLower = candidate.toLowerCase();
933
- for (const pattern of patterns) {
934
- const patLower = pattern.toLowerCase();
935
- if (!patLower.includes("*") && !patLower.includes("?")) {
936
- if (candidateLower === patLower)
937
- return true;
938
- continue;
939
- }
940
- if (globToRegExp(pattern).test(candidate))
941
- return true;
942
- }
943
- return false;
944
- }
945
- /**
946
- * Convert excluded directory names into glob patterns used by scanners.
947
- */
948
- export function getExcludedDirGlobs() {
949
- return EXCLUDED_DIRS.map((dir) => `**/${dir}/**`);
950
- }
951
- /**
952
- * Shared Knip ignore patterns derived from central exclusions.
953
- */
954
- export function getKnipIgnorePatterns() {
955
- return [
956
- ...getExcludedDirGlobs(),
957
- "**/*.test.ts",
958
- "**/*.test.tsx",
959
- "**/*.test.js",
960
- "**/*.test.jsx",
961
- "**/*.spec.ts",
962
- "**/*.spec.tsx",
963
- "**/*.spec.js",
964
- "**/*.spec.jsx",
965
- "**/*.poc.test.ts",
966
- "**/*.poc.test.tsx",
967
- "**/__tests__/**",
968
- "**/tests/**",
969
- ];
970
- }
971
- /**
972
- * Spawn a command and detect whether it modified a file on disk.
973
- * Returns 1 if the file content changed after the command ran, 0 otherwise.
974
- * Useful for auto-fix tools (ESLint, Stylelint, RuboCop, etc.).
975
- */
976
- export async function detectFileChangedAfterCommand(filePath, command, args, cwd, ignoreStatuses = []) {
977
- let before = "";
978
- try {
979
- before = fs.readFileSync(filePath, "utf-8");
980
- }
981
- catch {
982
- return 0;
983
- }
984
- // #1995: a command cooling down after a spawn timeout must not be handed
985
- // a second budget - autofix is one of the lanes that paid twice for a
986
- // wedged .cmd shim. Return "no fix applied" (an honest not-checked).
987
- if (isInSpawnTimeoutCooldown(command))
988
- return 0;
989
- const result = await safeSpawnAsync(command, args, {
990
- timeout: 30000,
991
- cwd,
992
- });
993
- if (result.error)
994
- return 0;
995
- if (result.failure === "timeout") {
996
- noteSpawnTimeout({
997
- tool: path.basename(command).replace(/\.[^.]+$/, ""),
998
- command,
999
- phase: "autofix",
1000
- durationMs: 30000,
1001
- teardown: result.timeoutTeardown,
1002
- });
1003
- return 0;
1004
- }
1005
- if (result.status !== 0 && !ignoreStatuses.includes(result.status ?? -1)) {
1006
- return 0;
1007
- }
1008
- try {
1009
- const after = fs.readFileSync(filePath, "utf-8");
1010
- return before !== after ? 1 : 0;
1011
- }
1012
- catch {
1013
- return 0;
1014
- }
1015
- }
1016
- /**
1017
- * Check if file path is a test/fixture/mock file.
1018
- * Used by secrets scanner, rate command, and dispatch runners
1019
- * to skip these files (false positives on fake credentials, etc).
1020
- *
1021
- * Delegate naming/directory classification to file-role (#2928). Fixtures,
1022
- * mocks and test helpers remain this skip gate's separate policy.
1023
- */
1024
- export function isTestFile(filePath) {
1025
- if (detectFileRole(filePath) === "test")
1026
- return true;
1027
- const normalized = filePath.replace(/\\/g, "/");
1028
- return (normalized.includes("test-utils") ||
1029
- normalized.startsWith("test-") ||
1030
- normalized.includes(".fixture.") ||
1031
- normalized.includes(".mock."));
1032
- }