@herbertgao/pi-extensions 2026.8.13 → 2026.8.15

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 (263) hide show
  1. package/README.md +19 -14
  2. package/THIRD_PARTY_NOTICES.md +0 -1
  3. package/node_modules/@czottmann/pi-automode/CHANGELOG.md +19 -0
  4. package/node_modules/@czottmann/pi-automode/README.md +5 -1
  5. package/node_modules/@czottmann/pi-automode/extensions/auto-mode/classifier.ts +126 -13
  6. package/node_modules/@czottmann/pi-automode/extensions/auto-mode/config.ts +7 -3
  7. package/node_modules/@czottmann/pi-automode/extensions/auto-mode/constants.ts +2 -0
  8. package/node_modules/@czottmann/pi-automode/extensions/auto-mode/hard-deny.ts +134 -23
  9. package/node_modules/@czottmann/pi-automode/package.json +1 -1
  10. package/node_modules/@herbertgao/{pi-stash → pi-bark}/LICENSE +4 -5
  11. package/node_modules/@herbertgao/pi-bark/README.md +44 -0
  12. package/node_modules/@herbertgao/pi-bark/assets/pi-icon.png +0 -0
  13. package/node_modules/@herbertgao/pi-bark/package.json +53 -0
  14. package/node_modules/@herbertgao/pi-bark/src/index.ts +178 -0
  15. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +1 -1
  16. package/node_modules/@herbertgao/pi-cc-extensions/README.md +1 -1
  17. package/node_modules/@herbertgao/pi-cc-extensions/package.json +3 -3
  18. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +6 -0
  19. package/node_modules/@herbertgao/pi-subagents/package.json +2 -1
  20. package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +8 -1
  21. package/node_modules/@juicesharp/rpiv-ask-user-question/package.json +2 -2
  22. package/node_modules/@narumitw/pi-btw/README.md +125 -88
  23. package/node_modules/@narumitw/pi-btw/dist/index.ts +140 -45
  24. package/node_modules/@narumitw/pi-btw/dist/index.ts.map +2 -2
  25. package/node_modules/@narumitw/pi-btw/package.json +5 -8
  26. package/node_modules/@narumitw/pi-btw/src/btw.ts +31 -26
  27. package/node_modules/@narumitw/pi-btw/src/fullscreen-ui.ts +106 -17
  28. package/node_modules/@narumitw/pi-btw/src/menu.ts +34 -2
  29. package/node_modules/@narumitw/pi-btw/src/settings.ts +16 -0
  30. package/node_modules/@tifan/pi-handoff/README.md +36 -13
  31. package/node_modules/@tifan/pi-handoff/package.json +2 -2
  32. package/node_modules/@tifan/pi-handoff/src/index.ts +160 -4
  33. package/node_modules/@tifan/pi-preferred-thinking/README.md +1 -1
  34. package/node_modules/@tifan/pi-preferred-thinking/package.json +1 -1
  35. package/node_modules/@tifan/pi-preferred-thinking/src/index.ts +15 -2
  36. package/node_modules/@tifan/pi-recap/README.md +1 -1
  37. package/node_modules/@tifan/pi-recap/package.json +2 -2
  38. package/node_modules/@tifan/pi-recap/src/index.ts +15 -0
  39. package/node_modules/@tifan/pi-rename/README.md +42 -21
  40. package/node_modules/@tifan/pi-rename/package.json +1 -1
  41. package/node_modules/@tifan/pi-rename/src/index.ts +62 -11
  42. package/node_modules/@tifan/pi-rename/src/language.ts +18 -0
  43. package/node_modules/@tifan/pi-rename/src/models.ts +69 -13
  44. package/node_modules/@tifan/pi-rename/src/naming.ts +36 -7
  45. package/node_modules/@tifan/pi-rename/src/sanitize.ts +22 -14
  46. package/node_modules/pi-lens/CHANGELOG.md +320 -0
  47. package/node_modules/pi-lens/config/dependency-cruiser-eager-allowlist.json +79 -0
  48. package/node_modules/pi-lens/dist/clients/actionable-warnings-logger.js +16 -1
  49. package/node_modules/pi-lens/dist/clients/ast-grep-client.js +13 -6
  50. package/node_modules/pi-lens/dist/clients/availability-probe-flight.js +12 -0
  51. package/node_modules/pi-lens/dist/clients/biome-client.js +7 -0
  52. package/node_modules/pi-lens/dist/clients/blocker-freshness.js +20 -0
  53. package/node_modules/pi-lens/dist/clients/bounded-telemetry.js +56 -19
  54. package/node_modules/pi-lens/dist/clients/build-identity.js +95 -0
  55. package/node_modules/pi-lens/dist/clients/bus-publish.js +3 -0
  56. package/node_modules/pi-lens/dist/clients/cache/rule-cache.js +2 -1
  57. package/node_modules/pi-lens/dist/clients/cache-observability.js +2 -1
  58. package/node_modules/pi-lens/dist/clients/cascade-logger.js +15 -1
  59. package/node_modules/pi-lens/dist/clients/dead-code-client.js +14 -11
  60. package/node_modules/pi-lens/dist/clients/degradation-ledger.js +56 -4
  61. package/node_modules/pi-lens/dist/clients/demoted-finding-render.js +14 -0
  62. package/node_modules/pi-lens/dist/clients/dependency-checker.js +20 -3
  63. package/node_modules/pi-lens/dist/clients/deps/minimatch.js +1 -1
  64. package/node_modules/pi-lens/dist/clients/dispatch/collect-later-tier.js +39 -0
  65. package/node_modules/pi-lens/dist/clients/dispatch/dispatcher.js +150 -9
  66. package/node_modules/pi-lens/dist/clients/dispatch/fact-store.js +231 -9
  67. package/node_modules/pi-lens/dist/clients/dispatch/integration.js +205 -100
  68. package/node_modules/pi-lens/dist/clients/dispatch/pending-runner-findings.js +87 -0
  69. package/node_modules/pi-lens/dist/clients/dispatch/plan.js +21 -5
  70. package/node_modules/pi-lens/dist/clients/dispatch/runners/ast-grep-napi.js +174 -55
  71. package/node_modules/pi-lens/dist/clients/dispatch/runners/eslint.js +5 -1
  72. package/node_modules/pi-lens/dist/clients/dispatch/runners/helm-lint.js +16 -3
  73. package/node_modules/pi-lens/dist/clients/dispatch/runners/helm-render.js +54 -9
  74. package/node_modules/pi-lens/dist/clients/dispatch/runners/index.js +1 -3
  75. package/node_modules/pi-lens/dist/clients/dispatch/runners/lsp.js +37 -1
  76. package/node_modules/pi-lens/dist/clients/dispatch/runners/markdownlint.js +4 -1
  77. package/node_modules/pi-lens/dist/clients/dispatch/runners/oxlint.js +11 -4
  78. package/node_modules/pi-lens/dist/clients/dispatch/runners/psscriptanalyzer.js +4 -0
  79. package/node_modules/pi-lens/dist/clients/dispatch/runners/rust-clippy.js +8 -3
  80. package/node_modules/pi-lens/dist/clients/dispatch/runners/utils/runner-helpers.js +76 -25
  81. package/node_modules/pi-lens/dist/clients/dispatch/runners/utils/spawn-outcome.js +4 -0
  82. package/node_modules/pi-lens/dist/clients/dispatch/runners/utils/tool-failure.js +19 -7
  83. package/node_modules/pi-lens/dist/clients/dispatch/runners/utils/toolchain-availability.js +7 -13
  84. package/node_modules/pi-lens/dist/clients/dispatch/runners/yaml-rule-parser.js +51 -17
  85. package/node_modules/pi-lens/dist/clients/event-loop-monitor.js +66 -1
  86. package/node_modules/pi-lens/dist/clients/file-utils.js +157 -7
  87. package/node_modules/pi-lens/dist/clients/finding-delivery-gate.js +5 -0
  88. package/node_modules/pi-lens/dist/clients/formatters.js +28 -3
  89. package/node_modules/pi-lens/dist/clients/git-guard.js +197 -47
  90. package/node_modules/pi-lens/dist/clients/git-tracked-ignore.js +32 -1
  91. package/node_modules/pi-lens/dist/clients/govulncheck-client.js +5 -1
  92. package/node_modules/pi-lens/dist/clients/gzip-stage-write.js +7 -0
  93. package/node_modules/pi-lens/dist/clients/installer/index.js +131 -34
  94. package/node_modules/pi-lens/dist/clients/installer/managed-tool-refresh.js +3 -1
  95. package/node_modules/pi-lens/dist/clients/instance-reaper.js +4 -13
  96. package/node_modules/pi-lens/dist/clients/instance-registry-lock.js +145 -0
  97. package/node_modules/pi-lens/dist/clients/instance-registry.js +432 -122
  98. package/node_modules/pi-lens/dist/clients/jscpd-client.js +6 -1
  99. package/node_modules/pi-lens/dist/clients/language-profile.js +4 -2
  100. package/node_modules/pi-lens/dist/clients/latency-logger.js +19 -1
  101. package/node_modules/pi-lens/dist/clients/lens-flag-registry.js +8 -0
  102. package/node_modules/pi-lens/dist/clients/lens-map.js +3 -1
  103. package/node_modules/pi-lens/dist/clients/lsp/cascade-tier.js +4 -0
  104. package/node_modules/pi-lens/dist/clients/lsp/client.js +516 -31
  105. package/node_modules/pi-lens/dist/clients/lsp/config.js +25 -2
  106. package/node_modules/pi-lens/dist/clients/lsp/diagnostic-binding.js +9 -4
  107. package/node_modules/pi-lens/dist/clients/lsp/index.js +509 -182
  108. package/node_modules/pi-lens/dist/clients/lsp/jvm-runtime.js +5 -0
  109. package/node_modules/pi-lens/dist/clients/lsp/launch.js +36 -8
  110. package/node_modules/pi-lens/dist/clients/lsp/pending-aux-coverage.js +116 -4
  111. package/node_modules/pi-lens/dist/clients/lsp/server.js +142 -13
  112. package/node_modules/pi-lens/dist/clients/lsp/session-roots.js +99 -0
  113. package/node_modules/pi-lens/dist/clients/lsp/workspace-diagnostics-cache.js +16 -6
  114. package/node_modules/pi-lens/dist/clients/lsp/workspace-sweep-hold.js +32 -23
  115. package/node_modules/pi-lens/dist/clients/lsp-mutation.js +16 -2
  116. package/node_modules/pi-lens/dist/clients/mcp/analyze.js +12 -6
  117. package/node_modules/pi-lens/dist/clients/mcp/session.js +14 -1
  118. package/node_modules/pi-lens/dist/clients/memory-sampler.js +23 -1
  119. package/node_modules/pi-lens/dist/clients/message-end-attribution.js +30 -0
  120. package/node_modules/pi-lens/dist/clients/metrics-history.js +21 -4
  121. package/node_modules/pi-lens/dist/clients/opaque-mutation-scan.js +232 -18
  122. package/node_modules/pi-lens/dist/clients/package-manager.js +6 -18
  123. package/node_modules/pi-lens/dist/clients/path-keyed-map.js +14 -1
  124. package/node_modules/pi-lens/dist/clients/path-utils.js +32 -0
  125. package/node_modules/pi-lens/dist/clients/pipeline.js +0 -8
  126. package/node_modules/pi-lens/dist/clients/process-singletons.js +210 -0
  127. package/node_modules/pi-lens/dist/clients/project-diagnostics/runner-adapters/madge.js +2 -1
  128. package/node_modules/pi-lens/dist/clients/project-diagnostics/scanner.js +10 -4
  129. package/node_modules/pi-lens/dist/clients/project-snapshot.js +33 -11
  130. package/node_modules/pi-lens/dist/clients/read-guard-logger.js +24 -2
  131. package/node_modules/pi-lens/dist/clients/read-guard.js +74 -7
  132. package/node_modules/pi-lens/dist/clients/recent-touches.js +17 -5
  133. package/node_modules/pi-lens/dist/clients/review-graph/builder.js +639 -62
  134. package/node_modules/pi-lens/dist/clients/review-graph/tsconfig-paths.js +5 -1
  135. package/node_modules/pi-lens/dist/clients/review-graph-logger.js +21 -1
  136. package/node_modules/pi-lens/dist/clients/runtime-coordinator.js +68 -0
  137. package/node_modules/pi-lens/dist/clients/runtime-session.js +30 -12
  138. package/node_modules/pi-lens/dist/clients/runtime-tool-call.js +15 -0
  139. package/node_modules/pi-lens/dist/clients/runtime-tool-result.js +106 -7
  140. package/node_modules/pi-lens/dist/clients/runtime-turn.js +242 -27
  141. package/node_modules/pi-lens/dist/clients/safe-spawn.js +158 -18
  142. package/node_modules/pi-lens/dist/clients/security-scan-client.js +48 -17
  143. package/node_modules/pi-lens/dist/clients/session-lifecycle.js +238 -42
  144. package/node_modules/pi-lens/dist/clients/sg-runner.js +27 -15
  145. package/node_modules/pi-lens/dist/clients/shared-checkout-guard.js +338 -0
  146. package/node_modules/pi-lens/dist/clients/spawn-output-cap.js +37 -0
  147. package/node_modules/pi-lens/dist/clients/spawn-timeout-cooldown.js +15 -1
  148. package/node_modules/pi-lens/dist/clients/startup-scan.js +6 -7
  149. package/node_modules/pi-lens/dist/clients/startup-timing.js +69 -4
  150. package/node_modules/pi-lens/dist/clients/string-utils.js +20 -0
  151. package/node_modules/pi-lens/dist/clients/test-runner-client.js +419 -88
  152. package/node_modules/pi-lens/dist/clients/tool-policy.js +1 -1
  153. package/node_modules/pi-lens/dist/clients/tree-sitter-client.js +11 -5
  154. package/node_modules/pi-lens/dist/clients/tree-sitter-logger.js +17 -1
  155. package/node_modules/pi-lens/dist/clients/warm-attach.js +8 -10
  156. package/node_modules/pi-lens/dist/clients/word-index-logger.js +13 -1
  157. package/node_modules/pi-lens/dist/clients/word-index-store.js +448 -0
  158. package/node_modules/pi-lens/dist/clients/word-index.js +582 -104
  159. package/node_modules/pi-lens/dist/clients/workspace-topology.js +17 -0
  160. package/node_modules/pi-lens/dist/clients/zizmor-config.js +26 -6
  161. package/node_modules/pi-lens/dist/index.js +11243 -6651
  162. package/node_modules/pi-lens/dist/mcp/build-staleness.js +8 -7
  163. package/node_modules/pi-lens/dist/mcp/cli.js +3 -1
  164. package/node_modules/pi-lens/dist/mcp/server.js +6 -1
  165. package/node_modules/pi-lens/dist/tools/lens-diagnostics.js +4 -0
  166. package/node_modules/pi-lens/dist/tools/lsp-diagnostics.js +14 -5
  167. package/node_modules/pi-lens/dist/tools/lsp-navigation.js +3 -1
  168. package/node_modules/pi-lens/docs/agent-guide.md +4 -2
  169. package/node_modules/pi-lens/docs/ast-grep_rules_catalog.md +41 -10
  170. package/node_modules/pi-lens/docs/astplayground.md +26 -17
  171. package/node_modules/pi-lens/package.json +5 -1
  172. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/c-no-malloc-free-test.yml +20 -0
  173. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/cpp-no-malloc-free-test.yml +25 -0
  174. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/cpp-no-printf-test.yml +19 -0
  175. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/go-no-fmt-println-test.yml +19 -0
  176. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/go-no-panic-in-lib-test.yml +17 -0
  177. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/go-no-underscore-func-name-test.yml +18 -0
  178. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/go-prefer-errors-is-test.yml +15 -0
  179. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/go-prefer-string-builder-test.yml +21 -0
  180. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/hyphenated-svg-attribute-test.yml +11 -0
  181. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/kotlin-no-lateinit-test.yml +17 -0
  182. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/kotlin-no-nullable-boolean-test.yml +15 -0
  183. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/kotlin-no-println-test.yml +19 -0
  184. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/kotlin-no-unnecessary-let-test.yml +7 -0
  185. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/kotlin-no-unsafe-cast-test.yml +7 -0
  186. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/kotlin-no-var-test.yml +7 -0
  187. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/kotlin-prefer-data-class-test.yml +25 -0
  188. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/kotlin-prefer-is-empty-test.yml +11 -0
  189. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-important-test.yml +21 -0
  190. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-raw-types-test.yml +30 -0
  191. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-string-concat-in-loop-test.yml +100 -0
  192. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-system-out-println-test.yml +7 -0
  193. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/prefer-string-is-empty-test.yml +7 -0
  194. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/python-optional-type-test.yml +9 -0
  195. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/reducible-list-comprehension-test.yml +11 -0
  196. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/ruby-symbol-to-proc-candidate-test.yml +10 -0
  197. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/rust-no-chars-enumerate-test.yml +7 -0
  198. package/node_modules/pi-lens/rules/ast-grep-rules/rules/c-no-malloc-free.yml +39 -0
  199. package/node_modules/pi-lens/rules/ast-grep-rules/rules/cpp-no-malloc-free.yml +45 -0
  200. package/node_modules/pi-lens/rules/ast-grep-rules/rules/cpp-no-printf.yml +41 -0
  201. package/node_modules/pi-lens/rules/ast-grep-rules/rules/go-no-fmt-println.yml +43 -0
  202. package/node_modules/pi-lens/rules/ast-grep-rules/rules/go-no-panic-in-lib.yml +41 -0
  203. package/node_modules/pi-lens/rules/ast-grep-rules/rules/go-no-underscore-func-name.yml +35 -0
  204. package/node_modules/pi-lens/rules/ast-grep-rules/rules/go-prefer-errors-is.yml +40 -0
  205. package/node_modules/pi-lens/rules/ast-grep-rules/rules/go-prefer-string-builder.yml +43 -0
  206. package/node_modules/pi-lens/rules/ast-grep-rules/rules/hyphenated-svg-attribute.yml +32 -0
  207. package/node_modules/pi-lens/rules/ast-grep-rules/rules/kotlin-no-lateinit.yml +37 -0
  208. package/node_modules/pi-lens/rules/ast-grep-rules/rules/kotlin-no-nullable-boolean.yml +33 -0
  209. package/node_modules/pi-lens/rules/ast-grep-rules/rules/kotlin-no-println.yml +42 -0
  210. package/node_modules/pi-lens/rules/ast-grep-rules/rules/kotlin-no-unnecessary-let.yml +28 -0
  211. package/node_modules/pi-lens/rules/ast-grep-rules/rules/kotlin-no-unsafe-cast.yml +28 -0
  212. package/node_modules/pi-lens/rules/ast-grep-rules/rules/kotlin-no-var.yml +35 -0
  213. package/node_modules/pi-lens/rules/ast-grep-rules/rules/kotlin-prefer-data-class.yml +66 -0
  214. package/node_modules/pi-lens/rules/ast-grep-rules/rules/kotlin-prefer-is-empty.yml +35 -0
  215. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-important.yml +21 -0
  216. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-raw-types.yml +33 -0
  217. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-string-concat-in-loop.yml +90 -0
  218. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-system-out-println.yml +16 -0
  219. package/node_modules/pi-lens/rules/ast-grep-rules/rules/prefer-string-is-empty.yml +11 -0
  220. package/node_modules/pi-lens/rules/ast-grep-rules/rules/python-optional-type.yml +22 -0
  221. package/node_modules/pi-lens/rules/ast-grep-rules/rules/reducible-list-comprehension.yml +29 -0
  222. package/node_modules/pi-lens/rules/ast-grep-rules/rules/ruby-symbol-to-proc-candidate.yml +25 -0
  223. package/node_modules/pi-lens/rules/ast-grep-rules/rules/rust-no-chars-enumerate.yml +19 -0
  224. package/node_modules/pi-mcp-adapter/CHANGELOG.md +35 -0
  225. package/node_modules/pi-mcp-adapter/README.md +5 -2
  226. package/node_modules/pi-mcp-adapter/cli.js +4 -4
  227. package/node_modules/pi-mcp-adapter/commands.ts +1 -1
  228. package/node_modules/pi-mcp-adapter/config.ts +1 -0
  229. package/node_modules/pi-mcp-adapter/dist/config.js +1 -0
  230. package/node_modules/pi-mcp-adapter/dist/config.js.map +1 -1
  231. package/node_modules/pi-mcp-adapter/dist/mcp-bearer-store.d.ts +24 -0
  232. package/node_modules/pi-mcp-adapter/dist/mcp-bearer-store.js +336 -0
  233. package/node_modules/pi-mcp-adapter/dist/mcp-bearer-store.js.map +1 -0
  234. package/node_modules/pi-mcp-adapter/dist/types.d.ts +3 -1
  235. package/node_modules/pi-mcp-adapter/dist/types.js.map +1 -1
  236. package/node_modules/pi-mcp-adapter/index.ts +90 -6
  237. package/node_modules/pi-mcp-adapter/mcp-auth-flow.ts +124 -32
  238. package/node_modules/pi-mcp-adapter/mcp-bearer-store.ts +0 -2
  239. package/node_modules/pi-mcp-adapter/mcp-oauth-provider.ts +89 -0
  240. package/node_modules/pi-mcp-adapter/mcp-references.ts +9 -1
  241. package/node_modules/pi-mcp-adapter/package.json +1 -1
  242. package/node_modules/pi-mcp-adapter/proxy-modes.ts +62 -22
  243. package/node_modules/pi-mcp-adapter/request-headers-command.ts +1 -1
  244. package/node_modules/pi-mcp-adapter/server-manager.ts +6 -0
  245. package/node_modules/pi-mcp-adapter/types.ts +3 -1
  246. package/node_modules/pi-web-access/CHANGELOG.md +42 -0
  247. package/node_modules/pi-web-access/README.md +26 -10
  248. package/node_modules/pi-web-access/curator-page.ts +12 -3
  249. package/node_modules/pi-web-access/curator-server.ts +3 -1
  250. package/node_modules/pi-web-access/extract.ts +88 -13
  251. package/node_modules/pi-web-access/gemini-search.ts +10 -5
  252. package/node_modules/pi-web-access/github-extract.ts +47 -3
  253. package/node_modules/pi-web-access/index.ts +40 -40
  254. package/node_modules/pi-web-access/package.json +1 -1
  255. package/node_modules/pi-web-access/page-query.ts +61 -8
  256. package/node_modules/pi-web-access/xcrawl.ts +264 -0
  257. package/package.json +19 -22
  258. package/node_modules/@herbertgao/pi-stash/README.md +0 -34
  259. package/node_modules/@herbertgao/pi-stash/package.json +0 -51
  260. package/node_modules/@herbertgao/pi-stash/src/index.ts +0 -118
  261. package/node_modules/@tifan/pi-titlebar-spinner/README.md +0 -24
  262. package/node_modules/@tifan/pi-titlebar-spinner/package.json +0 -39
  263. package/node_modules/@tifan/pi-titlebar-spinner/src/index.ts +0 -49
