pi-lens 3.8.73 → 4.0.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 (346) hide show
  1. package/CHANGELOG.md +2614 -12
  2. package/README.md +50 -21
  3. package/dist/clients/actionable-warnings.js +73 -18
  4. package/dist/clients/agent-behavior-client.js +21 -4
  5. package/dist/clients/ast-grep-client.js +68 -16
  6. package/dist/clients/ast-grep-types.js +0 -1
  7. package/dist/clients/ast-grep-yaml-synth.js +37 -10
  8. package/dist/clients/atomic-write-staging.js +63 -0
  9. package/dist/clients/atomic-write.js +116 -16
  10. package/dist/clients/bash-file-access.js +193 -23
  11. package/dist/clients/biome-client.js +29 -25
  12. package/dist/clients/bootstrap.js +11 -2
  13. package/dist/clients/bounded-cache.js +34 -0
  14. package/dist/clients/bounded-pid-file-lock.js +192 -0
  15. package/dist/clients/bus-events-logger.js +5 -1
  16. package/dist/clients/bus-publish.js +10 -3
  17. package/dist/clients/cache/rule-cache.js +89 -6
  18. package/dist/clients/cache-manager.js +97 -9
  19. package/dist/clients/cache-observability.js +498 -0
  20. package/dist/clients/call-graph.js +460 -108
  21. package/dist/clients/cascade-logger.js +5 -1
  22. package/dist/clients/child-unref.js +85 -0
  23. package/dist/clients/codebase-model.js +52 -23
  24. package/dist/clients/collateral-test-role.js +40 -0
  25. package/dist/clients/complexity-client.js +6 -8
  26. package/dist/clients/console-guard-install.js +14 -0
  27. package/dist/clients/cooperative-budget.js +42 -0
  28. package/dist/clients/dead-code-client.js +2 -1
  29. package/dist/clients/debug-handles.js +206 -0
  30. package/dist/clients/debug-heap.js +167 -0
  31. package/dist/clients/degradation-ledger.js +153 -0
  32. package/dist/clients/dependency-checker.js +466 -63
  33. package/dist/clients/diagnostic-dispositions.js +83 -13
  34. package/dist/clients/diagnostics-publish.js +10 -3
  35. package/dist/clients/dispatch/auxiliary-lsp.js +34 -0
  36. package/dist/clients/dispatch/dispatcher.js +71 -13
  37. package/dist/clients/dispatch/fact-store.js +11 -0
  38. package/dist/clients/dispatch/facts/function-facts.js +37 -7
  39. package/dist/clients/dispatch/facts/import-facts.js +108 -119
  40. package/dist/clients/dispatch/facts/tree-sitter-facts.js +12 -12
  41. package/dist/clients/dispatch/facts/try-catch-facts.js +13 -0
  42. package/dist/clients/dispatch/indent-detect.js +35 -0
  43. package/dist/clients/dispatch/inline-suppressions.js +17 -8
  44. package/dist/clients/dispatch/integration.js +1094 -611
  45. package/dist/clients/dispatch/lazy.js +14 -0
  46. package/dist/clients/dispatch/plan.js +11 -1
  47. package/dist/clients/dispatch/rule-id-normalize.js +50 -0
  48. package/dist/clients/dispatch/rule-policy.js +135 -0
  49. package/dist/clients/dispatch/rules/async-noise.js +1 -0
  50. package/dist/clients/dispatch/rules/unsafe-boundary.js +7 -0
  51. package/dist/clients/dispatch/runners/ast-grep-napi.js +47 -6
  52. package/dist/clients/dispatch/runners/biome-check.js +5 -9
  53. package/dist/clients/dispatch/runners/detekt.js +3 -2
  54. package/dist/clients/dispatch/runners/hadolint.js +2 -1
  55. package/dist/clients/dispatch/runners/helm-lint.js +154 -0
  56. package/dist/clients/dispatch/runners/htmlhint.js +3 -2
  57. package/dist/clients/dispatch/runners/index.js +5 -1
  58. package/dist/clients/dispatch/runners/lsp.js +14 -6
  59. package/dist/clients/dispatch/runners/markdownlint.js +4 -9
  60. package/dist/clients/dispatch/runners/psscriptanalyzer.js +10 -1
  61. package/dist/clients/dispatch/runners/pyright.js +9 -5
  62. package/dist/clients/dispatch/runners/ruff.js +4 -8
  63. package/dist/clients/dispatch/runners/shellcheck.js +2 -3
  64. package/dist/clients/dispatch/runners/shfmt.js +2 -3
  65. package/dist/clients/dispatch/runners/spotbugs.js +2 -1
  66. package/dist/clients/dispatch/runners/taplo.js +2 -1
  67. package/dist/clients/dispatch/runners/terragrunt.js +163 -0
  68. package/dist/clients/dispatch/runners/tflint.js +37 -5
  69. package/dist/clients/dispatch/runners/tree-sitter.js +155 -166
  70. package/dist/clients/dispatch/runners/trivy-config.js +13 -7
  71. package/dist/clients/dispatch/runners/utils/lazy-installer.js +3 -0
  72. package/dist/clients/dispatch/runners/utils/runner-helpers.js +284 -34
  73. package/dist/clients/dispatch/runners/utils/spawn-outcome.js +22 -0
  74. package/dist/clients/dispatch/runners/yaml-rule-parser.js +5 -4
  75. package/dist/clients/disposition-publish.js +10 -3
  76. package/dist/clients/durable-store.js +97 -0
  77. package/dist/clients/event-loop-monitor.js +94 -3
  78. package/dist/clients/extension-log.js +139 -0
  79. package/dist/clients/extension-mode.js +73 -0
  80. package/dist/clients/feature-hints.js +53 -7
  81. package/dist/clients/file-kinds.js +143 -31
  82. package/dist/clients/file-role.js +18 -3
  83. package/dist/clients/file-utils.js +56 -34
  84. package/dist/clients/fix-worklog.js +14 -2
  85. package/dist/clients/format-events-publish.js +16 -3
  86. package/dist/clients/format-service.js +24 -8
  87. package/dist/clients/formatters-lazy.js +8 -0
  88. package/dist/clients/formatters.js +358 -61
  89. package/dist/clients/generated-artifacts.js +169 -15
  90. package/dist/clients/git-guard.js +681 -11
  91. package/dist/clients/git-tracked-ignore.js +4 -0
  92. package/dist/clients/go-client.js +2 -1
  93. package/dist/clients/govulncheck-client.js +8 -0
  94. package/dist/clients/grammar-source.js +12 -4
  95. package/dist/clients/gzip-stage-write.js +102 -0
  96. package/dist/clients/host-ports.js +31 -0
  97. package/dist/clients/installer/index.js +733 -213
  98. package/dist/clients/instance-reaper.js +142 -172
  99. package/dist/clients/jscpd-client.js +31 -54
  100. package/dist/clients/knip-client.js +78 -36
  101. package/dist/clients/language-policy.js +14 -2
  102. package/dist/clients/language-profile.js +72 -77
  103. package/dist/clients/latency-logger.js +28 -16
  104. package/dist/clients/lens-config.js +140 -166
  105. package/dist/clients/lens-engine.js +124 -21
  106. package/dist/clients/lens-events.js +27 -4
  107. package/dist/clients/lens-flag-registry.js +293 -0
  108. package/dist/clients/lens-map.js +96 -26
  109. package/dist/clients/live-bus-emitter.js +30 -0
  110. package/dist/clients/log-cleanup.js +8 -18
  111. package/dist/clients/lsp/cascade-tier.js +23 -3
  112. package/dist/clients/lsp/client.js +566 -57
  113. package/dist/clients/lsp/config.js +74 -10
  114. package/dist/clients/lsp/diagnostic-binding.js +86 -0
  115. package/dist/clients/lsp/edits.js +1012 -121
  116. package/dist/clients/lsp/index.js +1840 -803
  117. package/dist/clients/lsp/language.js +4 -1
  118. package/dist/clients/lsp/launch.js +40 -32
  119. package/dist/clients/lsp/path-utils.js +1 -1
  120. package/dist/clients/lsp/ruby-drive-dirs.js +83 -0
  121. package/dist/clients/lsp/server.js +279 -60
  122. package/dist/clients/lsp/workspace-diagnostics-cache.js +28 -4
  123. package/dist/clients/lsp-document-symbols.js +112 -0
  124. package/dist/clients/lsp-lazy.js +8 -0
  125. package/dist/clients/lsp-mutation.js +248 -0
  126. package/dist/clients/mcp/analyze.js +128 -36
  127. package/dist/clients/mcp/ipc.js +157 -24
  128. package/dist/clients/mcp/review.js +36 -3
  129. package/dist/clients/mcp/session.js +216 -8
  130. package/dist/clients/memory-sampler.js +115 -0
  131. package/dist/clients/metrics-client.js +2 -1
  132. package/dist/clients/metrics-history.js +2 -1
  133. package/dist/clients/module-report-lsp.js +5 -0
  134. package/dist/clients/module-report.js +267 -82
  135. package/dist/clients/ndjson-logger.js +334 -103
  136. package/dist/clients/opengrep-client.js +1 -1
  137. package/dist/clients/partial-edit-apply.js +120 -5
  138. package/dist/clients/path-keyed-map.js +76 -0
  139. package/dist/clients/path-utils.js +141 -5
  140. package/dist/clients/performance-report.js +327 -0
  141. package/dist/clients/pipeline.js +54 -13
  142. package/dist/clients/print-mode.js +21 -0
  143. package/dist/clients/project-changes.js +117 -4
  144. package/dist/clients/project-diagnostics/cache.js +3 -2
  145. package/dist/clients/project-diagnostics/extractors.js +26 -115
  146. package/dist/clients/project-diagnostics/fresh-fetch.js +149 -19
  147. package/dist/clients/project-diagnostics/runner-adapters/call-graph-impact.js +117 -0
  148. package/dist/clients/project-diagnostics/runner-adapters/runner-findings.js +37 -5
  149. package/dist/clients/project-diagnostics/scanner.js +268 -128
  150. package/dist/clients/project-lens-config.js +138 -34
  151. package/dist/clients/project-report.js +64 -25
  152. package/dist/clients/project-scale.js +8 -10
  153. package/dist/clients/project-snapshot-persist-worker.js +6 -0
  154. package/dist/clients/project-snapshot.js +767 -8
  155. package/dist/clients/project-trust.js +181 -0
  156. package/dist/clients/quiet-window.js +27 -5
  157. package/dist/clients/read-bridge.js +147 -0
  158. package/dist/clients/read-expansion.js +22 -12
  159. package/dist/clients/read-guard-logger.js +159 -1
  160. package/dist/clients/read-guard-tool-lines.js +150 -29
  161. package/dist/clients/read-guard.js +262 -3
  162. package/dist/clients/redact/secrets.js +449 -0
  163. package/dist/clients/resource-sampler.js +144 -39
  164. package/dist/clients/reverse-deps.js +48 -0
  165. package/dist/clients/review-graph/builder.js +2570 -326
  166. package/dist/clients/review-graph/git-identity.js +2 -1
  167. package/dist/clients/review-graph/import-resolvers.js +21 -10
  168. package/dist/clients/review-graph/persist-worker.js +10 -0
  169. package/dist/clients/review-graph/query.js +5 -0
  170. package/dist/clients/review-graph/shared-extraction-ir.js +90 -0
  171. package/dist/clients/review-graph/symbol-id.js +46 -0
  172. package/dist/clients/review-graph/tsconfig-paths.js +57 -6
  173. package/dist/clients/review-graph/workspace-modules.js +51 -3
  174. package/dist/clients/review-graph-logger.js +53 -0
  175. package/dist/clients/ruff-client.js +27 -44
  176. package/dist/clients/runtime-agent-end.js +111 -75
  177. package/dist/clients/runtime-context.js +36 -12
  178. package/dist/clients/runtime-coordinator.js +76 -8
  179. package/dist/clients/runtime-session.js +799 -137
  180. package/dist/clients/runtime-tool-call.js +117 -62
  181. package/dist/clients/runtime-tool-result.js +218 -23
  182. package/dist/clients/runtime-turn.js +284 -40
  183. package/dist/clients/rust-client.js +2 -1
  184. package/dist/clients/safe-spawn.js +873 -71
  185. package/dist/clients/security-scan-client.js +2 -1
  186. package/dist/clients/session-start-observability.js +15 -0
  187. package/dist/clients/session-state-store.js +5 -3
  188. package/dist/clients/sessionstart-logger.js +18 -0
  189. package/dist/clients/sg-runner.js +284 -159
  190. package/dist/clients/slow-fs.js +2 -1
  191. package/dist/clients/smells-rollup.js +224 -0
  192. package/dist/clients/source-filter.js +231 -43
  193. package/dist/clients/source-walker.js +66 -10
  194. package/dist/clients/startup-scan.js +15 -16
  195. package/dist/clients/startup-timing.js +9 -0
  196. package/dist/clients/test-runner-client.js +38 -8
  197. package/dist/clients/todo-scanner.js +30 -3
  198. package/dist/clients/tool-event.js +35 -0
  199. package/dist/clients/tool-policy.js +388 -39
  200. package/dist/clients/tool-render.js +155 -0
  201. package/dist/clients/tree-sitter-cache.js +153 -140
  202. package/dist/clients/tree-sitter-client.js +1722 -80
  203. package/dist/clients/tree-sitter-logger.js +64 -1
  204. package/dist/clients/tree-sitter-query-loader.js +117 -12
  205. package/dist/clients/tree-sitter-shared.js +48 -19
  206. package/dist/clients/tree-sitter-symbol-extractor.js +115 -11
  207. package/dist/clients/user-notify.js +51 -0
  208. package/dist/clients/vanished-instance-marker.js +57 -0
  209. package/dist/clients/warm-attach.js +33 -13
  210. package/dist/clients/widget-state.js +342 -49
  211. package/dist/clients/word-index-logger.js +44 -0
  212. package/dist/clients/word-index.js +612 -68
  213. package/dist/clients/workspace-topology.js +100 -7
  214. package/dist/index.js +65923 -47161
  215. package/dist/mcp/analyze-cli.js +185 -29
  216. package/dist/mcp/cli.js +110 -0
  217. package/dist/mcp/server.js +272 -50
  218. package/dist/tools/ast-grep-search.js +93 -27
  219. package/dist/tools/lens-diagnostics.js +247 -41
  220. package/dist/tools/lsp-diagnostics.js +153 -40
  221. package/dist/tools/lsp-navigation.js +51 -31
  222. package/dist/tools/module-report.js +9 -0
  223. package/dist/tools/symbol-search.js +21 -2
  224. package/docs/agent-guide.md +247 -0
  225. package/docs/agent-tools.md +21 -10
  226. package/docs/analysisall.md +192 -0
  227. package/docs/api-ports-inventory.md +165 -0
  228. package/docs/ast-grep_rules_catalog.md +5 -2
  229. package/docs/astplayground.md +3 -4
  230. package/docs/audit1.md +5 -5
  231. package/docs/durable-store-audit-1202.md +32 -0
  232. package/docs/environment-variables.md +197 -11
  233. package/docs/fable.md +27 -0
  234. package/docs/features.md +35 -5
  235. package/docs/globalconfig.md +101 -5
  236. package/docs/language-coverage.md +6 -5
  237. package/docs/lsp-capability-matrix.md +2 -2
  238. package/docs/mcp.md +54 -20
  239. package/docs/servercapabilities.md +7 -4
  240. package/docs/settings.md +192 -0
  241. package/docs/tools.md +18 -1
  242. package/docs/tree-sitter_rules_catalog.md +11 -31
  243. package/docs/usage.md +31 -0
  244. package/package.json +139 -138
  245. package/rules/ast-grep-rules/rule-tests/hardcoded-url-js-test.yml +1 -0
  246. package/rules/ast-grep-rules/rule-tests/hardcoded-url-test.yml +2 -0
  247. package/rules/ast-grep-rules/rule-tests/no-bare-except-test.yml +49 -0
  248. package/rules/ast-grep-rules/rule-tests/no-bare-host-path-in-win32-branch-test.yml +87 -0
  249. package/rules/ast-grep-rules/rule-tests/no-case-declarations-js-test.yml +10 -0
  250. package/rules/ast-grep-rules/rule-tests/no-case-declarations-test.yml +10 -0
  251. package/rules/ast-grep-rules/rule-tests/no-javascript-url-js-test.yml +10 -0
  252. package/rules/ast-grep-rules/rule-tests/no-javascript-url-test.yml +10 -0
  253. package/rules/ast-grep-rules/rule-tests/no-nested-links-test.yml +11 -1
  254. package/rules/ast-grep-rules/rule-tests/no-raw-json-store-write-test.yml +17 -0
  255. package/rules/ast-grep-rules/rule-tests/no-win32-isabsolute-for-qualification-test.yml +16 -0
  256. package/rules/ast-grep-rules/rule-tests/strict-equality-js-test.yml +3 -0
  257. package/rules/ast-grep-rules/rule-tests/strict-equality-test.yml +3 -0
  258. package/rules/ast-grep-rules/rule-tests/strict-inequality-js-test.yml +3 -0
  259. package/rules/ast-grep-rules/rule-tests/strict-inequality-test.yml +4 -0
  260. package/rules/ast-grep-rules/rules/hardcoded-url-js.yml +22 -4
  261. package/rules/ast-grep-rules/rules/hardcoded-url.yml +22 -4
  262. package/rules/ast-grep-rules/rules/no-bare-except.yml +3 -15
  263. package/rules/ast-grep-rules/rules/no-bare-host-path-in-win32-branch.yml +25 -0
  264. package/rules/ast-grep-rules/rules/no-case-declarations-js.yml +4 -3
  265. package/rules/ast-grep-rules/rules/no-case-declarations.yml +4 -3
  266. package/rules/ast-grep-rules/rules/no-console-except-error-js.yml +10 -0
  267. package/rules/ast-grep-rules/rules/no-console-except-error.yml +10 -0
  268. package/rules/ast-grep-rules/rules/no-javascript-url-js.yml +42 -6
  269. package/rules/ast-grep-rules/rules/no-javascript-url.yml +42 -6
  270. package/rules/ast-grep-rules/rules/no-nested-links.yml +7 -0
  271. package/rules/ast-grep-rules/rules/no-raw-json-store-write.yml +30 -0
  272. package/rules/ast-grep-rules/rules/no-win32-isabsolute-for-qualification.yml +23 -0
  273. package/rules/ast-grep-rules/rules/strict-equality-js.yml +14 -1
  274. package/rules/ast-grep-rules/rules/strict-equality.yml +14 -1
  275. package/rules/ast-grep-rules/rules/strict-inequality-js.yml +14 -1
  276. package/rules/ast-grep-rules/rules/strict-inequality.yml +14 -1
  277. package/rules/tree-sitter-queries/cpp/no-memset-sensitive-data.yml +9 -3
  278. package/rules/tree-sitter-queries/cpp/no-scoped-lock-without-args.yml +6 -6
  279. package/rules/tree-sitter-queries/css/calc-spacing.yml +8 -6
  280. package/rules/tree-sitter-queries/go/go-mutex-copy.yml +21 -18
  281. package/rules/tree-sitter-queries/go/go-shared-map-write-goroutine.yml +3 -3
  282. package/rules/tree-sitter-queries/java/infinite-loop-java.yml +3 -3
  283. package/rules/tree-sitter-queries/java/junit-call-super.yml +6 -4
  284. package/rules/tree-sitter-queries/java/no-double-checked-locking.yml +10 -8
  285. package/rules/tree-sitter-queries/java/no-field-shadowing.yml +1 -1
  286. package/rules/tree-sitter-queries/java/prepared-statement-valid-indices.yml +2 -3
  287. package/rules/tree-sitter-queries/java/resources-closed.yml +2 -2
  288. package/rules/tree-sitter-queries/java/springboot-default-package.yml +6 -3
  289. package/rules/tree-sitter-queries/java/switch-fall-through.yml +6 -4
  290. package/rules/tree-sitter-queries/java/switch-non-case-labels.yml +4 -3
  291. package/rules/tree-sitter-queries/java/tests-include-assertions.yml +6 -5
  292. package/rules/tree-sitter-queries/javascript/switch-case-termination-js.yml +5 -8
  293. package/rules/tree-sitter-queries/javascript/switch-non-case-labels.yml +3 -2
  294. package/rules/tree-sitter-queries/kotlin/prepared-statement-indices.yml +9 -5
  295. package/rules/tree-sitter-queries/php/this-in-static-context.yml +5 -5
  296. package/rules/tree-sitter-queries/python/exit-signature-check.yml +2 -9
  297. package/rules/tree-sitter-queries/python/in-operator-unsupported.yml +3 -4
  298. package/rules/tree-sitter-queries/python/no-super-torchscript.yml +4 -8
  299. package/rules/tree-sitter-queries/python/notimplemented-boolean-context.yml +1 -5
  300. package/rules/tree-sitter-queries/python/python-empty-except.yml +1 -1
  301. package/rules/tree-sitter-queries/python/return-in-init.yml +0 -2
  302. package/rules/tree-sitter-queries/python/yield-return-outside-function.yml +0 -3
  303. package/rules/tree-sitter-queries/ruby/ruby-command-injection.yml +1 -12
  304. package/rules/tree-sitter-queries/ruby/ruby-eval.yml +1 -1
  305. package/rules/tree-sitter-queries/ruby/ruby-insecure-deserialization.yml +4 -4
  306. package/rules/tree-sitter-queries/ruby/ruby-insecure-random.yml +4 -11
  307. package/rules/tree-sitter-queries/ruby/ruby-open-struct.yml +1 -1
  308. package/rules/tree-sitter-queries/ruby/ruby-string-eval.yml +2 -3
  309. package/rules/tree-sitter-queries/ruby/ruby-weak-hash.yml +4 -4
  310. package/rules/tree-sitter-queries/rust/rust-lock-held-across-await.yml +4 -3
  311. package/rules/tree-sitter-queries/tsx/no-nested-links.yml +4 -6
  312. package/rules/tree-sitter-queries/typescript/console-statement.yml +11 -0
  313. package/rules/tree-sitter-queries/typescript/duplicate-function-arg.yml +4 -9
  314. package/rules/tree-sitter-queries/typescript/empty-switch-case.yml +13 -9
  315. package/rules/tree-sitter-queries/typescript/infinite-loop.yml +2 -2
  316. package/rules/tree-sitter-queries/typescript/mixed-async-styles.yml +10 -1
  317. package/rules/tree-sitter-queries/typescript/switch-case-termination.yml +5 -8
  318. package/rules/tree-sitter-queries/typescript/ts-insecure-random.yml +7 -10
  319. package/rules/tree-sitter-queries/typescript/unsafe-regex.yml +4 -2
  320. package/rules/typos/_typos.toml +17 -0
  321. package/scripts/analyze-pi-lens-logs.mjs +55 -2
  322. package/skills/pi-lens-write-tree-sitter-rule/SKILL.md +5 -0
  323. package/dist/clients/ast-grep-parser.js +0 -86
  324. package/dist/clients/config-enabled-shape.js +0 -39
  325. package/dist/clients/lsp/interactive-install.js +0 -367
  326. package/dist/clients/lsp/lsp-index.js +0 -10
  327. package/dist/clients/lsp/server-strategies.js +0 -5
  328. package/dist/clients/project-metadata.js +0 -690
  329. package/dist/clients/source-groups.js +0 -96
  330. package/dist/clients/types.js +0 -11
  331. package/docs/env_variables.md +0 -10
  332. package/rules/tree-sitter-queries/abap-disabled/delete-where.yml +0 -46
  333. package/rules/tree-sitter-queries/cpp/no-confused-move-forward.yml +0 -59
  334. package/rules/tree-sitter-queries/cpp/noexcept-functions.yml +0 -58
  335. package/rules/tree-sitter-queries/java/mockito-initialized.yml +0 -66
  336. package/rules/tree-sitter-queries/java/no-wait-notify-on-thread.yml +0 -58
  337. package/rules/tree-sitter-queries/java/short-circuit-logic.yml +0 -57
  338. package/rules/tree-sitter-queries/java/spring-session-attributes-setcomplete.yml +0 -75
  339. package/rules/tree-sitter-queries/plsql-disabled/delete-update-where.yml +0 -56
  340. package/rules/tree-sitter-queries/plsql-disabled/end-loop-semicolon.yml +0 -51
  341. package/rules/tree-sitter-queries/plsql-disabled/fetch-bulk-collect-limit.yml +0 -47
  342. package/rules/tree-sitter-queries/plsql-disabled/forallsave-exceptions.yml +0 -51
  343. package/rules/tree-sitter-queries/plsql-disabled/nchar-nvarchar2-bytes.yml +0 -54
  344. package/rules/tree-sitter-queries/plsql-disabled/not-null-initialization.yml +0 -59
  345. package/rules/tree-sitter-queries/plsql-disabled/raise-application-error-codes.yml +0 -50
  346. package/rules/tree-sitter-queries/typescript-disabled/ts-path-traversal.yml +0 -71
