pi-lens 4.1.2 → 4.1.4

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 (359) hide show
  1. package/CHANGELOG.md +1308 -0
  2. package/README.md +3 -0
  3. package/config/biome/core.jsonc +11 -2
  4. package/config/dependency-cruiser-eager-allowlist.json +91 -0
  5. package/dist/clients/actionable-warnings-logger.js +18 -3
  6. package/dist/clients/actionable-warnings.js +927 -80
  7. package/dist/clients/agent-behavior-client.js +13 -4
  8. package/dist/clients/ast-grep-client.js +136 -9
  9. package/dist/clients/ast-grep-rule-manager.js +60 -5
  10. package/dist/clients/ast-grep-tool-logger.js +2 -2
  11. package/dist/clients/availability-probe-flight.js +12 -0
  12. package/dist/clients/bash-file-access.js +1 -3
  13. package/dist/clients/biome-client.js +16 -2
  14. package/dist/clients/blocker-freshness.js +34 -0
  15. package/dist/clients/bootstrap.js +509 -73
  16. package/dist/clients/bounded-cache.js +152 -12
  17. package/dist/clients/bounded-telemetry.js +115 -23
  18. package/dist/clients/build-identity.js +95 -0
  19. package/dist/clients/bundled-resource-health.js +113 -0
  20. package/dist/clients/bus-events-logger.js +2 -2
  21. package/dist/clients/bus-publish.js +3 -0
  22. package/dist/clients/cache/rule-cache.js +33 -5
  23. package/dist/clients/cache-manager.js +105 -6
  24. package/dist/clients/cache-observability.js +46 -19
  25. package/dist/clients/cargo-manifest.js +422 -0
  26. package/dist/clients/cascade-logger.js +17 -3
  27. package/dist/clients/code-quality-warnings.js +13 -3
  28. package/dist/clients/complexity-client.js +16 -5
  29. package/dist/clients/config-core/deny.js +221 -0
  30. package/dist/clients/config-core/index.js +47 -0
  31. package/dist/clients/config-core/merge.js +357 -0
  32. package/dist/clients/config-core/normalize.js +340 -0
  33. package/dist/clients/config-core/process-spec.js +248 -0
  34. package/dist/clients/config-core/provenance.js +171 -0
  35. package/dist/clients/config-core/records.js +218 -0
  36. package/dist/clients/config-core/resolve.js +125 -0
  37. package/dist/clients/config-core/safe-object.js +78 -0
  38. package/dist/clients/config-core/schema.js +167 -0
  39. package/dist/clients/config-diagnostic-codes.js +281 -0
  40. package/dist/clients/config-locations.js +160 -0
  41. package/dist/clients/config-resolve.js +789 -0
  42. package/dist/clients/config-schema.js +197 -0
  43. package/dist/clients/config-warn.js +407 -0
  44. package/dist/clients/dead-code-client.js +33 -25
  45. package/dist/clients/dead-code-logger.js +2 -2
  46. package/dist/clients/deadline-utils.js +178 -0
  47. package/dist/clients/debug-handles.js +2 -2
  48. package/dist/clients/debug-heap.js +3 -3
  49. package/dist/clients/deferred-lsp-work.js +106 -0
  50. package/dist/clients/degradation-ledger.js +166 -8
  51. package/dist/clients/demoted-finding-render.js +14 -0
  52. package/dist/clients/dependency-checker.js +28 -22
  53. package/dist/clients/deps/minimatch.js +1 -1
  54. package/dist/clients/diagnostic-line-freshness.js +12 -9
  55. package/dist/clients/diagnostic-logger.js +14 -4
  56. package/dist/clients/dispatch/collect-later-tier.js +39 -0
  57. package/dist/clients/dispatch/dispatcher.js +304 -19
  58. package/dist/clients/dispatch/fact-store.js +328 -9
  59. package/dist/clients/dispatch/integration.js +214 -107
  60. package/dist/clients/dispatch/pending-runner-findings.js +87 -0
  61. package/dist/clients/dispatch/plan.js +21 -5
  62. package/dist/clients/dispatch/runners/actionlint.js +0 -1
  63. package/dist/clients/dispatch/runners/ast-grep-napi.js +550 -77
  64. package/dist/clients/dispatch/runners/biome-check.js +0 -1
  65. package/dist/clients/dispatch/runners/cpp-check.js +0 -1
  66. package/dist/clients/dispatch/runners/credo.js +0 -1
  67. package/dist/clients/dispatch/runners/cue-vet.js +0 -1
  68. package/dist/clients/dispatch/runners/dart-analyze.js +0 -1
  69. package/dist/clients/dispatch/runners/detekt.js +0 -1
  70. package/dist/clients/dispatch/runners/dotnet-build.js +0 -1
  71. package/dist/clients/dispatch/runners/elixir-check.js +0 -1
  72. package/dist/clients/dispatch/runners/eslint.js +5 -2
  73. package/dist/clients/dispatch/runners/fact-rules.js +0 -1
  74. package/dist/clients/dispatch/runners/fish-indent.js +0 -1
  75. package/dist/clients/dispatch/runners/gleam-check.js +0 -1
  76. package/dist/clients/dispatch/runners/go-vet.js +1 -3
  77. package/dist/clients/dispatch/runners/golangci-lint.js +0 -1
  78. package/dist/clients/dispatch/runners/hadolint.js +0 -1
  79. package/dist/clients/dispatch/runners/helm-lint.js +16 -4
  80. package/dist/clients/dispatch/runners/helm-render.js +54 -10
  81. package/dist/clients/dispatch/runners/htmlhint.js +0 -1
  82. package/dist/clients/dispatch/runners/index.js +1 -3
  83. package/dist/clients/dispatch/runners/javac.js +0 -1
  84. package/dist/clients/dispatch/runners/ktlint.js +0 -1
  85. package/dist/clients/dispatch/runners/lsp.js +37 -2
  86. package/dist/clients/dispatch/runners/markdownlint.js +4 -2
  87. package/dist/clients/dispatch/runners/mypy.js +0 -1
  88. package/dist/clients/dispatch/runners/oxlint.js +24 -22
  89. package/dist/clients/dispatch/runners/php-lint.js +0 -1
  90. package/dist/clients/dispatch/runners/phpstan.js +0 -1
  91. package/dist/clients/dispatch/runners/prisma-validate.js +0 -1
  92. package/dist/clients/dispatch/runners/psscriptanalyzer.js +4 -1
  93. package/dist/clients/dispatch/runners/pyright.js +7 -4
  94. package/dist/clients/dispatch/runners/rubocop.js +0 -1
  95. package/dist/clients/dispatch/runners/ruff.js +0 -1
  96. package/dist/clients/dispatch/runners/rust-clippy.js +9 -6
  97. package/dist/clients/dispatch/runners/shellcheck.js +0 -1
  98. package/dist/clients/dispatch/runners/shfmt.js +0 -1
  99. package/dist/clients/dispatch/runners/spellcheck.js +0 -1
  100. package/dist/clients/dispatch/runners/spotbugs.js +0 -1
  101. package/dist/clients/dispatch/runners/sqlfluff.js +0 -1
  102. package/dist/clients/dispatch/runners/stylelint.js +0 -1
  103. package/dist/clients/dispatch/runners/swiftlint.js +0 -1
  104. package/dist/clients/dispatch/runners/taplo.js +0 -1
  105. package/dist/clients/dispatch/runners/terragrunt.js +0 -1
  106. package/dist/clients/dispatch/runners/tflint.js +0 -1
  107. package/dist/clients/dispatch/runners/tree-sitter.js +0 -1
  108. package/dist/clients/dispatch/runners/trivy-config.js +0 -1
  109. package/dist/clients/dispatch/runners/utils/availability-policy.js +3 -0
  110. package/dist/clients/dispatch/runners/utils/diagnostic-parsers.js +3 -4
  111. package/dist/clients/dispatch/runners/utils/runner-helpers.js +270 -105
  112. package/dist/clients/dispatch/runners/utils/spawn-outcome.js +4 -0
  113. package/dist/clients/dispatch/runners/utils/tool-failure.js +19 -7
  114. package/dist/clients/dispatch/runners/utils/toolchain-availability.js +89 -26
  115. package/dist/clients/dispatch/runners/vale.js +0 -1
  116. package/dist/clients/dispatch/runners/yaml-rule-parser.js +51 -17
  117. package/dist/clients/dispatch/runners/yamllint.js +0 -1
  118. package/dist/clients/dispatch/runners/zig-check.js +0 -1
  119. package/dist/clients/disposition-logger.js +3 -3
  120. package/dist/clients/effective-config.js +403 -0
  121. package/dist/clients/error-class.js +23 -0
  122. package/dist/clients/event-loop-hold.js +274 -0
  123. package/dist/clients/event-loop-monitor.js +66 -1
  124. package/dist/clients/extension-log.js +2 -2
  125. package/dist/clients/feature-hints.js +2 -1
  126. package/dist/clients/file-time.js +6 -1
  127. package/dist/clients/file-utils.js +266 -13
  128. package/dist/clients/finding-delivery-gate.js +55 -13
  129. package/dist/clients/format-service.js +6 -1
  130. package/dist/clients/formatters.js +303 -104
  131. package/dist/clients/freshness-cadence.js +17 -0
  132. package/dist/clients/generated-artifacts.js +114 -19
  133. package/dist/clients/generation-guard.js +4 -9
  134. package/dist/clients/git-guard.js +198 -48
  135. package/dist/clients/git-tracked-ignore.js +32 -1
  136. package/dist/clients/go-client.js +39 -0
  137. package/dist/clients/govulncheck-client.js +5 -1
  138. package/dist/clients/gradle-ktfmt-style.js +252 -0
  139. package/dist/clients/gzip-stage-write.js +7 -0
  140. package/dist/clients/hashline-anchor.js +424 -0
  141. package/dist/clients/hook-budgets.js +76 -0
  142. package/dist/clients/host-edit-normalize.js +5 -2
  143. package/dist/clients/host-ports.js +1 -1
  144. package/dist/clients/installer/index.js +200 -84
  145. package/dist/clients/installer/managed-tool-refresh.js +3 -1
  146. package/dist/clients/instance-reaper.js +108 -243
  147. package/dist/clients/instance-registry-lock.js +145 -0
  148. package/dist/clients/instance-registry.js +435 -122
  149. package/dist/clients/jscpd-client.js +6 -1
  150. package/dist/clients/language-profile.js +4 -2
  151. package/dist/clients/language-registry.js +595 -0
  152. package/dist/clients/latency-logger.js +179 -3
  153. package/dist/clients/ledger-bounds.js +13 -0
  154. package/dist/clients/lens-config.js +141 -30
  155. package/dist/clients/lens-engine.js +30 -37
  156. package/dist/clients/lens-flag-registry.js +67 -6
  157. package/dist/clients/lens-map.js +3 -1
  158. package/dist/clients/log-cleanup.js +2 -2
  159. package/dist/clients/lsp/aggregation.js +3 -1
  160. package/dist/clients/lsp/cascade-tier.js +4 -0
  161. package/dist/clients/lsp/client.js +672 -49
  162. package/dist/clients/lsp/config.js +504 -156
  163. package/dist/clients/lsp/diagnostic-binding.js +10 -5
  164. package/dist/clients/lsp/edits.js +15 -2
  165. package/dist/clients/lsp/index.js +1179 -247
  166. package/dist/clients/lsp/jvm-runtime.js +5 -0
  167. package/dist/clients/lsp/language.js +18 -169
  168. package/dist/clients/lsp/launch.js +38 -9
  169. package/dist/clients/lsp/pending-aux-coverage.js +113 -12
  170. package/dist/clients/lsp/server.js +426 -160
  171. package/dist/clients/lsp/session-roots.js +192 -0
  172. package/dist/clients/lsp/spawn-history.js +2 -7
  173. package/dist/clients/lsp/tsserver-sync.js +9 -2
  174. package/dist/clients/lsp/workspace-diagnostics-cache.js +17 -7
  175. package/dist/clients/lsp/workspace-sweep-hold.js +32 -23
  176. package/dist/clients/lsp-mutation.js +179 -23
  177. package/dist/clients/map-with-concurrency.js +36 -0
  178. package/dist/clients/mcp/analyze.js +45 -10
  179. package/dist/clients/mcp/session.js +19 -17
  180. package/dist/clients/memory-sampler.js +28 -1
  181. package/dist/clients/message-end-attribution.js +30 -0
  182. package/dist/clients/metrics-history.js +21 -4
  183. package/dist/clients/middle-man-analysis.js +2 -4
  184. package/dist/clients/module-report.js +20 -45
  185. package/dist/clients/mutating-tool.js +651 -0
  186. package/dist/clients/mutation-attribution.js +368 -0
  187. package/dist/clients/mutation-bridge.js +240 -0
  188. package/dist/clients/ndjson-logger.js +247 -20
  189. package/dist/clients/observed-mutation-sources.js +101 -0
  190. package/dist/clients/observed-mutation.js +1215 -0
  191. package/dist/clients/opaque-mutation-scan.js +300 -40
  192. package/dist/clients/opengrep-config.js +4 -0
  193. package/dist/clients/package-manager.js +201 -44
  194. package/dist/clients/partial-edit-apply.js +359 -80
  195. package/dist/clients/path-attribution-telemetry.js +23 -7
  196. package/dist/clients/path-keyed-map.js +35 -3
  197. package/dist/clients/path-utils.js +460 -13
  198. package/dist/clients/persist-debounce.js +8 -1
  199. package/dist/clients/php-cs-fixer-config.js +114 -0
  200. package/dist/clients/pipeline.js +77 -24
  201. package/dist/clients/probe-home-state.js +228 -0
  202. package/dist/clients/process-bridge.js +66 -0
  203. package/dist/clients/process-singletons.js +210 -0
  204. package/dist/clients/process-snapshot.js +68 -0
  205. package/dist/clients/project-diagnostics/fresh-fetch.js +4 -3
  206. package/dist/clients/project-diagnostics/runner-adapters/madge.js +2 -1
  207. package/dist/clients/project-diagnostics/runner-adapters/runner-findings.js +27 -3
  208. package/dist/clients/project-diagnostics/scanner.js +61 -24
  209. package/dist/clients/project-lens-config.js +393 -122
  210. package/dist/clients/project-snapshot.js +85 -35
  211. package/dist/clients/python-environment.js +217 -0
  212. package/dist/clients/python-provenance.js +639 -0
  213. package/dist/clients/quiet-window.js +6 -1
  214. package/dist/clients/read-bridge.js +13 -21
  215. package/dist/clients/read-expansion.js +9 -46
  216. package/dist/clients/read-guard-logger.js +39 -6
  217. package/dist/clients/read-guard-tool-lines.js +364 -212
  218. package/dist/clients/read-guard.js +95 -7
  219. package/dist/clients/recent-touches.js +17 -5
  220. package/dist/clients/resource-sampler.js +195 -96
  221. package/dist/clients/review-graph/builder.js +752 -132
  222. package/dist/clients/review-graph/service.js +55 -3
  223. package/dist/clients/review-graph/shared-extraction-ir.js +7 -15
  224. package/dist/clients/review-graph/tsconfig-paths.js +5 -1
  225. package/dist/clients/review-graph/workspace-modules.js +10 -74
  226. package/dist/clients/review-graph-logger.js +30 -4
  227. package/dist/clients/runtime-agent-end.js +18 -2
  228. package/dist/clients/runtime-context.js +49 -16
  229. package/dist/clients/runtime-coordinator.js +93 -6
  230. package/dist/clients/runtime-session.js +169 -34
  231. package/dist/clients/runtime-tool-call.js +183 -35
  232. package/dist/clients/runtime-tool-result.js +894 -241
  233. package/dist/clients/runtime-turn.js +1264 -74
  234. package/dist/clients/rust-client.js +31 -0
  235. package/dist/clients/safe-spawn.js +191 -28
  236. package/dist/clients/sanitize.js +7 -1
  237. package/dist/clients/scratch-tree-policy.js +1 -3
  238. package/dist/clients/security-scan-client.js +51 -17
  239. package/dist/clients/session-lifecycle.js +238 -42
  240. package/dist/clients/session-start-observability.js +79 -0
  241. package/dist/clients/sessionstart-logger.js +12 -3
  242. package/dist/clients/sg-runner.js +27 -15
  243. package/dist/clients/sgconfig.js +6 -1
  244. package/dist/clients/shared-checkout-guard.js +338 -0
  245. package/dist/clients/skills-resolver.js +105 -0
  246. package/dist/clients/smells-rollup.js +2 -2
  247. package/dist/clients/spawn-output-cap.js +37 -0
  248. package/dist/clients/spawn-timeout-cooldown.js +15 -1
  249. package/dist/clients/startup-scan.js +6 -7
  250. package/dist/clients/startup-timing.js +69 -4
  251. package/dist/clients/string-utils.js +33 -0
  252. package/dist/clients/subagent-mode.js +17 -4
  253. package/dist/clients/test-runner-client.js +586 -118
  254. package/dist/clients/test-runner-delivery.js +239 -0
  255. package/dist/clients/tool-definition.js +41 -1
  256. package/dist/clients/tool-policy.js +92 -22
  257. package/dist/clients/tree-sitter-cache.js +40 -40
  258. package/dist/clients/tree-sitter-client.js +97 -53
  259. package/dist/clients/tree-sitter-logger.js +19 -3
  260. package/dist/clients/tree-sitter-query-loader.js +81 -1
  261. package/dist/clients/tree-sitter-shared.js +51 -46
  262. package/dist/clients/tree-sitter-symbol-extractor.js +28 -0
  263. package/dist/clients/typos-config.js +5 -0
  264. package/dist/clients/user-notify.js +6 -2
  265. package/dist/clients/warm-attach.js +8 -10
  266. package/dist/clients/widget-state.js +191 -26
  267. package/dist/clients/word-index-logger.js +15 -3
  268. package/dist/clients/word-index-store.js +463 -0
  269. package/dist/clients/word-index.js +815 -125
  270. package/dist/clients/workspace-topology.js +25 -1
  271. package/dist/clients/zizmor-config.js +29 -6
  272. package/dist/index.js +68577 -53950
  273. package/dist/mcp/analyze-cli.js +3 -1
  274. package/dist/mcp/build-staleness.js +8 -7
  275. package/dist/mcp/cli.js +3 -1
  276. package/dist/mcp/server.js +133 -6
  277. package/dist/scripts/lib/process-scan.mjs +583 -0
  278. package/dist/scripts/lib/skills-predicate.mjs +129 -0
  279. package/dist/tools/effective-config.js +89 -0
  280. package/dist/tools/lens-diagnostics.js +99 -24
  281. package/dist/tools/lsp-diagnostics.js +81 -85
  282. package/dist/tools/lsp-navigation.js +40 -17
  283. package/dist/tools/shared.js +0 -1
  284. package/docs/agent-guide.md +68 -3
  285. package/docs/ast-grep_rules_catalog.md +41 -10
  286. package/docs/astplayground.md +26 -17
  287. package/docs/configuration.md +222 -0
  288. package/docs/dependencies.md +3 -3
  289. package/docs/features.md +44 -5
  290. package/docs/language-coverage.md +2 -2
  291. package/docs/pi-lens-fixer.md +25 -0
  292. package/docs/pi-lens-investigator.md +25 -0
  293. package/docs/pi-lens-reviewer.md +27 -0
  294. package/docs/pi-lens-subagent.md +38 -0
  295. package/docs/pi-lens-warden.md +55 -0
  296. package/docs/public-api-stability.md +359 -0
  297. package/docs/release-qa-baseline.md +182 -0
  298. package/docs/subagent-compat.md +110 -30
  299. package/docs/tree-sitter_rules_catalog.md +2 -2
  300. package/package.json +17 -21
  301. package/rules/ast-grep-rules/rule-tests/c-no-malloc-free-test.yml +20 -0
  302. package/rules/ast-grep-rules/rule-tests/cpp-no-malloc-free-test.yml +25 -0
  303. package/rules/ast-grep-rules/rule-tests/cpp-no-printf-test.yml +19 -0
  304. package/rules/ast-grep-rules/rule-tests/go-no-fmt-println-test.yml +19 -0
  305. package/rules/ast-grep-rules/rule-tests/go-no-panic-in-lib-test.yml +17 -0
  306. package/rules/ast-grep-rules/rule-tests/go-no-underscore-func-name-test.yml +18 -0
  307. package/rules/ast-grep-rules/rule-tests/go-prefer-errors-is-test.yml +15 -0
  308. package/rules/ast-grep-rules/rule-tests/go-prefer-string-builder-test.yml +21 -0
  309. package/rules/ast-grep-rules/rule-tests/hyphenated-svg-attribute-test.yml +11 -0
  310. package/rules/ast-grep-rules/rule-tests/kotlin-no-lateinit-test.yml +17 -0
  311. package/rules/ast-grep-rules/rule-tests/kotlin-no-nullable-boolean-test.yml +15 -0
  312. package/rules/ast-grep-rules/rule-tests/kotlin-no-println-test.yml +19 -0
  313. package/rules/ast-grep-rules/rule-tests/kotlin-no-unnecessary-let-test.yml +7 -0
  314. package/rules/ast-grep-rules/rule-tests/kotlin-no-unsafe-cast-test.yml +7 -0
  315. package/rules/ast-grep-rules/rule-tests/kotlin-no-var-test.yml +7 -0
  316. package/rules/ast-grep-rules/rule-tests/kotlin-prefer-data-class-test.yml +25 -0
  317. package/rules/ast-grep-rules/rule-tests/kotlin-prefer-is-empty-test.yml +11 -0
  318. package/rules/ast-grep-rules/rule-tests/no-important-test.yml +21 -0
  319. package/rules/ast-grep-rules/rule-tests/no-raw-types-test.yml +30 -0
  320. package/rules/ast-grep-rules/rule-tests/no-string-concat-in-loop-test.yml +100 -0
  321. package/rules/ast-grep-rules/rule-tests/no-system-out-println-test.yml +7 -0
  322. package/rules/ast-grep-rules/rule-tests/prefer-string-is-empty-test.yml +7 -0
  323. package/rules/ast-grep-rules/rule-tests/python-optional-type-test.yml +9 -0
  324. package/rules/ast-grep-rules/rule-tests/reducible-list-comprehension-test.yml +11 -0
  325. package/rules/ast-grep-rules/rule-tests/ruby-symbol-to-proc-candidate-test.yml +10 -0
  326. package/rules/ast-grep-rules/rule-tests/rust-no-chars-enumerate-test.yml +7 -0
  327. package/rules/ast-grep-rules/rules/c-no-malloc-free.yml +39 -0
  328. package/rules/ast-grep-rules/rules/cpp-no-malloc-free.yml +45 -0
  329. package/rules/ast-grep-rules/rules/cpp-no-printf.yml +41 -0
  330. package/rules/ast-grep-rules/rules/go-no-fmt-println.yml +43 -0
  331. package/rules/ast-grep-rules/rules/go-no-panic-in-lib.yml +41 -0
  332. package/rules/ast-grep-rules/rules/go-no-underscore-func-name.yml +35 -0
  333. package/rules/ast-grep-rules/rules/go-prefer-errors-is.yml +40 -0
  334. package/rules/ast-grep-rules/rules/go-prefer-string-builder.yml +43 -0
  335. package/rules/ast-grep-rules/rules/hyphenated-svg-attribute.yml +32 -0
  336. package/rules/ast-grep-rules/rules/kotlin-no-lateinit.yml +37 -0
  337. package/rules/ast-grep-rules/rules/kotlin-no-nullable-boolean.yml +33 -0
  338. package/rules/ast-grep-rules/rules/kotlin-no-println.yml +42 -0
  339. package/rules/ast-grep-rules/rules/kotlin-no-unnecessary-let.yml +28 -0
  340. package/rules/ast-grep-rules/rules/kotlin-no-unsafe-cast.yml +28 -0
  341. package/rules/ast-grep-rules/rules/kotlin-no-var.yml +35 -0
  342. package/rules/ast-grep-rules/rules/kotlin-prefer-data-class.yml +66 -0
  343. package/rules/ast-grep-rules/rules/kotlin-prefer-is-empty.yml +35 -0
  344. package/rules/ast-grep-rules/rules/no-important.yml +21 -0
  345. package/rules/ast-grep-rules/rules/no-raw-types.yml +33 -0
  346. package/rules/ast-grep-rules/rules/no-string-concat-in-loop.yml +90 -0
  347. package/rules/ast-grep-rules/rules/no-system-out-println.yml +16 -0
  348. package/rules/ast-grep-rules/rules/prefer-string-is-empty.yml +11 -0
  349. package/rules/ast-grep-rules/rules/python-optional-type.yml +22 -0
  350. package/rules/ast-grep-rules/rules/reducible-list-comprehension.yml +29 -0
  351. package/rules/ast-grep-rules/rules/ruby-symbol-to-proc-candidate.yml +25 -0
  352. package/rules/ast-grep-rules/rules/rust-no-chars-enumerate.yml +19 -0
  353. package/rules/tree-sitter-queries/python/python-cross-language-method.yml +3 -3
  354. package/rules/tree-sitter-queries/python/python-hallucinated-import.yml +2 -2
  355. package/rules/tree-sitter-queries/python/python-sql-injection.yml +12 -2
  356. package/scripts/analyze-pi-lens-logs.mjs +192 -1
  357. package/scripts/install-selftest.mjs +58 -2
  358. package/scripts/lib/skills-predicate.mjs +129 -0
  359. package/scripts/rpc-load-check.mjs +3 -1