@@ -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,73 @@ 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,
196
+ * `clients/lsp/session-roots.ts:45`) because that set lives in memory for one
197
+ * process while this one is serialized to disk for all of them.
198
+ */
199
+ const INSTANCE_ROOT_CAP = 32;
200
+ /**
201
+ * The SINGLE owner of root-set semantics: dedupe, append order, and
202
+ * primary-preserving cap eviction (#2130).
203
+ *
204
+ * Both writers — `registerInstance` (the full session-start registration) and
205
+ * `registerInstanceRoot` (the lightweight add a declined secondary-root start
206
+ * performs) — fold through this, so the two can never disagree about what the
207
+ * set means. Pure, so the rule is testable without touching the filesystem.
208
+ */
209
+ export function mergeInstanceRoots(priorRoots, normalizedRoot) {
210
+ const roots = priorRoots.includes(normalizedRoot)
211
+ ? [...priorRoots]
212
+ : [...priorRoots, normalizedRoot];
213
+ // Evict from index 1 upward so the primary at index 0 survives.
214
+ while (roots.length > INSTANCE_ROOT_CAP)
215
+ roots.splice(1, 1);
216
+ return roots;
217
+ }
218
+ /**
219
+ * Register `projectRoot` for this process, ADDITIVELY (#2130).
220
+ *
221
+ * Creates the entry on first call and pins `projectRoot` as the primary. Every
222
+ * later call for a different root APPENDS to `projectRoots` instead of
223
+ * overwriting — that overwrite is the defect #2130 records, where a subagent
224
+ * temp worktree's session start made the host advertise a temp dir as its root.
225
+ * Re-registering a root already in the set is a no-op for the set (the
226
+ * heartbeat/rss fields still refresh).
227
+ */
228
+ export function registerInstance(projectRoot) {
229
+ return queueRegistryMutation(() => registerInstanceNow(projectRoot));
230
+ }
231
+ async function registerInstanceNow(projectRoot) {
157
232
  if (!isInstanceRegistryEnabled())
158
233
  return;
159
234
  const pid = process.pid;
160
235
  const normalizedRoot = normalizeFilePath(projectRoot);
161
- const file = await readRegistryAsync();
162
236
  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
237
  const identity = isSubagentSession() ? getSubagentIdentity() : undefined;
166
238
  const subagent = identity
167
239
  ? {
@@ -171,17 +243,96 @@ export async function registerInstance(projectRoot) {
171
243
  runId: identity.runId,
172
244
  }
173
245
  : 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 } : {}),