@@ -45,61 +45,185 @@
45
45
  * - pip packages
46
46
  * - GitHub releases (platform-specific binaries → ~/.pi-lens/bin/)
47
47
  */
48
+ import { logExtension } from "../extension-log.js";
48
49
  import { spawn } from "node:child_process";
49
- import { existsSync, statSync } from "node:fs";
50
+ import { existsSync, statSync, unlinkSync } from "node:fs";
50
51
  import fs from "node:fs/promises";
51
52
  import https from "node:https";
52
53
  import { createRequire } from "node:module";
53
54
  import os from "node:os";
54
55
  import path from "node:path";
56
+ import { BoundedLruCache } from "../bounded-cache.js";
57
+ import { isFullyQualified } from "../path-utils.js";
58
+ import { assertInstallAllowed, projectTrustDenialReason, } from "../project-trust.js";
55
59
  const _installerRequire = createRequire(import.meta.url);
56
60
  import { createGunzip } from "node:zlib";
57
- import { isTestMode } from "../env-utils.js";
61
+ import { logSessionStart } from "../sessionstart-logger.js";
62
+ import { commitDurableStoreAsync } from "../durable-store.js";
58
63
  import { getGlobalPiLensDir } from "../file-utils.js";
59
64
  import { allAvailableGlobalBinDirs, installArgs, pmBinary, resolveNodePackageManager, } from "../package-manager.js";