@@ -12,19 +12,18 @@
12
12
  * File shape: `{ instances: InstanceEntry[] }`. Missing or corrupt file is
13
13
  * treated as `{ instances: [] }` — this module must never throw on a read.
14
14
  *
15
- * Concurrency: every write is read-modify-write-whole-file with an atomic
16
- * tmp+rename (same pattern as clients/review-graph/builder.ts). Two
17
- * processes racing a write is a KNOWN, ACCEPTED race for slice 1
18
- * (last-writer-wins) — a lost update here only means a stale/missing
19
- * observability entry, never data corruption (the tmp+rename guarantees the
20
- * file itself is always valid JSON). A future slice can add file locking or
21
- * per-pid shard files if this proves too lossy in practice.
15
+ * Concurrency: every whole-file writer holds the adjacent `<registry>.lock`
16
+ * O_EXCL lock across its read-modify-write. Contenders use 5-25ms jittered
17
+ * backoff for up to 500ms; stale locks older than 5s or owned by a dead pid
18
+ * are displaced and reclaimed. A crash can still leave a stale lock during
19
+ * that window, so takeover remains deliberately bounded and observable.
22
20
  */
23
21
  import * as fs from "node:fs";
24
22
  import * as path from "node:path";
25
23
  import { writeFileAtomic, writeFileAtomicAsync } from "./atomic-write.js";
