@herbertgao/pi-extensions 2026.10.12 → 2026.10.14

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 (269) hide show
  1. package/README.md +11 -11
  2. package/THIRD_PARTY_NOTICES.md +3 -3
  3. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +7 -9
  4. package/node_modules/@herbertgao/pi-cc-extensions/README.md +7 -9
  5. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/config.ts +1 -0
  6. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +14 -8
  7. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/context.ts +22 -5
  8. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/footer.ts +28 -6
  9. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +33 -12
  10. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +60 -17
  11. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/default-mode.ts +1 -5
  12. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/index.ts +20 -5
  13. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/markdown-enhance.ts +4 -1
  14. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/interaction.ts +42 -18
  15. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/layout.ts +12 -3
  16. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/ccstyle-tool.ts +131 -0
  17. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/grouping.ts +217 -113
  18. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/names.ts +12 -5
  19. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/subagent-notification.ts +556 -0
  20. package/node_modules/@herbertgao/pi-cc-extensions/extensions/utils/ansi-text.ts +50 -0
  21. package/node_modules/@herbertgao/pi-cc-extensions/extensions/utils/format.ts +11 -0
  22. package/node_modules/@herbertgao/pi-cc-extensions/extensions/utils/patch-keys.ts +4 -0
  23. package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
  24. package/node_modules/@juicesharp/rpiv-ask-user-question/README.md +1 -0
  25. package/node_modules/@juicesharp/rpiv-ask-user-question/ask-user-question.ts +27 -3
  26. package/node_modules/@juicesharp/rpiv-ask-user-question/config.ts +23 -0
  27. package/node_modules/@juicesharp/rpiv-ask-user-question/docs/configuration.md +15 -0
  28. package/node_modules/@juicesharp/rpiv-ask-user-question/docs/keyboard.md +9 -2
  29. package/node_modules/@juicesharp/rpiv-ask-user-question/locales/de.json +7 -4
  30. package/node_modules/@juicesharp/rpiv-ask-user-question/locales/en.json +8 -5
  31. package/node_modules/@juicesharp/rpiv-ask-user-question/locales/es.json +7 -4
  32. package/node_modules/@juicesharp/rpiv-ask-user-question/locales/fr.json +7 -4
  33. package/node_modules/@juicesharp/rpiv-ask-user-question/locales/pt-BR.json +7 -4
  34. package/node_modules/@juicesharp/rpiv-ask-user-question/locales/pt.json +7 -4
  35. package/node_modules/@juicesharp/rpiv-ask-user-question/locales/ru.json +7 -4
  36. package/node_modules/@juicesharp/rpiv-ask-user-question/locales/uk.json +7 -4
  37. package/node_modules/@juicesharp/rpiv-ask-user-question/locales/zh.json +7 -4
  38. package/node_modules/@juicesharp/rpiv-ask-user-question/package.json +4 -3
  39. package/node_modules/@juicesharp/rpiv-ask-user-question/presentation.ts +11 -1
  40. package/node_modules/@juicesharp/rpiv-ask-user-question/state/build-questionnaire.ts +6 -0
  41. package/node_modules/@juicesharp/rpiv-ask-user-question/state/key-router.ts +49 -8
  42. package/node_modules/@juicesharp/rpiv-ask-user-question/state/questionnaire-session.ts +6 -0
  43. package/node_modules/@juicesharp/rpiv-ask-user-question/state/state-reducer.ts +13 -1
  44. package/node_modules/@juicesharp/rpiv-ask-user-question/state/state.ts +2 -0
  45. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/preview/preview-block-renderer.ts +19 -7
  46. package/node_modules/@juicesharp/rpiv-ask-user-question/view/dialog-builder.ts +36 -7
  47. package/node_modules/@juicesharp/rpiv-ask-user-question/view/dialog-copy.ts +13 -2
  48. package/node_modules/@juicesharp/rpiv-ask-user-question/view/tab-content-strategy.ts +24 -8
  49. package/node_modules/@juicesharp/rpiv-ask-user-question/view/transcript.ts +144 -0
  50. package/node_modules/@narumitw/pi-btw/README.md +7 -2
  51. package/node_modules/@narumitw/pi-btw/dist/index.ts +371 -118
  52. package/node_modules/@narumitw/pi-btw/dist/index.ts.map +4 -4
  53. package/node_modules/@narumitw/pi-btw/docs/main-context-runtime.md +45 -0
  54. package/node_modules/@narumitw/pi-btw/docs/workflows.md +48 -5
  55. package/node_modules/@narumitw/pi-btw/package.json +1 -1
  56. package/node_modules/@narumitw/pi-btw/src/btw.ts +39 -14
  57. package/node_modules/@narumitw/pi-btw/src/import-main-updates.ts +84 -0
  58. package/node_modules/@narumitw/pi-btw/src/keybindings.ts +29 -4
  59. package/node_modules/@narumitw/pi-btw/src/main-context-snapshot.ts +125 -0
  60. package/node_modules/@narumitw/pi-btw/src/menu.ts +1 -0
  61. package/node_modules/@narumitw/pi-btw/src/side-thread.ts +66 -17
  62. package/node_modules/@narumitw/pi-btw/src/transcript-markdown.ts +5 -5
  63. package/node_modules/@narumitw/pi-btw/src/transcript-pager.ts +47 -6
  64. package/node_modules/pi-lens/CHANGELOG.md +440 -0
  65. package/node_modules/pi-lens/README.md +13 -3
  66. package/node_modules/pi-lens/config/dependency-cruiser-eager-allowlist.json +1 -0
  67. package/node_modules/pi-lens/dist/chunk-22Y2BM7H.js +23 -0
  68. package/node_modules/pi-lens/dist/{chunk-ATKJFDQN.js → chunk-27VWVB23.js} +12 -14
  69. package/node_modules/pi-lens/dist/{chunk-S2HEXIWI.js → chunk-2FYKETQJ.js} +10 -6
  70. package/node_modules/pi-lens/dist/{chunk-SRYEJNES.js → chunk-2LDMXL2M.js} +2 -2
  71. package/node_modules/pi-lens/dist/{chunk-ZHH37KZL.js → chunk-2SDHYHHO.js} +17 -17
  72. package/node_modules/pi-lens/dist/chunk-2Y6OJRSI.js +38 -0
  73. package/node_modules/pi-lens/dist/chunk-3SNDVPOR.js +507 -0
  74. package/node_modules/pi-lens/dist/{chunk-5OFV52AM.js → chunk-3WCEHYOI.js} +1 -1
  75. package/node_modules/pi-lens/dist/chunk-44X7VIKR.js +73 -0
  76. package/node_modules/pi-lens/dist/{chunk-DEL2U6CM.js → chunk-4FHUGDKU.js} +16 -14
  77. package/node_modules/pi-lens/dist/{chunk-CT4MN5IU.js → chunk-4ODSZ35Z.js} +353 -359
  78. package/node_modules/pi-lens/dist/{chunk-ZIVJBOO3.js → chunk-4U7GDSZQ.js} +2 -2
  79. package/node_modules/pi-lens/dist/chunk-54NIOJJZ.js +25 -0
  80. package/node_modules/pi-lens/dist/{chunk-N5FLEO7W.js → chunk-5DKE4HGX.js} +37 -37
  81. package/node_modules/pi-lens/dist/{chunk-P63GXC37.js → chunk-5LRUKYFA.js} +31 -4
  82. package/node_modules/pi-lens/dist/{chunk-HRNHZA3N.js → chunk-63NMUNYP.js} +12 -16
  83. package/node_modules/pi-lens/dist/{chunk-HWCCCQNX.js → chunk-6XSESGWD.js} +13 -6
  84. package/node_modules/pi-lens/dist/{chunk-UMS2MFPZ.js → chunk-72J27ICO.js} +2 -3
  85. package/node_modules/pi-lens/dist/{chunk-ED36RF6Y.js → chunk-7FLRUH6B.js} +1 -1
  86. package/node_modules/pi-lens/dist/chunk-7IYC4ENJ.js +297 -0
  87. package/node_modules/pi-lens/dist/chunk-7WWQAW5P.js +30 -0
  88. package/node_modules/pi-lens/dist/{chunk-3DA2JDOL.js → chunk-7ZS7MC24.js} +551 -203
  89. package/node_modules/pi-lens/dist/{chunk-WMYE35PX.js → chunk-AHWA4AKM.js} +7 -5
  90. package/node_modules/pi-lens/dist/{chunk-JW3YWBVB.js → chunk-AI3GP74G.js} +17 -19
  91. package/node_modules/pi-lens/dist/{chunk-AGSS7277.js → chunk-APFJKOP6.js} +6 -23
  92. package/node_modules/pi-lens/dist/{chunk-ZVUL7QYY.js → chunk-ASRAO7KG.js} +29 -32
  93. package/node_modules/pi-lens/dist/{chunk-BW5KFIQC.js → chunk-AWQWXSW4.js} +1 -0
  94. package/node_modules/pi-lens/dist/{chunk-TLX72JTG.js → chunk-CG5V25HX.js} +1 -1
  95. package/node_modules/pi-lens/dist/chunk-CKEQFGLT.js +32 -0
  96. package/node_modules/pi-lens/dist/{chunk-Y6GZHWSJ.js → chunk-COOUUC5W.js} +6 -6
  97. package/node_modules/pi-lens/dist/{chunk-XTBDCR27.js → chunk-CPZ5JJW6.js} +4 -4
  98. package/node_modules/pi-lens/dist/{chunk-RKKOYPRA.js → chunk-DS2USX5G.js} +13 -15
  99. package/node_modules/pi-lens/dist/chunk-EA2ZRG44.js +27 -0
  100. package/node_modules/pi-lens/dist/{chunk-GSLNCYGG.js → chunk-EDMLIW6W.js} +13 -14
  101. package/node_modules/pi-lens/dist/{chunk-2EECBNC5.js → chunk-EIKRZ32J.js} +75 -0
  102. package/node_modules/pi-lens/dist/chunk-EKNWOL2I.js +27 -0
  103. package/node_modules/pi-lens/dist/{chunk-R3T7CLQ2.js → chunk-ELZRSR5N.js} +41 -41
  104. package/node_modules/pi-lens/dist/{chunk-GMX5OS7B.js → chunk-EN5AM7PX.js} +11 -12
  105. package/node_modules/pi-lens/dist/{chunk-3RKP3FMS.js → chunk-EWXXLS26.js} +226 -24
  106. package/node_modules/pi-lens/dist/chunk-EX4EXBW7.js +37 -0
  107. package/node_modules/pi-lens/dist/{chunk-XHJBS436.js → chunk-EXVXBSGN.js} +25 -25
  108. package/node_modules/pi-lens/dist/{chunk-MZGQNL3Y.js → chunk-F7BO6FWH.js} +12 -13
  109. package/node_modules/pi-lens/dist/{chunk-V35JG4JB.js → chunk-FEDWAYDS.js} +152 -334
  110. package/node_modules/pi-lens/dist/{chunk-J64T55EI.js → chunk-FWZRGGGY.js} +73 -9
  111. package/node_modules/pi-lens/dist/{chunk-T57LYLZT.js → chunk-G224FADB.js} +1 -1
  112. package/node_modules/pi-lens/dist/chunk-G5UCJFT7.js +26 -0
  113. package/node_modules/pi-lens/dist/{chunk-LLJNQKQW.js → chunk-GLW3YDZZ.js} +20 -13
  114. package/node_modules/pi-lens/dist/{chunk-GXFV6MYU.js → chunk-GTDSYEA2.js} +72 -39
  115. package/node_modules/pi-lens/dist/{chunk-DUO2TU77.js → chunk-GYRZ72R4.js} +10 -4
  116. package/node_modules/pi-lens/dist/chunk-HYVXA3BB.js +49 -0
  117. package/node_modules/pi-lens/dist/{chunk-W66O5E25.js → chunk-IEBJF3PN.js} +13 -15
  118. package/node_modules/pi-lens/dist/{chunk-GAQ7OQG6.js → chunk-IL7K66ZQ.js} +83 -94
  119. package/node_modules/pi-lens/dist/{chunk-T7FEBKXN.js → chunk-JWOVP5BL.js} +7 -9
  120. package/node_modules/pi-lens/dist/{chunk-UBOQLVT2.js → chunk-K2GUZ4DN.js} +4 -4
  121. package/node_modules/pi-lens/dist/{chunk-5VSF4UUQ.js → chunk-K4SZB56V.js} +34 -39
  122. package/node_modules/pi-lens/dist/{chunk-7D6L4MTX.js → chunk-KCBRHV5E.js} +3 -3
  123. package/node_modules/pi-lens/dist/{chunk-GSM5UU7A.js → chunk-KFXCL4OV.js} +38 -28
  124. package/node_modules/pi-lens/dist/{chunk-J6MPGQTS.js → chunk-KJJAVH3X.js} +81 -15
  125. package/node_modules/pi-lens/dist/{chunk-BWD5EPKO.js → chunk-KPVLQHCZ.js} +4 -6
  126. package/node_modules/pi-lens/dist/{chunk-MPNJLASA.js → chunk-KX56K73G.js} +10 -13
  127. package/node_modules/pi-lens/dist/{chunk-AWSCPCN2.js → chunk-LMCTHJ2H.js} +19 -19
  128. package/node_modules/pi-lens/dist/{chunk-IWDLU6K3.js → chunk-MEFLGBCS.js} +4 -6
  129. package/node_modules/pi-lens/dist/{chunk-TOY6QKOH.js → chunk-MKPCELNI.js} +17 -17
  130. package/node_modules/pi-lens/dist/{chunk-POMLXPMY.js → chunk-N3PLNNCW.js} +1 -1
  131. package/node_modules/pi-lens/dist/chunk-N5FBM25N.js +22 -0
  132. package/node_modules/pi-lens/dist/{chunk-CYRKQRPM.js → chunk-NFNVDDGB.js} +2 -4
  133. package/node_modules/pi-lens/dist/{chunk-RMLC67LF.js → chunk-NLIVE7L6.js} +2 -30
  134. package/node_modules/pi-lens/dist/{chunk-24AKHFGP.js → chunk-OMJ3OFBJ.js} +6 -6
  135. package/node_modules/pi-lens/dist/{chunk-IQWN5JCP.js → chunk-OZNCKLOX.js} +13 -14
  136. package/node_modules/pi-lens/dist/chunk-P5XUGPIX.js +31 -0
  137. package/node_modules/pi-lens/dist/{chunk-2KXTHF3M.js → chunk-PJXNTPB2.js} +253 -33
  138. package/node_modules/pi-lens/dist/chunk-PKOXJIVT.js +88 -0
  139. package/node_modules/pi-lens/dist/{chunk-DGUKIYSI.js → chunk-PP2A5V2T.js} +8 -10
  140. package/node_modules/pi-lens/dist/{chunk-KAPJINKN.js → chunk-Q42LJANT.js} +2 -2
  141. package/node_modules/pi-lens/dist/{chunk-UZ2XCLYS.js → chunk-Q4BKKOVC.js} +8 -8
  142. package/node_modules/pi-lens/dist/{chunk-TIQ2PKDW.js → chunk-QT66NEYN.js} +4 -4
  143. package/node_modules/pi-lens/dist/{chunk-U44DJXQP.js → chunk-RCHO5W7M.js} +15 -18
  144. package/node_modules/pi-lens/dist/{chunk-YH5MVY2U.js → chunk-RG3MXTRI.js} +7 -7
  145. package/node_modules/pi-lens/dist/chunk-RG7OODGM.js +57 -0
  146. package/node_modules/pi-lens/dist/{chunk-OHKJ7PQF.js → chunk-RU34BA4D.js} +43 -39
  147. package/node_modules/pi-lens/dist/{chunk-JMYYOTQG.js → chunk-S26LC76R.js} +13 -1
  148. package/node_modules/pi-lens/dist/{chunk-XBJVAEEO.js → chunk-S55TEC7I.js} +3 -2
  149. package/node_modules/pi-lens/dist/{chunk-RVK72CZX.js → chunk-SJHC3BCZ.js} +1397 -481
  150. package/node_modules/pi-lens/dist/{chunk-IYNJ6YPZ.js → chunk-SNEUMLM7.js} +4 -4
  151. package/node_modules/pi-lens/dist/{chunk-S67KYG37.js → chunk-T4NGVFYI.js} +2 -2
  152. package/node_modules/pi-lens/dist/{chunk-YCWYO6TQ.js → chunk-THEXI2QO.js} +48 -45
  153. package/node_modules/pi-lens/dist/{chunk-AMERCH6V.js → chunk-TL2TCJYL.js} +15 -16
  154. package/node_modules/pi-lens/dist/{chunk-KUA4OJ5Y.js → chunk-TPYYEDP5.js} +823 -350
  155. package/node_modules/pi-lens/dist/{chunk-YNE3RP52.js → chunk-TVZRLTG6.js} +8 -1
  156. package/node_modules/pi-lens/dist/{chunk-ROYSX2S5.js → chunk-UCVMSOXF.js} +2 -2
  157. package/node_modules/pi-lens/dist/chunk-UL5SXQVX.js +32 -0
  158. package/node_modules/pi-lens/dist/{chunk-7HXE67BN.js → chunk-UO66IMVP.js} +2 -2
  159. package/node_modules/pi-lens/dist/{chunk-VOOAPROD.js → chunk-UVY4TOJH.js} +3 -3
  160. package/node_modules/pi-lens/dist/{chunk-RKBXZN3A.js → chunk-VIDEKABZ.js} +2 -2
  161. package/node_modules/pi-lens/dist/{chunk-2FN63LPV.js → chunk-VITFDI3O.js} +13 -14
  162. package/node_modules/pi-lens/dist/{chunk-6DLWKFEX.js → chunk-VUAVE3QC.js} +41 -42
  163. package/node_modules/pi-lens/dist/{chunk-FM4RDMKT.js → chunk-WUY4BZEP.js} +10 -12
  164. package/node_modules/pi-lens/dist/{chunk-SD4I7ZO4.js → chunk-X3UTCXAA.js} +43 -53
  165. package/node_modules/pi-lens/dist/chunk-XHDBJODR.js +45 -0
  166. package/node_modules/pi-lens/dist/{chunk-5IUSNGOC.js → chunk-XHLK33VM.js} +28 -21
  167. package/node_modules/pi-lens/dist/{chunk-3KAZU3VR.js → chunk-XI34NWDI.js} +2 -2
  168. package/node_modules/pi-lens/dist/{chunk-QBFBRV2B.js → chunk-XWFIHYCH.js} +4 -2
  169. package/node_modules/pi-lens/dist/{chunk-JUKMK5Y4.js → chunk-Y2TPADJR.js} +10 -11
  170. package/node_modules/pi-lens/dist/{chunk-EBC36LNN.js → chunk-Y5KTA2OB.js} +17 -17
  171. package/node_modules/pi-lens/dist/{chunk-HYGZEMX6.js → chunk-YKVDBNPO.js} +11 -5
  172. package/node_modules/pi-lens/dist/{chunk-KN35K52N.js → chunk-YSDPVDFC.js} +3 -3
  173. package/node_modules/pi-lens/dist/chunk-YWNO5Q4R.js +44 -0
  174. package/node_modules/pi-lens/dist/{chunk-US7ECLD7.js → chunk-YWWG4AQA.js} +119 -28
  175. package/node_modules/pi-lens/dist/{chunk-O4NWQT6I.js → chunk-YXDCRUKQ.js} +4 -4
  176. package/node_modules/pi-lens/dist/{chunk-XYURS6EN.js → chunk-YXGRRORB.js} +15 -17
  177. package/node_modules/pi-lens/dist/{chunk-IUE7SSKV.js → chunk-ZAPSUBLU.js} +13 -7
  178. package/node_modules/pi-lens/dist/{chunk-EUXZEFTV.js → chunk-ZPJM7DID.js} +3 -3
  179. package/node_modules/pi-lens/dist/{chunk-5HSRT26B.js → chunk-ZSUX7KEM.js} +16 -15
  180. package/node_modules/pi-lens/dist/index.js +37155 -32210
  181. package/node_modules/pi-lens/dist/mcp/analyze-cli.js +11 -12
  182. package/node_modules/pi-lens/dist/mcp/cli.js +46 -45
  183. package/node_modules/pi-lens/dist/mcp/server.js +1210 -574
  184. package/node_modules/pi-lens/dist/mcp/worker.js +65 -65
  185. package/node_modules/pi-lens/dist/probes/installer.js +21 -23
  186. package/node_modules/pi-lens/docs/adr/0010-trace-validation-session-lifecycle.md +390 -0
  187. package/node_modules/pi-lens/docs/adr/README.md +1 -0
  188. package/node_modules/pi-lens/docs/ast-grep_rules_catalog.md +5 -3
  189. package/node_modules/pi-lens/docs/configuration.md +9 -0
  190. package/node_modules/pi-lens/docs/engineering-principles.md +12 -0
  191. package/node_modules/pi-lens/docs/environment-variables.md +20 -0
  192. package/node_modules/pi-lens/docs/features.md +16 -1
  193. package/node_modules/pi-lens/docs/globalconfig.md +37 -8
  194. package/node_modules/pi-lens/docs/lsp-capability-matrix.md +105 -12
  195. package/node_modules/pi-lens/docs/lsp-idle-eviction.md +37 -18
  196. package/node_modules/pi-lens/docs/pi-lens-fixer.md +22 -1
  197. package/node_modules/pi-lens/docs/pi-lens-investigator.md +14 -0
  198. package/node_modules/pi-lens/docs/pi-lens-merge-policy.md +23 -10
  199. package/node_modules/pi-lens/docs/pi-lens-monitor.md +64 -8
  200. package/node_modules/pi-lens/docs/pi-lens-retro.md +2 -2
  201. package/node_modules/pi-lens/docs/pi-lens-reviewer.md +48 -1
  202. package/node_modules/pi-lens/docs/pi-lens-subagent.md +8 -1
  203. package/node_modules/pi-lens/docs/release-qa-baseline.md +19 -7
  204. package/node_modules/pi-lens/docs/servercapabilities.md +47 -47
  205. package/node_modules/pi-lens/docs/settings.md +9 -5
  206. package/node_modules/pi-lens/docs/subagent-compat.md +1 -1
  207. package/node_modules/pi-lens/docs/usage.md +1 -0
  208. package/node_modules/pi-lens/package.json +6 -4
  209. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-return-value-in-generator-test.yml +17 -0
  210. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-sql-in-code-execute-js-test.yml +86 -0
  211. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-sql-in-code-execute-test.yml +86 -0
  212. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/unchecked-numeric-parse-python-test.yml +15 -0
  213. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-return-value-in-generator.yml +9 -4
  214. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-sql-in-code-execute-js.yml +119 -0
  215. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-sql-in-code-execute.yml +119 -0
  216. package/node_modules/pi-lens/rules/ast-grep-rules/rules/unchecked-numeric-parse-python.yml +13 -2
  217. package/node_modules/pi-lens/rules/rule-catalog.json +25 -1
  218. package/node_modules/pi-lens/scripts/analyze-pi-lens-logs.mjs +15 -5
  219. package/node_modules/pi-lens/scripts/lib/is-main-module.mjs +27 -0
  220. package/node_modules/pi-lens/scripts/lib/scratch-home-env.mjs +21 -0
  221. package/node_modules/pi-lens/scripts/rpc-load-check.mjs +4 -6
  222. package/node_modules/pi-lens/scripts/warm-loader-cache.mjs +2 -5
  223. package/node_modules/pi-next-cue/package.json +4 -1
  224. package/node_modules/pi-provider-qoder/dist/index.js +438 -283
  225. package/node_modules/pi-provider-qoder/package.json +1 -1
  226. package/node_modules/pi-typesafe/README.md +6 -6
  227. package/node_modules/pi-typesafe/dist/ask.js +9 -2
  228. package/node_modules/pi-typesafe/dist/auth.d.ts +3 -2
  229. package/node_modules/pi-typesafe/dist/auth.js +2 -2
  230. package/node_modules/pi-typesafe/dist/backends.d.ts +20 -5
  231. package/node_modules/pi-typesafe/dist/backends.js +32 -8
  232. package/node_modules/pi-typesafe/dist/batch.d.ts +1 -1
  233. package/node_modules/pi-typesafe/dist/batch.js +2 -2
  234. package/node_modules/pi-typesafe/dist/client.d.ts +1 -1
  235. package/node_modules/pi-typesafe/dist/client.js +24 -12
  236. package/node_modules/pi-typesafe/dist/credentials.d.ts +8 -6
  237. package/node_modules/pi-typesafe/dist/credentials.js +70 -16
  238. package/node_modules/pi-typesafe/dist/extension.js +118 -26
  239. package/node_modules/pi-typesafe/dist/index.d.ts +1 -1
  240. package/node_modules/pi-typesafe/dist/index.js +1 -1
  241. package/node_modules/pi-typesafe/dist/key-prompt.d.ts +1 -1
  242. package/node_modules/pi-typesafe/dist/key-prompt.js +6 -6
  243. package/node_modules/pi-typesafe/dist/login.d.ts +11 -10
  244. package/node_modules/pi-typesafe/dist/login.js +24 -21
  245. package/node_modules/pi-typesafe/dist/schema.d.ts +8 -8
  246. package/node_modules/pi-typesafe/dist/schema.js +29 -7
  247. package/node_modules/pi-typesafe/package.json +2 -2
  248. package/package.json +12 -12
  249. package/node_modules/pi-lens/dist/chunk-3PTHXJXR.js +0 -28
  250. package/node_modules/pi-lens/dist/chunk-3QED2P4V.js +0 -31
  251. package/node_modules/pi-lens/dist/chunk-5WRPDP2A.js +0 -47
  252. package/node_modules/pi-lens/dist/chunk-ABBOA7UD.js +0 -157
  253. package/node_modules/pi-lens/dist/chunk-CUHSHSB6.js +0 -273
  254. package/node_modules/pi-lens/dist/chunk-GL5LUMZE.js +0 -51
  255. package/node_modules/pi-lens/dist/chunk-HAD7QRQI.js +0 -30
  256. package/node_modules/pi-lens/dist/chunk-JORED7EX.js +0 -44
  257. package/node_modules/pi-lens/dist/chunk-KYUB6QDC.js +0 -72
  258. package/node_modules/pi-lens/dist/chunk-LZSEQW6A.js +0 -57
  259. package/node_modules/pi-lens/dist/chunk-M2IFVFWU.js +0 -79
  260. package/node_modules/pi-lens/dist/chunk-M2UD3LPU.js +0 -88
  261. package/node_modules/pi-lens/dist/chunk-MBKQHGA7.js +0 -39
  262. package/node_modules/pi-lens/dist/chunk-R7YOCSNV.js +0 -23
  263. package/node_modules/pi-lens/dist/chunk-SKAMFC7A.js +0 -28
  264. package/node_modules/pi-lens/dist/chunk-SYE6T2EB.js +0 -28
  265. package/node_modules/pi-lens/dist/chunk-TRETHTQO.js +0 -26
  266. package/node_modules/pi-lens/dist/chunk-UA7ZXYDR.js +0 -184
  267. package/node_modules/pi-lens/dist/chunk-XTFDJI3T.js +0 -24
  268. package/node_modules/pi-lens/dist/chunk-Z3CCVDUB.js +0 -76
  269. package/node_modules/pi-next-cue/.github/workflows/publish.yml +0 -20