65
+ import { resetSafeSpawnWindowsCommandCache, safeSpawnAsync, } from "../safe-spawn.js";
60
66
  // Global installation directory for pi-lens tools
61
67
  const TOOLS_DIR = path.join(getGlobalPiLensDir(), "tools");
68
+ const INSTALL_LOCK_PATH = path.join(TOOLS_DIR, ".install.lock");
69
+ const activeInstallLocks = new Set();
70
+ let installLockExitCleanupRegistered = false;
71
+ /**
72
+ * The managed tools tree, for callers that need to tell a path `getToolPath()`
73
+ * returned from the managed install apart from a global/PATH hit (the tool
74
+ * registry is this module's business — don't re-derive `<pi-lens home>/tools`).
75
+ */
76
+ export function getManagedToolsDir() {
77
+ return TOOLS_DIR;
78
+ }
79
+ function isProcessAlive(pid) {
80
+ try {
81
+ process.kill(pid, 0);
82
+ return true;
83
+ }
84
+ catch (error) {
85
+ return error.code === "EPERM";
86
+ }
87
+ }
88
+ async function acquireInstallLock() {
89
+ await fs.mkdir(TOOLS_DIR, { recursive: true });
90
+ // #946 review F2: the waiter's bound must exceed the owner's install bound
91
+ // (PI_LENS_INSTALL_TIMEOUT_MS, default 120s) — a 30s waiter gave up on a
92
+ // legitimate slow install and reported the tool unavailable for the whole
93
+ // session even though it arrived seconds later.
94
+ const timeoutMs = Number(process.env.PI_LENS_INSTALL_LOCK_TIMEOUT_MS) || 150_000;
95
+ const deadline = Date.now() + timeoutMs;
96
+ let lastOwner = "unknown owner";
97
+ while (Date.now() < deadline) {
98
+ try {
99
+ const handle = await fs.open(INSTALL_LOCK_PATH, "wx");
100
+ await handle.writeFile(JSON.stringify({ pid: process.pid, createdAt: Date.now() }));
101
+ await handle.close();
102
+ activeInstallLocks.add(INSTALL_LOCK_PATH);
103
+ if (!installLockExitCleanupRegistered) {
104
+ installLockExitCleanupRegistered = true;
105
+ process.once("exit", () => {
106
+ for (const lockPath of activeInstallLocks) {
107
+ try {
108
+ unlinkSync(lockPath);
109
+ }
110
+ catch {
111
+ // Best effort; the next owner verifies this PID is dead.
112
+ }
113
+ }
114
+ });
115
+ }
116
+ let released = false;
117
+ return {
118
+ release: async () => {
119
+ if (released)
120
+ return;
121
+ released = true;
122
+ activeInstallLocks.delete(INSTALL_LOCK_PATH);
123
+ await fs.rm(INSTALL_LOCK_PATH, { force: true });
124
+ },
125
+ };
126
+ }
127
+ catch (error) {
128
+ if (error.code !== "EEXIST")
129
+ throw error;
130
+ try {
131
+ const owner = JSON.parse(await fs.readFile(INSTALL_LOCK_PATH, "utf8"));
132
+ lastOwner = `pid=${owner.pid} createdAt=${owner.createdAt}`;
133
+ // #946 review F1: PID liveness alone cannot detect a hard-killed
134
+ // owner whose PID Windows has recycled — that lock would poison
135
+ // every future install with a full-timeout wait. A lock older
136
+ // than any legitimate install (owner install bound + slack) is
137
+ // stale regardless of what the PID now points at.
138
+ const maxAgeMs = (Number(process.env.PI_LENS_INSTALL_TIMEOUT_MS) || 120_000) +
139
+ 60_000;
140
+ const expired = Number.isFinite(owner.createdAt) &&
141
+ Date.now() - owner.createdAt > maxAgeMs;
142
+ if (expired ||
143
+ (Number.isInteger(owner.pid) &&
144
+ owner.pid > 0 &&
145
+ !isProcessAlive(owner.pid))) {
146
+ await fs.rm(INSTALL_LOCK_PATH, { force: true });
147
+ continue;
148
+ }
149
+ }
150
+ catch (readError) {
151
+ lastOwner = "unreadable owner";
152
+ // An unreadable/empty lock has no createdAt to age out — fall
153
+ // back to the file's own mtime for the max-age check so it is
154
+ // eventually recoverable (#946 review F1/F6).
155
+ try {
156
+ const stat = await fs.stat(INSTALL_LOCK_PATH);
157
+ const maxAgeMs = (Number(process.env.PI_LENS_INSTALL_TIMEOUT_MS) || 120_000) +
158
+ 60_000;
159
+ if (Date.now() - stat.mtimeMs > maxAgeMs) {
160
+ await fs.rm(INSTALL_LOCK_PATH, { force: true });
161
+ continue;
162
+ }
163
+ }
164
+ catch {
165
+ // stat raced a release — loop and retry acquisition.
166
+ }
167
+ void readError;
168
+ }
169
+ await new Promise((resolve) => setTimeout(resolve, 100));
170
+ }
171
+ }
172
+ return {
173
+ reason: `timed out after ${timeoutMs}ms waiting for shared tools install lock (${lastOwner})`,
174
+ };
175
+ }
62
176
  // Directory for GitHub-downloaded binaries
63
177
  const GITHUB_BIN_DIR = path.join(getGlobalPiLensDir(), "bin");
64
178
  // Debug flag - set via PI_LENS_DEBUG=1 or --debug
65
179
  const DEBUG = process.env.PI_LENS_DEBUG === "1" || process.argv.includes("--debug");
66
- const SESSIONSTART_LOG_DIR = getGlobalPiLensDir();
67
- const SESSIONSTART_LOG = path.join(SESSIONSTART_LOG_DIR, "sessionstart.log");
180
+ /** Test-only platform seam for Windows resource-layout coverage on Linux CI. */
181
+ function installerPlatform() {
182
+ const override = process.env.PI_LENS_TEST_PLATFORM;
183
+ if (override === "win32" || override === "linux") {
184
+ return override;
185
+ }
186
+ return process.platform;
187
+ }
68
188
  /**
69
189
  * Log debug messages only when DEBUG is enabled
70
190
  */
71
191
  function debugLog(...args) {
72
192
  if (DEBUG) {
73
- console.error("[auto-install:debug]", ...args);
74
- }
75
- }
76
- function logSessionStart(msg) {
77
- if (isTestMode()) {
78
- return;
193
+ // #1333: DEBUG gate preserved; sink is extension.log, never the TUI.
194
+ logExtension({
195
+ subsystem: "auto-install",
196
+ level: "debug",
197
+ message: args
198
+ .map((arg) => (typeof arg === "string" ? arg : JSON.stringify(arg)))
199
+ .join(" "),
200
+ });
79
201
  }
80
- const line = `[${new Date().toISOString()}] ${msg}\n`;
81
- void fs
82
- .mkdir(SESSIONSTART_LOG_DIR, { recursive: true })
83
- .then(() => fs.appendFile(SESSIONSTART_LOG, line))
84
- .catch(() => {
85
- // best-effort logging
86
- });
87
202
  }
88
203
  /**
89
204
  * Build a GitHub-release `assetMatch` from a small per-platform table, replacing
90
205
  * the copy-pasted `if (platform === "linux") return arch === "arm64" ? … : …`
91
206
  * ladder that several release entries repeat verbatim. Each platform maps to its
92
207
  * `x64` (default) and optional `arm64` asset substring; a missing platform or
93
- * arch ⇒ unsupported (`undefined`), exactly as the hand-written ladders behaved.
208
+ * arch ⇒ unsupported (`undefined`). Arches outside x64/arm64 (ia32, ppc64, …)
209
+ * are unsupported too — no release entry ships a 32-bit or exotic asset, and
210
+ * handing back the x64 substring there would install an unrunnable binary.
94
211
  */
95
212
  function archAssetMatch(table) {
96
213
  return (platform, arch) => {
97
- const entry = table[platform];
98
- if (!entry)
214
+ if (arch !== "x64" && arch !== "arm64")
99
215
  return undefined;
100
- return arch === "arm64" ? entry.arm64 : entry.x64;
216
+ return table[platform]?.[arch];
101
217
  };
102
218
  }