26
24
  import { recordDegradationOnce } from "./degradation-ledger.js";
27
25
  import { getGlobalPiLensDir } from "./file-utils.js";
26
+ import { withInstanceRegistryLock, withInstanceRegistryLockSync, } from "./instance-registry-lock.js";
28
27
  // #735: reuse the #449/#525 reaper's exact conservative liveness check
29
28
  // (`process.kill(pid, 0)`, ESRCH-only-means-dead) rather than inventing a
30
29
  // second one — see realIsPidAlive's own docstring, which already calls out
@@ -34,13 +33,19 @@ import { getGlobalPiLensDir } from "./file-utils.js";
34
33
  // use on both sides happens inside function bodies, never at module-
35
34
  // evaluation time, so both modules are fully initialized before either
36
35
  // import is actually invoked.
37
- import { realIsPidAlive } from "./instance-reaper.js";
36
+ import { realIsPidAlive, STALE_HEARTBEAT_MS } from "./instance-reaper.js";
38
37
  import { normalizeFilePath } from "./path-utils.js";
38
+ import { getProcessSingleton } from "./process-singletons.js";
39
39
  import { getSubagentIdentity, isSubagentSession } from "./subagent-mode.js";
40
40
  function registryPath() {
41
41
  return path.join(getGlobalPiLensDir(), "instances.json");
42
42
  }