246
+ await writeRegistryWithRetry((file) => {
247
+ const others = file.instances.filter((entry) => entry.pid !== pid);
248
+ const existing = file.instances.find((entry) => entry.pid === pid);
249
+ // #2130 round 2, class sweep. A `recordLspChild` that arrives before
250
+ // this call synthesizes the entry from `process.cwd()` and stamps
251
+ // `rootSource: "lsp-fallback"` to say so. Pinning made that GUESS
252
+ // permanent: the real session root joined the set behind it, and the
253
+ // host went on advertising a directory nobody asked it to serve —
254
+ // #2130's symptom reached through a different writer. So the first
255
+ // REAL registration takes the pin from a guessed primary. Any other
256
+ // `rootSource` ("session-cwd", "service-cwd") IS evidence of the root
257
+ // and keeps its pin, with this root appending behind it as usual.
258
+ //
259
+ // Review round 1, F1: ONLY index 0 is the guess. Everything behind it
260
+ // was appended by `registerInstanceRoot`, which is a declined
261
+ // secondary-root start recording a root it genuinely serves and which
262
+ // does not clear `rootSource`. Discarding the whole set would drop
263
+ // those, blinding the shared-checkout guard (#2107) to a live root —
264
+ // the same harm, inverted. Re-seed with the real root so it pins, then
265
+ // fold the rest back through `mergeInstanceRoots` so dedupe, order,
266
+ // and the cap stay single-owned.
267
+ const existingRoots = existing ? getInstanceRoots(existing) : [];
268
+ const roots = existing?.rootSource === "lsp-fallback"
269
+ ? existingRoots
270
+ .slice(1)
271
+ .reduce((acc, root) => mergeInstanceRoots(acc, root), [normalizedRoot])
272
+ : mergeInstanceRoots(existingRoots, normalizedRoot);
273
+ others.push({
274
+ pid,
275
+ startedAt: existing?.startedAt ?? now,
276
+ projectRoot: roots[0] ?? normalizedRoot,
277
+ projectRoots: roots,
278
+ lspChildren: existing?.lspChildren ?? [],
279
+ lspChildCount: existing?.lspChildren?.length ?? 0,
280
+ rssBytes: process.memoryUsage().rss,
281
+ heartbeatAt: now,
282
+ ...(subagent ? { subagent } : {}),
283
+ });
284
+ return { instances: others };
285
+ }, (file) => file.instances.some((entry) => entry.pid === pid));
286
+ }
287
+ /**
288
+ * Add ONE root to this process's existing entry (#2130), without any of
289
+ * `registerInstance`'s other side effects — no RSS resample, no `startedAt`
290
+ * reseed, no subagent-identity capture.
291
+ *
292
+ * This is what a DECLINED session start performs. `registerInstance` lives in
293
+ * the full-start body, below the #473/#2129 secondary gate, so a
294
+ * `secondary-root` start never reaches it. Without this call the temp root
295
+ * would be absent from `instances.json` entirely: the shared-checkout guard
296
+ * and warm attach would have LESS information about it than before #2130, and
297
+ * `deregisterInstanceRoot` would have nothing to remove.
298
+ *
299
+ * NEVER creates an entry. A declined start has no host entry to append to only
300
+ * when this process never registered one (the registry was reaped, or the
301
+ * primary's start has not landed yet). Synthesizing one here would write the
302
+ * TEMP root as `projectRoot` — reproducing the exact clobber #2130 is about —
303
+ * so this returns quietly instead. The next `registerInstance` re-creates the
304
+ * entry with the real root pinned.
305
+ *
306
+ * Shares the serialization tail with every other same-process registry
307
+ * mutation, so it cannot interleave its read-modify-write with a concurrent
308
+ * `registerInstance` and silently revert it (#1724).
309
+ */
310
+ export function registerInstanceRoot(projectRoot) {
311
+ return queueRegistryMutation(() => registerInstanceRootNow(projectRoot));
312
+ }
313
+ async function registerInstanceRootNow(projectRoot) {
314
+ if (!isInstanceRegistryEnabled())
315
+ return;
316
+ const pid = process.pid;
317
+ const normalizedRoot = normalizeFilePath(projectRoot);
318
+ await withInstanceRegistryLock(registryPath(), async () => {
319
+ const file = await readRegistryAsync();
320
+ const idx = file.instances.findIndex((entry) => entry.pid === pid);
321
+ if (idx === -1)
322
+ return;
323
+ const current = file.instances[idx];
324
+ const priorRoots = getInstanceRoots(current);
325
+ const roots = mergeInstanceRoots(priorRoots, normalizedRoot);
326
+ if (roots.length === priorRoots.length &&
327
+ roots.every((root, index) => root === priorRoots[index]))
328
+ return;
329
+ file.instances[idx] = {
330
+ ...current,
331
+ projectRoot: roots[0] ?? current.projectRoot,
332
+ projectRoots: roots,
333
+ };
334
+ await writeRegistryAsync(file);
183
335
  });
184
- await writeRegistryAsync({ instances: others });
185
336
  }