@@ -7,13 +7,15 @@ import {
7
7
  normalizeMessage,
8
8
  sanitizeCorrelationId,
9
9
  stableFindingId
10
- } from "./chunk-IWDLU6K3.js";
10
+ } from "./chunk-MEFLGBCS.js";
11
11
  import {
12
12
  mapWithConcurrency
13
13
  } from "./chunk-XIMYZ3JA.js";
14
14
  import {
15
15
  classifyCascadeWaitTier,
16
16
  classifyServerWaitTier,
17
+ declinesLooseFileRoot,
18
+ declinesProjectlessRoot,
17
19
  disabledPrimaries,
18
20
  enforceLspRootCeiling,
19
21
  findLocalTyposConfig,
@@ -36,24 +38,24 @@ import {
36
38
  resolveLspServerCwd,
37
39
  serverTraits,
38
40
  withLspProjectCodePermission
39
- } from "./chunk-3DA2JDOL.js";
41
+ } from "./chunk-7ZS7MC24.js";
40
42
  import {
41
43
  findLocalOpengrepConfig
42
- } from "./chunk-HWCCCQNX.js";
44
+ } from "./chunk-6XSESGWD.js";
43
45
  import {
44
46
  emitBounded
45
- } from "./chunk-CUHSHSB6.js";
47
+ } from "./chunk-3SNDVPOR.js";
46
48
  import {
47
49
  loadProjectSnapshot,
48
50
  readJsonCache
49
- } from "./chunk-T7FEBKXN.js";
51
+ } from "./chunk-JWOVP5BL.js";
50
52
  import {
51
53
  acquireWorkspaceSweepHold,
52
54
  configureLspServiceLifecycle,
53
55
  getOwnedLspService,
54
56
  peekOwnedLspService,
55
57
  resetOwnedLspService
56
- } from "./chunk-SRYEJNES.js";
58
+ } from "./chunk-2LDMXL2M.js";
57
59
  import {
58
60
  collectForwardImportMtimes,
59
61
  exceedsLspSyncLimits,
@@ -64,45 +66,47 @@ import {
64
66
  implicitScopeOf,
65
67
  importSourceNameParts,
66
68
  isGoSourceFile,
67
- pathBirthtimeMs
68
- } from "./chunk-V35JG4JB.js";
69
- import {
70
- EXTENSION_TO_LSP_ID
71
- } from "./chunk-GXFV6MYU.js";
69
+ lineTextAt,
70
+ pathBirthtimeMs,
71
+ scanDocumentContent
72
+ } from "./chunk-FEDWAYDS.js";
72
73
  import {
73
74
  js_yaml_default
74
- } from "./chunk-FM4RDMKT.js";
75
+ } from "./chunk-WUY4BZEP.js";
76
+ import {
77
+ EXTENSION_TO_LSP_ID,
78
+ lspLanguageId,
79
+ resolveFilenameLanguage
80
+ } from "./chunk-GTDSYEA2.js";
81
+ import {
82
+ HOOK_WALL_BUDGET_MS
83
+ } from "./chunk-CKEQFGLT.js";
75
84
  import {
76
- HOOK_WALL_BUDGET_MS,
77
85
  bounded,
78
86
  withDeadline,
79
87
  withTimeout
80
- } from "./chunk-RMLC67LF.js";
81
- import {
82
- PathKeyedMap
83
- } from "./chunk-Z3CCVDUB.js";
88
+ } from "./chunk-NLIVE7L6.js";
84
89
  import {
85
90
  diagnosticsIpcPathForCwd,
86
91
  requestWarmCodeActions,
87
92
  requestWarmDiagnostics
88
- } from "./chunk-KAPJINKN.js";
93
+ } from "./chunk-Q42LJANT.js";
89
94
  import {
90
95
  CONTENT_HASH_MAX_BYTES,
91
- freshnessFromMtime,
92
96
  hashContentBytes,
93
97
  hashFileBytes
94
- } from "./chunk-AGSS7277.js";
98
+ } from "./chunk-APFJKOP6.js";
95
99
  import {
96
100
  findLocalZizmorConfig,
97
101
  logSessionStart
98
- } from "./chunk-GAQ7OQG6.js";
102
+ } from "./chunk-IL7K66ZQ.js";
99
103
  import {
100
104
  findLocalBinUpwards,
101
105
  isProjectLocalBinPath
102
- } from "./chunk-5VSF4UUQ.js";
106
+ } from "./chunk-K4SZB56V.js";
103
107
  import {
104
108
  getLspCapableKinds
105
- } from "./chunk-HRNHZA3N.js";
109
+ } from "./chunk-63NMUNYP.js";
106
110
  import {
107
111
  createGenerationMap,
108
112
  createGenerationSource,
@@ -120,39 +124,42 @@ import {
120
124
  removeLspChild,
121
125
  sampleProcessTreeCpuPercent,
122
126
  selectLivePeerInstances
123
- } from "./chunk-KUA4OJ5Y.js";
127
+ } from "./chunk-TPYYEDP5.js";
124
128
  import {
125
129
  createSingleFlight
126
- } from "./chunk-BW5KFIQC.js";
130
+ } from "./chunk-AWQWXSW4.js";
127
131
  import {
128
132
  SPECIAL_FILENAMES,
129
133
  getLanguageId
130
- } from "./chunk-DUO2TU77.js";
134
+ } from "./chunk-GYRZ72R4.js";
131
135
  import {
136
+ PathKeyedMap,
132
137
  detectFileRole
133
- } from "./chunk-J6MPGQTS.js";
138
+ } from "./chunk-KJJAVH3X.js";
134
139
  import {
135
140
  assertInstallAllowed,
136
141
  isLspSpawnAllowedByTrust,
137
- projectTrustDenialReason
138
- } from "./chunk-M2IFVFWU.js";
139
- import {
142
+ projectTrustDenialReason,
140
143
  writeFileAtomic
141
- } from "./chunk-2EECBNC5.js";
144
+ } from "./chunk-EIKRZ32J.js";
142
145
  import {
143
146
  compareOrdinal,
144
147
  incrementDegradationCount,
145
148
  recordDegradation,
146
- recordDegradationOnce
147
- } from "./chunk-J64T55EI.js";
149
+ recordDegradationOnce,
150
+ truncateForLedger
151
+ } from "./chunk-FWZRGGGY.js";
148
152
  import {
149
153
  logExtension
150
- } from "./chunk-POMLXPMY.js";
154
+ } from "./chunk-N3PLNNCW.js";
155
+ import {
156
+ freshnessFromMtime
157
+ } from "./chunk-S26LC76R.js";
151
158
  import {
152
159
  logLatency,
153
160
  phaseFinished,
154
161
  phaseStarted
155
- } from "./chunk-QBFBRV2B.js";
162
+ } from "./chunk-XWFIHYCH.js";
156
163
  import {
157
164
  createNdjsonLogger,
158
165
  getGlobalPiLensLogDir,
@@ -160,13 +167,11 @@ import {
160
167
  getProcessSingleton,
161
168
  isTestMode,
162
169
  nextModuleEvaluationOrdinal
163
- } from "./chunk-YNE3RP52.js";
170
+ } from "./chunk-TVZRLTG6.js";
164
171
  import {
165
172
  BoundedFifoMap,
166
173
  BoundedLruCache,
167
- BoundedSet
168
- } from "./chunk-ABBOA7UD.js";
169
- import {
174
+ BoundedSet,
170
175
  isAtOrAboveHomeDir,
171
176
  isUnderDir,
172
177
  isWindowsPath,
@@ -175,12 +180,11 @@ import {
175
180
  normalizeFilePath,
176
181
  normalizeMapKey,
177
182
  pathsEqual,
178
- realpathOrResolve,
179
183
  toPosix,
180
184
  toProjectRelativePath,
181
185
  uriToDiskPath,
182
186
  uriToPath
183
- } from "./chunk-3RKP3FMS.js";
187
+ } from "./chunk-EWXXLS26.js";
184
188
  import {
185
189
  __commonJS,
186
190
  __require,
@@ -1403,8 +1407,8 @@ var require_semaphore = __commonJS({
1403
1407
  this._waiting = [];
1404
1408
  }
1405
1409
  lock(thunk) {
1406
- return new Promise((resolve8, reject) => {
1407
- this._waiting.push({ thunk, resolve: resolve8, reject });
1410
+ return new Promise((resolve9, reject) => {
1411
+ this._waiting.push({ thunk, resolve: resolve9, reject });
1408
1412
  this.runNext();
1409
1413
  });
1410
1414
  }
@@ -3030,9 +3034,9 @@ ${JSON.stringify(message, null, 4)}`);
3030
3034
  if (typeof cancellationStrategy.sender.enableCancellation === "function") {
3031
3035
  cancellationStrategy.sender.enableCancellation(requestMessage);
3032
3036
  }
3033
- return new Promise(async (resolve8, reject) => {
3037
+ return new Promise(async (resolve9, reject) => {
3034
3038
  const resolveWithCleanup = (r) => {
3035
- resolve8(r);
3039
+ resolve9(r);
3036
3040
  cancellationStrategy.sender.cleanup(id);
3037
3041
  disposable?.dispose();
3038
3042
  };
@@ -3461,10 +3465,10 @@ var require_ril = __commonJS({
3461
3465
  return api_1.Disposable.create(() => this.stream.off("end", listener));
3462
3466
  }
3463
3467
  write(data, encoding) {
3464
- return new Promise((resolve8, reject) => {
3468
+ return new Promise((resolve9, reject) => {
3465
3469
  const callback = (error) => {
3466
3470
  if (error === void 0 || error === null) {
3467
- resolve8();
3471
+ resolve9();
3468
3472
  } else {
3469
3473
  reject(error);
3470
3474
  }
@@ -3600,9 +3604,9 @@ var require_main = __commonJS({
3600
3604
  exports.createMessageConnection = createMessageConnection2;
3601
3605
  var ril_1 = __importDefault(require_ril());
3602
3606
  ril_1.default.install();
3603
- var path16 = __importStar(__require("path"));
3607
+ var path18 = __importStar(__require("path"));
3604
3608
  var os2 = __importStar(__require("os"));
3605
- var fs12 = __importStar(__require("fs"));
3609
+ var fs14 = __importStar(__require("fs"));
3606
3610
  var crypto_1 = __require("crypto");
3607
3611
  var net_1 = __require("net");
3608
3612
  var api_1 = require_api();
@@ -3743,7 +3747,7 @@ var require_main = __commonJS({
3743
3747
  }
3744
3748
  let randomLength = 32;
3745
3749
  const fixedLength = "/lsp-.sock".length;
3746
- const tmpDir = fs12.realpathSync(XDG_RUNTIME_DIR ?? os2.tmpdir());
3750
+ const tmpDir = fs14.realpathSync(XDG_RUNTIME_DIR ?? os2.tmpdir());
3747
3751
  const limit = safeIpcPathLengths.get(process.platform);
3748
3752
  if (limit !== void 0) {
3749
3753
  randomLength = Math.min(limit - tmpDir.length - fixedLength, randomLength);
@@ -3752,14 +3756,14 @@ var require_main = __commonJS({
3752
3756
  throw new Error(`Unable to generate a random pipe name with ${randomLength} characters.`);
3753
3757
  }
3754
3758
  const randomSuffix = (0, crypto_1.randomBytes)(Math.floor(randomLength / 2)).toString("hex");
3755
- return path16.join(tmpDir, `lsp-${randomSuffix}.sock`);
3759
+ return path18.join(tmpDir, `lsp-${randomSuffix}.sock`);
3756
3760
  }
3757
3761
  function createClientPipeTransport(pipeName, encoding = "utf-8") {
3758
3762
  let connectResolve;
3759
- const connected = new Promise((resolve8, _reject) => {
3760
- connectResolve = resolve8;
3763
+ const connected = new Promise((resolve9, _reject) => {
3764
+ connectResolve = resolve9;
3761
3765
  });
3762
- return new Promise((resolve8, reject) => {
3766
+ return new Promise((resolve9, reject) => {
3763
3767
  const server = (0, net_1.createServer)((socket) => {
3764
3768
  server.close();
3765
3769
  connectResolve([
@@ -3770,7 +3774,7 @@ var require_main = __commonJS({
3770
3774
  server.on("error", reject);
3771
3775
  server.listen(pipeName, () => {
3772
3776
  server.removeListener("error", reject);
3773
- resolve8({
3777
+ resolve9({
3774
3778
  onConnected: () => {
3775
3779
  return connected;
3776
3780
  }
@@ -3787,10 +3791,10 @@ var require_main = __commonJS({
3787
3791
  }
3788
3792
  function createClientSocketTransport(port, encoding = "utf-8") {
3789
3793
  let connectResolve;
3790
- const connected = new Promise((resolve8, _reject) => {
3791
- connectResolve = resolve8;
3794
+ const connected = new Promise((resolve9, _reject) => {
3795
+ connectResolve = resolve9;
3792
3796
  });
3793
- return new Promise((resolve8, reject) => {
3797
+ return new Promise((resolve9, reject) => {
3794
3798
  const server = (0, net_1.createServer)((socket) => {
3795
3799
  server.close();
3796
3800
  connectResolve([
@@ -3807,7 +3811,7 @@ var require_main = __commonJS({
3807
3811
  return;
3808
3812
  }
3809
3813
  const boundPort = address.port;
3810
- resolve8({
3814
+ resolve9({
3811
3815
  port: () => boundPort,
3812
3816
  onConnected: () => {
3813
3817
  return connected;
@@ -3850,8 +3854,8 @@ var CASCADE_DIAGNOSTICS_TTL_MS = 24e4;
3850
3854
 
3851
3855
  // dist/clients/lsp/index.js
3852
3856
  import * as nodeFs2 from "node:fs";
3853
- import fs11 from "node:fs/promises";
3854
- import path15 from "node:path";
3857
+ import fs13 from "node:fs/promises";
3858
+ import path17 from "node:path";
3855
3859
  import { pathToFileURL as pathToFileURL3, URL as URL3 } from "node:url";
3856
3860
 
3857
3861
  // dist/clients/lsp/workspace-diagnostics-session.js
@@ -3948,7 +3952,7 @@ async function importTargetsToAnnounce(cwd, importers, onScope) {
3948
3952
  reason: `resolved the imports of ${CREATED_IMPORT_SCAN_MAX_FILES} of ${importers.length} files in one diagnostics call`
3949
3953
  });
3950
3954
  }
3951
- const { extractForwardImports } = await import("./chunk-JORED7EX.js");
3955
+ const { extractForwardImports } = await import("./chunk-XHDBJODR.js");
3952
3956
  const targets = /* @__PURE__ */ new Set();
3953
3957
  const reexports = /* @__PURE__ */ new Map();
3954
3958
  let resolved2 = 0;
@@ -4284,7 +4288,6 @@ function isNosemgrepSuppressed(d, content) {
4284
4288
  const startLine = d.range?.start?.line;
4285
4289
  if (startLine == null)
4286
4290
  return false;
4287
- const lines = content.split("\n");
4288
4291
  const ruleId = String(d.code ?? "");
4289
4292
  const checkLine = (text, standaloneOnly) => {
4290
4293
  if (!text)
@@ -4296,14 +4299,14 @@ function isNosemgrepSuppressed(d, content) {
4296
4299
  return true;
4297
4300
  return m[1].split(",").map((s) => s.trim()).filter(Boolean).includes(ruleId);
4298
4301
  };
4299
- return checkLine(lines[startLine], false) || checkLine(lines[startLine - 1], true);
4302
+ return checkLine(lineTextAt(content, startLine), false) || checkLine(lineTextAt(content, startLine - 1), true);
4300
4303
  }
4301
4304
  var ZIZMOR_IGNORE_RE = /#\s*zizmor:\s*ignore\[([^\]]+)\]/i;
4302
4305
  function isZizmorIgnoreSuppressed(d, content) {
4303
4306
  const startLine = d.range?.start?.line;
4304
4307
  if (startLine == null)
4305
4308
  return false;
4306
- const line = content.split("\n")[startLine];
4309
+ const line = lineTextAt(content, startLine);
4307
4310
  if (!line)
4308
4311
  return false;
4309
4312
  const match = ZIZMOR_IGNORE_RE.exec(line);
@@ -5123,88 +5126,58 @@ var FIX_RUN_HASH_BYTE_BUDGET = 64 * 1024 * 1024;
5123
5126
  // dist/clients/observed-mutation.js
5124
5127
  import * as path5 from "node:path";
5125
5128
 
5126
- // dist/clients/opaque-mutation-scan.js
5127
- var OPAQUE_HASH_BUDGET_BYTES = 8 * 1024 * 1024;
5128
- var MAX_GIT_STATUS_OUTPUT_BYTES = 16 * 1024 * 1024;
5129
- var OPAQUE_BASELINE_PENDING_CAP = 64;
5130
- var OpaqueBaselineStore = class _OpaqueBaselineStore {
5131
- pending = new BoundedFifoMap(OPAQUE_BASELINE_PENDING_CAP);
5132
- static keyOf(slot, callId) {
5133
- return callId === void 0 ? slot : `${slot}#${callId}`;
5134
- }
5135
- /**
5136
- * Store `state` for a call. A baseline this displaces is lost: its
5137
- * `tool_result` will find nothing and report `partial-recognition-no-baseline`,
5138
- * withholding the blocker section of a write the agent authored. That loss is
5139
- * counted in the degradation ledger, one entry per cause with a running count,
5140
- * never one row per occurrence (#4137).
5141
- *
5142
- * First, an entry whose turn is over is retired: pi sends no `tool_result`
5143
- * for a call a `tool_call` handler blocked or Escape aborted before it ran,
5144
- * and on a non-git project the entry holds a whole-tree stat snapshot.
5145
- */
5146
- record(slot, callId, state4, turn) {
5147
- for (const [staleKey, entry] of this.pending.entriesArray())
5148
- if (entry.turn && !entry.turn.isLive(entry.turn.key)) {
5149
- this.pending.delete(staleKey);
5150
- recordBaselineLoss("unsettled");
5151
- }
5152
- const key = _OpaqueBaselineStore.keyOf(slot, callId);
5153
- const overwrote = this.pending.delete(key);
5154
- const evicted = this.pending.set(key, { state: state4, turn });
5155
- if (overwrote)
5156
- recordBaselineLoss("overwrite");
5157
- if (evicted.length > 0)
5158
- recordBaselineLoss("cap");
5159
- }
5160
- take(slot, callId) {
5161
- const key = _OpaqueBaselineStore.keyOf(slot, callId);
5162
- const entry = this.pending.get(key);
5163
- this.pending.delete(key);
5164
- return entry?.state;
5165
- }
5166
- /** Session-boundary clear - unconsumed baselines are unreachable after reset. */
5167
- takeAllForTest() {
5168
- this.pending.clear();
5169
- }
5170
- };
5171
- var BASELINE_LOSS_REASONS = {
5172
- overwrite: "a pending bash baseline was replaced before its tool_result took it; that call reports partial-recognition-no-baseline and withholds blockers (host without distinct tool-call ids, or a reused id)",
5173
- cap: `more than ${OPAQUE_BASELINE_PENDING_CAP} bash baselines awaited a tool_result; the oldest was dropped`,
5174
- unsettled: "a bash baseline outlived its turn with no tool_result (the call was blocked or aborted before it ran) and was retired; a result that still arrives reports partial-recognition-no-baseline"
5175
- };
5176
- function recordBaselineLoss(cause) {
5177
- incrementDegradationCount({
5178
- kind: "opaque-baseline-lost",
5179
- subject: cause,
5180
- reason: BASELINE_LOSS_REASONS[cause]
5181
- });
5129
+ // dist/clients/host-edit-normalize.js
5130
+ var HOST_SMART_SINGLE_QUOTES = [8216, 8217, 8218, 8219];
5131
+ var HOST_SMART_DOUBLE_QUOTES = [8220, 8221, 8222, 8223];
5132
+ var HOST_UNICODE_DASHES = [
5133
+ 8208,
5134
+ 8209,
5135
+ 8210,
5136
+ 8211,
5137
+ 8212,
5138
+ 8213,
5139
+ 8722
5140
+ ];
5141
+ var HOST_SPECIAL_SPACES = [
5142
+ 160,
5143
+ 8194,
5144
+ 8195,
5145
+ 8196,
5146
+ 8197,
5147
+ 8198,
5148
+ 8199,
5149
+ 8200,
5150
+ 8201,
5151
+ 8202,
5152
+ 8239,
5153
+ 8287,
5154
+ 12288
5155
+ ];
5156
+ var HOST_BOM_CODE_POINT = 65279;
5157
+ var charClass = (codePoints) => new RegExp(`[${String.fromCharCode(...codePoints)}]`, "g");
5158
+ var SMART_SINGLE_QUOTES_RE = charClass(HOST_SMART_SINGLE_QUOTES);
5159
+ var SMART_DOUBLE_QUOTES_RE = charClass(HOST_SMART_DOUBLE_QUOTES);
5160
+ var UNICODE_DASHES_RE = charClass(HOST_UNICODE_DASHES);
5161
+ var SPECIAL_SPACES_RE = charClass(HOST_SPECIAL_SPACES);
5162
+ var BOM = String.fromCharCode(HOST_BOM_CODE_POINT);
5163
+ function detectLineEnding(content) {
5164
+ const crlfIdx = content.indexOf("\r\n");
5165
+ const lfIdx = content.indexOf("\n");
5166
+ if (lfIdx === -1)
5167
+ return "\n";
5168
+ if (crlfIdx === -1)
5169
+ return "\n";
5170
+ return crlfIdx < lfIdx ? "\r\n" : "\n";
5182
5171
  }
5183
- var globalStoreSymbol = /* @__PURE__ */ Symbol.for("pi-lens:opaque-snapshot-store");
5184
- var globalSlot = globalThis;
5185
- function getOpaqueBaselineStore() {
5186
- const existing = globalSlot[globalStoreSymbol]?.store;
5187
- if (existing)
5188
- return existing;
5189
- const created = new OpaqueBaselineStore();
5190
- globalSlot[globalStoreSymbol] = { store: created };
5191
- return created;
5172
+ function normalizeToLF(text) {
5173
+ return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
5192
5174
  }
5193
- var gitRepoMemo = /* @__PURE__ */ new Map();
5194
- function resetOpaqueMutationState() {
5195
- getOpaqueBaselineStore().takeAllForTest();
5196
- gitRepoMemo.clear();
5197
- gitToplevelMemo.clear();
5198
- headRecords.clear();
5199
- headLooks.clear();
5175
+ function restoreLineEndings(text, ending) {
5176
+ return ending === "\r\n" ? text.replace(/\n/g, "\r\n") : text;
5200
5177
  }
5201
- var HEAD_RECORD_CAP = 64;
5202
- var headRecords = new BoundedFifoMap(HEAD_RECORD_CAP);
5203
- var headLooks = createSingleFlight({ coalesceTrailing: true });
5204
- var gitToplevelMemo = /* @__PURE__ */ new Map();
5205
5178
 
5206
- // dist/clients/read-guard.js
5207
- import { constants as bufferConstants } from "node:buffer";
5179
+ // dist/clients/partial-edit-apply.js
5180
+ import { createHash as createHash3 } from "node:crypto";
5208
5181
  import * as fs4 from "node:fs";
5209
5182
 
5210
5183
  // dist/clients/file-time.js
@@ -5345,6 +5318,75 @@ function clearAllSessions() {
5345
5318
  globalState.locks.clear();
5346
5319
  }
5347
5320
 
5321
+ // dist/clients/partial-edit-apply.js
5322
+ var MAX_APPLIED_RECORDS_PER_FILE = 8;
5323
+ var MAX_APPLIED_RECORD_FILES = 64;
5324
+ function editPairDigest(oldText, newText) {
5325
+ return createHash3("sha256").update(JSON.stringify([oldText, newText ?? ""]), "utf8").digest("hex");
5326
+ }
5327
+ var PartialApplyRecordStore = class {
5328
+ // Bounded on the PathKeyedMap itself (#2442): the file axis used to
5329
+ // hand-roll `keys().next().value` here, which also evicted an unrelated
5330
+ // file when a path ALREADY in the map was re-recorded at capacity.
5331
+ files = new PathKeyedMap(normalizeMapKey, MAX_APPLIED_RECORD_FILES);
5332
+ find(filePath, oldText, newText) {
5333
+ if (!oldText)
5334
+ return void 0;
5335
+ const pairDigest = editPairDigest(oldText, newText);
5336
+ const records = this.files.get(filePath) ?? [];
5337
+ return records.find((r) => r.pairDigest === pairDigest);
5338
+ }
5339
+ record(filePath, oldText, newText, contentHash2) {
5340
+ if (!oldText)
5341
+ return;
5342
+ const pairDigest = editPairDigest(oldText, newText);
5343
+ const records = this.files.get(filePath) ?? [];
5344
+ const existing = records.findIndex((r) => r.pairDigest === pairDigest);
5345
+ if (existing >= 0)
5346
+ records.splice(existing, 1);
5347
+ const entry = {
5348
+ pairDigest,
5349
+ contentHash: contentHash2 ?? hashFile(filePath),
5350
+ appliedAtMs: Date.now()
5351
+ };
5352
+ if (records.length >= MAX_APPLIED_RECORDS_PER_FILE)
5353
+ records.shift();
5354
+ records.push(entry);
5355
+ this.files.set(filePath, records);
5356
+ }
5357
+ /**
5358
+ * Stamps the post-afterWrite file hash onto an existing record so a later
5359
+ * identical retry against the formatter-rewritten file is still recognized as
5360
+ * already-applied (#2402). No-op when the pair was never recorded.
5361
+ */
5362
+ noteAfterWriteHash(filePath, oldText, newText, afterWriteContentHash) {
5363
+ if (!oldText)
5364
+ return;
5365
+ const pairDigest = editPairDigest(oldText, newText);
5366
+ const record2 = this.files.get(filePath)?.find((r) => r.pairDigest === pairDigest);
5367
+ if (record2)
5368
+ record2.afterWriteContentHash = afterWriteContentHash;
5369
+ }
5370
+ clear() {
5371
+ this.files.clear();
5372
+ }
5373
+ get fileCount() {
5374
+ return this.files.size;
5375
+ }
5376
+ };
5377
+ var fileLock = createFileTime("partial-edit-apply");
5378
+ function hashFile(filePath) {
5379
+ try {
5380
+ return createHash3("sha256").update(fs4.readFileSync(filePath)).digest("hex");
5381
+ } catch {
5382
+ return void 0;
5383
+ }
5384
+ }
5385
+
5386
+ // dist/clients/read-guard.js
5387
+ import { constants as bufferConstants } from "node:buffer";
5388
+ import * as fs5 from "node:fs";
5389
+
5348
5390
  // dist/clients/eval-timestamp.js
5349
5391
  import { performance as performance2 } from "node:perf_hooks";
5350
5392
  var PI_LENS_EVAL_STARTED_MS = performance2.now();
@@ -5526,7 +5568,7 @@ var READ_BINDING_MAX_BYTES = 4 * 1024 * 1024;
5526
5568
  var ABSENT_SIZE = -1;
5527
5569
  function observeAuthoredBytes(filePath, knownHash, authoredRanges) {
5528
5570
  try {
5529
- const stat3 = fs4.statSync(filePath);
5571
+ const stat3 = fs5.statSync(filePath);
5530
5572
  const hash = knownHash !== void 0 ? knownHash : stat3.size <= READ_BINDING_MAX_BYTES ? hashFileBytes(filePath) : void 0;
5531
5573
  return {
5532
5574
  size: stat3.size,
@@ -5535,7 +5577,7 @@ function observeAuthoredBytes(filePath, knownHash, authoredRanges) {
5535
5577
  ...hash !== void 0 && { hash },
5536
5578
  ...authoredRanges !== void 0 && { authoredRanges },
5537
5579
  ...authoredRanges !== void 0 && {
5538
- authoredLineCount: splitLines(fs4.readFileSync(filePath, "utf-8")).length
5580
+ authoredLineCount: splitLines(fs5.readFileSync(filePath, "utf-8")).length
5539
5581
  }
5540
5582
  };
5541
5583
  } catch {
@@ -5567,7 +5609,7 @@ function isValidAuthoredRanges(value) {
5567
5609
  function authoredBytesIntact(filePath, authored) {
5568
5610
  let stat3;
5569
5611
  try {
5570
- stat3 = fs4.statSync(filePath);
5612
+ stat3 = fs5.statSync(filePath);
5571
5613
  } catch {
5572
5614
  return authored.size === ABSENT_SIZE;
5573
5615
  }
@@ -5625,7 +5667,7 @@ var READ_GUARD_MAX_CHECKED_PATHS_PER_CALL = 128;
5625
5667
  var READ_GUARD_IDLE_EVICT_MS_DEFAULT = 30 * 6e4;
5626
5668
  function _currentContentMatchesBindingForTests(filePath, binding) {
5627
5669
  try {
5628
- const content = fs4.readFileSync(filePath, "utf-8");
5670
+ const content = fs5.readFileSync(filePath, "utf-8");
5629
5671
  const boundContent = binding.fullFile ? content : splitLines(content).slice(binding.offset - 1, binding.offset - 1 + binding.limit).join("\n");
5630
5672
  return hashContentBytes(Buffer.from(boundContent, "utf8")) === binding.hash;
5631
5673
  } catch {
@@ -5693,8 +5735,8 @@ function scanFileLines(filePath, ranges, opts) {
5693
5735
  const lines = /* @__PURE__ */ new Map();
5694
5736
  let fd;
5695
5737
  try {
5696
- fd = fs4.openSync(filePath, "r");
5697
- const size = fs4.fstatSync(fd).size;
5738
+ fd = fs5.openSync(filePath, "r");
5739
+ const size = fs5.fstatSync(fd).size;
5698
5740
  if (size > SCAN_MAX_BYTES)
5699
5741
  return overByteGate(filePath, size);
5700
5742
  const byteBudget = size > 0 ? size : SCAN_MAX_BYTES + 1;
@@ -5705,7 +5747,7 @@ function scanFileLines(filePath, ranges, opts) {
5705
5747
  let parts = [];
5706
5748
  const keepLine = () => lines.set(lineNo, Buffer.concat(parts).toString("utf8"));
5707
5749
  while (consumed < byteBudget && !done(lineNo)) {
5708
- const n = fs4.readSync(fd, chunk, 0, Math.min(chunk.length, byteBudget - consumed), null);
5750
+ const n = fs5.readSync(fd, chunk, 0, Math.min(chunk.length, byteBudget - consumed), null);
5709
5751
  if (n === 0)
5710
5752
  break;
5711
5753
  consumed += n;
@@ -5761,7 +5803,7 @@ function scanFileLines(filePath, ranges, opts) {
5761
5803
  return void 0;
5762
5804
  } finally {
5763
5805
  if (fd !== void 0)
5764
- fs4.closeSync(fd);
5806
+ fs5.closeSync(fd);
5765
5807
  }
5766
5808
  }
5767
5809
  function overByteGate(filePath, bytes) {
@@ -5793,7 +5835,7 @@ function currentLinesMatchReadSnapshot(filePath, read, [startLine, endLine]) {
5793
5835
  }
5794
5836
  let lines;
5795
5837
  try {
5796
- lines = splitLines(fs4.readFileSync(filePath, "utf-8"));
5838
+ lines = splitLines(fs5.readFileSync(filePath, "utf-8"));
5797
5839
  } catch {
5798
5840
  return {
5799
5841
  checked: true,
@@ -5857,9 +5899,9 @@ var ReadGuard = class {
5857
5899
  // Existence-independent index for hasKnownPath/forgetPath (#1668 review
5858
5900
  // F1). `this.key()` (normalizeFilePath) branches on whether `filePath`
5859
5901
  // currently exists on disk, on EVERY platform since #3098 — an existing
5860
- // file resolves to its on-disk casing (win32: `realpathSync.native`;
5861
- // POSIX: the on-disk casing of the trailing segments), a missing one to a
5862
- // lowercased tail on win32 and to the caller's own spelling on POSIX.
5902
+ // file resolves to its path identity (`realpathSync.native` on both, #4689
5903
+ // on POSIX), a missing one to its nearest existing ancestor's identity
5904
+ // plus a lowercased tail on win32 and the caller's own tail on POSIX.
5863
5905
  // recordRead/recordWritten always key while the file is still on disk
5864
5906
  // (real casing); hasKnownPath/forgetPath are queried AFTER an external
5865
5907
  // delete already landed, when the path no longer exists — recomputing
@@ -5909,21 +5951,16 @@ var ReadGuard = class {
5909
5951
  * Keying the reads/edits/exemptions maps on the raw path made a read recorded
5910
5952
  * under one form invisible to an edit checked under another, producing a false
5911
5953
  * `zero_read` block despite the file having been read. `normalizeFilePath`
5912
- * folds separators and Windows casing to one key, so record and lookup always
5913
- * agree. Every map access in this class MUST key through here.
5954
+ * folds separators and Windows casing to one key and, for an absolute path,
5955
+ * answers its path identity (#4689), so a read through a link credits an
5956
+ * edit of its target and the reverse. Every map access in this class MUST
5957
+ * key through here, the tool_call license included: before #4689 the
5958
+ * license had its own realpath key (`licenseKey`) while the read credit kept
5959
+ * the spelling, so one class held two identities for one file.
5914
5960
  */
5915
5961
  key(filePath) {
5916
5962
  return normalizeFilePath(filePath);
5917
5963
  }
5918
- /**
5919
- * License keys compare paths independently resolved by the tool_call and
5920
- * the writer. Unlike the general map key, this identity must collapse a
5921
- * symlink spelling to the file it names; missing files retain an absolute
5922
- * resolved fallback so the comparison still fails closed.
5923
- */
5924
- licenseKey(filePath) {
5925
- return normalizeFilePath(realpathOrResolve(filePath));
5926
- }
5927
5964
  idleEvictMs() {
5928
5965
  const value = Number.parseInt(process.env.PI_LENS_READ_GUARD_IDLE_EVICT_MS ?? "", 10);
5929
5966
  return Number.isSafeInteger(value) && value > 0 ? value : READ_GUARD_IDLE_EVICT_MS_DEFAULT;
@@ -6260,7 +6297,7 @@ var ReadGuard = class {
6260
6297
  for (const rawPath of rawPaths) {
6261
6298
  if (checked.size >= READ_GUARD_MAX_CHECKED_PATHS_PER_CALL)
6262
6299
  return;
6263
- checked.add(this.licenseKey(rawPath));
6300
+ checked.add(this.key(rawPath));
6264
6301
  }
6265
6302
  }
6266
6303
  /**
@@ -6273,7 +6310,7 @@ var ReadGuard = class {
6273
6310
  if (callId === void 0)
6274
6311
  return false;
6275
6312
  const checked = this.checkedPathsByCall.get(callId);
6276
- const licensedPath = this.licenseKey(filePath);
6313
+ const licensedPath = this.key(filePath);
6277
6314
  if (checked?.has(licensedPath) !== true)
6278
6315
  return false;
6279
6316
  checked.delete(licensedPath);
@@ -6566,7 +6603,7 @@ Re-read the relevant section, then retry the edit using the current line range/c
6566
6603
  */
6567
6604
  isNewFile(filePath) {
6568
6605
  try {
6569
- return !fs4.existsSync(filePath);
6606
+ return !fs5.existsSync(filePath);
6570
6607
  } catch {
6571
6608
  return true;
6572
6609
  }
@@ -6932,7 +6969,7 @@ Re-read the relevant section, then retry the edit using the current line range/c
6932
6969
  if (!Array.isArray(records) || records.length === 0)
6933
6970
  continue;
6934
6971
  const filePath = this.key(rawPath);
6935
- const exists = fs4.existsSync(filePath);
6972
+ const exists = fs5.existsSync(filePath);
6936
6973
  for (const read of records) {
6937
6974
  const id = read?.toolCallId;
6938
6975
  if (!exists || typeof id !== "string" || !onBranch.has(id)) {
@@ -7028,7 +7065,7 @@ Re-read the relevant section, then retry the edit using the current line range/c
7028
7065
  let evidence;
7029
7066
  try {
7030
7067
  evidence = writtenContent !== void 0 ? deliveredLineEvidence(writtenContent, 1) : {
7031
- lineCount: splitLines(fs4.readFileSync(filePath, "utf-8")).length,
7068
+ lineCount: splitLines(fs5.readFileSync(filePath, "utf-8")).length,
7032
7069
  lineHashes: void 0
7033
7070
  };
7034
7071
  } catch {
@@ -7054,7 +7091,7 @@ Re-read the relevant section, then retry the edit using the current line range/c
7054
7091
  canIgnoreStalenessByHashes(filePath, reads, touchedLines, editRanges) {
7055
7092
  let lines;
7056
7093
  try {
7057
- lines = splitLines(fs4.readFileSync(filePath, "utf-8"));
7094
+ lines = splitLines(fs5.readFileSync(filePath, "utf-8"));
7058
7095
  } catch {
7059
7096
  return false;
7060
7097
  }
@@ -7194,7 +7231,7 @@ Re-read the relevant section, then retry the edit using the current line range/c
7194
7231
  }
7195
7232
  let lines;
7196
7233
  try {
7197
- lines = splitLines(fs4.readFileSync(filePath, "utf-8"));
7234
+ lines = splitLines(fs5.readFileSync(filePath, "utf-8"));
7198
7235
  } catch {
7199
7236
  return void 0;
7200
7237
  }
@@ -7382,6 +7419,127 @@ function mapVerdictAction(action) {
7382
7419
  }
7383
7420
  }
7384
7421
 
7422
+ // dist/clients/read-guard-tool-lines.js
7423
+ var MAX_FAILURE_TRACKER_SIZE = 200;
7424
+ var recentOldTextFailures = new BoundedFifoMap(MAX_FAILURE_TRACKER_SIZE);
7425
+
7426
+ // dist/clients/bash-file-access.js
7427
+ var ANSI_C_ESCAPES = new Map(Object.entries({
7428
+ a: 7,
7429
+ b: 8,
7430
+ e: 27,
7431
+ E: 27,
7432
+ f: 12,
7433
+ n: 10,
7434
+ r: 13,
7435
+ t: 9,
7436
+ v: 11,
7437
+ "\\": 92,
7438
+ "'": 39,
7439
+ '"': 34,
7440
+ "?": 63
7441
+ }).map(([escape, value]) => [escape.charCodeAt(0), value]));
7442
+
7443
+ // dist/clients/opaque-mutation-scan.js
7444
+ var OPAQUE_HASH_BUDGET_BYTES = 8 * 1024 * 1024;
7445
+ var MAX_GIT_STATUS_OUTPUT_BYTES = 16 * 1024 * 1024;
7446
+ var PI_BUILTIN_TOOL_WRITES = new Map(Object.entries({
7447
+ bash: "opaque",
7448
+ powershell: "opaque",
7449
+ write: "named",
7450
+ edit: "named",
7451
+ read: "none",
7452
+ grep: "none",
7453
+ find: "none",
7454
+ ls: "none"
7455
+ }));
7456
+ var OPAQUE_BASELINE_PENDING_CAP = 64;
7457
+ var OpaqueBaselineStore = class _OpaqueBaselineStore {
7458
+ pending = new BoundedFifoMap(OPAQUE_BASELINE_PENDING_CAP);
7459
+ static keyOf(slot, callId) {
7460
+ return callId === void 0 ? slot : `${slot}#${callId}`;
7461
+ }
7462
+ /**
7463
+ * Store `state` for a call. A baseline this displaces is lost: its
7464
+ * `tool_result` will find nothing and report `partial-recognition-no-baseline`,
7465
+ * withholding the blocker section of a write the agent authored. That loss is
7466
+ * counted in the degradation ledger, one entry per cause with a running count,
7467
+ * never one row per occurrence (#4137).
7468
+ *
7469
+ * First, an entry whose turn is over is retired: pi sends no `tool_result`
7470
+ * for a call a `tool_call` handler blocked or Escape aborted before it ran,
7471
+ * and on a non-git project the entry holds a whole-tree stat snapshot.
7472
+ */
7473
+ record(slot, callId, state4, turn) {
7474
+ for (const [staleKey, entry] of this.pending.entriesArray())
7475
+ if (entry.turn && !entry.turn.isLive(entry.turn.key)) {
7476
+ this.pending.delete(staleKey);
7477
+ recordBaselineLoss("unsettled");
7478
+ }
7479
+ const key = _OpaqueBaselineStore.keyOf(slot, callId);
7480
+ const overwrote = this.pending.delete(key);
7481
+ const evicted = this.pending.set(key, { state: state4, turn });
7482
+ if (overwrote)
7483
+ recordBaselineLoss("overwrite");
7484
+ if (evicted.length > 0)
7485
+ recordBaselineLoss("cap");
7486
+ }
7487
+ /**
7488
+ * #4732: whether `tool_call` recorded a baseline for this call. A tool other
7489
+ * than bash recovers only then, so its `tool_result` follows the decision its
7490
+ * own `tool_call` made instead of re-deriving it (shape 19).
7491
+ */
7492
+ has(slot, callId) {
7493
+ return this.pending.has(_OpaqueBaselineStore.keyOf(slot, callId));
7494
+ }
7495
+ take(slot, callId) {
7496
+ const key = _OpaqueBaselineStore.keyOf(slot, callId);
7497
+ const entry = this.pending.get(key);
7498
+ this.pending.delete(key);
7499
+ return entry?.state;
7500
+ }
7501
+ /** Session-boundary clear - unconsumed baselines are unreachable after reset. */
7502
+ takeAllForTest() {
7503
+ this.pending.clear();
7504
+ }
7505
+ };
7506
+ var BASELINE_LOSS_REASONS = {
7507
+ overwrite: "a pending opaque baseline (bash or another captured tool) was replaced before its tool_result took it; that call reports partial-recognition-no-baseline and withholds blockers (host without distinct tool-call ids, or a reused id)",
7508
+ cap: `more than ${OPAQUE_BASELINE_PENDING_CAP} opaque baselines (bash or other captured tools) awaited a tool_result; the oldest was dropped`,
7509
+ unsettled: "an opaque baseline (bash or another captured tool) outlived its turn with no tool_result (the call was blocked or aborted before it ran) and was retired; a result that still arrives reports partial-recognition-no-baseline"
7510
+ };
7511
+ function recordBaselineLoss(cause) {
7512
+ incrementDegradationCount({
7513
+ kind: "opaque-baseline-lost",
7514
+ subject: cause,
7515
+ reason: BASELINE_LOSS_REASONS[cause]
7516
+ });
7517
+ }
7518
+ var globalStoreSymbol = /* @__PURE__ */ Symbol.for("pi-lens:opaque-snapshot-store");
7519
+ var globalSlot = globalThis;
7520
+ function getOpaqueBaselineStore() {
7521
+ const existing = globalSlot[globalStoreSymbol]?.store;
7522
+ if (existing)
7523
+ return existing;
7524
+ const created = new OpaqueBaselineStore();
7525
+ globalSlot[globalStoreSymbol] = { store: created };
7526
+ return created;
7527
+ }
7528
+ var gitRepoMemo = /* @__PURE__ */ new Map();
7529
+ function resetOpaqueMutationState() {
7530
+ getOpaqueBaselineStore().takeAllForTest();
7531
+ gitRepoMemo.clear();
7532
+ gitToplevelMemo.clear();
7533
+ headRecords.clear();
7534
+ headLooks.clear();
7535
+ pendingHeadDiscards.clear();
7536
+ }
7537
+ var HEAD_RECORD_CAP = 64;
7538
+ var headRecords = new BoundedFifoMap(HEAD_RECORD_CAP);
7539
+ var pendingHeadDiscards = new BoundedFifoMap(HEAD_RECORD_CAP);
7540
+ var headLooks = createSingleFlight({ coalesceTrailing: true });
7541
+ var gitToplevelMemo = /* @__PURE__ */ new Map();
7542
+
7385
7543
  // dist/clients/observed-mutation.js
7386
7544
  var OBSERVED_HANDLED_MAX = 1e3;
7387
7545
  var OBSERVED_HASH_BUDGET_BYTES = 2 * 1024 * 1024;
@@ -7874,8 +8032,8 @@ function recordLspMutationOutcome(context, status) {
7874
8032
  }
7875
8033
 
7876
8034
  // dist/clients/lsp/diagnostic-binding.js
7877
- import { createHash as createHash3 } from "node:crypto";
7878
- import * as fs5 from "node:fs";
8035
+ import { createHash as createHash4 } from "node:crypto";
8036
+ import * as fs6 from "node:fs";
7879
8037
  function resolveTouchVerdict(input) {
7880
8038
  const unavailableIds = [...new Set(input.unavailablePrimaryServerIds ?? [])];
7881
8039
  if (unavailableIds.length > 0) {
@@ -7937,7 +8095,7 @@ function auxiliaryCoverageGap(evidence) {
7937
8095
  return evidence.filter((aux) => aux.outcome !== "answered" && aux.publishedThisContent !== true).map((aux) => aux.serverId);
7938
8096
  }
7939
8097
  function hashDiagnosticContent(content) {
7940
- return createHash3("sha256").update(content).digest("hex");
8098
+ return createHash4("sha256").update(content).digest("hex");
7941
8099
  }
7942
8100
  function composeBoundToCurrentDisk(values) {
7943
8101
  if (values.some((v) => v === false))
@@ -7963,7 +8121,7 @@ function createDiskBindingCache() {
7963
8121
  return "unknown";
7964
8122
  let stat3;
7965
8123
  try {
7966
- stat3 = fs5.statSync(filePath);
8124
+ stat3 = fs6.statSync(filePath);
7967
8125
  } catch {
7968
8126
  return "unknown";
7969
8127
  }
@@ -7971,7 +8129,7 @@ function createDiskBindingCache() {
7971
8129
  if (!cached || cached.mtimeMs !== stat3.mtimeMs || cached.size !== stat3.size) {
7972
8130
  let diskHash;
7973
8131
  try {
7974
- diskHash = hashDiagnosticContent(fs5.readFileSync(filePath, "utf-8"));
8132
+ diskHash = hashDiagnosticContent(fs6.readFileSync(filePath, "utf-8"));
7975
8133
  } catch {
7976
8134
  return "unknown";
7977
8135
  }
@@ -8029,12 +8187,12 @@ async function runPerServerGroups(groups, concurrency, processGroup, signal) {
8029
8187
  import path13 from "node:path";
8030
8188
 
8031
8189
  // dist/clients/widget-state.js
8032
- import { readFileSync as readFileSync6 } from "node:fs";
8190
+ import { readFileSync as readFileSync7 } from "node:fs";
8033
8191
  import { stat } from "node:fs/promises";
8034
8192
  import { pathToFileURL } from "node:url";
8035
8193
 
8036
8194
  // dist/clients/diagnostic-line-freshness.js
8037
- import * as fs6 from "node:fs";
8195
+ import * as fs7 from "node:fs";
8038
8196
 
8039
8197
  // dist/clients/stale-marker.js
8040
8198
  var STALE_LINE_MARKER = "[stale \u2014 re-run to confirm]";
@@ -8051,13 +8209,13 @@ function rememberInSharedCache(cache, filePath, entry) {
8051
8209
  cache.set(filePath, entry);
8052
8210
  }
8053
8211
  function countNewlinesChunked(filePath, sizeBytes) {
8054
- const fd = fs6.openSync(filePath, "r");
8212
+ const fd = fs7.openSync(filePath, "r");
8055
8213
  try {
8056
8214
  const buffer = Buffer.allocUnsafe(Math.min(NEWLINE_SCAN_CHUNK_BYTES, sizeBytes) || 1);
8057
8215
  let newlineCount = 0;
8058
8216
  let position = 0;
8059
8217
  while (position < sizeBytes) {
8060
- const bytesRead = fs6.readSync(fd, buffer, 0, buffer.length, position);
8218
+ const bytesRead = fs7.readSync(fd, buffer, 0, buffer.length, position);
8061
8219
  if (bytesRead <= 0)
8062
8220
  break;
8063
8221
  for (let i = 0; i < bytesRead; i++) {
@@ -8068,13 +8226,13 @@ function countNewlinesChunked(filePath, sizeBytes) {
8068
8226
  }
8069
8227
  return newlineCount;
8070
8228
  } finally {
8071
- fs6.closeSync(fd);
8229
+ fs7.closeSync(fd);
8072
8230
  }
8073
8231
  }
8074
8232
  function getCachedLineCount(filePath, cache = sharedLineCountCache) {
8075
8233
  let stat3;
8076
8234
  try {
8077
- stat3 = fs6.statSync(filePath);
8235
+ stat3 = fs7.statSync(filePath);
8078
8236
  } catch {
8079
8237
  return void 0;
8080
8238
  }
@@ -8129,7 +8287,7 @@ function demotePastEofDiagnostics(args) {
8129
8287
  }
8130
8288
  let sizeBytes;
8131
8289
  try {
8132
- sizeBytes = fs6.statSync(args.filePath).size;
8290
+ sizeBytes = fs7.statSync(args.filePath).size;
8133
8291
  } catch {
8134
8292
  sizeBytes = 0;
8135
8293
  }
@@ -8159,8 +8317,8 @@ function resyncDocumentOnPastEof(filePath) {
8159
8317
  void (async () => {
8160
8318
  try {
8161
8319
  const [{ getOwnedLspService: getOwnedLspService2 }, content] = await Promise.all([
8162
- import("./chunk-O4NWQT6I.js"),
8163
- fs6.promises.readFile(filePath, "utf-8")
8320
+ import("./chunk-YXDCRUKQ.js"),
8321
+ fs7.promises.readFile(filePath, "utf-8")
8164
8322
  ]);
8165
8323
  await getOwnedLspService2().openFile(filePath, content, { preserveDiagnostics: false });
8166
8324
  } catch {
@@ -8215,7 +8373,7 @@ var WriteOrderingGuard = class {
8215
8373
  };
8216
8374
 
8217
8375
  // dist/clients/diagnostic-dispositions.js
8218
- import * as fs7 from "node:fs";
8376
+ import * as fs8 from "node:fs";
8219
8377
  import * as path9 from "node:path";
8220
8378
 
8221
8379
  // dist/clients/disposition-logger.js
@@ -8234,13 +8392,19 @@ var writer2 = createNdjsonLogger({
8234
8392
  var liveEmitter3 = createLiveBusEmitter();
8235
8393
 
8236
8394
  // dist/clients/diagnostic-dispositions.js
8237
- var deferredThisSession = /* @__PURE__ */ new Set();
8395
+ var deferredByCwd = /* @__PURE__ */ new Map();
8238
8396
  var widgetDispositionReconciler = null;
8239
8397
  function registerWidgetDispositionReconciler(reconciler) {
8240
8398
  widgetDispositionReconciler = reconciler;
8241
8399
  }
8242
- function deferredKey(cwd, anchor) {
8243
- return `${normalizeMapKey(cwd)}::${anchor}`;
8400
+ function deferredAnchorsFor(cwd) {
8401
+ return deferredByCwd.get(normalizeMapKey(cwd));
8402
+ }
8403
+ function hasDeferredThisSession(cwd) {
8404
+ return deferredByCwd.has(normalizeMapKey(cwd));
8405
+ }
8406
+ function nothingToApply(dispositions, cwd) {
8407
+ return !dispositions && !hasDeferredThisSession(cwd);
8244
8408
  }
8245
8409
  var normalizeMessage2 = normalizeMessage;
8246
8410
  function strictAnchorSpan(content, line) {
@@ -8296,9 +8460,9 @@ function statePath(cwd) {
8296
8460
  return path9.join(getProjectDataDir(cwd), "cache", "diagnostic-dispositions.json");
8297
8461
  }
8298
8462
  var stateCache = null;
8299
- var dispositionStatSync = fs7.statSync;
8463
+ var dispositionStatSync = fs8.statSync;
8300
8464
  function hasAnyDispositionMarks(cwd) {
8301
- return Boolean(readState(cwd).dispositions) || deferredThisSession.size > 0;
8465
+ return Boolean(readState(cwd).dispositions) || hasDeferredThisSession(cwd);
8302
8466
  }
8303
8467
  function hasStrictDispositionMarks(cwd) {
8304
8468
  const dispositions = readState(cwd).dispositions;
@@ -8310,7 +8474,7 @@ function hasStrictDispositionMarks(cwd) {
8310
8474
  }
8311
8475
  return false;
8312
8476
  }
8313
- var multiFileReadFileSync = fs7.readFileSync;
8477
+ var multiFileReadFileSync = fs8.readFileSync;
8314
8478
  function readState(cwd) {
8315
8479
  const p = statePath(cwd);
8316
8480
  let stat3;
@@ -8335,7 +8499,7 @@ function readState(cwd) {
8335
8499
  }
8336
8500
  let state4;
8337
8501
  try {
8338
- const parsed = JSON.parse(fs7.readFileSync(p, "utf-8"));
8502
+ const parsed = JSON.parse(fs8.readFileSync(p, "utf-8"));
8339
8503
  state4 = parsed && typeof parsed === "object" ? parsed : {};
8340
8504
  } catch {
8341
8505
  state4 = {};
@@ -8352,16 +8516,20 @@ function readState(cwd) {
8352
8516
  function getDisposition(cwd, anchor) {
8353
8517
  return readState(cwd).dispositions?.[anchor];
8354
8518
  }
8519
+ function resetDeferredDispositions() {
8520
+ deferredByCwd.clear();
8521
+ }
8355
8522
  function applyDispositions(diagnostics, cwd, filePath, content) {
8356
8523
  if (!diagnostics.length)
8357
8524
  return diagnostics;
8358
8525
  const dispositions = readState(cwd).dispositions;
8359
- if (!dispositions && deferredThisSession.size === 0)
8526
+ if (nothingToApply(dispositions, cwd))
8360
8527
  return diagnostics;
8528
+ const deferred = deferredAnchorsFor(cwd);
8361
8529
  return diagnostics.filter((d) => {
8362
8530
  const { strict, weak } = anchorsForDiagnostic(cwd, filePath, d, content);
8363
8531
  const isBlocking2 = d.semantic === "blocking";
8364
- if (!isBlocking2 && deferredThisSession.has(deferredKey(cwd, weak))) {
8532
+ if (!isBlocking2 && deferred?.has(weak)) {
8365
8533
  return false;
8366
8534
  }
8367
8535
  if (dispositions?.[strict]?.disposition === "false-positive")
@@ -8376,8 +8544,9 @@ function applyWeakDispositions(diagnostics, cwd, filePath) {
8376
8544
  if (!diagnostics.length)
8377
8545
  return diagnostics;
8378
8546
  const dispositions = readState(cwd).dispositions;
8379
- if (!dispositions && deferredThisSession.size === 0)
8547
+ if (nothingToApply(dispositions, cwd))
8380
8548
  return diagnostics;
8549
+ const deferred = deferredAnchorsFor(cwd);
8381
8550
  return diagnostics.filter((d) => {
8382
8551
  if (d.semantic === "blocking")
8383
8552
  return true;
@@ -8389,7 +8558,7 @@ function applyWeakDispositions(diagnostics, cwd, filePath) {
8389
8558
  message: d.message,
8390
8559
  line: d.line
8391
8560
  });
8392
- if (deferredThisSession.has(deferredKey(cwd, weak)))
8561
+ if (deferred?.has(weak))
8393
8562
  return false;
8394
8563
  if (dispositions?.[weak]?.disposition === "suppress")
8395
8564
  return false;
@@ -8400,7 +8569,7 @@ function applyDispositionsMultiFile(diagnostics, cwd, filePathOf) {
8400
8569
  if (!diagnostics.length)
8401
8570
  return diagnostics;
8402
8571
  const dispositions = readState(cwd).dispositions;
8403
- if (!dispositions && deferredThisSession.size === 0)
8572
+ if (nothingToApply(dispositions, cwd))
8404
8573
  return diagnostics;
8405
8574
  const groups = /* @__PURE__ */ new Map();
8406
8575
  for (const d of diagnostics) {
@@ -8426,11 +8595,11 @@ function applyDispositionsMultiFile(diagnostics, cwd, filePathOf) {
8426
8595
  }
8427
8596
 
8428
8597
  // dist/clients/session-state-store.js
8429
- import { promises as fs8 } from "node:fs";
8598
+ import { promises as fs9 } from "node:fs";
8430
8599
  async function dropStaleFiles(widget, savedAt) {
8431
8600
  const checked = await Promise.all(widget.files.map(async (file) => {
8432
8601
  try {
8433
- const st = await fs8.stat(file.filePath);
8602
+ const st = await fs9.stat(file.filePath);
8434
8603
  return freshnessFromMtime({
8435
8604
  mtimeMs: st.mtimeMs,
8436
8605
  referenceMs: savedAt,
@@ -8502,7 +8671,7 @@ function reconcileWidgetDisposition(cwd, target, _disposition, content) {
8502
8671
  let source = content ?? target.content;
8503
8672
  if (source === void 0) {
8504
8673
  try {
8505
- source = readFileSync6(target.filePath, "utf8");
8674
+ source = readFileSync7(target.filePath, "utf8");
8506
8675
  } catch {
8507
8676
  recordDegradationOnce({
8508
8677
  kind: "widget-disposition-reconcile-fallback",
@@ -8545,7 +8714,12 @@ function reconcileWidgetDisposition(cwd, target, _disposition, content) {
8545
8714
  const writeIndex = admitWidgetDiagnosticsWrite(target.filePath);
8546
8715
  if (!diagnosticsWriteGuard.shouldWrite(fileMapKey(target.filePath), writeIndex))
8547
8716
  return;
8717
+ const { hasFinalDiagnosticsSnapshot, touchedAt } = rec;
8548
8718
  commitDiagnostics(rec, target.filePath, normalized, Date.now(), fileMapKey(target.filePath), false);
8719
+ if (!hasFinalDiagnosticsSnapshot) {
8720
+ rec.hasFinalDiagnosticsSnapshot = false;
8721
+ rec.touchedAt = touchedAt;
8722
+ }
8549
8723
  }
8550
8724
  function admitWidgetDiagnosticsWrite(filePath, writeIndex) {
8551
8725
  const key = fileMapKey(filePath);
@@ -8694,7 +8868,7 @@ function normalizeDiagnostics(filePath, diagnostics, observedTs) {
8694
8868
  var retentionIdentity = findingIdentity;
8695
8869
  function readContentOrUndefined(filePath) {
8696
8870
  try {
8697
- return readFileSync6(filePath, "utf8");
8871
+ return readFileSync7(filePath, "utf8");
8698
8872
  } catch {
8699
8873
  recordDegradationOnce({
8700
8874
  kind: "widget-mark-anchor-unreadable",
@@ -8835,7 +9009,7 @@ function reconcileCorrelatedScanDiagnostics(filePath, diagnostics, writeIndex, o
8835
9009
  }));
8836
9010
  commitDiagnostics(getOrCreate(filePath, key), filePath, correlated, observedTs, key);
8837
9011
  }
8838
- async function reconcileStaleWidgetFiles() {
9012
+ async function reconcileStaleWidgetFiles(onStaleFile) {
8839
9013
  const entries = [...files.entries()];
8840
9014
  const verdicts = await Promise.all(
8841
9015
  // `mapKey` is the normalized `files` key (used for deletion); stat the
@@ -8845,10 +9019,15 @@ async function reconcileStaleWidgetFiles() {
8845
9019
  try {
8846
9020
  mtimeMs = (await stat(rec.filePath)).mtimeMs;
8847
9021
  } catch {
8848
- return { mapKey, action: "drop" };
9022
+ return { mapKey, action: "missing" };
8849
9023
  }
8850
9024
  if (rec.allDiagnostics.length === 0) {
8851
- return freshnessFromMtime({ mtimeMs, referenceMs: rec.touchedAt }).verdict === "stale" ? { mapKey, action: "drop" } : { mapKey, action: "keep" };
9025
+ return freshnessFromMtime({ mtimeMs, referenceMs: rec.touchedAt }).verdict === "stale" ? {
9026
+ mapKey,
9027
+ action: "stale",
9028
+ mtimeMs,
9029
+ survivors: []
9030
+ } : { mapKey, action: "keep" };
8852
9031
  }
8853
9032
  const mtimeStale = (d) => freshnessFromMtime({
8854
9033
  mtimeMs,
@@ -8859,32 +9038,32 @@ async function reconcileStaleWidgetFiles() {
8859
9038
  if (survivors.length === rec.allDiagnostics.length) {
8860
9039
  return { mapKey, action: "keep" };
8861
9040
  }
8862
- if (survivors.length === 0) {
8863
- return { mapKey, action: "drop" };
8864
- }
8865
- return { mapKey, action: "prune", survivors };
9041
+ return { mapKey, action: "stale", mtimeMs, survivors };
8866
9042
  })
8867
9043
  );
8868
- let dropped = 0;
9044
+ let changed = 0;
8869
9045
  for (const v of verdicts) {
8870
9046
  if (v.action === "keep")
8871
9047
  continue;
8872
- if (v.action === "drop") {
9048
+ const rec = files.get(v.mapKey);
9049
+ if (rec)
9050
+ onStaleFile?.(rec.filePath);
9051
+ changed += 1;
9052
+ if (v.action === "missing") {
8873
9053
  files.delete(v.mapKey);
8874
- dropped += 1;
8875
9054
  continue;
8876
9055
  }
8877
- const rec = files.get(v.mapKey);
8878
- if (rec) {
8879
- rec.allDiagnostics = v.survivors;
8880
- rec.diagnostics = capStoredDiagnostics(v.survivors);
8881
- rec.diagnosticCounts = countDiagnostics(v.survivors);
8882
- }
8883
- dropped += 1;
9056
+ if (!rec)
9057
+ continue;
9058
+ rec.allDiagnostics = v.survivors;
9059
+ rec.diagnostics = capStoredDiagnostics(v.survivors);
9060
+ rec.diagnosticCounts = countDiagnostics(v.survivors);
9061
+ rec.hasFinalDiagnosticsSnapshot = false;
9062
+ rec.touchedAt = Math.max(Date.now(), v.mtimeMs);
8884
9063
  }
8885
- if (dropped > 0)
9064
+ if (changed > 0)
8886
9065
  requestRenderFn?.();
8887
- return dropped;
9066
+ return changed;
8888
9067
  }
8889
9068
  async function reconcileStaleWidgetDependencyBlockers(cwd, turnIndex) {
8890
9069
  let demoted = 0;
@@ -9048,6 +9227,14 @@ function recordLsp(serverId, root, status, durationMs) {
9048
9227
  lspServers.set(key, { serverId, root, status: mapped, durationMs });
9049
9228
  requestRender();
9050
9229
  }
9230
+ function classifyFileTier(rec) {
9231
+ if (rec.diagnosticCounts.blocking > 0)
9232
+ return "blocking";
9233
+ if (rec.diagnosticCounts.errors > 0 || rec.diagnosticCounts.warnings > 0) {
9234
+ return "warning";
9235
+ }
9236
+ return "clean";
9237
+ }
9051
9238
  function getOrCreate(filePath, key = fileMapKey(filePath)) {
9052
9239
  maybePruneInactiveFileRecords();
9053
9240
  return files.get(key) ?? {
@@ -9061,8 +9248,11 @@ function getOrCreate(filePath, key = fileMapKey(filePath)) {
9061
9248
  touchedAt: Date.now()
9062
9249
  };
9063
9250
  }
9251
+ function holdsDrawableFindings(rec) {
9252
+ return classifyFileTier(rec) !== "clean";
9253
+ }
9064
9254
  function hasLiveDiagnostic(rec) {
9065
- return rec.hasFinalDiagnosticsSnapshot && rec.diagnostics.length > 0;
9255
+ return rec.diagnostics.length > 0 && (rec.hasFinalDiagnosticsSnapshot || holdsDrawableFindings(rec));
9066
9256
  }
9067
9257
  function capStoredDiagnostics(diagnostics) {
9068
9258
  if (diagnostics.length <= MAX_STORED_DIAGNOSTICS_PER_FILE)
@@ -9106,14 +9296,14 @@ async function raceToCompletion(promises3, shouldComplete, options = { timeoutMs
9106
9296
  const languageCount = promises3.length - auxIndices.size;
9107
9297
  let languageRemaining = languageCount;
9108
9298
  let auxGraceStarted = false;
9109
- return new Promise((resolve8) => {
9299
+ return new Promise((resolve9) => {
9110
9300
  const timeout = setTimeout(() => {
9111
9301
  completed = true;
9112
9302
  if (graceTimer)
9113
9303
  clearTimeout(graceTimer);
9114
9304
  if (auxGraceTimer)
9115
9305
  clearTimeout(auxGraceTimer);
9116
- resolve8(results.filter((r) => r !== void 0));
9306
+ resolve9(results.filter((r) => r !== void 0));
9117
9307
  }, options.timeoutMs);
9118
9308
  const finalize = () => {
9119
9309
  if (completed)
@@ -9124,7 +9314,7 @@ async function raceToCompletion(promises3, shouldComplete, options = { timeoutMs
9124
9314
  clearTimeout(graceTimer);
9125
9315
  if (auxGraceTimer)
9126
9316
  clearTimeout(auxGraceTimer);
9127
- resolve8(results.filter((r) => r !== void 0));
9317
+ resolve9(results.filter((r) => r !== void 0));
9128
9318
  };
9129
9319
  const startAuxGrace = () => {
9130
9320
  if (auxGraceStarted || completed)
@@ -9183,7 +9373,8 @@ async function raceToCompletion(promises3, shouldComplete, options = { timeoutMs
9183
9373
  }
9184
9374
 
9185
9375
  // dist/clients/lsp/edits.js
9186
- import fs9 from "node:fs/promises";
9376
+ import fs10 from "node:fs/promises";
9377
+ import { readFileSync as readFileSync8, realpathSync as realpathSync2, statSync as statSync8 } from "node:fs";
9187
9378
  import path10 from "node:path";
9188
9379
  import { URL as URL2 } from "node:url";
9189
9380
 
@@ -9209,12 +9400,6 @@ function convertCharacterOffset(encoding, lineText, utf16Character) {
9209
9400
  return Buffer.byteLength(prefix, "utf8");
9210
9401
  return [...prefix].length;
9211
9402
  }
9212
- function lineTextAt(content, line) {
9213
- if (line < 0)
9214
- return "";
9215
- const lines = content.split("\n");
9216
- return lines[line] ?? "";
9217
- }
9218
9403
 
9219
9404
  // dist/clients/lsp/watch-queue.js
9220
9405
  var WATCH_DEBOUNCE_MS = 100;
@@ -9290,56 +9475,6 @@ var WatchedFilesQueue = class {
9290
9475
  }
9291
9476
  };
9292
9477
 
9293
- // dist/clients/host-edit-normalize.js
9294
- var HOST_SMART_SINGLE_QUOTES = [8216, 8217, 8218, 8219];
9295
- var HOST_SMART_DOUBLE_QUOTES = [8220, 8221, 8222, 8223];
9296
- var HOST_UNICODE_DASHES = [
9297
- 8208,
9298
- 8209,
9299
- 8210,
9300
- 8211,
9301
- 8212,
9302
- 8213,
9303
- 8722
9304
- ];
9305
- var HOST_SPECIAL_SPACES = [
9306
- 160,
9307
- 8194,
9308
- 8195,
9309
- 8196,
9310
- 8197,
9311
- 8198,
9312
- 8199,
9313
- 8200,
9314
- 8201,
9315
- 8202,
9316
- 8239,
9317
- 8287,
9318
- 12288
9319
- ];
9320
- var HOST_BOM_CODE_POINT = 65279;
9321
- var charClass = (codePoints) => new RegExp(`[${String.fromCharCode(...codePoints)}]`, "g");
9322
- var SMART_SINGLE_QUOTES_RE = charClass(HOST_SMART_SINGLE_QUOTES);
9323
- var SMART_DOUBLE_QUOTES_RE = charClass(HOST_SMART_DOUBLE_QUOTES);
9324
- var UNICODE_DASHES_RE = charClass(HOST_UNICODE_DASHES);
9325
- var SPECIAL_SPACES_RE = charClass(HOST_SPECIAL_SPACES);
9326
- var BOM = String.fromCharCode(HOST_BOM_CODE_POINT);
9327
- function detectLineEnding(content) {
9328
- const crlfIdx = content.indexOf("\r\n");
9329
- const lfIdx = content.indexOf("\n");
9330
- if (lfIdx === -1)
9331
- return "\n";
9332
- if (crlfIdx === -1)
9333
- return "\n";
9334
- return crlfIdx < lfIdx ? "\r\n" : "\n";
9335
- }
9336
- function normalizeToLF(text) {
9337
- return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
9338
- }
9339
- function restoreLineEndings(text, ending) {
9340
- return ending === "\r\n" ? text.replace(/\n/g, "\r\n") : text;
9341
- }
9342
-
9343
9478
  // dist/clients/lsp/edits.js
9344
9479
  var StaleWorkspaceEditContentError = class extends Error {
9345
9480
  };
@@ -9653,7 +9788,11 @@ function mergeWorkspaceTextEditsByPriority(entries) {
9653
9788
  continue;
9654
9789
  for (const [uri, edits] of flattenWorkspaceTextEdits(entry.edit)) {
9655
9790
  const key = pathIndexKey(uri);
9656
- const bucket = merged.get(key) ?? { uri, edits: [] };
9791
+ const bucket = merged.get(key) ?? {
9792
+ uri,
9793
+ edits: [],
9794
+ sourceClientKeys: /* @__PURE__ */ new Set()
9795
+ };
9657
9796
  const kept = bucket.edits;
9658
9797
  for (const edit of edits) {
9659
9798
  inputEditCount += 1;
@@ -9667,15 +9806,25 @@ function mergeWorkspaceTextEditsByPriority(entries) {
9667
9806
  if (exactKey !== void 0)
9668
9807
  seenExact.add(exactKey);
9669
9808
  kept.push(edit);
9809
+ bucket.sourceClientKeys.add(entry.clientKey ?? entry.serverId);
9670
9810
  }
9671
9811
  if (kept.length > 0)
9672
9812
  merged.set(key, bucket);
9673
9813
  }
9674
9814
  }
9675
9815
  const changes = {};
9676
- for (const { uri, edits } of merged.values())
9816
+ const sourceClientKeys = /* @__PURE__ */ new Map();
9817
+ for (const [key, { uri, edits, sourceClientKeys: sources }] of merged) {
9677
9818
  changes[uri] = edits;
9678
- return { edit: { changes }, droppedConflicts, inputEditCount, serverIds };
9819
+ sourceClientKeys.set(key, [...sources]);
9820
+ }
9821
+ return {
9822
+ edit: { changes },
9823
+ droppedConflicts,
9824
+ inputEditCount,
9825
+ serverIds,
9826
+ sourceClientKeys
9827
+ };
9679
9828
  }
9680
9829
  function pathIndexKey(uri) {
9681
9830
  return normalizeEphemeralMapKey(uriToPath(uri));
@@ -9712,6 +9861,64 @@ function plannedDiskPaths(planned) {
9712
9861
  function workspaceEditTextPaths(edit) {
9713
9862
  return planWorkspaceEdit(edit).flatMap((op) => op.kind === "text" ? [uriToDiskPath(op.uri)] : []);
9714
9863
  }
9864
+ var RENAME_MTIME_MARGIN_MS = 2e3;
9865
+ function captureRenameExpectedContent(edit, cwd, requestedAtMs, readTrackedSend, target, sourceClientKeysByPath) {
9866
+ const expected = /* @__PURE__ */ new Map();
9867
+ let targetRealPath;
9868
+ if (target !== void 0) {
9869
+ try {
9870
+ targetRealPath = realpathSync2.native(target.filePath);
9871
+ } catch {
9872
+ targetRealPath = void 0;
9873
+ }
9874
+ }
9875
+ for (const diskPath of workspaceEditTextPaths(edit)) {
9876
+ let realPath;
9877
+ let content;
9878
+ let mtimeMs;
9879
+ try {
9880
+ realPath = realpathSync2.native(diskPath);
9881
+ content = readFileSync8(realPath, "utf-8");
9882
+ mtimeMs = statSync8(realPath).mtimeMs;
9883
+ } catch {
9884
+ continue;
9885
+ }
9886
+ if (target !== void 0 && realPath === targetRealPath) {
9887
+ expected.set(realPath, target.content);
9888
+ continue;
9889
+ }
9890
+ const contributorKeys = sourceClientKeysByPath?.get(normalizeEphemeralMapKey(realPath));
9891
+ const trackedResult = readTrackedSend(diskPath, cwd, contributorKeys);
9892
+ const tracked = trackedResult === void 0 ? [] : Array.isArray(trackedResult) ? trackedResult : [trackedResult];
9893
+ const contentHash2 = hashDiagnosticContent(content);
9894
+ let hasComparableSend = false;
9895
+ const comparableKeys = /* @__PURE__ */ new Set();
9896
+ for (const trackedSend of tracked) {
9897
+ const firstOpenedAfterRequest = (trackedSend.openedAtMs ?? 0) >= requestedAtMs;
9898
+ const quietSinceClientStart = trackedSend.clientStartedAtMs !== void 0 && mtimeMs < trackedSend.clientStartedAtMs - RENAME_MTIME_MARGIN_MS;
9899
+ const sent = firstOpenedAfterRequest && quietSinceClientStart ? void 0 : trackedSend;
9900
+ if (sent !== void 0) {
9901
+ hasComparableSend = true;
9902
+ comparableKeys.add(trackedSend.clientKey);
9903
+ if (sent.hash !== contentHash2 || (sent.changedAtMs ?? requestedAtMs) >= requestedAtMs) {
9904
+ refuseStaleWorkspaceEdit(diskPath, "it changed after the language server computed the rename from it");
9905
+ }
9906
+ } else if (trackedSend.hash !== contentHash2 || trackedSend.openedHash !== trackedSend.hash) {
9907
+ refuseStaleWorkspaceEdit(diskPath, "it changed after the language client first opened it, after the rename was requested");
9908
+ }
9909
+ }
9910
+ const unboundKeys = contributorKeys?.filter((key) => !comparableKeys.has(key)) ?? [];
9911
+ const boundByRecord = hasComparableSend && unboundKeys.length === 0;
9912
+ const noOpenCopy = unboundKeys.length === 0 ? "the language server has no open copy" : `the language client ${unboundKeys.join(", ")} that edits it had no open copy`;
9913
+ if (!boundByRecord && mtimeMs >= requestedAtMs) {
9914
+ refuseStaleWorkspaceEdit(diskPath, `it was written after the rename was requested and ${noOpenCopy}, so it may not have read these bytes`);
9915
+ } else if (!boundByRecord && mtimeMs >= requestedAtMs - RENAME_MTIME_MARGIN_MS) {
9916
+ refuseStaleWorkspaceEdit(diskPath, `it was modified within ${RENAME_MTIME_MARGIN_MS / 1e3} s of the rename request${unboundKeys.length === 0 ? "" : ` and ${noOpenCopy}`}; retry`);
9917
+ }
9918
+ expected.set(realPath, content);
9919
+ }
9920
+ return expected;
9921
+ }
9715
9922
  function planWorkspaceEdit(edit, trackOrigins = false) {
9716
9923
  parseWorkspaceEdit(edit);
9717
9924
  const ops = [];
@@ -9861,7 +10068,7 @@ function summarizeWorkspaceEdit(edit, cwd) {
9861
10068
  }
9862
10069
  async function lstatOrMissing(filePath) {
9863
10070
  try {
9864
- return await fs9.lstat(filePath);
10071
+ return await fs10.lstat(filePath);
9865
10072
  } catch (err) {
9866
10073
  if (err.code === "ENOENT")
9867
10074
  return void 0;
@@ -9873,7 +10080,7 @@ function isSameFsIdentity(a, b) {
9873
10080
  }
9874
10081
  async function bigintLstatOrMissing(filePath) {
9875
10082
  try {
9876
- return await fs9.lstat(filePath, { bigint: true });
10083
+ return await fs10.lstat(filePath, { bigint: true });
9877
10084
  } catch (err) {
9878
10085
  if (err.code === "ENOENT")
9879
10086
  return void 0;
@@ -9907,7 +10114,7 @@ async function resolveExistingAncestor(filePath) {
9907
10114
  const tail = [];
9908
10115
  while (true) {
9909
10116
  try {
9910
- const resolved2 = await fs9.realpath(current);
10117
+ const resolved2 = await fs10.realpath(current);
9911
10118
  return path10.join(resolved2, ...tail.reverse());
9912
10119
  } catch (err) {
9913
10120
  const code = err.code;
@@ -10008,8 +10215,8 @@ async function preflightWorkspaceEdit(planned, cwd, options) {
10008
10215
  const physicalPath = resolveVirtualPath(filePath);
10009
10216
  if (!physicalPath)
10010
10217
  throw new Error(`text edit target does not exist: ${filePath}`);
10011
- const content = await fs9.readFile(physicalPath, "utf-8");
10012
- const expected = options.expectedContent?.get(await fs9.realpath(physicalPath));
10218
+ const content = await fs10.readFile(physicalPath, "utf-8");
10219
+ const expected = options.expectedContent?.get(await fs10.realpath(physicalPath));
10013
10220
  if (expected !== void 0 && expected !== content) {
10014
10221
  refuseStaleWorkspaceEdit(filePath, "the file changed after the edit was computed from it");
10015
10222
  }
@@ -10197,14 +10404,14 @@ async function applyWorkspaceEdit(edit, cwd, options = {}) {
10197
10404
  skipOperation(op);
10198
10405
  continue;
10199
10406
  }
10200
- const content = await fs9.readFile(diskPath, "utf-8");
10407
+ const content = await fs10.readFile(diskPath, "utf-8");
10201
10408
  const updated = applyTextEditsToString(content, edits, "utf-16");
10202
10409
  const changesLineCount = edits.some((edit2) => {
10203
10410
  const removedLines = edit2.range.end.line - edit2.range.start.line;
10204
10411
  const insertedLines = (edit2.newText.match(/\r\n|\r|\n/g) ?? []).length;
10205
10412
  return removedLines !== insertedLines;
10206
10413
  });
10207
- await fs9.writeFile(diskPath, updated, "utf-8");
10414
+ await fs10.writeFile(diskPath, updated, "utf-8");
10208
10415
  const start = Math.min(...edits.map((item) => item.range.start.line + 1));
10209
10416
  const end = Math.max(...edits.map((item) => item.range.end.line + (item.range.end.character === 0 && item.range.end.line > item.range.start.line ? 0 : 1)));
10210
10417
  touchedFiles.add(filePath);
@@ -10223,11 +10430,11 @@ async function applyWorkspaceEdit(edit, cwd, options = {}) {
10223
10430
  } else if (op.kind === "create") {
10224
10431
  const filePath = uriToPath(op.uri);
10225
10432
  const diskPath = uriToDiskPath(op.uri);
10226
- await fs9.mkdir(path10.dirname(diskPath), { recursive: true });
10433
+ await fs10.mkdir(path10.dirname(diskPath), { recursive: true });
10227
10434
  if (op.options?.overwrite)
10228
- await fs9.writeFile(diskPath, "", "utf-8");
10435
+ await fs10.writeFile(diskPath, "", "utf-8");
10229
10436
  else
10230
- await fs9.writeFile(diskPath, "", { flag: "wx" });
10437
+ await fs10.writeFile(diskPath, "", { flag: "wx" });
10231
10438
  resourceChanges.push({ filePath: diskPath, type: FILE_CREATED });
10232
10439
  touchedFiles.add(filePath);
10233
10440
  fileDetails.push({
@@ -10243,10 +10450,10 @@ async function applyWorkspaceEdit(edit, cwd, options = {}) {
10243
10450
  const newPath = uriToPath(op.newUri);
10244
10451
  const oldDisk = uriToDiskPath(op.oldUri);
10245
10452
  const newDisk = uriToDiskPath(op.newUri);
10246
- await fs9.mkdir(path10.dirname(newDisk), { recursive: true });
10453
+ await fs10.mkdir(path10.dirname(newDisk), { recursive: true });
10247
10454
  if (op.options?.overwrite)
10248
- await fs9.rm(newDisk, { recursive: true, force: true });
10249
- await fs9.rename(oldDisk, newDisk);
10455
+ await fs10.rm(newDisk, { recursive: true, force: true });
10456
+ await fs10.rename(oldDisk, newDisk);
10250
10457
  resourceChanges.push({ filePath: oldDisk, type: FILE_DELETED }, { filePath: newDisk, type: FILE_CREATED });
10251
10458
  touchedFiles.add(oldPath);
10252
10459
  touchedFiles.add(newPath);
@@ -10266,7 +10473,7 @@ async function applyWorkspaceEdit(edit, cwd, options = {}) {
10266
10473
  } else {
10267
10474
  const filePath = uriToPath(op.uri);
10268
10475
  const diskPath = uriToDiskPath(op.uri);
10269
- await fs9.rm(diskPath, {
10476
+ await fs10.rm(diskPath, {
10270
10477
  recursive: op.options?.recursive === true,
10271
10478
  force: false
10272
10479
  });
@@ -10504,7 +10711,7 @@ async function attemptTsserverSyncDiagnostics(file, svc) {
10504
10711
  }
10505
10712
 
10506
10713
  // dist/clients/lsp/workspace-diagnostics-cache.js
10507
- import * as fs10 from "node:fs";
10714
+ import * as fs11 from "node:fs";
10508
10715
  import * as path12 from "node:path";
10509
10716
 
10510
10717
  // dist/clients/reverse-deps.js
@@ -10703,7 +10910,7 @@ function loadWorkspaceDiagnosticsCache(cwd) {
10703
10910
  }
10704
10911
  function saveWorkspaceDiagnosticsCache(cwd, cache) {
10705
10912
  const filePath = cachePath(cwd);
10706
- fs10.mkdirSync(path12.dirname(filePath), { recursive: true });
10913
+ fs11.mkdirSync(path12.dirname(filePath), { recursive: true });
10707
10914
  writeFileAtomic(filePath, JSON.stringify(cache, null, 2), {
10708
10915
  bestEffort: false
10709
10916
  });
@@ -10737,7 +10944,7 @@ function classifyWorkspaceDiagnosticsCacheExpiry(entry, now, sessionStartedAt, f
10737
10944
  function isEntryFresh(filePath, entry, getImports) {
10738
10945
  let ownStat;
10739
10946
  try {
10740
- ownStat = fs10.statSync(filePath);
10947
+ ownStat = fs11.statSync(filePath);
10741
10948
  } catch {
10742
10949
  return false;
10743
10950
  }
@@ -10761,7 +10968,7 @@ function isEntryFresh(filePath, entry, getImports) {
10761
10968
  for (const dep of imports) {
10762
10969
  let mtimeMs;
10763
10970
  try {
10764
- mtimeMs = fs10.statSync(dep).mtimeMs;
10971
+ mtimeMs = fs11.statSync(dep).mtimeMs;
10765
10972
  } catch {
10766
10973
  return false;
10767
10974
  }
@@ -11056,7 +11263,8 @@ var CLIENT_CAPABILITIES = {
11056
11263
  fileOperations: {
11057
11264
  dynamicRegistration: false,
11058
11265
  willRename: true,
11059
- didRename: true
11266
+ didRename: true,
11267
+ didCreate: true
11060
11268
  }
11061
11269
  },
11062
11270
  textDocument: {
@@ -11201,8 +11409,8 @@ async function killProcessTree(proc, pid, options = {}) {
11201
11409
  proc.unref?.();
11202
11410
  return;
11203
11411
  }
11204
- await new Promise((resolve8) => {
11205
- killer.once("close", () => resolve8());
11412
+ await new Promise((resolve9) => {
11413
+ killer.once("close", () => resolve9());
11206
11414
  killer.once("error", (err) => {
11207
11415
  logLatency({
11208
11416
  type: "phase",
@@ -11211,7 +11419,7 @@ async function killProcessTree(proc, pid, options = {}) {
11211
11419
  durationMs: 0,
11212
11420
  metadata: { pid, platform: "win32", taskkillError: String(err) }
11213
11421
  });
11214
- resolve8();
11422
+ resolve9();
11215
11423
  });
11216
11424
  });
11217
11425
  } catch (err) {
@@ -11269,18 +11477,18 @@ async function killProcessTree(proc, pid, options = {}) {
11269
11477
  proc.unref?.();
11270
11478
  return;
11271
11479
  }
11272
- const exitedInTime = await new Promise((resolve8) => {
11480
+ const exitedInTime = await new Promise((resolve9) => {
11273
11481
  if (proc.exitCode != null || proc.signalCode != null) {
11274
- resolve8(true);
11482
+ resolve9(true);
11275
11483
  return;
11276
11484
  }
11277
11485
  const onExit = () => {
11278
11486
  clearTimeout(timer);
11279
- resolve8(true);
11487
+ resolve9(true);
11280
11488
  };
11281
11489
  const timer = setTimeout(() => {
11282
11490
  proc.off?.("exit", onExit);
11283
- resolve8(false);
11491
+ resolve9(false);
11284
11492
  }, 1500);
11285
11493
  proc.once?.("exit", onExit);
11286
11494
  });
@@ -11452,8 +11660,13 @@ function rebaselineForRulesRefresh(state4) {
11452
11660
  phase: "lsp_rules_refreshed",
11453
11661
  filePath: state4.root,
11454
11662
  durationMs: 0,
11455
- metadata: { serverId: state4.serverId, rebaselinedPaths: counts.size }
11663
+ metadata: {
11664
+ serverId: state4.serverId,
11665
+ rebaselinedPaths: counts.size,
11666
+ heldEmptyPublishes: state4.heldEmptyPublishes ?? 0
11667
+ }
11456
11668
  });
11669
+ state4.heldEmptyPublishes = 0;
11457
11670
  }
11458
11671
  function publicationCountsForPath(state4, normalizedPath) {
11459
11672
  const lastSent = state4.documentVersions.get(normalizedPath);
@@ -11465,6 +11678,7 @@ function publicationCountsForPath(state4, normalizedPath) {
11465
11678
  function diagnosticsVersionForPath(state4, normalizedPath) {
11466
11679
  return state4.diagnosticsVersionsByPath?.get(normalizedPath) ?? 0;
11467
11680
  }
11681
+ var PENDING_RECEIPT_DROPPED = "pending-receipt-dropped";
11468
11682
  function clearDiagnosticsForPath(state4, normalizedPath) {
11469
11683
  const legacy = state4;
11470
11684
  state4.pushDiagnostics?.delete(normalizedPath);
@@ -11478,6 +11692,7 @@ function clearDiagnosticsForPath(state4, normalizedPath) {
11478
11692
  state4.documentPullDiagnostics?.delete(normalizedPath);
11479
11693
  state4.documentPullDiagnosticTimestamps?.delete(normalizedPath);
11480
11694
  state4.diagnosticDocVersions?.delete(normalizedPath);
11695
+ state4.nonEmptyAnswerPhases?.delete(normalizedPath);
11481
11696
  state4.diagnosticBindings?.delete(normalizedPath);
11482
11697
  state4.diagnosticsVersionsByPath?.delete(normalizedPath);
11483
11698
  for (const key of pullSourceKeysForPath(state4, normalizedPath)) {
@@ -11517,36 +11732,8 @@ function logTypeScriptPullSettle(state4, normalizedPath, durationMs, pullSettleS
11517
11732
  }
11518
11733
  });
11519
11734
  }
11520
- function scanSentContent(content) {
11521
- if (content.indexOf("\r") === -1) {
11522
- let lfNewlineCount2 = 0;
11523
- let start2 = 0;
11524
- for (let i = content.indexOf("\n"); i !== -1; i = content.indexOf("\n", i + 1)) {
11525
- lfNewlineCount2++;
11526
- start2 = i + 1;
11527
- }
11528
- return { lfNewlineCount: lfNewlineCount2, lastLine: { index: lfNewlineCount2, start: start2 } };
11529
- }
11530
- let lfNewlineCount = 0;
11531
- let index = 0;
11532
- let start = 0;
11533
- for (let i = 0; i < content.length; i++) {
11534
- const code = content.charCodeAt(i);
11535
- if (code !== 10 && code !== 13)
11536
- continue;
11537
- if (code === 10) {
11538
- lfNewlineCount++;
11539
- } else if (content.charCodeAt(i + 1) === 10) {
11540
- lfNewlineCount++;
11541
- i++;
11542
- }
11543
- index++;
11544
- start = i + 1;
11545
- }
11546
- return { lfNewlineCount, lastLine: { index, start } };
11547
- }
11548
- function recordSentContent(state4, normalizedPath, version, content, coalescedCount = 0) {
11549
- const scan = scanSentContent(content);
11735
+ function recordSentContent(state4, normalizedPath, version, content, coalescedCount = 0, contentHash2) {
11736
+ const scan = scanDocumentContent(content);
11550
11737
  const previous = state4.documentContentHashes.get(normalizedPath);
11551
11738
  if (previous && previous.version > version) {
11552
11739
  incrementDegradationCount({
@@ -11562,7 +11749,7 @@ function recordSentContent(state4, normalizedPath, version, content, coalescedCo
11562
11749
  state4.incrementalTextBearingPaths?.delete(normalizedPath);
11563
11750
  }
11564
11751
  state4.documentContentHashes.delete(normalizedPath);
11565
- const hash = hashDiagnosticContent(content);
11752
+ const hash = contentHash2 ?? hashDiagnosticContent(content);
11566
11753
  state4.documentContentHashes.set(normalizedPath, {
11567
11754
  version,
11568
11755
  hash,
@@ -11629,7 +11816,7 @@ function buildContentChanges(state4, normalizedPath, content) {
11629
11816
  return [{ text: content }];
11630
11817
  }
11631
11818
  const previousText = previous.text;
11632
- const lastLine = previous.lastLine ?? scanSentContent(previousText).lastLine;
11819
+ const lastLine = previous.lastLine ?? scanDocumentContent(previousText).lastLine;
11633
11820
  const lastLineText = previousText.slice(lastLine.start);
11634
11821
  return [
11635
11822
  {
@@ -11704,6 +11891,128 @@ function resolveConfigurationSection(initialization, section) {
11704
11891
  }
11705
11892
  return cur;
11706
11893
  }
11894
+ var MAX_TRACKED_SERVER_MESSAGES = 8;
11895
+ function isConfigLoadFailureMessage(message) {
11896
+ return /\b(?:fail|failed|fails|failure|unable|could not|error)\b/i.test(message) && /\b(?:download|load|fetch|resolve|read|parse)\b/i.test(message) && /\b(?:config|configuration|rules?|ruleset)\b/i.test(message);
11897
+ }
11898
+ function noteServerShowMessage(state4, params) {
11899
+ const raw = typeof params?.message === "string" ? params.message.trim() : "";
11900
+ if (!raw)
11901
+ return;
11902
+ const text = truncateForLedger(raw.replace(/\s+/g, " "));
11903
+ const type = typeof params?.type === "number" ? params.type : 4;
11904
+ const digest = hashDiagnosticContent(raw).slice(0, 12);
11905
+ const isConfigFailure = type === 1 && isConfigLoadFailureMessage(raw);
11906
+ let retractedPaths = 0;
11907
+ if (isConfigFailure && state4.configLoadFailure === void 0 && isAuxiliary({ role: state4.serverRole })) {
11908
+ state4.configLoadFailure = { message: text, atMs: Date.now() };
11909
+ retractedPaths = retractUnscannedEmptyPublications(state4);
11910
+ }
11911
+ const messages = state4.serverMessages ??= /* @__PURE__ */ new Map();
11912
+ const known = messages.has(digest);
11913
+ const cap = MAX_TRACKED_SERVER_MESSAGES + (isConfigFailure ? 1 : 0);
11914
+ if (!known && messages.size >= cap) {
11915
+ incrementDegradationCount({
11916
+ kind: "lsp-server-message",
11917
+ subject: `${state4.serverId}:showMessage-cap`,
11918
+ reason: `${type}: distinct showMessage texts reached ${MAX_TRACKED_SERVER_MESSAGES}; later ones are counted, not recorded`
11919
+ });
11920
+ return;
11921
+ }
11922
+ messages.set(digest, (messages.get(digest) ?? 0) + 1);
11923
+ emitBounded("lsp_server_message", `${state4.serverId}:message:${digest}`, {
11924
+ filePath: state4.root,
11925
+ durationMs: 0,
11926
+ metadata: {
11927
+ serverId: state4.serverId,
11928
+ messageType: type,
11929
+ message: text,
11930
+ ...isConfigFailure && { configLoadFailure: true },
11931
+ ...retractedPaths > 0 && { retractedPaths }
11932
+ }
11933
+ }, {
11934
+ ledgerKind: isConfigFailure ? "lsp-server-config-load-failed" : "lsp-server-message",
11935
+ reason: text,
11936
+ risingEdgePer: "identity"
11937
+ });
11938
+ }
11939
+ function answerPhase(state4, filePath) {
11940
+ return `${state4.rulesGeneration ?? 0}:${state4.documentVersions.get(filePath) ?? -1}`;
11941
+ }
11942
+ function auxiliaryEmptyIsNotEvidence(state4, filePath, docVersion) {
11943
+ const failure = state4.configLoadFailure;
11944
+ if (failure === void 0) {
11945
+ if (docVersion !== void 0)
11946
+ return false;
11947
+ const phase = answerPhase(state4, filePath);
11948
+ if (state4.nonEmptyAnswerPhases?.get(filePath) !== phase)
11949
+ return false;
11950
+ countPublication(state4, filePath);
11951
+ emitBounded(
11952
+ "lsp_publish_dropped_empty_after_finding",
11953
+ // Keyed per server and path, never per phase: a phase moves with every
11954
+ // edit, so a phase key would add one tally per edit for the session
11955
+ // (#4790 review F2, shape 46). The phase rides as a field.
11956
+ `${state4.serverId}:empty-after-finding:${filePath}`,
11957
+ {
11958
+ filePath,
11959
+ durationMs: 0,
11960
+ metadata: { serverId: state4.serverId, phase }
11961
+ },
11962
+ {
11963
+ ledgerKind: "lsp-auxiliary-empty-after-finding",
11964
+ reason: "empty publish dropped: a finding from the same rules generation and send stands",
11965
+ risingEdgePer: "identity"
11966
+ }
11967
+ );
11968
+ return true;
11969
+ }
11970
+ countPublication(state4, filePath);
11971
+ emitBounded("lsp_publish_dropped_server_config_failed", `${state4.serverId}:dropped:${filePath}`, {
11972
+ filePath,
11973
+ durationMs: 0,
11974
+ metadata: {
11975
+ serverId: state4.serverId,
11976
+ via: "publish",
11977
+ message: failure.message
11978
+ }
11979
+ }, {
11980
+ ledgerKind: "lsp-server-config-load-failed",
11981
+ reason: `empty publish dropped: ${failure.message}`,
11982
+ risingEdgePer: "identity"
11983
+ });
11984
+ return true;
11985
+ }
11986
+ function retractUnscannedEmptyPublications(state4) {
11987
+ let retracted = 0;
11988
+ const emptyStoredPaths = [];
11989
+ for (const [normalizedPath, diags] of state4.pushDiagnostics) {
11990
+ if (diags.length === 0)
11991
+ emptyStoredPaths.push(normalizedPath);
11992
+ }
11993
+ for (const normalizedPath of emptyStoredPaths) {
11994
+ state4.pushDiagnostics.delete(normalizedPath);
11995
+ state4.pushDiagnosticTimestamps.delete(normalizedPath);
11996
+ state4.diagnosticDocVersions.delete(normalizedPath);
11997
+ state4.diagnosticBindings.delete(normalizedPath);
11998
+ state4.diagnosticsVersionsByPath.delete(normalizedPath);
11999
+ retracted += 1;
12000
+ emitBounded("lsp_publish_dropped_server_config_failed", `${state4.serverId}:dropped:${normalizedPath}`, {
12001
+ filePath: normalizedPath,
12002
+ durationMs: 0,
12003
+ metadata: {
12004
+ serverId: state4.serverId,
12005
+ via: "retracted",
12006
+ message: state4.configLoadFailure?.message ?? ""
12007
+ }
12008
+ }, {
12009
+ ledgerKind: "lsp-server-config-load-failed",
12010
+ reason: `stored empty answer retracted: ${state4.configLoadFailure?.message ?? ""}`,
12011
+ risingEdgePer: "identity"
12012
+ });
12013
+ }
12014
+ return retracted;
12015
+ }
11707
12016
  function setupIncomingHandlers(state4, initialization, onDiagnosticsPublished) {
11708
12017
  state4.connection.onNotification("textDocument/publishDiagnostics", (params) => {
11709
12018
  const publishReceivedAt = Date.now();
@@ -11717,8 +12026,11 @@ function setupIncomingHandlers(state4, initialization, onDiagnosticsPublished) {
11717
12026
  countPublication(state4, normalizedPath);
11718
12027
  return;
11719
12028
  }
11720
- onDiagnosticsPublished?.(state4.serverId);
11721
12029
  const newDiags = normalizeLspDiagnostics(params.diagnostics || []);
12030
+ if (newDiags.length === 0 && auxiliaryEmptyIsNotEvidence(state4, normalizedPath, docVersion)) {
12031
+ return;
12032
+ }
12033
+ onDiagnosticsPublished?.(state4.serverId);
11722
12034
  const fence = state4.diagnosticFences.get(normalizedPath);
11723
12035
  if (docVersion === void 0 && fence) {
11724
12036
  fence.dropped += 1;
@@ -11744,7 +12056,8 @@ function setupIncomingHandlers(state4, initialization, onDiagnosticsPublished) {
11744
12056
  logExtension({
11745
12057
  subsystem: "lsp-pub",
11746
12058
  level: "debug",
11747
- message: `server=${state4.serverId} pubVersion=${docVersion} docVersion=${state4.documentVersions?.get(normalizedPath)} diags=${newDiags.length}`
12059
+ message: `server=${state4.serverId} pubVersion=${docVersion} docVersion=${state4.documentVersions?.get(normalizedPath)} diags=${newDiags.length}`,
12060
+ metadata: { path: normalizedPath }
11748
12061
  });
11749
12062
  }
11750
12063
  const strategy = getStrategy(state4.serverId, state4.launchVariant);
@@ -11802,6 +12115,11 @@ function setupIncomingHandlers(state4, initialization, onDiagnosticsPublished) {
11802
12115
  const currentVersion = state4.documentVersions.get(normalizedPath);
11803
12116
  return currentVersion !== void 0 && docVersion < currentVersion;
11804
12117
  };
12118
+ if (strategy.emptyUntilRulesRefreshed && !state4.rulesGeneration && newDiags.length === 0 && !state4.pushDiagnostics.has(normalizedPath) && !state4.pendingDiagnostics.has(normalizedPath)) {
12119
+ state4.heldEmptyPublishes = (state4.heldEmptyPublishes ?? 0) + 1;
12120
+ countPublication(state4, normalizedPath);
12121
+ return;
12122
+ }
11805
12123
  if (strategy.emptyFirstPublish === "indexing" && !state4.emptyFirstPublishHoldSpent && newDiags.length === 0 && !state4.pushDiagnostics.has(normalizedPath) && !state4.pendingDiagnostics.has(normalizedPath)) {
11806
12124
  state4.emptyFirstPublishHoldSpent = true;
11807
12125
  logLatency({
@@ -11814,17 +12132,26 @@ function setupIncomingHandlers(state4, initialization, onDiagnosticsPublished) {
11814
12132
  emptyFirstPublish: strategy.emptyFirstPublish,
11815
12133
  // `pubVersion`, the `[lsp-pub]` trace's own field name for the
11816
12134
  // publish's LSP document version — not a lifecycle identity, and
11817
- // not the retired glossary spelling (AGENTS.md "generation").
12135
+ // not the retired glossary spelling (AGENTS.md "session, turn or generation lifecycle").
11818
12136
  pubVersion: docVersion ?? "push-unversioned"
11819
12137
  }
11820
12138
  });
11821
12139
  return;
11822
12140
  }
12141
+ if (newDiags.length > 0 && isAuxiliary({ role: state4.serverRole })) {
12142
+ (state4.nonEmptyAnswerPhases ??= /* @__PURE__ */ new Map()).set(normalizedPath, answerPhase(state4, normalizedPath));
12143
+ }
11823
12144
  if (strategy.seedFirstPush && !state4.pushDiagnostics.has(normalizedPath)) {
11824
12145
  if (isSupersededPush()) {
11825
12146
  countPublication(state4, normalizedPath);
11826
12147
  return;
11827
12148
  }
12149
+ const olderTimer = state4.pendingDiagnostics.get(normalizedPath);
12150
+ if (olderTimer) {
12151
+ clearTimeout(olderTimer);
12152
+ state4.pendingDiagnostics.delete(normalizedPath);
12153
+ countPublication(state4, normalizedPath);
12154
+ }
11828
12155
  state4.pushDiagnostics.set(normalizedPath, newDiags);
11829
12156
  state4.pushDiagnosticTimestamps.set(normalizedPath, Date.now());
11830
12157
  recordDocVersion();
@@ -11843,6 +12170,11 @@ function setupIncomingHandlers(state4, initialization, onDiagnosticsPublished) {
11843
12170
  state4.pendingDiagnostics.delete(normalizedPath);
11844
12171
  if (isSupersededPush()) {
11845
12172
  countPublication(state4, normalizedPath);
12173
+ state4.diagnosticEmitter.emit(PENDING_RECEIPT_DROPPED, normalizedPath);
12174
+ return;
12175
+ }
12176
+ if (newDiags.length === 0 && auxiliaryEmptyIsNotEvidence(state4, normalizedPath, docVersion)) {
12177
+ state4.diagnosticEmitter.emit(PENDING_RECEIPT_DROPPED, normalizedPath);
11846
12178
  return;
11847
12179
  }
11848
12180
  state4.pushDiagnostics.set(normalizedPath, newDiags);
@@ -11926,7 +12258,14 @@ function setupIncomingHandlers(state4, initialization, onDiagnosticsPublished) {
11926
12258
  });
11927
12259
  state4.connection.onRequest("window/workDoneProgress/create", async () => {
11928
12260
  });
11929
- state4.connection.onNotification("semgrep/rulesRefreshed", () => rebaselineForRulesRefresh(state4));
12261
+ state4.connection.onNotification("window/showMessage", (params) => {
12262
+ noteServerShowMessage(state4, params);
12263
+ });
12264
+ state4.connection.onNotification("semgrep/rulesRefreshed", () => {
12265
+ state4.rulesGeneration = (state4.rulesGeneration ?? 0) + 1;
12266
+ delete state4.configLoadFailure;
12267
+ rebaselineForRulesRefresh(state4);
12268
+ });
11930
12269
  let refreshRepullRunning = false;
11931
12270
  let refreshRepullRerunRequested = false;
11932
12271
  const runRefreshRepullPool = async () => {
@@ -12421,7 +12760,7 @@ async function clientWaitForDiagnostics(state4, filePath, timeoutMs, options = {
12421
12760
  const retryBudgetMs = strategy.pullRetryBudgetMs > 0 ? Math.min(timeoutMs, strategy.pullRetryBudgetMs) : 0;
12422
12761
  const startedAt = Date.now();
12423
12762
  while (outcome.status !== "found" && Date.now() - startedAt < retryBudgetMs) {
12424
- await new Promise((resolve8) => setTimeout(resolve8, PULL_DIAGNOSTICS_RETRY_INTERVAL_MS));
12763
+ await new Promise((resolve9) => setTimeout(resolve9, PULL_DIAGNOSTICS_RETRY_INTERVAL_MS));
12425
12764
  outcome = await clientRequestPullDiagnostics(state4, filePath, Math.max(0, retryBudgetMs - (Date.now() - startedAt)));
12426
12765
  if (outcome.status === "clean")
12427
12766
  sawClean = true;
@@ -12437,11 +12776,23 @@ async function clientWaitForDiagnostics(state4, filePath, timeoutMs, options = {
12437
12776
  return;
12438
12777
  }
12439
12778
  }
12440
- if (hasFreshDiagnostics() && !isVersionStale() && getMergedDiagnosticsForPath(state4, normalizedPath).length > 0) {
12779
+ const laterReceiptPending = () => state4.pendingDiagnostics.has(normalizedPath);
12780
+ const storedAnswerSettles = () => hasFreshDiagnostics() && !isVersionStale() && getMergedDiagnosticsForPath(state4, normalizedPath).length > 0;
12781
+ if (storedAnswerSettles() && !laterReceiptPending()) {
12441
12782
  return;
12442
12783
  }
12443
- return new Promise((resolve8) => {
12784
+ const answerStored = () => hasFreshDiagnostics() && !isVersionStale() && (state4.pushDiagnostics.has(normalizedPath) || state4.documentPullDiagnostics.has(normalizedPath));
12785
+ return new Promise((resolve9) => {
12444
12786
  let debounceTimer;
12787
+ let settleDeferred = storedAnswerSettles();
12788
+ const finish = () => {
12789
+ if (debounceTimer)
12790
+ clearTimeout(debounceTimer);
12791
+ state4.diagnosticEmitter.off("diagnostics", onDiagnostics);
12792
+ state4.diagnosticEmitter.off(PENDING_RECEIPT_DROPPED, onReceiptDropped);
12793
+ clearTimeout(timeout);
12794
+ resolve9();
12795
+ };
12445
12796
  const onDiagnostics = (fp) => {
12446
12797
  if (normalizeMapKey(fp) !== normalizedPath)
12447
12798
  return;
@@ -12454,18 +12805,25 @@ async function clientWaitForDiagnostics(state4, filePath, timeoutMs, options = {
12454
12805
  const timeSincePush = hit ? Date.now() - hit : Infinity;
12455
12806
  const remaining = Math.max(0, strategy.debounceMs - timeSincePush);
12456
12807
  debounceTimer = setTimeout(() => {
12457
- state4.diagnosticEmitter.off("diagnostics", onDiagnostics);
12458
- clearTimeout(timeout);
12459
- resolve8();
12808
+ debounceTimer = void 0;
12809
+ if (laterReceiptPending()) {
12810
+ settleDeferred = true;
12811
+ return;
12812
+ }
12813
+ if (!answerStored())
12814
+ return;
12815
+ finish();
12460
12816
  }, remaining);
12461
12817
  };
12818
+ const onReceiptDropped = (fp) => {
12819
+ if (normalizeMapKey(fp) !== normalizedPath)
12820
+ return;
12821
+ if (settleDeferred && answerStored())
12822
+ finish();
12823
+ };
12462
12824
  state4.diagnosticEmitter.on("diagnostics", onDiagnostics);
12463
- const timeout = setTimeout(() => {
12464
- if (debounceTimer)
12465
- clearTimeout(debounceTimer);
12466
- state4.diagnosticEmitter.off("diagnostics", onDiagnostics);
12467
- resolve8();
12468
- }, timeoutMs);
12825
+ state4.diagnosticEmitter.on(PENDING_RECEIPT_DROPPED, onReceiptDropped);
12826
+ const timeout = setTimeout(finish, timeoutMs);
12469
12827
  });
12470
12828
  }
12471
12829
  function handleNotifyExternalChange(state4, filePath, type) {
@@ -12491,15 +12849,25 @@ function watchedTypeForExisting(state4, normalizedPath, info) {
12491
12849
  }
12492
12850
  return state4.createdAnnounced?.has(normalizedPath) ? FILE_CHANGED : FILE_CREATED;
12493
12851
  }
12494
- function handleAnnounceCreated(state4, entries) {
12852
+ async function handleAnnounceCreated(state4, entries) {
12495
12853
  if (!isClientAlive(state4))
12496
12854
  return;
12855
+ const didCreateUris = [];
12497
12856
  for (const { filePath, stat: info } of entries) {
12498
12857
  const normalizedPath = normalizeMapKey(filePath);
12499
12858
  if (watchedTypeForExisting(state4, normalizedPath, info) !== FILE_CREATED) {
12500
12859
  continue;
12501
12860
  }
12502
- enqueueWatchedChange(state4, normalizedPath, state4.openDocumentUris?.get(normalizedPath) ?? pathToFileURL2(filePath).href, FILE_CREATED);
12861
+ const uri = state4.openDocumentUris?.get(normalizedPath) ?? pathToFileURL2(filePath).href;
12862
+ enqueueWatchedChange(state4, normalizedPath, uri, FILE_CREATED);
12863
+ if (await fileOperationFiltersMatch(state4.fileOperationFilters?.didCreate, uri, uri, filePath, filePath)) {
12864
+ didCreateUris.push(uri);
12865
+ }
12866
+ }
12867
+ if (didCreateUris.length > 0 && isClientAlive(state4)) {
12868
+ await safeSendNotification(state4.connection, "workspace/didCreateFiles", {
12869
+ files: didCreateUris.map((uri) => ({ uri }))
12870
+ });
12503
12871
  }
12504
12872
  state4.watchQueue.flushIfCreated();
12505
12873
  }
@@ -12565,7 +12933,7 @@ function recordDidSaveSendFailed(state4, normalizedPath) {
12565
12933
  metadata: { filePath: normalizedPath }
12566
12934
  });
12567
12935
  }
12568
- async function handleNotifyOpenOnce(state4, filePath, content, languageId, preserveDiagnostics = false, silent = false, coalescedCount = 0, saved = false) {
12936
+ async function handleNotifyOpenOnce(state4, filePath, content, languageId, preserveDiagnostics = false, silent = false, coalescedCount = 0, saved = false, contentHash2) {
12569
12937
  if (!isClientAlive(state4))
12570
12938
  return false;
12571
12939
  const normalizedPath = normalizeMapKey(filePath);
@@ -12589,7 +12957,7 @@ async function handleNotifyOpenOnce(state4, filePath, content, languageId, prese
12589
12957
  return false;
12590
12958
  const reopenSent = await safeSendNotification(state4.connection, "textDocument/didOpen", { textDocument: { uri, languageId, version, text: content } });
12591
12959
  if (reopenSent)
12592
- recordSentContent(state4, normalizedPath, version, content, coalescedCount);
12960
+ recordSentContent(state4, normalizedPath, version, content, coalescedCount, contentHash2);
12593
12961
  state4.openDocuments.add(normalizedPath);
12594
12962
  state4.openDocumentUris?.set(normalizedPath, uri);
12595
12963
  if (saved && reopenSent)
@@ -12601,7 +12969,7 @@ async function handleNotifyOpenOnce(state4, filePath, content, languageId, prese
12601
12969
  contentChanges: buildContentChanges(state4, normalizedPath, content)
12602
12970
  });
12603
12971
  if (changeSent)
12604
- recordSentContent(state4, normalizedPath, version, content, coalescedCount);
12972
+ recordSentContent(state4, normalizedPath, version, content, coalescedCount, contentHash2);
12605
12973
  if (saved && changeSent)
12606
12974
  await sendDidSave(state4, normalizedPath, uri, content);
12607
12975
  return changeSent;
@@ -12618,19 +12986,25 @@ async function handleNotifyOpenOnce(state4, filePath, content, languageId, prese
12618
12986
  if (!silent) {
12619
12987
  let watchedType = FILE_CREATED;
12620
12988
  let onDisk = false;
12989
+ let info;
12621
12990
  try {
12622
- const info = await stat2(filePath);
12991
+ info = await stat2(filePath);
12623
12992
  onDisk = true;
12624
12993
  watchedType = watchedTypeForExisting(state4, normalizedPath, info);
12625
12994
  } catch {
12626
12995
  }
12996
+ if (info && watchedType === FILE_CREATED && await fileOperationFiltersMatch(state4.fileOperationFilters?.didCreate, uri, uri, filePath, filePath)) {
12997
+ await safeSendNotification(state4.connection, "workspace/didCreateFiles", {
12998
+ files: [{ uri }]
12999
+ });
13000
+ }
12627
13001
  enqueueWatchedChange(state4, normalizedPath, uri, watchedType, onDisk);
12628
13002
  }
12629
13003
  if (!isClientAlive(state4))
12630
13004
  return false;
12631
13005
  const openSent = await sendFenced(state4, normalizedPath, uri, "textDocument/didOpen", { textDocument: { uri, languageId, version: 0, text: content } });
12632
13006
  if (openSent)
12633
- recordSentContent(state4, normalizedPath, 0, content, coalescedCount);
13007
+ recordSentContent(state4, normalizedPath, 0, content, coalescedCount, contentHash2);
12634
13008
  state4.pendingOpens.delete(normalizedPath);
12635
13009
  state4.openDocuments.add(normalizedPath);
12636
13010
  state4.closedDocuments?.delete(normalizedPath);
@@ -12656,9 +13030,9 @@ function enqueueDocumentNotify(state4, normalizedPath, run, saved = false, readS
12656
13030
  queue = { running: false, active: void 0 };
12657
13031
  state4.notifyChangeQueues.set(normalizedPath, queue);
12658
13032
  }
12659
- return new Promise((resolve8, reject) => {
13033
+ return new Promise((resolve9, reject) => {
12660
13034
  if (queue.closing && !close) {
12661
- resolve8(false);
13035
+ resolve9(false);
12662
13036
  return;
12663
13037
  }
12664
13038
  const previous = queue?.pending;
@@ -12672,7 +13046,7 @@ function enqueueDocumentNotify(state4, normalizedPath, run, saved = false, readS
12672
13046
  const before = (a, b) => a !== void 0 && b !== void 0 && a < b;
12673
13047
  const stale = previous !== void 0 && (saveOnly || before(readStamp, previous.readStamp) || before(readStamp, lastSent));
12674
13048
  const heldStamp = before(previous?.readStamp, lastSent) ? void 0 : previous?.readStamp;
12675
- waiters.push({ resolve: resolve8, reject, stale });
13049
+ waiters.push({ resolve: resolve9, reject, stale });
12676
13050
  queue.pending = {
12677
13051
  run: stale ? previous.run : run,
12678
13052
  saveOnly: stale ? previous.saveOnly : saveOnly,
@@ -12740,11 +13114,11 @@ function handleNotifySave(state4, filePath, onlyIfOwed = false) {
12740
13114
  const normalizedPath = normalizeMapKey(filePath);
12741
13115
  return enqueueDocumentNotify(state4, normalizedPath, (_count, _saved, debtOnly) => sendDidSaveForHeldDocument(state4, normalizedPath, debtOnly), true, void 0, false, true, onlyIfOwed);
12742
13116
  }
12743
- function handleNotifyOpen(state4, filePath, content, languageId, preserveDiagnostics = false, silent = false, saved = false, readStamp) {
13117
+ function handleNotifyOpen(state4, filePath, content, languageId, preserveDiagnostics = false, silent = false, saved = false, readStamp, contentHash2) {
12744
13118
  const normalizedPath = normalizeMapKey(filePath);
12745
- return enqueueDocumentNotify(state4, normalizedPath, (coalescedCount, queuedSaved) => handleNotifyOpenOnce(state4, filePath, content, languageId, preserveDiagnostics, silent, coalescedCount, queuedSaved), saved, readStamp);
13119
+ return enqueueDocumentNotify(state4, normalizedPath, (coalescedCount, queuedSaved) => handleNotifyOpenOnce(state4, filePath, content, languageId, preserveDiagnostics, silent, coalescedCount, queuedSaved, contentHash2), saved, readStamp);
12746
13120
  }
12747
- async function handleNotifyChangeOnce(state4, filePath, content, normalizedPath, coalescedCount = 0, saved = false) {
13121
+ async function handleNotifyChangeOnce(state4, filePath, content, normalizedPath, coalescedCount = 0, saved = false, contentHash2) {
12748
13122
  if (!isClientAlive(state4))
12749
13123
  return false;
12750
13124
  const uri = state4.openDocumentUris?.get(normalizedPath) ?? pathToFileURL2(filePath).href;
@@ -12763,7 +13137,7 @@ async function handleNotifyChangeOnce(state4, filePath, content, normalizedPath,
12763
13137
  state4.documentOpenedAt.set(normalizedPath, Date.now());
12764
13138
  state4.diagnosticPublicationCounts.set(normalizedPath, 0);
12765
13139
  if (fallbackOpenSent)
12766
- recordSentContent(state4, normalizedPath, 0, content, coalescedCount);
13140
+ recordSentContent(state4, normalizedPath, 0, content, coalescedCount, contentHash2);
12767
13141
  state4.openDocuments.add(normalizedPath);
12768
13142
  state4.closedDocuments?.delete(normalizedPath);
12769
13143
  state4.openDocumentUris?.set(normalizedPath, uri);
@@ -12779,14 +13153,14 @@ async function handleNotifyChangeOnce(state4, filePath, content, normalizedPath,
12779
13153
  contentChanges: buildContentChanges(state4, normalizedPath, content)
12780
13154
  });
12781
13155
  if (changeSent)
12782
- recordSentContent(state4, normalizedPath, version, content, coalescedCount);
13156
+ recordSentContent(state4, normalizedPath, version, content, coalescedCount, contentHash2);
12783
13157
  if (saved && changeSent)
12784
13158
  await sendDidSave(state4, normalizedPath, uri, content);
12785
13159
  return changeSent;
12786
13160
  }
12787
- function handleNotifyChange(state4, filePath, content) {
13161
+ function handleNotifyChange(state4, filePath, content, contentHash2) {
12788
13162
  const normalizedPath = normalizeMapKey(filePath);
12789
- return enqueueDocumentNotify(state4, normalizedPath, (coalescedCount, queuedSaved) => handleNotifyChangeOnce(state4, filePath, content, normalizedPath, coalescedCount, queuedSaved));
13163
+ return enqueueDocumentNotify(state4, normalizedPath, (coalescedCount, queuedSaved) => handleNotifyChangeOnce(state4, filePath, content, normalizedPath, coalescedCount, queuedSaved, contentHash2));
12790
13164
  }
12791
13165
  async function closedAndGone(state4, filePath, normalizedPath) {
12792
13166
  if (!state4.closedDocuments?.has(normalizedPath))
@@ -13145,14 +13519,20 @@ async function runReadOnlyServerCommand(state4, command, args, timeoutMs = PROBE
13145
13519
  reason: `command "${command}" is not advertised by the ${state4.serverId} server`
13146
13520
  };
13147
13521
  }
13522
+ const abandon = new AbortController();
13523
+ const request = safeSendRequest(state4.connection, "workspace/executeCommand", { command, arguments: args ?? [] }, abandon.signal, void 0, true);
13148
13524
  try {
13149
- const result = await withTimeout(safeSendRequest(state4.connection, "workspace/executeCommand", {
13150
- command,
13151
- arguments: args ?? []
13152
- }), timeoutMs);
13525
+ const result = await withTimeout(request, timeoutMs);
13153
13526
  return { executed: true, result };
13154
13527
  } catch (err) {
13155
13528
  if (err instanceof Error && err.message.startsWith("Timeout after")) {
13529
+ abandon.abort();
13530
+ await request;
13531
+ recordDegradationOnce({
13532
+ kind: "lsp-readonly-command-released",
13533
+ subject: state4.serverId,
13534
+ reason: `${command} timed out after ${timeoutMs}ms; the request was cancelled and released locally`
13535
+ });
13156
13536
  return {
13157
13537
  executed: false,
13158
13538
  reason: `workspace/executeCommand timed out after ${timeoutMs}ms`
@@ -13244,7 +13624,7 @@ function hasNotifyInFlightFor(state4, filePath) {
13244
13624
  }
13245
13625
  async function createLSPClient(options) {
13246
13626
  installCrashGuard();
13247
- const { serverId, process: lspProcess, root, sessionCwd, initialization, initializeTimeoutMs = INITIALIZE_TIMEOUT_MS, launchVariant, onDiagnosticsPublished } = options;
13627
+ const { serverId, process: lspProcess, root, sessionCwd, initialization, initializeTimeoutMs = INITIALIZE_TIMEOUT_MS, launchVariant, settingsSection, role, onDiagnosticsPublished } = options;
13248
13628
  void recordLspChild({
13249
13629
  pid: lspProcess.pid,
13250
13630
  serverId,
@@ -13354,8 +13734,12 @@ async function createLSPClient(options) {
13354
13734
  pullRequestSequences: /* @__PURE__ */ new Map(),
13355
13735
  workspacePullResultCache: /* @__PURE__ */ new Map(),
13356
13736
  openDocuments: /* @__PURE__ */ new Set(),
13737
+ // #4764: the declared role, so a config-load failure gates only an
13738
+ // auxiliary scanner's empty publications.
13739
+ ...role !== void 0 && { serverRole: role },
13357
13740
  // #3310: one-shot, per client session.
13358
13741
  emptyFirstPublishHoldSpent: false,
13742
+ rulesGeneration: 0,
13359
13743
  diagnosticFences: /* @__PURE__ */ new Map(),
13360
13744
  closedDocuments: /* @__PURE__ */ new Set(),
13361
13745
  openDocumentUris: /* @__PURE__ */ new Map(),
@@ -13396,7 +13780,8 @@ async function createLSPClient(options) {
13396
13780
  // holds one are refused.
13397
13781
  (uris) => noteWorkspaceFileCreated(state4.serverId, state4.root, uris.map(uriToPath))
13398
13782
  );
13399
- setupIncomingHandlers(state4, initialization, onDiagnosticsPublished);
13783
+ const settings = settingsSection && initialization ? { [settingsSection]: initialization } : initialization;
13784
+ setupIncomingHandlers(state4, settings, onDiagnosticsPublished);
13400
13785
  connection.listen();
13401
13786
  setupConnectionLifecycle(state4, recentStderr);
13402
13787
  let initResult;
@@ -13453,7 +13838,7 @@ async function createLSPClient(options) {
13453
13838
  const fileOperations = isCapabilityRecord(workspace) ? workspace.fileOperations : void 0;
13454
13839
  const malformedFileOperationRegistrations = /* @__PURE__ */ new Set();
13455
13840
  if (isCapabilityRecord(fileOperations)) {
13456
- for (const operation of ["willRename", "didRename"]) {
13841
+ for (const operation of ["didCreate", "willRename", "didRename"]) {
13457
13842
  if (fileOperations[operation] !== void 0 && parseFileOperationFilters(fileOperations[operation]) === void 0) {
13458
13843
  malformedFileOperationRegistrations.add(operation);
13459
13844
  }
@@ -13462,6 +13847,7 @@ async function createLSPClient(options) {
13462
13847
  state4.fileOperationMalformedRegistrations = malformedFileOperationRegistrations;
13463
13848
  if (isCapabilityRecord(fileOperations)) {
13464
13849
  state4.fileOperationFilters = {
13850
+ didCreate: parseFileOperationFilters(fileOperations.didCreate),
13465
13851
  willRename: parseFileOperationFilters(fileOperations.willRename),
13466
13852
  didRename: parseFileOperationFilters(fileOperations.didRename)
13467
13853
  };
@@ -13475,9 +13861,9 @@ async function createLSPClient(options) {
13475
13861
  }
13476
13862
  state4.staticDiagnosticsMode = state4.workspaceDiagnosticsSupport.mode;
13477
13863
  await safeSendNotification(connection, "initialized", {});
13478
- if (initialization) {
13864
+ if (settings) {
13479
13865
  await safeSendNotification(connection, "workspace/didChangeConfiguration", {
13480
- settings: initialization
13866
+ settings
13481
13867
  });
13482
13868
  }
13483
13869
  return {
@@ -13504,11 +13890,11 @@ async function createLSPClient(options) {
13504
13890
  /** #2358: the OS pid of the live server process (see interface doc). */
13505
13891
  getProcessPid: () => lspProcess.pid,
13506
13892
  notify: {
13507
- async open(filePath, content, languageId, preserveDiagnostics, silent, saved, readStamp) {
13508
- return handleNotifyOpen(state4, filePath, content, languageId, preserveDiagnostics, silent, saved, readStamp);
13893
+ async open(filePath, content, languageId, preserveDiagnostics, silent, saved, readStamp, contentHash2) {
13894
+ return handleNotifyOpen(state4, filePath, content, languageId, preserveDiagnostics, silent, saved, readStamp, contentHash2);
13509
13895
  },
13510
- async change(filePath, content) {
13511
- return handleNotifyChange(state4, filePath, content);
13896
+ async change(filePath, content, contentHash2) {
13897
+ return handleNotifyChange(state4, filePath, content, contentHash2);
13512
13898
  },
13513
13899
  save(filePath, onlyIfOwed) {
13514
13900
  return handleNotifySave(state4, filePath, onlyIfOwed);
@@ -13521,12 +13907,21 @@ async function createLSPClient(options) {
13521
13907
  state4.watchQueue.flush();
13522
13908
  },
13523
13909
  announceCreated(entries) {
13524
- handleAnnounceCreated(state4, entries);
13910
+ handleAnnounceCreated(state4, entries).catch((cause) => {
13911
+ incrementDegradationCount({
13912
+ kind: "lsp-sibling-announcement",
13913
+ subject: `${state4.serverId}:workspace/didCreateFiles`,
13914
+ reason: `didCreateFiles failed: ${String(cause)}`
13915
+ });
13916
+ });
13525
13917
  }
13526
13918
  },
13527
13919
  getDiagnostics(filePath) {
13528
13920
  return getMergedDiagnosticsForPath(state4, normalizeMapKey(filePath));
13529
13921
  },
13922
+ getConfigLoadFailure() {
13923
+ return state4.configLoadFailure?.message;
13924
+ },
13530
13925
  getDiagnosticBinding(filePath) {
13531
13926
  return state4.diagnosticBindings.get(normalizeMapKey(filePath));
13532
13927
  },
@@ -13869,17 +14264,28 @@ async function safeSendNotification(connection, method, params) {
13869
14264
  }
13870
14265
  }
13871
14266
  var activeRequestsByConnection = /* @__PURE__ */ new WeakMap();
14267
+ var RELEASED_ON_ABORT = /* @__PURE__ */ Symbol("released-on-abort");
13872
14268
  function isConnectionBusy(connection) {
13873
14269
  return (activeRequestsByConnection.get(connection) ?? 0) > 0;
13874
14270
  }
13875
- async function safeSendRequest(connection, method, params, signal, settlement) {
14271
+ async function safeSendRequest(connection, method, params, signal, settlement, releaseOnAbort = false) {
13876
14272
  if (signal?.aborted)
13877
14273
  return void 0;
13878
14274
  let tokenSource;
13879
14275
  let onAbort;
14276
+ let released;
14277
+ let release;
13880
14278
  if (signal) {
13881
14279
  tokenSource = new import_node.CancellationTokenSource();
13882
- onAbort = () => tokenSource?.cancel();
14280
+ if (releaseOnAbort) {
14281
+ released = new Promise((resolve9) => {
14282
+ release = () => resolve9(RELEASED_ON_ABORT);
14283
+ });
14284
+ }
14285
+ onAbort = () => {
14286
+ tokenSource?.cancel();
14287
+ release?.();
14288
+ };
13883
14289
  signal.addEventListener("abort", onAbort, { once: true });
13884
14290
  }
13885
14291
  const send = () => tokenSource ? connection.sendRequest(method, params, tokenSource.token) : connection.sendRequest(method, params);
@@ -13888,7 +14294,12 @@ async function safeSendRequest(connection, method, params, signal, settlement) {
13888
14294
  const MAX_ATTEMPTS = 2;
13889
14295
  for (let attempt = 1; ; attempt++) {
13890
14296
  try {
13891
- return await send();
14297
+ if (!released)
14298
+ return await send();
14299
+ const reply = await Promise.race([send(), released]);
14300
+ if (reply === RELEASED_ON_ABORT)
14301
+ return void 0;
14302
+ return reply;
13892
14303
  } catch (err) {
13893
14304
  if (isCancellationError(err)) {
13894
14305
  if (settlement)
@@ -14011,6 +14422,7 @@ function detectOperationSupport(initResult) {
14011
14422
  rename: hasProvider("renameProvider"),
14012
14423
  willRenameFiles: isCapabilityRecord(fileOperations) && isFileOperationRegistrationOptions(fileOperations.willRename),
14013
14424
  didRenameFiles: isCapabilityRecord(fileOperations) && isFileOperationRegistrationOptions(fileOperations.didRename),
14425
+ didCreateFiles: isCapabilityRecord(fileOperations) && isFileOperationRegistrationOptions(fileOperations.didCreate),
14014
14426
  implementation: hasProvider("implementationProvider"),
14015
14427
  callHierarchy: hasProvider("callHierarchyProvider")
14016
14428
  };
@@ -14189,6 +14601,16 @@ var ClientRegistry = class {
14189
14601
  inFlight = /* @__PURE__ */ new Map();
14190
14602
  /** Epoch ms of each key's last successful spawn. */
14191
14603
  clientSpawnedAt = /* @__PURE__ */ new Map();
14604
+ /**
14605
+ * Epoch ms each live client's LAUNCH began, before its process read the
14606
+ * tree (#4532 round 5, review F6). The install look compares an install
14607
+ * against this: `clientSpawnedAt` is stamped after the initialize handshake,
14608
+ * so an install that landed while the server was starting read as older
14609
+ * than the client and became the baseline. Kept apart from
14610
+ * `clientSpawnedAt` because the #1127 breaker measures post-init uptime from
14611
+ * that one. Same key and lifetime: written beside it, retired with it.
14612
+ */
14613
+ clientLaunchStartedAt = /* @__PURE__ */ new Map();
14192
14614
  hooks;
14193
14615
  sessionCwd;
14194
14616
  workspaceProbeLogged = /* @__PURE__ */ new Set();
@@ -14417,8 +14839,8 @@ var ClientRegistry = class {
14417
14839
  async withClientSpawnGate(operation) {
14418
14840
  const previous = this.clientSpawnGate;
14419
14841
  let release;
14420
- this.clientSpawnGate = new Promise((resolve8) => {
14421
- release = resolve8;
14842
+ this.clientSpawnGate = new Promise((resolve9) => {
14843
+ release = resolve9;
14422
14844
  });
14423
14845
  await previous;
14424
14846
  try {
@@ -14512,6 +14934,7 @@ var ClientRegistry = class {
14512
14934
  this.hooks.releaseNotifyWrite(key);
14513
14935
  this.clients.delete(key);
14514
14936
  this.clientSpawnedAt.delete(key);
14937
+ this.clientLaunchStartedAt.delete(key);
14515
14938
  this.hooks.forgetReadiness(key);
14516
14939
  this.clientLastUsedAt.delete(key);
14517
14940
  if (this.adoptedClientKeys.delete(key)) {
@@ -14523,8 +14946,14 @@ var ClientRegistry = class {
14523
14946
  this.hooks.forgetNotifyBacklog(key);
14524
14947
  }
14525
14948
  scheduleIdleEviction(key, server) {
14526
- if (server.idleEviction !== "transparent" && !this.adoptedClientKeys.has(key))
14949
+ if (server.idleEviction !== "transparent" && !this.adoptedClientKeys.has(key)) {
14950
+ recordDegradationOnce({
14951
+ kind: "lsp-idle-eviction-declined",
14952
+ subject: server.id,
14953
+ reason: `no idle-eviction timer: declared ${server.idleEviction ?? "unmeasured"}`
14954
+ });
14527
14955
  return;
14956
+ }
14528
14957
  this.clearIdleEvictionTimer(key);
14529
14958
  const lastUsedAt = this.clientLastUsedAt.get(key) ?? Date.now();
14530
14959
  const { root } = parseClientKey(key);
@@ -14594,6 +15023,37 @@ var ClientRegistry = class {
14594
15023
  recordBreaker(key, reason) {
14595
15024
  recordDegradationOnce({ kind: "lsp-breaker", subject: key, reason });
14596
15025
  }
15026
+ /**
15027
+ * #4532: the roots of the live PRIMARY clients, each with the epoch ms its
15028
+ * earliest live client at that root spawned. The out-of-band install look
15029
+ * runs at these roots as well as the session's cwd, so a dependency install
15030
+ * in a LINKED WORKTREE — a root the session cwd is not under — restarts that
15031
+ * worktree's server. Read-only: never spawns and never waits.
15032
+ *
15033
+ * The earliest spawn, not the latest: `restartPrimaryClientsUnder` retires
15034
+ * every primary overlapping a root, so a root whose newer client spawned
15035
+ * after an install must not hide an older one that read the pre-install
15036
+ * tree. The epoch is the client's LAUNCH start (`clientLaunchStartedAt`):
15037
+ * the server reads the tree from its spawn on, not from the end of its
15038
+ * initialize handshake. An absent stamp reports 0, which a first look reads
15039
+ * as "no epoch" and never as "before every install".
15040
+ */
15041
+ livePrimaryClientRoots() {
15042
+ const byRoot = /* @__PURE__ */ new Map();
15043
+ for (const [key, client] of this.clients) {
15044
+ if (!client.isAlive())
15045
+ continue;
15046
+ const { serverId, root } = parseClientKey(key);
15047
+ if (!root)
15048
+ continue;
15049
+ if (isAuxiliary(getServerById(serverId)))
15050
+ continue;
15051
+ const spawnedAt = this.clientLaunchStartedAt.get(key) ?? 0;
15052
+ const prior = byRoot.get(root);
15053
+ byRoot.set(root, prior === void 0 ? spawnedAt : Math.min(prior, spawnedAt));
15054
+ }
15055
+ return [...byRoot].map(([root, spawnedAt]) => ({ root, spawnedAt }));
15056
+ }
14597
15057
  /**
14598
15058
  * #1934 review F1: record what a `spawnClient` call decided, at the point
14599
15059
  * it decides it. Called on EVERY path that returns without a client, so
@@ -14650,6 +15110,15 @@ var ClientRegistry = class {
14650
15110
  const allowInstall = this.shouldAllowInstall(server.id);
14651
15111
  const normalizedRoot = normalizeMapKey(root);
14652
15112
  const key = `${server.id}:${normalizedRoot}`;
15113
+ if (declinesLooseFileRoot(server, root)) {
15114
+ recordDegradationOnce({
15115
+ kind: "lsp-root-declined",
15116
+ subject: key,
15117
+ reason: `LSP root declined for ${server.id}: root at or above $HOME`
15118
+ });
15119
+ this.noteSpawnVerdict(key, "declined");
15120
+ return void 0;
15121
+ }
14653
15122
  const adopted = this.analysisRootModeForFile(filePath) === "adopted";
14654
15123
  if (adopted) {
14655
15124
  const localCommand = server.command ?? server.projectLocalCommand ?? server.availabilityKey;
@@ -14857,6 +15326,15 @@ var ClientRegistry = class {
14857
15326
  this.noteSpawnVerdict(key, "declined");
14858
15327
  return void 0;
14859
15328
  }
15329
+ if (await declinesProjectlessRoot(server, root)) {
15330
+ recordDegradationOnce({
15331
+ kind: "lsp-root-declined",
15332
+ subject: key,
15333
+ reason: `LSP spawn declined for ${server.id}: no project file at or below ${root}`
15334
+ });
15335
+ this.noteSpawnVerdict(key, "declined");
15336
+ return void 0;
15337
+ }
14860
15338
  const isOptionalServer = OPTIONAL_LSP_SERVER_IDS.has(server.id);
14861
15339
  const startedAt = Date.now();
14862
15340
  logSessionStart(`lsp spawn ${server.id}: start root=${root} install=${allowInstall ? "enabled" : "disabled"} file=${filePath}`);
@@ -14909,6 +15387,10 @@ var ClientRegistry = class {
14909
15387
  initialization: mergedInit,
14910
15388
  initializeTimeoutMs: server.initializeTimeoutMs,
14911
15389
  launchVariant: spawned.launchVariant,
15390
+ settingsSection: server.settingsSection,
15391
+ // #4764: the declared role travels with the client, so a failed server
15392
+ // config can gate an auxiliary scanner's empty publications only.
15393
+ role: server.role,
14912
15394
  onDiagnosticsPublished: (serverId) => {
14913
15395
  this.hooks.noteDiagnosticsPublished(serverId);
14914
15396
  }
@@ -14931,6 +15413,7 @@ var ClientRegistry = class {
14931
15413
  this.unavailableLogged.delete(key);
14932
15414
  this.lastSpawnVerdict.delete(key);
14933
15415
  this.clientSpawnedAt.set(key, Date.now());
15416
+ this.clientLaunchStartedAt.set(key, startedAt);
14934
15417
  this.clientLastUsedAt.set(key, Date.now());
14935
15418
  this.scheduleIdleEviction(key, server);
14936
15419
  this.failureCounts.delete(key);
@@ -15178,6 +15661,9 @@ function getBasenameLanguageId(base) {
15178
15661
  return BASENAME_LANGUAGE_PATTERNS.find(({ pattern }) => pattern.test(base))?.languageId;
15179
15662
  }
15180
15663
  function getLanguageId2(filePath) {
15664
+ const declared = resolveFilenameLanguage(filePath);
15665
+ if (declared)
15666
+ return lspLanguageId(declared);
15181
15667
  const ext = path14.extname(filePath).toLowerCase();
15182
15668
  if (ext && LANGUAGE_EXTENSIONS[ext]) {
15183
15669
  return LANGUAGE_EXTENSIONS[ext];
@@ -15210,6 +15696,333 @@ function auxWaitBudgetMs(serverId, isCold, configuredCeilingMs, declaredWaitMs)
15210
15696
  return Math.min(MAX_ADAPTIVE_AUX_GRACE_CEILING_MS, Math.max(declaredWaitMs, observedSpawnMs + ADAPTIVE_AUX_GRACE_MARGIN_MS));
15211
15697
  }
15212
15698
 
15699
+ // dist/clients/lsp/inferred-project.js
15700
+ import * as path16 from "node:path";
15701
+
15702
+ // dist/clients/lsp/environment-gap.js
15703
+ import * as fs12 from "node:fs";
15704
+ import { isBuiltin } from "node:module";
15705
+ import * as path15 from "node:path";
15706
+ var ENVIRONMENT_GAP_MARKER = "no dependency install resolved for this workspace";
15707
+ var ENVIRONMENT_GAP_NOTICE = `[${ENVIRONMENT_GAP_MARKER}; install the project's dependencies (npm ci, pnpm install, \u2026) and the server picks them up on its next restart]`;
15708
+ var TYPESCRIPT_DIAGNOSTIC_SOURCES = /* @__PURE__ */ new Set(["typescript", "ts", "tsserver"]);
15709
+ function isTypeScriptSourcedDiagnostic(d) {
15710
+ return TYPESCRIPT_DIAGNOSTIC_SOURCES.has((d.source ?? "").toLowerCase());
15711
+ }
15712
+ var TYPESCRIPT_SERVER_ID = "typescript";
15713
+ var ENV_NODE_MODULES_WALK_MAX_LEVELS = 32;
15714
+ var NODE_GLOBALS = /* @__PURE__ */ new Set([
15715
+ "process",
15716
+ "Buffer",
15717
+ "require",
15718
+ "module",
15719
+ "exports",
15720
+ "__dirname",
15721
+ "__filename",
15722
+ "global",
15723
+ "setTimeout",
15724
+ "clearTimeout",
15725
+ "setInterval",
15726
+ "clearInterval",
15727
+ "setImmediate",
15728
+ "clearImmediate",
15729
+ "queueMicrotask",
15730
+ "structuredClone",
15731
+ "URL",
15732
+ "URLSearchParams",
15733
+ "TextEncoder",
15734
+ "TextDecoder",
15735
+ "AbortController",
15736
+ "AbortSignal",
15737
+ "fetch",
15738
+ "performance"
15739
+ ]);
15740
+ var MISSING_MODULE = /^Cannot find module '([^']+)'/;
15741
+ var MISSING_NAMESPACE = /^Cannot find namespace '([^']+)'/;
15742
+ var MISSING_NAME = /^Cannot find name '([^']+)'/;
15743
+ var NODE_NAMESPACE = "NodeJS";
15744
+ var ENVIRONMENT_GAP_CODES = /* @__PURE__ */ new Set([2307, 2503, 2304, 2580, 2591]);
15745
+ var DECLARING_FIELDS = [
15746
+ "dependencies",
15747
+ "devDependencies",
15748
+ "peerDependencies",
15749
+ "optionalDependencies"
15750
+ ];
15751
+ function packageNameOf(specifier) {
15752
+ if (specifier.startsWith("@"))
15753
+ return /^@[^/]+\/[^/]+/.exec(specifier)?.[0];
15754
+ return specifier.split("/")[0];
15755
+ }
15756
+ var PACKAGE_NAME = /^(?:@[A-Za-z0-9~-][\w.~-]*\/)?[A-Za-z0-9~-][\w.~-]*$/;
15757
+ function admitPackageName(names, name) {
15758
+ if (PACKAGE_NAME.test(name))
15759
+ names.add(name);
15760
+ }
15761
+ function declaredPackageNames(startDir) {
15762
+ const names = /* @__PURE__ */ new Set();
15763
+ let dir = path15.resolve(startDir);
15764
+ for (let level = 0; level < ENV_NODE_MODULES_WALK_MAX_LEVELS; level++) {
15765
+ try {
15766
+ const manifest = JSON.parse(fs12.readFileSync(path15.join(dir, "package.json"), "utf8"));
15767
+ for (const field of DECLARING_FIELDS) {
15768
+ const declared = manifest[field];
15769
+ if (typeof declared !== "object" || declared === null)
15770
+ continue;
15771
+ if (Array.isArray(declared))
15772
+ continue;
15773
+ for (const name of Object.keys(declared)) {
15774
+ admitPackageName(names, name);
15775
+ if (!name.startsWith("@types/"))
15776
+ continue;
15777
+ const stem = name.slice("@types/".length);
15778
+ admitPackageName(names, stem.includes("__") ? `@${stem.replace("__", "/")}` : stem);
15779
+ }
15780
+ }
15781
+ } catch {
15782
+ }
15783
+ const parent = path15.dirname(dir);
15784
+ if (parent === dir)
15785
+ break;
15786
+ dir = parent;
15787
+ }
15788
+ return names;
15789
+ }
15790
+ function environmentGapKind(diagnostic) {
15791
+ if (diagnostic.severity !== 1)
15792
+ return void 0;
15793
+ if (!isTypeScriptSourcedDiagnostic(diagnostic))
15794
+ return void 0;
15795
+ if (diagnostic.serverId !== void 0 && diagnostic.serverId !== TYPESCRIPT_SERVER_ID)
15796
+ return void 0;
15797
+ const code = Number(diagnostic.code);
15798
+ if (!ENVIRONMENT_GAP_CODES.has(code))
15799
+ return void 0;
15800
+ const message = diagnostic.message.trim();
15801
+ if (code === 2307) {
15802
+ const specifier = MISSING_MODULE.exec(message)?.[1];
15803
+ return specifier === void 0 ? void 0 : { code, specifier };
15804
+ }
15805
+ if (code === 2503) {
15806
+ return MISSING_NAMESPACE.exec(message)?.[1] === NODE_NAMESPACE ? { code } : void 0;
15807
+ }
15808
+ const name = MISSING_NAME.exec(message)?.[1];
15809
+ return name !== void 0 && NODE_GLOBALS.has(name) ? { code } : void 0;
15810
+ }
15811
+ function hasResolvableNodeModules(startDir, stat3 = (candidate) => fs12.statSync(candidate)) {
15812
+ let dir = path15.resolve(startDir);
15813
+ for (let level = 0; level < ENV_NODE_MODULES_WALK_MAX_LEVELS; level++) {
15814
+ try {
15815
+ stat3(path15.join(dir, "node_modules"));
15816
+ return true;
15817
+ } catch (err) {
15818
+ if (err?.code !== "ENOENT") {
15819
+ return true;
15820
+ }
15821
+ }
15822
+ const parent = path15.dirname(dir);
15823
+ if (parent === dir)
15824
+ return false;
15825
+ dir = parent;
15826
+ }
15827
+ return true;
15828
+ }
15829
+ function demoteEnvironmentGapDiagnostics(diagnostics, options) {
15830
+ const candidates = /* @__PURE__ */ new Map();
15831
+ for (const diagnostic of diagnostics) {
15832
+ const kind = environmentGapKind(diagnostic);
15833
+ if (kind !== void 0)
15834
+ candidates.set(diagnostic, kind);
15835
+ }
15836
+ if (candidates.size === 0)
15837
+ return diagnostics;
15838
+ const startDir = options.startDir ?? path15.dirname(options.filePath);
15839
+ if (hasResolvableNodeModules(startDir, options.stat))
15840
+ return diagnostics;
15841
+ let declared;
15842
+ const admitted = /* @__PURE__ */ new Map();
15843
+ for (const [diagnostic, { code, specifier }] of candidates) {
15844
+ if (specifier !== void 0 && !isBuiltin(specifier)) {
15845
+ declared ??= declaredPackageNames(startDir);
15846
+ const name = packageNameOf(specifier);
15847
+ if (name === void 0 || !declared.has(name))
15848
+ continue;
15849
+ }
15850
+ admitted.set(diagnostic, code);
15851
+ }
15852
+ if (admitted.size === 0)
15853
+ return diagnostics;
15854
+ const startedAt = Date.now();
15855
+ const counts = /* @__PURE__ */ new Map();
15856
+ const demoted = diagnostics.map((diagnostic) => {
15857
+ const kind = admitted.get(diagnostic);
15858
+ if (kind === void 0)
15859
+ return diagnostic;
15860
+ counts.set(kind, (counts.get(kind) ?? 0) + 1);
15861
+ return {
15862
+ ...diagnostic,
15863
+ severity: 2,
15864
+ message: `${diagnostic.message} ${ENVIRONMENT_GAP_NOTICE}`
15865
+ };
15866
+ });
15867
+ for (const [code, count] of counts) {
15868
+ incrementDegradationCount({
15869
+ kind: "lsp-environment-gap-demoted",
15870
+ subject: String(code),
15871
+ reason: `TS${code} from a root with no resolvable node_modules: the finding keeps its line and loses blocking authority while the dependencies are absent`,
15872
+ metadata: { code, count, filePath: options.filePath }
15873
+ });
15874
+ }
15875
+ logLatency({
15876
+ type: "phase",
15877
+ phase: "lsp_environment_gap_demote",
15878
+ filePath: options.filePath,
15879
+ durationMs: Date.now() - startedAt,
15880
+ metadata: {
15881
+ demoted: demoted.length - (diagnostics.length - admitted.size),
15882
+ considered: diagnostics.length,
15883
+ codes: [...counts.keys()].sort((a, b) => a - b).join(",")
15884
+ }
15885
+ });
15886
+ return demoted;
15887
+ }
15888
+
15889
+ // dist/clients/lsp/inferred-project.js
15890
+ var INFERRED_PROJECT_MARKER = "not in any tsconfig project \u2014 checked with inferred settings";
15891
+ var TS_PROJECT_EXTENSIONS = /* @__PURE__ */ new Set([
15892
+ ".ts",
15893
+ ".tsx",
15894
+ ".mts",
15895
+ ".cts",
15896
+ ".js",
15897
+ ".jsx",
15898
+ ".mjs",
15899
+ ".cjs"
15900
+ ]);
15901
+ function isTsProjectFile(filePath) {
15902
+ return TS_PROJECT_EXTENSIONS.has(path16.extname(filePath).toLowerCase());
15903
+ }
15904
+ function suggestTsconfigInclude(filePath, cwd) {
15905
+ const relative3 = toProjectRelativePath(filePath, cwd);
15906
+ if (path16.posix.isAbsolute(relative3) || /^[A-Za-z]:/.test(relative3)) {
15907
+ const dir = relative3.slice(0, relative3.lastIndexOf("/"));
15908
+ return dir ? `${dir}/**` : relative3;
15909
+ }
15910
+ const segments = relative3.split("/").filter(Boolean);
15911
+ return segments.length > 1 ? `${segments[0]}/**` : relative3;
15912
+ }
15913
+ function inferredProjectNotice(filePath, cwd) {
15914
+ return `[${INFERRED_PROJECT_MARKER}; add ${suggestTsconfigInclude(filePath, cwd)} to a tsconfig for authoritative checking]`;
15915
+ }
15916
+ function applyInferredProjectDemotion(diagnostics, filePath, cwd) {
15917
+ if (!diagnostics.some(isDemotableDiagnostic))
15918
+ return diagnostics;
15919
+ const notice = inferredProjectNotice(filePath, cwd);
15920
+ return diagnostics.map((d) => isDemotableDiagnostic(d) ? { ...d, severity: 2, message: `${d.message} ${notice}` } : d);
15921
+ }
15922
+ function isDemotableDiagnostic(d) {
15923
+ return d.severity === 1 && isTypeScriptSourcedDiagnostic(d);
15924
+ }
15925
+ function hasInferredProjectCandidates(diagnostics, filePath) {
15926
+ return isTsProjectFile(filePath) && diagnostics.some(isDemotableDiagnostic);
15927
+ }
15928
+ async function demoteInferredProjectDiagnostics(diagnostics, options) {
15929
+ const { filePath, cwd, service } = options;
15930
+ if (!hasInferredProjectCandidates(diagnostics, filePath))
15931
+ return diagnostics;
15932
+ if (options.signal?.aborted)
15933
+ return diagnostics;
15934
+ const fetchIdentity = options.fetchIdentity ?? fetchTsserverProjectIdentity;
15935
+ const cache = options.identityCache;
15936
+ let identity;
15937
+ if (cache?.has(filePath)) {
15938
+ identity = cache.get(filePath);
15939
+ } else if (service === void 0) {
15940
+ return diagnostics;
15941
+ } else {
15942
+ identity = await fetchIdentity(service, filePath);
15943
+ cache?.set(filePath, identity);
15944
+ }
15945
+ if (identity?.projectKind !== "inferred")
15946
+ return diagnostics;
15947
+ return applyInferredProjectDemotion(diagnostics, filePath, cwd);
15948
+ }
15949
+ async function demoteLanguageServerRows(diagnostics, options) {
15950
+ const environmentChecked = demoteEnvironmentGapDiagnostics(diagnostics, {
15951
+ filePath: options.filePath
15952
+ });
15953
+ const membership = {
15954
+ ...options,
15955
+ identityCache: options.identityCache ?? /* @__PURE__ */ new Map()
15956
+ };
15957
+ const rows = await demoteInferredProjectDiagnostics(environmentChecked, membership);
15958
+ return {
15959
+ rows,
15960
+ replayable: async () => environmentChecked === diagnostics ? rows : demoteInferredProjectDiagnostics(diagnostics, membership)
15961
+ };
15962
+ }
15963
+ var INFERRED_PROJECT_PROBE_BUDGET = 300;
15964
+ async function demoteInferredProjectSweepResults(results, cwd, service, signal) {
15965
+ const startedAt = Date.now();
15966
+ const identityCache = /* @__PURE__ */ new Map();
15967
+ const out = [];
15968
+ let changed = false;
15969
+ let demotedFiles = 0;
15970
+ let demotedDiagnostics = 0;
15971
+ let budgetExhausted = false;
15972
+ let aborted = false;
15973
+ for (const result of results) {
15974
+ const raw = result.diagnostics ?? [];
15975
+ const diagnostics = demoteEnvironmentGapDiagnostics(raw, {
15976
+ filePath: result.filePath
15977
+ });
15978
+ const checked = diagnostics === raw ? result : { ...result, diagnostics };
15979
+ if (checked !== result)
15980
+ changed = true;
15981
+ if (signal?.aborted) {
15982
+ aborted = true;
15983
+ out.push(checked);
15984
+ continue;
15985
+ }
15986
+ if (identityCache.size >= INFERRED_PROJECT_PROBE_BUDGET && !identityCache.has(result.filePath)) {
15987
+ budgetExhausted = true;
15988
+ out.push(checked);
15989
+ continue;
15990
+ }
15991
+ const demoted = await demoteInferredProjectDiagnostics(diagnostics, {
15992
+ filePath: result.filePath,
15993
+ cwd,
15994
+ service,
15995
+ identityCache,
15996
+ signal
15997
+ });
15998
+ if (demoted === diagnostics) {
15999
+ out.push(checked);
16000
+ continue;
16001
+ }
16002
+ changed = true;
16003
+ demotedFiles += 1;
16004
+ demotedDiagnostics += demoted.filter((d, i) => d !== diagnostics[i]).length;
16005
+ out.push({ ...result, diagnostics: demoted });
16006
+ }
16007
+ if (demotedFiles > 0 || budgetExhausted || aborted) {
16008
+ logLatency({
16009
+ type: "phase",
16010
+ phase: "lsp_inferred_project_demote",
16011
+ filePath: cwd,
16012
+ durationMs: Date.now() - startedAt,
16013
+ metadata: {
16014
+ filesConsidered: results.length,
16015
+ filesProbed: identityCache.size,
16016
+ demotedFiles,
16017
+ demotedDiagnostics,
16018
+ budgetExhausted,
16019
+ aborted
16020
+ }
16021
+ });
16022
+ }
16023
+ return changed ? out : results;
16024
+ }
16025
+
15213
16026
  // dist/clients/lazy-import.js
15214
16027
  function createLazyImport(load) {
15215
16028
  let cached;
@@ -15227,7 +16040,7 @@ function createLazyImport(load) {
15227
16040
  }
15228
16041
 
15229
16042
  // dist/clients/lsp-lazy.js
15230
- var lazyLsp = createLazyImport(() => import("./chunk-KYUB6QDC.js"));
16043
+ var lazyLsp = createLazyImport(() => import("./chunk-44X7VIKR.js"));
15231
16044
  function warmLspService() {
15232
16045
  return lazyLsp.get();
15233
16046
  }
@@ -15319,8 +16132,8 @@ function destinationUriPreservingSpelling(oldUri, oldFilePath, newFilePath) {
15319
16132
  return canonical.href;
15320
16133
  }
15321
16134
  const canonicalDestination = () => `${original.protocol}//${authority}${canonical.pathname}`;
15322
- const oldParent = path15.resolve(path15.dirname(oldFilePath));
15323
- const newParent = path15.resolve(path15.dirname(newFilePath));
16135
+ const oldParent = path17.resolve(path17.dirname(oldFilePath));
16136
+ const newParent = path17.resolve(path17.dirname(newFilePath));
15324
16137
  if (normalizeMapKey(oldParent) !== normalizeMapKey(newParent)) {
15325
16138
  return canonicalDestination();
15326
16139
  }
@@ -15330,7 +16143,7 @@ function destinationUriPreservingSpelling(oldUri, oldFilePath, newFilePath) {
15330
16143
  let rawName = canonical.pathname.slice(canonical.pathname.lastIndexOf("/") + 1);
15331
16144
  const oldRawName = original.pathname.slice(slash + 1);
15332
16145
  const oldName = decodeURIComponent(oldRawName);
15333
- const expectedOldName = path15.basename(oldFilePath);
16146
+ const expectedOldName = path17.basename(oldFilePath);
15334
16147
  if (oldName.toLowerCase() !== expectedOldName.toLowerCase()) {
15335
16148
  return canonicalDestination();
15336
16149
  }
@@ -15520,7 +16333,7 @@ async function collectWorkspaceDiagnosticFiles(root, maxFiles = getMaxWorkspaceD
15520
16333
  return;
15521
16334
  if (entry.isSymbolicLink())
15522
16335
  continue;
15523
- const full = path15.join(current, entry.name);
16336
+ const full = path17.join(current, entry.name);
15524
16337
  if (entry.isDirectory()) {
15525
16338
  if (isExcludedDirName(entry.name))
15526
16339
  continue;
@@ -16541,8 +17354,8 @@ var LSPService = class _LSPService {
16541
17354
  return { outstandingMs: 0 };
16542
17355
  }
16543
17356
  let resolveSettled;
16544
- const settled = new Promise((resolve8) => {
16545
- resolveSettled = resolve8;
17357
+ const settled = new Promise((resolve9) => {
17358
+ resolveSettled = resolve9;
16546
17359
  });
16547
17360
  const token = {
16548
17361
  startedAt: Date.now(),
@@ -16614,19 +17427,23 @@ var LSPService = class _LSPService {
16614
17427
  * normal, expected answer.
16615
17428
  *
16616
17429
  * SCOPE, stated so the next reader does not assume the room is closed: this
16617
- * covers the BREAKER doors only (cooldown + permanent). `ensureClientForServer`
16618
- * also drops a scanner for a temporarily-unavailable command (the #1496 latch),
16619
- * `optionalDisabled`, a spawn failure, or capacity eviction. Those are the same
16620
- * defect class in the same lane, but they are persistent-absence states rather
16621
- * than a transient blackout, so flagging every touch partial for them is a
16622
- * broader behavior change than #1459 is scoped to make. Tracked separately.
17430
+ * covers the BREAKER doors only (cooldown + permanent), plus the #4760
17431
+ * root-policy decline, which is a PERMANENT policy answer (the resolved
17432
+ * root is at or above `$HOME`) and never retries in this session.
17433
+ * `ensureClientForServer` also drops a scanner for a temporarily-unavailable
17434
+ * command (the #1496 latch), `optionalDisabled`, a spawn failure, or capacity
17435
+ * eviction. Those are the same defect class in the same lane, but they are
17436
+ * persistent-absence states rather than a transient blackout, so flagging
17437
+ * every touch partial for them is a broader behavior change than #1459 is
17438
+ * scoped to make. Tracked separately.
16623
17439
  */
16624
- async brokenSkippedAuxiliaryServerIds(filePath, clientScope, options, spawned) {
17440
+ async skippedAuxiliaryServerIds(filePath, clientScope, options, spawned) {
16625
17441
  if (clientScope === "primary")
16626
- return [];
17442
+ return { brokenSkippedServerIds: [], policySkippedServerIds: [] };
16627
17443
  const enabledAuxiliaries = clientScope === "with-auxiliary" ? new Set(options.auxiliaryServerIds ?? []) : void 0;
16628
17444
  const attached = new Set(spawned.map((entry) => entry.info.id));
16629
- const skipped = [];
17445
+ const brokenSkippedServerIds = [];
17446
+ const policySkippedServerIds = [];
16630
17447
  for (const server of getServersForFileWithConfig(filePath)) {
16631
17448
  if (!isAuxiliary(server))
16632
17449
  continue;
@@ -16636,15 +17453,20 @@ var LSPService = class _LSPService {
16636
17453
  continue;
16637
17454
  if (enabledAuxiliaries && !enabledAuxiliaries.has(server.id))
16638
17455
  continue;
16639
- const key = await this.demonstratedReadyKeyFor(server, filePath);
16640
- if (!key)
17456
+ const root = await this.clientRegistry.resolveServerRoot(server, filePath);
17457
+ if (!root)
17458
+ continue;
17459
+ if (declinesLooseFileRoot(server, root)) {
17460
+ policySkippedServerIds.push(server.id);
16641
17461
  continue;
17462
+ }
17463
+ const key = `${server.id}:${normalizeMapKey(root)}`;
16642
17464
  const brokenUntil = this.state.broken.get(key);
16643
17465
  if (this.clientRegistry.permanentlyBroken.has(key) || typeof brokenUntil === "number" && brokenUntil > Date.now()) {
16644
- skipped.push(server.id);
17466
+ brokenSkippedServerIds.push(server.id);
16645
17467
  }
16646
17468
  }
16647
- return skipped;
17469
+ return { brokenSkippedServerIds, policySkippedServerIds };
16648
17470
  }
16649
17471
  activeClientsForCwd(cwd, priorityServerIds = []) {
16650
17472
  const normalizedCwd = normalizeMapKey(cwd);
@@ -16659,7 +17481,7 @@ var LSPService = class _LSPService {
16659
17481
  const sameOrNested = root === normalizedCwd || root.startsWith(`${normalizedCwd}/`) || normalizedCwd.startsWith(`${root}/`);
16660
17482
  if (!sameOrNested)
16661
17483
  continue;
16662
- entries.push({ serverId, client });
17484
+ entries.push({ clientKey: key, serverId, client });
16663
17485
  }
16664
17486
  return entries.sort((a, b) => (priority.get(a.serverId) ?? Number.MAX_SAFE_INTEGER) - (priority.get(b.serverId) ?? Number.MAX_SAFE_INTEGER));
16665
17487
  }
@@ -16684,15 +17506,18 @@ var LSPService = class _LSPService {
16684
17506
  }
16685
17507
  return [...paths];
16686
17508
  }
16687
- /**
16688
- * #3601: the fingerprint of the content the first live client (the file's
16689
- * own servers first) last sent for `filePath`, and when a send last changed
16690
- * it, or `undefined` when no live client under `cwd` tracks the document.
16691
- * In-memory only: it spawns, opens and stats nothing.
16692
- */
16693
- getTrackedContent(filePath, cwd) {
17509
+ getTrackedContent(filePath, cwd, sourceClientKeys) {
16694
17510
  const priorityServerIds = getServersForFileWithConfig(filePath).map((server) => server.id);
16695
- for (const { client } of this.activeClientsForCwd(cwd, priorityServerIds)) {
17511
+ const clients = this.activeClientsForCwd(cwd, priorityServerIds);
17512
+ if (sourceClientKeys !== void 0) {
17513
+ const sourceSet = new Set(sourceClientKeys);
17514
+ const sends = clients.filter(({ clientKey }) => sourceSet.has(clientKey)).flatMap(({ clientKey, client }) => {
17515
+ const sent = client.getSentContent?.(filePath);
17516
+ return sent === void 0 ? [] : [{ ...sent, clientKey }];
17517
+ });
17518
+ return sends;
17519
+ }
17520
+ for (const { client } of clients) {
16696
17521
  const sent = client.getSentContent?.(filePath);
16697
17522
  if (sent !== void 0)
16698
17523
  return sent;
@@ -16743,8 +17568,8 @@ var LSPService = class _LSPService {
16743
17568
  const effectiveMaxWaitMs = hardCapMs !== void 0 ? serverBaseMs > 0 ? Math.min(serverBaseMs, hardCapMs) : hardCapMs : serverBaseMs;
16744
17569
  let knownSlowResolve;
16745
17570
  const knownSlowSentinel = /* @__PURE__ */ Symbol("lsp-client-wait-known-slow");
16746
- const knownSlow = new Promise((resolve8) => {
16747
- knownSlowResolve = () => resolve8(knownSlowSentinel);
17571
+ const knownSlow = new Promise((resolve9) => {
17572
+ knownSlowResolve = () => resolve9(knownSlowSentinel);
16748
17573
  });
16749
17574
  const noteSpawnInFlight = (serverId) => {
16750
17575
  const knownDurationMs = getSuccessfulLspSpawnDurationMs(serverId);
@@ -16835,8 +17660,8 @@ var LSPService = class _LSPService {
16835
17660
  waitResult = await Promise.race([
16836
17661
  withBudget(),
16837
17662
  knownSlow,
16838
- new Promise((resolve8) => {
16839
- waitTimer = setTimeout(() => resolve8(timeoutSentinel), effectiveMaxWaitMs);
17663
+ new Promise((resolve9) => {
17664
+ waitTimer = setTimeout(() => resolve9(timeoutSentinel), effectiveMaxWaitMs);
16840
17665
  })
16841
17666
  ]);
16842
17667
  } finally {
@@ -17139,6 +17964,19 @@ var LSPService = class _LSPService {
17139
17964
  return 0;
17140
17965
  return (await this.clientRegistry.restartPrimaryClientsUnder(root)).length;
17141
17966
  }
17967
+ /**
17968
+ * #4532: the roots of the live PRIMARY clients, each with the epoch ms its
17969
+ * earliest live client at that root spawned. The `tool_result` install look
17970
+ * runs at each of these roots as well as the session's cwd, so an install in
17971
+ * a LINKED WORKTREE restarts that worktree's server; before this, the look
17972
+ * only ever ran at the session cwd, and a worktree install reached no server
17973
+ * for 14 minutes (issue #4532 gap 7). Read-only: spawns nothing.
17974
+ */
17975
+ livePrimaryClientRoots() {
17976
+ if (this.checkDestroyed())
17977
+ return [];
17978
+ return this.clientRegistry.livePrimaryClientRoots();
17979
+ }
17142
17980
  /**
17143
17981
  * #4320: before a batch serves any cached answer, tell every live client the
17144
17982
  * batch's files that are new to its server and not yet announced to it, and
@@ -17193,6 +18031,21 @@ var LSPService = class _LSPService {
17193
18031
  * (for a server whose replies are `threaded` it proves only liveness).
17194
18032
  * `drained` requires measured single-task ordering and a successful probe;
17195
18033
  * threaded/unmeasured servers and timeouts are undrained.
18034
+ *
18035
+ * #4782: a server may check a document as soon as it reads its change, so a
18036
+ * dependent sent before its rewritten dependency is checked against the
18037
+ * dependency's old bytes, and its re-check after the dependency arrives is
18038
+ * the server's own timer, which can answer after the drain reply. No answer
18039
+ * carries the dependency's version, so no read can tell. A client whose
18040
+ * server `rechecks` unchanged bytes is therefore sent each document again,
18041
+ * after the last one it was sent, before the drain: the server's latest check
18042
+ * of each follows every change of this pass, and the re-send's version bump
18043
+ * lets a versioned server's older answer be dropped as superseded. The
18044
+ * re-send clears the path's stored answer, so the dispatch read waits for
18045
+ * the answer to it; the drain below runs only for `single-task-ordered`
18046
+ * clients, and no row declared `rechecks` is one. Both sends carry the stamp
18047
+ * taken before the read (#3481): a parallel tool's newer read of the same
18048
+ * path, sent in between, makes the queue drop this pass's older bytes.
17196
18049
  */
17197
18050
  async resyncHeldPrimaries(filePaths, drainMs) {
17198
18051
  let sent = 0;
@@ -17207,9 +18060,10 @@ var LSPService = class _LSPService {
17207
18060
  exclude.add(server.id);
17208
18061
  if (servers.every((server) => exclude.has(server.id)))
17209
18062
  continue;
18063
+ const readStamp = performance.now();
17210
18064
  let content;
17211
18065
  try {
17212
- content = await fs11.readFile(filePath, "utf8");
18066
+ content = await fs13.readFile(filePath, "utf8");
17213
18067
  } catch {
17214
18068
  continue;
17215
18069
  }
@@ -17217,7 +18071,8 @@ var LSPService = class _LSPService {
17217
18071
  diagnostics: "none",
17218
18072
  source: "head_move_primary",
17219
18073
  clientScope: "all",
17220
- excludeServerIds: exclude
18074
+ excludeServerIds: exclude,
18075
+ readStamp
17221
18076
  });
17222
18077
  sent += 1;
17223
18078
  for (const server of servers) {
@@ -17226,15 +18081,22 @@ var LSPService = class _LSPService {
17226
18081
  const root = await this.clientRegistry.resolveServerRoot(server, filePath);
17227
18082
  const key = root ? `${server.id}:${normalizeMapKey(root)}` : void 0;
17228
18083
  const client = key ? this.state.clients.get(key) : void 0;
17229
- if (key && client)
18084
+ if (key && client) {
18085
+ const traits = serverTraits(server);
18086
+ const documents = sentTo.get(key)?.documents ?? [];
18087
+ documents.push({ filePath, content, readStamp });
17230
18088
  sentTo.set(key, {
17231
18089
  client,
17232
- ordered: serverTraits(server).replyOrdering === "single-task-ordered"
18090
+ ordered: traits.replyOrdering === "single-task-ordered",
18091
+ rechecks: traits.resendRecheck === "rechecks",
18092
+ documents
17233
18093
  });
18094
+ }
17234
18095
  }
17235
18096
  }
17236
18097
  if (sentTo.size === 0)
17237
18098
  return { sent, drained: true };
18099
+ await Promise.all([...sentTo.values()].flatMap(({ client, rechecks, documents }) => (rechecks ? documents : []).slice(0, -1).map(({ filePath, content, readStamp }) => client.notify.open(filePath, content, getLanguageId2(filePath) ?? "plaintext", void 0, void 0, void 0, readStamp))));
17238
18100
  const answers = await Promise.all([...sentTo.values()].map(async ({ client, ordered }) => {
17239
18101
  if (!ordered)
17240
18102
  return false;
@@ -17265,7 +18127,7 @@ var LSPService = class _LSPService {
17265
18127
  const targets = /* @__PURE__ */ new Set();
17266
18128
  const changed = /* @__PURE__ */ new Map();
17267
18129
  for (const changedPath of changedPaths) {
17268
- const resolved2 = path15.resolve(changedPath);
18130
+ const resolved2 = path17.resolve(changedPath);
17269
18131
  for (const server of getServersForFileWithConfig(resolved2)) {
17270
18132
  const root = await this.clientRegistry.resolveServerRoot(server, resolved2);
17271
18133
  if (!root)
@@ -17666,6 +18528,7 @@ var LSPService = class _LSPService {
17666
18528
  return false;
17667
18529
  return auxPublishedThisContent.has(serverId) || bindingMatchesTouchContent(entry.client.getDiagnosticBinding?.(filePath));
17668
18530
  };
18531
+ const auxPublishedCount = (client, published) => published ? client.getDiagnostics?.(filePath)?.length ?? 0 : 0;
17669
18532
  const notifyWriteTimedOutServerIds = [];
17670
18533
  const notifyDeferredServerIds = [];
17671
18534
  const supersededServerIds = [];
@@ -17710,7 +18573,19 @@ var LSPService = class _LSPService {
17710
18573
  let rejected = false;
17711
18574
  try {
17712
18575
  const writeStartedAt = Date.now();
17713
- const writePromise = entry.client.notify.open(filePath, content, languageId, void 0, silent, options.saved === true, options.readStamp).then((sent) => sent !== false);
18576
+ const writePromise = entry.client.notify.open(
18577
+ filePath,
18578
+ content,
18579
+ languageId,
18580
+ void 0,
18581
+ silent,
18582
+ options.saved === true,
18583
+ options.readStamp,
18584
+ // #2066: the #1095 fingerprint `touchFile` already computed for
18585
+ // these exact bytes (`contentHash` above). Without it the send
18586
+ // walks the document again for the same sha256.
18587
+ contentHash2
18588
+ ).then((sent) => sent !== false);
17714
18589
  if (gated && clientKey) {
17715
18590
  this.noteAuxNotifyIssued(clientKey, entry.client);
17716
18591
  }
@@ -17943,8 +18818,8 @@ var LSPService = class _LSPService {
17943
18818
  let shared = this.firstContactWaits.get(entry.info.id);
17944
18819
  if (!shared) {
17945
18820
  let removeShutdownListener;
17946
- const shutdown = new Promise((resolve8) => {
17947
- const onShutdown = () => resolve8("shutdown");
18821
+ const shutdown = new Promise((resolve9) => {
18822
+ const onShutdown = () => resolve9("shutdown");
17948
18823
  if (this.shutdownController.signal.aborted) {
17949
18824
  onShutdown();
17950
18825
  return;
@@ -18015,22 +18890,24 @@ var LSPService = class _LSPService {
18015
18890
  const outcomes = await Promise.all(auxWaits.map(async (aux) => {
18016
18891
  const { budgetMs } = aux;
18017
18892
  if (aux.demoted) {
18893
+ const demotedPublished = auxiliaryPublicationEvidence({
18894
+ bindingMatchesContent: auxCoversThisContent(aux.serverId),
18895
+ baseline: aux.baseline,
18896
+ currentPathVersion: readPathVersion(aux.client)
18897
+ });
18018
18898
  return {
18019
18899
  serverId: aux.serverId,
18020
18900
  outcome: deferredResyncServerIds.has(aux.serverId) ? "deferred" : "demoted",
18021
- publishedThisContent: auxiliaryPublicationEvidence({
18022
- bindingMatchesContent: auxCoversThisContent(aux.serverId),
18023
- baseline: aux.baseline,
18024
- currentPathVersion: readPathVersion(aux.client)
18025
- }),
18901
+ publishedThisContent: demotedPublished,
18902
+ publishedCount: auxPublishedCount(aux.client, demotedPublished),
18026
18903
  budgetMs,
18027
18904
  elapsedMs: 0,
18028
18905
  elapsedSinceNotifyMs: 0
18029
18906
  };
18030
18907
  }
18031
18908
  let timer;
18032
- const timeout = new Promise((resolve8) => {
18033
- timer = setTimeout(() => resolve8(false), budgetMs);
18909
+ const timeout = new Promise((resolve9) => {
18910
+ timer = setTimeout(() => resolve9(false), budgetMs);
18034
18911
  if (typeof timer === "object" && "unref" in timer) {
18035
18912
  timer.unref?.();
18036
18913
  }
@@ -18066,6 +18943,7 @@ var LSPService = class _LSPService {
18066
18943
  // below is master's line; the stamp axis already decided
18067
18944
  // the outcome above and must not re-admit the row here.
18068
18945
  publishedThisContent: auxCoversThisContent(aux.serverId),
18946
+ publishedCount: auxPublishedCount(aux.client, publishedEvidence || auxCoversThisContent(aux.serverId)),
18069
18947
  budgetMs,
18070
18948
  elapsedMs,
18071
18949
  // #1458 S3: elapsed measured from BEFORE the primary wait
@@ -18127,8 +19005,8 @@ var LSPService = class _LSPService {
18127
19005
  const graceMs = readTsserverSyncGraceMs();
18128
19006
  const primaryClient = spawned[0].client;
18129
19007
  const syncRacer = (async () => {
18130
- await new Promise((resolve8) => {
18131
- const timer = setTimeout(resolve8, graceMs);
19008
+ await new Promise((resolve9) => {
19009
+ const timer = setTimeout(resolve9, graceMs);
18132
19010
  timer.unref?.();
18133
19011
  });
18134
19012
  const publishedAt = primaryClient.getAllDiagnostics?.().get(normalizedPath)?.ts;
@@ -18198,6 +19076,7 @@ var LSPService = class _LSPService {
18198
19076
  // below is master's line; the stamp axis already decided
18199
19077
  // the outcome above and must not re-admit the row here.
18200
19078
  publishedThisContent: auxCoversThisContent(entry.info.id),
19079
+ publishedCount: auxPublishedCount(entry.client, publishedEvidence || auxCoversThisContent(entry.info.id)),
18201
19080
  budgetMs: timeoutFor(entry.client.serverId),
18202
19081
  elapsedMs: waitedMs,
18203
19082
  elapsedSinceNotifyMs: waitedMs
@@ -18404,26 +19283,36 @@ var LSPService = class _LSPService {
18404
19283
  diagnosticsUnansweredServerIds: diagnosticsUnansweredPrimaryServerIds
18405
19284
  });
18406
19285
  const inconclusive = verdict.inconclusive;
18407
- const brokenSkippedServerIds = collected !== void 0 ? await this.brokenSkippedAuxiliaryServerIds(filePath, clientScope, options, spawned) : [];
19286
+ const skippedAuxiliaries = collected !== void 0 ? await this.skippedAuxiliaryServerIds(filePath, clientScope, options, spawned) : { brokenSkippedServerIds: [], policySkippedServerIds: [] };
19287
+ const brokenSkippedServerIds = skippedAuxiliaries.brokenSkippedServerIds;
19288
+ const policySkippedServerIds = skippedAuxiliaries.policySkippedServerIds;
18408
19289
  const auxNoAnswerServerIds = spawned.filter((entry) => isAuxiliary(entry.info) && (diagnosticsUnansweredServerIds.includes(entry.info.id) || notifyWriteTimedOutServerIds.includes(entry.info.id)) && !auxCoveredAtMerge.has(entry.info.id)).map((entry) => entry.info.id);
18409
19290
  const unconfirmedServerIds = [
18410
19291
  .../* @__PURE__ */ new Set([
18411
19292
  ...auxUnconfirmedServerIds ?? [],
18412
19293
  ...auxNoAnswerServerIds,
18413
19294
  ...uncoveredDeferredServerIds,
18414
- ...brokenSkippedServerIds
19295
+ ...brokenSkippedServerIds,
19296
+ ...policySkippedServerIds
18415
19297
  ])
18416
19298
  ].filter((serverId) => !auxCoveredAtMerge.has(serverId));
18417
19299
  const coverageGap = unconfirmedServerIds.length > 0;
18418
- if (brokenSkippedServerIds.length > 0 || uncoveredDeferredServerIds.length > 0 || // #1549: the auxiliary deadline misses that used to surface as a blanket
19300
+ if (brokenSkippedServerIds.length > 0 || policySkippedServerIds.length > 0 || uncoveredDeferredServerIds.length > 0 || // #1549: the auxiliary deadline misses that used to surface as a blanket
18419
19301
  // `inconclusive` need their own row now that the touch reports usable
18420
19302
  // findings — otherwise the fix would remove the only record of the blackout.
18421
19303
  auxNoAnswerServerIds.length > 0) {
19304
+ const configFailureSuffix = (serverId) => {
19305
+ const failure = spawned.find((entry) => entry.info.id === serverId)?.client.getConfigLoadFailure?.();
19306
+ return failure ? ` (server reported: ${failure})` : "";
19307
+ };
18422
19308
  for (const serverId of unconfirmedServerIds) {
18423
19309
  const reasons = [
18424
19310
  brokenSkippedServerIds.includes(serverId) && "breaker skip",
19311
+ policySkippedServerIds.includes(serverId) && "root policy skip",
18425
19312
  uncoveredDeferredServerIds.includes(serverId) && "deferred resync",
18426
- auxNoAnswerServerIds.includes(serverId) && "no diagnostics answer"
19313
+ auxNoAnswerServerIds.includes(serverId) && // #4764: WHY it did not answer, when the server said so itself
19314
+ // (a failed config load reads like a timeout otherwise).
19315
+ `no diagnostics answer${configFailureSuffix(serverId)}`
18427
19316
  ].filter(Boolean);
18428
19317
  incrementDegradationCount({
18429
19318
  kind: "lsp-scanner-coverage-gap",
@@ -18440,6 +19329,9 @@ var LSPService = class _LSPService {
18440
19329
  ...brokenSkippedServerIds.length > 0 && {
18441
19330
  brokenSkippedServerIds
18442
19331
  },
19332
+ ...policySkippedServerIds.length > 0 && {
19333
+ policySkippedServerIds
19334
+ },
18443
19335
  // #1586: the deferrals this touch is actually uncovered for. The
18444
19336
  // gate action keeps its own record in `lsp_notify_resync_deferred`;
18445
19337
  // this row exists to prove a blackout, and a scanner already bound
@@ -18609,6 +19501,7 @@ var LSPService = class _LSPService {
18609
19501
  // named here either. The gate's own action is recorded regardless, in
18610
19502
  // `lsp_notify_resync_deferred`.
18611
19503
  ...brokenSkippedServerIds.length > 0 && { brokenSkippedServerIds },
19504
+ ...policySkippedServerIds.length > 0 && { policySkippedServerIds },
18612
19505
  ...uncoveredDeferredServerIds.length > 0 && {
18613
19506
  deferredResyncServerIds: uncoveredDeferredServerIds
18614
19507
  },
@@ -19366,21 +20259,24 @@ var LSPService = class _LSPService {
19366
20259
  });
19367
20260
  return false;
19368
20261
  });
19369
- const willResults = await Promise.all(willRenameClients.map(async ({ serverId, client }) => {
20262
+ const renameRequestedAtMs = Date.now();
20263
+ const willResults = await Promise.all(willRenameClients.map(async ({ clientKey, serverId, client }) => {
19370
20264
  try {
19371
20265
  return {
20266
+ clientKey,
19372
20267
  serverId,
19373
- edit: await client.willRenameFiles(oldFilePath, newFilePath)
20268
+ edit: await client.willRenameFiles(oldFilePath, newFilePath),
20269
+ failed: false
19374
20270
  };
19375
20271
  } catch (err) {
19376
20272
  willRenameFailures.push({
19377
20273
  serverId,
19378
20274
  error: err instanceof Error ? err.message : String(err)
19379
20275
  });
19380
- return { serverId, edit: null };
20276
+ return { clientKey, serverId, edit: null, failed: true };
19381
20277
  }
19382
20278
  }));
19383
- const successfulWillResults = willResults.filter((result) => !willRenameFailures.some((failure) => failure.serverId === result.serverId));
20279
+ const successfulWillResults = willResults.filter((result) => !result.failed);
19384
20280
  if (willRenameClients.length > 0 && successfulWillResults.length === 0) {
19385
20281
  throw new Error(`workspace/willRenameFiles failed for all active LSP servers: ${willRenameFailures.map((failure) => `${failure.serverId}: ${failure.error}`).join("; ")}`);
19386
20282
  }
@@ -19402,7 +20298,12 @@ var LSPService = class _LSPService {
19402
20298
  applied = await applyWorkspaceEdit(merged.edit, cwd, {
19403
20299
  mutationContext: options.mutationContext,
19404
20300
  observe: false,
19405
- watchedFileSink: this
20301
+ watchedFileSink: this,
20302
+ // #3734: nothing read the old path on this flow, so there is no
20303
+ // target: every text-edited file is bound by its client's send record,
20304
+ // else by its mtime against the instant above (`formal/lsp-rename-edit`,
20305
+ // `Issue3734Bound`).
20306
+ expectedContent: captureRenameExpectedContent(merged.edit, cwd, renameRequestedAtMs, (filePath, atCwd, sourceClientKeys) => sourceClientKeys === void 0 ? this.getTrackedContent(filePath, atCwd) : this.getTrackedContent(filePath, atCwd, sourceClientKeys), void 0, merged.sourceClientKeys)
19406
20307
  });
19407
20308
  } catch (err) {
19408
20309
  if (options.mutationContext) {
@@ -19416,7 +20317,8 @@ var LSPService = class _LSPService {
19416
20317
  }
19417
20318
  throw err;
19418
20319
  }
19419
- const openDocuments = activeClients.filter(({ client }) => client.isDocumentOpen(oldFilePath)).map(({ serverId, client }) => ({
20320
+ const openDocuments = activeClients.filter(({ client }) => client.isDocumentOpen(oldFilePath)).map(({ clientKey, serverId, client }) => ({
20321
+ clientKey,
19420
20322
  serverId,
19421
20323
  client,
19422
20324
  oldUri: client.getDocumentUri(oldFilePath)
@@ -19439,7 +20341,7 @@ var LSPService = class _LSPService {
19439
20341
  status: "failed"
19440
20342
  });
19441
20343
  }
19442
- const content = await fs11.readFile(oldFilePath, "utf-8");
20344
+ const content = await fs13.readFile(oldFilePath, "utf-8");
19443
20345
  const languageId = getLanguageId2(oldFilePath) ?? "plaintext";
19444
20346
  const resyncFailures = [];
19445
20347
  await Promise.all(openDocuments.map(async ({ serverId, client }) => {
@@ -19503,10 +20405,10 @@ var LSPService = class _LSPService {
19503
20405
  }
19504
20406
  throw err;
19505
20407
  }
19506
- const relOld = path15.relative(cwd, oldFilePath).replace(/\\/g, "/") || path15.basename(oldFilePath);
19507
- const relNew = path15.relative(cwd, newFilePath).replace(/\\/g, "/") || path15.basename(newFilePath);
20408
+ const relOld = path17.relative(cwd, oldFilePath).replace(/\\/g, "/") || path17.basename(oldFilePath);
20409
+ const relNew = path17.relative(cwd, newFilePath).replace(/\\/g, "/") || path17.basename(newFilePath);
19508
20410
  const renameDescription = `Renamed ${relOld} \u2192 ${relNew}`;
19509
- await Promise.all(activeClients.map(async ({ serverId, client }) => {
20411
+ await Promise.all(activeClients.map(async ({ clientKey, serverId, client }) => {
19510
20412
  if (client.getOperationSupport().didRenameFiles !== true) {
19511
20413
  recordDegradationOnce({
19512
20414
  kind: "lsp-capability-skip",
@@ -19515,7 +20417,7 @@ var LSPService = class _LSPService {
19515
20417
  });
19516
20418
  return;
19517
20419
  }
19518
- const opened = openDocuments.find((entry) => entry.serverId === serverId);
20420
+ const opened = openDocuments.find((entry) => entry.clientKey === clientKey);
19519
20421
  const result = await runRenameNotify(() => opened?.oldUri ? client.didRenameFiles(oldFilePath, newFilePath, opened.oldUri, destinationUriPreservingSpelling(opened.oldUri, oldFilePath, newFilePath)) : client.didRenameFiles(oldFilePath, newFilePath), RENAME_NOTIFY_TIMEOUT_MS);
19520
20422
  if (!result.ok) {
19521
20423
  didRenameFailures.push({
@@ -19819,12 +20721,12 @@ var LSPService = class _LSPService {
19819
20721
  ms: timeoutMs,
19820
20722
  onTimeout: "undefined"
19821
20723
  }),
19822
- new Promise((resolve8) => {
20724
+ new Promise((resolve9) => {
19823
20725
  if (options.signal.aborted) {
19824
- resolve8();
20726
+ resolve9();
19825
20727
  return;
19826
20728
  }
19827
- options.signal.addEventListener("abort", () => resolve8(), {
20729
+ options.signal.addEventListener("abort", () => resolve9(), {
19828
20730
  once: true
19829
20731
  });
19830
20732
  })
@@ -19853,10 +20755,10 @@ var LSPService = class _LSPService {
19853
20755
  if (failedServerIds.length > 0 && !options.signal?.aborted) {
19854
20756
  const backoffMs = warmupRetryBackoffMs();
19855
20757
  if (backoffMs > 0) {
19856
- await new Promise((resolve8) => {
19857
- const timer = setTimeout(resolve8, backoffMs);
20758
+ await new Promise((resolve9) => {
20759
+ const timer = setTimeout(resolve9, backoffMs);
19858
20760
  timer.unref?.();
19859
- options.signal?.addEventListener("abort", () => resolve8(), {
20761
+ options.signal?.addEventListener("abort", () => resolve9(), {
19860
20762
  once: true
19861
20763
  });
19862
20764
  });
@@ -19890,7 +20792,7 @@ var LSPService = class _LSPService {
19890
20792
  }
19891
20793
  async runWorkspaceDiagnosticsSwept(cwd, options = {}) {
19892
20794
  const startedAt = Date.now();
19893
- const root = path15.resolve(cwd);
20795
+ const root = path17.resolve(cwd);
19894
20796
  const { signal } = options;
19895
20797
  void this.sweepDocumentDrift().catch(() => {
19896
20798
  });
@@ -19926,7 +20828,7 @@ var LSPService = class _LSPService {
19926
20828
  await Promise.all(openImports.slice(0, SCOPED_DEPENDENCY_TOUCH_MAX).map(async (dependency) => {
19927
20829
  let content;
19928
20830
  try {
19929
- content = await fs11.readFile(dependency, "utf8");
20831
+ content = await fs13.readFile(dependency, "utf8");
19930
20832
  } catch {
19931
20833
  return;
19932
20834
  }
@@ -20044,12 +20946,12 @@ var LSPService = class _LSPService {
20044
20946
  })(), { ms: perFileMs, onTimeout: "undefined" });
20045
20947
  await (signal ? Promise.race([
20046
20948
  preOpenAttempt,
20047
- new Promise((resolve8) => {
20949
+ new Promise((resolve9) => {
20048
20950
  if (signal.aborted) {
20049
- resolve8();
20951
+ resolve9();
20050
20952
  return;
20051
20953
  }
20052
- signal.addEventListener("abort", () => resolve8(), {
20954
+ signal.addEventListener("abort", () => resolve9(), {
20053
20955
  once: true
20054
20956
  });
20055
20957
  })
@@ -20083,7 +20985,20 @@ var LSPService = class _LSPService {
20083
20985
  await this.ensureWarmForSweep(filePath, { signal });
20084
20986
  }
20085
20987
  const touchResult = attached?.available ? {
20086
- diags: attached.response.diagnostics,
20988
+ // #4645: the incumbent's membership answer, applied on receipt
20989
+ // through the owner's rule. This sweep records its rows into
20990
+ // the workspace cache, and an attached process has no live
20991
+ // tsserver to re-ask on a replay, so the verdict stays in the
20992
+ // rows: the form the batch cache stores (`replayable()`). The
20993
+ // environment rule still runs at render, against the install
20994
+ // state of that render.
20995
+ diags: attached.response.projectIdentity === void 0 ? attached.response.diagnostics : await demoteInferredProjectDiagnostics(attached.response.diagnostics, {
20996
+ filePath,
20997
+ cwd,
20998
+ identityCache: /* @__PURE__ */ new Map([
20999
+ [filePath, attached.response.projectIdentity]
21000
+ ])
21001
+ }),
20087
21002
  // #1470: the incumbent's coverage gap crosses the socket as an
20088
21003
  // explicit DTO field, so carry it onto the wrapper the sweep
20089
21004
  // reads. Dropping it here would let a partially covered
@@ -20707,9 +21622,8 @@ export {
20707
21622
  drainPendingAuxCapEvictedCount,
20708
21623
  recordNapiFallbackCoverage,
20709
21624
  resetPendingAuxiliaryCoverage,
20710
- resetOpaqueMutationState,
20711
- createFileTime,
20712
21625
  clearAllSessions,
21626
+ PartialApplyRecordStore,
20713
21627
  getActiveSessionId,
20714
21628
  beginScope,
20715
21629
  retireScope,
@@ -20717,6 +21631,7 @@ export {
20717
21631
  scopeCell,
20718
21632
  lineContentHash,
20719
21633
  ReadGuard,
21634
+ resetOpaqueMutationState,
20720
21635
  resetObservedMutationNet,
20721
21636
  logBusEvent,
20722
21637
  recordStaleBusFailure,
@@ -20745,6 +21660,7 @@ export {
20745
21660
  hasAnyDispositionMarks,
20746
21661
  hasStrictDispositionMarks,
20747
21662
  getDisposition,
21663
+ resetDeferredDispositions,
20748
21664
  applyDispositions,
20749
21665
  applyWeakDispositions,
20750
21666
  applyDispositionsMultiFile,
@@ -20766,16 +21682,16 @@ export {
20766
21682
  getFileDiagnosticSummaries,
20767
21683
  getSuppressedDiagnostics,
20768
21684
  countRetainedSuppressedRows,
20769
- refuseStaleWorkspaceEdit,
20770
- workspaceEditTextPaths,
21685
+ captureRenameExpectedContent,
20771
21686
  summarizeWorkspaceEdit,
20772
21687
  applyWorkspaceEdit,
20773
- fetchTsserverProjectIdentity,
20774
21688
  attemptTsserverSyncDiagnostics,
20775
21689
  rankFilesByReverseDependencyCentrality,
20776
21690
  buildReverseDependencyIndexFromGraph,
20777
21691
  buildProbeScopeKey,
20778
21692
  createWorkspaceDiagnosticsCacheContext,
21693
+ demoteLanguageServerRows,
21694
+ demoteInferredProjectSweepResults,
20779
21695
  createLazyImport,
20780
21696
  loadLspService,
20781
21697
  tryWarmAttachedDiagnostics,