219
+ // Go-style `<os>_<arch>.zip` release assets, shared verbatim by tflint and
220
+ // terraform-ls — both entries carried byte-identical ladders, down to the asset
221
+ // strings themselves.
222
+ const OS_ARCH_ZIP_ASSETS = {
223
+ linux: { x64: "linux_amd64.zip", arm64: "linux_arm64.zip" },
224
+ darwin: { x64: "darwin_amd64.zip", arm64: "darwin_arm64.zip" },
225
+ win32: { x64: "windows_amd64.zip", arm64: "windows_arm64.zip" },
226
+ };
103
227
  export const TOOLS = [
104
228
  // Core LSP servers
105
229
  {
@@ -257,6 +381,24 @@ export const TOOLS = [
257
381
  packageName: "bash-language-server",
258
382
  binaryName: "bash-language-server",
259
383
  },
384
+ {
385
+ id: "fish-lsp",
386
+ name: "Fish Language Server",
387
+ checkCommand: "fish-lsp",
388
+ checkArgs: ["--version"],
389
+ installStrategy: "npm",
390
+ packageName: "fish-lsp",
391
+ binaryName: "fish-lsp",
392
+ },
393
+ {
394
+ id: "cmake-language-server",
395
+ name: "CMake Language Server",
396
+ checkCommand: "cmake-language-server",
397
+ checkArgs: ["--version"],
398
+ installStrategy: "pip",
399
+ packageName: "cmake-language-server",
400
+ binaryName: "cmake-language-server",
401
+ },
260
402
  {
261
403
  id: "yaml-language-server",
262
404
  name: "YAML Language Server",
@@ -313,6 +455,31 @@ export const TOOLS = [
313
455
  },
314
456
  },
315
457
  },
458
+ {
459
+ id: "helm",
460
+ name: "Helm",
461
+ checkCommand: "helm",
462
+ checkArgs: ["version", "--short"],
463
+ installStrategy: "github",
464
+ binaryName: "helm",
465
+ github: {
466
+ repo: "helm/helm",
467
+ assetMatch: (platform, arch) => {
468
+ // helm publishes per-OS archives: tar.gz for POSIX, zip for Windows.
469
+ const cpu = arch === "arm64" ? "arm64" : "amd64";
470
+ if (platform === "linux")
471
+ return `linux-${cpu}.tar.gz`;
472
+ if (platform === "darwin")
473
+ return `darwin-${cpu}.tar.gz`;
474
+ if (platform === "win32")
475
+ return `windows-${cpu}.zip`;
476
+ return undefined;
477
+ },
478
+ // Release archives nest the executable under an OS/arch directory;
479
+ // the installer searches recursively and adds the Windows suffix.
480
+ binaryInArchive: "helm",
481
+ },
482
+ },
316
483
  {
317
484
  // Opengrep: a single standalone binary per platform on GitHub releases —
318
485
  // no login, no telemetry (the reason for switching off Semgrep, #111).
@@ -814,18 +981,39 @@ export const TOOLS = [
814
981
  binaryName: "tflint",
815
982
  github: {
816
983
  repo: "terraform-linters/tflint",
817
- assetMatch: (platform, arch) => {
818
- if (platform === "linux")
819
- return arch === "arm64" ? "linux_arm64.zip" : "linux_amd64.zip";
820
- if (platform === "darwin")
821
- return arch === "arm64" ? "darwin_arm64.zip" : "darwin_amd64.zip";
822
- if (platform === "win32")
823
- return arch === "arm64" ? "windows_arm64.zip" : "windows_amd64.zip";
824
- return undefined;
825
- },
984
+ assetMatch: archAssetMatch(OS_ARCH_ZIP_ASSETS),
826
985
  binaryInArchive: "tflint",
827
986
  },
828
987
  },
988
+ {
989
+ // Terragrunt ships a bare native binary per platform on GitHub releases.
990
+ // Windows arm64 uses the x64 binary through Windows' built-in emulation —
991
+ // there is no terragrunt_windows_arm64.exe upstream.
992
+ id: "terragrunt",
993
+ name: "terragrunt",
994
+ checkCommand: "terragrunt",
995
+ checkArgs: ["--version"],
996
+ installStrategy: "github",
997
+ binaryName: "terragrunt",
998
+ github: {
999
+ repo: "gruntwork-io/terragrunt",
1000
+ assetMatch: archAssetMatch({
1001
+ linux: {
1002
+ x64: "terragrunt_linux_amd64",
1003
+ arm64: "terragrunt_linux_arm64",
1004
+ },
1005
+ darwin: {
1006
+ x64: "terragrunt_darwin_amd64",
1007
+ arm64: "terragrunt_darwin_arm64",
1008
+ },
1009
+ win32: {
1010
+ x64: "terragrunt_windows_amd64.exe",
1011
+ arm64: "terragrunt_windows_amd64.exe",
1012
+ },
1013
+ }),
1014
+ // bare binary — no binaryInArchive
1015
+ },
1016
+ },
829
1017
  {
830
1018
  id: "gitleaks",
831
1019
  name: "gitleaks",
@@ -950,15 +1138,7 @@ export const TOOLS = [
950
1138
  github: {
951
1139
  repo: "hashicorp/terraform-ls",
952
1140
  hashiCorpReleaseProduct: "terraform-ls",
953
- assetMatch: (platform, arch) => {
954
- if (platform === "linux")
955
- return arch === "arm64" ? "linux_arm64.zip" : "linux_amd64.zip";
956
- if (platform === "darwin")
957
- return arch === "arm64" ? "darwin_arm64.zip" : "darwin_amd64.zip";
958
- if (platform === "win32")
959
- return arch === "arm64" ? "windows_arm64.zip" : "windows_amd64.zip";
960
- return undefined;
961
- },
1141
+ assetMatch: archAssetMatch(OS_ARCH_ZIP_ASSETS),
962
1142
  binaryInArchive: "terraform-ls",
963
1143
  },
964
1144
  },
@@ -1110,49 +1290,215 @@ export const TOOLS = [
1110
1290
  },
1111
1291
  ];
1112
1292
  const ensureInFlight = new Map();
1293
+ const installFailureReasons = new Map();
1294
+ /** Last honest install refusal/failure reason for callers that need diagnostics. */
1295
+ export function getInstallFailureReason(toolId) {
1296
+ return installFailureReasons.get(toolId);
1297
+ }
1113
1298
  // Session-lifetime cache: once a tool path is resolved, skip the process-spawn check on subsequent calls.
1114
- const resolvedPathCache = new Map();
1299
+ const resolvedPathCache = new BoundedLruCache(256);
1115
1300
  const PROBE_CACHE_PATH = path.join(getGlobalPiLensDir(), "probe-cache.json");
1301
+ const PROBE_CACHE_LOCK_STALE_MS = 180_000;
1116
1302
  const PROBE_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
1303
+ const PROBE_CACHE_FLUSH_LOCK_WAIT_MS = 250;
1304
+ const PROBE_CACHE_FLUSH_RETRY_DELAY_MS = 300;
1305
+ const PROBE_CACHE_FLUSH_RETRY_MAX_DELAY_MS = 30_000;
1117
1306
  let _probeCache = null;
1118
1307
  let _probeCacheDirty = false;
1119
1308
  let _probeCacheFlushTimer = null;
1309
+ let _probeCacheWriteInFlight = null;
1310
+ let _probeCacheRetryAttempt = 0;
1311
+ let _probeCacheChangeGeneration = 0;
1312
+ // Read-modify-write deltas let a long-lived process merge with entries another
1313
+ // process discovered after this process's initial read. `null` is a deliberate
1314
+ // deletion (TTL/stale-path eviction), not an absent map value.
1315
+ const _probeCacheChanges = new Map();
1316
+ const _probeCacheChangeVersions = new Map();
1120
1317
  async function readProbeCache() {
1121
1318
  if (_probeCache !== null)
1122
1319
  return _probeCache;
1123
1320
  try {
1124
1321
  const raw = await fs.readFile(PROBE_CACHE_PATH, "utf-8");
1125
- _probeCache = JSON.parse(raw);
1322
+ const parsed = JSON.parse(raw);
1323
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1324
+ throw new Error("probe-cache root is not an object");
1325
+ }
1326
+ _probeCache = parsed;
1126
1327
  }
1127
- catch {
1328
+ catch (err) {
1329
+ const code = err?.code;
1330
+ if (code !== "ENOENT") {
1331
+ logSessionStart(`auto-install probe-cache: read failed (${code ?? "invalid"}); treating cache as unavailable`);
1332
+ }
1128
1333
  _probeCache = {};
1129
1334
  }
1130
1335
  return _probeCache;
1131
1336
  }
1132
- function scheduleProbeFlush() {
1337
+ function markProbeCacheChange(toolId, entry) {
1338
+ _probeCacheChanges.set(toolId, entry);
1339
+ _probeCacheChangeVersions.set(toolId, ++_probeCacheChangeGeneration);
1340
+ _probeCacheDirty = true;
1341
+ scheduleProbeFlush();
1342
+ }
1343
+ function scheduleProbeFlush(delayMs = PROBE_CACHE_FLUSH_RETRY_DELAY_MS) {
1133
1344
  if (_probeCacheFlushTimer !== null)
1134
1345
  return;
1135
1346
  _probeCacheFlushTimer = setTimeout(() => {
1136
- _probeCacheFlushTimer = null;
1137
- if (!_probeCacheDirty || _probeCache === null)
1138
- return;
1139
- _probeCacheDirty = false;
1140
- void fs
1141
- .writeFile(PROBE_CACHE_PATH, JSON.stringify(_probeCache, null, 2))
1142
- .catch(() => { });
1143
- }, 300);
1347
+ void flushProbeCache();
1348
+ }, delayMs);
1144
1349
  _probeCacheFlushTimer.unref?.();
1145
1350
  }
1351
+ function scheduleProbeFlushRetry() {
1352
+ const delay = Math.min(PROBE_CACHE_FLUSH_RETRY_MAX_DELAY_MS, PROBE_CACHE_FLUSH_RETRY_DELAY_MS * 2 ** Math.min(_probeCacheRetryAttempt, 6));
1353
+ _probeCacheRetryAttempt += 1;
1354
+ scheduleProbeFlush(delay);
1355
+ }
1356
+ function snapshotProbeCacheChanges() {
1357
+ return {
1358
+ changes: new Map(_probeCacheChanges),
1359
+ versions: new Map(_probeCacheChangeVersions),
1360
+ };
1361
+ }
1362
+ function deserializeProbeCache(contents) {
1363
+ if (contents === undefined)
1364
+ return {};
1365
+ const parsed = JSON.parse(contents);
1366
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1367
+ throw new Error("probe-cache root is not an object");
1368
+ }
1369
+ return parsed;
1370
+ }
1371
+ function applyProbeCacheChanges(disk, changes) {
1372
+ for (const [toolId, entry] of changes) {
1373
+ if (entry === null)
1374
+ delete disk[toolId];
1375
+ else
1376
+ disk[toolId] = entry;
1377
+ }
1378
+ }
1379
+ /**
1380
+ * Install-lifetime ageing belongs to the authoritative merge, not only to the
1381
+ * lookup path: a sibling process may have left expired entries on disk since
1382
+ * this process loaded its in-memory snapshot. The async durable-store lock
1383
+ * supplies the probe cache's former quarantine/stale-owner recovery.
1384
+ */
1385
+ function ageProbeCache(disk) {
1386
+ const cutoff = Date.now() - PROBE_CACHE_TTL_MS;
1387
+ for (const [toolId, entry] of Object.entries(disk)) {
1388
+ if (!Number.isFinite(entry.cachedAt) || entry.cachedAt < cutoff) {
1389
+ delete disk[toolId];
1390
+ }
1391
+ }
1392
+ }
1393
+ function publishProbeCacheWrite(disk, snapshotVersions) {
1394
+ // Publish the sibling-process merge plus any updates that arrived during
1395
+ // the write. Only an unchanged snapshot entry is retired.
1396
+ const pendingAfterWrite = new Map(_probeCacheChanges);
1397
+ _probeCache = disk;
1398
+ for (const [toolId, entry] of pendingAfterWrite) {
1399
+ if (entry === null)
1400
+ delete _probeCache[toolId];
1401
+ else
1402
+ _probeCache[toolId] = entry;
1403
+ }
1404
+ for (const [toolId, version] of snapshotVersions) {
1405
+ if (_probeCacheChangeVersions.get(toolId) === version) {
1406
+ _probeCacheChanges.delete(toolId);
1407
+ _probeCacheChangeVersions.delete(toolId);
1408
+ }
1409
+ }
1410
+ _probeCacheDirty = _probeCacheChanges.size > 0;
1411
+ _probeCacheRetryAttempt = 0;
1412
+ return _probeCacheDirty ? "written-with-pending" : "written";
1413
+ }
1414
+ async function writeProbeCache() {
1415
+ try {
1416
+ // Snapshot versions before the awaited disk read/write. A new update for
1417
+ // the same tool may arrive while the atomic write is in flight; its newer
1418
+ // version must remain pending for the next flush.
1419
+ const { changes, versions } = snapshotProbeCacheChanges();
1420
+ let result = "written";
1421
+ const committed = await commitDurableStoreAsync({
1422
+ path: PROBE_CACHE_PATH,
1423
+ deserialize: deserializeProbeCache,
1424
+ merge: (disk) => {
1425
+ ageProbeCache(disk);
1426
+ applyProbeCacheChanges(disk, changes);
1427
+ return disk;
1428
+ },
1429
+ serialize: (disk) => JSON.stringify(disk, null, 2),
1430
+ waitMs: PROBE_CACHE_FLUSH_LOCK_WAIT_MS,
1431
+ retryMs: 25,
1432
+ staleMs: PROBE_CACHE_LOCK_STALE_MS,
1433
+ timeoutMessage: "Timed out waiting for probe-cache lock",
1434
+ onContention: "skip-log",
1435
+ logContention: () => {
1436
+ logSessionStart("auto-install probe-cache: flush deferred because another process owns the lock");
1437
+ },
1438
+ afterWriteLocked: (disk) => {
1439
+ result = publishProbeCacheWrite(disk, versions);
1440
+ },
1441
+ });
1442
+ if (committed === undefined) {
1443
+ scheduleProbeFlushRetry();
1444
+ return "deferred";
1445
+ }
1446
+ return result;
1447
+ }
1448
+ catch (err) {
1449
+ // Keep dirty state so a later timer/explicit flush can retry. The error
1450
+ // is logged without paths, source, or command text; an unavailable cache
1451
+ // must never look like a clean empty cache to operators.
1452
+ logSessionStart(`auto-install probe-cache: flush failed (${err?.code ?? "write error"}); pending update retained`);
1453
+ scheduleProbeFlushRetry();
1454
+ return "failed";
1455
+ }
1456
+ }
1457
+ /** Await pending probe-cache persistence before a one-shot process exits. */
1458
+ export async function flushProbeCache() {
1459
+ if (_probeCacheFlushTimer !== null) {
1460
+ clearTimeout(_probeCacheFlushTimer);
1461
+ _probeCacheFlushTimer = null;
1462
+ }
1463
+ // #946 review F4: if the 300ms timer's write already started, the dirty
1464
+ // flag is false but the write may still be in flight — an immediate
1465
+ // process.exit would truncate it. Always await the in-flight write.
1466
+ if (_probeCacheWriteInFlight) {
1467
+ await _probeCacheWriteInFlight;
1468
+ if (!_probeCacheDirty)
1469
+ return "written";
1470
+ }
1471
+ if (!_probeCacheDirty || _probeCache === null)
1472
+ return "idle";
1473
+ const write = writeProbeCache();
1474
+ _probeCacheWriteInFlight = write;
1475
+ try {
1476
+ return await write;
1477
+ }
1478
+ finally {
1479
+ if (_probeCacheWriteInFlight === write)
1480
+ _probeCacheWriteInFlight = null;
1481
+ }
1482
+ }
1146
1483
  function isAstGrepVersionOutput(output) {
1147
1484
  return /\bast[- ]grep\b/i.test(output);
1148
1485
  }