186
337
  /** Update this process's heartbeat/rss (and, since #620, host CPU% + live
187
338
  * LSP children's rss/CPU%). Cheap — safe to call every turn end. */
@@ -189,40 +340,43 @@ export async function updateHeartbeat(patch = {}) {
189
340
  if (!isInstanceRegistryEnabled())
190
341
  return;
191
342
  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);
343
+ await withInstanceRegistryLock(registryPath(), async () => {
344
+ const file = await readRegistryAsync();
345
+ const idx = file.instances.findIndex((entry) => entry.pid === pid);
346
+ if (idx === -1) {
347
+ // No prior registerInstance in this run (e.g. registry file was reaped
348
+ // out from under us, or heartbeat fired before session_start finished) —
349
+ // nothing to update against; skip rather than fabricate a projectRoot.
350
+ return;
351
+ }
352
+ const now = new Date().toISOString();
353
+ const current = file.instances[idx];
354
+ const lspChildren = patch.childUsage
355
+ ? current.lspChildren.map((child) => {
356
+ const usage = patch.childUsage?.[child.pid];
357
+ if (!usage)
358
+ return child;
359
+ return {
360
+ ...child,
361
+ rssBytes: usage.rssBytes ?? child.rssBytes,
362
+ cpuPercent: usage.cpuPercent ?? child.cpuPercent,
363
+ };
364
+ })
365
+ : current.lspChildren;
366
+ file.instances[idx] = {
367
+ ...current,
368
+ rssBytes: patch.rssBytes ?? process.memoryUsage().rss,
369
+ cpuPercent: patch.cpuPercent ?? current.cpuPercent,
370
+ lspChildren,
371
+ lspChildCount: lspChildren.length,
372
+ heartbeatAt: now,
373
+ };
374
+ await writeRegistryAsync(file);
375
+ });
223
376
  }
