pi-lens 4.4.4 → 4.4.6

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 (191) hide show
  1. package/CHANGELOG.md +477 -0
  2. package/README.md +45 -3
  3. package/config/biome/core.jsonc +3 -3
  4. package/config/dependency-cruiser-eager-allowlist.json +1 -0
  5. package/dist/{chunk-UBOQLVT2.js → chunk-2DDDCJDL.js} +4 -4
  6. package/dist/{chunk-RKKOYPRA.js → chunk-2DMLM3ZO.js} +13 -15
  7. package/dist/chunk-2F47TQOA.js +73 -0
  8. package/dist/{chunk-O4NWQT6I.js → chunk-2PHMIAKO.js} +4 -4
  9. package/dist/{chunk-DGUKIYSI.js → chunk-2RLWJO5K.js} +8 -10
  10. package/dist/{chunk-S67KYG37.js → chunk-2X4VLOCC.js} +2 -2
  11. package/dist/{chunk-TIQ2PKDW.js → chunk-3MYEA7QD.js} +4 -4
  12. package/dist/{chunk-3DA2JDOL.js → chunk-3WEPUD2V.js} +551 -203
  13. package/dist/{chunk-AMERCH6V.js → chunk-4AVZ3TG7.js} +15 -16
  14. package/dist/{chunk-IYNJ6YPZ.js → chunk-4PCQCU47.js} +4 -4
  15. package/dist/chunk-4WX4CTUE.js +57 -0
  16. package/dist/{chunk-P63GXC37.js → chunk-5APMQ2IJ.js} +31 -4
  17. package/dist/{chunk-ZIVJBOO3.js → chunk-5CV5ITZF.js} +2 -2
  18. package/dist/{chunk-6DLWKFEX.js → chunk-5ZR3APIM.js} +41 -42
  19. package/dist/{chunk-XTBDCR27.js → chunk-63RIVFQI.js} +4 -4
  20. package/dist/{chunk-GSLNCYGG.js → chunk-75SY4F24.js} +13 -14
  21. package/dist/{chunk-U44DJXQP.js → chunk-7RQXA5GG.js} +15 -18
  22. package/dist/chunk-A3YNG5KP.js +45 -0
  23. package/dist/{chunk-5OFV52AM.js → chunk-AE37FEGH.js} +1 -1
  24. package/dist/{chunk-BWD5EPKO.js → chunk-AMXIUN2R.js} +4 -6
  25. package/dist/{chunk-3KAZU3VR.js → chunk-ARD426WI.js} +2 -2
  26. package/dist/{chunk-BW5KFIQC.js → chunk-AWQWXSW4.js} +1 -0
  27. package/dist/{chunk-YH5MVY2U.js → chunk-BHUWL2Y3.js} +7 -7
  28. package/dist/{chunk-CT4MN5IU.js → chunk-BI5LAQ3Y.js} +353 -359
  29. package/dist/{chunk-KAPJINKN.js → chunk-BM5GS6ZH.js} +2 -2
  30. package/dist/{chunk-TLX72JTG.js → chunk-BWYQUPOS.js} +1 -1
  31. package/dist/chunk-CFRQMBGP.js +49 -0
  32. package/dist/{chunk-RMLC67LF.js → chunk-CJYKEW2L.js} +2 -30
  33. package/dist/chunk-CKEQFGLT.js +32 -0
  34. package/dist/{chunk-IWDLU6K3.js → chunk-DC4CFXM5.js} +4 -6
  35. package/dist/{chunk-ZVUL7QYY.js → chunk-DMSLNKF7.js} +29 -32
  36. package/dist/{chunk-KN35K52N.js → chunk-DQXSPYRI.js} +3 -3
  37. package/dist/{chunk-HYGZEMX6.js → chunk-EVDGNG4F.js} +11 -5
  38. package/dist/{chunk-SRYEJNES.js → chunk-F5Z6URKM.js} +2 -2
  39. package/dist/{chunk-UMS2MFPZ.js → chunk-F6X3YJWD.js} +2 -3
  40. package/dist/{chunk-XYURS6EN.js → chunk-FA5LDARD.js} +15 -17
  41. package/dist/{chunk-24AKHFGP.js → chunk-FFL3A2VP.js} +6 -6
  42. package/dist/chunk-FJIVKLPH.js +31 -0
  43. package/dist/chunk-G2B7F6ZU.js +88 -0
  44. package/dist/{chunk-US7ECLD7.js → chunk-GAACZY6R.js} +131 -41
  45. package/dist/{chunk-MZGQNL3Y.js → chunk-GMTFDAOK.js} +12 -13
  46. package/dist/{chunk-VOOAPROD.js → chunk-GNSIWBAT.js} +3 -3
  47. package/dist/chunk-GTAI2J6U.js +27 -0
  48. package/dist/{chunk-RVK72CZX.js → chunk-GZE7WOI4.js} +1362 -459
  49. package/dist/{chunk-IUE7SSKV.js → chunk-H7HTEQUZ.js} +13 -7
  50. package/dist/{chunk-EUXZEFTV.js → chunk-HK6JVFZC.js} +3 -3
  51. package/dist/chunk-IPDG45G5.js +26 -0
  52. package/dist/{chunk-5HSRT26B.js → chunk-J6JP25XU.js} +16 -15
  53. package/dist/{chunk-HWCCCQNX.js → chunk-JL6CXUMW.js} +13 -6
  54. package/dist/{chunk-EBC36LNN.js → chunk-K2YGBXOA.js} +17 -17
  55. package/dist/{chunk-WMYE35PX.js → chunk-KLQVC3XC.js} +7 -5
  56. package/dist/{chunk-ATKJFDQN.js → chunk-KSR7RGQY.js} +12 -14
  57. package/dist/{chunk-POMLXPMY.js → chunk-KXF5R4UN.js} +1 -1
  58. package/dist/{chunk-LLJNQKQW.js → chunk-LEJOJDXL.js} +20 -13
  59. package/dist/{chunk-JUKMK5Y4.js → chunk-MA77RSFN.js} +10 -11
  60. package/dist/{chunk-GAQ7OQG6.js → chunk-MKVZQUEG.js} +85 -96
  61. package/dist/{chunk-2EECBNC5.js → chunk-MN7MHUXQ.js} +75 -0
  62. package/dist/{chunk-DEL2U6CM.js → chunk-MT6BVNFW.js} +16 -14
  63. package/dist/chunk-NDMCVUYK.js +507 -0
  64. package/dist/{chunk-HRNHZA3N.js → chunk-NIU2IPC5.js} +12 -16
  65. package/dist/{chunk-AGSS7277.js → chunk-NNKXDXXS.js} +7 -24
  66. package/dist/{chunk-V35JG4JB.js → chunk-OJLTLYHB.js} +152 -334
  67. package/dist/{chunk-J6MPGQTS.js → chunk-OLAWH5UQ.js} +81 -15
  68. package/dist/{chunk-T57LYLZT.js → chunk-OOU2WZZE.js} +1 -1
  69. package/dist/{chunk-CYRKQRPM.js → chunk-OSTKYB55.js} +2 -4
  70. package/dist/chunk-P4QNXS6I.js +27 -0
  71. package/dist/chunk-PKES3ISE.js +297 -0
  72. package/dist/{chunk-ROYSX2S5.js → chunk-PO45POGF.js} +2 -2
  73. package/dist/{chunk-T7FEBKXN.js → chunk-PPIBVH4R.js} +7 -9
  74. package/dist/{chunk-3RKP3FMS.js → chunk-PQJFG24Z.js} +295 -23
  75. package/dist/{chunk-KUA4OJ5Y.js → chunk-Q3UZHW6N.js} +846 -350
  76. package/dist/{chunk-N5FLEO7W.js → chunk-Q4EMRFNA.js} +37 -37
  77. package/dist/{chunk-5IUSNGOC.js → chunk-Q4FCYCRE.js} +28 -21
  78. package/dist/chunk-Q6D6VMI4.js +22 -0
  79. package/dist/{chunk-UZ2XCLYS.js → chunk-QGSTQH4D.js} +8 -8
  80. package/dist/{chunk-DUO2TU77.js → chunk-RZOXUSPC.js} +10 -4
  81. package/dist/{chunk-JMYYOTQG.js → chunk-S26LC76R.js} +13 -1
  82. package/dist/{chunk-GMX5OS7B.js → chunk-S67UJDGQ.js} +11 -12
  83. package/dist/chunk-SCIUNBPF.js +44 -0
  84. package/dist/{chunk-RKBXZN3A.js → chunk-SJJYRZB4.js} +2 -2
  85. package/dist/chunk-SXGD4ANG.js +25 -0
  86. package/dist/{chunk-YCWYO6TQ.js → chunk-T7FTXGS3.js} +48 -45
  87. package/dist/{chunk-FM4RDMKT.js → chunk-TIQJPRDD.js} +115 -61
  88. package/dist/{chunk-XHJBS436.js → chunk-TIYGSODX.js} +25 -25
  89. package/dist/{chunk-S2HEXIWI.js → chunk-U2SDMG7C.js} +10 -6
  90. package/dist/{chunk-2KXTHF3M.js → chunk-U6OC3QEM.js} +253 -33
  91. package/dist/{chunk-AWSCPCN2.js → chunk-UCGQT677.js} +19 -19
  92. package/dist/chunk-UHGF5UT5.js +32 -0
  93. package/dist/{chunk-JW3YWBVB.js → chunk-UN4TEBWN.js} +17 -19
  94. package/dist/{chunk-ZHH37KZL.js → chunk-V3APN3DY.js} +17 -17
  95. package/dist/{chunk-ED36RF6Y.js → chunk-V63BC55Q.js} +1 -1
  96. package/dist/{chunk-XBJVAEEO.js → chunk-VG5JS5SW.js} +3 -2
  97. package/dist/{chunk-W66O5E25.js → chunk-VPBIMOAQ.js} +13 -15
  98. package/dist/chunk-VQH24FIP.js +37 -0
  99. package/dist/{chunk-YNE3RP52.js → chunk-VSFLRN5Y.js} +8 -1
  100. package/dist/{chunk-7D6L4MTX.js → chunk-W2V54OCL.js} +3 -3
  101. package/dist/{chunk-2FN63LPV.js → chunk-W5LGKNET.js} +13 -14
  102. package/dist/{chunk-IQWN5JCP.js → chunk-W5R5SABV.js} +13 -14
  103. package/dist/{chunk-R3T7CLQ2.js → chunk-WIZWZR4C.js} +41 -41
  104. package/dist/{chunk-TOY6QKOH.js → chunk-WQOIR3QY.js} +17 -17
  105. package/dist/{chunk-Y6GZHWSJ.js → chunk-XAIT2YGS.js} +6 -6
  106. package/dist/chunk-XCUHKYCQ.js +23 -0
  107. package/dist/{chunk-GSM5UU7A.js → chunk-XQCSWV2G.js} +44 -35
  108. package/dist/{chunk-OHKJ7PQF.js → chunk-YBSONGSZ.js} +43 -39
  109. package/dist/{chunk-GXFV6MYU.js → chunk-YISME6ON.js} +72 -39
  110. package/dist/chunk-YRD4ISED.js +30 -0
  111. package/dist/{chunk-SD4I7ZO4.js → chunk-YSBHPOY6.js} +43 -53
  112. package/dist/{chunk-QBFBRV2B.js → chunk-Z2XAOKHK.js} +4 -2
  113. package/dist/{chunk-5VSF4UUQ.js → chunk-Z7IGUAXL.js} +34 -39
  114. package/dist/{chunk-MPNJLASA.js → chunk-ZKXQKGWZ.js} +10 -13
  115. package/dist/{chunk-J64T55EI.js → chunk-ZQ6NZZTB.js} +75 -9
  116. package/dist/chunk-ZUUI3ZSA.js +38 -0
  117. package/dist/{chunk-7HXE67BN.js → chunk-ZYNI26MI.js} +2 -2
  118. package/dist/index.js +32674 -27567
  119. package/dist/mcp/analyze-cli.js +11 -12
  120. package/dist/mcp/cli.js +46 -45
  121. package/dist/mcp/server.js +1210 -574
  122. package/dist/mcp/worker.js +65 -65
  123. package/dist/probes/installer.js +21 -23
  124. package/docs/adr/0010-trace-validation-session-lifecycle.md +390 -0
  125. package/docs/adr/README.md +1 -0
  126. package/docs/agent-tools.md +28 -7
  127. package/docs/ast-grep_rules_catalog.md +5 -3
  128. package/docs/configuration.md +12 -1
  129. package/docs/defect-shapes.md +738 -0
  130. package/docs/engineering-principles.md +12 -0
  131. package/docs/environment-variables.md +20 -0
  132. package/docs/features.md +16 -1
  133. package/docs/globalconfig.md +37 -8
  134. package/docs/invariants/caches-stores.md +30 -0
  135. package/docs/invariants/dispatch-runners.md +164 -0
  136. package/docs/invariants/git-guard-host.md +53 -0
  137. package/docs/invariants/language-config.md +31 -0
  138. package/docs/invariants/lsp-trust-exec.md +286 -0
  139. package/docs/invariants/paths-os.md +59 -0
  140. package/docs/invariants/session-telemetry.md +74 -0
  141. package/docs/lsp-capability-matrix.md +105 -12
  142. package/docs/lsp-idle-eviction.md +37 -18
  143. package/docs/pi-lens-fixer.md +24 -2
  144. package/docs/pi-lens-investigator.md +14 -0
  145. package/docs/pi-lens-merge-policy.md +32 -17
  146. package/docs/pi-lens-monitor.md +66 -10
  147. package/docs/pi-lens-orchestration.md +41 -0
  148. package/docs/pi-lens-release.md +20 -0
  149. package/docs/pi-lens-retro.md +5 -4
  150. package/docs/pi-lens-reviewer.md +54 -7
  151. package/docs/pi-lens-subagent.md +10 -3
  152. package/docs/release-qa-baseline.md +19 -7
  153. package/docs/servercapabilities.md +47 -47
  154. package/docs/settings.md +9 -5
  155. package/docs/subagent-compat.md +1 -1
  156. package/docs/usage.md +1 -0
  157. package/package.json +8 -5
  158. package/rules/ast-grep-rules/rule-tests/no-return-value-in-generator-test.yml +17 -0
  159. package/rules/ast-grep-rules/rule-tests/no-sql-in-code-execute-js-test.yml +86 -0
  160. package/rules/ast-grep-rules/rule-tests/no-sql-in-code-execute-test.yml +86 -0
  161. package/rules/ast-grep-rules/rule-tests/unchecked-numeric-parse-python-test.yml +15 -0
  162. package/rules/ast-grep-rules/rules/no-return-value-in-generator.yml +9 -4
  163. package/rules/ast-grep-rules/rules/no-sql-in-code-execute-js.yml +119 -0
  164. package/rules/ast-grep-rules/rules/no-sql-in-code-execute.yml +119 -0
  165. package/rules/ast-grep-rules/rules/unchecked-numeric-parse-python.yml +13 -2
  166. package/rules/rule-catalog.json +25 -1
  167. package/scripts/analyze-pi-lens-logs.mjs +15 -5
  168. package/scripts/lib/is-main-module.mjs +27 -0
  169. package/scripts/lib/scratch-home-env.mjs +21 -0
  170. package/scripts/rpc-load-check.mjs +4 -6
  171. package/scripts/warm-loader-cache.mjs +2 -5
  172. package/dist/chunk-3PTHXJXR.js +0 -28
  173. package/dist/chunk-3QED2P4V.js +0 -31
  174. package/dist/chunk-5WRPDP2A.js +0 -47
  175. package/dist/chunk-ABBOA7UD.js +0 -157
  176. package/dist/chunk-CUHSHSB6.js +0 -273
  177. package/dist/chunk-GL5LUMZE.js +0 -51
  178. package/dist/chunk-HAD7QRQI.js +0 -30
  179. package/dist/chunk-JORED7EX.js +0 -44
  180. package/dist/chunk-KYUB6QDC.js +0 -72
  181. package/dist/chunk-LZSEQW6A.js +0 -57
  182. package/dist/chunk-M2IFVFWU.js +0 -79
  183. package/dist/chunk-M2UD3LPU.js +0 -88
  184. package/dist/chunk-MBKQHGA7.js +0 -39
  185. package/dist/chunk-R7YOCSNV.js +0 -23
  186. package/dist/chunk-SKAMFC7A.js +0 -28
  187. package/dist/chunk-SYE6T2EB.js +0 -28
  188. package/dist/chunk-TRETHTQO.js +0 -26
  189. package/dist/chunk-UA7ZXYDR.js +0 -184
  190. package/dist/chunk-XTFDJI3T.js +0 -24
  191. package/dist/chunk-Z3CCVDUB.js +0 -76
@@ -7,13 +7,15 @@ import {
7
7
  normalizeMessage,
8
8
  sanitizeCorrelationId,
9
9
  stableFindingId
10
- } from "./chunk-IWDLU6K3.js";
10
+ } from "./chunk-DC4CFXM5.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-3WEPUD2V.js";
40
42
  import {
41
43
  findLocalOpengrepConfig
42
- } from "./chunk-HWCCCQNX.js";
44
+ } from "./chunk-JL6CXUMW.js";
43
45
  import {
44
46
  emitBounded
45
- } from "./chunk-CUHSHSB6.js";
47
+ } from "./chunk-NDMCVUYK.js";
46
48
  import {
47
49
  loadProjectSnapshot,
48
50
  readJsonCache
49
- } from "./chunk-T7FEBKXN.js";
51
+ } from "./chunk-PPIBVH4R.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-F5Z6URKM.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-OJLTLYHB.js";
72
73
  import {
73
74
  js_yaml_default
74
- } from "./chunk-FM4RDMKT.js";
75
+ } from "./chunk-TIQJPRDD.js";
76
+ import {
77
+ EXTENSION_TO_LSP_ID,
78
+ lspLanguageId,
79
+ resolveFilenameLanguage
80
+ } from "./chunk-YISME6ON.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-CJYKEW2L.js";
84
89
  import {
85
90
  diagnosticsIpcPathForCwd,
86
91
  requestWarmCodeActions,
87
92
  requestWarmDiagnostics
88
- } from "./chunk-KAPJINKN.js";
93
+ } from "./chunk-BM5GS6ZH.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-NNKXDXXS.js";
95
99
  import {
96
100
  findLocalZizmorConfig,
97
101
  logSessionStart
98
- } from "./chunk-GAQ7OQG6.js";
102
+ } from "./chunk-MKVZQUEG.js";
99
103
  import {
100
104
  findLocalBinUpwards,
101
105
  isProjectLocalBinPath
102
- } from "./chunk-5VSF4UUQ.js";
106
+ } from "./chunk-Z7IGUAXL.js";
103
107
  import {
104
108
  getLspCapableKinds
105
- } from "./chunk-HRNHZA3N.js";
109
+ } from "./chunk-NIU2IPC5.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-Q3UZHW6N.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-RZOXUSPC.js";
131
135
  import {
136
+ PathKeyedMap,
132
137
  detectFileRole
133
- } from "./chunk-J6MPGQTS.js";
138
+ } from "./chunk-OLAWH5UQ.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-MN7MHUXQ.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-ZQ6NZZTB.js";
148
152
  import {
149
153
  logExtension
150
- } from "./chunk-POMLXPMY.js";
154
+ } from "./chunk-KXF5R4UN.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-Z2XAOKHK.js";
156
163
  import {
157
164
  createNdjsonLogger,
158
165
  getGlobalPiLensLogDir,
@@ -160,27 +167,26 @@ import {
160
167
  getProcessSingleton,
161
168
  isTestMode,
162
169
  nextModuleEvaluationOrdinal
163
- } from "./chunk-YNE3RP52.js";
170
+ } from "./chunk-VSFLRN5Y.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,
178
+ kernelPathIdentityAsync,
173
179
  minimatch,
174
180
  normalizeEphemeralMapKey,
175
181
  normalizeFilePath,
176
182
  normalizeMapKey,
177
183
  pathsEqual,
178
- realpathOrResolve,
184
+ realpathOrResolveAsync,
179
185
  toPosix,
180
186
  toProjectRelativePath,
181
187
  uriToDiskPath,
182
188
  uriToPath