43
43
  // --- Kill switch (lazy, memoized — house style per clients/runtime-config.ts) ---
44
+ // #2146 class-sweep verdict: STAYS at module scope. Duplicating this memo
45
+ // across module evaluations is wasteful, not wrong — every copy re-reads the
46
+ // same `process.env` and reaches the same answer, so no caller can observe a
47
+ // disagreement. Only state that is WRONG when duplicated moves to
48
+ // `process-singletons.ts`.
44
49
  let _enabledCache;
45
50
  /**
46
51
  * `PI_LENS_INSTANCE_REGISTRY=0` disables the registry entirely: every
@@ -140,6 +145,16 @@ async function writeRegistryAsync(file) {
140
145
  // never a thrown error for the caller.
141
146
  await writeFileAtomicAsync(target, JSON.stringify(file));
142
147
  }
148
+ const REGISTRY_WRITE_RETRIES = 3;
149
+ async function writeRegistryWithRetry(mutate, isCommitted) {
150
+ await withInstanceRegistryLock(registryPath(), async () => {
151
+ for (let attempt = 0; attempt < REGISTRY_WRITE_RETRIES; attempt++) {
152
+ await writeRegistryAsync(mutate(await readRegistryAsync()));
153
+ if (isCommitted(await readRegistryAsync()))
154
+ return;
155
+ }
156
+ });
157
+ }
143
158
  function writeRegistrySync(file) {
144
159
  const dir = getGlobalPiLensDir();
145
160
  const target = registryPath();
@@ -152,16 +167,76 @@ function writeRegistrySync(file) {
152
167
  writeFileAtomic(target, JSON.stringify(file));
153
168
  }
154
169
  // --- Mutations (all read-modify-write whole file) ---
155
- /** Create/overwrite this process's entry. */
156
- export async function registerInstance(projectRoot) {
170
+ /**
171
+ * Every root an entry serves, oldest first (#2130).
172
+ *
173
+ * The single reader for root identity in this module — no caller may compare
174
+ * `entry.projectRoot` directly, or a host's secondary roots become invisible
175
+ * again. Folds a pre-#2130 entry (no `projectRoots`) back to its scalar root,
176
+ * and drops non-string / empty members so a hand-edited or torn file cannot
177
+ * make a comparison throw.
178
+ */
179
+ export function getInstanceRoots(entry) {
180
+ const listed = Array.isArray(entry.projectRoots)
181
+ ? entry.projectRoots.filter((root) => typeof root === "string" && root.length > 0)
182
+ : [];
183
+ if (listed.length > 0)
184
+ return listed;
185
+ return typeof entry.projectRoot === "string" && entry.projectRoot.length > 0
186
+ ? [entry.projectRoot]
187
+ : [];
188
+ }
189
+ /**
190
+ * Bound on the per-host root set (#2130). A host that legitimately serves many
191
+ * worktrees must not grow an unbounded path list inside a file every other
192
+ * pi-lens process reads on every heartbeat. Eviction drops the OLDEST
193
+ * NON-PRIMARY root: `projectRoot` is the host's own working directory and the
194
+ * one the shared-checkout guard most needs, so it is never evicted.
195
+ * Deliberately smaller than `SESSION_ROOT_CAP` (128, `clients/lsp/
196
+ * session-roots.ts`) because that registry lives in memory for one process
197
+ * while this one is serialized to disk for all of them. The two are not
198
+ * mirrors: they answer different questions about different populations, so
199
+ * #2518's one-store rule (a root's LSP config cannot be evicted while the
200
+ * root is served) does not extend to this cap.
201
+ */
202
+ const INSTANCE_ROOT_CAP = 32;
203
+ /**
204
+ * The SINGLE owner of root-set semantics: dedupe, append order, and
205
+ * primary-preserving cap eviction (#2130).
206
+ *
207
+ * Both writers — `registerInstance` (the full session-start registration) and
208
+ * `registerInstanceRoot` (the lightweight add a declined secondary-root start
209
+ * performs) — fold through this, so the two can never disagree about what the
210
+ * set means. Pure, so the rule is testable without touching the filesystem.
211
+ */
212
+ export function mergeInstanceRoots(priorRoots, normalizedRoot) {
213
+ const roots = priorRoots.includes(normalizedRoot)
214
+ ? [...priorRoots]
215
+ : [...priorRoots, normalizedRoot];
216
+ // Evict from index 1 upward so the primary at index 0 survives.
217
+ while (roots.length > INSTANCE_ROOT_CAP)
218
+ roots.splice(1, 1);
219
+ return roots;
220
+ }
221
+ /**
222
+ * Register `projectRoot` for this process, ADDITIVELY (#2130).
223
+ *
224
+ * Creates the entry on first call and pins `projectRoot` as the primary. Every
225
+ * later call for a different root APPENDS to `projectRoots` instead of
226
+ * overwriting — that overwrite is the defect #2130 records, where a subagent
227
+ * temp worktree's session start made the host advertise a temp dir as its root.
228
+ * Re-registering a root already in the set is a no-op for the set (the
229
+ * heartbeat/rss fields still refresh).
230
+ */
231
+ export function registerInstance(projectRoot) {
232
+ return queueRegistryMutation(() => registerInstanceNow(projectRoot));
233
+ }
234
+ async function registerInstanceNow(projectRoot) {
157
235
  if (!isInstanceRegistryEnabled())
158
236
  return;
159
237
  const pid = process.pid;
160
238
  const normalizedRoot = normalizeFilePath(projectRoot);
161
- const file = await readRegistryAsync();
162
239
  const now = new Date().toISOString();
163
- const others = file.instances.filter((entry) => entry.pid !== pid);
164
- const existing = file.instances.find((entry) => entry.pid === pid);
165
240
  const identity = isSubagentSession() ? getSubagentIdentity() : undefined;
166
241
  const subagent = identity
167
242
  ? {
@@ -171,17 +246,96 @@ export async function registerInstance(projectRoot) {
171
246
  runId: identity.runId,
172
247
  }
173
248
  : undefined;
174
- others.push({
175
- pid,
176
- startedAt: existing?.startedAt ?? now,
177
- projectRoot: normalizedRoot,
178
- lspChildren: existing?.lspChildren ?? [],
179
- lspChildCount: existing?.lspChildren?.length ?? 0,
180
- rssBytes: process.memoryUsage().rss,
181
- heartbeatAt: now,
182
- ...(subagent ? { subagent } : {}),
249
+ await writeRegistryWithRetry((file) => {
250
+ const others = file.instances.filter((entry) => entry.pid !== pid);
251
+ const existing = file.instances.find((entry) => entry.pid === pid);
252
+ // #2130 round 2, class sweep. A `recordLspChild` that arrives before
253
+ // this call synthesizes the entry from `process.cwd()` and stamps
254
+ // `rootSource: "lsp-fallback"` to say so. Pinning made that GUESS
255
+ // permanent: the real session root joined the set behind it, and the
256
+ // host went on advertising a directory nobody asked it to serve —
257
+ // #2130's symptom reached through a different writer. So the first
258
+ // REAL registration takes the pin from a guessed primary. Any other
259
+ // `rootSource` ("session-cwd", "service-cwd") IS evidence of the root
260
+ // and keeps its pin, with this root appending behind it as usual.
261
+ //
262
+ // Review round 1, F1: ONLY index 0 is the guess. Everything behind it
263
+ // was appended by `registerInstanceRoot`, which is a declined
264
+ // secondary-root start recording a root it genuinely serves and which
265
+ // does not clear `rootSource`. Discarding the whole set would drop
266
+ // those, blinding the shared-checkout guard (#2107) to a live root —
267
+ // the same harm, inverted. Re-seed with the real root so it pins, then
268
+ // fold the rest back through `mergeInstanceRoots` so dedupe, order,
269
+ // and the cap stay single-owned.
270
+ const existingRoots = existing ? getInstanceRoots(existing) : [];
271
+ const roots = existing?.rootSource === "lsp-fallback"
272
+ ? existingRoots
273
+ .slice(1)
274
+ .reduce((acc, root) => mergeInstanceRoots(acc, root), [normalizedRoot])
275
+ : mergeInstanceRoots(existingRoots, normalizedRoot);
276
+ others.push({
277
+ pid,
278
+ startedAt: existing?.startedAt ?? now,
279
+ projectRoot: roots[0] ?? normalizedRoot,
280
+ projectRoots: roots,
281
+ lspChildren: existing?.lspChildren ?? [],
282
+ lspChildCount: existing?.lspChildren?.length ?? 0,
283
+ rssBytes: process.memoryUsage().rss,
284
+ heartbeatAt: now,
285
+ ...(subagent ? { subagent } : {}),
286
+ });
287
+ return { instances: others };
288
+ }, (file) => file.instances.some((entry) => entry.pid === pid));
289
+ }
290
+ /**
291
+ * Add ONE root to this process's existing entry (#2130), without any of
292
+ * `registerInstance`'s other side effects — no RSS resample, no `startedAt`
293
+ * reseed, no subagent-identity capture.
294
+ *
295
+ * This is what a DECLINED session start performs. `registerInstance` lives in
296
+ * the full-start body, below the #473/#2129 secondary gate, so a
297
+ * `secondary-root` start never reaches it. Without this call the temp root
298
+ * would be absent from `instances.json` entirely: the shared-checkout guard
299
+ * and warm attach would have LESS information about it than before #2130, and
300
+ * `deregisterInstanceRoot` would have nothing to remove.
301
+ *
302
+ * NEVER creates an entry. A declined start has no host entry to append to only
303
+ * when this process never registered one (the registry was reaped, or the
304
+ * primary's start has not landed yet). Synthesizing one here would write the
305
+ * TEMP root as `projectRoot` — reproducing the exact clobber #2130 is about —
306
+ * so this returns quietly instead. The next `registerInstance` re-creates the
307
+ * entry with the real root pinned.
308
+ *
309
+ * Shares the serialization tail with every other same-process registry
310
+ * mutation, so it cannot interleave its read-modify-write with a concurrent
311
+ * `registerInstance` and silently revert it (#1724).
312
+ */
313
+ export function registerInstanceRoot(projectRoot) {
314
+ return queueRegistryMutation(() => registerInstanceRootNow(projectRoot));
315
+ }
316
+ async function registerInstanceRootNow(projectRoot) {
317
+ if (!isInstanceRegistryEnabled())
318
+ return;
319
+ const pid = process.pid;
320
+ const normalizedRoot = normalizeFilePath(projectRoot);
321
+ await withInstanceRegistryLock(registryPath(), async () => {
322
+ const file = await readRegistryAsync();
323
+ const idx = file.instances.findIndex((entry) => entry.pid === pid);
324
+ if (idx === -1)
325
+ return;
326
+ const current = file.instances[idx];
327
+ const priorRoots = getInstanceRoots(current);
328
+ const roots = mergeInstanceRoots(priorRoots, normalizedRoot);
329
+ if (roots.length === priorRoots.length &&
330
+ roots.every((root, index) => root === priorRoots[index]))
331
+ return;
332
+ file.instances[idx] = {
333
+ ...current,
334
+ projectRoot: roots[0] ?? current.projectRoot,
335
+ projectRoots: roots,
336
+ };
337
+ await writeRegistryAsync(file);
183
338
  });
184
- await writeRegistryAsync({ instances: others });
185
339
  }
186
340
  /** Update this process's heartbeat/rss (and, since #620, host CPU% + live
187
341
  * LSP children's rss/CPU%). Cheap — safe to call every turn end. */
@@ -189,40 +343,43 @@ export async function updateHeartbeat(patch = {}) {
189
343
  if (!isInstanceRegistryEnabled())
190
344
  return;
191
345
  const pid = process.pid;
192
- const file = await readRegistryAsync();
193
- const idx = file.instances.findIndex((entry) => entry.pid === pid);
194
- if (idx === -1) {
195
- // No prior registerInstance in this run (e.g. registry file was reaped
196
- // out from under us, or heartbeat fired before session_start finished) —
197
- // nothing to update against; skip rather than fabricate a projectRoot.
198
- return;
199
- }
200
- const now = new Date().toISOString();
201
- const current = file.instances[idx];
202
- const lspChildren = patch.childUsage
203
- ? current.lspChildren.map((child) => {
204
- const usage = patch.childUsage?.[child.pid];
205
- if (!usage)
206
- return child;
207
- return {
208
- ...child,
209
- rssBytes: usage.rssBytes ?? child.rssBytes,
210
- cpuPercent: usage.cpuPercent ?? child.cpuPercent,
211
- };
212
- })
213
- : current.lspChildren;
214
- file.instances[idx] = {
215
- ...current,
216
- rssBytes: patch.rssBytes ?? process.memoryUsage().rss,
217
- cpuPercent: patch.cpuPercent ?? current.cpuPercent,
218
- lspChildren,
219
- lspChildCount: lspChildren.length,
220
- heartbeatAt: now,
221
- };
222
- await writeRegistryAsync(file);
346
+ await withInstanceRegistryLock(registryPath(), async () => {
347
+ const file = await readRegistryAsync();
348
+ const idx = file.instances.findIndex((entry) => entry.pid === pid);
349
+ if (idx === -1) {
350
+ // No prior registerInstance in this run (e.g. registry file was reaped
351
+ // out from under us, or heartbeat fired before session_start finished) —
352
+ // nothing to update against; skip rather than fabricate a projectRoot.
353
+ return;
354
+ }
355
+ const now = new Date().toISOString();
356
+ const current = file.instances[idx];
357
+ const lspChildren = patch.childUsage
358
+ ? current.lspChildren.map((child) => {
359
+ const usage = patch.childUsage?.[child.pid];
360
+ if (!usage)
361
+ return child;
362
+ return {
363
+ ...child,
364
+ rssBytes: usage.rssBytes ?? child.rssBytes,
365
+ cpuPercent: usage.cpuPercent ?? child.cpuPercent,
366
+ };
367
+ })
368
+ : current.lspChildren;
369
+ file.instances[idx] = {
370
+ ...current,
371
+ rssBytes: patch.rssBytes ?? process.memoryUsage().rss,
372
+ cpuPercent: patch.cpuPercent ?? current.cpuPercent,
373
+ lspChildren,
374
+ lspChildCount: lspChildren.length,
375
+ heartbeatAt: now,
376
+ };
377
+ await writeRegistryAsync(file);
378
+ });
223
379
  }
224
- // Every mutation below (`recordLspChild`, `removeLspChild`) reads the WHOLE
225
- // registry file, edits this process's own `lspChildren`, and writes the whole
380
+ // Every mutation routed through this tail (`registerInstance`,
381
+ // `registerInstanceRoot`, `recordLspChild`, `removeLspChild`) reads the WHOLE
382
+ // registry file, edits this process's own entry, and writes the whole
226
383
  // file back. Two such mutations from the SAME process — e.g. a client-ceiling
227
384
  // eviction's `removeLspChild(victimPid)` racing the replacement spawn's
228
385
  // `recordLspChild(newChild)` that follows it — are ordinary concurrent async
@@ -236,22 +393,50 @@ export async function updateHeartbeat(patch = {}) {
236
393
  // and "remove" can never interleave their read-modify-write against each
237
394
  // other — the single seam both the forced-shutdown and self-crash
238
395
  // deregistration paths route through.
239
- let registryChildMutationTail = Promise.resolve();
240
- function queueRegistryChildMutation(op) {
241
- const run = registryChildMutationTail.then(op);
242
- registryChildMutationTail = run.catch(() => { });
396
+ //
397
+ // #2146: the tail must be the PROCESS's one serialization point, and module
398
+ // scope did not deliver that. pi evaluates the pi-lens module graph up to nine
399
+ // times per process, so this module had up to nine tails, each serializing only
400
+ // its own callers. The dogfood run measured the consequence directly: three
401
+ // `instance-registry-corrupt` records inside nine seconds, with two project
402
+ // roots and one live instance's entry lost from `instances.json` — exactly the
403
+ // torn read-modify-write this tail exists to prevent, reintroduced by
404
+ // duplication rather than by a missing await. Keying it on `globalThis` makes
405
+ // every evaluation queue onto the same tail.
406
+ const REGISTRY_TAIL_FAMILY = "instance-registry.mutation-tail";
407
+ /** Bump when the tail cell's shape changes. */
408
+ const REGISTRY_TAIL_VERSION = 1;
409
+ function registryTailState() {
410
+ return getProcessSingleton(REGISTRY_TAIL_FAMILY, REGISTRY_TAIL_VERSION, () => ({
411
+ tail: Promise.resolve(),
412
+ }));
413
+ }
414
+ function queueRegistryMutation(op) {
415
+ const state = registryTailState();
416
+ const run = state.tail.then(op);
417
+ state.tail = run.catch(() => { });
243
418
  return run;
244
419
  }
420
+ /**
421
+ * Test-only: resolve once every registry mutation queued so far has landed.
422
+ *
423
+ * Several production call sites fire registry writes and deliberately do not
424
+ * await them (`void registerInstance(...)` in the session_start handler), so a
425
+ * test that reads the file straight afterwards races them. Queuing an empty op
426
+ * on the same tail joins the queue rather than sleeping on it, which keeps the
427
+ * wait exact instead of timing-dependent.
428
+ */
429
+ export function _settleRegistryMutationsForTests() {
430
+ return queueRegistryMutation(async () => { });
431
+ }
245
432
  /** Append/replace (by pid) an LSP child under this process's entry. */
246
433
  export function recordLspChild(entry) {
247
- return queueRegistryChildMutation(() => recordLspChildNow(entry));
434
+ return queueRegistryMutation(() => recordLspChildNow(entry));
248
435
  }
249
436
  async function recordLspChildNow(entry) {
250
437
  if (!isInstanceRegistryEnabled())
251
438
  return;
252
439
  const pid = process.pid;
253
- const file = await readRegistryAsync();
254
- const idx = file.instances.findIndex((inst) => inst.pid === pid);
255
440
  const now = new Date().toISOString();
256
441
  const childEntry = {
257
442
  pid: entry.pid,
@@ -260,30 +445,61 @@ async function recordLspChildNow(entry) {
260
445
  marker: entry.marker,
261
446
  spawnedAt: now,
262
447
  };
263
- if (idx === -1) {
264
- // registerInstance hasn't run yet in this process (or was reaped) —
265
- // synthesize a minimal entry so the child is still tracked.
266
- file.instances.push({
267
- pid,
268
- startedAt: now,
269
- projectRoot: normalizeFilePath(process.cwd()),
270
- lspChildren: [childEntry],
271
- lspChildCount: 1,
272
- rssBytes: process.memoryUsage().rss,
273
- heartbeatAt: now,
274
- });
275
- }
276
- else {
277
- const current = file.instances[idx];
278
- const filtered = current.lspChildren.filter((child) => child.pid !== entry.pid);
279
- filtered.push(childEntry);
280
- file.instances[idx] = {
281
- ...current,
282
- lspChildren: filtered,
283
- lspChildCount: filtered.length,
284
- };
285
- }
286
- await writeRegistryAsync(file);
448
+ const hostIdentity = getSubagentIdentity();
449
+ await writeRegistryWithRetry((file) => {
450
+ const idx = file.instances.findIndex((inst) => inst.pid === pid);
451
+ if (idx === -1) {
452
+ // registerInstance hasn't run yet in this process (or was reaped) —
453
+ // synthesize a minimal entry so the child is still tracked.
454
+ recordDegradationOnce({
455
+ kind: "instance-registry-registration-missing",
456
+ subject: String(pid),
457
+ reason: "synthesizing host entry while recording an LSP child",
458
+ });
459
+ const identity = entry.sessionIdentity;
460
+ if (!identity?.projectRoot) {
461
+ recordDegradationOnce({
462
+ kind: "instance-registry-identity-fallback",
463
+ subject: String(pid),
464
+ reason: "session cwd unavailable; using process cwd",
465
+ });
466
+ }
467
+ const projectRoot = normalizeFilePath(identity?.projectRoot ?? process.cwd());
468
+ file.instances.push({
469
+ pid,
470
+ startedAt: identity?.startedAt ?? now,
471
+ projectRoot,
472
+ rootSource: identity?.rootSource ?? "lsp-fallback",
473
+ projectRoots: [projectRoot],
474
+ lspChildren: [childEntry],
475
+ lspChildCount: 1,
476
+ rssBytes: process.memoryUsage().rss,
477
+ heartbeatAt: now,
478
+ ...(hostIdentity
479
+ ? {
480
+ subagent: {
481
+ marker: hostIdentity.marker,
482
+ agentType: hostIdentity.agentName,
483
+ parentPid: hostIdentity.parentPid,
484
+ runId: hostIdentity.runId,
485
+ },
486
+ }
487
+ : {}),
488
+ });
489
+ }
490
+ else {
491
+ const current = file.instances[idx];
492
+ const filtered = current.lspChildren.filter((child) => child.pid !== entry.pid);
493
+ filtered.push(childEntry);
494
+ file.instances[idx] = {
495
+ ...current,
496
+ lspChildren: filtered,
497
+ lspChildCount: filtered.length,
498
+ };
499
+ }
500
+ return file;
501
+ }, (file) => file.instances.some((instance) => instance.pid === pid &&
502
+ instance.lspChildren.some((child) => child.pid === entry.pid)));
287
503
  }
288
504
  /**
289
505
  * Remove an LSP child (by pid) from this process's entry. `expectedMarker`,
@@ -299,33 +515,35 @@ async function recordLspChildNow(entry) {
299
515
  * of that exact pid, well inside the OS's pid-reuse latency.
300
516
  */
301
517
  export function removeLspChild(pid, expectedMarker) {
302
- return queueRegistryChildMutation(() => removeLspChildNow(pid, expectedMarker));
518
+ return queueRegistryMutation(() => removeLspChildNow(pid, expectedMarker));
303
519
  }
304
520
  async function removeLspChildNow(pid, expectedMarker) {
305
521
  if (!isInstanceRegistryEnabled())
306
522
  return;
307
523
  const selfPid = process.pid;
308
- const file = await readRegistryAsync();
309
- const idx = file.instances.findIndex((inst) => inst.pid === selfPid);
310
- if (idx === -1)
311
- return;
312
- const current = file.instances[idx];
313
- const filtered = current.lspChildren.filter((child) => {
314
- if (child.pid !== pid)
315
- return true; // keep — different pid
316
- if (expectedMarker && child.marker && child.marker !== expectedMarker) {
317
- return true; // keep — pid recycled onto a differently-marked child
318
- }
319
- return false; // drop — this is the child we're deregistering
524
+ await withInstanceRegistryLock(registryPath(), async () => {
525
+ const file = await readRegistryAsync();
526
+ const idx = file.instances.findIndex((inst) => inst.pid === selfPid);
527
+ if (idx === -1)
528
+ return;
529
+ const current = file.instances[idx];
530
+ const filtered = current.lspChildren.filter((child) => {
531
+ if (child.pid !== pid)
532
+ return true; // keep — different pid
533
+ if (expectedMarker && child.marker && child.marker !== expectedMarker) {
534
+ return true; // keep — pid recycled onto a differently-marked child
535
+ }
536
+ return false; // drop — this is the child we're deregistering
537
+ });
538
+ if (filtered.length === current.lspChildren.length)
539
+ return; // nothing removed
540
+ file.instances[idx] = {
541
+ ...current,
542
+ lspChildren: filtered,
543
+ lspChildCount: filtered.length,
544
+ };
545
+ await writeRegistryAsync(file);
320
546
  });
321
- if (filtered.length === current.lspChildren.length)
322
- return; // nothing removed
323
- file.instances[idx] = {
324
- ...current,
325
- lspChildren: filtered,
326
- lspChildCount: filtered.length,
327
- };
328
- await writeRegistryAsync(file);
329
547
  }
330
548
  /**
331
549
  * Remove this process's entry entirely. SYNC fs only — safe to call from
@@ -336,11 +554,98 @@ export function deregisterInstance() {
336
554
  if (!isInstanceRegistryEnabled())
337
555
  return;
338
556
  const pid = process.pid;
339
- const file = readRegistrySync();
340
- const remaining = file.instances.filter((entry) => entry.pid !== pid);
341
- if (remaining.length === file.instances.length)
342
- return; // nothing to remove
343
- writeRegistrySync({ instances: remaining });
557
+ withInstanceRegistryLockSync(registryPath(), () => {
558
+ const file = readRegistrySync();
559
+ const remaining = file.instances.filter((entry) => entry.pid !== pid);
560
+ if (remaining.length === file.instances.length)
561
+ return;
562
+ writeRegistrySync({ instances: remaining });
563
+ });
564
+ }
565
+ /**
566
+ * Drop ONE root from this process's entry (#2130) — the scoped counterpart to
567
+ * {@link deregisterInstance}, for a worktree this host stops serving while the
568
+ * host itself keeps running.
569
+ *
570
+ * SYNC fs inside, matching `deregisterInstance`'s `session_shutdown` contract
571
+ * (#234: no child spawns at teardown; this function spawns none). Removing the
572
+ * LAST root removes the whole entry — a host serving no root is not a peer any
573
+ * caller should find. Removing the primary promotes the next root to
574
+ * `projectRoot` rather than leaving a stale scalar behind.
575
+ *
576
+ * QUEUED, unlike `deregisterInstance` (#2130 round 2). The two look alike but
577
+ * run at opposite ends of a process's life. `deregisterInstance` runs as the
578
+ * HOST exits, where a queued write may never get a turn, so it must bypass the
579
+ * tail and write immediately. This one runs at a SECONDARY's shutdown, where
580
+ * the process lives on and the ordering is what matters: a declined start fires
581
+ * `void registerInstanceRoot(cwd)` onto the tail (index.ts:1851) and never
582
+ * awaits it, so a short-lived subagent reaching shutdown first would remove a
583
+ * root that had not been added yet. The removal found nothing, the queued add
584
+ * landed behind it, and the temp root LEAKED until host exit or cap eviction.
585
+ * Sharing the tail makes remove-after-add hold by construction.
586
+ *
587
+ * The returned promise resolves when the removal has landed. Callers in
588
+ * teardown paths may fire and forget it — the tail still orders the write —
589
+ * but they can no longer read the file straight afterwards and expect the
590
+ * removal to be visible.
591
+ */
592
+ export function deregisterInstanceRoot(projectRoot) {
593
+ return queueRegistryMutation(async () => deregisterInstanceRootNow(projectRoot));
594
+ }
595
+ function deregisterInstanceRootNow(projectRoot) {
596
+ if (!isInstanceRegistryEnabled())
597
+ return;
598
+ const pid = process.pid;
599
+ const normalizedRoot = normalizeFilePath(projectRoot);
600
+ withInstanceRegistryLockSync(registryPath(), () => {
601
+ const file = readRegistrySync();
602
+ const idx = file.instances.findIndex((entry) => entry.pid === pid);
603
+ if (idx === -1)
604
+ return;
605
+ const current = file.instances[idx];
606
+ const remainingRoots = getInstanceRoots(current).filter((root) => root !== normalizedRoot);
607
+ if (remainingRoots.length === getInstanceRoots(current).length)
608
+ return;
609
+ if (remainingRoots.length === 0) {
610
+ writeRegistrySync({
611
+ instances: file.instances.filter((entry) => entry.pid !== pid),
612
+ });
613
+ return;
614
+ }
615
+ file.instances[idx] = {
616
+ ...current,
617
+ projectRoot: remainingRoots[0],
618
+ projectRoots: remainingRoots,
619
+ };
620
+ writeRegistrySync(file);
621
+ });
622
+ }
623
+ /**
624
+ * True when `a` and `b` are the same directory, or one contains the other.
625
+ * Compared on SEGMENT boundaries, so `/repo-backup` never matches `/repo`.
626
+ */
627
+ function rootsOverlap(a, b) {
628
+ if (a === b)
629
+ return true;
630
+ const [shorter, longer] = a.length < b.length ? [a, b] : [b, a];
631
+ return longer.startsWith(shorter.endsWith("/") ? shorter : `${shorter}/`);
632
+ }
633
+ export function selectLivePeerInstances(entries, root, now = Date.now(), isPidAlive = realIsPidAlive, match = "exact") {
634
+ const normalizedRoot = normalizeFilePath(root);
635
+ return entries
636
+ .filter((entry) => entry.pid !== process.pid &&
637
+ // #2130: a host serves a SET of roots. Matching only
638
+ // `entry.projectRoot` made every secondary root invisible, so a peer
639
+ // working in the same checkout under its second root read as "no
640
+ // peer" — and the shared-checkout guard then allowed the destructive
641
+ // command it exists to block.
642
+ getInstanceRoots(entry).some((entryRoot) => match === "exact"
643
+ ? entryRoot === normalizedRoot
644
+ : rootsOverlap(entryRoot, normalizedRoot)) &&
645
+ isPidAlive(entry.pid) &&
646
+ Number.isFinite(Date.parse(entry.heartbeatAt)) &&
647
+ now - Date.parse(entry.heartbeatAt) <= STALE_HEARTBEAT_MS)
648
+ .sort((a, b) => Date.parse(a.startedAt) - Date.parse(b.startedAt));
344
649
  }
345
650
  /**
346
651
  * PURE aggregation over a registry snapshot: "how much CPU/RAM is pi-lens
@@ -383,9 +688,11 @@ export function computeResourceFootprint(instances, isPidAlive) {
383
688
  const perInstance = liveInstances.map((instance) => {
384
689
  const lspChildRssBytes = instance.lspChildren.reduce((sum, child) => sum + (child.rssBytes ?? 0), 0);
385
690
  const lspChildCpuPercent = instance.lspChildren.reduce((sum, child) => sum + (child.cpuPercent ?? 0), 0);
691
+ const roots = getInstanceRoots(instance);
386
692
  return {
387
693
  pid: instance.pid,
388
- projectRoot: instance.projectRoot,
694
+ projectRoot: roots[0] ?? instance.projectRoot,
695
+ projectRoots: roots,
389
696
  rssBytes: instance.rssBytes ?? 0,
390
697
  cpuPercent: instance.cpuPercent ?? 0,
391
698
  lspChildCount: instance.lspChildren.length,
@@ -448,13 +755,19 @@ export async function getResourceFootprint(isPidAlive = realIsPidAlive) {
448
755
  * an earlier snapshot) to narrow — not eliminate — the last-writer-wins race
449
756
  * already accepted for this module's read-modify-write model (see the
450
757
  * module docstring). Mirrors clients/instance-reaper.ts's
451
- * `pruneDeadInstances`, kept local here rather than imported to avoid
452
- * reaching back across the same import edge `realIsPidAlive` already
453
- * crosses in the other direction. */
758
+ * `pruneDeadInstances` in the reaper delegates here so this module owns the
759
+ * registry lock seam without creating a dependency on the reaper. */
760
+ export async function pruneDeadInstances(deadPids) {
761
+ const result = await withInstanceRegistryLock(registryPath(), async () => {
762
+ const file = await readRegistryAsync();
763
+ const remaining = file.instances.filter((entry) => !deadPids.has(entry.pid));
764
+ if (remaining.length === file.instances.length)
765
+ return "no-match";
766
+ await writeRegistryAsync({ instances: remaining });
767
+ return "pruned";
768
+ });
769
+ return result ?? "could-not-acquire";
770
+ }
454
771
  async function prunePids(deadPids) {
455
- const file = await readRegistryAsync();
456
- const remaining = file.instances.filter((entry) => !deadPids.has(entry.pid));
457
- if (remaining.length === file.instances.length)
458
- return;
459
- await writeRegistryAsync({ instances: remaining });
772
+ await pruneDeadInstances(deadPids);
460
773
  }