224
- // Every mutation below (`recordLspChild`, `removeLspChild`) reads the WHOLE
225
- // registry file, edits this process's own `lspChildren`, and writes the whole
377
+ // Every mutation routed through this tail (`registerInstance`,
378
+ // `registerInstanceRoot`, `recordLspChild`, `removeLspChild`) reads the WHOLE
379
+ // registry file, edits this process's own entry, and writes the whole
226
380
  // file back. Two such mutations from the SAME process — e.g. a client-ceiling
227
381
  // eviction's `removeLspChild(victimPid)` racing the replacement spawn's
228
382
  // `recordLspChild(newChild)` that follows it — are ordinary concurrent async
@@ -236,22 +390,50 @@ export async function updateHeartbeat(patch = {}) {
236
390
  // and "remove" can never interleave their read-modify-write against each
237
391
  // other — the single seam both the forced-shutdown and self-crash
238
392
  // deregistration paths route through.
239
- let registryChildMutationTail = Promise.resolve();
240
- function queueRegistryChildMutation(op) {
241
- const run = registryChildMutationTail.then(op);
242
- registryChildMutationTail = run.catch(() => { });
393
+ //
394
+ // #2146: the tail must be the PROCESS's one serialization point, and module
395
+ // scope did not deliver that. pi evaluates the pi-lens module graph up to nine
396
+ // times per process, so this module had up to nine tails, each serializing only
397
+ // its own callers. The dogfood run measured the consequence directly: three
398
+ // `instance-registry-corrupt` records inside nine seconds, with two project
399
+ // roots and one live instance's entry lost from `instances.json` — exactly the
400
+ // torn read-modify-write this tail exists to prevent, reintroduced by
401
+ // duplication rather than by a missing await. Keying it on `globalThis` makes
402
+ // every evaluation queue onto the same tail.
403
+ const REGISTRY_TAIL_FAMILY = "instance-registry.mutation-tail";
404
+ /** Bump when the tail cell's shape changes. */
405
+ const REGISTRY_TAIL_VERSION = 1;
406
+ function registryTailState() {
407
+ return getProcessSingleton(REGISTRY_TAIL_FAMILY, REGISTRY_TAIL_VERSION, () => ({
408
+ tail: Promise.resolve(),
409
+ }));
410
+ }
411
+ function queueRegistryMutation(op) {
412
+ const state = registryTailState();
413
+ const run = state.tail.then(op);
414
+ state.tail = run.catch(() => { });
243
415
  return run;
244
416
  }
417
+ /**
418
+ * Test-only: resolve once every registry mutation queued so far has landed.
419
+ *
420
+ * Several production call sites fire registry writes and deliberately do not
421
+ * await them (`void registerInstance(...)` in the session_start handler), so a
422
+ * test that reads the file straight afterwards races them. Queuing an empty op
423
+ * on the same tail joins the queue rather than sleeping on it, which keeps the
424
+ * wait exact instead of timing-dependent.
425
+ */
426
+ export function _settleRegistryMutationsForTests() {
427
+ return queueRegistryMutation(async () => { });
428
+ }
245
429
  /** Append/replace (by pid) an LSP child under this process's entry. */
246
430
  export function recordLspChild(entry) {
247
- return queueRegistryChildMutation(() => recordLspChildNow(entry));
431
+ return queueRegistryMutation(() => recordLspChildNow(entry));
248
432
  }
249
433
  async function recordLspChildNow(entry) {
250
434
  if (!isInstanceRegistryEnabled())
251
435
  return;
252
436
  const pid = process.pid;
253
- const file = await readRegistryAsync();
254
- const idx = file.instances.findIndex((inst) => inst.pid === pid);
255
437
  const now = new Date().toISOString();
256
438
  const childEntry = {
257
439
  pid: entry.pid,
@@ -260,30 +442,61 @@ async function recordLspChildNow(entry) {
260
442
  marker: entry.marker,
261
443
  spawnedAt: now,
262
444
  };
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);
445
+ const hostIdentity = getSubagentIdentity();
446
+ await writeRegistryWithRetry((file) => {
447
+ const idx = file.instances.findIndex((inst) => inst.pid === pid);
448
+ if (idx === -1) {
449
+ // registerInstance hasn't run yet in this process (or was reaped) —
450
+ // synthesize a minimal entry so the child is still tracked.
451
+ recordDegradationOnce({
452
+ kind: "instance-registry-registration-missing",
453
+ subject: String(pid),
454
+ reason: "synthesizing host entry while recording an LSP child",
455
+ });
456
+ const identity = entry.sessionIdentity;
457
+ if (!identity?.projectRoot) {
458
+ recordDegradationOnce({
459
+ kind: "instance-registry-identity-fallback",
460
+ subject: String(pid),
461
+ reason: "session cwd unavailable; using process cwd",
462
+ });
463
+ }
464
+ const projectRoot = normalizeFilePath(identity?.projectRoot ?? process.cwd());
465
+ file.instances.push({
466
+ pid,
467
+ startedAt: identity?.startedAt ?? now,
468
+ projectRoot,
469
+ rootSource: identity?.rootSource ?? "lsp-fallback",
470
+ projectRoots: [projectRoot],
471
+ lspChildren: [childEntry],
472
+ lspChildCount: 1,
473
+ rssBytes: process.memoryUsage().rss,
474
+ heartbeatAt: now,
475
+ ...(hostIdentity
476
+ ? {
477
+ subagent: {
478
+ marker: hostIdentity.marker,
479
+ agentType: hostIdentity.agentName,
480
+ parentPid: hostIdentity.parentPid,
481
+ runId: hostIdentity.runId,
482
+ },
483
+ }
484
+ : {}),
485
+ });
486
+ }
487
+ else {
488
+ const current = file.instances[idx];
489
+ const filtered = current.lspChildren.filter((child) => child.pid !== entry.pid);
490
+ filtered.push(childEntry);
491
+ file.instances[idx] = {
492
+ ...current,
493
+ lspChildren: filtered,
494
+ lspChildCount: filtered.length,
495
+ };
496
+ }
497
+ return file;
498
+ }, (file) => file.instances.some((instance) => instance.pid === pid &&
499
+ instance.lspChildren.some((child) => child.pid === entry.pid)));
287
500
  }
288
501
  /**
289
502
  * Remove an LSP child (by pid) from this process's entry. `expectedMarker`,
@@ -299,33 +512,35 @@ async function recordLspChildNow(entry) {
299
512
  * of that exact pid, well inside the OS's pid-reuse latency.
300
513
  */
301
514
  export function removeLspChild(pid, expectedMarker) {
302
- return queueRegistryChildMutation(() => removeLspChildNow(pid, expectedMarker));
515
+ return queueRegistryMutation(() => removeLspChildNow(pid, expectedMarker));
303
516
  }
304
517
  async function removeLspChildNow(pid, expectedMarker) {
305
518
  if (!isInstanceRegistryEnabled())
306
519
  return;
307
520
  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
521
+ await withInstanceRegistryLock(registryPath(), async () => {
522
+ const file = await readRegistryAsync();
523
+ const idx = file.instances.findIndex((inst) => inst.pid === selfPid);
524
+ if (idx === -1)
525
+ return;
526
+ const current = file.instances[idx];
527
+ const filtered = current.lspChildren.filter((child) => {
528
+ if (child.pid !== pid)
529
+ return true; // keep — different pid
530
+ if (expectedMarker && child.marker && child.marker !== expectedMarker) {
531
+ return true; // keep — pid recycled onto a differently-marked child
532
+ }
533
+ return false; // drop — this is the child we're deregistering
534
+ });
535
+ if (filtered.length === current.lspChildren.length)
536
+ return; // nothing removed
537
+ file.instances[idx] = {
538
+ ...current,
539
+ lspChildren: filtered,
540
+ lspChildCount: filtered.length,
541
+ };
542
+ await writeRegistryAsync(file);
320
543
  });
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
544
  }
330
545
  /**
331
546
  * Remove this process's entry entirely. SYNC fs only — safe to call from
@@ -336,11 +551,98 @@ export function deregisterInstance() {
336
551
  if (!isInstanceRegistryEnabled())
337
552
  return;
338
553
  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 });
554
+ withInstanceRegistryLockSync(registryPath(), () => {
555
+ const file = readRegistrySync();
556
+ const remaining = file.instances.filter((entry) => entry.pid !== pid);
557
+ if (remaining.length === file.instances.length)
558
+ return;
559
+ writeRegistrySync({ instances: remaining });
560
+ });
561
+ }
562
+ /**
563
+ * Drop ONE root from this process's entry (#2130) — the scoped counterpart to
564
+ * {@link deregisterInstance}, for a worktree this host stops serving while the
565
+ * host itself keeps running.
566
+ *
567
+ * SYNC fs inside, matching `deregisterInstance`'s `session_shutdown` contract
568
+ * (#234: no child spawns at teardown; this function spawns none). Removing the
569
+ * LAST root removes the whole entry — a host serving no root is not a peer any
570
+ * caller should find. Removing the primary promotes the next root to
571
+ * `projectRoot` rather than leaving a stale scalar behind.
572
+ *
573
+ * QUEUED, unlike `deregisterInstance` (#2130 round 2). The two look alike but
574
+ * run at opposite ends of a process's life. `deregisterInstance` runs as the
575
+ * HOST exits, where a queued write may never get a turn, so it must bypass the
576
+ * tail and write immediately. This one runs at a SECONDARY's shutdown, where
577
+ * the process lives on and the ordering is what matters: a declined start fires
578
+ * `void registerInstanceRoot(cwd)` onto the tail (index.ts:1851) and never
579
+ * awaits it, so a short-lived subagent reaching shutdown first would remove a
580
+ * root that had not been added yet. The removal found nothing, the queued add
581
+ * landed behind it, and the temp root LEAKED until host exit or cap eviction.
582
+ * Sharing the tail makes remove-after-add hold by construction.
583
+ *
584
+ * The returned promise resolves when the removal has landed. Callers in
585
+ * teardown paths may fire and forget it — the tail still orders the write —
586
+ * but they can no longer read the file straight afterwards and expect the
587
+ * removal to be visible.
588
+ */
589
+ export function deregisterInstanceRoot(projectRoot) {
590
+ return queueRegistryMutation(async () => deregisterInstanceRootNow(projectRoot));
591
+ }
592
+ function deregisterInstanceRootNow(projectRoot) {
593
+ if (!isInstanceRegistryEnabled())
594
+ return;
595
+ const pid = process.pid;
596
+ const normalizedRoot = normalizeFilePath(projectRoot);
597
+ withInstanceRegistryLockSync(registryPath(), () => {
598
+ const file = readRegistrySync();
599
+ const idx = file.instances.findIndex((entry) => entry.pid === pid);
600
+ if (idx === -1)
601
+ return;
602
+ const current = file.instances[idx];
603
+ const remainingRoots = getInstanceRoots(current).filter((root) => root !== normalizedRoot);
604
+ if (remainingRoots.length === getInstanceRoots(current).length)
605
+ return;
606
+ if (remainingRoots.length === 0) {
607
+ writeRegistrySync({
608
+ instances: file.instances.filter((entry) => entry.pid !== pid),
609
+ });
610
+ return;
611
+ }
612
+ file.instances[idx] = {
613
+ ...current,
614
+ projectRoot: remainingRoots[0],
615
+ projectRoots: remainingRoots,
616
+ };
617
+ writeRegistrySync(file);
618
+ });
619
+ }
620
+ /**
621
+ * True when `a` and `b` are the same directory, or one contains the other.
622
+ * Compared on SEGMENT boundaries, so `/repo-backup` never matches `/repo`.
623
+ */
624
+ function rootsOverlap(a, b) {
625
+ if (a === b)
626
+ return true;
627
+ const [shorter, longer] = a.length < b.length ? [a, b] : [b, a];
628
+ return longer.startsWith(shorter.endsWith("/") ? shorter : `${shorter}/`);
629
+ }
630
+ export function selectLivePeerInstances(entries, root, now = Date.now(), isPidAlive = realIsPidAlive, match = "exact") {
631
+ const normalizedRoot = normalizeFilePath(root);
632
+ return entries
633
+ .filter((entry) => entry.pid !== process.pid &&
634
+ // #2130: a host serves a SET of roots. Matching only
635
+ // `entry.projectRoot` made every secondary root invisible, so a peer
636
+ // working in the same checkout under its second root read as "no
637
+ // peer" — and the shared-checkout guard then allowed the destructive
638
+ // command it exists to block.
639
+ getInstanceRoots(entry).some((entryRoot) => match === "exact"
640
+ ? entryRoot === normalizedRoot
641
+ : rootsOverlap(entryRoot, normalizedRoot)) &&
642
+ isPidAlive(entry.pid) &&
643
+ Number.isFinite(Date.parse(entry.heartbeatAt)) &&
644
+ now - Date.parse(entry.heartbeatAt) <= STALE_HEARTBEAT_MS)
645
+ .sort((a, b) => Date.parse(a.startedAt) - Date.parse(b.startedAt));
344
646
  }
345
647
  /**
346
648
  * PURE aggregation over a registry snapshot: "how much CPU/RAM is pi-lens
@@ -383,9 +685,11 @@ export function computeResourceFootprint(instances, isPidAlive) {
383
685
  const perInstance = liveInstances.map((instance) => {
384
686
  const lspChildRssBytes = instance.lspChildren.reduce((sum, child) => sum + (child.rssBytes ?? 0), 0);
385
687
  const lspChildCpuPercent = instance.lspChildren.reduce((sum, child) => sum + (child.cpuPercent ?? 0), 0);
688
+ const roots = getInstanceRoots(instance);
386
689
  return {
387
690
  pid: instance.pid,
388
- projectRoot: instance.projectRoot,
691
+ projectRoot: roots[0] ?? instance.projectRoot,
692
+ projectRoots: roots,
389
693
  rssBytes: instance.rssBytes ?? 0,
390
694
  cpuPercent: instance.cpuPercent ?? 0,
391
695
  lspChildCount: instance.lspChildren.length,
@@ -448,13 +752,19 @@ export async function getResourceFootprint(isPidAlive = realIsPidAlive) {
448
752
  * an earlier snapshot) to narrow — not eliminate — the last-writer-wins race
449
753
  * already accepted for this module's read-modify-write model (see the
450
754
  * 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. */
755
+ * `pruneDeadInstances` in the reaper delegates here so this module owns the
756
+ * registry lock seam without creating a dependency on the reaper. */
757
+ export async function pruneDeadInstances(deadPids) {
758
+ const result = await withInstanceRegistryLock(registryPath(), async () => {
759
+ const file = await readRegistryAsync();
760
+ const remaining = file.instances.filter((entry) => !deadPids.has(entry.pid));
761
+ if (remaining.length === file.instances.length)
762
+ return "no-match";
763
+ await writeRegistryAsync({ instances: remaining });
764
+ return "pruned";
765
+ });
766
+ return result ?? "could-not-acquire";
767
+ }
454
768
  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 });
769
+ await pruneDeadInstances(deadPids);
460
770
  }