183
- } from "./chunk-3RKP3FMS.js";
189
+ } from "./chunk-PQJFG24Z.js";
184
190
  import {
185
191
  __commonJS,
186
192
  __require,
@@ -3600,9 +3606,9 @@ var require_main = __commonJS({
3600
3606
  exports.createMessageConnection = createMessageConnection2;
3601
3607
  var ril_1 = __importDefault(require_ril());
3602
3608
  ril_1.default.install();
3603
- var path16 = __importStar(__require("path"));
3609
+ var path18 = __importStar(__require("path"));
3604
3610
  var os2 = __importStar(__require("os"));
3605
- var fs12 = __importStar(__require("fs"));
3611
+ var fs14 = __importStar(__require("fs"));
3606
3612
  var crypto_1 = __require("crypto");
3607
3613
  var net_1 = __require("net");
3608
3614
  var api_1 = require_api();
@@ -3743,7 +3749,7 @@ var require_main = __commonJS({
3743
3749
  }
3744
3750
  let randomLength = 32;
3745
3751
  const fixedLength = "/lsp-.sock".length;
3746
- const tmpDir = fs12.realpathSync(XDG_RUNTIME_DIR ?? os2.tmpdir());
3752
+ const tmpDir = fs14.realpathSync(XDG_RUNTIME_DIR ?? os2.tmpdir());
3747
3753
  const limit = safeIpcPathLengths.get(process.platform);
3748
3754
  if (limit !== void 0) {
3749
3755
  randomLength = Math.min(limit - tmpDir.length - fixedLength, randomLength);
@@ -3752,7 +3758,7 @@ var require_main = __commonJS({
3752
3758
  throw new Error(`Unable to generate a random pipe name with ${randomLength} characters.`);
3753
3759
  }
3754
3760
  const randomSuffix = (0, crypto_1.randomBytes)(Math.floor(randomLength / 2)).toString("hex");
3755
- return path16.join(tmpDir, `lsp-${randomSuffix}.sock`);
3761
+ return path18.join(tmpDir, `lsp-${randomSuffix}.sock`);
3756
3762
  }
3757
3763
  function createClientPipeTransport(pipeName, encoding = "utf-8") {
3758
3764
  let connectResolve;
@@ -3850,8 +3856,8 @@ var CASCADE_DIAGNOSTICS_TTL_MS = 24e4;
3850
3856
 
3851
3857
  // dist/clients/lsp/index.js
3852
3858
  import * as nodeFs2 from "node:fs";
3853
- import fs11 from "node:fs/promises";
3854
- import path15 from "node:path";
3859
+ import fs13 from "node:fs/promises";
3860
+ import path17 from "node:path";
3855
3861
  import { pathToFileURL as pathToFileURL3, URL as URL3 } from "node:url";
3856
3862
 
3857
3863
  // dist/clients/lsp/workspace-diagnostics-session.js
@@ -3948,7 +3954,7 @@ async function importTargetsToAnnounce(cwd, importers, onScope) {
3948
3954
  reason: `resolved the imports of ${CREATED_IMPORT_SCAN_MAX_FILES} of ${importers.length} files in one diagnostics call`
3949
3955
  });
3950
3956
  }
3951
- const { extractForwardImports } = await import("./chunk-JORED7EX.js");
3957
+ const { extractForwardImports } = await import("./chunk-A3YNG5KP.js");
3952
3958
  const targets = /* @__PURE__ */ new Set();
3953
3959
  const reexports = /* @__PURE__ */ new Map();
3954
3960
  let resolved2 = 0;
@@ -4284,7 +4290,6 @@ function isNosemgrepSuppressed(d, content) {
4284
4290
  const startLine = d.range?.start?.line;
4285
4291
  if (startLine == null)
4286
4292
  return false;
4287
- const lines = content.split("\n");
4288
4293
  const ruleId = String(d.code ?? "");
4289
4294
  const checkLine = (text, standaloneOnly) => {
4290
4295
  if (!text)
@@ -4296,14 +4301,14 @@ function isNosemgrepSuppressed(d, content) {
4296
4301
  return true;
4297
4302
  return m[1].split(",").map((s) => s.trim()).filter(Boolean).includes(ruleId);
4298
4303
  };
4299
- return checkLine(lines[startLine], false) || checkLine(lines[startLine - 1], true);
4304
+ return checkLine(lineTextAt(content, startLine), false) || checkLine(lineTextAt(content, startLine - 1), true);
4300
4305
  }
4301
4306
  var ZIZMOR_IGNORE_RE = /#\s*zizmor:\s*ignore\[([^\]]+)\]/i;
4302
4307
  function isZizmorIgnoreSuppressed(d, content) {
4303
4308
  const startLine = d.range?.start?.line;
4304
4309
  if (startLine == null)
4305
4310
  return false;
4306
- const line = content.split("\n")[startLine];
4311
+ const line = lineTextAt(content, startLine);
4307
4312
  if (!line)
4308
4313
  return false;
4309
4314
  const match = ZIZMOR_IGNORE_RE.exec(line);
@@ -5069,8 +5074,6 @@ function resetPendingAuxiliaryCoverage() {
5069
5074
  import * as path7 from "node:path";
5070
5075
 
5071
5076
  // dist/clients/file-mutation-queue.js
5072
- import { realpath } from "node:fs/promises";
5073
- import { resolve as resolve2 } from "node:path";
5074
5077
  var loadHostSdk;
5075
5078
  var hostQueue;
5076
5079
  var hostSessionManager;
@@ -5106,13 +5109,10 @@ function withHostFileMutationQueue(filePath, fn) {
5106
5109
  const loader = loadHostSdk;
5107
5110
  if (!loader)
5108
5111
  return fn();
5109
- return resolveHostQueue(loader).then((queue) => queue ? queue(resolve2(filePath), fn) : fn());
5112
+ return resolveHostQueue(loader).then((queue) => queue ? realpathOrResolveAsync(filePath).then((key) => queue(key, fn)) : fn());
5110
5113
  }
5111
5114
  async function withHostFileMutationQueues(filePaths, fn) {
5112
- const keys = await Promise.all(filePaths.map((filePath) => {
5113
- const resolvedPath = resolve2(filePath);
5114
- return realpath(resolvedPath).catch(() => resolvedPath);
5115
- }));
5115
+ const keys = await Promise.all(filePaths.map((filePath) => realpathOrResolveAsync(filePath)));
5116
5116
  return [...new Set(keys)].sort(compareOrdinal).reduceRight((inner, key) => () => withHostFileMutationQueue(key, inner), fn)();
5117
5117
  }
5118
5118
 
@@ -5123,88 +5123,58 @@ var FIX_RUN_HASH_BYTE_BUDGET = 64 * 1024 * 1024;
5123
5123
  // dist/clients/observed-mutation.js
5124
5124
  import * as path5 from "node:path";
5125
5125
 
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
- });
5126
+ // dist/clients/host-edit-normalize.js
5127
+ var HOST_SMART_SINGLE_QUOTES = [8216, 8217, 8218, 8219];
5128
+ var HOST_SMART_DOUBLE_QUOTES = [8220, 8221, 8222, 8223];
5129
+ var HOST_UNICODE_DASHES = [
5130
+ 8208,
5131
+ 8209,
5132
+ 8210,
5133
+ 8211,
5134
+ 8212,
5135
+ 8213,
5136
+ 8722
5137
+ ];
5138
+ var HOST_SPECIAL_SPACES = [
5139
+ 160,
5140
+ 8194,
5141
+ 8195,
5142
+ 8196,
5143
+ 8197,
5144
+ 8198,
5145
+ 8199,
5146
+ 8200,
5147
+ 8201,
5148
+ 8202,
5149
+ 8239,
5150
+ 8287,
5151
+ 12288
5152
+ ];
5153
+ var HOST_BOM_CODE_POINT = 65279;
5154
+ var charClass = (codePoints) => new RegExp(`[${String.fromCharCode(...codePoints)}]`, "g");
5155
+ var SMART_SINGLE_QUOTES_RE = charClass(HOST_SMART_SINGLE_QUOTES);
5156
+ var SMART_DOUBLE_QUOTES_RE = charClass(HOST_SMART_DOUBLE_QUOTES);
5157
+ var UNICODE_DASHES_RE = charClass(HOST_UNICODE_DASHES);
5158
+ var SPECIAL_SPACES_RE = charClass(HOST_SPECIAL_SPACES);
5159
+ var BOM = String.fromCharCode(HOST_BOM_CODE_POINT);
5160
+ function detectLineEnding(content) {
5161
+ const crlfIdx = content.indexOf("\r\n");
5162
+ const lfIdx = content.indexOf("\n");
5163
+ if (lfIdx === -1)
5164
+ return "\n";
5165
+ if (crlfIdx === -1)
5166
+ return "\n";
5167
+ return crlfIdx < lfIdx ? "\r\n" : "\n";
5182
5168
  }
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;
5169
+ function normalizeToLF(text) {
5170
+ return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
5192
5171
  }
5193
- var gitRepoMemo = /* @__PURE__ */ new Map();
5194
- function resetOpaqueMutationState() {
5195
- getOpaqueBaselineStore().takeAllForTest();
5196
- gitRepoMemo.clear();
5197
- gitToplevelMemo.clear();
5198
- headRecords.clear();
5199
- headLooks.clear();
5172
+ function restoreLineEndings(text, ending) {
5173
+ return ending === "\r\n" ? text.replace(/\n/g, "\r\n") : text;
5200
5174
  }
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
5175
 
5206
- // dist/clients/read-guard.js
5207
- import { constants as bufferConstants } from "node:buffer";
5176
+ // dist/clients/partial-edit-apply.js
5177
+ import { createHash as createHash3 } from "node:crypto";
5208
5178
  import * as fs4 from "node:fs";
5209
5179
 
5210
5180
  // dist/clients/file-time.js
@@ -5345,6 +5315,75 @@ function clearAllSessions() {
5345
5315
  globalState.locks.clear();
5346
5316
  }
5347
5317
 
5318
+ // dist/clients/partial-edit-apply.js
5319
+ var MAX_APPLIED_RECORDS_PER_FILE = 8;
5320
+ var MAX_APPLIED_RECORD_FILES = 64;
5321
+ function editPairDigest(oldText, newText) {
5322
+ return createHash3("sha256").update(JSON.stringify([oldText, newText ?? ""]), "utf8").digest("hex");
5323
+ }
5324
+ var PartialApplyRecordStore = class {
5325
+ // Bounded on the PathKeyedMap itself (#2442): the file axis used to
5326
+ // hand-roll `keys().next().value` here, which also evicted an unrelated
5327
+ // file when a path ALREADY in the map was re-recorded at capacity.
5328
+ files = new PathKeyedMap(normalizeMapKey, MAX_APPLIED_RECORD_FILES);
5329
+ find(filePath, oldText, newText) {
5330
+ if (!oldText)
5331
+ return void 0;
5332
+ const pairDigest = editPairDigest(oldText, newText);
5333
+ const records = this.files.get(filePath) ?? [];
5334
+ return records.find((r) => r.pairDigest === pairDigest);
5335
+ }
5336
+ record(filePath, oldText, newText, contentHash2) {
5337
+ if (!oldText)
5338
+ return;
5339
+ const pairDigest = editPairDigest(oldText, newText);
5340
+ const records = this.files.get(filePath) ?? [];
5341
+ const existing = records.findIndex((r) => r.pairDigest === pairDigest);
5342
+ if (existing >= 0)
5343
+ records.splice(existing, 1);
5344
+ const entry = {
5345
+ pairDigest,
5346
+ contentHash: contentHash2 ?? hashFile(filePath),
5347
+ appliedAtMs: Date.now()
5348
+ };
5349
+ if (records.length >= MAX_APPLIED_RECORDS_PER_FILE)
5350
+ records.shift();
5351
+ records.push(entry);
5352
+ this.files.set(filePath, records);
5353
+ }
5354
+ /**
5355
+ * Stamps the post-afterWrite file hash onto an existing record so a later
5356
+ * identical retry against the formatter-rewritten file is still recognized as
5357
+ * already-applied (#2402). No-op when the pair was never recorded.
5358
+ */
5359
+ noteAfterWriteHash(filePath, oldText, newText, afterWriteContentHash) {
5360
+ if (!oldText)
5361
+ return;
5362
+ const pairDigest = editPairDigest(oldText, newText);
5363
+ const record2 = this.files.get(filePath)?.find((r) => r.pairDigest === pairDigest);
5364
+ if (record2)
5365
+ record2.afterWriteContentHash = afterWriteContentHash;
5366
+ }
5367
+ clear() {
5368
+ this.files.clear();
5369
+ }
5370
+ get fileCount() {
5371
+ return this.files.size;
5372
+ }
5373
+ };
5374
+ var fileLock = createFileTime("partial-edit-apply");
5375
+ function hashFile(filePath) {
5376
+ try {
5377
+ return createHash3("sha256").update(fs4.readFileSync(filePath)).digest("hex");
5378
+ } catch {
5379
+ return void 0;
5380
+ }
5381
+ }
5382
+
5383
+ // dist/clients/read-guard.js
5384
+ import { constants as bufferConstants } from "node:buffer";
5385
+ import * as fs5 from "node:fs";
5386
+
5348
5387
  // dist/clients/eval-timestamp.js
5349
5388
  import { performance as performance2 } from "node:perf_hooks";
5350
5389
  var PI_LENS_EVAL_STARTED_MS = performance2.now();
@@ -5526,7 +5565,7 @@ var READ_BINDING_MAX_BYTES = 4 * 1024 * 1024;
5526
5565
  var ABSENT_SIZE = -1;
5527
5566
  function observeAuthoredBytes(filePath, knownHash, authoredRanges) {
5528
5567
  try {
5529
- const stat3 = fs4.statSync(filePath);
5568
+ const stat3 = fs5.statSync(filePath);
5530
5569
  const hash = knownHash !== void 0 ? knownHash : stat3.size <= READ_BINDING_MAX_BYTES ? hashFileBytes(filePath) : void 0;
5531
5570
  return {
5532
5571
  size: stat3.size,
@@ -5535,7 +5574,7 @@ function observeAuthoredBytes(filePath, knownHash, authoredRanges) {
5535
5574
  ...hash !== void 0 && { hash },
5536
5575
  ...authoredRanges !== void 0 && { authoredRanges },
5537
5576
  ...authoredRanges !== void 0 && {
5538
- authoredLineCount: splitLines(fs4.readFileSync(filePath, "utf-8")).length
5577
+ authoredLineCount: splitLines(fs5.readFileSync(filePath, "utf-8")).length
5539
5578
  }
5540
5579
  };
5541
5580
  } catch {
@@ -5567,7 +5606,7 @@ function isValidAuthoredRanges(value) {
5567
5606
  function authoredBytesIntact(filePath, authored) {
5568
5607
  let stat3;
5569
5608
  try {
5570
- stat3 = fs4.statSync(filePath);
5609
+ stat3 = fs5.statSync(filePath);
5571
5610
  } catch {
5572
5611
  return authored.size === ABSENT_SIZE;
5573
5612
  }
@@ -5625,7 +5664,7 @@ var READ_GUARD_MAX_CHECKED_PATHS_PER_CALL = 128;
5625
5664
  var READ_GUARD_IDLE_EVICT_MS_DEFAULT = 30 * 6e4;
5626
5665
  function _currentContentMatchesBindingForTests(filePath, binding) {
5627
5666
  try {
5628
- const content = fs4.readFileSync(filePath, "utf-8");
5667
+ const content = fs5.readFileSync(filePath, "utf-8");
5629
5668
  const boundContent = binding.fullFile ? content : splitLines(content).slice(binding.offset - 1, binding.offset - 1 + binding.limit).join("\n");
5630
5669
  return hashContentBytes(Buffer.from(boundContent, "utf8")) === binding.hash;
5631
5670
  } catch {
@@ -5693,8 +5732,8 @@ function scanFileLines(filePath, ranges, opts) {
5693
5732
  const lines = /* @__PURE__ */ new Map();
5694
5733
  let fd;
5695
5734
  try {
5696
- fd = fs4.openSync(filePath, "r");
5697
- const size = fs4.fstatSync(fd).size;
5735
+ fd = fs5.openSync(filePath, "r");
5736
+ const size = fs5.fstatSync(fd).size;
5698
5737
  if (size > SCAN_MAX_BYTES)
5699
5738
  return overByteGate(filePath, size);
5700
5739
  const byteBudget = size > 0 ? size : SCAN_MAX_BYTES + 1;
@@ -5705,7 +5744,7 @@ function scanFileLines(filePath, ranges, opts) {
5705
5744
  let parts = [];
5706
5745
  const keepLine = () => lines.set(lineNo, Buffer.concat(parts).toString("utf8"));
5707
5746
  while (consumed < byteBudget && !done(lineNo)) {
5708
- const n = fs4.readSync(fd, chunk, 0, Math.min(chunk.length, byteBudget - consumed), null);
5747
+ const n = fs5.readSync(fd, chunk, 0, Math.min(chunk.length, byteBudget - consumed), null);
5709
5748
  if (n === 0)
5710
5749
  break;
5711
5750
  consumed += n;
@@ -5761,7 +5800,7 @@ function scanFileLines(filePath, ranges, opts) {
5761
5800
  return void 0;
5762
5801
  } finally {
5763
5802
  if (fd !== void 0)
5764
- fs4.closeSync(fd);
5803
+ fs5.closeSync(fd);
5765
5804
  }
5766
5805
  }
5767
5806
  function overByteGate(filePath, bytes) {
@@ -5793,7 +5832,7 @@ function currentLinesMatchReadSnapshot(filePath, read, [startLine, endLine]) {
5793
5832
  }
5794
5833
  let lines;
5795
5834
  try {
5796
- lines = splitLines(fs4.readFileSync(filePath, "utf-8"));
5835
+ lines = splitLines(fs5.readFileSync(filePath, "utf-8"));
5797
5836
  } catch {
5798
5837
  return {
5799
5838
  checked: true,
@@ -5857,9 +5896,9 @@ var ReadGuard = class {
5857
5896
  // Existence-independent index for hasKnownPath/forgetPath (#1668 review
5858
5897
  // F1). `this.key()` (normalizeFilePath) branches on whether `filePath`
5859
5898
  // 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.
5899
+ // file resolves to its path identity (`realpathSync.native` on both, #4689
5900
+ // on POSIX), a missing one to its nearest existing ancestor's identity
5901
+ // plus a lowercased tail on win32 and the caller's own tail on POSIX.
5863
5902
  // recordRead/recordWritten always key while the file is still on disk
5864
5903
  // (real casing); hasKnownPath/forgetPath are queried AFTER an external
5865
5904
  // delete already landed, when the path no longer exists — recomputing
@@ -5909,21 +5948,16 @@ var ReadGuard = class {
5909
5948
  * Keying the reads/edits/exemptions maps on the raw path made a read recorded
5910
5949
  * under one form invisible to an edit checked under another, producing a false
5911
5950
  * `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.
5951
+ * folds separators and Windows casing to one key and, for an absolute path,
5952
+ * answers its path identity (#4689), so a read through a link credits an
5953
+ * edit of its target and the reverse. Every map access in this class MUST
5954
+ * key through here, the tool_call license included: before #4689 the
5955
+ * license had its own realpath key (`licenseKey`) while the read credit kept
5956
+ * the spelling, so one class held two identities for one file.
5914
5957
  */
5915
5958
  key(filePath) {
5916
5959
  return normalizeFilePath(filePath);
5917
5960
  }
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
5961
  idleEvictMs() {
5928
5962
  const value = Number.parseInt(process.env.PI_LENS_READ_GUARD_IDLE_EVICT_MS ?? "", 10);
5929
5963
  return Number.isSafeInteger(value) && value > 0 ? value : READ_GUARD_IDLE_EVICT_MS_DEFAULT;
@@ -6260,7 +6294,7 @@ var ReadGuard = class {
6260
6294
  for (const rawPath of rawPaths) {
6261
6295
  if (checked.size >= READ_GUARD_MAX_CHECKED_PATHS_PER_CALL)
6262
6296
  return;
6263
- checked.add(this.licenseKey(rawPath));
6297
+ checked.add(this.key(rawPath));
6264
6298
  }
6265
6299
  }
6266
6300
  /**
@@ -6273,7 +6307,7 @@ var ReadGuard = class {
6273
6307
  if (callId === void 0)
6274
6308
  return false;
6275
6309
  const checked = this.checkedPathsByCall.get(callId);
6276
- const licensedPath = this.licenseKey(filePath);
6310
+ const licensedPath = this.key(filePath);
6277
6311
  if (checked?.has(licensedPath) !== true)
6278
6312
  return false;
6279
6313
  checked.delete(licensedPath);
@@ -6566,7 +6600,7 @@ Re-read the relevant section, then retry the edit using the current line range/c
6566
6600
  */
6567
6601
  isNewFile(filePath) {
6568
6602
  try {
6569
- return !fs4.existsSync(filePath);
6603
+ return !fs5.existsSync(filePath);
6570
6604
  } catch {
6571
6605
  return true;
6572
6606
  }
@@ -6932,7 +6966,7 @@ Re-read the relevant section, then retry the edit using the current line range/c
6932
6966
  if (!Array.isArray(records) || records.length === 0)
6933
6967
  continue;
6934
6968
  const filePath = this.key(rawPath);
6935
- const exists = fs4.existsSync(filePath);
6969
+ const exists = fs5.existsSync(filePath);
6936
6970
  for (const read of records) {
6937
6971
  const id = read?.toolCallId;
6938
6972
  if (!exists || typeof id !== "string" || !onBranch.has(id)) {
@@ -7028,7 +7062,7 @@ Re-read the relevant section, then retry the edit using the current line range/c
7028
7062
  let evidence;
7029
7063
  try {
7030
7064
  evidence = writtenContent !== void 0 ? deliveredLineEvidence(writtenContent, 1) : {
7031
- lineCount: splitLines(fs4.readFileSync(filePath, "utf-8")).length,
7065
+ lineCount: splitLines(fs5.readFileSync(filePath, "utf-8")).length,
7032
7066
  lineHashes: void 0
7033
7067
  };
7034
7068
  } catch {
@@ -7054,7 +7088,7 @@ Re-read the relevant section, then retry the edit using the current line range/c
7054
7088
  canIgnoreStalenessByHashes(filePath, reads, touchedLines, editRanges) {
7055
7089
  let lines;
7056
7090
  try {
7057
- lines = splitLines(fs4.readFileSync(filePath, "utf-8"));
7091
+ lines = splitLines(fs5.readFileSync(filePath, "utf-8"));
7058
7092
  } catch {
7059
7093
  return false;
7060
7094
  }
@@ -7194,7 +7228,7 @@ Re-read the relevant section, then retry the edit using the current line range/c
7194
7228
  }
7195
7229
  let lines;
7196
7230
  try {
7197
- lines = splitLines(fs4.readFileSync(filePath, "utf-8"));
7231
+ lines = splitLines(fs5.readFileSync(filePath, "utf-8"));
7198
7232
  } catch {
7199
7233
  return void 0;
7200
7234
  }
@@ -7382,6 +7416,129 @@ function mapVerdictAction(action) {
7382
7416
  }
7383
7417
  }
7384
7418
 
7419
+ // dist/clients/read-guard-tool-lines.js
7420
+ var MAX_FAILURE_TRACKER_SIZE = 200;
7421
+ var recentOldTextFailures = new BoundedFifoMap(MAX_FAILURE_TRACKER_SIZE);
7422
+
7423
+ // dist/clients/bash-file-access.js
7424
+ var ANSI_C_ESCAPES = new Map(Object.entries({
7425
+ a: 7,
7426
+ b: 8,
7427
+ e: 27,
7428
+ E: 27,
7429
+ f: 12,
7430
+ n: 10,
7431
+ r: 13,
7432
+ t: 9,
7433
+ v: 11,
7434
+ "\\": 92,
7435
+ "'": 39,
7436
+ '"': 34,
7437
+ "?": 63
7438
+ }).map(([escape, value]) => [escape.charCodeAt(0), value]));
7439
+
7440
+ // dist/clients/opaque-mutation-scan.js
7441
+ var OPAQUE_HASH_BUDGET_BYTES = 8 * 1024 * 1024;
7442
+ var MAX_GIT_STATUS_OUTPUT_BYTES = 16 * 1024 * 1024;
7443
+ var PI_BUILTIN_TOOL_WRITES = new Map(Object.entries({
7444
+ bash: "opaque",
7445
+ powershell: "opaque",
7446
+ write: "named",
7447
+ edit: "named",
7448
+ read: "none",
7449
+ grep: "none",
7450
+ find: "none",
7451
+ ls: "none"
7452
+ }));
7453
+ var OPAQUE_BASELINE_PENDING_CAP = 64;
7454
+ var OpaqueBaselineStore = class _OpaqueBaselineStore {
7455
+ pending = new BoundedFifoMap(OPAQUE_BASELINE_PENDING_CAP);
7456
+ static keyOf(slot, callId) {
7457
+ return callId === void 0 ? slot : `${slot}#${callId}`;
7458
+ }
7459
+ /**
7460
+ * Store `state` for a call. A baseline this displaces is lost: its
7461
+ * `tool_result` will find nothing and report `partial-recognition-no-baseline`,
7462
+ * withholding the blocker section of a write the agent authored. That loss is
7463
+ * counted in the degradation ledger, one entry per cause with a running count,
7464
+ * never one row per occurrence (#4137).
7465
+ *
7466
+ * First, an entry whose turn is over is retired: pi sends no `tool_result`
7467
+ * for a call a `tool_call` handler blocked or Escape aborted before it ran,
7468
+ * and on a non-git project the entry holds a whole-tree stat snapshot.
7469
+ */
7470
+ record(slot, callId, state4, turn) {
7471
+ for (const [staleKey, entry] of this.pending.entriesArray())
7472
+ if (entry.turn && !entry.turn.isLive(entry.turn.key)) {
7473
+ this.pending.delete(staleKey);
7474
+ recordBaselineLoss("unsettled");
7475
+ }
7476
+ const key = _OpaqueBaselineStore.keyOf(slot, callId);
7477
+ const overwrote = this.pending.delete(key);
7478
+ const evicted = this.pending.set(key, { state: state4, turn });
7479
+ if (overwrote)
7480
+ recordBaselineLoss("overwrite");
7481
+ if (evicted.length > 0)
7482
+ recordBaselineLoss("cap");
7483
+ }
7484
+ /**
7485
+ * #4732: whether `tool_call` recorded a baseline for this call. A tool other
7486
+ * than bash recovers only then, so its `tool_result` follows the decision its
7487
+ * own `tool_call` made instead of re-deriving it (shape 19).
7488
+ */
7489
+ has(slot, callId) {
7490
+ return this.pending.has(_OpaqueBaselineStore.keyOf(slot, callId));
7491
+ }
7492
+ take(slot, callId) {
7493
+ const key = _OpaqueBaselineStore.keyOf(slot, callId);
7494
+ const entry = this.pending.get(key);
7495
+ this.pending.delete(key);
7496
+ return entry?.state;
7497
+ }
7498
+ /** Session-boundary clear - unconsumed baselines are unreachable after reset. */
7499
+ takeAllForTest() {
7500
+ this.pending.clear();
7501
+ }
7502
+ };
7503
+ var BASELINE_LOSS_REASONS = {
7504
+ 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)",
7505
+ cap: `more than ${OPAQUE_BASELINE_PENDING_CAP} opaque baselines (bash or other captured tools) awaited a tool_result; the oldest was dropped`,
7506
+ 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"
7507
+ };
7508
+ function recordBaselineLoss(cause) {
7509
+ incrementDegradationCount({
7510
+ kind: "opaque-baseline-lost",
7511
+ subject: cause,
7512
+ reason: BASELINE_LOSS_REASONS[cause]
7513
+ });
7514
+ }
7515
+ var globalStoreSymbol = /* @__PURE__ */ Symbol.for("pi-lens:opaque-snapshot-store");
7516
+ var globalSlot = globalThis;
7517
+ function getOpaqueBaselineStore() {
7518
+ const existing = globalSlot[globalStoreSymbol]?.store;
7519
+ if (existing)
7520
+ return existing;
7521
+ const created = new OpaqueBaselineStore();
7522
+ globalSlot[globalStoreSymbol] = { store: created };
7523
+ return created;
7524
+ }
7525
+ var gitRepoMemo = /* @__PURE__ */ new Map();
7526
+ var overCapRootMemo = new BoundedFifoMap(16);
7527
+ function resetOpaqueMutationState() {
7528
+ getOpaqueBaselineStore().takeAllForTest();
7529
+ gitRepoMemo.clear();
7530
+ overCapRootMemo.clear();
7531
+ gitToplevelMemo.clear();
7532
+ headRecords.clear();
7533
+ headLooks.clear();
7534
+ pendingHeadDiscards.clear();
7535
+ }
7536
+ var HEAD_RECORD_CAP = 64;
7537
+ var headRecords = new BoundedFifoMap(HEAD_RECORD_CAP);
7538
+ var pendingHeadDiscards = new BoundedFifoMap(HEAD_RECORD_CAP);
7539
+ var headLooks = createSingleFlight({ coalesceTrailing: true });
7540
+ var gitToplevelMemo = /* @__PURE__ */ new Map();
7541
+
7385
7542
  // dist/clients/observed-mutation.js
7386
7543
  var OBSERVED_HANDLED_MAX = 1e3;
7387
7544
  var OBSERVED_HASH_BUDGET_BYTES = 2 * 1024 * 1024;
@@ -7874,8 +8031,8 @@ function recordLspMutationOutcome(context, status) {
7874
8031
  }
7875
8032
 
7876
8033
  // dist/clients/lsp/diagnostic-binding.js
7877
- import { createHash as createHash3 } from "node:crypto";
7878
- import * as fs5 from "node:fs";
8034
+ import { createHash as createHash4 } from "node:crypto";
8035
+ import * as fs6 from "node:fs";
7879
8036
  function resolveTouchVerdict(input) {
7880
8037
  const unavailableIds = [...new Set(input.unavailablePrimaryServerIds ?? [])];
7881
8038
  if (unavailableIds.length > 0) {
@@ -7937,7 +8094,7 @@ function auxiliaryCoverageGap(evidence) {
7937
8094
  return evidence.filter((aux) => aux.outcome !== "answered" && aux.publishedThisContent !== true).map((aux) => aux.serverId);
7938
8095
  }
7939
8096
  function hashDiagnosticContent(content) {
7940
- return createHash3("sha256").update(content).digest("hex");
8097
+ return createHash4("sha256").update(content).digest("hex");
7941
8098
  }
7942
8099
  function composeBoundToCurrentDisk(values) {
7943
8100
  if (values.some((v) => v === false))
@@ -7963,7 +8120,7 @@ function createDiskBindingCache() {
7963
8120
  return "unknown";
7964
8121
  let stat3;
7965
8122
  try {
7966
- stat3 = fs5.statSync(filePath);
8123
+ stat3 = fs6.statSync(filePath);
7967
8124
  } catch {
7968
8125
  return "unknown";
7969
8126
  }
@@ -7971,7 +8128,7 @@ function createDiskBindingCache() {
7971
8128
  if (!cached || cached.mtimeMs !== stat3.mtimeMs || cached.size !== stat3.size) {
7972
8129
  let diskHash;
7973
8130
  try {
7974
- diskHash = hashDiagnosticContent(fs5.readFileSync(filePath, "utf-8"));
8131
+ diskHash = hashDiagnosticContent(fs6.readFileSync(filePath, "utf-8"));
7975
8132
  } catch {
7976
8133
  return "unknown";
7977
8134
  }
@@ -8029,12 +8186,12 @@ async function runPerServerGroups(groups, concurrency, processGroup, signal) {
8029
8186
  import path13 from "node:path";
8030
8187
 
8031
8188
  // dist/clients/widget-state.js
8032
- import { readFileSync as readFileSync6 } from "node:fs";
8189
+ import { readFileSync as readFileSync7 } from "node:fs";
8033
8190
  import { stat } from "node:fs/promises";
8034
8191
  import { pathToFileURL } from "node:url";
8035
8192
 
8036
8193
  // dist/clients/diagnostic-line-freshness.js
8037
- import * as fs6 from "node:fs";
8194
+ import * as fs7 from "node:fs";
8038
8195
 
8039
8196
  // dist/clients/stale-marker.js
8040
8197
  var STALE_LINE_MARKER = "[stale \u2014 re-run to confirm]";
@@ -8051,13 +8208,13 @@ function rememberInSharedCache(cache, filePath, entry) {
8051
8208
  cache.set(filePath, entry);
8052
8209
  }
8053
8210
  function countNewlinesChunked(filePath, sizeBytes) {
8054
- const fd = fs6.openSync(filePath, "r");
8211
+ const fd = fs7.openSync(filePath, "r");
8055
8212
  try {
8056
8213
  const buffer = Buffer.allocUnsafe(Math.min(NEWLINE_SCAN_CHUNK_BYTES, sizeBytes) || 1);
8057
8214
  let newlineCount = 0;
8058
8215
  let position = 0;
8059
8216
  while (position < sizeBytes) {
8060
- const bytesRead = fs6.readSync(fd, buffer, 0, buffer.length, position);
8217
+ const bytesRead = fs7.readSync(fd, buffer, 0, buffer.length, position);
8061
8218
  if (bytesRead <= 0)
8062
8219
  break;
8063
8220
  for (let i = 0; i < bytesRead; i++) {
@@ -8068,13 +8225,13 @@ function countNewlinesChunked(filePath, sizeBytes) {
8068
8225
  }
8069
8226
  return newlineCount;
8070
8227
  } finally {
8071
- fs6.closeSync(fd);
8228
+ fs7.closeSync(fd);
8072
8229
  }
8073
8230
  }
8074
8231
  function getCachedLineCount(filePath, cache = sharedLineCountCache) {
8075
8232
  let stat3;
8076
8233
  try {
8077
- stat3 = fs6.statSync(filePath);
8234
+ stat3 = fs7.statSync(filePath);
8078
8235
  } catch {
8079
8236
  return void 0;
8080
8237
  }
@@ -8129,7 +8286,7 @@ function demotePastEofDiagnostics(args) {
8129
8286
  }
8130
8287
  let sizeBytes;
8131
8288
  try {
8132
- sizeBytes = fs6.statSync(args.filePath).size;
8289
+ sizeBytes = fs7.statSync(args.filePath).size;
8133
8290
  } catch {
8134
8291
  sizeBytes = 0;
8135
8292
  }
@@ -8159,8 +8316,8 @@ function resyncDocumentOnPastEof(filePath) {
8159
8316
  void (async () => {
8160
8317
  try {
8161
8318
  const [{ getOwnedLspService: getOwnedLspService2 }, content] = await Promise.all([
8162
- import("./chunk-O4NWQT6I.js"),
8163
- fs6.promises.readFile(filePath, "utf-8")
8319
+ import("./chunk-2PHMIAKO.js"),
8320
+ fs7.promises.readFile(filePath, "utf-8")
8164
8321
  ]);
8165
8322
  await getOwnedLspService2().openFile(filePath, content, { preserveDiagnostics: false });
8166
8323
  } catch {
@@ -8215,7 +8372,7 @@ var WriteOrderingGuard = class {
8215
8372
  };
8216
8373
 
8217
8374
  // dist/clients/diagnostic-dispositions.js
8218
- import * as fs7 from "node:fs";
8375
+ import * as fs8 from "node:fs";
8219
8376
  import * as path9 from "node:path";
8220
8377
 
8221
8378
  // dist/clients/disposition-logger.js
@@ -8234,13 +8391,19 @@ var writer2 = createNdjsonLogger({
8234
8391
  var liveEmitter3 = createLiveBusEmitter();
8235
8392
 
8236
8393
  // dist/clients/diagnostic-dispositions.js
8237
- var deferredThisSession = /* @__PURE__ */ new Set();
8394
+ var deferredByCwd = /* @__PURE__ */ new Map();
8238
8395
  var widgetDispositionReconciler = null;
8239
8396
  function registerWidgetDispositionReconciler(reconciler) {
8240
8397
  widgetDispositionReconciler = reconciler;
8241
8398
  }
8242
- function deferredKey(cwd, anchor) {
8243
- return `${normalizeMapKey(cwd)}::${anchor}`;
8399
+ function deferredAnchorsFor(cwd) {
8400
+ return deferredByCwd.get(normalizeMapKey(cwd));
8401
+ }
8402
+ function hasDeferredThisSession(cwd) {
8403
+ return deferredByCwd.has(normalizeMapKey(cwd));
8404
+ }
8405
+ function nothingToApply(dispositions, cwd) {
8406
+ return !dispositions && !hasDeferredThisSession(cwd);
8244
8407
  }
8245
8408
  var normalizeMessage2 = normalizeMessage;
8246
8409
  function strictAnchorSpan(content, line) {
@@ -8296,9 +8459,9 @@ function statePath(cwd) {
8296
8459
  return path9.join(getProjectDataDir(cwd), "cache", "diagnostic-dispositions.json");
8297
8460
  }
8298
8461
  var stateCache = null;
8299
- var dispositionStatSync = fs7.statSync;
8462
+ var dispositionStatSync = fs8.statSync;
8300
8463
  function hasAnyDispositionMarks(cwd) {
8301
- return Boolean(readState(cwd).dispositions) || deferredThisSession.size > 0;
8464
+ return Boolean(readState(cwd).dispositions) || hasDeferredThisSession(cwd);
8302
8465
  }
8303
8466
  function hasStrictDispositionMarks(cwd) {
8304
8467
  const dispositions = readState(cwd).dispositions;
@@ -8310,7 +8473,7 @@ function hasStrictDispositionMarks(cwd) {
8310
8473
  }
8311
8474
  return false;
8312
8475
  }
8313
- var multiFileReadFileSync = fs7.readFileSync;
8476
+ var multiFileReadFileSync = fs8.readFileSync;
8314
8477
  function readState(cwd) {
8315
8478
  const p = statePath(cwd);
8316
8479
  let stat3;
@@ -8335,7 +8498,7 @@ function readState(cwd) {
8335
8498
  }
8336
8499
  let state4;
8337
8500
  try {
8338
- const parsed = JSON.parse(fs7.readFileSync(p, "utf-8"));
8501
+ const parsed = JSON.parse(fs8.readFileSync(p, "utf-8"));
8339
8502
  state4 = parsed && typeof parsed === "object" ? parsed : {};
8340
8503
  } catch {
8341
8504
  state4 = {};
@@ -8352,16 +8515,20 @@ function readState(cwd) {
8352
8515
  function getDisposition(cwd, anchor) {
8353
8516
  return readState(cwd).dispositions?.[anchor];
8354
8517
  }
8518
+ function resetDeferredDispositions() {
8519
+ deferredByCwd.clear();
8520
+ }
8355
8521
  function applyDispositions(diagnostics, cwd, filePath, content) {
8356
8522
  if (!diagnostics.length)
8357
8523
  return diagnostics;
8358
8524
  const dispositions = readState(cwd).dispositions;
8359
- if (!dispositions && deferredThisSession.size === 0)
8525
+ if (nothingToApply(dispositions, cwd))
8360
8526
  return diagnostics;
8527
+ const deferred = deferredAnchorsFor(cwd);
8361
8528
  return diagnostics.filter((d) => {
8362
8529
  const { strict, weak } = anchorsForDiagnostic(cwd, filePath, d, content);
8363
8530
  const isBlocking2 = d.semantic === "blocking";
8364
- if (!isBlocking2 && deferredThisSession.has(deferredKey(cwd, weak))) {
8531
+ if (!isBlocking2 && deferred?.has(weak)) {
8365
8532
  return false;
8366
8533
  }
8367
8534
  if (dispositions?.[strict]?.disposition === "false-positive")
@@ -8376,8 +8543,9 @@ function applyWeakDispositions(diagnostics, cwd, filePath) {
8376
8543
  if (!diagnostics.length)
8377
8544
  return diagnostics;
8378
8545
  const dispositions = readState(cwd).dispositions;
8379
- if (!dispositions && deferredThisSession.size === 0)
8546
+ if (nothingToApply(dispositions, cwd))
8380
8547
  return diagnostics;
8548
+ const deferred = deferredAnchorsFor(cwd);
8381
8549
  return diagnostics.filter((d) => {
8382
8550
  if (d.semantic === "blocking")
8383
8551
  return true;
@@ -8389,7 +8557,7 @@ function applyWeakDispositions(diagnostics, cwd, filePath) {
8389
8557
  message: d.message,
8390
8558
  line: d.line
8391
8559
  });
8392
- if (deferredThisSession.has(deferredKey(cwd, weak)))
8560
+ if (deferred?.has(weak))
8393
8561
  return false;
8394
8562
  if (dispositions?.[weak]?.disposition === "suppress")
8395
8563
  return false;
@@ -8400,7 +8568,7 @@ function applyDispositionsMultiFile(diagnostics, cwd, filePathOf) {
8400
8568
  if (!diagnostics.length)
8401
8569
  return diagnostics;
8402
8570
  const dispositions = readState(cwd).dispositions;
8403
- if (!dispositions && deferredThisSession.size === 0)
8571
+ if (nothingToApply(dispositions, cwd))
8404
8572
  return diagnostics;
8405
8573
  const groups = /* @__PURE__ */ new Map();
8406
8574
  for (const d of diagnostics) {
@@ -8426,11 +8594,11 @@ function applyDispositionsMultiFile(diagnostics, cwd, filePathOf) {
8426
8594
  }
8427
8595
 
8428
8596
  // dist/clients/session-state-store.js
8429
- import { promises as fs8 } from "node:fs";
8597
+ import { promises as fs9 } from "node:fs";
8430
8598
  async function dropStaleFiles(widget, savedAt) {
8431
8599
  const checked = await Promise.all(widget.files.map(async (file) => {
8432
8600
  try {
8433
- const st = await fs8.stat(file.filePath);
8601
+ const st = await fs9.stat(file.filePath);
8434
8602
  return freshnessFromMtime({
8435
8603
  mtimeMs: st.mtimeMs,
8436
8604
  referenceMs: savedAt,
@@ -8502,7 +8670,7 @@ function reconcileWidgetDisposition(cwd, target, _disposition, content) {
8502
8670
  let source = content ?? target.content;
8503
8671
  if (source === void 0) {
8504
8672
  try {
8505
- source = readFileSync6(target.filePath, "utf8");
8673
+ source = readFileSync7(target.filePath, "utf8");
8506
8674
  } catch {
8507
8675
  recordDegradationOnce({
8508
8676
  kind: "widget-disposition-reconcile-fallback",
@@ -8545,7 +8713,12 @@ function reconcileWidgetDisposition(cwd, target, _disposition, content) {
8545
8713
  const writeIndex = admitWidgetDiagnosticsWrite(target.filePath);
8546
8714
  if (!diagnosticsWriteGuard.shouldWrite(fileMapKey(target.filePath), writeIndex))
8547
8715
  return;
8716
+ const { hasFinalDiagnosticsSnapshot, touchedAt } = rec;
8548
8717
  commitDiagnostics(rec, target.filePath, normalized, Date.now(), fileMapKey(target.filePath), false);
8718
+ if (!hasFinalDiagnosticsSnapshot) {
8719
+ rec.hasFinalDiagnosticsSnapshot = false;
8720
+ rec.touchedAt = touchedAt;
8721
+ }
8549
8722
  }
8550
8723
  function admitWidgetDiagnosticsWrite(filePath, writeIndex) {
8551
8724
  const key = fileMapKey(filePath);
@@ -8694,7 +8867,7 @@ function normalizeDiagnostics(filePath, diagnostics, observedTs) {
8694
8867
  var retentionIdentity = findingIdentity;
8695
8868
  function readContentOrUndefined(filePath) {
8696
8869
  try {
8697
- return readFileSync6(filePath, "utf8");
8870
+ return readFileSync7(filePath, "utf8");
8698
8871
  } catch {
8699
8872
  recordDegradationOnce({
8700
8873
  kind: "widget-mark-anchor-unreadable",
@@ -8835,7 +9008,7 @@ function reconcileCorrelatedScanDiagnostics(filePath, diagnostics, writeIndex, o
8835
9008
  }));
8836
9009
  commitDiagnostics(getOrCreate(filePath, key), filePath, correlated, observedTs, key);
8837
9010
  }
8838
- async function reconcileStaleWidgetFiles() {
9011
+ async function reconcileStaleWidgetFiles(onStaleFile) {
8839
9012
  const entries = [...files.entries()];
8840
9013
  const verdicts = await Promise.all(
8841
9014
  // `mapKey` is the normalized `files` key (used for deletion); stat the
@@ -8845,10 +9018,15 @@ async function reconcileStaleWidgetFiles() {
8845
9018
  try {
8846
9019
  mtimeMs = (await stat(rec.filePath)).mtimeMs;
8847
9020
  } catch {
8848
- return { mapKey, action: "drop" };
9021
+ return { mapKey, action: "missing" };
8849
9022
  }
8850
9023
  if (rec.allDiagnostics.length === 0) {
8851
- return freshnessFromMtime({ mtimeMs, referenceMs: rec.touchedAt }).verdict === "stale" ? { mapKey, action: "drop" } : { mapKey, action: "keep" };
9024
+ return freshnessFromMtime({ mtimeMs, referenceMs: rec.touchedAt }).verdict === "stale" ? {
9025
+ mapKey,
9026
+ action: "stale",
9027
+ mtimeMs,
9028
+ survivors: []
9029
+ } : { mapKey, action: "keep" };
8852
9030
  }
8853
9031
  const mtimeStale = (d) => freshnessFromMtime({
8854
9032
  mtimeMs,
@@ -8859,32 +9037,32 @@ async function reconcileStaleWidgetFiles() {
8859
9037
  if (survivors.length === rec.allDiagnostics.length) {
8860
9038
  return { mapKey, action: "keep" };
8861
9039
  }
8862
- if (survivors.length === 0) {
8863
- return { mapKey, action: "drop" };
8864
- }
8865
- return { mapKey, action: "prune", survivors };
9040
+ return { mapKey, action: "stale", mtimeMs, survivors };
8866
9041
  })
8867
9042
  );
8868
- let dropped = 0;
9043
+ let changed = 0;
8869
9044
  for (const v of verdicts) {
8870
9045
  if (v.action === "keep")
8871
9046
  continue;
8872
- if (v.action === "drop") {
9047
+ const rec = files.get(v.mapKey);
9048
+ if (rec)
9049
+ onStaleFile?.(rec.filePath);
9050
+ changed += 1;
9051
+ if (v.action === "missing") {
8873
9052
  files.delete(v.mapKey);
8874
- dropped += 1;
8875
9053
  continue;
8876
9054
  }
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;
9055
+ if (!rec)
9056
+ continue;
9057
+ rec.allDiagnostics = v.survivors;
9058
+ rec.diagnostics = capStoredDiagnostics(v.survivors);
9059
+ rec.diagnosticCounts = countDiagnostics(v.survivors);
9060
+ rec.hasFinalDiagnosticsSnapshot = false;
9061
+ rec.touchedAt = Math.max(Date.now(), v.mtimeMs);
8884
9062
  }
8885
- if (dropped > 0)
9063
+ if (changed > 0)
8886
9064
  requestRenderFn?.();
8887
- return dropped;
9065
+ return changed;
8888
9066
  }
8889
9067
  async function reconcileStaleWidgetDependencyBlockers(cwd, turnIndex) {
8890
9068
  let demoted = 0;
@@ -9048,6 +9226,14 @@ function recordLsp(serverId, root, status, durationMs) {
9048
9226
  lspServers.set(key, { serverId, root, status: mapped, durationMs });
9049
9227
  requestRender();
9050
9228
  }
9229
+ function classifyFileTier(rec) {
9230
+ if (rec.diagnosticCounts.blocking > 0)
9231
+ return "blocking";
9232
+ if (rec.diagnosticCounts.errors > 0 || rec.diagnosticCounts.warnings > 0) {
9233
+ return "warning";
9234
+ }
9235
+ return "clean";
9236
+ }
9051
9237
  function getOrCreate(filePath, key = fileMapKey(filePath)) {
9052
9238
  maybePruneInactiveFileRecords();
9053
9239
  return files.get(key) ?? {
@@ -9061,8 +9247,11 @@ function getOrCreate(filePath, key = fileMapKey(filePath)) {
9061
9247
  touchedAt: Date.now()
9062
9248
  };
9063
9249
  }
9250
+ function holdsDrawableFindings(rec) {
9251
+ return classifyFileTier(rec) !== "clean";
9252
+ }
9064
9253
  function hasLiveDiagnostic(rec) {
9065
- return rec.hasFinalDiagnosticsSnapshot && rec.diagnostics.length > 0;
9254
+ return rec.diagnostics.length > 0 && (rec.hasFinalDiagnosticsSnapshot || holdsDrawableFindings(rec));
9066
9255
  }
9067
9256
  function capStoredDiagnostics(diagnostics) {
9068
9257
  if (diagnostics.length <= MAX_STORED_DIAGNOSTICS_PER_FILE)
@@ -9183,7 +9372,8 @@ async function raceToCompletion(promises3, shouldComplete, options = { timeoutMs
9183
9372
  }
9184
9373
 
9185
9374
  // dist/clients/lsp/edits.js
9186
- import fs9 from "node:fs/promises";
9375
+ import fs10 from "node:fs/promises";
9376
+ import { readFileSync as readFileSync8, realpathSync as realpathSync2, statSync as statSync8 } from "node:fs";
9187
9377
  import path10 from "node:path";
9188
9378
  import { URL as URL2 } from "node:url";
9189
9379
 
@@ -9209,12 +9399,6 @@ function convertCharacterOffset(encoding, lineText, utf16Character) {
9209
9399
  return Buffer.byteLength(prefix, "utf8");
9210
9400
  return [...prefix].length;
9211
9401
  }
9212
- function lineTextAt(content, line) {
9213
- if (line < 0)
9214
- return "";
9215
- const lines = content.split("\n");
9216
- return lines[line] ?? "";
9217
- }
9218
9402
 
9219
9403
  // dist/clients/lsp/watch-queue.js
9220
9404
  var WATCH_DEBOUNCE_MS = 100;
@@ -9290,56 +9474,6 @@ var WatchedFilesQueue = class {
9290
9474
  }
9291
9475
  };
9292
9476
 
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
9477
  // dist/clients/lsp/edits.js
9344
9478
  var StaleWorkspaceEditContentError = class extends Error {
9345
9479
  };
@@ -9653,7 +9787,11 @@ function mergeWorkspaceTextEditsByPriority(entries) {
9653
9787
  continue;
9654
9788
  for (const [uri, edits] of flattenWorkspaceTextEdits(entry.edit)) {
9655
9789
  const key = pathIndexKey(uri);
9656
- const bucket = merged.get(key) ?? { uri, edits: [] };
9790
+ const bucket = merged.get(key) ?? {
9791
+ uri,
9792
+ edits: [],
9793
+ sourceClientKeys: /* @__PURE__ */ new Set()
9794
+ };
9657
9795
  const kept = bucket.edits;
9658
9796
  for (const edit of edits) {
9659
9797
  inputEditCount += 1;
@@ -9667,15 +9805,25 @@ function mergeWorkspaceTextEditsByPriority(entries) {
9667
9805
  if (exactKey !== void 0)
9668
9806
  seenExact.add(exactKey);
9669
9807
  kept.push(edit);
9808
+ bucket.sourceClientKeys.add(entry.clientKey ?? entry.serverId);
9670
9809
  }
9671
9810
  if (kept.length > 0)
9672
9811
  merged.set(key, bucket);
9673
9812
  }
9674
9813
  }
9675
9814
  const changes = {};
9676
- for (const { uri, edits } of merged.values())
9815
+ const sourceClientKeys = /* @__PURE__ */ new Map();
9816
+ for (const [key, { uri, edits, sourceClientKeys: sources }] of merged) {
9677
9817
  changes[uri] = edits;
9678
- return { edit: { changes }, droppedConflicts, inputEditCount, serverIds };
9818
+ sourceClientKeys.set(key, [...sources]);
9819
+ }
9820
+ return {
9821
+ edit: { changes },
9822
+ droppedConflicts,
9823
+ inputEditCount,
9824
+ serverIds,
9825
+ sourceClientKeys
9826
+ };
9679
9827
  }
9680
9828
  function pathIndexKey(uri) {
9681
9829
  return normalizeEphemeralMapKey(uriToPath(uri));
@@ -9712,6 +9860,64 @@ function plannedDiskPaths(planned) {
9712
9860
  function workspaceEditTextPaths(edit) {
9713
9861
  return planWorkspaceEdit(edit).flatMap((op) => op.kind === "text" ? [uriToDiskPath(op.uri)] : []);
9714
9862
  }
9863
+ var RENAME_MTIME_MARGIN_MS = 2e3;
9864
+ function captureRenameExpectedContent(edit, cwd, requestedAtMs, readTrackedSend, target, sourceClientKeysByPath) {
9865
+ const expected = /* @__PURE__ */ new Map();
9866
+ let targetRealPath;
9867
+ if (target !== void 0) {
9868
+ try {
9869
+ targetRealPath = realpathSync2.native(target.filePath);
9870
+ } catch {
9871
+ targetRealPath = void 0;
9872
+ }
9873
+ }
9874
+ for (const diskPath of workspaceEditTextPaths(edit)) {
9875
+ let realPath;
9876
+ let content;
9877
+ let mtimeMs;
9878
+ try {
9879
+ realPath = realpathSync2.native(diskPath);
9880
+ content = readFileSync8(realPath, "utf-8");
9881
+ mtimeMs = statSync8(realPath).mtimeMs;
9882
+ } catch {
9883
+ continue;
9884
+ }
9885
+ if (target !== void 0 && realPath === targetRealPath) {
9886
+ expected.set(realPath, target.content);
9887
+ continue;
9888
+ }
9889
+ const contributorKeys = sourceClientKeysByPath?.get(normalizeEphemeralMapKey(realPath));
9890
+ const trackedResult = readTrackedSend(diskPath, cwd, contributorKeys);
9891
+ const tracked = trackedResult === void 0 ? [] : Array.isArray(trackedResult) ? trackedResult : [trackedResult];
9892
+ const contentHash2 = hashDiagnosticContent(content);
9893
+ let hasComparableSend = false;
9894
+ const comparableKeys = /* @__PURE__ */ new Set();
9895
+ for (const trackedSend of tracked) {
9896
+ const firstOpenedAfterRequest = (trackedSend.openedAtMs ?? 0) >= requestedAtMs;
9897
+ const quietSinceClientStart = trackedSend.clientStartedAtMs !== void 0 && mtimeMs < trackedSend.clientStartedAtMs - RENAME_MTIME_MARGIN_MS;
9898
+ const sent = firstOpenedAfterRequest && quietSinceClientStart ? void 0 : trackedSend;
9899
+ if (sent !== void 0) {
9900
+ hasComparableSend = true;
9901
+ comparableKeys.add(trackedSend.clientKey);
9902
+ if (sent.hash !== contentHash2 || (sent.changedAtMs ?? requestedAtMs) >= requestedAtMs) {
9903
+ refuseStaleWorkspaceEdit(diskPath, "it changed after the language server computed the rename from it");
9904
+ }
9905
+ } else if (trackedSend.hash !== contentHash2 || trackedSend.openedHash !== trackedSend.hash) {
9906
+ refuseStaleWorkspaceEdit(diskPath, "it changed after the language client first opened it, after the rename was requested");
9907
+ }
9908
+ }
9909
+ const unboundKeys = contributorKeys?.filter((key) => !comparableKeys.has(key)) ?? [];
9910
+ const boundByRecord = hasComparableSend && unboundKeys.length === 0;
9911
+ const noOpenCopy = unboundKeys.length === 0 ? "the language server has no open copy" : `the language client ${unboundKeys.join(", ")} that edits it had no open copy`;
9912
+ if (!boundByRecord && mtimeMs >= requestedAtMs) {
9913
+ refuseStaleWorkspaceEdit(diskPath, `it was written after the rename was requested and ${noOpenCopy}, so it may not have read these bytes`);
9914
+ } else if (!boundByRecord && mtimeMs >= requestedAtMs - RENAME_MTIME_MARGIN_MS) {
9915
+ refuseStaleWorkspaceEdit(diskPath, `it was modified within ${RENAME_MTIME_MARGIN_MS / 1e3} s of the rename request${unboundKeys.length === 0 ? "" : ` and ${noOpenCopy}`}; retry`);
9916
+ }
9917
+ expected.set(realPath, content);
9918
+ }
9919
+ return expected;
9920
+ }
9715
9921
  function planWorkspaceEdit(edit, trackOrigins = false) {
9716
9922
  parseWorkspaceEdit(edit);
9717
9923
  const ops = [];
@@ -9861,7 +10067,7 @@ function summarizeWorkspaceEdit(edit, cwd) {
9861
10067
  }
9862
10068
  async function lstatOrMissing(filePath) {
9863
10069
  try {
9864
- return await fs9.lstat(filePath);
10070
+ return await fs10.lstat(filePath);
9865
10071
  } catch (err) {
9866
10072
  if (err.code === "ENOENT")
9867
10073
  return void 0;
@@ -9873,7 +10079,7 @@ function isSameFsIdentity(a, b) {
9873
10079
  }
9874
10080
  async function bigintLstatOrMissing(filePath) {
9875
10081
  try {
9876
- return await fs9.lstat(filePath, { bigint: true });
10082
+ return await fs10.lstat(filePath, { bigint: true });
9877
10083
  } catch (err) {
9878
10084
  if (err.code === "ENOENT")
9879
10085
  return void 0;
@@ -9897,32 +10103,19 @@ async function assertParentIsUsable(filePath, stateFor) {
9897
10103
  return;
9898
10104
  }
9899
10105
  const parent = path10.dirname(current);
9900
- if (parent === current)
9901
- throw new Error(`resource parent does not exist: ${filePath}`);
9902
- current = parent;
9903
- }
9904
- }
9905
- async function resolveExistingAncestor(filePath) {
9906
- let current = path10.resolve(filePath);
9907
- const tail = [];
9908
- while (true) {
9909
- try {
9910
- const resolved2 = await fs9.realpath(current);
9911
- return path10.join(resolved2, ...tail.reverse());
9912
- } catch (err) {
9913
- const code = err.code;
9914
- if (code !== "ENOENT" && code !== "ENOTDIR")
9915
- throw err;
9916
- const parent = path10.dirname(current);
9917
- if (parent === current)
9918
- throw err;
9919
- tail.push(path10.basename(current));
9920
- current = parent;
9921
- }
10106
+ if (parent === current)
10107
+ throw new Error(`resource parent does not exist: ${filePath}`);
10108
+ current = parent;
9922
10109
  }
9923
10110
  }
10111
+ async function requireKernelIdentity(filePath, subject) {
10112
+ const identity = await kernelPathIdentityAsync(filePath);
10113
+ if (identity === void 0 || !identity.kernelConfirmed)
10114
+ throw new Error(`workspace edit path identity is unresolvable: ${subject}`);
10115
+ return identity.identity;
10116
+ }
9924
10117
  async function createWorkspaceUriConfiner(cwd) {
9925
- const root = await resolveExistingAncestor(cwd);
10118
+ const root = await requireKernelIdentity(cwd, cwd);
9926
10119
  return async (uri) => {
9927
10120
  let filePath = "";
9928
10121
  try {
@@ -9935,7 +10128,7 @@ async function createWorkspaceUriConfiner(cwd) {
9935
10128
  }
9936
10129
  if (!path10.isAbsolute(filePath))
9937
10130
  throw new Error(`workspace edit path escapes workspace: ${uri}`);
9938
- const resolved2 = await resolveExistingAncestor(filePath);
10131
+ const resolved2 = await requireKernelIdentity(filePath, uri);
9939
10132
  if (!isUnderDir(resolved2, root))
9940
10133
  throw new Error(`workspace edit path escapes workspace: ${uri}`);
9941
10134
  return filePath;
@@ -10008,8 +10201,8 @@ async function preflightWorkspaceEdit(planned, cwd, options) {
10008
10201
  const physicalPath = resolveVirtualPath(filePath);
10009
10202
  if (!physicalPath)
10010
10203
  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));
10204
+ const content = await fs10.readFile(physicalPath, "utf-8");
10205
+ const expected = options.expectedContent?.get(await realpathOrResolveAsync(physicalPath));
10013
10206
  if (expected !== void 0 && expected !== content) {
10014
10207
  refuseStaleWorkspaceEdit(filePath, "the file changed after the edit was computed from it");
10015
10208
  }
@@ -10197,14 +10390,14 @@ async function applyWorkspaceEdit(edit, cwd, options = {}) {
10197
10390
  skipOperation(op);
10198
10391
  continue;
10199
10392
  }
10200
- const content = await fs9.readFile(diskPath, "utf-8");
10393
+ const content = await fs10.readFile(diskPath, "utf-8");
10201
10394
  const updated = applyTextEditsToString(content, edits, "utf-16");
10202
10395
  const changesLineCount = edits.some((edit2) => {
10203
10396
  const removedLines = edit2.range.end.line - edit2.range.start.line;
10204
10397
  const insertedLines = (edit2.newText.match(/\r\n|\r|\n/g) ?? []).length;
10205
10398
  return removedLines !== insertedLines;
10206
10399
  });
10207
- await fs9.writeFile(diskPath, updated, "utf-8");
10400
+ await fs10.writeFile(diskPath, updated, "utf-8");
10208
10401
  const start = Math.min(...edits.map((item) => item.range.start.line + 1));
10209
10402
  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
10403
  touchedFiles.add(filePath);
@@ -10223,11 +10416,11 @@ async function applyWorkspaceEdit(edit, cwd, options = {}) {
10223
10416
  } else if (op.kind === "create") {
10224
10417
  const filePath = uriToPath(op.uri);
10225
10418
  const diskPath = uriToDiskPath(op.uri);
10226
- await fs9.mkdir(path10.dirname(diskPath), { recursive: true });
10419
+ await fs10.mkdir(path10.dirname(diskPath), { recursive: true });
10227
10420
  if (op.options?.overwrite)
10228
- await fs9.writeFile(diskPath, "", "utf-8");
10421
+ await fs10.writeFile(diskPath, "", "utf-8");
10229
10422
  else
10230
- await fs9.writeFile(diskPath, "", { flag: "wx" });
10423
+ await fs10.writeFile(diskPath, "", { flag: "wx" });
10231
10424
  resourceChanges.push({ filePath: diskPath, type: FILE_CREATED });
10232
10425
  touchedFiles.add(filePath);
10233
10426
  fileDetails.push({
@@ -10243,10 +10436,10 @@ async function applyWorkspaceEdit(edit, cwd, options = {}) {
10243
10436
  const newPath = uriToPath(op.newUri);
10244
10437
  const oldDisk = uriToDiskPath(op.oldUri);
10245
10438
  const newDisk = uriToDiskPath(op.newUri);
10246
- await fs9.mkdir(path10.dirname(newDisk), { recursive: true });
10439
+ await fs10.mkdir(path10.dirname(newDisk), { recursive: true });
10247
10440
  if (op.options?.overwrite)
10248
- await fs9.rm(newDisk, { recursive: true, force: true });
10249
- await fs9.rename(oldDisk, newDisk);
10441
+ await fs10.rm(newDisk, { recursive: true, force: true });
10442
+ await fs10.rename(oldDisk, newDisk);
10250
10443
  resourceChanges.push({ filePath: oldDisk, type: FILE_DELETED }, { filePath: newDisk, type: FILE_CREATED });
10251
10444
  touchedFiles.add(oldPath);
10252
10445
  touchedFiles.add(newPath);
@@ -10266,7 +10459,7 @@ async function applyWorkspaceEdit(edit, cwd, options = {}) {
10266
10459
  } else {
10267
10460
  const filePath = uriToPath(op.uri);
10268
10461
  const diskPath = uriToDiskPath(op.uri);
10269
- await fs9.rm(diskPath, {
10462
+ await fs10.rm(diskPath, {
10270
10463
  recursive: op.options?.recursive === true,
10271
10464
  force: false
10272
10465
  });
@@ -10504,7 +10697,7 @@ async function attemptTsserverSyncDiagnostics(file, svc) {
10504
10697
  }
10505
10698
 
10506
10699
  // dist/clients/lsp/workspace-diagnostics-cache.js
10507
- import * as fs10 from "node:fs";
10700
+ import * as fs11 from "node:fs";
10508
10701
  import * as path12 from "node:path";
10509
10702
 
10510
10703
  // dist/clients/reverse-deps.js
@@ -10703,7 +10896,7 @@ function loadWorkspaceDiagnosticsCache(cwd) {
10703
10896
  }
10704
10897
  function saveWorkspaceDiagnosticsCache(cwd, cache) {
10705
10898
  const filePath = cachePath(cwd);
10706
- fs10.mkdirSync(path12.dirname(filePath), { recursive: true });
10899
+ fs11.mkdirSync(path12.dirname(filePath), { recursive: true });
10707
10900
  writeFileAtomic(filePath, JSON.stringify(cache, null, 2), {
10708
10901
  bestEffort: false
10709
10902
  });
@@ -10737,7 +10930,7 @@ function classifyWorkspaceDiagnosticsCacheExpiry(entry, now, sessionStartedAt, f
10737
10930
  function isEntryFresh(filePath, entry, getImports) {
10738
10931
  let ownStat;
10739
10932
  try {
10740
- ownStat = fs10.statSync(filePath);
10933
+ ownStat = fs11.statSync(filePath);
10741
10934
  } catch {
10742
10935
  return false;
10743
10936
  }
@@ -10761,7 +10954,7 @@ function isEntryFresh(filePath, entry, getImports) {
10761
10954
  for (const dep of imports) {
10762
10955
  let mtimeMs;
10763
10956
  try {
10764
- mtimeMs = fs10.statSync(dep).mtimeMs;
10957
+ mtimeMs = fs11.statSync(dep).mtimeMs;
10765
10958
  } catch {
10766
10959
  return false;
10767
10960
  }
@@ -11056,7 +11249,8 @@ var CLIENT_CAPABILITIES = {
11056
11249
  fileOperations: {
11057
11250
  dynamicRegistration: false,
11058
11251
  willRename: true,
11059
- didRename: true
11252
+ didRename: true,
11253
+ didCreate: true
11060
11254
  }
11061
11255
  },
11062
11256
  textDocument: {
@@ -11452,8 +11646,13 @@ function rebaselineForRulesRefresh(state4) {
11452
11646
  phase: "lsp_rules_refreshed",
11453
11647
  filePath: state4.root,
11454
11648
  durationMs: 0,
11455
- metadata: { serverId: state4.serverId, rebaselinedPaths: counts.size }
11649
+ metadata: {
11650
+ serverId: state4.serverId,
11651
+ rebaselinedPaths: counts.size,
11652
+ heldEmptyPublishes: state4.heldEmptyPublishes ?? 0
11653
+ }
11456
11654
  });
11655
+ state4.heldEmptyPublishes = 0;
11457
11656
  }
11458
11657
  function publicationCountsForPath(state4, normalizedPath) {
11459
11658
  const lastSent = state4.documentVersions.get(normalizedPath);
@@ -11465,6 +11664,7 @@ function publicationCountsForPath(state4, normalizedPath) {
11465
11664
  function diagnosticsVersionForPath(state4, normalizedPath) {
11466
11665
  return state4.diagnosticsVersionsByPath?.get(normalizedPath) ?? 0;
11467
11666
  }
11667
+ var PENDING_RECEIPT_DROPPED = "pending-receipt-dropped";
11468
11668
  function clearDiagnosticsForPath(state4, normalizedPath) {
11469
11669
  const legacy = state4;
11470
11670
  state4.pushDiagnostics?.delete(normalizedPath);
@@ -11478,6 +11678,7 @@ function clearDiagnosticsForPath(state4, normalizedPath) {
11478
11678
  state4.documentPullDiagnostics?.delete(normalizedPath);
11479
11679
  state4.documentPullDiagnosticTimestamps?.delete(normalizedPath);
11480
11680
  state4.diagnosticDocVersions?.delete(normalizedPath);
11681
+ state4.nonEmptyAnswerPhases?.delete(normalizedPath);
11481
11682
  state4.diagnosticBindings?.delete(normalizedPath);
11482
11683
  state4.diagnosticsVersionsByPath?.delete(normalizedPath);
11483
11684
  for (const key of pullSourceKeysForPath(state4, normalizedPath)) {
@@ -11517,36 +11718,8 @@ function logTypeScriptPullSettle(state4, normalizedPath, durationMs, pullSettleS
11517
11718
  }
11518
11719
  });
11519
11720
  }
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);
11721
+ function recordSentContent(state4, normalizedPath, version, content, coalescedCount = 0, contentHash2) {
11722
+ const scan = scanDocumentContent(content);
11550
11723
  const previous = state4.documentContentHashes.get(normalizedPath);
11551
11724
  if (previous && previous.version > version) {
11552
11725
  incrementDegradationCount({
@@ -11562,7 +11735,7 @@ function recordSentContent(state4, normalizedPath, version, content, coalescedCo
11562
11735
  state4.incrementalTextBearingPaths?.delete(normalizedPath);
11563
11736
  }
11564
11737
  state4.documentContentHashes.delete(normalizedPath);
11565
- const hash = hashDiagnosticContent(content);
11738
+ const hash = contentHash2 ?? hashDiagnosticContent(content);
11566
11739
  state4.documentContentHashes.set(normalizedPath, {
11567
11740
  version,
11568
11741
  hash,
@@ -11629,7 +11802,7 @@ function buildContentChanges(state4, normalizedPath, content) {
11629
11802
  return [{ text: content }];
11630
11803
  }
11631
11804
  const previousText = previous.text;
11632
- const lastLine = previous.lastLine ?? scanSentContent(previousText).lastLine;
11805
+ const lastLine = previous.lastLine ?? scanDocumentContent(previousText).lastLine;
11633
11806
  const lastLineText = previousText.slice(lastLine.start);
11634
11807
  return [
11635
11808
  {
@@ -11704,6 +11877,128 @@ function resolveConfigurationSection(initialization, section) {
11704
11877
  }
11705
11878
  return cur;
11706
11879
  }
11880
+ var MAX_TRACKED_SERVER_MESSAGES = 8;
11881
+ function isConfigLoadFailureMessage(message) {
11882
+ 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);
11883
+ }
11884
+ function noteServerShowMessage(state4, params) {
11885
+ const raw = typeof params?.message === "string" ? params.message.trim() : "";
11886
+ if (!raw)
11887
+ return;
11888
+ const text = truncateForLedger(raw.replace(/\s+/g, " "));
11889
+ const type = typeof params?.type === "number" ? params.type : 4;
11890
+ const digest = hashDiagnosticContent(raw).slice(0, 12);
11891
+ const isConfigFailure = type === 1 && isConfigLoadFailureMessage(raw);
11892
+ let retractedPaths = 0;
11893
+ if (isConfigFailure && state4.configLoadFailure === void 0 && isAuxiliary({ role: state4.serverRole })) {
11894
+ state4.configLoadFailure = { message: text, atMs: Date.now() };
11895
+ retractedPaths = retractUnscannedEmptyPublications(state4);
11896
+ }
11897
+ const messages = state4.serverMessages ??= /* @__PURE__ */ new Map();
11898
+ const known = messages.has(digest);
11899
+ const cap = MAX_TRACKED_SERVER_MESSAGES + (isConfigFailure ? 1 : 0);
11900
+ if (!known && messages.size >= cap) {
11901
+ incrementDegradationCount({
11902
+ kind: "lsp-server-message",
11903
+ subject: `${state4.serverId}:showMessage-cap`,
11904
+ reason: `${type}: distinct showMessage texts reached ${MAX_TRACKED_SERVER_MESSAGES}; later ones are counted, not recorded`
11905
+ });
11906
+ return;
11907
+ }
11908
+ messages.set(digest, (messages.get(digest) ?? 0) + 1);
11909
+ emitBounded("lsp_server_message", `${state4.serverId}:message:${digest}`, {
11910
+ filePath: state4.root,
11911
+ durationMs: 0,
11912
+ metadata: {
11913
+ serverId: state4.serverId,
11914
+ messageType: type,
11915
+ message: text,
11916
+ ...isConfigFailure && { configLoadFailure: true },
11917
+ ...retractedPaths > 0 && { retractedPaths }
11918
+ }
11919
+ }, {
11920
+ ledgerKind: isConfigFailure ? "lsp-server-config-load-failed" : "lsp-server-message",
11921
+ reason: text,
11922
+ risingEdgePer: "identity"
11923
+ });
11924
+ }
11925
+ function answerPhase(state4, filePath) {
11926
+ return `${state4.rulesGeneration ?? 0}:${state4.documentVersions.get(filePath) ?? -1}`;
11927
+ }
11928
+ function auxiliaryEmptyIsNotEvidence(state4, filePath, docVersion) {
11929
+ const failure = state4.configLoadFailure;
11930
+ if (failure === void 0) {
11931
+ if (docVersion !== void 0)
11932
+ return false;
11933
+ const phase = answerPhase(state4, filePath);
11934
+ if (state4.nonEmptyAnswerPhases?.get(filePath) !== phase)
11935
+ return false;
11936
+ countPublication(state4, filePath);
11937
+ emitBounded(
11938
+ "lsp_publish_dropped_empty_after_finding",
11939
+ // Keyed per server and path, never per phase: a phase moves with every
11940
+ // edit, so a phase key would add one tally per edit for the session
11941
+ // (#4790 review F2, shape 46). The phase rides as a field.
11942
+ `${state4.serverId}:empty-after-finding:${filePath}`,
11943
+ {
11944
+ filePath,
11945
+ durationMs: 0,
11946
+ metadata: { serverId: state4.serverId, phase }
11947
+ },
11948
+ {
11949
+ ledgerKind: "lsp-auxiliary-empty-after-finding",
11950
+ reason: "empty publish dropped: a finding from the same rules generation and send stands",
11951
+ risingEdgePer: "identity"
11952
+ }
11953
+ );
11954
+ return true;
11955
+ }
11956
+ countPublication(state4, filePath);
11957
+ emitBounded("lsp_publish_dropped_server_config_failed", `${state4.serverId}:dropped:${filePath}`, {
11958
+ filePath,
11959
+ durationMs: 0,
11960
+ metadata: {
11961
+ serverId: state4.serverId,
11962
+ via: "publish",
11963
+ message: failure.message
11964
+ }
11965
+ }, {
11966
+ ledgerKind: "lsp-server-config-load-failed",
11967
+ reason: `empty publish dropped: ${failure.message}`,
11968
+ risingEdgePer: "identity"
11969
+ });
11970
+ return true;
11971
+ }
11972
+ function retractUnscannedEmptyPublications(state4) {
11973
+ let retracted = 0;
11974
+ const emptyStoredPaths = [];
11975
+ for (const [normalizedPath, diags] of state4.pushDiagnostics) {
11976
+ if (diags.length === 0)
11977
+ emptyStoredPaths.push(normalizedPath);
11978
+ }
11979
+ for (const normalizedPath of emptyStoredPaths) {
11980
+ state4.pushDiagnostics.delete(normalizedPath);
11981
+ state4.pushDiagnosticTimestamps.delete(normalizedPath);
11982
+ state4.diagnosticDocVersions.delete(normalizedPath);
11983
+ state4.diagnosticBindings.delete(normalizedPath);
11984
+ state4.diagnosticsVersionsByPath.delete(normalizedPath);
11985
+ retracted += 1;
11986
+ emitBounded("lsp_publish_dropped_server_config_failed", `${state4.serverId}:dropped:${normalizedPath}`, {
11987
+ filePath: normalizedPath,
11988
+ durationMs: 0,
11989
+ metadata: {
11990
+ serverId: state4.serverId,
11991
+ via: "retracted",
11992
+ message: state4.configLoadFailure?.message ?? ""
11993
+ }
11994
+ }, {
11995
+ ledgerKind: "lsp-server-config-load-failed",
11996
+ reason: `stored empty answer retracted: ${state4.configLoadFailure?.message ?? ""}`,
11997
+ risingEdgePer: "identity"
11998
+ });
11999
+ }
12000
+ return retracted;
12001
+ }
11707
12002
  function setupIncomingHandlers(state4, initialization, onDiagnosticsPublished) {
11708
12003
  state4.connection.onNotification("textDocument/publishDiagnostics", (params) => {
11709
12004
  const publishReceivedAt = Date.now();
@@ -11717,8 +12012,11 @@ function setupIncomingHandlers(state4, initialization, onDiagnosticsPublished) {
11717
12012
  countPublication(state4, normalizedPath);
11718
12013
  return;
11719
12014
  }
11720
- onDiagnosticsPublished?.(state4.serverId);
11721
12015
  const newDiags = normalizeLspDiagnostics(params.diagnostics || []);
12016
+ if (newDiags.length === 0 && auxiliaryEmptyIsNotEvidence(state4, normalizedPath, docVersion)) {
12017
+ return;
12018
+ }
12019
+ onDiagnosticsPublished?.(state4.serverId);
11722
12020
  const fence = state4.diagnosticFences.get(normalizedPath);
11723
12021
  if (docVersion === void 0 && fence) {
11724
12022
  fence.dropped += 1;
@@ -11744,7 +12042,8 @@ function setupIncomingHandlers(state4, initialization, onDiagnosticsPublished) {
11744
12042
  logExtension({
11745
12043
  subsystem: "lsp-pub",
11746
12044
  level: "debug",
11747
- message: `server=${state4.serverId} pubVersion=${docVersion} docVersion=${state4.documentVersions?.get(normalizedPath)} diags=${newDiags.length}`
12045
+ message: `server=${state4.serverId} pubVersion=${docVersion} docVersion=${state4.documentVersions?.get(normalizedPath)} diags=${newDiags.length}`,
12046
+ metadata: { path: normalizedPath }
11748
12047
  });
11749
12048
  }
11750
12049
  const strategy = getStrategy(state4.serverId, state4.launchVariant);
@@ -11802,6 +12101,11 @@ function setupIncomingHandlers(state4, initialization, onDiagnosticsPublished) {
11802
12101
  const currentVersion = state4.documentVersions.get(normalizedPath);
11803
12102
  return currentVersion !== void 0 && docVersion < currentVersion;
11804
12103
  };
12104
+ if (strategy.emptyUntilRulesRefreshed && !state4.rulesGeneration && newDiags.length === 0 && !state4.pushDiagnostics.has(normalizedPath) && !state4.pendingDiagnostics.has(normalizedPath)) {
12105
+ state4.heldEmptyPublishes = (state4.heldEmptyPublishes ?? 0) + 1;
12106
+ countPublication(state4, normalizedPath);
12107
+ return;
12108
+ }
11805
12109
  if (strategy.emptyFirstPublish === "indexing" && !state4.emptyFirstPublishHoldSpent && newDiags.length === 0 && !state4.pushDiagnostics.has(normalizedPath) && !state4.pendingDiagnostics.has(normalizedPath)) {
11806
12110
  state4.emptyFirstPublishHoldSpent = true;
11807
12111
  logLatency({
@@ -11814,17 +12118,27 @@ function setupIncomingHandlers(state4, initialization, onDiagnosticsPublished) {
11814
12118
  emptyFirstPublish: strategy.emptyFirstPublish,
11815
12119
  // `pubVersion`, the `[lsp-pub]` trace's own field name for the
11816
12120
  // publish's LSP document version — not a lifecycle identity, and
11817
- // not the retired glossary spelling (AGENTS.md "generation").
12121
+ // not the retired glossary spelling (docs/defect-shapes.md "session, turn or
12122
+ // generation lifecycle").
11818
12123
  pubVersion: docVersion ?? "push-unversioned"
11819
12124
  }
11820
12125
  });
11821
12126
  return;
11822
12127
  }
12128
+ if (newDiags.length > 0 && isAuxiliary({ role: state4.serverRole })) {
12129
+ (state4.nonEmptyAnswerPhases ??= /* @__PURE__ */ new Map()).set(normalizedPath, answerPhase(state4, normalizedPath));
12130
+ }
11823
12131
  if (strategy.seedFirstPush && !state4.pushDiagnostics.has(normalizedPath)) {
11824
12132
  if (isSupersededPush()) {
11825
12133
  countPublication(state4, normalizedPath);
11826
12134
  return;
11827
12135
  }
12136
+ const olderTimer = state4.pendingDiagnostics.get(normalizedPath);
12137
+ if (olderTimer) {
12138
+ clearTimeout(olderTimer);
12139
+ state4.pendingDiagnostics.delete(normalizedPath);
12140
+ countPublication(state4, normalizedPath);
12141
+ }
11828
12142
  state4.pushDiagnostics.set(normalizedPath, newDiags);
11829
12143
  state4.pushDiagnosticTimestamps.set(normalizedPath, Date.now());
11830
12144
  recordDocVersion();
@@ -11843,6 +12157,11 @@ function setupIncomingHandlers(state4, initialization, onDiagnosticsPublished) {
11843
12157
  state4.pendingDiagnostics.delete(normalizedPath);
11844
12158
  if (isSupersededPush()) {
11845
12159
  countPublication(state4, normalizedPath);
12160
+ state4.diagnosticEmitter.emit(PENDING_RECEIPT_DROPPED, normalizedPath);
12161
+ return;
12162
+ }
12163
+ if (newDiags.length === 0 && auxiliaryEmptyIsNotEvidence(state4, normalizedPath, docVersion)) {
12164
+ state4.diagnosticEmitter.emit(PENDING_RECEIPT_DROPPED, normalizedPath);
11846
12165
  return;
11847
12166
  }
11848
12167
  state4.pushDiagnostics.set(normalizedPath, newDiags);
@@ -11926,7 +12245,14 @@ function setupIncomingHandlers(state4, initialization, onDiagnosticsPublished) {
11926
12245
  });
11927
12246
  state4.connection.onRequest("window/workDoneProgress/create", async () => {
11928
12247
  });
11929
- state4.connection.onNotification("semgrep/rulesRefreshed", () => rebaselineForRulesRefresh(state4));
12248
+ state4.connection.onNotification("window/showMessage", (params) => {
12249
+ noteServerShowMessage(state4, params);
12250
+ });
12251
+ state4.connection.onNotification("semgrep/rulesRefreshed", () => {
12252
+ state4.rulesGeneration = (state4.rulesGeneration ?? 0) + 1;
12253
+ delete state4.configLoadFailure;
12254
+ rebaselineForRulesRefresh(state4);
12255
+ });
11930
12256
  let refreshRepullRunning = false;
11931
12257
  let refreshRepullRerunRequested = false;
11932
12258
  const runRefreshRepullPool = async () => {
@@ -12437,11 +12763,23 @@ async function clientWaitForDiagnostics(state4, filePath, timeoutMs, options = {
12437
12763
  return;
12438
12764
  }
12439
12765
  }
12440
- if (hasFreshDiagnostics() && !isVersionStale() && getMergedDiagnosticsForPath(state4, normalizedPath).length > 0) {
12766
+ const laterReceiptPending = () => state4.pendingDiagnostics.has(normalizedPath);
12767
+ const storedAnswerSettles = () => hasFreshDiagnostics() && !isVersionStale() && getMergedDiagnosticsForPath(state4, normalizedPath).length > 0;
12768
+ if (storedAnswerSettles() && !laterReceiptPending()) {
12441
12769
  return;
12442
12770
  }
12771
+ const answerStored = () => hasFreshDiagnostics() && !isVersionStale() && (state4.pushDiagnostics.has(normalizedPath) || state4.documentPullDiagnostics.has(normalizedPath));
12443
12772
  return new Promise((resolve8) => {
12444
12773
  let debounceTimer;
12774
+ let settleDeferred = storedAnswerSettles();
12775
+ const finish = () => {
12776
+ if (debounceTimer)
12777
+ clearTimeout(debounceTimer);
12778
+ state4.diagnosticEmitter.off("diagnostics", onDiagnostics);
12779
+ state4.diagnosticEmitter.off(PENDING_RECEIPT_DROPPED, onReceiptDropped);
12780
+ clearTimeout(timeout);
12781
+ resolve8();
12782
+ };
12445
12783
  const onDiagnostics = (fp) => {
12446
12784
  if (normalizeMapKey(fp) !== normalizedPath)
12447
12785
  return;
@@ -12454,18 +12792,25 @@ async function clientWaitForDiagnostics(state4, filePath, timeoutMs, options = {
12454
12792
  const timeSincePush = hit ? Date.now() - hit : Infinity;
12455
12793
  const remaining = Math.max(0, strategy.debounceMs - timeSincePush);
12456
12794
  debounceTimer = setTimeout(() => {
12457
- state4.diagnosticEmitter.off("diagnostics", onDiagnostics);
12458
- clearTimeout(timeout);
12459
- resolve8();
12795
+ debounceTimer = void 0;
12796
+ if (laterReceiptPending()) {
12797
+ settleDeferred = true;
12798
+ return;
12799
+ }
12800
+ if (!answerStored())
12801
+ return;
12802
+ finish();
12460
12803
  }, remaining);
12461
12804
  };
12805
+ const onReceiptDropped = (fp) => {
12806
+ if (normalizeMapKey(fp) !== normalizedPath)
12807
+ return;
12808
+ if (settleDeferred && answerStored())
12809
+ finish();
12810
+ };
12462
12811
  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);
12812
+ state4.diagnosticEmitter.on(PENDING_RECEIPT_DROPPED, onReceiptDropped);
12813
+ const timeout = setTimeout(finish, timeoutMs);
12469
12814
  });
12470
12815
  }
12471
12816
  function handleNotifyExternalChange(state4, filePath, type) {
@@ -12491,15 +12836,25 @@ function watchedTypeForExisting(state4, normalizedPath, info) {
12491
12836
  }
12492
12837
  return state4.createdAnnounced?.has(normalizedPath) ? FILE_CHANGED : FILE_CREATED;
12493
12838
  }
12494
- function handleAnnounceCreated(state4, entries) {
12839
+ async function handleAnnounceCreated(state4, entries) {
12495
12840
  if (!isClientAlive(state4))
12496
12841
  return;
12842
+ const didCreateUris = [];
12497
12843
  for (const { filePath, stat: info } of entries) {
12498
12844
  const normalizedPath = normalizeMapKey(filePath);
12499
12845
  if (watchedTypeForExisting(state4, normalizedPath, info) !== FILE_CREATED) {
12500
12846
  continue;
12501
12847
  }
12502
- enqueueWatchedChange(state4, normalizedPath, state4.openDocumentUris?.get(normalizedPath) ?? pathToFileURL2(filePath).href, FILE_CREATED);
12848
+ const uri = state4.openDocumentUris?.get(normalizedPath) ?? pathToFileURL2(filePath).href;
12849
+ enqueueWatchedChange(state4, normalizedPath, uri, FILE_CREATED);
12850
+ if (await fileOperationFiltersMatch(state4.fileOperationFilters?.didCreate, uri, uri, filePath, filePath)) {
12851
+ didCreateUris.push(uri);
12852
+ }
12853
+ }
12854
+ if (didCreateUris.length > 0 && isClientAlive(state4)) {
12855
+ await safeSendNotification(state4.connection, "workspace/didCreateFiles", {
12856
+ files: didCreateUris.map((uri) => ({ uri }))
12857
+ });
12503
12858
  }
12504
12859
  state4.watchQueue.flushIfCreated();
12505
12860
  }
@@ -12565,7 +12920,7 @@ function recordDidSaveSendFailed(state4, normalizedPath) {
12565
12920
  metadata: { filePath: normalizedPath }
12566
12921
  });
12567
12922
  }
12568
- async function handleNotifyOpenOnce(state4, filePath, content, languageId, preserveDiagnostics = false, silent = false, coalescedCount = 0, saved = false) {
12923
+ async function handleNotifyOpenOnce(state4, filePath, content, languageId, preserveDiagnostics = false, silent = false, coalescedCount = 0, saved = false, contentHash2) {
12569
12924
  if (!isClientAlive(state4))
12570
12925
  return false;
12571
12926
  const normalizedPath = normalizeMapKey(filePath);
@@ -12589,7 +12944,7 @@ async function handleNotifyOpenOnce(state4, filePath, content, languageId, prese
12589
12944
  return false;
12590
12945
  const reopenSent = await safeSendNotification(state4.connection, "textDocument/didOpen", { textDocument: { uri, languageId, version, text: content } });
12591
12946
  if (reopenSent)
12592
- recordSentContent(state4, normalizedPath, version, content, coalescedCount);
12947
+ recordSentContent(state4, normalizedPath, version, content, coalescedCount, contentHash2);
12593
12948
  state4.openDocuments.add(normalizedPath);
12594
12949
  state4.openDocumentUris?.set(normalizedPath, uri);
12595
12950
  if (saved && reopenSent)
@@ -12601,7 +12956,7 @@ async function handleNotifyOpenOnce(state4, filePath, content, languageId, prese
12601
12956
  contentChanges: buildContentChanges(state4, normalizedPath, content)
12602
12957
  });
12603
12958
  if (changeSent)
12604
- recordSentContent(state4, normalizedPath, version, content, coalescedCount);
12959
+ recordSentContent(state4, normalizedPath, version, content, coalescedCount, contentHash2);
12605
12960
  if (saved && changeSent)
12606
12961
  await sendDidSave(state4, normalizedPath, uri, content);
12607
12962
  return changeSent;
@@ -12618,19 +12973,25 @@ async function handleNotifyOpenOnce(state4, filePath, content, languageId, prese
12618
12973
  if (!silent) {
12619
12974
  let watchedType = FILE_CREATED;
12620
12975
  let onDisk = false;
12976
+ let info;
12621
12977
  try {
12622
- const info = await stat2(filePath);
12978
+ info = await stat2(filePath);
12623
12979
  onDisk = true;
12624
12980
  watchedType = watchedTypeForExisting(state4, normalizedPath, info);
12625
12981
  } catch {
12626
12982
  }
12983
+ if (info && watchedType === FILE_CREATED && await fileOperationFiltersMatch(state4.fileOperationFilters?.didCreate, uri, uri, filePath, filePath)) {
12984
+ await safeSendNotification(state4.connection, "workspace/didCreateFiles", {
12985
+ files: [{ uri }]
12986
+ });
12987
+ }
12627
12988
  enqueueWatchedChange(state4, normalizedPath, uri, watchedType, onDisk);
12628
12989
  }
12629
12990
  if (!isClientAlive(state4))
12630
12991
  return false;
12631
12992
  const openSent = await sendFenced(state4, normalizedPath, uri, "textDocument/didOpen", { textDocument: { uri, languageId, version: 0, text: content } });
12632
12993
  if (openSent)
12633
- recordSentContent(state4, normalizedPath, 0, content, coalescedCount);
12994
+ recordSentContent(state4, normalizedPath, 0, content, coalescedCount, contentHash2);
12634
12995
  state4.pendingOpens.delete(normalizedPath);
12635
12996
  state4.openDocuments.add(normalizedPath);
12636
12997
  state4.closedDocuments?.delete(normalizedPath);
@@ -12740,11 +13101,11 @@ function handleNotifySave(state4, filePath, onlyIfOwed = false) {
12740
13101
  const normalizedPath = normalizeMapKey(filePath);
12741
13102
  return enqueueDocumentNotify(state4, normalizedPath, (_count, _saved, debtOnly) => sendDidSaveForHeldDocument(state4, normalizedPath, debtOnly), true, void 0, false, true, onlyIfOwed);
12742
13103
  }
12743
- function handleNotifyOpen(state4, filePath, content, languageId, preserveDiagnostics = false, silent = false, saved = false, readStamp) {
13104
+ function handleNotifyOpen(state4, filePath, content, languageId, preserveDiagnostics = false, silent = false, saved = false, readStamp, contentHash2) {
12744
13105
  const normalizedPath = normalizeMapKey(filePath);
12745
- return enqueueDocumentNotify(state4, normalizedPath, (coalescedCount, queuedSaved) => handleNotifyOpenOnce(state4, filePath, content, languageId, preserveDiagnostics, silent, coalescedCount, queuedSaved), saved, readStamp);
13106
+ return enqueueDocumentNotify(state4, normalizedPath, (coalescedCount, queuedSaved) => handleNotifyOpenOnce(state4, filePath, content, languageId, preserveDiagnostics, silent, coalescedCount, queuedSaved, contentHash2), saved, readStamp);
12746
13107
  }
12747
- async function handleNotifyChangeOnce(state4, filePath, content, normalizedPath, coalescedCount = 0, saved = false) {
13108
+ async function handleNotifyChangeOnce(state4, filePath, content, normalizedPath, coalescedCount = 0, saved = false, contentHash2) {
12748
13109
  if (!isClientAlive(state4))
12749
13110
  return false;
12750
13111
  const uri = state4.openDocumentUris?.get(normalizedPath) ?? pathToFileURL2(filePath).href;
@@ -12763,7 +13124,7 @@ async function handleNotifyChangeOnce(state4, filePath, content, normalizedPath,
12763
13124
  state4.documentOpenedAt.set(normalizedPath, Date.now());
12764
13125
  state4.diagnosticPublicationCounts.set(normalizedPath, 0);
12765
13126
  if (fallbackOpenSent)
12766
- recordSentContent(state4, normalizedPath, 0, content, coalescedCount);
13127
+ recordSentContent(state4, normalizedPath, 0, content, coalescedCount, contentHash2);
12767
13128
  state4.openDocuments.add(normalizedPath);
12768
13129
  state4.closedDocuments?.delete(normalizedPath);
12769
13130
  state4.openDocumentUris?.set(normalizedPath, uri);
@@ -12779,14 +13140,14 @@ async function handleNotifyChangeOnce(state4, filePath, content, normalizedPath,
12779
13140
  contentChanges: buildContentChanges(state4, normalizedPath, content)
12780
13141
  });
12781
13142
  if (changeSent)
12782
- recordSentContent(state4, normalizedPath, version, content, coalescedCount);
13143
+ recordSentContent(state4, normalizedPath, version, content, coalescedCount, contentHash2);
12783
13144
  if (saved && changeSent)
12784
13145
  await sendDidSave(state4, normalizedPath, uri, content);
12785
13146
  return changeSent;
12786
13147
  }
12787
- function handleNotifyChange(state4, filePath, content) {
13148
+ function handleNotifyChange(state4, filePath, content, contentHash2) {
12788
13149
  const normalizedPath = normalizeMapKey(filePath);
12789
- return enqueueDocumentNotify(state4, normalizedPath, (coalescedCount, queuedSaved) => handleNotifyChangeOnce(state4, filePath, content, normalizedPath, coalescedCount, queuedSaved));
13150
+ return enqueueDocumentNotify(state4, normalizedPath, (coalescedCount, queuedSaved) => handleNotifyChangeOnce(state4, filePath, content, normalizedPath, coalescedCount, queuedSaved, contentHash2));
12790
13151
  }
12791
13152
  async function closedAndGone(state4, filePath, normalizedPath) {
12792
13153
  if (!state4.closedDocuments?.has(normalizedPath))
@@ -13145,14 +13506,20 @@ async function runReadOnlyServerCommand(state4, command, args, timeoutMs = PROBE
13145
13506
  reason: `command "${command}" is not advertised by the ${state4.serverId} server`
13146
13507
  };
13147
13508
  }
13509
+ const abandon = new AbortController();
13510
+ const request = safeSendRequest(state4.connection, "workspace/executeCommand", { command, arguments: args ?? [] }, abandon.signal, void 0, true);
13148
13511
  try {
13149
- const result = await withTimeout(safeSendRequest(state4.connection, "workspace/executeCommand", {
13150
- command,
13151
- arguments: args ?? []
13152
- }), timeoutMs);
13512
+ const result = await withTimeout(request, timeoutMs);
13153
13513
  return { executed: true, result };
13154
13514
  } catch (err) {
13155
13515
  if (err instanceof Error && err.message.startsWith("Timeout after")) {
13516
+ abandon.abort();
13517
+ await request;
13518
+ recordDegradationOnce({
13519
+ kind: "lsp-readonly-command-released",
13520
+ subject: state4.serverId,
13521
+ reason: `${command} timed out after ${timeoutMs}ms; the request was cancelled and released locally`
13522
+ });
13156
13523
  return {
13157
13524
  executed: false,
13158
13525
  reason: `workspace/executeCommand timed out after ${timeoutMs}ms`
@@ -13244,7 +13611,7 @@ function hasNotifyInFlightFor(state4, filePath) {
13244
13611
  }
13245
13612
  async function createLSPClient(options) {
13246
13613
  installCrashGuard();
13247
- const { serverId, process: lspProcess, root, sessionCwd, initialization, initializeTimeoutMs = INITIALIZE_TIMEOUT_MS, launchVariant, onDiagnosticsPublished } = options;
13614
+ const { serverId, process: lspProcess, root, sessionCwd, initialization, initializeTimeoutMs = INITIALIZE_TIMEOUT_MS, launchVariant, settingsSection, role, onDiagnosticsPublished } = options;
13248
13615
  void recordLspChild({
13249
13616
  pid: lspProcess.pid,
13250
13617
  serverId,
@@ -13354,8 +13721,12 @@ async function createLSPClient(options) {
13354
13721
  pullRequestSequences: /* @__PURE__ */ new Map(),
13355
13722
  workspacePullResultCache: /* @__PURE__ */ new Map(),
13356
13723
  openDocuments: /* @__PURE__ */ new Set(),
13724
+ // #4764: the declared role, so a config-load failure gates only an
13725
+ // auxiliary scanner's empty publications.
13726
+ ...role !== void 0 && { serverRole: role },
13357
13727
  // #3310: one-shot, per client session.
13358
13728
  emptyFirstPublishHoldSpent: false,
13729
+ rulesGeneration: 0,
13359
13730
  diagnosticFences: /* @__PURE__ */ new Map(),
13360
13731
  closedDocuments: /* @__PURE__ */ new Set(),
13361
13732
  openDocumentUris: /* @__PURE__ */ new Map(),
@@ -13396,7 +13767,8 @@ async function createLSPClient(options) {
13396
13767
  // holds one are refused.
13397
13768
  (uris) => noteWorkspaceFileCreated(state4.serverId, state4.root, uris.map(uriToPath))
13398
13769
  );
13399
- setupIncomingHandlers(state4, initialization, onDiagnosticsPublished);
13770
+ const settings = settingsSection && initialization ? { [settingsSection]: initialization } : initialization;
13771
+ setupIncomingHandlers(state4, settings, onDiagnosticsPublished);
13400
13772
  connection.listen();
13401
13773
  setupConnectionLifecycle(state4, recentStderr);
13402
13774
  let initResult;
@@ -13453,7 +13825,7 @@ async function createLSPClient(options) {
13453
13825
  const fileOperations = isCapabilityRecord(workspace) ? workspace.fileOperations : void 0;
13454
13826
  const malformedFileOperationRegistrations = /* @__PURE__ */ new Set();
13455
13827
  if (isCapabilityRecord(fileOperations)) {
13456
- for (const operation of ["willRename", "didRename"]) {
13828
+ for (const operation of ["didCreate", "willRename", "didRename"]) {
13457
13829
  if (fileOperations[operation] !== void 0 && parseFileOperationFilters(fileOperations[operation]) === void 0) {
13458
13830
  malformedFileOperationRegistrations.add(operation);
13459
13831
  }
@@ -13462,6 +13834,7 @@ async function createLSPClient(options) {
13462
13834
  state4.fileOperationMalformedRegistrations = malformedFileOperationRegistrations;
13463
13835
  if (isCapabilityRecord(fileOperations)) {
13464
13836
  state4.fileOperationFilters = {
13837
+ didCreate: parseFileOperationFilters(fileOperations.didCreate),
13465
13838
  willRename: parseFileOperationFilters(fileOperations.willRename),
13466
13839
  didRename: parseFileOperationFilters(fileOperations.didRename)
13467
13840
  };
@@ -13475,9 +13848,9 @@ async function createLSPClient(options) {
13475
13848
  }
13476
13849
  state4.staticDiagnosticsMode = state4.workspaceDiagnosticsSupport.mode;
13477
13850
  await safeSendNotification(connection, "initialized", {});
13478
- if (initialization) {
13851
+ if (settings) {
13479
13852
  await safeSendNotification(connection, "workspace/didChangeConfiguration", {
13480
- settings: initialization
13853
+ settings
13481
13854
  });
13482
13855
  }
13483
13856
  return {
@@ -13504,11 +13877,11 @@ async function createLSPClient(options) {
13504
13877
  /** #2358: the OS pid of the live server process (see interface doc). */
13505
13878
  getProcessPid: () => lspProcess.pid,
13506
13879
  notify: {
13507
- async open(filePath, content, languageId, preserveDiagnostics, silent, saved, readStamp) {
13508
- return handleNotifyOpen(state4, filePath, content, languageId, preserveDiagnostics, silent, saved, readStamp);
13880
+ async open(filePath, content, languageId, preserveDiagnostics, silent, saved, readStamp, contentHash2) {
13881
+ return handleNotifyOpen(state4, filePath, content, languageId, preserveDiagnostics, silent, saved, readStamp, contentHash2);
13509
13882
  },
13510
- async change(filePath, content) {
13511
- return handleNotifyChange(state4, filePath, content);
13883
+ async change(filePath, content, contentHash2) {
13884
+ return handleNotifyChange(state4, filePath, content, contentHash2);
13512
13885
  },
13513
13886
  save(filePath, onlyIfOwed) {
13514
13887
  return handleNotifySave(state4, filePath, onlyIfOwed);
@@ -13521,12 +13894,21 @@ async function createLSPClient(options) {
13521
13894
  state4.watchQueue.flush();
13522
13895
  },
13523
13896
  announceCreated(entries) {
13524
- handleAnnounceCreated(state4, entries);
13897
+ handleAnnounceCreated(state4, entries).catch((cause) => {
13898
+ incrementDegradationCount({
13899
+ kind: "lsp-sibling-announcement",
13900
+ subject: `${state4.serverId}:workspace/didCreateFiles`,
13901
+ reason: `didCreateFiles failed: ${String(cause)}`
13902
+ });
13903
+ });
13525
13904
  }
13526
13905
  },
13527
13906
  getDiagnostics(filePath) {
13528
13907
  return getMergedDiagnosticsForPath(state4, normalizeMapKey(filePath));
13529
13908
  },
13909
+ getConfigLoadFailure() {
13910
+ return state4.configLoadFailure?.message;
13911
+ },
13530
13912
  getDiagnosticBinding(filePath) {
13531
13913
  return state4.diagnosticBindings.get(normalizeMapKey(filePath));
13532
13914
  },
@@ -13869,17 +14251,28 @@ async function safeSendNotification(connection, method, params) {
13869
14251
  }
13870
14252
  }
13871
14253
  var activeRequestsByConnection = /* @__PURE__ */ new WeakMap();
14254
+ var RELEASED_ON_ABORT = /* @__PURE__ */ Symbol("released-on-abort");
13872
14255
  function isConnectionBusy(connection) {
13873
14256
  return (activeRequestsByConnection.get(connection) ?? 0) > 0;
13874
14257
  }
13875
- async function safeSendRequest(connection, method, params, signal, settlement) {
14258
+ async function safeSendRequest(connection, method, params, signal, settlement, releaseOnAbort = false) {
13876
14259
  if (signal?.aborted)
13877
14260
  return void 0;
13878
14261
  let tokenSource;
13879
14262
  let onAbort;
14263
+ let released;
14264
+ let release;
13880
14265
  if (signal) {
13881
14266
  tokenSource = new import_node.CancellationTokenSource();
13882
- onAbort = () => tokenSource?.cancel();
14267
+ if (releaseOnAbort) {
14268
+ released = new Promise((resolve8) => {
14269
+ release = () => resolve8(RELEASED_ON_ABORT);
14270
+ });
14271
+ }
14272
+ onAbort = () => {
14273
+ tokenSource?.cancel();
14274
+ release?.();
14275
+ };
13883
14276
  signal.addEventListener("abort", onAbort, { once: true });
13884
14277
  }
13885
14278
  const send = () => tokenSource ? connection.sendRequest(method, params, tokenSource.token) : connection.sendRequest(method, params);
@@ -13888,7 +14281,12 @@ async function safeSendRequest(connection, method, params, signal, settlement) {
13888
14281
  const MAX_ATTEMPTS = 2;
13889
14282
  for (let attempt = 1; ; attempt++) {
13890
14283
  try {
13891
- return await send();
14284
+ if (!released)
14285
+ return await send();
14286
+ const reply = await Promise.race([send(), released]);
14287
+ if (reply === RELEASED_ON_ABORT)
14288
+ return void 0;
14289
+ return reply;
13892
14290
  } catch (err) {
13893
14291
  if (isCancellationError(err)) {
13894
14292
  if (settlement)
@@ -14011,6 +14409,7 @@ function detectOperationSupport(initResult) {
14011
14409
  rename: hasProvider("renameProvider"),
14012
14410
  willRenameFiles: isCapabilityRecord(fileOperations) && isFileOperationRegistrationOptions(fileOperations.willRename),
14013
14411
  didRenameFiles: isCapabilityRecord(fileOperations) && isFileOperationRegistrationOptions(fileOperations.didRename),
14412
+ didCreateFiles: isCapabilityRecord(fileOperations) && isFileOperationRegistrationOptions(fileOperations.didCreate),
14014
14413
  implementation: hasProvider("implementationProvider"),
14015
14414
  callHierarchy: hasProvider("callHierarchyProvider")
14016
14415
  };
@@ -14189,6 +14588,16 @@ var ClientRegistry = class {
14189
14588
  inFlight = /* @__PURE__ */ new Map();
14190
14589
  /** Epoch ms of each key's last successful spawn. */
14191
14590
  clientSpawnedAt = /* @__PURE__ */ new Map();
14591
+ /**
14592
+ * Epoch ms each live client's LAUNCH began, before its process read the
14593
+ * tree (#4532 round 5, review F6). The install look compares an install
14594
+ * against this: `clientSpawnedAt` is stamped after the initialize handshake,
14595
+ * so an install that landed while the server was starting read as older
14596
+ * than the client and became the baseline. Kept apart from
14597
+ * `clientSpawnedAt` because the #1127 breaker measures post-init uptime from
14598
+ * that one. Same key and lifetime: written beside it, retired with it.
14599
+ */
14600
+ clientLaunchStartedAt = /* @__PURE__ */ new Map();
14192
14601
  hooks;
14193
14602
  sessionCwd;
14194
14603
  workspaceProbeLogged = /* @__PURE__ */ new Set();
@@ -14512,6 +14921,7 @@ var ClientRegistry = class {
14512
14921
  this.hooks.releaseNotifyWrite(key);
14513
14922
  this.clients.delete(key);
14514
14923
  this.clientSpawnedAt.delete(key);
14924
+ this.clientLaunchStartedAt.delete(key);
14515
14925
  this.hooks.forgetReadiness(key);
14516
14926
  this.clientLastUsedAt.delete(key);
14517
14927
  if (this.adoptedClientKeys.delete(key)) {
@@ -14523,8 +14933,14 @@ var ClientRegistry = class {
14523
14933
  this.hooks.forgetNotifyBacklog(key);
14524
14934
  }
14525
14935
  scheduleIdleEviction(key, server) {
14526
- if (server.idleEviction !== "transparent" && !this.adoptedClientKeys.has(key))
14936
+ if (server.idleEviction !== "transparent" && !this.adoptedClientKeys.has(key)) {
14937
+ recordDegradationOnce({
14938
+ kind: "lsp-idle-eviction-declined",
14939
+ subject: server.id,
14940
+ reason: `no idle-eviction timer: declared ${server.idleEviction ?? "unmeasured"}`
14941
+ });
14527
14942
  return;
14943
+ }
14528
14944
  this.clearIdleEvictionTimer(key);
14529
14945
  const lastUsedAt = this.clientLastUsedAt.get(key) ?? Date.now();
14530
14946
  const { root } = parseClientKey(key);
@@ -14594,6 +15010,37 @@ var ClientRegistry = class {
14594
15010
  recordBreaker(key, reason) {
14595
15011
  recordDegradationOnce({ kind: "lsp-breaker", subject: key, reason });
14596
15012
  }
15013
+ /**
15014
+ * #4532: the roots of the live PRIMARY clients, each with the epoch ms its
15015
+ * earliest live client at that root spawned. The out-of-band install look
15016
+ * runs at these roots as well as the session's cwd, so a dependency install
15017
+ * in a LINKED WORKTREE — a root the session cwd is not under — restarts that
15018
+ * worktree's server. Read-only: never spawns and never waits.
15019
+ *
15020
+ * The earliest spawn, not the latest: `restartPrimaryClientsUnder` retires
15021
+ * every primary overlapping a root, so a root whose newer client spawned
15022
+ * after an install must not hide an older one that read the pre-install
15023
+ * tree. The epoch is the client's LAUNCH start (`clientLaunchStartedAt`):
15024
+ * the server reads the tree from its spawn on, not from the end of its
15025
+ * initialize handshake. An absent stamp reports 0, which a first look reads
15026
+ * as "no epoch" and never as "before every install".
15027
+ */
15028
+ livePrimaryClientRoots() {
15029
+ const byRoot = /* @__PURE__ */ new Map();
15030
+ for (const [key, client] of this.clients) {
15031
+ if (!client.isAlive())
15032
+ continue;
15033
+ const { serverId, root } = parseClientKey(key);
15034
+ if (!root)
15035
+ continue;
15036
+ if (isAuxiliary(getServerById(serverId)))
15037
+ continue;
15038
+ const spawnedAt = this.clientLaunchStartedAt.get(key) ?? 0;
15039
+ const prior = byRoot.get(root);
15040
+ byRoot.set(root, prior === void 0 ? spawnedAt : Math.min(prior, spawnedAt));
15041
+ }
15042
+ return [...byRoot].map(([root, spawnedAt]) => ({ root, spawnedAt }));
15043
+ }
14597
15044
  /**
14598
15045
  * #1934 review F1: record what a `spawnClient` call decided, at the point
14599
15046
  * it decides it. Called on EVERY path that returns without a client, so
@@ -14650,6 +15097,15 @@ var ClientRegistry = class {
14650
15097
  const allowInstall = this.shouldAllowInstall(server.id);
14651
15098
  const normalizedRoot = normalizeMapKey(root);
14652
15099
  const key = `${server.id}:${normalizedRoot}`;
15100
+ if (declinesLooseFileRoot(server, root)) {
15101
+ recordDegradationOnce({
15102
+ kind: "lsp-root-declined",
15103
+ subject: key,
15104
+ reason: `LSP root declined for ${server.id}: root at or above $HOME`
15105
+ });
15106
+ this.noteSpawnVerdict(key, "declined");
15107
+ return void 0;
15108
+ }
14653
15109
  const adopted = this.analysisRootModeForFile(filePath) === "adopted";
14654
15110
  if (adopted) {
14655
15111
  const localCommand = server.command ?? server.projectLocalCommand ?? server.availabilityKey;
@@ -14857,6 +15313,15 @@ var ClientRegistry = class {
14857
15313
  this.noteSpawnVerdict(key, "declined");
14858
15314
  return void 0;
14859
15315
  }
15316
+ if (await declinesProjectlessRoot(server, root)) {
15317
+ recordDegradationOnce({
15318
+ kind: "lsp-root-declined",
15319
+ subject: key,
15320
+ reason: `LSP spawn declined for ${server.id}: no project file at or below ${root}`
15321
+ });
15322
+ this.noteSpawnVerdict(key, "declined");
15323
+ return void 0;
15324
+ }
14860
15325
  const isOptionalServer = OPTIONAL_LSP_SERVER_IDS.has(server.id);
14861
15326
  const startedAt = Date.now();
14862
15327
  logSessionStart(`lsp spawn ${server.id}: start root=${root} install=${allowInstall ? "enabled" : "disabled"} file=${filePath}`);
@@ -14909,6 +15374,10 @@ var ClientRegistry = class {
14909
15374
  initialization: mergedInit,
14910
15375
  initializeTimeoutMs: server.initializeTimeoutMs,
14911
15376
  launchVariant: spawned.launchVariant,
15377
+ settingsSection: server.settingsSection,
15378
+ // #4764: the declared role travels with the client, so a failed server
15379
+ // config can gate an auxiliary scanner's empty publications only.
15380
+ role: server.role,
14912
15381
  onDiagnosticsPublished: (serverId) => {
14913
15382
  this.hooks.noteDiagnosticsPublished(serverId);
14914
15383
  }
@@ -14931,6 +15400,7 @@ var ClientRegistry = class {
14931
15400
  this.unavailableLogged.delete(key);
14932
15401
  this.lastSpawnVerdict.delete(key);
14933
15402
  this.clientSpawnedAt.set(key, Date.now());
15403
+ this.clientLaunchStartedAt.set(key, startedAt);
14934
15404
  this.clientLastUsedAt.set(key, Date.now());
14935
15405
  this.scheduleIdleEviction(key, server);
14936
15406
  this.failureCounts.delete(key);
@@ -15178,6 +15648,9 @@ function getBasenameLanguageId(base) {
15178
15648
  return BASENAME_LANGUAGE_PATTERNS.find(({ pattern }) => pattern.test(base))?.languageId;
15179
15649
  }
15180
15650
  function getLanguageId2(filePath) {
15651
+ const declared = resolveFilenameLanguage(filePath);
15652
+ if (declared)
15653
+ return lspLanguageId(declared);
15181
15654
  const ext = path14.extname(filePath).toLowerCase();
15182
15655
  if (ext && LANGUAGE_EXTENSIONS[ext]) {
15183
15656
  return LANGUAGE_EXTENSIONS[ext];
@@ -15210,6 +15683,333 @@ function auxWaitBudgetMs(serverId, isCold, configuredCeilingMs, declaredWaitMs)
15210
15683
  return Math.min(MAX_ADAPTIVE_AUX_GRACE_CEILING_MS, Math.max(declaredWaitMs, observedSpawnMs + ADAPTIVE_AUX_GRACE_MARGIN_MS));
15211
15684
  }
15212
15685
 
15686
+ // dist/clients/lsp/inferred-project.js
15687
+ import * as path16 from "node:path";
15688
+
15689
+ // dist/clients/lsp/environment-gap.js
15690
+ import * as fs12 from "node:fs";
15691
+ import { isBuiltin } from "node:module";
15692
+ import * as path15 from "node:path";
15693
+ var ENVIRONMENT_GAP_MARKER = "no dependency install resolved for this workspace";
15694
+ 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]`;
15695
+ var TYPESCRIPT_DIAGNOSTIC_SOURCES = /* @__PURE__ */ new Set(["typescript", "ts", "tsserver"]);
15696
+ function isTypeScriptSourcedDiagnostic(d) {
15697
+ return TYPESCRIPT_DIAGNOSTIC_SOURCES.has((d.source ?? "").toLowerCase());
15698
+ }
15699
+ var TYPESCRIPT_SERVER_ID = "typescript";
15700
+ var ENV_NODE_MODULES_WALK_MAX_LEVELS = 32;
15701
+ var NODE_GLOBALS = /* @__PURE__ */ new Set([
15702
+ "process",
15703
+ "Buffer",
15704
+ "require",
15705
+ "module",
15706
+ "exports",
15707
+ "__dirname",
15708
+ "__filename",
15709
+ "global",
15710
+ "setTimeout",
15711
+ "clearTimeout",
15712
+ "setInterval",
15713
+ "clearInterval",
15714
+ "setImmediate",
15715
+ "clearImmediate",
15716
+ "queueMicrotask",
15717
+ "structuredClone",
15718
+ "URL",
15719
+ "URLSearchParams",
15720
+ "TextEncoder",
15721
+ "TextDecoder",
15722
+ "AbortController",
15723
+ "AbortSignal",
15724
+ "fetch",
15725
+ "performance"
15726
+ ]);
15727
+ var MISSING_MODULE = /^Cannot find module '([^']+)'/;
15728
+ var MISSING_NAMESPACE = /^Cannot find namespace '([^']+)'/;
15729
+ var MISSING_NAME = /^Cannot find name '([^']+)'/;
15730
+ var NODE_NAMESPACE = "NodeJS";
15731
+ var ENVIRONMENT_GAP_CODES = /* @__PURE__ */ new Set([2307, 2503, 2304, 2580, 2591]);
15732
+ var DECLARING_FIELDS = [
15733
+ "dependencies",
15734
+ "devDependencies",
15735
+ "peerDependencies",
15736
+ "optionalDependencies"
15737
+ ];
15738
+ function packageNameOf(specifier) {
15739
+ if (specifier.startsWith("@"))
15740
+ return /^@[^/]+\/[^/]+/.exec(specifier)?.[0];
15741
+ return specifier.split("/")[0];
15742
+ }
15743
+ var PACKAGE_NAME = /^(?:@[A-Za-z0-9~-][\w.~-]*\/)?[A-Za-z0-9~-][\w.~-]*$/;
15744
+ function admitPackageName(names, name) {
15745
+ if (PACKAGE_NAME.test(name))
15746
+ names.add(name);
15747
+ }
15748
+ function declaredPackageNames(startDir) {
15749
+ const names = /* @__PURE__ */ new Set();
15750
+ let dir = path15.resolve(startDir);
15751
+ for (let level = 0; level < ENV_NODE_MODULES_WALK_MAX_LEVELS; level++) {
15752
+ try {
15753
+ const manifest = JSON.parse(fs12.readFileSync(path15.join(dir, "package.json"), "utf8"));
15754
+ for (const field of DECLARING_FIELDS) {
15755
+ const declared = manifest[field];
15756
+ if (typeof declared !== "object" || declared === null)
15757
+ continue;
15758
+ if (Array.isArray(declared))
15759
+ continue;
15760
+ for (const name of Object.keys(declared)) {
15761
+ admitPackageName(names, name);
15762
+ if (!name.startsWith("@types/"))
15763
+ continue;
15764
+ const stem = name.slice("@types/".length);
15765
+ admitPackageName(names, stem.includes("__") ? `@${stem.replace("__", "/")}` : stem);
15766
+ }
15767
+ }
15768
+ } catch {
15769
+ }
15770
+ const parent = path15.dirname(dir);
15771
+ if (parent === dir)
15772
+ break;
15773
+ dir = parent;
15774
+ }
15775
+ return names;
15776
+ }
15777
+ function environmentGapKind(diagnostic) {
15778
+ if (diagnostic.severity !== 1)
15779
+ return void 0;
15780
+ if (!isTypeScriptSourcedDiagnostic(diagnostic))
15781
+ return void 0;
15782
+ if (diagnostic.serverId !== void 0 && diagnostic.serverId !== TYPESCRIPT_SERVER_ID)
15783
+ return void 0;
15784
+ const code = Number(diagnostic.code);
15785
+ if (!ENVIRONMENT_GAP_CODES.has(code))
15786
+ return void 0;
15787
+ const message = diagnostic.message.trim();
15788
+ if (code === 2307) {
15789
+ const specifier = MISSING_MODULE.exec(message)?.[1];
15790
+ return specifier === void 0 ? void 0 : { code, specifier };
15791
+ }
15792
+ if (code === 2503) {
15793
+ return MISSING_NAMESPACE.exec(message)?.[1] === NODE_NAMESPACE ? { code } : void 0;
15794
+ }
15795
+ const name = MISSING_NAME.exec(message)?.[1];
15796
+ return name !== void 0 && NODE_GLOBALS.has(name) ? { code } : void 0;
15797
+ }
15798
+ function hasResolvableNodeModules(startDir, stat3 = (candidate) => fs12.statSync(candidate)) {
15799
+ let dir = path15.resolve(startDir);
15800
+ for (let level = 0; level < ENV_NODE_MODULES_WALK_MAX_LEVELS; level++) {
15801
+ try {
15802
+ stat3(path15.join(dir, "node_modules"));
15803
+ return true;
15804
+ } catch (err) {
15805
+ if (err?.code !== "ENOENT") {
15806
+ return true;
15807
+ }
15808
+ }
15809
+ const parent = path15.dirname(dir);
15810
+ if (parent === dir)
15811
+ return false;
15812
+ dir = parent;
15813
+ }
15814
+ return true;
15815
+ }
15816
+ function demoteEnvironmentGapDiagnostics(diagnostics, options) {
15817
+ const candidates = /* @__PURE__ */ new Map();
15818
+ for (const diagnostic of diagnostics) {
15819
+ const kind = environmentGapKind(diagnostic);
15820
+ if (kind !== void 0)
15821
+ candidates.set(diagnostic, kind);
15822
+ }
15823
+ if (candidates.size === 0)
15824
+ return diagnostics;
15825
+ const startDir = options.startDir ?? path15.dirname(options.filePath);
15826
+ if (hasResolvableNodeModules(startDir, options.stat))
15827
+ return diagnostics;
15828
+ let declared;
15829
+ const admitted = /* @__PURE__ */ new Map();
15830
+ for (const [diagnostic, { code, specifier }] of candidates) {
15831
+ if (specifier !== void 0 && !isBuiltin(specifier)) {
15832
+ declared ??= declaredPackageNames(startDir);
15833
+ const name = packageNameOf(specifier);
15834
+ if (name === void 0 || !declared.has(name))
15835
+ continue;
15836
+ }
15837
+ admitted.set(diagnostic, code);
15838
+ }
15839
+ if (admitted.size === 0)
15840
+ return diagnostics;
15841
+ const startedAt = Date.now();
15842
+ const counts = /* @__PURE__ */ new Map();
15843
+ const demoted = diagnostics.map((diagnostic) => {
15844
+ const kind = admitted.get(diagnostic);
15845
+ if (kind === void 0)
15846
+ return diagnostic;
15847
+ counts.set(kind, (counts.get(kind) ?? 0) + 1);
15848
+ return {
15849
+ ...diagnostic,
15850
+ severity: 2,
15851
+ message: `${diagnostic.message} ${ENVIRONMENT_GAP_NOTICE}`
15852
+ };
15853
+ });
15854
+ for (const [code, count] of counts) {
15855
+ incrementDegradationCount({
15856
+ kind: "lsp-environment-gap-demoted",
15857
+ subject: String(code),
15858
+ 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`,
15859
+ metadata: { code, count, filePath: options.filePath }
15860
+ });
15861
+ }
15862
+ logLatency({
15863
+ type: "phase",
15864
+ phase: "lsp_environment_gap_demote",
15865
+ filePath: options.filePath,
15866
+ durationMs: Date.now() - startedAt,
15867
+ metadata: {
15868
+ demoted: demoted.length - (diagnostics.length - admitted.size),
15869
+ considered: diagnostics.length,
15870
+ codes: [...counts.keys()].sort((a, b) => a - b).join(",")
15871
+ }
15872
+ });
15873
+ return demoted;
15874
+ }
15875
+
15876
+ // dist/clients/lsp/inferred-project.js
15877
+ var INFERRED_PROJECT_MARKER = "not in any tsconfig project \u2014 checked with inferred settings";
15878
+ var TS_PROJECT_EXTENSIONS = /* @__PURE__ */ new Set([
15879
+ ".ts",
15880
+ ".tsx",
15881
+ ".mts",
15882
+ ".cts",
15883
+ ".js",
15884
+ ".jsx",
15885
+ ".mjs",
15886
+ ".cjs"
15887
+ ]);
15888
+ function isTsProjectFile(filePath) {
15889
+ return TS_PROJECT_EXTENSIONS.has(path16.extname(filePath).toLowerCase());
15890
+ }
15891
+ function suggestTsconfigInclude(filePath, cwd) {
15892
+ const relative3 = toProjectRelativePath(filePath, cwd);
15893
+ if (path16.posix.isAbsolute(relative3) || /^[A-Za-z]:/.test(relative3)) {
15894
+ const dir = relative3.slice(0, relative3.lastIndexOf("/"));
15895
+ return dir ? `${dir}/**` : relative3;
15896
+ }
15897
+ const segments = relative3.split("/").filter(Boolean);
15898
+ return segments.length > 1 ? `${segments[0]}/**` : relative3;
15899
+ }
15900
+ function inferredProjectNotice(filePath, cwd) {
15901
+ return `[${INFERRED_PROJECT_MARKER}; add ${suggestTsconfigInclude(filePath, cwd)} to a tsconfig for authoritative checking]`;
15902
+ }
15903
+ function applyInferredProjectDemotion(diagnostics, filePath, cwd) {
15904
+ if (!diagnostics.some(isDemotableDiagnostic))
15905
+ return diagnostics;
15906
+ const notice = inferredProjectNotice(filePath, cwd);
15907
+ return diagnostics.map((d) => isDemotableDiagnostic(d) ? { ...d, severity: 2, message: `${d.message} ${notice}` } : d);
15908
+ }
15909
+ function isDemotableDiagnostic(d) {
15910
+ return d.severity === 1 && isTypeScriptSourcedDiagnostic(d);
15911
+ }
15912
+ function hasInferredProjectCandidates(diagnostics, filePath) {
15913
+ return isTsProjectFile(filePath) && diagnostics.some(isDemotableDiagnostic);
15914
+ }
15915
+ async function demoteInferredProjectDiagnostics(diagnostics, options) {
15916
+ const { filePath, cwd, service } = options;
15917
+ if (!hasInferredProjectCandidates(diagnostics, filePath))
15918
+ return diagnostics;
15919
+ if (options.signal?.aborted)
15920
+ return diagnostics;
15921
+ const fetchIdentity = options.fetchIdentity ?? fetchTsserverProjectIdentity;
15922
+ const cache = options.identityCache;
15923
+ let identity;
15924
+ if (cache?.has(filePath)) {
15925
+ identity = cache.get(filePath);
15926
+ } else if (service === void 0) {
15927
+ return diagnostics;
15928
+ } else {
15929
+ identity = await fetchIdentity(service, filePath);
15930
+ cache?.set(filePath, identity);
15931
+ }
15932
+ if (identity?.projectKind !== "inferred")
15933
+ return diagnostics;
15934
+ return applyInferredProjectDemotion(diagnostics, filePath, cwd);
15935
+ }
15936
+ async function demoteLanguageServerRows(diagnostics, options) {
15937
+ const environmentChecked = demoteEnvironmentGapDiagnostics(diagnostics, {
15938
+ filePath: options.filePath
15939
+ });
15940
+ const membership = {
15941
+ ...options,
15942
+ identityCache: options.identityCache ?? /* @__PURE__ */ new Map()
15943
+ };
15944
+ const rows = await demoteInferredProjectDiagnostics(environmentChecked, membership);
15945
+ return {
15946
+ rows,
15947
+ replayable: async () => environmentChecked === diagnostics ? rows : demoteInferredProjectDiagnostics(diagnostics, membership)
15948
+ };
15949
+ }
15950
+ var INFERRED_PROJECT_PROBE_BUDGET = 300;
15951
+ async function demoteInferredProjectSweepResults(results, cwd, service, signal) {
15952
+ const startedAt = Date.now();
15953
+ const identityCache = /* @__PURE__ */ new Map();
15954
+ const out = [];
15955
+ let changed = false;
15956
+ let demotedFiles = 0;
15957
+ let demotedDiagnostics = 0;
15958
+ let budgetExhausted = false;
15959
+ let aborted = false;
15960
+ for (const result of results) {
15961
+ const raw = result.diagnostics ?? [];
15962
+ const diagnostics = demoteEnvironmentGapDiagnostics(raw, {
15963
+ filePath: result.filePath
15964
+ });
15965
+ const checked = diagnostics === raw ? result : { ...result, diagnostics };
15966
+ if (checked !== result)
15967
+ changed = true;
15968
+ if (signal?.aborted) {
15969
+ aborted = true;
15970
+ out.push(checked);
15971
+ continue;
15972
+ }
15973
+ if (identityCache.size >= INFERRED_PROJECT_PROBE_BUDGET && !identityCache.has(result.filePath)) {
15974
+ budgetExhausted = true;
15975
+ out.push(checked);
15976
+ continue;
15977
+ }
15978
+ const demoted = await demoteInferredProjectDiagnostics(diagnostics, {
15979
+ filePath: result.filePath,
15980
+ cwd,
15981
+ service,
15982
+ identityCache,
15983
+ signal
15984
+ });
15985
+ if (demoted === diagnostics) {
15986
+ out.push(checked);
15987
+ continue;
15988
+ }
15989
+ changed = true;
15990
+ demotedFiles += 1;
15991
+ demotedDiagnostics += demoted.filter((d, i) => d !== diagnostics[i]).length;
15992
+ out.push({ ...result, diagnostics: demoted });
15993
+ }
15994
+ if (demotedFiles > 0 || budgetExhausted || aborted) {
15995
+ logLatency({
15996
+ type: "phase",
15997
+ phase: "lsp_inferred_project_demote",
15998
+ filePath: cwd,
15999
+ durationMs: Date.now() - startedAt,
16000
+ metadata: {
16001
+ filesConsidered: results.length,
16002
+ filesProbed: identityCache.size,
16003
+ demotedFiles,
16004
+ demotedDiagnostics,
16005
+ budgetExhausted,
16006
+ aborted
16007
+ }
16008
+ });
16009
+ }
16010
+ return changed ? out : results;
16011
+ }
16012
+
15213
16013
  // dist/clients/lazy-import.js
15214
16014
  function createLazyImport(load) {
15215
16015
  let cached;
@@ -15227,7 +16027,7 @@ function createLazyImport(load) {
15227
16027
  }
15228
16028
 
15229
16029
  // dist/clients/lsp-lazy.js
15230
- var lazyLsp = createLazyImport(() => import("./chunk-KYUB6QDC.js"));
16030
+ var lazyLsp = createLazyImport(() => import("./chunk-2F47TQOA.js"));
15231
16031
  function warmLspService() {
15232
16032
  return lazyLsp.get();
15233
16033
  }
@@ -15319,8 +16119,8 @@ function destinationUriPreservingSpelling(oldUri, oldFilePath, newFilePath) {
15319
16119
  return canonical.href;
15320
16120
  }
15321
16121
  const canonicalDestination = () => `${original.protocol}//${authority}${canonical.pathname}`;
15322
- const oldParent = path15.resolve(path15.dirname(oldFilePath));
15323
- const newParent = path15.resolve(path15.dirname(newFilePath));
16122
+ const oldParent = path17.resolve(path17.dirname(oldFilePath));
16123
+ const newParent = path17.resolve(path17.dirname(newFilePath));
15324
16124
  if (normalizeMapKey(oldParent) !== normalizeMapKey(newParent)) {
15325
16125
  return canonicalDestination();
15326
16126
  }
@@ -15330,7 +16130,7 @@ function destinationUriPreservingSpelling(oldUri, oldFilePath, newFilePath) {
15330
16130
  let rawName = canonical.pathname.slice(canonical.pathname.lastIndexOf("/") + 1);
15331
16131
  const oldRawName = original.pathname.slice(slash + 1);
15332
16132
  const oldName = decodeURIComponent(oldRawName);
15333
- const expectedOldName = path15.basename(oldFilePath);
16133
+ const expectedOldName = path17.basename(oldFilePath);
15334
16134
  if (oldName.toLowerCase() !== expectedOldName.toLowerCase()) {
15335
16135
  return canonicalDestination();
15336
16136
  }
@@ -15520,7 +16320,7 @@ async function collectWorkspaceDiagnosticFiles(root, maxFiles = getMaxWorkspaceD
15520
16320
  return;
15521
16321
  if (entry.isSymbolicLink())
15522
16322
  continue;
15523
- const full = path15.join(current, entry.name);
16323
+ const full = path17.join(current, entry.name);
15524
16324
  if (entry.isDirectory()) {
15525
16325
  if (isExcludedDirName(entry.name))
15526
16326
  continue;
@@ -16614,19 +17414,23 @@ var LSPService = class _LSPService {
16614
17414
  * normal, expected answer.
16615
17415
  *
16616
17416
  * 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.
17417
+ * covers the BREAKER doors only (cooldown + permanent), plus the #4760
17418
+ * root-policy decline, which is a PERMANENT policy answer (the resolved
17419
+ * root is at or above `$HOME`) and never retries in this session.
17420
+ * `ensureClientForServer` also drops a scanner for a temporarily-unavailable
17421
+ * command (the #1496 latch), `optionalDisabled`, a spawn failure, or capacity
17422
+ * eviction. Those are the same defect class in the same lane, but they are
17423
+ * persistent-absence states rather than a transient blackout, so flagging
17424
+ * every touch partial for them is a broader behavior change than #1459 is
17425
+ * scoped to make. Tracked separately.
16623
17426
  */
16624
- async brokenSkippedAuxiliaryServerIds(filePath, clientScope, options, spawned) {
17427
+ async skippedAuxiliaryServerIds(filePath, clientScope, options, spawned) {
16625
17428
  if (clientScope === "primary")
16626
- return [];
17429
+ return { brokenSkippedServerIds: [], policySkippedServerIds: [] };
16627
17430
  const enabledAuxiliaries = clientScope === "with-auxiliary" ? new Set(options.auxiliaryServerIds ?? []) : void 0;
16628
17431
  const attached = new Set(spawned.map((entry) => entry.info.id));
16629
- const skipped = [];
17432
+ const brokenSkippedServerIds = [];
17433
+ const policySkippedServerIds = [];
16630
17434
  for (const server of getServersForFileWithConfig(filePath)) {
16631
17435
  if (!isAuxiliary(server))
16632
17436
  continue;
@@ -16636,15 +17440,20 @@ var LSPService = class _LSPService {
16636
17440
  continue;
16637
17441
  if (enabledAuxiliaries && !enabledAuxiliaries.has(server.id))
16638
17442
  continue;
16639
- const key = await this.demonstratedReadyKeyFor(server, filePath);
16640
- if (!key)
17443
+ const root = await this.clientRegistry.resolveServerRoot(server, filePath);
17444
+ if (!root)
17445
+ continue;
17446
+ if (declinesLooseFileRoot(server, root)) {
17447
+ policySkippedServerIds.push(server.id);
16641
17448
  continue;
17449
+ }
17450
+ const key = `${server.id}:${normalizeMapKey(root)}`;
16642
17451
  const brokenUntil = this.state.broken.get(key);
16643
17452
  if (this.clientRegistry.permanentlyBroken.has(key) || typeof brokenUntil === "number" && brokenUntil > Date.now()) {
16644
- skipped.push(server.id);
17453
+ brokenSkippedServerIds.push(server.id);
16645
17454
  }
16646
17455
  }
16647
- return skipped;
17456
+ return { brokenSkippedServerIds, policySkippedServerIds };
16648
17457
  }
16649
17458
  activeClientsForCwd(cwd, priorityServerIds = []) {
16650
17459
  const normalizedCwd = normalizeMapKey(cwd);
@@ -16659,7 +17468,7 @@ var LSPService = class _LSPService {
16659
17468
  const sameOrNested = root === normalizedCwd || root.startsWith(`${normalizedCwd}/`) || normalizedCwd.startsWith(`${root}/`);
16660
17469
  if (!sameOrNested)
16661
17470
  continue;
16662
- entries.push({ serverId, client });
17471
+ entries.push({ clientKey: key, serverId, client });
16663
17472
  }
16664
17473
  return entries.sort((a, b) => (priority.get(a.serverId) ?? Number.MAX_SAFE_INTEGER) - (priority.get(b.serverId) ?? Number.MAX_SAFE_INTEGER));
16665
17474
  }
@@ -16684,15 +17493,18 @@ var LSPService = class _LSPService {
16684
17493
  }
16685
17494
  return [...paths];
16686
17495
  }
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) {
17496
+ getTrackedContent(filePath, cwd, sourceClientKeys) {
16694
17497
  const priorityServerIds = getServersForFileWithConfig(filePath).map((server) => server.id);
16695
- for (const { client } of this.activeClientsForCwd(cwd, priorityServerIds)) {
17498
+ const clients = this.activeClientsForCwd(cwd, priorityServerIds);
17499
+ if (sourceClientKeys !== void 0) {
17500
+ const sourceSet = new Set(sourceClientKeys);
17501
+ const sends = clients.filter(({ clientKey }) => sourceSet.has(clientKey)).flatMap(({ clientKey, client }) => {
17502
+ const sent = client.getSentContent?.(filePath);
17503
+ return sent === void 0 ? [] : [{ ...sent, clientKey }];
17504
+ });
17505
+ return sends;
17506
+ }
17507
+ for (const { client } of clients) {
16696
17508
  const sent = client.getSentContent?.(filePath);
16697
17509
  if (sent !== void 0)
16698
17510
  return sent;
@@ -17139,6 +17951,19 @@ var LSPService = class _LSPService {
17139
17951
  return 0;
17140
17952
  return (await this.clientRegistry.restartPrimaryClientsUnder(root)).length;
17141
17953
  }
17954
+ /**
17955
+ * #4532: the roots of the live PRIMARY clients, each with the epoch ms its
17956
+ * earliest live client at that root spawned. The `tool_result` install look
17957
+ * runs at each of these roots as well as the session's cwd, so an install in
17958
+ * a LINKED WORKTREE restarts that worktree's server; before this, the look
17959
+ * only ever ran at the session cwd, and a worktree install reached no server
17960
+ * for 14 minutes (issue #4532 gap 7). Read-only: spawns nothing.
17961
+ */
17962
+ livePrimaryClientRoots() {
17963
+ if (this.checkDestroyed())
17964
+ return [];
17965
+ return this.clientRegistry.livePrimaryClientRoots();
17966
+ }
17142
17967
  /**
17143
17968
  * #4320: before a batch serves any cached answer, tell every live client the
17144
17969
  * batch's files that are new to its server and not yet announced to it, and
@@ -17193,6 +18018,21 @@ var LSPService = class _LSPService {
17193
18018
  * (for a server whose replies are `threaded` it proves only liveness).
17194
18019
  * `drained` requires measured single-task ordering and a successful probe;
17195
18020
  * threaded/unmeasured servers and timeouts are undrained.
18021
+ *
18022
+ * #4782: a server may check a document as soon as it reads its change, so a
18023
+ * dependent sent before its rewritten dependency is checked against the
18024
+ * dependency's old bytes, and its re-check after the dependency arrives is
18025
+ * the server's own timer, which can answer after the drain reply. No answer
18026
+ * carries the dependency's version, so no read can tell. A client whose
18027
+ * server `rechecks` unchanged bytes is therefore sent each document again,
18028
+ * after the last one it was sent, before the drain: the server's latest check
18029
+ * of each follows every change of this pass, and the re-send's version bump
18030
+ * lets a versioned server's older answer be dropped as superseded. The
18031
+ * re-send clears the path's stored answer, so the dispatch read waits for
18032
+ * the answer to it; the drain below runs only for `single-task-ordered`
18033
+ * clients, and no row declared `rechecks` is one. Both sends carry the stamp
18034
+ * taken before the read (#3481): a parallel tool's newer read of the same
18035
+ * path, sent in between, makes the queue drop this pass's older bytes.
17196
18036
  */
17197
18037
  async resyncHeldPrimaries(filePaths, drainMs) {
17198
18038
  let sent = 0;
@@ -17207,9 +18047,10 @@ var LSPService = class _LSPService {
17207
18047
  exclude.add(server.id);
17208
18048
  if (servers.every((server) => exclude.has(server.id)))
17209
18049
  continue;
18050
+ const readStamp = performance.now();
17210
18051
  let content;
17211
18052
  try {
17212
- content = await fs11.readFile(filePath, "utf8");
18053
+ content = await fs13.readFile(filePath, "utf8");
17213
18054
  } catch {
17214
18055
  continue;
17215
18056
  }
@@ -17217,7 +18058,8 @@ var LSPService = class _LSPService {
17217
18058
  diagnostics: "none",
17218
18059
  source: "head_move_primary",
17219
18060
  clientScope: "all",
17220
- excludeServerIds: exclude
18061
+ excludeServerIds: exclude,
18062
+ readStamp
17221
18063
  });
17222
18064
  sent += 1;
17223
18065
  for (const server of servers) {
@@ -17226,15 +18068,22 @@ var LSPService = class _LSPService {
17226
18068
  const root = await this.clientRegistry.resolveServerRoot(server, filePath);
17227
18069
  const key = root ? `${server.id}:${normalizeMapKey(root)}` : void 0;
17228
18070
  const client = key ? this.state.clients.get(key) : void 0;
17229
- if (key && client)
18071
+ if (key && client) {
18072
+ const traits = serverTraits(server);
18073
+ const documents = sentTo.get(key)?.documents ?? [];
18074
+ documents.push({ filePath, content, readStamp });
17230
18075
  sentTo.set(key, {
17231
18076
  client,
17232
- ordered: serverTraits(server).replyOrdering === "single-task-ordered"
18077
+ ordered: traits.replyOrdering === "single-task-ordered",
18078
+ rechecks: traits.resendRecheck === "rechecks",
18079
+ documents
17233
18080
  });
18081
+ }
17234
18082
  }
17235
18083
  }
17236
18084
  if (sentTo.size === 0)
17237
18085
  return { sent, drained: true };
18086
+ 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
18087
  const answers = await Promise.all([...sentTo.values()].map(async ({ client, ordered }) => {
17239
18088
  if (!ordered)
17240
18089
  return false;
@@ -17265,7 +18114,7 @@ var LSPService = class _LSPService {
17265
18114
  const targets = /* @__PURE__ */ new Set();
17266
18115
  const changed = /* @__PURE__ */ new Map();
17267
18116
  for (const changedPath of changedPaths) {
17268
- const resolved2 = path15.resolve(changedPath);
18117
+ const resolved2 = path17.resolve(changedPath);
17269
18118
  for (const server of getServersForFileWithConfig(resolved2)) {
17270
18119
  const root = await this.clientRegistry.resolveServerRoot(server, resolved2);
17271
18120
  if (!root)
@@ -17666,6 +18515,7 @@ var LSPService = class _LSPService {
17666
18515
  return false;
17667
18516
  return auxPublishedThisContent.has(serverId) || bindingMatchesTouchContent(entry.client.getDiagnosticBinding?.(filePath));
17668
18517
  };
18518
+ const auxPublishedCount = (client, published) => published ? client.getDiagnostics?.(filePath)?.length ?? 0 : 0;
17669
18519
  const notifyWriteTimedOutServerIds = [];
17670
18520
  const notifyDeferredServerIds = [];
17671
18521
  const supersededServerIds = [];
@@ -17710,7 +18560,19 @@ var LSPService = class _LSPService {
17710
18560
  let rejected = false;
17711
18561
  try {
17712
18562
  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);
18563
+ const writePromise = entry.client.notify.open(
18564
+ filePath,
18565
+ content,
18566
+ languageId,
18567
+ void 0,
18568
+ silent,
18569
+ options.saved === true,
18570
+ options.readStamp,
18571
+ // #2066: the #1095 fingerprint `touchFile` already computed for
18572
+ // these exact bytes (`contentHash` above). Without it the send
18573
+ // walks the document again for the same sha256.
18574
+ contentHash2
18575
+ ).then((sent) => sent !== false);
17714
18576
  if (gated && clientKey) {
17715
18577
  this.noteAuxNotifyIssued(clientKey, entry.client);
17716
18578
  }
@@ -18015,14 +18877,16 @@ var LSPService = class _LSPService {
18015
18877
  const outcomes = await Promise.all(auxWaits.map(async (aux) => {
18016
18878
  const { budgetMs } = aux;
18017
18879
  if (aux.demoted) {
18880
+ const demotedPublished = auxiliaryPublicationEvidence({
18881
+ bindingMatchesContent: auxCoversThisContent(aux.serverId),
18882
+ baseline: aux.baseline,
18883
+ currentPathVersion: readPathVersion(aux.client)
18884
+ });
18018
18885
  return {
18019
18886
  serverId: aux.serverId,
18020
18887
  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
- }),
18888
+ publishedThisContent: demotedPublished,
18889
+ publishedCount: auxPublishedCount(aux.client, demotedPublished),
18026
18890
  budgetMs,
18027
18891
  elapsedMs: 0,
18028
18892
  elapsedSinceNotifyMs: 0
@@ -18066,6 +18930,7 @@ var LSPService = class _LSPService {
18066
18930
  // below is master's line; the stamp axis already decided
18067
18931
  // the outcome above and must not re-admit the row here.
18068
18932
  publishedThisContent: auxCoversThisContent(aux.serverId),
18933
+ publishedCount: auxPublishedCount(aux.client, publishedEvidence || auxCoversThisContent(aux.serverId)),
18069
18934
  budgetMs,
18070
18935
  elapsedMs,
18071
18936
  // #1458 S3: elapsed measured from BEFORE the primary wait
@@ -18198,6 +19063,7 @@ var LSPService = class _LSPService {
18198
19063
  // below is master's line; the stamp axis already decided
18199
19064
  // the outcome above and must not re-admit the row here.
18200
19065
  publishedThisContent: auxCoversThisContent(entry.info.id),
19066
+ publishedCount: auxPublishedCount(entry.client, publishedEvidence || auxCoversThisContent(entry.info.id)),
18201
19067
  budgetMs: timeoutFor(entry.client.serverId),
18202
19068
  elapsedMs: waitedMs,
18203
19069
  elapsedSinceNotifyMs: waitedMs
@@ -18404,26 +19270,36 @@ var LSPService = class _LSPService {
18404
19270
  diagnosticsUnansweredServerIds: diagnosticsUnansweredPrimaryServerIds
18405
19271
  });
18406
19272
  const inconclusive = verdict.inconclusive;
18407
- const brokenSkippedServerIds = collected !== void 0 ? await this.brokenSkippedAuxiliaryServerIds(filePath, clientScope, options, spawned) : [];
19273
+ const skippedAuxiliaries = collected !== void 0 ? await this.skippedAuxiliaryServerIds(filePath, clientScope, options, spawned) : { brokenSkippedServerIds: [], policySkippedServerIds: [] };
19274
+ const brokenSkippedServerIds = skippedAuxiliaries.brokenSkippedServerIds;
19275
+ const policySkippedServerIds = skippedAuxiliaries.policySkippedServerIds;
18408
19276
  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
19277
  const unconfirmedServerIds = [
18410
19278
  .../* @__PURE__ */ new Set([
18411
19279
  ...auxUnconfirmedServerIds ?? [],
18412
19280
  ...auxNoAnswerServerIds,
18413
19281
  ...uncoveredDeferredServerIds,
18414
- ...brokenSkippedServerIds
19282
+ ...brokenSkippedServerIds,
19283
+ ...policySkippedServerIds
18415
19284
  ])
18416
19285
  ].filter((serverId) => !auxCoveredAtMerge.has(serverId));
18417
19286
  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
19287
+ if (brokenSkippedServerIds.length > 0 || policySkippedServerIds.length > 0 || uncoveredDeferredServerIds.length > 0 || // #1549: the auxiliary deadline misses that used to surface as a blanket
18419
19288
  // `inconclusive` need their own row now that the touch reports usable
18420
19289
  // findings — otherwise the fix would remove the only record of the blackout.
18421
19290
  auxNoAnswerServerIds.length > 0) {
19291
+ const configFailureSuffix = (serverId) => {
19292
+ const failure = spawned.find((entry) => entry.info.id === serverId)?.client.getConfigLoadFailure?.();
19293
+ return failure ? ` (server reported: ${failure})` : "";
19294
+ };
18422
19295
  for (const serverId of unconfirmedServerIds) {
18423
19296
  const reasons = [
18424
19297
  brokenSkippedServerIds.includes(serverId) && "breaker skip",
19298
+ policySkippedServerIds.includes(serverId) && "root policy skip",
18425
19299
  uncoveredDeferredServerIds.includes(serverId) && "deferred resync",
18426
- auxNoAnswerServerIds.includes(serverId) && "no diagnostics answer"
19300
+ auxNoAnswerServerIds.includes(serverId) && // #4764: WHY it did not answer, when the server said so itself
19301
+ // (a failed config load reads like a timeout otherwise).
19302
+ `no diagnostics answer${configFailureSuffix(serverId)}`
18427
19303
  ].filter(Boolean);
18428
19304
  incrementDegradationCount({
18429
19305
  kind: "lsp-scanner-coverage-gap",
@@ -18440,6 +19316,9 @@ var LSPService = class _LSPService {
18440
19316
  ...brokenSkippedServerIds.length > 0 && {
18441
19317
  brokenSkippedServerIds
18442
19318
  },
19319
+ ...policySkippedServerIds.length > 0 && {
19320
+ policySkippedServerIds
19321
+ },
18443
19322
  // #1586: the deferrals this touch is actually uncovered for. The
18444
19323
  // gate action keeps its own record in `lsp_notify_resync_deferred`;
18445
19324
  // this row exists to prove a blackout, and a scanner already bound
@@ -18609,6 +19488,7 @@ var LSPService = class _LSPService {
18609
19488
  // named here either. The gate's own action is recorded regardless, in
18610
19489
  // `lsp_notify_resync_deferred`.
18611
19490
  ...brokenSkippedServerIds.length > 0 && { brokenSkippedServerIds },
19491
+ ...policySkippedServerIds.length > 0 && { policySkippedServerIds },
18612
19492
  ...uncoveredDeferredServerIds.length > 0 && {
18613
19493
  deferredResyncServerIds: uncoveredDeferredServerIds
18614
19494
  },
@@ -19366,21 +20246,24 @@ var LSPService = class _LSPService {
19366
20246
  });
19367
20247
  return false;
19368
20248
  });
19369
- const willResults = await Promise.all(willRenameClients.map(async ({ serverId, client }) => {
20249
+ const renameRequestedAtMs = Date.now();
20250
+ const willResults = await Promise.all(willRenameClients.map(async ({ clientKey, serverId, client }) => {
19370
20251
  try {
19371
20252
  return {
20253
+ clientKey,
19372
20254
  serverId,
19373
- edit: await client.willRenameFiles(oldFilePath, newFilePath)
20255
+ edit: await client.willRenameFiles(oldFilePath, newFilePath),
20256
+ failed: false
19374
20257
  };
19375
20258
  } catch (err) {
19376
20259
  willRenameFailures.push({
19377
20260
  serverId,
19378
20261
  error: err instanceof Error ? err.message : String(err)
19379
20262
  });
19380
- return { serverId, edit: null };
20263
+ return { clientKey, serverId, edit: null, failed: true };
19381
20264
  }
19382
20265
  }));
19383
- const successfulWillResults = willResults.filter((result) => !willRenameFailures.some((failure) => failure.serverId === result.serverId));
20266
+ const successfulWillResults = willResults.filter((result) => !result.failed);
19384
20267
  if (willRenameClients.length > 0 && successfulWillResults.length === 0) {
19385
20268
  throw new Error(`workspace/willRenameFiles failed for all active LSP servers: ${willRenameFailures.map((failure) => `${failure.serverId}: ${failure.error}`).join("; ")}`);
19386
20269
  }
@@ -19402,7 +20285,12 @@ var LSPService = class _LSPService {
19402
20285
  applied = await applyWorkspaceEdit(merged.edit, cwd, {
19403
20286
  mutationContext: options.mutationContext,
19404
20287
  observe: false,
19405
- watchedFileSink: this
20288
+ watchedFileSink: this,
20289
+ // #3734: nothing read the old path on this flow, so there is no
20290
+ // target: every text-edited file is bound by its client's send record,
20291
+ // else by its mtime against the instant above (`formal/lsp-rename-edit`,
20292
+ // `Issue3734Bound`).
20293
+ 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
20294
  });
19407
20295
  } catch (err) {
19408
20296
  if (options.mutationContext) {
@@ -19416,7 +20304,8 @@ var LSPService = class _LSPService {
19416
20304
  }
19417
20305
  throw err;
19418
20306
  }
19419
- const openDocuments = activeClients.filter(({ client }) => client.isDocumentOpen(oldFilePath)).map(({ serverId, client }) => ({
20307
+ const openDocuments = activeClients.filter(({ client }) => client.isDocumentOpen(oldFilePath)).map(({ clientKey, serverId, client }) => ({
20308
+ clientKey,
19420
20309
  serverId,
19421
20310
  client,
19422
20311
  oldUri: client.getDocumentUri(oldFilePath)
@@ -19439,7 +20328,7 @@ var LSPService = class _LSPService {
19439
20328
  status: "failed"
19440
20329
  });
19441
20330
  }
19442
- const content = await fs11.readFile(oldFilePath, "utf-8");
20331
+ const content = await fs13.readFile(oldFilePath, "utf-8");
19443
20332
  const languageId = getLanguageId2(oldFilePath) ?? "plaintext";
19444
20333
  const resyncFailures = [];
19445
20334
  await Promise.all(openDocuments.map(async ({ serverId, client }) => {
@@ -19503,10 +20392,10 @@ var LSPService = class _LSPService {
19503
20392
  }
19504
20393
  throw err;
19505
20394
  }
19506
- const relOld = path15.relative(cwd, oldFilePath).replace(/\\/g, "/") || path15.basename(oldFilePath);
19507
- const relNew = path15.relative(cwd, newFilePath).replace(/\\/g, "/") || path15.basename(newFilePath);
20395
+ const relOld = path17.relative(cwd, oldFilePath).replace(/\\/g, "/") || path17.basename(oldFilePath);
20396
+ const relNew = path17.relative(cwd, newFilePath).replace(/\\/g, "/") || path17.basename(newFilePath);
19508
20397
  const renameDescription = `Renamed ${relOld} \u2192 ${relNew}`;
19509
- await Promise.all(activeClients.map(async ({ serverId, client }) => {
20398
+ await Promise.all(activeClients.map(async ({ clientKey, serverId, client }) => {
19510
20399
  if (client.getOperationSupport().didRenameFiles !== true) {
19511
20400
  recordDegradationOnce({
19512
20401
  kind: "lsp-capability-skip",
@@ -19515,7 +20404,7 @@ var LSPService = class _LSPService {
19515
20404
  });
19516
20405
  return;
19517
20406
  }
19518
- const opened = openDocuments.find((entry) => entry.serverId === serverId);
20407
+ const opened = openDocuments.find((entry) => entry.clientKey === clientKey);
19519
20408
  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
20409
  if (!result.ok) {
19521
20410
  didRenameFailures.push({
@@ -19890,7 +20779,7 @@ var LSPService = class _LSPService {
19890
20779
  }
19891
20780
  async runWorkspaceDiagnosticsSwept(cwd, options = {}) {
19892
20781
  const startedAt = Date.now();
19893
- const root = path15.resolve(cwd);
20782
+ const root = path17.resolve(cwd);
19894
20783
  const { signal } = options;
19895
20784
  void this.sweepDocumentDrift().catch(() => {
19896
20785
  });
@@ -19926,7 +20815,7 @@ var LSPService = class _LSPService {
19926
20815
  await Promise.all(openImports.slice(0, SCOPED_DEPENDENCY_TOUCH_MAX).map(async (dependency) => {
19927
20816
  let content;
19928
20817
  try {
19929
- content = await fs11.readFile(dependency, "utf8");
20818
+ content = await fs13.readFile(dependency, "utf8");
19930
20819
  } catch {
19931
20820
  return;
19932
20821
  }
@@ -20083,7 +20972,20 @@ var LSPService = class _LSPService {
20083
20972
  await this.ensureWarmForSweep(filePath, { signal });
20084
20973
  }
20085
20974
  const touchResult = attached?.available ? {
20086
- diags: attached.response.diagnostics,
20975
+ // #4645: the incumbent's membership answer, applied on receipt
20976
+ // through the owner's rule. This sweep records its rows into
20977
+ // the workspace cache, and an attached process has no live
20978
+ // tsserver to re-ask on a replay, so the verdict stays in the
20979
+ // rows: the form the batch cache stores (`replayable()`). The
20980
+ // environment rule still runs at render, against the install
20981
+ // state of that render.
20982
+ diags: attached.response.projectIdentity === void 0 ? attached.response.diagnostics : await demoteInferredProjectDiagnostics(attached.response.diagnostics, {
20983
+ filePath,
20984
+ cwd,
20985
+ identityCache: /* @__PURE__ */ new Map([
20986
+ [filePath, attached.response.projectIdentity]
20987
+ ])
20988
+ }),
20087
20989
  // #1470: the incumbent's coverage gap crosses the socket as an
20088
20990
  // explicit DTO field, so carry it onto the wrapper the sweep
20089
20991
  // reads. Dropping it here would let a partially covered
@@ -20707,9 +21609,8 @@ export {
20707
21609
  drainPendingAuxCapEvictedCount,
20708
21610
  recordNapiFallbackCoverage,
20709
21611
  resetPendingAuxiliaryCoverage,
20710
- resetOpaqueMutationState,
20711
- createFileTime,
20712
21612
  clearAllSessions,
21613
+ PartialApplyRecordStore,
20713
21614
  getActiveSessionId,
20714
21615
  beginScope,
20715
21616
  retireScope,
@@ -20717,6 +21618,7 @@ export {
20717
21618
  scopeCell,
20718
21619
  lineContentHash,
20719
21620
  ReadGuard,
21621
+ resetOpaqueMutationState,
20720
21622
  resetObservedMutationNet,
20721
21623
  logBusEvent,
20722
21624
  recordStaleBusFailure,
@@ -20745,6 +21647,7 @@ export {
20745
21647
  hasAnyDispositionMarks,
20746
21648
  hasStrictDispositionMarks,
20747
21649
  getDisposition,
21650
+ resetDeferredDispositions,
20748
21651
  applyDispositions,
20749
21652
  applyWeakDispositions,
20750
21653
  applyDispositionsMultiFile,
@@ -20766,16 +21669,16 @@ export {
20766
21669
  getFileDiagnosticSummaries,
20767
21670
  getSuppressedDiagnostics,
20768
21671
  countRetainedSuppressedRows,
20769
- refuseStaleWorkspaceEdit,
20770
- workspaceEditTextPaths,
21672
+ captureRenameExpectedContent,
20771
21673
  summarizeWorkspaceEdit,
20772
21674
  applyWorkspaceEdit,
20773
- fetchTsserverProjectIdentity,
20774
21675
  attemptTsserverSyncDiagnostics,
20775
21676
  rankFilesByReverseDependencyCentrality,
20776
21677
  buildReverseDependencyIndexFromGraph,
20777
21678
  buildProbeScopeKey,
20778
21679
  createWorkspaceDiagnosticsCacheContext,
21680
+ demoteLanguageServerRows,
21681
+ demoteInferredProjectSweepResults,
20779
21682
  createLazyImport,
20780
21683
  loadLspService,
20781
21684
  tryWarmAttachedDiagnostics,