1149
1486
  async function verifyAstGrepProbePath(binPath) {
1150
1487
  return new Promise((resolve) => {
1151
- const proc = spawn(binPath, ["--version"], {
1152
- stdio: ["ignore", "pipe", "pipe"],
1153
- shell: process.platform === "win32" && /\.(cmd|bat)$/i.test(binPath),
1154
- timeout: 5000,
1155
- });
1488
+ let proc;
1489
+ try {
1490
+ proc = spawn(binPath, ["--version"], {
1491
+ stdio: ["ignore", "pipe", "pipe"],
1492
+ shell: process.platform === "win32" && /\.(cmd|bat)$/i.test(binPath),
1493
+ timeout: 5000,
1494
+ });
1495
+ }
1496
+ catch {
1497
+ // SYNCHRONOUS spawn throw (Windows `spawn UNKNOWN`/EINVAL, the pidusage
1498
+ // bug class, #533) — best-effort probe, resolve rather than reject.
1499
+ resolve(false);
1500
+ return;
1501
+ }
1156
1502
  let output = "";
1157
1503
  proc.stdout?.on("data", (data) => (output += data));
1158
1504
  proc.stderr?.on("data", (data) => (output += data));
@@ -1171,8 +1517,7 @@ export async function checkProbeCache(toolId) {
1171
1517
  if (Date.now() - entry.cachedAt > PROBE_CACHE_TTL_MS) {
1172
1518
  logSessionStart(`auto-install probe-cache ${toolId}: miss (ttl expired)`);
1173
1519
  delete cache[toolId];
1174
- _probeCacheDirty = true;
1175
- scheduleProbeFlush();
1520
+ markProbeCacheChange(toolId, null);
1176
1521
  return undefined;
1177
1522
  }
1178
1523
  try {
@@ -1181,15 +1526,13 @@ export async function checkProbeCache(toolId) {
1181
1526
  if (stat.mtimeMs !== entry.mtimeMs) {
1182
1527
  logSessionStart(`auto-install probe-cache ${toolId}: miss (mtime changed)`);
1183
1528
  delete cache[toolId];
1184
- _probeCacheDirty = true;
1185
- scheduleProbeFlush();
1529
+ markProbeCacheChange(toolId, null);
1186
1530
  return undefined;
1187
1531
  }
1188
1532
  if (toolId === "ast-grep" && !(await verifyAstGrepProbePath(entry.path))) {
1189
1533
  logSessionStart(`auto-install probe-cache ${toolId}: miss (not ast-grep: ${entry.path})`);
1190
1534
  delete cache[toolId];
1191
- _probeCacheDirty = true;
1192
- scheduleProbeFlush();
1535
+ markProbeCacheChange(toolId, null);
1193
1536
  return undefined;
1194
1537
  }
1195
1538
  return entry.path;
@@ -1197,8 +1540,7 @@ export async function checkProbeCache(toolId) {
1197
1540
  catch {
1198
1541
  logSessionStart(`auto-install probe-cache ${toolId}: miss (gone: ${entry.path})`);
1199
1542
  delete cache[toolId];
1200
- _probeCacheDirty = true;
1201
- scheduleProbeFlush();
1543
+ markProbeCacheChange(toolId, null);
1202
1544
  return undefined;
1203
1545
  }
1204
1546
  }
@@ -1207,13 +1549,13 @@ export async function updateProbeCache(toolId, resolvedPath) {
1207
1549
  try {
1208
1550
  const stat = await fs.stat(resolvedPath);
1209
1551
  const cache = await readProbeCache();
1210
- cache[toolId] = {
1552
+ const entry = {
1211
1553
  path: resolvedPath,
1212
1554
  mtimeMs: stat.mtimeMs,
1213
1555
  cachedAt: Date.now(),
1214
1556
  };
1215
- _probeCacheDirty = true;
1216
- scheduleProbeFlush();
1557
+ cache[toolId] = entry;
1558
+ markProbeCacheChange(toolId, entry);
1217
1559
  }
1218
1560
  catch {
1219
1561
  // best-effort
@@ -1223,23 +1565,41 @@ export async function updateProbeCache(toolId, resolvedPath) {
1223
1565
  export function resetProbeCacheStateForTesting() {
1224
1566
  _probeCache = null;
1225
1567
  _probeCacheDirty = false;
1568
+ _probeCacheChanges.clear();
1569
+ _probeCacheChangeVersions.clear();
1570
+ _probeCacheChangeGeneration = 0;
1571
+ _probeCacheRetryAttempt = 0;
1226
1572
  resolvedPathCache.clear();
1227
1573
  ensureInFlight.clear();
1574
+ installFailureReasons.clear();
1228
1575
  lastManagedInstallVersion.clear();
1576
+ resetPathWalkMemo();
1229
1577
  if (_probeCacheFlushTimer !== null) {
1230
1578
  clearTimeout(_probeCacheFlushTimer);
1231
1579
  _probeCacheFlushTimer = null;
1232
1580
  }
1233
1581
  }
1234
1582
  // --- Check Functions ---
1583
+ const pathWalkMemo = new Map();
1584
+ function hashSync(value) {
1585
+ let hash = 0x811c9dc5;
1586
+ for (let i = 0; i < value.length; i += 1) {
1587
+ hash ^= value.charCodeAt(i);
1588
+ hash = Math.imul(hash, 0x01000193);
1589
+ }
1590
+ return (hash >>> 0).toString(16);
1591
+ }
1592
+ export function resetPathWalkMemo() {
1593
+ pathWalkMemo.clear();
1594
+ }
1235
1595
  /**
1236
1596
  * Check if a command is available in PATH by walking PATH entries and
1237
1597
  * verifying each candidate is a real file with non-zero size.
1238
1598
  * Catches broken symlinks (stat throws ENOENT or returns size 0) without
1239
1599
  * spawning a process — ~μs per candidate vs ~50ms for which/where.
1240
1600
  */
1241
- async function isCommandAvailable(command, _args) {
1242
- const isWindows = process.platform === "win32";
1601
+ export async function isCommandAvailable(command, _args) {
1602
+ const isWindows = installerPlatform() === "win32";
1243
1603
  const pathEnv = process.env.PATH || process.env.Path || process.env.path || "";
1244
1604
  const dirs = pathEnv.split(path.delimiter);
1245
1605
  // On Windows, probe .exe, .cmd, and .bat extensions in addition to bare name.
@@ -1266,6 +1626,28 @@ async function isCommandAvailable(command, _args) {
1266
1626
  }
1267
1627
  return false;
1268
1628
  }
1629
+ /**
1630
+ * Can `command` even be spawned? Path-bearing commands stat the file directly;
1631
+ * bare names walk PATH. ~μs either way — callers use this to skip a `--version`
1632
+ * probe that is guaranteed to fail with a full spawn round-trip.
1633
+ */
1634
+ export async function isSpawnableCommand(command) {
1635
+ if (/[\\/]/.test(command)) {
1636
+ try {
1637
+ const stat = statSync(command);
1638
+ return stat.isFile() && stat.size > 0;
1639
+ }
1640
+ catch {
1641
+ return false;
1642
+ }
1643
+ }
1644
+ const memoKey = `${command}:${hashSync(process.env.PATH || "")}`;
1645
+ if (pathWalkMemo.has(memoKey))
1646
+ return pathWalkMemo.get(memoKey) ?? false;
1647
+ const isSpawnable = await isCommandAvailable(command);
1648
+ pathWalkMemo.set(memoKey, isSpawnable);
1649
+ return isSpawnable;
1650
+ }
1269
1651
  // --- Verification Functions
1270
1652
  /**
1271
1653
  * Stdio LSP servers built on `vscode-languageserver-node` (the entire
@@ -1320,7 +1702,7 @@ const lastManagedInstallVersion = new Map();
1320
1702
  */
1321
1703
  async function verifyToolBinary(binPath, onVersionOutput) {
1322
1704
  return new Promise((resolve) => {
1323
- const isWindows = process.platform === "win32";
1705
+ const isWindows = installerPlatform() === "win32";
1324
1706
  const hasKnownWindowsExt = /\.(cmd|exe|ps1)$/i.test(binPath);
1325
1707
  // On Windows, resolve the best executable path:
1326
1708
  // - extensionless → prefer .cmd (cmd.exe-safe)
@@ -1341,11 +1723,21 @@ async function verifyToolBinary(binPath, onVersionOutput) {
1341
1723
  }
1342
1724
  // When shell:true (Windows .cmd), bake args into the command string to avoid DEP0190.
1343
1725
  const spawnCmd = useShell ? `"${execPath}" --version` : execPath;
1344
- const proc = spawn(spawnCmd, useShell ? [] : ["--version"], {
1345
- timeout: 10000,
1346
- stdio: ["ignore", "pipe", "pipe"],
1347
- shell: useShell,
1348
- });
1726
+ let proc;
1727
+ try {
1728
+ proc = spawn(spawnCmd, useShell ? [] : ["--version"], {
1729
+ timeout: 10000,
1730
+ stdio: ["ignore", "pipe", "pipe"],
1731
+ shell: useShell,
1732
+ });
1733
+ }
1734
+ catch (err) {
1735
+ // SYNCHRONOUS spawn throw (Windows `spawn UNKNOWN`/EINVAL, the pidusage
1736
+ // bug class, #533) — best-effort verify, resolve rather than reject.
1737
+ logSessionStart(`auto-install verify: spawn threw for ${binPath} (${err instanceof Error ? err.message : String(err)})`);
1738
+ resolve(false);
1739
+ return;
1740
+ }
1349
1741
  let stdout = "";
1350
1742
  let stderr = "";
1351
1743
  proc.stdout?.on("data", (data) => (stdout += data));
@@ -1405,11 +1797,20 @@ export async function getAllToolStatuses() {
1405
1797
  status.path = tool.checkCommand;
1406
1798
  // Try to get version
1407
1799
  const versionResult = await new Promise((resolve) => {
1408
- const proc = spawn(tool.checkCommand, ["--version"], {
1409
- stdio: ["ignore", "pipe", "pipe"],
1410
- shell: process.platform === "win32",
1411
- timeout: 5000,
1412
- });
1800
+ let proc;
1801
+ try {
1802
+ proc = spawn(tool.checkCommand, ["--version"], {
1803
+ stdio: ["ignore", "pipe", "pipe"],
1804
+ shell: process.platform === "win32",
1805
+ timeout: 5000,
1806
+ });
1807
+ }
1808
+ catch {
1809
+ // SYNCHRONOUS spawn throw (Windows `spawn UNKNOWN`/EINVAL, the
1810
+ // pidusage bug class, #533) — best-effort, resolve empty version.
1811
+ resolve("");
1812
+ return;
1813
+ }
1413
1814
  let out = "";
1414
1815
  proc.stdout?.on("data", (d) => (out += d));
1415
1816
  proc.stderr?.on("data", (d) => (out += d));
@@ -1462,7 +1863,7 @@ export async function getAllToolStatuses() {
1462
1863
  }
1463
1864
  // 5. Check pi-lens auto-install (~/.pi-lens/tools/)
1464
1865
  const localBase = path.join(TOOLS_DIR, "node_modules", ".bin", tool.binaryName || tool.id);
1465
- const localPath = process.platform === "win32" ? `${localBase}.cmd` : localBase;
1866
+ const localPath = installerPlatform() === "win32" ? `${localBase}.cmd` : localBase;
1466
1867
  try {
1467
1868
  await fs.access(localPath);
1468
1869
  if (await verifyToolBinary(localPath)) {
@@ -1527,7 +1928,7 @@ export function resolvePlatformPackageBinary(tool) {
1527
1928
  const spec = tool.platformPackage;
1528
1929
  if (!spec || !tool.packageName)
1529
1930
  return undefined;
1530
- const suffix = spec.suffixes[`${process.platform}-${process.arch}`];
1931
+ const suffix = spec.suffixes[`${installerPlatform()}-${process.arch}`];
1531
1932
  if (!suffix)
1532
1933
  return undefined;
1533
1934
  const platformPkg = `${spec.base ?? tool.packageName}-${suffix}`;
@@ -1543,7 +1944,7 @@ export function resolvePlatformPackageBinary(tool) {
1543
1944
  catch {
1544
1945
  pkgDir = path.dirname(_installerRequire.resolve(`${platformPkg}/package.json`));
1545
1946
  }
1546
- const isWin = process.platform === "win32";
1947
+ const isWin = installerPlatform() === "win32";
1547
1948
  for (const bin of spec.binaries) {
1548
1949
  for (const name of isWin ? [`${bin}.exe`, bin] : [bin]) {
1549
1950
  const candidate = path.join(pkgDir, name);
@@ -1589,7 +1990,7 @@ export async function getToolPath(toolId) {
1589
1990
  // This avoids the ~2-5s overhead of spawning npm global probes and PATH
1590
1991
  // searches for tools we already manage locally.
1591
1992
  const localBase = path.join(TOOLS_DIR, "node_modules", ".bin", tool.binaryName || tool.id);
1592
- if (process.platform === "win32") {
1993
+ if (installerPlatform() === "win32") {
1593
1994
  // Prefer .cmd over extensionless — Node.js can't execute POSIX shell scripts on Windows
1594
1995
  const cmdPath = `${localBase}.cmd`;
1595
1996
  try {
@@ -1616,15 +2017,17 @@ export async function getToolPath(toolId) {
1616
2017
  // fall through to extensionless
1617
2018
  }
1618
2019
  }
1619
- try {
1620
- await fs.access(localBase);
1621
- if (await verifyToolBinary(localBase, recordVersion)) {
1622
- return localBase;
2020
+ if (installerPlatform() !== "win32") {
2021
+ try {
2022
+ await fs.access(localBase);
2023
+ if (await verifyToolBinary(localBase, recordVersion)) {
2024
+ return localBase;
2025
+ }
2026
+ logSessionStart(`auto-install verify: ${localBase} exists but is broken, will reinstall`);
2027
+ }
2028
+ catch {
2029
+ // fall through to global checks
1623
2030
  }
1624
- logSessionStart(`auto-install verify: ${localBase} exists but is broken, will reinstall`);
1625
- }
1626
- catch {
1627
- // fall through to global checks
1628
2031
  }
1629
2032
  // npm/pnpm/bun: prefer the native per-platform binary directly. The main
1630
2033
  // package's launcher often can't find it under a symlink store / after a
@@ -1727,7 +2130,6 @@ async function findNpmGlobalToolPath(binaryName) {
1727
2130
  ? [
1728
2131
  path.join(dir, `${binaryName}.cmd`),
1729
2132
  path.join(dir, `${binaryName}.exe`),
1730
- path.join(dir, binaryName),
1731
2133
  ]
1732
2134
  : [path.join(dir, binaryName)];
1733
2135
  for (const candidate of candidates) {
@@ -1849,10 +2251,19 @@ async function getPythonUserBaseCandidates() {
1849
2251
  const spawnCmd = isWin
1850
2252
  ? [probe.command, ...probe.args].join(" ")
1851
2253
  : probe.command;
1852
- const proc = spawn(spawnCmd, isWin ? [] : probe.args, {
1853
- stdio: ["ignore", "pipe", "pipe"],
1854
- shell: isWin,
1855
- });
2254
+ let proc;
2255
+ try {
2256
+ proc = spawn(spawnCmd, isWin ? [] : probe.args, {
2257
+ stdio: ["ignore", "pipe", "pipe"],
2258
+ shell: isWin,
2259
+ });
2260
+ }
2261
+ catch {
2262
+ // SYNCHRONOUS spawn throw (Windows `spawn UNKNOWN`/EINVAL, the
2263
+ // pidusage bug class, #533) — best-effort probe, resolve empty.
2264
+ resolve("");
2265
+ return;
2266
+ }
1856
2267
  let stdout = "";
1857
2268
  proc.stdout?.on("data", (data) => (stdout += data));
1858
2269
  proc.on("exit", (code) => resolve(code === 0 ? stdout.trim() : ""));
@@ -1925,11 +2336,20 @@ function httpsGet(url, maxRedirects = 5, headers = {}) {
1925
2336
  */
1926
2337
  function runCommand(command, args, cwd) {
1927
2338
  return new Promise((resolve) => {
1928
- const proc = spawn(command, args, {
1929
- cwd,
1930
- stdio: "ignore",
1931
- shell: process.platform === "win32",
1932
- });
2339
+ let proc;
2340
+ try {
2341
+ proc = spawn(command, args, {
2342
+ cwd,
2343
+ stdio: "ignore",
2344
+ shell: process.platform === "win32",
2345
+ });
2346
+ }
2347
+ catch {
2348
+ // SYNCHRONOUS spawn throw (Windows `spawn UNKNOWN`/EINVAL, the pidusage
2349
+ // bug class, #533) — resolve false rather than reject/crash.
2350
+ resolve(false);
2351
+ return;
2352
+ }
1933
2353
  proc.on("exit", (code) => resolve(code === 0));
1934
2354
  proc.on("error", () => resolve(false));
1935
2355
  });
@@ -1960,7 +2380,7 @@ async function installGitHubTool(tool) {
1960
2380
  logSessionStart(`github-install ${tool.id}: release fetch failed: ${err.message}`);
1961
2381
  return undefined;
1962
2382
  }
1963
- const asset = releaseJson.assets.find((a) => a.name.includes(assetSubstring)) ??
2383
+ const asset = pickReleaseAsset(releaseJson.assets, assetSubstring) ??
1964
2384
  deriveHashiCorpReleaseAsset(tool, releaseJson.tag_name, assetSubstring);
1965
2385
  if (!asset) {
1966
2386
  logSessionStart(`github-install ${tool.id}: no asset matched "${assetSubstring}"`);
@@ -2257,23 +2677,16 @@ async function installArchiveTool(tool) {
2257
2677
  const tarBin = isWindows
2258
2678
  ? `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\tar.exe`
2259
2679
  : "tar";
2260
- const extracted = await new Promise((resolve) => {
2261
- const proc = spawn(tarBin, tarArgs, {
2262
- cwd: TOOLS_DIR,
2263
- stdio: ["ignore", "ignore", "pipe"],
2264
- });
2265
- let stderr = "";
2266
- proc.stderr?.on("data", (d) => (stderr += d));
2267
- const timer = setTimeout(() => {
2268
- proc.kill();
2269
- resolve({ ok: false, stderr: "extraction timed out" });
2270
- }, 120_000);
2271
- proc.on("exit", (code) => {
2272
- clearTimeout(timer);
2273
- resolve({ ok: code === 0, stderr });
2274
- });
2275
- proc.on("error", (err) => resolve({ ok: false, stderr: err.message }));
2680
+ const extractResult = await safeSpawnAsync(tarBin, tarArgs, {
2681
+ cwd: TOOLS_DIR,
2682
+ timeout: 120_000,
2683
+ ignoreAmbientSignal: true,
2684
+ lifetimeCoupled: true,
2276
2685
  });
2686
+ const extracted = {
2687
+ ok: extractResult.status === 0,
2688
+ stderr: extractResult.error?.message ?? extractResult.stderr,
2689
+ };
2277
2690
  await fs.rm(tmpArchive, { force: true });
2278
2691
  if (!extracted.ok) {
2279
2692
  logSessionStart(`archive-install ${tool.id}: extraction failed: ${extracted.stderr}`);
@@ -2344,41 +2757,35 @@ async function installNpmTool(packageName, binaryName) {
2344
2757
  await fs.writeFile(packageJsonPath, JSON.stringify({ name: "pi-lens-tools", version: "1.0.0" }, null, 2));
2345
2758
  }
2346
2759
  // Resolve the package manager for the tools dir and build install args.
2347
- const isWindows = process.platform === "win32";
2760
+ const isWindows = installerPlatform() === "win32";
2348
2761
  const pm = await resolveNodePackageManager(TOOLS_DIR);
2349
- const pmCommand = pmBinary(pm);
2762
+ const testNpmScript = process.env.PI_LENS_TEST_MODE === "1"
2763
+ ? process.env.PI_LENS_TEST_NPM_SCRIPT
2764
+ : undefined;
2765
+ const pmCommand = testNpmScript ? process.execPath : pmBinary(pm);
2350
2766
  // Use --ignore-scripts unless the package explicitly needs postinstall
2351
2767
  // (e.g. biome downloads a platform-specific native binary via postinstall).
2352
2768
  const needsScripts = NEEDS_POSTINSTALL.has(packageName);
2353
2769
  const baseInstallArgs = installArgs(pm, packageName, {
2354
2770
  ignoreScripts: !needsScripts,
2355
2771
  });
2356
- const INSTALL_TIMEOUT_MS = 120_000;
2357
- const runInstallAttempt = async (args) => new Promise((resolve) => {
2358
- const proc = spawn(pmCommand, args, {
2772
+ const INSTALL_TIMEOUT_MS = Number(process.env.PI_LENS_INSTALL_TIMEOUT_MS) || 120_000;
2773
+ const runInstallAttempt = async (args) => {
2774
+ const result = await safeSpawnAsync(pmCommand, args, {
2359
2775
  cwd: TOOLS_DIR,
2360
- stdio: ["ignore", "pipe", "pipe"],
2361
- shell: isWindows, // Required for .cmd files on Windows
2362
- });
2363
- let stderr = "";
2364
- proc.stderr?.on("data", (data) => (stderr += data));
2365
- const timer = setTimeout(() => {
2366
- proc.kill();
2367
- resolve({
2368
- ok: false,
2369
- stderr: `install timed out after ${INSTALL_TIMEOUT_MS / 1000}s`,
2370
- });
2371
- }, INSTALL_TIMEOUT_MS);
2372
- proc.on("exit", (code) => {
2373
- clearTimeout(timer);
2374
- resolve({ ok: code === 0, stderr });
2776
+ timeout: INSTALL_TIMEOUT_MS,
2777
+ ignoreAmbientSignal: true,
2778
+ lifetimeCoupled: true,
2375
2779
  });
2376
- proc.on("error", (err) => {
2377
- clearTimeout(timer);
2378
- resolve({ ok: false, stderr: err.message });
2379
- });
2380
- });
2381
- let outcome = await runInstallAttempt(baseInstallArgs);
2780
+ return {
2781
+ ok: result.status === 0,
2782
+ stderr: result.error?.message ?? result.stderr,
2783
+ };
2784
+ };
2785
+ let outcome = await runInstallAttempt([
2786
+ ...(testNpmScript ? [testNpmScript] : []),
2787
+ ...baseInstallArgs,
2788
+ ]);
2382
2789
  // --legacy-peer-deps is npm-only; retry just npm's ERESOLVE failures.
2383
2790
  const erResolve = outcome.ok === false &&
2384
2791
  /npm\s+error\s+ERESOLVE|\bERESOLVE\b|could not resolve/i.test(outcome.stderr);
@@ -2388,14 +2795,20 @@ async function installNpmTool(packageName, binaryName) {
2388
2795
  legacyPeerDeps: true,
2389
2796
  });
2390
2797
  logSessionStart(`auto-install npm ${packageName}: retry with --legacy-peer-deps after ERESOLVE`);
2391
- outcome = await runInstallAttempt(retryArgs);
2798
+ outcome = await runInstallAttempt([
2799
+ ...(testNpmScript ? [testNpmScript] : []),
2800
+ ...retryArgs,
2801
+ ]);
2392
2802
  }
2393
2803
  if (!outcome.ok) {
2394
2804
  throw new Error(`Failed to install ${packageName}: ${outcome.stderr}`);
2395
2805
  }
2396
- const binPath = path.join(TOOLS_DIR, "node_modules", ".bin", binaryName);
2806
+ // npm creates a command shim on Windows; retain that actual executable path
2807
+ // rather than probing/storing the extensionless POSIX sibling.
2808
+ const binBase = path.join(TOOLS_DIR, "node_modules", ".bin", binaryName);
2809
+ const binPath = installerPlatform() === "win32" ? `${binBase}.cmd` : binBase;
2397
2810
  // Make executable on Unix
2398
- if (process.platform !== "win32") {
2811
+ if (installerPlatform() !== "win32") {
2399
2812
  try {
2400
2813
  await fs.chmod(binPath, 0o750);
2401
2814
  }
@@ -2425,10 +2838,10 @@ async function installNpmTool(packageName, binaryName) {
2425
2838
  try {
2426
2839
  const packagePath = path.join(TOOLS_DIR, "node_modules", packageName);
2427
2840
  await fs.rm(packagePath, { recursive: true, force: true });
2428
- await fs.rm(binPath, { force: true });
2841
+ await fs.rm(binBase, { force: true });
2429
2842
  if (isWindows) {
2430
- await fs.rm(`${binPath}.cmd`, { force: true });
2431
- await fs.rm(`${binPath}.ps1`, { force: true });
2843
+ await fs.rm(`${binBase}.cmd`, { force: true });
2844
+ await fs.rm(`${binBase}.ps1`, { force: true });
2432
2845
  }
2433
2846
  }
2434
2847
  catch {
@@ -2475,33 +2888,32 @@ async function installPipTool(packageName) {
2475
2888
  ];
2476
2889
  let lastError = "";
2477
2890
  for (const candidate of pipCandidates) {
2478
- const outcome = await new Promise((resolve) => {
2479
- const proc = spawn(candidate.command, candidate.args, {
2480
- stdio: ["ignore", "pipe", "pipe"],
2481
- shell: isWindows, // Required for .cmd files on Windows
2482
- });
2483
- let stderr = "";
2484
- proc.stderr?.on("data", (data) => (stderr += data));
2485
- proc.on("exit", (code) => {
2486
- if (code === 0) {
2487
- resolve({ ok: true, error: "" });
2488
- }
2489
- else {
2490
- resolve({ ok: false, error: stderr.trim() });
2491
- }
2492
- });
2493
- proc.on("error", (err) => {
2494
- resolve({ ok: false, error: err.message });
2495
- });
2891
+ const pipResult = await safeSpawnAsync(candidate.command, candidate.args, {
2892
+ timeout: 120_000,
2893
+ ignoreAmbientSignal: true,
2894
+ lifetimeCoupled: true,
2496
2895
  });
2896
+ const outcome = {
2897
+ ok: pipResult.status === 0,
2898
+ error: (pipResult.error?.message ?? pipResult.stderr).trim(),
2899
+ };
2497
2900
  if (outcome.ok) {
2498
2901
  // Ensure user-level scripts directory is available in current process PATH.
2499
2902
  // This helps tools installed via `pip install --user` become immediately callable.
2500
2903
  const userBaseResult = await new Promise((resolve) => {
2501
- const probe = spawn(candidate.command, ["-m", "site", "--user-base"], {
2502
- stdio: ["ignore", "pipe", "pipe"],
2503
- shell: isWindows,
2504
- });
2904
+ let probe;
2905
+ try {
2906
+ probe = spawn(candidate.command, ["-m", "site", "--user-base"], {
2907
+ stdio: ["ignore", "pipe", "pipe"],
2908
+ shell: isWindows,
2909
+ });
2910
+ }
2911
+ catch {
2912
+ // SYNCHRONOUS spawn throw (Windows `spawn UNKNOWN`/EINVAL, the
2913
+ // pidusage bug class, #533) — best-effort probe, resolve empty.
2914
+ resolve("");
2915
+ return;
2916
+ }
2505
2917
  let stdout = "";
2506
2918
  probe.stdout?.on("data", (data) => (stdout += data));
2507
2919
  probe.on("exit", (code) => {
@@ -2576,21 +2988,15 @@ async function installPipTool(packageName) {
2576
2988
  }
2577
2989
  async function installGemTool(packageName) {
2578
2990
  try {
2579
- const isWindows = process.platform === "win32";
2580
- const outcome = await new Promise((resolve) => {
2581
- const proc = spawn("gem", ["install", packageName, "--no-document"], {
2582
- stdio: ["ignore", "pipe", "pipe"],
2583
- shell: isWindows,
2584
- });
2585
- let stderr = "";
2586
- proc.stderr?.on("data", (data) => (stderr += data));
2587
- proc.on("exit", (code) => {
2588
- resolve({ ok: code === 0, error: stderr.trim() });
2589
- });
2590
- proc.on("error", (err) => {
2591
- resolve({ ok: false, error: err.message });
2592
- });
2991
+ const gemResult = await safeSpawnAsync("gem", ["install", packageName, "--no-document"], {
2992
+ timeout: 120_000,
2993
+ ignoreAmbientSignal: true,
2994
+ lifetimeCoupled: true,
2593
2995
  });
2996
+ const outcome = {
2997
+ ok: gemResult.status === 0,
2998
+ error: (gemResult.error?.message ?? gemResult.stderr).trim(),
2999
+ };
2594
3000
  if (!outcome.ok) {
2595
3001
  throw new Error(`Failed to install ${packageName} via gem: ${outcome.error}`);
2596
3002
  }
@@ -2601,10 +3007,42 @@ async function installGemTool(packageName) {
2601
3007
  return undefined;
2602
3008
  }
2603
3009
  }
3010
+ async function finishInstallAttempt(toolId, ok, startedAt) {
3011
+ logSessionStart(`auto-install ${toolId}: ${ok ? "success" : "failed"} (${Date.now() - startedAt}ms)`);
3012
+ if (ok) {
3013
+ // A prior availability probe may have cached ENOENT for this exact child
3014
+ // PATH. Make a successful mutation visible immediately rather than waiting
3015
+ // for the bounded negative-cache TTL or the next session reset (#1199).
3016
+ resetSafeSpawnWindowsCommandCache();
3017
+ // #1276: the madge managed-path memo is keyed only by projectRoot, but
3018
+ // reads PATH/discovery/install state that a completed install can just
3019
+ // have changed — drop it here too, right alongside the safe-spawn reset.
3020
+ // AWAITED (not fire-and-forget): a caller that starts the next madge
3021
+ // resolution the instant `installTool`/`ensureTool` resolves must observe
3022
+ // the reset memo, not a stale pre-install one, and a rejected dynamic
3023
+ // import must not become a silent unhandled rejection. Dynamic import
3024
+ // avoids a static dependency-checker.js <-> installer/index.js cycle
3025
+ // (dependency-checker.js already imports this module dynamically for the
3026
+ // same reason).
3027
+ try {
3028
+ const { resetMadgeManagedPathMemo } = await import("../dependency-checker.js");
3029
+ resetMadgeManagedPathMemo();
3030
+ }
3031
+ catch (err) {
3032
+ logSessionStart(`auto-install ${toolId}: madge memo reset failed: ${err.message}`);
3033
+ }
3034
+ }
3035
+ return ok;
3036
+ }
2604
3037
  /**
2605
3038
  * Install a tool by ID
2606
3039
  */
2607
3040
  export async function installTool(toolId) {
3041
+ if (process.env.PI_LENS_DISABLE_TOOL_INSTALL === "1") {
3042
+ installFailureReasons.set(toolId, "installation disabled by PI_LENS_DISABLE_TOOL_INSTALL=1");
3043
+ logSessionStart(`auto-install ${toolId}: refused — PI_LENS_DISABLE_TOOL_INSTALL=1`);
3044
+ return false;
3045
+ }
2608
3046
  const tool = TOOLS.find((t) => t.id === toolId);
2609
3047
  if (!tool) {
2610
3048
  logSessionStart(`auto-install ${toolId}: unknown tool id`);
@@ -2618,49 +3056,37 @@ export async function installTool(toolId) {
2618
3056
  if (!tool.packageName || !tool.binaryName)
2619
3057
  return false;
2620
3058
  const npmPath = await installNpmTool(tool.packageName, tool.binaryName);
2621
- const ok = npmPath !== undefined;
2622
- logSessionStart(`auto-install ${tool.id}: ${ok ? "success" : "failed"} (${Date.now() - startedAt}ms)`);
2623
- return ok;
3059
+ return finishInstallAttempt(tool.id, npmPath !== undefined, startedAt);
2624
3060
  }
2625
3061
  case "pip": {
2626
3062
  if (!tool.packageName)
2627
3063
  return false;
2628
3064
  const pipPath = await installPipTool(tool.packageName);
2629
- const ok = pipPath !== undefined;
2630
- logSessionStart(`auto-install ${tool.id}: ${ok ? "success" : "failed"} (${Date.now() - startedAt}ms)`);
2631
- return ok;
3065
+ return finishInstallAttempt(tool.id, pipPath !== undefined, startedAt);
2632
3066
  }
2633
3067
  case "gem": {
2634
3068
  if (!tool.packageName)
2635
3069
  return false;
2636
3070
  const gemPath = await installGemTool(tool.packageName);
2637
- const ok = gemPath !== undefined;
2638
- logSessionStart(`auto-install ${tool.id}: ${ok ? "success" : "failed"} (${Date.now() - startedAt}ms)`);
2639
- return ok;
3071
+ return finishInstallAttempt(tool.id, gemPath !== undefined, startedAt);
2640
3072
  }
2641
3073
  case "github": {
2642
3074
  if (!tool.github)
2643
3075
  return false;
2644
3076
  const ghPath = await installGitHubTool(tool);
2645
- const ok = ghPath !== undefined;
2646
- logSessionStart(`auto-install ${tool.id}: ${ok ? "success" : "failed"} (${Date.now() - startedAt}ms)`);
2647
- return ok;
3077
+ return finishInstallAttempt(tool.id, ghPath !== undefined, startedAt);
2648
3078
  }
2649
3079
  case "maven": {
2650
3080
  if (!tool.maven)
2651
3081
  return false;
2652
3082
  const mavenPath = await installMavenTool(tool);
2653
- const ok = mavenPath !== undefined;
2654
- logSessionStart(`auto-install ${tool.id}: ${ok ? "success" : "failed"} (${Date.now() - startedAt}ms)`);
2655
- return ok;
3083
+ return finishInstallAttempt(tool.id, mavenPath !== undefined, startedAt);
2656
3084
  }
2657
3085
  case "archive": {
2658
3086
  if (!tool.archive)
2659
3087
  return false;
2660
3088
  const archivePath = await installArchiveTool(tool);
2661
- const ok = archivePath !== undefined;
2662
- logSessionStart(`auto-install ${tool.id}: ${ok ? "success" : "failed"} (${Date.now() - startedAt}ms)`);
2663
- return ok;
3089
+ return finishInstallAttempt(tool.id, archivePath !== undefined, startedAt);
2664
3090
  }
2665
3091
  default:
2666
3092
  logSessionStart(`auto-install ${tool.id}: unsupported strategy`);
@@ -2673,9 +3099,25 @@ export async function installTool(toolId) {
2673
3099
  }
2674
3100
  }
2675
3101
  /**
2676
- * Ensure a tool is installed (check first, install if missing)
3102
+ * Ensure a tool is installed (check first, install if missing).
3103
+ *
3104
+ * #1334 S5: when the pi host has actively denied project trust, the INSTALL
3105
+ * half is switched off here — the request degrades to the existing
3106
+ * `allowInstall:false` discovery-only path rather than failing outright, so an
3107
+ * already-present binary keeps working while nothing is downloaded or executed
3108
+ * on behalf of an untrusted project. A host with no trust surface at all
3109
+ * (`"unknown"`) is unaffected.
2677
3110
  */
2678
3111
  export async function ensureTool(toolId, opts) {
3112
+ if (opts?.allowInstall !== false &&
3113
+ !assertInstallAllowed(`managed tool ensure: ${toolId}`)) {
3114
+ logSessionStart(`auto-install ensure ${toolId}: install gated — ${projectTrustDenialReason()}; discovery only`);
3115
+ return ensureToolResolved(toolId, { ...opts, allowInstall: false });
3116
+ }
3117
+ return ensureToolResolved(toolId, opts);
3118
+ }
3119
+ async function ensureToolResolved(toolId, opts) {
3120
+ installFailureReasons.delete(toolId);
2679
3121
  const cacheResolvedPath = (result) => {
2680
3122
  if (result) {
2681
3123
  resolvedPathCache.set(toolId, result);
@@ -2696,8 +3138,7 @@ export async function ensureTool(toolId, opts) {
2696
3138
  try {
2697
3139
  const probeCache = await readProbeCache();
2698
3140
  delete probeCache[toolId];
2699
- _probeCacheDirty = true;
2700
- scheduleProbeFlush();
3141
+ markProbeCacheChange(toolId, null);
2701
3142
  }
2702
3143
  catch {
2703
3144
  // best-effort
@@ -2706,8 +3147,23 @@ export async function ensureTool(toolId, opts) {
2706
3147
  logSessionStart(`auto-install ensure ${toolId}: force reinstall blocked — install disabled, discovery only (${Date.now() - ensureStartMs}ms)`);
2707
3148
  return cacheResolvedPath(await getToolPath(toolId));
2708
3149
  }
2709
- // Force download
2710
- const installed = await installTool(toolId);
3150
+ if (process.env.PI_LENS_DISABLE_TOOL_INSTALL === "1") {
3151
+ installFailureReasons.set(toolId, "installation disabled by PI_LENS_DISABLE_TOOL_INSTALL=1");
3152
+ logSessionStart(`auto-install ensure ${toolId}: refused — PI_LENS_DISABLE_TOOL_INSTALL=1`);
3153
+ return undefined;
3154
+ }
3155
+ const lock = await acquireInstallLock();
3156
+ if (!lock.release) {
3157
+ logSessionStart(`auto-install ensure ${toolId}: ${lock.reason}`);
3158
+ return undefined;
3159
+ }
3160
+ let installed;
3161
+ try {
3162
+ installed = await installTool(toolId);
3163
+ }
3164
+ finally {
3165
+ await lock.release();
3166
+ }
2711
3167
  if (!installed) {
2712
3168
  logSessionStart(`auto-install ensure ${toolId}: force reinstall failed (${Date.now() - ensureStartMs}ms)`);
2713
3169
  return undefined;
@@ -2721,8 +3177,23 @@ export async function ensureTool(toolId, opts) {
2721
3177
  }
2722
3178
  // Fast path 1: in-memory session cache — no I/O.
2723
3179
  const cached = resolvedPathCache.get(toolId);
2724
- if (cached)
2725
- return cached;
3180
+ if (cached) {
3181
+ if (!isFullyQualified(cached))
3182
+ return cached;
3183
+ try {
3184
+ await fs.access(cached);
3185
+ return cached;
3186
+ }
3187
+ catch {
3188
+ // The executor would report ENOENT for this cached positive. Evict it
3189
+ // before discovery so the failure heals on this call, not after restart.
3190
+ }
3191
+ resolvedPathCache.delete(toolId);
3192
+ const probeCache = await readProbeCache();
3193
+ delete probeCache[toolId];
3194
+ markProbeCacheChange(toolId, null);
3195
+ logSessionStart(`auto-install ensure ${toolId}: cached path disappeared; re-probing`);
3196
+ }
2726
3197
  // Fast path 2: persistent probe cache — fs.access + stat, no process spawn.
2727
3198
  const diskCached = await checkProbeCache(toolId);
2728
3199
  if (diskCached) {
@@ -2783,7 +3254,32 @@ export async function ensureTool(toolId, opts) {
2783
3254
  logSessionStart(`auto-install ensure ${toolId}: install disabled — discovery only, not found (${Date.now() - ensureStartMs}ms)`);
2784
3255
  return undefined;
2785
3256
  }
2786
- const installed = await installTool(toolId);
3257
+ if (process.env.PI_LENS_DISABLE_TOOL_INSTALL === "1") {
3258
+ installFailureReasons.set(toolId, "installation disabled by PI_LENS_DISABLE_TOOL_INSTALL=1");
3259
+ logSessionStart(`auto-install ensure ${toolId}: refused — PI_LENS_DISABLE_TOOL_INSTALL=1 (${Date.now() - ensureStartMs}ms)`);
3260
+ return undefined;
3261
+ }
3262
+ const lock = await acquireInstallLock();
3263
+ if (!lock.release) {
3264
+ installFailureReasons.set(toolId, lock.reason ?? "install lock failed");
3265
+ logSessionStart(`auto-install ensure ${toolId}: ${lock.reason}`);
3266
+ return undefined;
3267
+ }
3268
+ let installed;
3269
+ try {
3270
+ // Cross-process double-check: the lock waiter may now observe the tool
3271
+ // installed by its predecessor and must not run a second package manager.
3272
+ const installedByPeer = await getToolPath(toolId);
3273
+ if (installedByPeer) {
3274
+ resolvedPathCache.set(toolId, installedByPeer);
3275
+ void updateProbeCache(toolId, installedByPeer);
3276
+ return installedByPeer;
3277
+ }
3278
+ installed = await installTool(toolId);
3279
+ }
3280
+ finally {
3281
+ await lock.release();
3282
+ }
2787
3283
  if (!installed) {
2788
3284
  logSessionStart(`auto-install ensure ${toolId}: unavailable (${Date.now() - ensureStartMs}ms)`);
2789
3285
  return undefined;
@@ -2871,9 +3367,11 @@ export const GITHUB_TOOLS = [
2871
3367
  "zizmor",
2872
3368
  "typos-lsp",
2873
3369
  "tflint",
3370
+ "terragrunt",
2874
3371
  "terraform-ls",
2875
3372
  "zls",
2876
3373
  "hadolint",
3374
+ "helm",
2877
3375
  "gitleaks",
2878
3376
  "taplo",
2879
3377
  "vale",
@@ -2906,6 +3404,28 @@ export function resolveGitHubArchiveBinaryCandidates(toolId, platform, assetName
2906
3404
  const binaryName = tool.github?.binaryInArchive ?? tool.binaryName ?? tool.id;
2907
3405
  return getArchiveBinaryCandidates(binaryName, platform, assetName);
2908
3406
  }
3407
+ // Signature/checksum siblings a release publishes next to the real asset. A
3408
+ // bare-binary tool's substring IS the whole asset name, so `includes` alone
3409
+ // matches `<asset>.asc` too and would install a signature file as the binary.
3410
+ const ASSET_SIDECAR_SUFFIXES = [
3411
+ ".asc",
3412
+ ".sig",
3413
+ ".minisig",
3414
+ ".pem",
3415
+ ".cert",
3416
+ ".sbom",
3417
+ ".sha256",
3418
+ ".sha256sum",
3419
+ ".md5",
3420
+ ];
3421
+ function isAssetSidecar(name) {
3422
+ const lower = name.toLowerCase();
3423
+ return ASSET_SIDECAR_SUFFIXES.some((suffix) => lower.endsWith(suffix));
3424
+ }
3425
+ export function pickReleaseAsset(assets, assetSubstring) {
3426
+ return (assets.find((a) => a.name === assetSubstring) ??
3427
+ assets.find((a) => a.name.includes(assetSubstring) && !isAssetSidecar(a.name)));
3428
+ }
2909
3429
  function deriveHashiCorpReleaseAsset(tool, tagName, assetSubstring) {
2910
3430
  const product = tool.github?.hashiCorpReleaseProduct;
2911
3431
  if (!product || !tagName)