pi-lens 4.4.7 → 4.4.8

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 (167) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/README.md +12 -2
  3. package/config/markdownlint/run-no-fix.mjs +36 -0
  4. package/dist/{chunk-WME2OQST.js → chunk-2453RRJ2.js} +11 -6
  5. package/dist/{chunk-FZKFVUEC.js → chunk-2BKUFQKR.js} +276 -208
  6. package/dist/chunk-2TS4GLOJ.js +31 -0
  7. package/dist/{chunk-QHSNL7B2.js → chunk-2ZE3AUJQ.js} +12 -14
  8. package/dist/{chunk-MPKRJBPK.js → chunk-35WKJWO5.js} +28 -30
  9. package/dist/chunk-3JAHQBSY.js +27 -0
  10. package/dist/{chunk-4LM3VAZH.js → chunk-3O5EII3W.js} +2 -2
  11. package/dist/chunk-447YZL4S.js +25 -0
  12. package/dist/{chunk-H7OR7DFZ.js → chunk-4B2YFN4U.js} +25 -21
  13. package/dist/{chunk-OSTKYB55.js → chunk-4BKU7PV3.js} +1 -1
  14. package/dist/{chunk-RRV3FNNM.js → chunk-4LL2VRNY.js} +27 -28
  15. package/dist/{chunk-BZARLRJW.js → chunk-4NBWFYWW.js} +9 -9
  16. package/dist/{chunk-KKCK636N.js → chunk-4QG55RRC.js} +12 -12
  17. package/dist/{chunk-RQS4QQSD.js → chunk-4W52ZKZX.js} +2 -2
  18. package/dist/{chunk-Z2XAOKHK.js → chunk-565VRUP4.js} +2 -2
  19. package/dist/{chunk-HWDAVBFU.js → chunk-57X2CDRX.js} +23 -23
  20. package/dist/{chunk-MB6PXBUA.js → chunk-5F3XF3SX.js} +7 -15
  21. package/dist/{chunk-O4BJFESU.js → chunk-5RNB4HVK.js} +1 -1
  22. package/dist/{chunk-ZMAUPOMG.js → chunk-5T5A6YAJ.js} +35 -34
  23. package/dist/{chunk-4ZYJHQMB.js → chunk-6FIRFP6A.js} +12 -12
  24. package/dist/{chunk-4YHYPW2G.js → chunk-6GMGEKQN.js} +9 -5
  25. package/dist/{chunk-4LOE5R5P.js → chunk-6LJOJ6EO.js} +20 -15
  26. package/dist/{chunk-3YY7IXIL.js → chunk-6YUNI7B5.js} +3 -3
  27. package/dist/{chunk-PKES3ISE.js → chunk-7ANZ7XDD.js} +2 -2
  28. package/dist/{chunk-FB5SCCPT.js → chunk-7CGIDRIK.js} +16 -15
  29. package/dist/{chunk-L3CMBQMH.js → chunk-7MAD5ZAY.js} +16 -17
  30. package/dist/{chunk-WDBICWH3.js → chunk-7TNILKGY.js} +1 -1
  31. package/dist/{chunk-RORGS5II.js → chunk-A5GRLYPZ.js} +9 -9
  32. package/dist/{chunk-MNJIXFX4.js → chunk-AGGUWKRK.js} +1 -1
  33. package/dist/{chunk-ABPKUVA4.js → chunk-BBET6HD6.js} +1 -1
  34. package/dist/{chunk-L5JYIU47.js → chunk-BHWW6FAX.js} +14 -13
  35. package/dist/{chunk-URCQWAQ4.js → chunk-BOPDQ7AZ.js} +23 -21
  36. package/dist/{chunk-KDX35VXP.js → chunk-BQG2QFVO.js} +158 -133
  37. package/dist/{chunk-CB4WHS4H.js → chunk-BUZIQDFS.js} +3 -3
  38. package/dist/{chunk-2PHMIAKO.js → chunk-CM73PPGD.js} +4 -4
  39. package/dist/{chunk-DH5JPM3K.js → chunk-CUDD35TW.js} +10 -9
  40. package/dist/{chunk-AWDSEDER.js → chunk-CZL44WFN.js} +2 -2
  41. package/dist/{chunk-N5WSK2K7.js → chunk-DIWK3LBC.js} +12 -15
  42. package/dist/{chunk-24BILSZW.js → chunk-DYRZGUMA.js} +2 -2
  43. package/dist/{chunk-PR6PO3ES.js → chunk-FHEV6T4L.js} +22 -18
  44. package/dist/{chunk-DQZFQSR5.js → chunk-FRLAUP2B.js} +4 -4
  45. package/dist/{chunk-RZOXUSPC.js → chunk-G5GV2Q7K.js} +2 -2
  46. package/dist/{chunk-EKWX4WD3.js → chunk-G6JKM4O7.js} +7 -7
  47. package/dist/chunk-GGYOZWHW.js +27 -0
  48. package/dist/{chunk-XT2HTCJ5.js → chunk-GIRBSBGL.js} +6 -5
  49. package/dist/{chunk-PQJFG24Z.js → chunk-GMROJJRN.js} +1292 -946
  50. package/dist/{chunk-U6VN4NVL.js → chunk-HHR7WGCI.js} +3 -3
  51. package/dist/{chunk-TIQJPRDD.js → chunk-HKIL6DCL.js} +3 -2
  52. package/dist/{chunk-SNDXCFRS.js → chunk-HUAM7QG3.js} +11 -11
  53. package/dist/{chunk-QOE342SU.js → chunk-HXFUTMX2.js} +2 -2
  54. package/dist/{chunk-U7BD2QL7.js → chunk-I22THIHI.js} +12 -12
  55. package/dist/chunk-IE5D3RA5.js +58 -0
  56. package/dist/{chunk-DPGEAHZT.js → chunk-IYVYZQRL.js} +10 -16
  57. package/dist/{chunk-3F6BMY53.js → chunk-JBP7KESM.js} +1 -1
  58. package/dist/{chunk-U5HPROLA.js → chunk-JE6HKLC7.js} +2 -2
  59. package/dist/{chunk-ZE3KXHS7.js → chunk-JPRDTY5S.js} +85 -3
  60. package/dist/{chunk-HO6LWE2E.js → chunk-JYLOYTZD.js} +17 -1
  61. package/dist/{chunk-KW5JQPO5.js → chunk-JZRP4DGP.js} +2 -2
  62. package/dist/{chunk-CPSR3AVL.js → chunk-KZ4ALBCH.js} +2 -2
  63. package/dist/{chunk-6IR3ZYIB.js → chunk-L3CLUGDY.js} +3 -3
  64. package/dist/{chunk-LV4UMYVH.js → chunk-L4NEVZ4T.js} +28 -27
  65. package/dist/chunk-LPYTPNOJ.js +22 -0
  66. package/dist/{chunk-WGRJOXED.js → chunk-LSFXZLPW.js} +1016 -636
  67. package/dist/{chunk-LBLBAFG3.js → chunk-MC6VB2E5.js} +4 -4
  68. package/dist/{chunk-U2SDMG7C.js → chunk-NM2NWH55.js} +5 -5
  69. package/dist/{chunk-T7A2HK2B.js → chunk-NSPVR3FN.js} +19 -18
  70. package/dist/{chunk-ZGSJDWQU.js → chunk-O2ARHQKF.js} +2 -2
  71. package/dist/{chunk-OXOI55RU.js → chunk-O4N5BQ3T.js} +10 -10
  72. package/dist/{chunk-3FRLWYBG.js → chunk-OC7VWJBZ.js} +39 -40
  73. package/dist/chunk-OFNMHPBT.js +89 -0
  74. package/dist/{chunk-HR3OJ3TH.js → chunk-OWTG6UMO.js} +21 -21
  75. package/dist/{chunk-75GAYVNO.js → chunk-OY7WZI7Q.js} +6 -6
  76. package/dist/{chunk-ZJTT47IG.js → chunk-OZWXLJMX.js} +2 -2
  77. package/dist/{chunk-F6X3YJWD.js → chunk-PIQQM32Y.js} +2 -2
  78. package/dist/chunk-PKLB2XJL.js +8 -0
  79. package/dist/{chunk-EAOK7MIZ.js → chunk-PKSUMEPT.js} +17 -4
  80. package/dist/{chunk-YISME6ON.js → chunk-PPKECBPP.js} +1 -1
  81. package/dist/{chunk-4L36HG27.js → chunk-R2QQC33W.js} +14 -14
  82. package/dist/{chunk-LUBPZN36.js → chunk-R4QWJQ2H.js} +11 -11
  83. package/dist/{chunk-V63BC55Q.js → chunk-RGGH6M34.js} +1 -1
  84. package/dist/{chunk-Y7F7IEE3.js → chunk-RZG472YW.js} +65 -7
  85. package/dist/{chunk-PUZ3E2J4.js → chunk-SDFKOLSF.js} +6 -6
  86. package/dist/{chunk-YHC2O2WO.js → chunk-SFLHSL5R.js} +9 -9
  87. package/dist/{chunk-CCV2EU7T.js → chunk-SP4TFY5F.js} +14 -13
  88. package/dist/{chunk-J6JP25XU.js → chunk-SQC7K3SP.js} +4 -3
  89. package/dist/{chunk-3K2F6UDZ.js → chunk-T2S3FNNJ.js} +44 -42
  90. package/dist/{chunk-2TF6RXWB.js → chunk-TV6RXRYH.js} +10 -10
  91. package/dist/{chunk-GNSIWBAT.js → chunk-U3AS2FR6.js} +3 -3
  92. package/dist/{chunk-F7K5IBZG.js → chunk-UHHLR2VY.js} +40 -40
  93. package/dist/chunk-UYXV5NIS.js +20 -0
  94. package/dist/{chunk-VSFLRN5Y.js → chunk-VLQ7UKZH.js} +1 -1
  95. package/dist/{chunk-VUZWQ7UG.js → chunk-VN3L2JWZ.js} +46 -72
  96. package/dist/{chunk-NA7SEXHE.js → chunk-VOP4PJKA.js} +7 -7
  97. package/dist/{chunk-F5Z6URKM.js → chunk-VOXTCULR.js} +2 -2
  98. package/dist/{chunk-LLS45EWB.js → chunk-VPLBLWFO.js} +6 -8
  99. package/dist/chunk-W3BGKBBK.js +27 -0
  100. package/dist/{chunk-ZKXQKGWZ.js → chunk-WC6WRNQT.js} +4 -3
  101. package/dist/{chunk-YVHBNSME.js → chunk-WMDUT4KH.js} +1148 -1132
  102. package/dist/{chunk-KXF5R4UN.js → chunk-WQV6BI4Q.js} +1 -1
  103. package/dist/chunk-WXUDRAG6.js +24 -0
  104. package/dist/{chunk-KPPJTH44.js → chunk-X35S7HSB.js} +28 -10
  105. package/dist/{chunk-JMEKXFOL.js → chunk-X66YJ2SS.js} +40 -34
  106. package/dist/{chunk-CE6VMBCB.js → chunk-XOMGO63G.js} +22 -21
  107. package/dist/{chunk-LS3QJRUB.js → chunk-XWIME22V.js} +13 -13
  108. package/dist/{chunk-R5MOQM2H.js → chunk-XYLC35E4.js} +119 -87
  109. package/dist/{chunk-OE5ZBP7F.js → chunk-YHGYAEFH.js} +18 -18
  110. package/dist/{chunk-7E2563GA.js → chunk-ZFORSIED.js} +13 -13
  111. package/dist/{chunk-E7HJ56Y7.js → chunk-ZKLTNLAW.js} +64 -73
  112. package/dist/chunk-ZONZ6YY3.js +74 -0
  113. package/dist/chunk-ZSM35JF4.js +30 -0
  114. package/dist/{chunk-RC2Z6K47.js → chunk-ZZDIOAAJ.js} +15 -6
  115. package/dist/index.js +6993 -5396
  116. package/dist/mcp/analyze-cli.js +10 -10
  117. package/dist/mcp/cli.js +44 -42
  118. package/dist/mcp/server.js +1627 -504
  119. package/dist/mcp/worker.js +62 -61
  120. package/dist/probes/installer.js +20 -19
  121. package/docs/adr/0003-git-guard-latch-writer.md +11 -6
  122. package/docs/agent-tools.md +18 -8
  123. package/docs/alignment-families.md +29 -0
  124. package/docs/ast-grep_rules_catalog.md +6 -4
  125. package/docs/ci-bot-pr-checks.md +126 -0
  126. package/docs/configuration.md +99 -3
  127. package/docs/defect-shapes.md +55 -12
  128. package/docs/engineering-principles.md +27 -2
  129. package/docs/features.md +2 -2
  130. package/docs/invariants/git-guard-host.md +7 -3
  131. package/docs/invariants/language-config.md +15 -4
  132. package/docs/invariants/lsp-trust-exec.md +16 -2
  133. package/docs/invariants/paths-os.md +4 -2
  134. package/docs/lsp-capability-matrix.md +119 -39
  135. package/docs/merge-queue-rollout.md +1 -1
  136. package/docs/pi-lens-fixer.md +24 -17
  137. package/docs/pi-lens-merge-policy.md +20 -11
  138. package/docs/pi-lens-monitor.md +9 -0
  139. package/docs/pi-lens-orchestration.md +4 -1
  140. package/docs/pi-lens-reviewer.md +5 -5
  141. package/docs/pi-lens-subagent.md +6 -3
  142. package/docs/public-api-stability.md +18 -2
  143. package/docs/schema/pi-lens-config-v1.json +10 -0
  144. package/docs/settings.md +10 -6
  145. package/docs/word-index.md +17 -5
  146. package/package.json +5 -3
  147. package/rules/ast-grep-rules/rule-tests/no-accumulating-spread-js-test.yml +37 -0
  148. package/rules/ast-grep-rules/rule-tests/ts-redundant-filter-map-test.yml +12 -1
  149. package/rules/ast-grep-rules/rule-tests-disabled/filter-then-map-js-test.yml +12 -0
  150. package/rules/ast-grep-rules/rule-tests-disabled/filter-then-map-test.yml +25 -0
  151. package/rules/ast-grep-rules/rules/no-accumulating-spread-js.yml +49 -1
  152. package/rules/ast-grep-rules/rules/ts-redundant-filter-map.yml +9 -1
  153. package/rules/ast-grep-rules/rules-disabled/filter-then-map-js.yml +17 -0
  154. package/rules/ast-grep-rules/rules-disabled/filter-then-map.yml +36 -0
  155. package/rules/ast-grep-rules/self-scan-baseline.json +1 -1
  156. package/dist/chunk-46TNM7XZ.js +0 -88
  157. package/dist/chunk-72OKUXSD.js +0 -31
  158. package/dist/chunk-7GLOLOSH.js +0 -57
  159. package/dist/chunk-AKUUMGD5.js +0 -26
  160. package/dist/chunk-ASUXV767.js +0 -22
  161. package/dist/chunk-CTADOKYM.js +0 -25
  162. package/dist/chunk-JJ2RRESP.js +0 -58
  163. package/dist/chunk-LSC3VADM.js +0 -23
  164. package/dist/chunk-SHLDT3OI.js +0 -27
  165. package/dist/chunk-UF7RTZSO.js +0 -27
  166. package/dist/chunk-W4WP2ERB.js +0 -30
  167. package/dist/chunk-YES5CACN.js +0 -73
@@ -3,7 +3,7 @@ import { createRequire as __pilensCreateRequire } from "node:module"; const requ
3
3
  import {
4
4
  GitleaksClient,
5
5
  classifyAndFilterFindings
6
- } from "../chunk-VUZWQ7UG.js";
6
+ } from "../chunk-VN3L2JWZ.js";
7
7
  import {
8
8
  DEAD_CODE_DELTA_MAX_SHOWN,
9
9
  deadCodeIssueCount,
@@ -11,18 +11,18 @@ import {
11
11
  deadCodeIssues,
12
12
  formatDeadCodeDelta,
13
13
  stableFindingKey
14
- } from "../chunk-QHSNL7B2.js";
14
+ } from "../chunk-2ZE3AUJQ.js";
15
15
  import {
16
16
  clearFormatterCache
17
- } from "../chunk-RRV3FNNM.js";
17
+ } from "../chunk-4LL2VRNY.js";
18
18
  import {
19
19
  findNearestProjectRoot,
20
20
  isStartupScanVerdictFresh,
21
21
  resolveStartupScanContext
22
- } from "../chunk-75GAYVNO.js";
22
+ } from "../chunk-OY7WZI7Q.js";
23
23
  import {
24
24
  loadCallGraph
25
- } from "../chunk-6IR3ZYIB.js";
25
+ } from "../chunk-L3CLUGDY.js";
26
26
  import {
27
27
  isHardFailureSummary
28
28
  } from "../chunk-7U2IDNXN.js";
@@ -31,11 +31,11 @@ import {
31
31
  formatRunDurationMs,
32
32
  isExcludedTestTarget,
33
33
  isRunnerErrorResult
34
- } from "../chunk-HR3OJ3TH.js";
34
+ } from "../chunk-OWTG6UMO.js";
35
35
  import {
36
36
  GovulncheckClient
37
- } from "../chunk-YHC2O2WO.js";
38
- import "../chunk-ZJTT47IG.js";
37
+ } from "../chunk-SFLHSL5R.js";
38
+ import "../chunk-OZWXLJMX.js";
39
39
  import {
40
40
  resetManagedToolRefreshSession
41
41
  } from "../chunk-UXVNL3D7.js";
@@ -53,7 +53,7 @@ import {
53
53
  peekTurnEndFindings,
54
54
  snapshotAdvisoryProvenance,
55
55
  validateAdvisoryProvenance
56
- } from "../chunk-4YHYPW2G.js";
56
+ } from "../chunk-6GMGEKQN.js";
57
57
  import {
58
58
  CacheManager,
59
59
  DEFAULT_MAX_AGE_MS,
@@ -63,6 +63,7 @@ import {
63
63
  admitsProjectWideFindings,
64
64
  analyzeFile,
65
65
  applyFindingPolicy,
66
+ applyFindingPolicyByOwner,
66
67
  applyLspFindingPolicy,
67
68
  applyPushedFindingPolicy,
68
69
  applyPushedFindingPolicyByFile,
@@ -75,6 +76,7 @@ import {
75
76
  convertLspDiagnostics,
76
77
  createDispatchContext,
77
78
  createMcpHost,
79
+ disabledRunnersOf,
78
80
  dispositionSuppressedLine,
79
81
  drainPendingRunnerFindings,
80
82
  dropStaleRunnerFindings,
@@ -93,7 +95,7 @@ import {
93
95
  inlineBlockerIdentities,
94
96
  laneCopyStandsFor,
95
97
  listCascadePendingNeighbors,
96
- loadProjectRulePolicyMap,
98
+ loadProjectRulePolicy,
97
99
  loadSg,
98
100
  logCascade,
99
101
  markCascadeUnansweredPrimariesDelivered,
@@ -113,61 +115,63 @@ import {
113
115
  resetPsScriptAnalyzerAvailability,
114
116
  runProviders,
115
117
  stampLineHashes
116
- } from "../chunk-WGRJOXED.js";
118
+ } from "../chunk-LSFXZLPW.js";
117
119
  import {
118
120
  resetLazyInstallAttempts
119
- } from "../chunk-LBLBAFG3.js";
121
+ } from "../chunk-MC6VB2E5.js";
120
122
  import {
121
123
  isTestRoleCollateral
122
- } from "../chunk-MNJIXFX4.js";
123
- import {
124
- findingsResult,
125
- hasUsableResult,
126
- reachedNoVerdict
127
- } from "../chunk-Y7F7IEE3.js";
128
- import "../chunk-JJ2RRESP.js";
129
- import "../chunk-EAOK7MIZ.js";
124
+ } from "../chunk-AGGUWKRK.js";
125
+ import "../chunk-PKSUMEPT.js";
130
126
  import {
131
127
  resetGoAvailability
132
- } from "../chunk-4LM3VAZH.js";
128
+ } from "../chunk-3O5EII3W.js";
133
129
  import {
134
- TrivyClient
135
- } from "../chunk-E7HJ56Y7.js";
130
+ TrivyClient,
131
+ trivyEvidenceFiles
132
+ } from "../chunk-ZKLTNLAW.js";
133
+ import "../chunk-KZ4ALBCH.js";
134
+ import "../chunk-JPRDTY5S.js";
136
135
  import {
137
136
  scannerReportParentDir
138
- } from "../chunk-V63BC55Q.js";
139
- import "../chunk-CPSR3AVL.js";
140
- import "../chunk-ZE3KXHS7.js";
137
+ } from "../chunk-RGGH6M34.js";
138
+ import {
139
+ findingsResult,
140
+ hasUsableResult,
141
+ reachedNoVerdict
142
+ } from "../chunk-RZG472YW.js";
141
143
  import {
142
144
  resetRustAvailability
143
- } from "../chunk-RQS4QQSD.js";
144
- import "../chunk-CB4WHS4H.js";
145
- import "../chunk-N5WSK2K7.js";
145
+ } from "../chunk-4W52ZKZX.js";
146
+ import "../chunk-BUZIQDFS.js";
147
+ import "../chunk-DIWK3LBC.js";
146
148
  import {
147
149
  getSgCommand,
148
150
  resetDispatchAvailabilityState,
149
151
  resolveManagedToolClient
150
- } from "../chunk-7E2563GA.js";
151
- import "../chunk-MB6PXBUA.js";
152
- import "../chunk-DQZFQSR5.js";
153
- import "../chunk-3YY7IXIL.js";
154
- import "../chunk-WDBICWH3.js";
152
+ } from "../chunk-ZFORSIED.js";
153
+ import "../chunk-5F3XF3SX.js";
154
+ import "../chunk-FRLAUP2B.js";
155
+ import "../chunk-6YUNI7B5.js";
156
+ import "../chunk-7TNILKGY.js";
155
157
  import {
156
158
  SYMBOL_KIND_NAMES,
157
159
  captureReviewGraphStructuralIr,
158
160
  formatReviewGraphRevisionDriftNote,
159
161
  publishReviewGraphFileIr,
160
162
  reviewGraphIrContentHash
161
- } from "../chunk-H7OR7DFZ.js";
163
+ } from "../chunk-4B2YFN4U.js";
162
164
  import {
163
165
  buildSymbolId
164
166
  } from "../chunk-3MED75HT.js";
167
+ import "../chunk-PKLB2XJL.js";
165
168
  import {
166
169
  MAX_LATE_AUX_REARMS,
167
170
  PAST_EOF_STALE_MARKER,
168
171
  PRIMARY_UNAVAILABLE_CAUSE,
169
172
  PartialApplyRecordStore,
170
173
  ReadGuard,
174
+ SERVER_CONFIG_FILE_NAMES,
171
175
  STALE_LINE_MARKER,
172
176
  Text,
173
177
  WriteOrderingGuard,
@@ -225,6 +229,9 @@ import {
225
229
  markWidgetFileBlockersStale,
226
230
  newLspMutationCorrelationId,
227
231
  nextOrderTurn,
232
+ noteWorkspaceDependenciesChanged,
233
+ noteWorkspaceFilesChangedOnDisk,
234
+ peekLSPService,
228
235
  pendingAuxiliaryCoverageSize,
229
236
  primaryUnavailableCause,
230
237
  rearmPendingAuxiliaryCoverage,
@@ -257,9 +264,10 @@ import {
257
264
  touchCompletedConfirmationPolicy,
258
265
  touchCoverageGap,
259
266
  tryWarmAttachedDiagnostics,
267
+ warmAnswerBinding,
260
268
  widgetDiagnosticUri,
261
269
  writeOrderToken
262
- } from "../chunk-FZKFVUEC.js";
270
+ } from "../chunk-2BKUFQKR.js";
263
271
  import {
264
272
  ANY_POSITION,
265
273
  foldedFindingIdentity,
@@ -269,7 +277,7 @@ import {
269
277
  resetMutationAttribution,
270
278
  retainRecordedFindings,
271
279
  stableFindingId
272
- } from "../chunk-XT2HTCJ5.js";
280
+ } from "../chunk-GIRBSBGL.js";
273
281
  import {
274
282
  mapWithConcurrency
275
283
  } from "../chunk-XIMYZ3JA.js";
@@ -293,9 +301,10 @@ import {
293
301
  resetLSPCaseSensitivityState,
294
302
  resolveLspCwdForFile,
295
303
  shouldInitializeSessionRoot
296
- } from "../chunk-R5MOQM2H.js";
297
- import "../chunk-24BILSZW.js";
304
+ } from "../chunk-XYLC35E4.js";
305
+ import "../chunk-DYRZGUMA.js";
298
306
  import {
307
+ PROJECT_VENV_DIR_NAMES,
299
308
  PYTHON_DECLARATION_CONCURRENCY,
300
309
  describePythonCompileWithheld,
301
310
  detectPythonTargetVersion,
@@ -305,7 +314,7 @@ import {
305
314
  partitionOutrankedPythonCompileVerdicts,
306
315
  recordPythonCompileVerdictDrop,
307
316
  resetBoundedTelemetry
308
- } from "../chunk-PR6PO3ES.js";
317
+ } from "../chunk-FHEV6T4L.js";
309
318
  import {
310
319
  PROJECT_SNAPSHOT_VERSION,
311
320
  getProjectSnapshotLegacyPath,
@@ -320,26 +329,27 @@ import {
320
329
  readJsonCache,
321
330
  readProjectSnapshotMeta,
322
331
  saveRuntimeProjectSnapshot
323
- } from "../chunk-RC2Z6K47.js";
332
+ } from "../chunk-ZZDIOAAJ.js";
324
333
  import {
325
334
  SWEEP_IDLE_SAFETY_MARGIN_MS,
326
335
  getFullScanWallClockMs,
327
336
  isWorkspaceSweepActive,
328
337
  runWhenWorkspaceSweepIdle
329
- } from "../chunk-F5Z6URKM.js";
338
+ } from "../chunk-VOXTCULR.js";
330
339
  import "../chunk-5W3R6LFT.js";
331
340
  import {
332
341
  DEPENDENCY_DRIFT_MAX_DELIVERIES,
333
342
  RUNTIME_CONFIG,
343
+ SELF_DRIFT_MAX_DELIVERIES,
334
344
  TreeSitterSymbolExtractor,
335
345
  exceedsLspSyncLimits,
336
346
  resolveImportToFiles,
337
347
  sweepInlineBlockerFreshness,
338
348
  symbolExtractionGrammar
339
- } from "../chunk-MPKRJBPK.js";
340
- import "../chunk-DH5JPM3K.js";
341
- import "../chunk-PKES3ISE.js";
342
- import "../chunk-ZKXQKGWZ.js";
349
+ } from "../chunk-35WKJWO5.js";
350
+ import "../chunk-CUDD35TW.js";
351
+ import "../chunk-7ANZ7XDD.js";
352
+ import "../chunk-WC6WRNQT.js";
343
353
  import {
344
354
  EXT_TO_LANG,
345
355
  classifyTreeSitterWasmError,
@@ -352,41 +362,42 @@ import {
352
362
  queryLoader,
353
363
  reportBundledResourceDirHealth,
354
364
  resolveTreeSitterLanguage
355
- } from "../chunk-L5JYIU47.js";
365
+ } from "../chunk-BHWW6FAX.js";
356
366
  import "../chunk-Z54ZSOBZ.js";
357
367
  import {
358
368
  getUserRuleRoot
359
- } from "../chunk-U6VN4NVL.js";
369
+ } from "../chunk-HHR7WGCI.js";
360
370
  import {
361
371
  dump,
362
372
  resolvePackagePath
363
- } from "../chunk-TIQJPRDD.js";
373
+ } from "../chunk-HKIL6DCL.js";
364
374
  import {
365
375
  SCAN_LANGUAGE_PRIORITY,
366
376
  extensionsForLanguage,
367
377
  extensionsForLanguageToken,
368
378
  resolveLanguage
369
- } from "../chunk-YISME6ON.js";
379
+ } from "../chunk-PPKECBPP.js";
370
380
  import "../chunk-6HWVI6MI.js";
371
- import "../chunk-O4BJFESU.js";
381
+ import "../chunk-5RNB4HVK.js";
372
382
  import {
373
383
  HOOK_WALL_BUDGET_MS
374
384
  } from "../chunk-CKEQFGLT.js";
375
385
  import {
376
386
  bounded,
377
387
  combineAbortSignals,
388
+ untilAborted,
378
389
  withDeadline
379
- } from "../chunk-HO6LWE2E.js";
390
+ } from "../chunk-JYLOYTZD.js";
380
391
  import {
381
392
  centralityFromReverseDeps,
382
393
  getWordIndexBuildStatus,
383
394
  logWordIndex,
384
395
  searchWordIndex,
385
396
  triggerBackgroundWordIndexBuild
386
- } from "../chunk-SNDXCFRS.js";
397
+ } from "../chunk-HUAM7QG3.js";
387
398
  import {
388
399
  getProjectDiagnosticsScannerMaxFiles
389
- } from "../chunk-QOE342SU.js";
400
+ } from "../chunk-HXFUTMX2.js";
390
401
  import {
391
402
  WARM_TURN_END_SCHEMA_VERSION,
392
403
  createWarmIpcLineReader,
@@ -394,33 +405,34 @@ import {
394
405
  ipcPathForCwd,
395
406
  readTurnEndStatus,
396
407
  unlinkStaleUnixSocket
397
- } from "../chunk-AWDSEDER.js";
408
+ } from "../chunk-CZL44WFN.js";
398
409
  import {
399
410
  hashContentBytes,
400
411
  resolveRunnerPath,
401
412
  toRunnerDisplayPath
402
- } from "../chunk-LLS45EWB.js";
413
+ } from "../chunk-VPLBLWFO.js";
403
414
  import "../chunk-2BEMIWEW.js";
404
415
  import "../chunk-IJYGIDF4.js";
405
416
  import {
406
417
  commitDurableStore,
407
418
  resetResolvedPathCache,
408
419
  resetZizmorTokenAvailability
409
- } from "../chunk-KDX35VXP.js";
420
+ } from "../chunk-BQG2QFVO.js";
410
421
  import {
411
422
  resolveToolCwd
412
- } from "../chunk-DPGEAHZT.js";
423
+ } from "../chunk-IYVYZQRL.js";
413
424
  import {
414
425
  _resetPackageManagerCache,
415
426
  findGlobalBinary,
416
427
  pmBinary,
417
428
  resolveNodePackageManager,
418
429
  runScriptArgs
419
- } from "../chunk-NA7SEXHE.js";
430
+ } from "../chunk-VOP4PJKA.js";
420
431
  import {
421
432
  getIsolatedNpxSpawnOptions,
422
433
  probeToolAsync
423
- } from "../chunk-3F6BMY53.js";
434
+ } from "../chunk-JBP7KESM.js";
435
+ import "../chunk-UYXV5NIS.js";
424
436
  import {
425
437
  classifyProbeFailure,
426
438
  createAvailabilityLatch,
@@ -428,20 +440,20 @@ import {
428
440
  logAvailabilityDecision,
429
441
  resetInstallRetryLatches,
430
442
  startHostStallSampler
431
- } from "../chunk-KW5JQPO5.js";
443
+ } from "../chunk-JZRP4DGP.js";
432
444
  import {
433
445
  canRunStartupHeavyScans,
434
446
  detectProjectLanguageProfile,
435
447
  getDefaultStartupTools
436
- } from "../chunk-PUZ3E2J4.js";
437
- import "../chunk-ABPKUVA4.js";
448
+ } from "../chunk-SDFKOLSF.js";
449
+ import "../chunk-BBET6HD6.js";
438
450
  import {
439
451
  collectSourceFilesWithBudgetAsync,
440
452
  getSlowFsVerdict,
441
453
  isSlowFs,
442
454
  slowFsDegradationNotice
443
- } from "../chunk-EKWX4WD3.js";
444
- import "../chunk-ZGSJDWQU.js";
455
+ } from "../chunk-G6JKM4O7.js";
456
+ import "../chunk-O2ARHQKF.js";
445
457
  import {
446
458
  displayProjectDataPath,
447
459
  drainProjectDataDirMigrations,
@@ -457,6 +469,7 @@ import {
457
469
  isRecordableProjectPath,
458
470
  isSubagentSession,
459
471
  isTestFile,
472
+ isWithinPathForm,
460
473
  loadPiLensGlobalConfig,
461
474
  realIsPidAlive,
462
475
  resetProjectDataDirSessionState,
@@ -470,7 +483,7 @@ import {
470
483
  sweepDeadEphemeralDataDirs,
471
484
  updateHeartbeat,
472
485
  withGenerationLockSync
473
- } from "../chunk-YVHBNSME.js";
486
+ } from "../chunk-WMDUT4KH.js";
474
487
  import {
475
488
  createSingleFlight
476
489
  } from "../chunk-AWQWXSW4.js";
@@ -480,7 +493,7 @@ import {
480
493
  } from "../chunk-QYF5S6P6.js";
481
494
  import {
482
495
  detectFileKind
483
- } from "../chunk-RZOXUSPC.js";
496
+ } from "../chunk-G5GV2Q7K.js";
484
497
  import {
485
498
  PathKeyedMap,
486
499
  compareKeys,
@@ -491,12 +504,12 @@ import {
491
504
  provenanceView,
492
505
  resolvePiLensConfig,
493
506
  summarizeConfigResolution
494
- } from "../chunk-KPPJTH44.js";
507
+ } from "../chunk-X35S7HSB.js";
495
508
  import {
496
509
  LSP_NAMESPACE_KEY,
497
510
  getPiLensGlobalConfigPath,
498
511
  resetWorkspaceTopology
499
- } from "../chunk-J6JP25XU.js";
512
+ } from "../chunk-SQC7K3SP.js";
500
513
  import {
501
514
  DEFAULT_MAX_OUTPUT_BYTES,
502
515
  createBoundedOutputSink,
@@ -506,7 +519,7 @@ import {
506
519
  setProjectTrustState,
507
520
  truncatedByOutputCap,
508
521
  writeFileAtomic
509
- } from "../chunk-U5HPROLA.js";
522
+ } from "../chunk-JE6HKLC7.js";
510
523
  import {
511
524
  LENS_TOOL_NAMES,
512
525
  TOOL_REGISTRY,
@@ -522,19 +535,19 @@ import {
522
535
  resolveLensToolName,
523
536
  toolRegistryEntryForMcp,
524
537
  translateGuidanceToolNames
525
- } from "../chunk-WME2OQST.js";
538
+ } from "../chunk-2453RRJ2.js";
526
539
  import {
527
540
  createSubsystemLogger,
528
541
  flushExtensionLog,
529
542
  logExtension
530
- } from "../chunk-KXF5R4UN.js";
543
+ } from "../chunk-WQV6BI4Q.js";
531
544
  import {
532
545
  freshnessFromMtime
533
546
  } from "../chunk-S26LC76R.js";
534
547
  import {
535
548
  claimPhaseOncePerSession,
536
549
  logLatency
537
- } from "../chunk-Z2XAOKHK.js";
550
+ } from "../chunk-565VRUP4.js";
538
551
  import {
539
552
  beginTurnContext,
540
553
  createNdjsonLogger,
@@ -543,11 +556,11 @@ import {
543
556
  isTestMode,
544
557
  runLogCleanup,
545
558
  setTurnContextSession
546
- } from "../chunk-VSFLRN5Y.js";
559
+ } from "../chunk-VLQ7UKZH.js";
547
560
  import "../chunk-LJDODBBZ.js";
548
561
  import {
549
562
  FactStore
550
- } from "../chunk-OSTKYB55.js";
563
+ } from "../chunk-4BKU7PV3.js";
551
564
  import {
552
565
  BoundedFifoMap,
553
566
  BoundedLruCache,
@@ -560,11 +573,13 @@ import {
560
573
  normalizeMapKey,
561
574
  pathsEqual,
562
575
  realpathOrResolve,
576
+ relativeInside,
563
577
  resolveHostToolPath,
578
+ toPosix,
564
579
  toProjectRelativePath,
565
580
  uriToPath,
566
581
  walkUpDirs
567
- } from "../chunk-PQJFG24Z.js";
582
+ } from "../chunk-GMROJJRN.js";
568
583
  import "../chunk-NXL4FFQQ.js";
569
584
 
570
585
  // dist/mcp/server.js
@@ -835,7 +850,6 @@ function compactRenderResult(summarize) {
835
850
 
836
851
  // dist/clients/ast-grep-client.js
837
852
  import * as fs4 from "node:fs";
838
- import * as os from "node:os";
839
853
  import * as path4 from "node:path";
840
854
 
841
855
  // dist/clients/ast-grep-rule-manager.js
@@ -883,14 +897,14 @@ var AstGrepRuleManager = class {
883
897
  fingerprint;
884
898
  ruleDescriptions = null;
885
899
  ruleFingerprint = null;
886
- constructor(ruleDir, log, fingerprint = () => getAstGrepRuleFingerprint()) {
900
+ constructor(ruleDir, log, fingerprint2 = () => getAstGrepRuleFingerprint()) {
887
901
  this.ruleDir = ruleDir;
888
902
  this.log = log;
889
- this.fingerprint = fingerprint;
903
+ this.fingerprint = fingerprint2;
890
904
  }
891
905
  loadRuleDescriptions() {
892
- const fingerprint = this.fingerprint();
893
- if (this.ruleDescriptions !== null && this.ruleFingerprint === fingerprint)
906
+ const fingerprint2 = this.fingerprint();
907
+ if (this.ruleDescriptions !== null && this.ruleFingerprint === fingerprint2)
894
908
  return this.ruleDescriptions;
895
909
  const descriptions = /* @__PURE__ */ new Map();
896
910
  const roots = Array.isArray(this.ruleDir) ? this.ruleDir : [this.ruleDir];
@@ -913,7 +927,7 @@ var AstGrepRuleManager = class {
913
927
  if (!rulesPath) {
914
928
  this.log(`Rule descriptions: no rules directory found in ${possiblePaths.join(", ")}`);
915
929
  this.ruleDescriptions = descriptions;
916
- this.ruleFingerprint = fingerprint;
930
+ this.ruleFingerprint = fingerprint2;
917
931
  return descriptions;
918
932
  }
919
933
  try {
@@ -932,7 +946,7 @@ var AstGrepRuleManager = class {
932
946
  this.log(`Failed to load rule descriptions: ${err.message}`);
933
947
  }
934
948
  this.ruleDescriptions = descriptions;
935
- this.ruleFingerprint = fingerprint;
949
+ this.ruleFingerprint = fingerprint2;
936
950
  return descriptions;
937
951
  }
938
952
  parseRuleYaml(content) {
@@ -1734,7 +1748,7 @@ function reportAstGrepRulesHealth(bundledRuleDir) {
1734
1748
  });
1735
1749
  reportBundledResourceDirHealth("ast-grep-rules-dir-missing", bundledRuleDir, health, "ast-grep rule descriptions");
1736
1750
  }
1737
- function recordAstGrepApply(matches, lineage, toolCallId) {
1751
+ function recordAstGrepApply(matches, { lineage, toolCallId, sessionId } = {}) {
1738
1752
  const bridge = getMutationBridge();
1739
1753
  if (!bridge || matches.length === 0)
1740
1754
  return;
@@ -1765,7 +1779,9 @@ function recordAstGrepApply(matches, lineage, toolCallId) {
1765
1779
  // `ast_grep_replace` call names only when its `paths` are files. The
1766
1780
  // call's own id lets the guard advance exactly the paths that call
1767
1781
  // checked, and end the authorship of every other file it rewrote.
1768
- ...toolCallId !== void 0 && { toolCallId }
1782
+ ...toolCallId !== void 0 && { toolCallId },
1783
+ // #4943: the calling session owns the deferred pass of what it rewrote.
1784
+ ...sessionId !== void 0 && { sessionId }
1769
1785
  });
1770
1786
  }
1771
1787
  }
@@ -1949,7 +1965,7 @@ var AstGrepClient = class {
1949
1965
  allMatches.push(...result.matches);
1950
1966
  }
1951
1967
  if (apply)
1952
- recordAstGrepApply(allMatches, options?.lineage, options?.toolCallId);
1968
+ recordAstGrepApply(allMatches, options);
1953
1969
  return {
1954
1970
  matches: allMatches,
1955
1971
  totalMatches: allMatches.length,
@@ -1996,7 +2012,7 @@ var AstGrepClient = class {
1996
2012
  * Dump the parsed tree-sitter AST for a snippet using ast-grep CLI.
1997
2013
  */
1998
2014
  async dumpAst(source, lang, options = {}) {
1999
- const tmpDir = fs4.mkdtempSync(path4.join(os.tmpdir(), "pi-lens-ast-dump-"));
2015
+ const tmpDir = fs4.mkdtempSync(path4.join(scannerReportParentDir(), "pi-lens-ast-dump-"));
2000
2016
  const tmpFile = path4.join(tmpDir, `snippet.${lang.replace(/[^a-z0-9_-]/gi, "") || "txt"}`);
2001
2017
  try {
2002
2018
  fs4.writeFileSync(tmpFile, source, "utf-8");
@@ -2026,7 +2042,7 @@ var AstGrepClient = class {
2026
2042
  if (shapeError)
2027
2043
  return { valid: false, error: shapeError };
2028
2044
  const snippet = validationSnippetFor(lang);
2029
- const tmpDir = fs4.mkdtempSync(path4.join(os.tmpdir(), "pi-lens-sg-validate-"));
2045
+ const tmpDir = fs4.mkdtempSync(path4.join(scannerReportParentDir(), "pi-lens-sg-validate-"));
2030
2046
  const tmpFile = path4.join(tmpDir, `snippet.${snippet.ext}`);
2031
2047
  try {
2032
2048
  fs4.writeFileSync(tmpFile, snippet.source, "utf-8");
@@ -2073,7 +2089,7 @@ var AstGrepClient = class {
2073
2089
  return { valid: false, error: shapeError };
2074
2090
  const language = extractRuleLanguage(ruleYaml) ?? "typescript";
2075
2091
  const snippet = validationSnippetFor(language);
2076
- const tmpDir = fs4.mkdtempSync(path4.join(os.tmpdir(), "pi-lens-sg-rule-"));
2092
+ const tmpDir = fs4.mkdtempSync(path4.join(scannerReportParentDir(), "pi-lens-sg-rule-"));
2077
2093
  try {
2078
2094
  fs4.writeFileSync(path4.join(tmpDir, `snippet.${snippet.ext}`), snippet.source, "utf-8");
2079
2095
  const result = await this.tempScanDetailed(tmpDir, ruleYaml, options);
@@ -2216,7 +2232,7 @@ var AstGrepClient = class {
2216
2232
  error: applyResult.error
2217
2233
  };
2218
2234
  }
2219
- recordAstGrepApply(preCheck.matches, options?.lineage, options?.toolCallId);
2235
+ recordAstGrepApply(preCheck.matches, options);
2220
2236
  return {
2221
2237
  matches: preCheck.matches,
2222
2238
  totalMatches: preCheck.totalMatches,
@@ -2350,7 +2366,7 @@ import * as path29 from "node:path";
2350
2366
 
2351
2367
  // dist/clients/project-diagnostics/scanner.js
2352
2368
  import * as fs6 from "node:fs";
2353
- import * as os2 from "node:os";
2369
+ import * as os from "node:os";
2354
2370
  import * as path6 from "node:path";
2355
2371
 
2356
2372
  // dist/clients/project-diagnostics/cache.js
@@ -2412,12 +2428,12 @@ function reconcileProjectDiagnosticsSnapshot(snapshot) {
2412
2428
  } catch {
2413
2429
  stat = void 0;
2414
2430
  }
2415
- const fingerprint = snapshot.fileFingerprints?.[filePath];
2416
- if (fingerprint && stat) {
2431
+ const fingerprint2 = snapshot.fileFingerprints?.[filePath];
2432
+ if (fingerprint2 && stat) {
2417
2433
  stale = true;
2418
- if (stat.size === fingerprint.sizeBytes) {
2434
+ if (stat.size === fingerprint2.sizeBytes) {
2419
2435
  try {
2420
- stale = hashDiagnosticContent(fs5.readFileSync(filePath, "utf-8")) !== fingerprint.contentHash;
2436
+ stale = hashDiagnosticContent(fs5.readFileSync(filePath, "utf-8")) !== fingerprint2.contentHash;
2421
2437
  } catch {
2422
2438
  stale = true;
2423
2439
  }
@@ -2704,7 +2720,7 @@ async function scanFileMajorRules(cwd, files, signal) {
2704
2720
  async function scanProjectDiagnostics(options) {
2705
2721
  const cwd = path6.resolve(options.cwd);
2706
2722
  const { signal } = options;
2707
- if (!options.files && isAtOrAboveHomeDir(realpathOrResolve(cwd), realpathOrResolve(options.homeDir ?? os2.homedir()))) {
2723
+ if (!options.files && isAtOrAboveHomeDir(realpathOrResolve(cwd), realpathOrResolve(options.homeDir ?? os.homedir()))) {
2708
2724
  return {
2709
2725
  version: PROJECT_DIAGNOSTICS_CACHE_VERSION,
2710
2726
  cwd,
@@ -2792,7 +2808,7 @@ import { spawn } from "node:child_process";
2792
2808
  import { existsSync as existsSync4 } from "node:fs";
2793
2809
  import { join as join6 } from "node:path";
2794
2810
  function resolveRebuildScript(serverFilePath) {
2795
- return serverFilePath.replace(/\\/g, "/").includes("/dist/") ? "build:dist" : "build";
2811
+ return toPosix(serverFilePath).includes("/dist/") ? "build:dist" : "build";
2796
2812
  }
2797
2813
  function analyzeFileFresh(workerPath, file, cwd, options = {}, timeoutMs = 12e4) {
2798
2814
  return new Promise((resolve32) => {
@@ -2983,29 +2999,29 @@ async function buildBootstrapClients() {
2983
2999
  }
2984
3000
  }
2985
3001
  const [ruffClient, biomeClient, knipClient, todoScanner, jscpdClient, depChecker, testRunnerClient, metricsClient, complexityClient, goClient, govulncheckClient, gitleaksClient, trivyClient, opengrepClient, rustClient, agentBehaviorClient2, deadCodeClients] = await Promise.all([
2986
- load("ruff", async () => new (await import("../chunk-JMEKXFOL.js")).RuffClient()),
2987
- load("biome", async () => new (await import("../chunk-ZMAUPOMG.js")).BiomeClient()),
2988
- load("knip", async () => new (await import("../chunk-3FRLWYBG.js")).KnipClient()),
2989
- load("todo", async () => new (await import("../chunk-4ZYJHQMB.js")).TodoScanner()),
2990
- load("jscpd", async () => new (await import("../chunk-F7K5IBZG.js")).JscpdClient()),
2991
- load("dependency-checker", async () => new (await import("../chunk-7GLOLOSH.js")).DependencyChecker()),
2992
- load("test-runner", async () => new (await import("../chunk-HWDAVBFU.js")).TestRunnerClient()),
2993
- load("metrics", async () => new (await import("../chunk-GNSIWBAT.js")).MetricsClient()),
2994
- load("complexity", async () => new (await import("../chunk-OE5ZBP7F.js")).ComplexityClient()),
3002
+ load("ruff", async () => new (await import("../chunk-X66YJ2SS.js")).RuffClient()),
3003
+ load("biome", async () => new (await import("../chunk-5T5A6YAJ.js")).BiomeClient()),
3004
+ load("knip", async () => new (await import("../chunk-OC7VWJBZ.js")).KnipClient()),
3005
+ load("todo", async () => new (await import("../chunk-6FIRFP6A.js")).TodoScanner()),
3006
+ load("jscpd", async () => new (await import("../chunk-UHHLR2VY.js")).JscpdClient()),
3007
+ load("dependency-checker", async () => new (await import("../chunk-IE5D3RA5.js")).DependencyChecker()),
3008
+ load("test-runner", async () => new (await import("../chunk-57X2CDRX.js")).TestRunnerClient()),
3009
+ load("metrics", async () => new (await import("../chunk-U3AS2FR6.js")).MetricsClient()),
3010
+ load("complexity", async () => new (await import("../chunk-YHGYAEFH.js")).ComplexityClient()),
2995
3011
  // The process-wide singleton, NOT a fresh instance (#2455 fix round 4,
2996
3012
  // F2). `handleSessionStart` reads this object for its "Active tools"
2997
3013
  // line while `resetGoAvailability` re-arms the singleton's latch; a
2998
3014
  // second instance here meant the reset never reached the surface a
2999
3015
  // user actually sees.
3000
- load("go", async () => (await import("../chunk-SHLDT3OI.js")).goClient),
3001
- load("govulncheck", async () => new (await import("../chunk-AKUUMGD5.js")).GovulncheckClient()),
3002
- load("gitleaks", async () => new (await import("../chunk-FB5SCCPT.js")).GitleaksClient()),
3003
- load("trivy", async () => new (await import("../chunk-4LOE5R5P.js")).TrivyClient()),
3004
- load("opengrep", async () => new (await import("../chunk-T7A2HK2B.js")).OpengrepClient()),
3016
+ load("go", async () => (await import("../chunk-GGYOZWHW.js")).goClient),
3017
+ load("govulncheck", async () => new (await import("../chunk-W3BGKBBK.js")).GovulncheckClient()),
3018
+ load("gitleaks", async () => new (await import("../chunk-7CGIDRIK.js")).GitleaksClient()),
3019
+ load("trivy", async () => new (await import("../chunk-6LJOJ6EO.js")).TrivyClient()),
3020
+ load("opengrep", async () => new (await import("../chunk-NSPVR3FN.js")).OpengrepClient()),
3005
3021
  // The process-wide singleton, for the same reason as "go" above.
3006
- load("rust", async () => (await import("../chunk-UF7RTZSO.js")).rustClient),
3007
- load("agent-behavior", async () => (await import("../chunk-ASUXV767.js")).agentBehaviorClient),
3008
- loadList("dead-code", async () => (await import("../chunk-L3CMBQMH.js")).getDeadCodeClients())
3022
+ load("rust", async () => (await import("../chunk-3JAHQBSY.js")).rustClient),
3023
+ load("agent-behavior", async () => (await import("../chunk-LPYTPNOJ.js")).agentBehaviorClient),
3024
+ loadList("dead-code", async () => (await import("../chunk-7MAD5ZAY.js")).getDeadCodeClients())
3009
3025
  ]);
3010
3026
  if (failures.length > 0)
3011
3027
  await logBootstrapFailures(failures);
@@ -3092,7 +3108,7 @@ function resetAnalyzerBootstrapSessionState() {
3092
3108
  }
3093
3109
 
3094
3110
  // dist/clients/formatters-lazy.js
3095
- var lazyFormatters = createLazyImport(() => import("../chunk-LV4UMYVH.js"));
3111
+ var lazyFormatters = createLazyImport(() => import("../chunk-L4NEVZ4T.js"));
3096
3112
  function warmFormatters() {
3097
3113
  return lazyFormatters.get();
3098
3114
  }
@@ -3273,16 +3289,45 @@ function appendProjectChangesAllocated(cwd, buildAll) {
3273
3289
  }
3274
3290
 
3275
3291
  // dist/clients/inline-blocker-fields.js
3292
+ function inlineBlockerSourceOf(diagnostic) {
3293
+ return diagnostic.tool?.trim() || "unknown";
3294
+ }
3276
3295
  function inlineBlockerSources(blockers) {
3277
- return [...new Set(blockers.map((d) => d.tool?.trim() || "unknown"))];
3296
+ return [...new Set(blockers.map(inlineBlockerSourceOf))];
3278
3297
  }
3279
3298
  function inlineBlockerLines(blockers, filePath) {
3280
- const own = normalizeEphemeralMapKey(filePath);
3281
- return blockers.filter(
3282
- // #4509 (N3): a stale entry's line is from older bytes, so it cites
3283
- // none: the past-EOF sweep would retire the whole record on it.
3284
- (d) => !d.positionStale && normalizeEphemeralMapKey(d.filePath) === own
3285
- ).map((d) => d.line).filter((line) => typeof line === "number");
3299
+ return inlineBlockerPlaces(blockers, filePath).map((place) => place.line);
3300
+ }
3301
+ function isCrossFileBlocker(d, filePath) {
3302
+ return !!d.filePath && normalizeEphemeralMapKey(d.filePath) !== normalizeEphemeralMapKey(filePath);
3303
+ }
3304
+ function inlineBlockerPlacement(blockers, filePath) {
3305
+ const places = [];
3306
+ let movedLine = 0;
3307
+ for (const d of blockers) {
3308
+ if (isCrossFileBlocker(d, filePath))
3309
+ continue;
3310
+ if (typeof d.line !== "number")
3311
+ continue;
3312
+ if (d.positionStale) {
3313
+ movedLine += 1;
3314
+ continue;
3315
+ }
3316
+ places.push({
3317
+ line: d.line,
3318
+ rule: d.rule?.trim() || inlineBlockerSourceOf(d)
3319
+ });
3320
+ }
3321
+ return {
3322
+ places,
3323
+ unplaced: {
3324
+ movedLine,
3325
+ noLineInThisFile: blockers.length - places.length - movedLine
3326
+ }
3327
+ };
3328
+ }
3329
+ function inlineBlockerPlaces(blockers, filePath) {
3330
+ return inlineBlockerPlacement(blockers, filePath).places;
3286
3331
  }
3287
3332
 
3288
3333
  // dist/clients/turn-summary.js
@@ -3409,6 +3454,15 @@ var MAX_RESOLVED_BLOCKER_FILES = 10;
3409
3454
  var MAX_OWED_ANCHORS = 16;
3410
3455
  var TOOL_CALL_ATTRIBUTION_CAPACITY = 256;
3411
3456
  var TOOL_CALL_ATTRIBUTION_TTL_MS = 5 * 6e4;
3457
+ function narrowedRecord(existing, kept) {
3458
+ return {
3459
+ ...existing,
3460
+ summary: formatDiagnostics(kept, "blocking").trim(),
3461
+ diagnostics: kept,
3462
+ sources: inlineBlockerSources(kept),
3463
+ lines: inlineBlockerLines(kept, existing.filePath)
3464
+ };
3465
+ }
3412
3466
  var TURN_WARNINGS_CELL = "turn-warnings";
3413
3467
  function newTurnWarningsCell() {
3414
3468
  return { actionable: /* @__PURE__ */ new Map(), codeQuality: /* @__PURE__ */ new Map() };
@@ -4547,13 +4601,7 @@ var RuntimeCoordinator = class {
4547
4601
  this._pendingInlineBlockers.delete(key);
4548
4602
  return retired.length;
4549
4603
  }
4550
- this._pendingInlineBlockers.set(key, {
4551
- ...existing,
4552
- summary: formatDiagnostics(kept, "blocking").trim(),
4553
- diagnostics: kept,
4554
- sources: inlineBlockerSources(kept),
4555
- lines: inlineBlockerLines(kept, existing.filePath)
4556
- });
4604
+ this._pendingInlineBlockers.set(key, narrowedRecord(existing, kept));
4557
4605
  return retired.length;
4558
4606
  }
4559
4607
  /**
@@ -4683,11 +4731,12 @@ var RuntimeCoordinator = class {
4683
4731
  * {@link markInlineBlockerStale}: it RE-ARMS rather than latching, so a
4684
4732
  * file whose bytes drift and then come back (a checkout, a revert, an
4685
4733
  * editor writing the original content) un-demotes on the next sweep
4686
- * instead of staying demoted for the session. That re-arm is what lets
4687
- * this axis skip the #1950 delivery cap entirely — a record that can heal
4688
- * needs no bounded-noise retirement, and applying the cap here would walk
4689
- * an ast-grep or tree-sitter security finding out of turn-end rendering
4690
- * permanently (#2982 review).
4734
+ * instead of staying demoted for the session. That re-arm covers a file whose
4735
+ * bytes COME BACK; it does not cover an agent rewrite that never returns to
4736
+ * them, which is why this axis carries its own delivery cap
4737
+ * (`SELF_DRIFT_MAX_DELIVERIES`, #4990) — a record that heals before the cap
4738
+ * un-demotes and is never retired, so the security-provenance concern
4739
+ * (#2982 review) still holds.
4691
4740
  *
4692
4741
  * Composes with the sibling gates the same way they compose with each
4693
4742
  * other: it never touches a record another gate demoted, and never heals a
@@ -4704,7 +4753,7 @@ var RuntimeCoordinator = class {
4704
4753
  const currentlySelfDrift = !!existing.stale && existing.staleReason === "self-drift";
4705
4754
  if (currentlySelfDrift === isSelfDrift)
4706
4755
  return false;
4707
- const { staleReason: _cleared, ...rest } = existing;
4756
+ const { staleReason: _cleared, staleDeliveryCount: _clearedCount, ...rest } = existing;
4708
4757
  this._pendingInlineBlockers.set(key, {
4709
4758
  ...rest,
4710
4759
  stale: isSelfDrift,
@@ -4785,14 +4834,14 @@ var RuntimeCoordinator = class {
4785
4834
  /**
4786
4835
  * #1950: commit one more turn end that re-served this record while
4787
4836
  * `stale`. The caller (`runtime-turn.ts`) only calls this for a
4788
- * `"dependency-drift"` demotion — a `"past-eof"` demotion retires after
4789
- * its own single delivery (#1944, `retireDemotedPastEofBlocker`) and
4790
- * never accumulates a count — and only AFTER confirming the turn's
4791
- * content will not be suppressed by the signature dedupe (see
4792
- * {@link peekInlineBlockerStaleDeliveryCount}), so this counts ACTUAL
4793
- * deliveries the agent saw, not turn-end loop iterations. Returns the new
4794
- * count, or 0 when there is no entry to count against (already retired,
4795
- * or never recorded).
4837
+ * `"dependency-drift"` or `"self-drift"` demotion — a `"past-eof"`
4838
+ * demotion retires after its own single delivery (#1944,
4839
+ * `retireDemotedPastEofBlocker`) and never accumulates a count — and only
4840
+ * AFTER confirming the turn's content will not be suppressed by the
4841
+ * signature dedupe (see {@link peekInlineBlockerStaleDeliveryCount}), so
4842
+ * this counts ACTUAL deliveries the agent saw, not turn-end loop
4843
+ * iterations. Returns the new count, or 0 when there is no entry to count
4844
+ * against (already retired, or never recorded).
4796
4845
  */
4797
4846
  incrementInlineBlockerStaleDelivery(filePath) {
4798
4847
  const key = filePath;
@@ -4807,30 +4856,33 @@ var RuntimeCoordinator = class {
4807
4856
  return next;
4808
4857
  }
4809
4858
  /**
4810
- * #1950: retire a dependency-drift demotion once it has been delivered
4811
- * `DEPENDENCY_DRIFT_MAX_DELIVERIES` times with no re-run confirming or
4812
- * clearing it. Unlike {@link retireDemotedPastEofBlocker}, the record is
4813
- * NOT provably unrecoverable — its coordinates are still in bounds, and a
4814
- * fresh dispatch of the file could still confirm or clear it. This is a
4815
- * bounded-noise cap, not a "this can never resolve" verdict, and the
4816
- * caller's ledger reason must say so (`demoted-finding-retired`'s "capped,
4817
- * re-run can still confirm" vs. past-EOF's "retired, unrecoverable").
4859
+ * #1950/#4990: retire a drift demotion once it has been delivered its axis's
4860
+ * cap with no re-run confirming or clearing it.
4861
+ * `"dependency-drift"` retires at `DEPENDENCY_DRIFT_MAX_DELIVERIES` and
4862
+ * `"self-drift"` at `SELF_DRIFT_MAX_DELIVERIES` (both decided by the caller,
4863
+ * `runtime-turn.ts`, which also owns the count). Unlike
4864
+ * {@link retireDemotedPastEofBlocker}, the record is NOT provably
4865
+ * unrecoverable — its coordinates are still in bounds, and a fresh dispatch
4866
+ * of the file could still confirm or clear it. This is a bounded-noise cap,
4867
+ * not a "this can never resolve" verdict, and the caller's ledger reason must
4868
+ * say so (`demoted-finding-retired`'s "capped, re-run can still confirm" vs.
4869
+ * past-EOF's "retired, unrecoverable").
4818
4870
  *
4819
- * Only ever touches this gate's OWN demotion (`staleReason ===
4820
- * "dependency-drift"`) — a past-EOF demotion on the same file is that
4821
- * gate's own record to retire, not this one's.
4871
+ * Only ever touches the named axis's OWN demotion: a record demoted by a
4872
+ * sibling gate on the same file is that gate's record to retire, not this
4873
+ * one's.
4822
4874
  *
4823
4875
  * @returns true when an entry was retired — the caller records it, so the
4824
4876
  * suppression is never silent (#1432 Gap 1).
4825
4877
  */
4826
- retireDemotedDependencyDriftBlocker(filePath) {
4878
+ retireDemotedDriftBlocker(filePath, reason) {
4827
4879
  const key = filePath;
4828
4880
  const existing = this._pendingInlineBlockers.get(key);
4829
4881
  if (!existing)
4830
4882
  return false;
4831
4883
  if (!existing.stale)
4832
4884
  return false;
4833
- if (existing.staleReason !== "dependency-drift")
4885
+ if (existing.staleReason !== reason)
4834
4886
  return false;
4835
4887
  this._pendingInlineBlockers.delete(key);
4836
4888
  return true;
@@ -4868,13 +4920,22 @@ var RuntimeCoordinator = class {
4868
4920
  * `semantic === "blocking"` diagnostic across all runners, so eslint,
4869
4921
  * biome-check, actionlint, elixir/gleam-check and ast-grep security rules all
4870
4922
  * land in this map. A language-server check knows nothing about any of them,
4871
- * so `coveredSources` must be a SUPERSET of the recorded sources or the entry
4872
- * stands. This is a commit gate: a record whose provenance is unknown (no
4873
- * `sources`) fails CLOSED and is never retired, because "we don't know what
4874
- * raised this" must not resolve to "an LSP check can clear it".
4923
+ * so the coverage test is per ROW (#4990 gap 1): the diagnostics whose source
4924
+ * the verdict covered leave the record, the rest stay, and a record with no
4925
+ * structured rows fails CLOSED and is never retired, because "we don't know
4926
+ * what raised this" must not resolve to "an LSP check can clear it".
4875
4927
  *
4876
- * @returns true when an entry was retired — the caller logs it, so an
4877
- * eviction is never silent (#1432 Gap 1).
4928
+ * Before #4990 the test was all-or-nothing on `record.sources`, so a record
4929
+ * with `["lsp", "oxlint"]` outlived a confirmed-clean typescript verdict
4930
+ * forever: one server cannot speak for the oxlint row, and the oxlint row was
4931
+ * never re-dispatched either. Per-source row retirement is the same filter
4932
+ * the record's own builder already applies (`inlineBlockerSources`), so a
4933
+ * partly-covered record narrows to what the verdict did not speak for and
4934
+ * keeps gating only on those rows.
4935
+ *
4936
+ * @returns true when the record was retired OR narrowed (at least one source
4937
+ * row left it). The caller records either, so a drop is never silent
4938
+ * (#1432 Gap 1).
4878
4939
  */
4879
4940
  retireInlineBlockerOnConfirmedClean(filePath, confirmedAtWriteOrder, coveredSources) {
4880
4941
  const key = filePath;
@@ -4887,12 +4948,106 @@ var RuntimeCoordinator = class {
4887
4948
  if (!existing.sources || existing.sources.length === 0)
4888
4949
  return false;
4889
4950
  const covered = new Set(coveredSources ?? []);
4890
- if (!existing.sources.every((source) => covered.has(source)))
4951
+ if (existing.sources.every((source) => covered.has(source))) {
4952
+ this.noteResolvedBlockerFile(existing, void 0, true);
4953
+ this._pendingInlineBlockers.delete(key);
4954
+ return true;
4955
+ }
4956
+ const diagnostics = existing.diagnostics;
4957
+ if (!diagnostics || diagnostics.length === 0)
4891
4958
  return false;
4892
- this.noteResolvedBlockerFile(existing, void 0, true);
4893
- this._pendingInlineBlockers.delete(key);
4959
+ const kept = diagnostics.filter((diagnostic) => !covered.has(inlineBlockerSourceOf(diagnostic)));
4960
+ if (kept.length === diagnostics.length)
4961
+ return false;
4962
+ if (kept.length === 0) {
4963
+ this.noteResolvedBlockerFile(existing, void 0, true);
4964
+ this._pendingInlineBlockers.delete(key);
4965
+ return true;
4966
+ }
4967
+ this._pendingInlineBlockers.set(key, narrowedRecord(existing, kept));
4894
4968
  return true;
4895
4969
  }
4970
+ /**
4971
+ * #5020: retire the rows of other files' records that cite a file a fresh
4972
+ * observation has settled. A chart-wide runner (helm-lint, helm-render) or an
4973
+ * import-following one (mypy, phpstan) reports a blocking row against a file
4974
+ * it did not dispatch for, so the row lands in the WRITTEN file's record
4975
+ * (#1641). That record is re-taken only by a dispatch of the written file,
4976
+ * which the agent has no reason to make once the cited file is fixed or gone:
4977
+ * `clearInlineBlockers` never ran for it, and the commit gate stayed shut with
4978
+ * nothing left to fix.
4979
+ *
4980
+ * The row is another file's claim, so the cited file's own state retires it
4981
+ * (`why`), and only two states do. `"cited-file-clean"`: the cited file was
4982
+ * dispatched and the runner that raised the row answered with no blocker of
4983
+ * its own on it (the caller proves that; `shouldRetire` is its verdict per
4984
+ * row). `"cited-file-missing"`: the cited file no longer exists, which the
4985
+ * #1245 reconcile already decides for a record's OWN file. Everything else
4986
+ * stays, rows with no structured diagnostics included (fail closed), and so
4987
+ * does a row that cites no file (`isCrossFileBlocker` is total).
4988
+ *
4989
+ * A clean verdict retires only a record it is strictly newer than
4990
+ * (`confirmedAtWriteOrder`, turn first), as `retireInlineBlockerOnConfirmedClean`
4991
+ * orders its own: a slow old clean must not erase a newer observation.
4992
+ *
4993
+ * `of` limits the retire to one session's records, the partition
4994
+ * `getInlineBlockersSnapshot` reads. Omitted, every session's record is
4995
+ * judged.
4996
+ *
4997
+ * @returns one entry per record that lost rows, with the session that owns
4998
+ * it, so the caller can bring the commit gate (the latch and the persisted
4999
+ * record) back in line. Counted once per file in the degradation ledger.
5000
+ */
5001
+ retireForeignRows(why, shouldRetire, confirmedAtWriteOrder, of) {
5002
+ const changed = [];
5003
+ for (const existing of this.getInlineBlockersSnapshot(of)) {
5004
+ const key = existing.filePath;
5005
+ if (confirmedAtWriteOrder !== void 0 && existing.writeOrder !== void 0 && confirmedAtWriteOrder <= existing.writeOrder)
5006
+ continue;
5007
+ const diagnostics = existing.diagnostics;
5008
+ if (!diagnostics)
5009
+ continue;
5010
+ const kept = diagnostics.filter((row) => !(isCrossFileBlocker(row, existing.filePath) && shouldRetire(row)));
5011
+ if (kept.length === diagnostics.length)
5012
+ continue;
5013
+ changed.push({
5014
+ filePath: existing.filePath,
5015
+ owner: existing.session ?? this._telemetrySessionId
5016
+ });
5017
+ incrementDegradationCount({
5018
+ kind: "cross-file-row-retired",
5019
+ subject: normalizeMapKey(existing.filePath),
5020
+ reason: why === "cited-file-clean" ? "a row naming another file left the record: that file was dispatched and its runner reported nothing on it (#5020)" : "a row naming another file left the record: that file no longer exists (#5020)"
5021
+ });
5022
+ if (kept.length === 0) {
5023
+ if (why === "cited-file-clean")
5024
+ this.noteResolvedBlockerFile(existing, void 0, true);
5025
+ this._pendingInlineBlockers.delete(key);
5026
+ } else {
5027
+ this._pendingInlineBlockers.set(key, narrowedRecord(existing, kept));
5028
+ }
5029
+ }
5030
+ return changed;
5031
+ }
5032
+ /**
5033
+ * #5020: the rows whose cited file is gone, for the two reads the commit gate
5034
+ * depends on (the turn end and the gate's own evaluation). Only an ABSOLUTE
5035
+ * cite is judged: a relative one is relative to whatever the runner ran in,
5036
+ * which the record does not keep, so a row that cannot be placed stays
5037
+ * (fail closed) rather than being resolved against a guess.
5038
+ *
5039
+ * Both reads persist what they retire into the caller's own cwd cache, and
5040
+ * each caller retires only its OWN session's records (`of`, required): the
5041
+ * acting session's own records, whose cache is the coordinator root's cache
5042
+ * or the session cwd's, whichever wrote them. A sweep by another session at
5043
+ * another cwd would write the wrong project's cache and leave the owner's
5044
+ * record refusing its next commit (PR #5033 round 3, F1 and item 4).
5045
+ * Another session's dead cite is that session's own turn end or commit gate
5046
+ * to retire.
5047
+ */
5048
+ retireForeignRowsOfMissingFiles(of) {
5049
+ return this.retireForeignRows("cited-file-missing", (row) => path8.isAbsolute(row.filePath) && !fs8.existsSync(row.filePath), void 0, of);
5050
+ }
4896
5051
  /**
4897
5052
  * #3218 criterion 2: a retirement no turn_end has delivered yet. The
4898
5053
  * read-only turn_end path uses it to fall through to the composer instead of
@@ -4965,8 +5120,8 @@ var RuntimeCoordinator = class {
4965
5120
  */
4966
5121
  getInlineBlockersSnapshot(of) {
4967
5122
  this.reconcileInlineBlockers();
4968
- const records = [...this._pendingInlineBlockers.values()];
4969
- return of ? records.filter((entry) => this.ownedBy(entry, of.sessionId)) : records;
5123
+ const records2 = [...this._pendingInlineBlockers.values()];
5124
+ return of ? records2.filter((entry) => this.ownedBy(entry, of.sessionId)) : records2;
4970
5125
  }
4971
5126
  consumeInlineBlockers() {
4972
5127
  const entries = this.getInlineBlockersSnapshot();
@@ -5236,9 +5391,9 @@ var RuntimeCoordinator = class {
5236
5391
  * flush call sites should prefer {@link claimDeferredFormatFiles}.
5237
5392
  */
5238
5393
  consumeDeferredFormatFiles() {
5239
- const records = [...this._pendingDeferredMutations.values()];
5394
+ const records2 = [...this._pendingDeferredMutations.values()];
5240
5395
  this._pendingDeferredMutations.clear();
5241
- return records;
5396
+ return records2;
5242
5397
  }
5243
5398
  /**
5244
5399
  * Ownership-filtered drain (#791). Claims and removes only the records
@@ -5265,23 +5420,32 @@ var RuntimeCoordinator = class {
5265
5420
  * observability — deleting it here would drop it forever with no
5266
5421
  * origin ever able to reclaim it.
5267
5422
  *
5423
+ * `ownedOnly` is a concurrent secondary's drain (#4943): it claims exactly
5424
+ * the records its own known session id owns. An ownerless record, another
5425
+ * session's and a stale orphan are all left for the primary, so a
5426
+ * secondary with no stable id claims nothing.
5427
+ *
5268
5428
  * Returns the claimed records, the left-queued mismatched-origin records,
5269
5429
  * and per-skipped record why it was left behind — callers use this for
5270
5430
  * `agent_end`'s latency-log provenance and for the "stale fallback
5271
5431
  * fired"/"orphan mismatch" log lines.
5272
5432
  */
5273
- claimDeferredFormatFiles(currentSessionId, now, staleAfterMs, currentOriginCwd) {
5433
+ claimDeferredFormatFiles(currentSessionId, now, staleAfterMs, currentOriginCwd, ownedOnly = false) {
5274
5434
  const claimed = [];
5275
5435
  const staleClaimed = [];
5276
5436
  const deferredToOwner = [];
5277
5437
  const droppedOrphans = [];
5278
5438
  for (const [key, record] of this._pendingDeferredMutations) {
5279
- const sameSession = record.ownerSessionId === void 0 || currentSessionId === void 0 || record.ownerSessionId === currentSessionId;
5439
+ const sameSession = ownedOnly ? currentSessionId !== void 0 && record.ownerSessionId === currentSessionId : record.ownerSessionId === void 0 || currentSessionId === void 0 || record.ownerSessionId === currentSessionId;
5280
5440
  if (sameSession) {
5281
5441
  claimed.push(record);
5282
5442
  this._pendingDeferredMutations.delete(key);
5283
5443
  continue;
5284
5444
  }
5445
+ if (ownedOnly) {
5446
+ deferredToOwner.push(record);
5447
+ continue;
5448
+ }
5285
5449
  const age = now - record.lastTouchedAt;
5286
5450
  if (age > staleAfterMs) {
5287
5451
  const originMatches = currentOriginCwd === void 0 || pathsEqual(record.originCwd, currentOriginCwd);
@@ -5298,8 +5462,8 @@ var RuntimeCoordinator = class {
5298
5462
  return { claimed, staleClaimed, deferredToOwner, droppedOrphans };
5299
5463
  }
5300
5464
  /** Return claimed records that were never started by an aborted drain. */
5301
- requeueDeferredFormatFiles(records) {
5302
- for (const record of records) {
5465
+ requeueDeferredFormatFiles(records2) {
5466
+ for (const record of records2) {
5303
5467
  const key = record.filePath;
5304
5468
  const existing = this._pendingDeferredMutations.get(key);
5305
5469
  if (existing) {
@@ -5317,11 +5481,11 @@ var RuntimeCoordinator = class {
5317
5481
  });
5318
5482
  }
5319
5483
  }
5320
- claimDeferredMutations(currentSessionId, now, staleAfterMs, currentOriginCwd) {
5321
- return this.claimDeferredFormatFiles(currentSessionId, now, staleAfterMs, currentOriginCwd);
5484
+ claimDeferredMutations(currentSessionId, now, staleAfterMs, currentOriginCwd, ownedOnly = false) {
5485
+ return this.claimDeferredFormatFiles(currentSessionId, now, staleAfterMs, currentOriginCwd, ownedOnly);
5322
5486
  }
5323
- requeueDeferredMutations(records) {
5324
- this.requeueDeferredFormatFiles(records);
5487
+ requeueDeferredMutations(records2) {
5488
+ this.requeueDeferredFormatFiles(records2);
5325
5489
  }
5326
5490
  shouldWarmLspOnRead(filePath, maxAgeMs = 12e4) {
5327
5491
  const state = this._lspReadWarmState.get(path8.resolve(filePath));
@@ -5350,7 +5514,7 @@ var RuntimeCoordinator = class {
5350
5514
 
5351
5515
  // dist/clients/runtime-session.js
5352
5516
  import * as nodeFs from "node:fs";
5353
- import * as os3 from "node:os";
5517
+ import * as os2 from "node:os";
5354
5518
  import * as path13 from "node:path";
5355
5519
 
5356
5520
  // dist/clients/message-end-attribution.js
@@ -5418,7 +5582,7 @@ function findMarkdownFiles(dir, baseDir, depth = 0, collected = { count: 0 }) {
5418
5582
  source: path10.relative(baseDir, dir) || path10.basename(baseDir),
5419
5583
  name: entry.name,
5420
5584
  filePath: fullPath,
5421
- relativePath: path10.relative(baseDir, fullPath).replace(/\\/g, "/")
5585
+ relativePath: toPosix(path10.relative(baseDir, fullPath))
5422
5586
  });
5423
5587
  }
5424
5588
  }
@@ -5725,7 +5889,7 @@ function logHostReadyDelay(deps, cwd) {
5725
5889
  function resolveSnapshotRoot(cwd) {
5726
5890
  const resolvedCwd = path13.resolve(cwd);
5727
5891
  const nearest = findNearestProjectRoot(resolvedCwd);
5728
- if (!nearest || isAtOrAboveHomeDir(realpathOrResolve(nearest), realpathOrResolve(os3.homedir()))) {
5892
+ if (!nearest || isAtOrAboveHomeDir(realpathOrResolve(nearest), realpathOrResolve(os2.homedir()))) {
5729
5893
  return resolvedCwd;
5730
5894
  }
5731
5895
  return nearest;
@@ -6016,8 +6180,8 @@ async function igniteDominantLanguageWarm(cwd, runtime, sessionGeneration, dbg)
6016
6180
  if (!runtime.isCurrentSession(sessionGeneration))
6017
6181
  return;
6018
6182
  const lspService = (await loadLspService()).getLSPService();
6019
- const { collectSourceFilesAsync } = await import("../chunk-U7BD2QL7.js");
6020
- const { CODE_KINDS, detectFileKind: detectFileKind2 } = await import("../chunk-U2SDMG7C.js");
6183
+ const { collectSourceFilesAsync } = await import("../chunk-I22THIHI.js");
6184
+ const { CODE_KINDS, detectFileKind: detectFileKind2 } = await import("../chunk-NM2NWH55.js");
6021
6185
  const files = await collectSourceFilesAsync(cwd, {
6022
6186
  inspectGeneratedHeaders: false
6023
6187
  });
@@ -6091,7 +6255,7 @@ function scheduleManagedToolRefresh(dbg, rulePack) {
6091
6255
  managedToolRefreshTimer = void 0;
6092
6256
  void (async () => {
6093
6257
  try {
6094
- const refresh = await import("../chunk-CE6VMBCB.js");
6258
+ const refresh = await import("../chunk-XOMGO63G.js");
6095
6259
  const outcome = await refresh.runManagedToolRefresh(void 0, {
6096
6260
  rulePack
6097
6261
  });
@@ -6141,7 +6305,7 @@ function scanOneTodoFile(scanner, filePath, items) {
6141
6305
  async function collectTodoBaselineItems(scanner, analysisRoot, stillCurrent) {
6142
6306
  const items = [];
6143
6307
  try {
6144
- const { getSourceFilesAsync } = await import("../chunk-CTADOKYM.js");
6308
+ const { getSourceFilesAsync } = await import("../chunk-447YZL4S.js");
6145
6309
  const files = await getSourceFilesAsync(analysisRoot, true);
6146
6310
  if (!stillCurrent())
6147
6311
  return items;
@@ -6170,7 +6334,7 @@ async function buildOrRefreshWordIndex(args) {
6170
6334
  const snapshot = loadProjectSnapshot(snapshotRoot);
6171
6335
  const snapshotLoadMs = Date.now() - snapshotLoadStartMs;
6172
6336
  if (snapshot?.wordIndex) {
6173
- const { deserializeWordIndex, refreshWordIndexIncrementally, countWordIndexPostingEntries: countWordIndexPostingEntries2, estimateWordIndexResidentBytes: estimateWordIndexResidentBytes2, notifyWordIndexPublished: notifyWordIndexPublished2 } = await import("../chunk-OXOI55RU.js");
6337
+ const { deserializeWordIndex, refreshWordIndexIncrementally, countWordIndexPostingEntries: countWordIndexPostingEntries2, estimateWordIndexResidentBytes: estimateWordIndexResidentBytes2, notifyWordIndexPublished: notifyWordIndexPublished2 } = await import("../chunk-O4N5BQ3T.js");
6174
6338
  const deserializeStartMs = Date.now();
6175
6339
  const index = deserializeWordIndex(snapshot.wordIndex);
6176
6340
  const deserializeMs = Date.now() - deserializeStartMs;
@@ -6243,7 +6407,7 @@ async function buildOrRefreshWordIndex(args) {
6243
6407
  }
6244
6408
  }
6245
6409
  }
6246
- const { buildWordIndexAsync, collectWordIndexDocs, countWordIndexPostingEntries, estimateWordIndexResidentBytes, notifyWordIndexPublished } = await import("../chunk-OXOI55RU.js");
6410
+ const { buildWordIndexAsync, collectWordIndexDocs, countWordIndexPostingEntries, estimateWordIndexResidentBytes, notifyWordIndexPublished } = await import("../chunk-O4N5BQ3T.js");
6247
6411
  const docs = await collectWordIndexDocs(analysisRoot, () => runtime.isCurrentSession(sessionGeneration), rebuildPreflightFiles);
6248
6412
  if (!runtime.isCurrentSession(sessionGeneration))
6249
6413
  return;
@@ -6622,9 +6786,9 @@ function scheduleStartupScansWithClients(deps, runtime, sessionGeneration, analy
6622
6786
  });
6623
6787
  let callGraphIdentity;
6624
6788
  const callGraphTask = runTask("call-graph", async () => {
6625
- const { FactStore: FactStore2 } = await import("../chunk-F6X3YJWD.js");
6626
- const { buildOrUpdateGraph, extractSymbolsAndRefsFromGraph, getReviewGraphCacheIdentity } = await import("../chunk-3K2F6UDZ.js");
6627
- const { buildCallGraph, saveCallGraph, loadCallGraph: loadCallGraph2 } = await import("../chunk-2TF6RXWB.js");
6789
+ const { FactStore: FactStore2 } = await import("../chunk-PIQQM32Y.js");
6790
+ const { buildOrUpdateGraph, extractSymbolsAndRefsFromGraph, getReviewGraphCacheIdentity } = await import("../chunk-T2S3FNNJ.js");
6791
+ const { buildCallGraph, saveCallGraph, loadCallGraph: loadCallGraph2 } = await import("../chunk-TV6RXRYH.js");
6628
6792
  if (!runtime.isCurrentSession(sessionGeneration))
6629
6793
  return;
6630
6794
  const startMs = Date.now();
@@ -6665,7 +6829,7 @@ function scheduleStartupScansWithClients(deps, runtime, sessionGeneration, analy
6665
6829
  return;
6666
6830
  if (!runtime.callGraph)
6667
6831
  return;
6668
- const { buildCodebaseModel, saveCodebaseModel, DEFAULT_CODEBASE_MODEL_TOKEN_BUDGET } = await import("../chunk-LS3QJRUB.js");
6832
+ const { buildCodebaseModel, saveCodebaseModel, DEFAULT_CODEBASE_MODEL_TOKEN_BUDGET } = await import("../chunk-XWIME22V.js");
6669
6833
  if (!callGraphIdentity)
6670
6834
  return;
6671
6835
  const model = buildCodebaseModel(runtime.callGraph, analysisRoot, DEFAULT_CODEBASE_MODEL_TOKEN_BUDGET, callGraphIdentity);
@@ -6874,8 +7038,8 @@ async function handleSessionStart(deps) {
6874
7038
  try {
6875
7039
  warmupDbg("warmup: starting background warmup");
6876
7040
  const scanContextStartedAt = Date.now();
6877
- const startupScanModule = await import("../chunk-KKCK636N.js");
6878
- const languageProfileModule = await import("../chunk-4L36HG27.js");
7041
+ const startupScanModule = await import("../chunk-4QG55RRC.js");
7042
+ const languageProfileModule = await import("../chunk-R2QQC33W.js");
6879
7043
  const warmupSnapshotRoot = resolveSnapshotRoot(warmupCwd);
6880
7044
  const cachedSnapshot = loadProjectSnapshot(warmupSnapshotRoot);
6881
7045
  warmupOwnSnapshotRead = cachedSnapshot ? {
@@ -7441,7 +7605,7 @@ function createActionableWarningId(args) {
7441
7605
  });
7442
7606
  }
7443
7607
  function legacyActionableWarningId(args) {
7444
- const rel = path15.relative(args.cwd, args.filePath).replace(/\\/g, "/");
7608
+ const rel = toPosix(path15.relative(args.cwd, args.filePath));
7445
7609
  const legacyRelativeFile = rel && !rel.startsWith("..") ? rel : normalizeMapKey(args.filePath);
7446
7610
  const parts = [
7447
7611
  legacyRelativeFile,
@@ -7585,9 +7749,9 @@ function recordFromLspDiagnostic(diag, filePath, cwd) {
7585
7749
  origin: "lsp"
7586
7750
  };
7587
7751
  }
7588
- function mergeWarnings(records) {
7752
+ function mergeWarnings(records2) {
7589
7753
  const byId = /* @__PURE__ */ new Map();
7590
- for (const record of records) {
7754
+ for (const record of records2) {
7591
7755
  const existing = byId.get(record.id);
7592
7756
  if (!existing) {
7593
7757
  byId.set(record.id, { ...record, actions: [...record.actions] });
@@ -7642,7 +7806,7 @@ function boundedNumber(value, fallback) {
7642
7806
  }
7643
7807
  async function buildActionableWarningsReport(args) {
7644
7808
  const cwd = path15.resolve(args.cwd);
7645
- const records = [...args.dispatchWarnings];
7809
+ const records2 = [...args.dispatchWarnings];
7646
7810
  const lspService = getLSPService();
7647
7811
  const excludeServerIds = args.getFlag ? configDisabledAuxiliaryLspServerIds(args.getFlag) : void 0;
7648
7812
  const observedAtByPath = /* @__PURE__ */ new Map();
@@ -7731,7 +7895,7 @@ async function buildActionableWarningsReport(args) {
7731
7895
  unchecked += targets.length - targets.indexOf(target);
7732
7896
  break;
7733
7897
  }
7734
- records.push(...await enrichFileFromLsp(cwd, args, target, inBandDeps));
7898
+ records2.push(...await enrichFileFromLsp(cwd, args, target, inBandDeps));
7735
7899
  observedAtByPath.set(normalizeMapKey(target.filePath), (/* @__PURE__ */ new Date()).toISOString());
7736
7900
  }
7737
7901
  };
@@ -7757,7 +7921,7 @@ async function buildActionableWarningsReport(args) {
7757
7921
  });
7758
7922
  args.dbg?.(`actionable_warnings: an earlier deferred LSP pull still holds the slot \u2014 skipping ${cold.length} fresh pull(s) this turn`);
7759
7923
  } else {
7760
- const carried = [...records];
7924
+ const carried = [...records2];
7761
7925
  const deferredArgs = args;
7762
7926
  const loopSignal = combineAbortSignals(args.signal, deferredSignal) ?? deferredSignal;
7763
7927
  const deferredDeps = {
@@ -7835,7 +7999,7 @@ async function buildActionableWarningsReport(args) {
7835
7999
  });
7836
8000
  }
7837
8001
  }
7838
- return assembleReport(cwd, args, records, {
8002
+ return assembleReport(cwd, args, records2, {
7839
8003
  observedAtByPath,
7840
8004
  fallbackObservedAt: buildStartedAt
7841
8005
  });
@@ -7973,8 +8137,8 @@ async function enrichFileFromLsp(cwd, args, target, deps) {
7973
8137
  });
7974
8138
  return out;
7975
8139
  }
7976
- function assembleReport(cwd, args, records, stamps) {
7977
- const merged = mergeWarnings(records);
8140
+ function assembleReport(cwd, args, records2, stamps) {
8141
+ const merged = mergeWarnings(records2);
7978
8142
  updateWarningState(cwd, merged);
7979
8143
  const reportWarnings = merged.map(({ legacyId: _legacyId, ...rest }) => rest);
7980
8144
  const byFile = /* @__PURE__ */ new Map();
@@ -8892,11 +9056,14 @@ function retireInlineBlockerAndResyncGuard(args) {
8892
9056
  const retired = args.runtime.retireInlineBlockerOnConfirmedClean(args.filePath, args.writeIndex, args.coveredSources);
8893
9057
  if (!retired)
8894
9058
  return false;
9059
+ resyncGitGuardAfterRetire({ ...args, owner });
9060
+ return true;
9061
+ }
9062
+ function resyncGitGuardAfterRetire(args) {
8895
9063
  args.runtime.updateGitGuardStatus(false, "");
8896
9064
  if (args.lensGuardEnabled) {
8897
- syncGitGuardRecord(args.runtime, args.cacheManager, args.cwd, args.filePath, void 0, void 0, owner);
9065
+ syncGitGuardRecord(args.runtime, args.cacheManager, args.cwd, args.filePath, args.analysisRootMode, void 0, args.owner, args.inCheckout);
8898
9066
  }
8899
- return true;
8900
9067
  }
8901
9068
  function resyncGitGuardAfterInlinePolicy(args) {
8902
9069
  const changed = args.runtime.applyInlineBlockerPolicyVerdicts(args.suppressedFilePaths, { sessionId: args.sessionId });
@@ -8904,10 +9071,10 @@ function resyncGitGuardAfterInlinePolicy(args) {
8904
9071
  return;
8905
9072
  args.runtime.updateGitGuardStatus(false, "");
8906
9073
  }
8907
- function syncGitGuardRecord(runtime, cacheManager2, cwd, editedFilePath, analysisRootMode = "session", editedCleanVerdict = false, sessionId) {
9074
+ function syncGitGuardRecord(runtime, cacheManager2, cwd, editedFilePath, analysisRootMode = "session", editedCleanVerdict = false, sessionId, inCheckout) {
8908
9075
  if (!canWriteAnalysisRoot(analysisRootMode))
8909
9076
  return;
8910
- const entries = (runtime.getInlineBlockersSnapshot?.({ sessionId }) ?? []).filter((entry) => !entry.policySuppressed);
9077
+ const entries = (runtime.getInlineBlockersSnapshot?.({ sessionId }) ?? []).filter((entry) => !entry.policySuppressed && (!inCheckout || inCheckout(entry.filePath)));
8911
9078
  const stored = storedRecord(cacheManager2, cwd)?.fields;
8912
9079
  if (entries.length === 0 && claimsNoBlocker(stored)) {
8913
9080
  cacheManager2.clearCache("turn-end-findings", cwd);
@@ -9231,7 +9398,15 @@ function render(kept, ctx) {
9231
9398
  report += ` \u2026 and ${kept.findings.length - findings.length} more
9232
9399
  `;
9233
9400
  }
9234
- advisorySections.push(report);
9401
+ advisorySections.push({
9402
+ part: report,
9403
+ cites: [
9404
+ ...new Set(kept.findings.flatMap((f) => {
9405
+ const callSite = f.trace.find((t) => t.filename)?.filename;
9406
+ return callSite === void 0 ? [] : [callSite];
9407
+ }))
9408
+ ]
9409
+ });
9235
9410
  }
9236
9411
  return {
9237
9412
  advisoryParts: advisorySections,
@@ -9393,16 +9568,18 @@ function render2(kept, ctx) {
9393
9568
  report += ` \u2026 and ${enriched.length - shown2.length} more
9394
9569
  `;
9395
9570
  }
9396
- blockerSections.push(report);
9571
+ blockerSections.push({ part: report, cites: enriched.map((f) => f.file) });
9397
9572
  }
9398
9573
  const staleSecretEntries = [
9399
9574
  ...kept.gitleaksStale.map((f) => ({
9400
9575
  file: toRunnerDisplayPath(ctx.cwd, f.file),
9576
+ filePath: f.file,
9401
9577
  rule: f.ruleId,
9402
9578
  source: "gitleaks"
9403
9579
  })),
9404
9580
  ...kept.trivyStale.map((f) => ({
9405
9581
  file: toRunnerDisplayPath(ctx.cwd, f.file),
9582
+ filePath: f.file,
9406
9583
  rule: f.ruleId,
9407
9584
  source: "trivy"
9408
9585
  }))
@@ -9424,7 +9601,10 @@ The cached line numbers are no longer trustworthy, so they are withheld. Re-run
9424
9601
  report += ` \u2026 and ${staleSecrets.length - shown2.length} more
9425
9602
  `;
9426
9603
  }
9427
- staleSections.push(report);
9604
+ staleSections.push({
9605
+ part: report,
9606
+ cites: [...new Set(staleSecrets.map((entry) => entry.filePath))]
9607
+ });
9428
9608
  }
9429
9609
  return {
9430
9610
  blockerParts: blockerSections,
@@ -9845,7 +10025,7 @@ async function runPersistentReverify(args) {
9845
10025
  } catch {
9846
10026
  touchedResult = void 0;
9847
10027
  }
9848
- if (touchedResult === void 0 || touchedResult.inconclusive === true || touchedResult.skipReason !== void 0 || (touchedResult.diagnosticsUnsupportedServerIds ?? []).length > 0 || !touchCompletedConfirmationPolicy(touchedResult)) {
10028
+ if (touchedResult === void 0 || touchedResult.inconclusive === true || touchedResult.binding?.boundToCurrentDisk === false || touchedResult.skipReason !== void 0 || (touchedResult.diagnosticsUnsupportedServerIds ?? []).length > 0 || !touchCompletedConfirmationPolicy(touchedResult)) {
9849
10029
  outcomes.push({
9850
10030
  filePath: entry.filePath,
9851
10031
  displayPath: entry.displayPath,
@@ -9931,12 +10111,12 @@ function readCurrentContent(filePath) {
9931
10111
  }
9932
10112
  }
9933
10113
  function applyInlineBlockerPolicy(record, cwd) {
9934
- const diagnostics = record.diagnostics;
10114
+ const { diagnostics, filePath } = record;
9935
10115
  if (!diagnostics || diagnostics.length === 0) {
9936
10116
  if (hasAnyDispositionMarks(cwd)) {
9937
10117
  recordDegradationOnce({
9938
10118
  kind: "inline-blocker-unstructured",
9939
- subject: `inline-blocker:${toRunnerDisplayPath(cwd, record.filePath)}`,
10119
+ subject: `inline-blocker:${toRunnerDisplayPath(cwd, filePath)}`,
9940
10120
  reason: "record carries no structured diagnostics; disposition marks cannot be applied to its rendered summary"
9941
10121
  });
9942
10122
  }
@@ -9948,37 +10128,30 @@ function applyInlineBlockerPolicy(record, cwd) {
9948
10128
  unstructured: true
9949
10129
  };
9950
10130
  }
9951
- const byFile = /* @__PURE__ */ new Map();
9952
- for (const diagnostic of diagnostics) {
9953
- const owner = path23.resolve(cwd, diagnostic.filePath);
9954
- const group = byFile.get(owner);
9955
- if (group)
9956
- group.push(diagnostic);
9957
- else
9958
- byFile.set(owner, [diagnostic]);
9959
- }
9960
- const policyMap = loadProjectRulePolicyMap(cwd);
9961
- const dropped = /* @__PURE__ */ new Set();
9962
- for (const [filePath, group] of byFile) {
9963
- const { kept: kept2 } = applyFindingPolicy(group, {
9964
- cwd,
9965
- filePath,
9966
- content: readCurrentContent(filePath),
9967
- policyMap,
9968
- identities: inlineBlockerIdentities
9969
- });
9970
- const survivors = new Set(kept2);
9971
- for (const diagnostic of group) {
9972
- if (!survivors.has(diagnostic))
9973
- dropped.add(diagnostic);
9974
- }
9975
- }
9976
- const kept = dropped.size === 0 ? [...diagnostics] : diagnostics.filter((diagnostic) => !dropped.has(diagnostic));
10131
+ const inProject = (file) => path23.resolve(cwd, file);
10132
+ const resolved = diagnostics.map((diagnostic) => ({
10133
+ ...diagnostic,
10134
+ filePath: inProject(diagnostic.filePath)
10135
+ }));
10136
+ const recordPath = inProject(filePath);
10137
+ const survivors = new Set(applyFindingPolicyByOwner(resolved, {
10138
+ cwd,
10139
+ filePath: recordPath,
10140
+ content: readCurrentContent(recordPath),
10141
+ // One policy for every file: each config owner resolves once.
10142
+ policyMap: loadProjectRulePolicy(cwd),
10143
+ identities: inlineBlockerIdentities
10144
+ }).kept);
10145
+ const kept = diagnostics.filter((_, index) => {
10146
+ const twin = resolved[index];
10147
+ return twin !== void 0 && survivors.has(twin);
10148
+ });
10149
+ const dropped = diagnostics.length - kept.length;
9977
10150
  return {
9978
10151
  body: kept.length === 0 ? void 0 : formatDiagnostics(kept, "blocking").trim(),
9979
10152
  candidates: diagnostics.length,
9980
10153
  kept: kept.length,
9981
- suppressed: dropped.size,
10154
+ suppressed: dropped,
9982
10155
  unstructured: false
9983
10156
  };
9984
10157
  }
@@ -10402,12 +10575,12 @@ function resyncCommitGateForReadOnlyTurn(args) {
10402
10575
  displayPath: toRunnerDisplayPath(args.cwd, entry.filePath),
10403
10576
  sources: entry.sources
10404
10577
  };
10405
- if (entry.stale) {
10406
- inlinePolicyEntries.push({ ...tally, stale: true });
10407
- continue;
10408
- }
10409
10578
  const policy = applyInlineBlockerPolicy(entry, args.cwd);
10410
- inlinePolicyEntries.push({ ...tally, stale: false, outcome: policy });
10579
+ inlinePolicyEntries.push({
10580
+ ...tally,
10581
+ stale: entry.stale === true,
10582
+ outcome: policy
10583
+ });
10411
10584
  if (policy.body === void 0)
10412
10585
  policySuppressedPaths.push(entry.filePath);
10413
10586
  }
@@ -10432,6 +10605,17 @@ function resyncCommitGateForReadOnlyTurn(args) {
10432
10605
  }
10433
10606
  });
10434
10607
  }
10608
+ function driftDeliveryCap(staleReason) {
10609
+ if (staleReason !== "dependency-drift" && staleReason !== "self-drift")
10610
+ return void 0;
10611
+ return {
10612
+ axis: staleReason,
10613
+ cap: staleReason === "self-drift" ? SELF_DRIFT_MAX_DELIVERIES : DEPENDENCY_DRIFT_MAX_DELIVERIES
10614
+ };
10615
+ }
10616
+ function suppressedByDispositionNote(suppressed) {
10617
+ return suppressed > 0 ? ` (suppressed by disposition: ${suppressed} finding(s))` : "";
10618
+ }
10435
10619
  async function handleTurnEnd(deps) {
10436
10620
  const { ctxCwd, getFlag, dbg, runtime, cacheManager: cacheManager2, knipClient, deadCodeClients, depChecker, testRunnerClient, sessionId, host = "pi", owner, resetLSPService: resetLSPService2, resetFormatService: resetFormatService2 } = deps;
10437
10621
  const turnIndexAtDispatch = runtime.turnIndex;
@@ -10538,6 +10722,21 @@ async function handleTurnEnd(deps) {
10538
10722
  const citePart = (part, files2) => {
10539
10723
  provenanceCitations.set(part, [...files2]);
10540
10724
  };
10725
+ const filelessParts = /* @__PURE__ */ new Map();
10726
+ const markFilelessPart = (part) => {
10727
+ if (filelessParts.get(part) === "carried")
10728
+ return;
10729
+ filelessParts.set(part, "this-turn");
10730
+ };
10731
+ const markCarriedPart = (part) => {
10732
+ filelessParts.set(part, "carried");
10733
+ };
10734
+ const registerLanePart = (entry) => {
10735
+ if ("filelessThisTurn" in entry)
10736
+ markFilelessPart(entry.part);
10737
+ else
10738
+ citePart(entry.part, entry.cites);
10739
+ };
10541
10740
  const deliveryHolds = [];
10542
10741
  const turnScope = deps.sessionScope ?? runtime.sessionScope;
10543
10742
  const holdScope = runtime.captureSessionGeneration();
@@ -10572,7 +10771,15 @@ async function handleTurnEnd(deps) {
10572
10771
  const runnerFindingsStart = Date.now();
10573
10772
  const runnerDrainSignal = deps.signal;
10574
10773
  const deliverySessionId = sessionId ?? runtime.telemetrySessionId;
10575
- const pendingRunnerFindings = await bounded(drainPendingRunnerFindings(0, runtime.sessionScope.capture(), deliverySessionId), {
10774
+ const deliveryTurnKey = runtime.turnKey(deliverySessionId);
10775
+ const pendingRunnerFindings = await bounded(drainPendingRunnerFindings(
10776
+ 0,
10777
+ runtime.sessionScope.capture(),
10778
+ deliverySessionId,
10779
+ // #4617 review F2: the boundary that leaves a run waiting, so the note
10780
+ // a later turn renders reads carried, not this-turn.
10781
+ deliveryTurnKey
10782
+ ), {
10576
10783
  ms: HOOK_WALL_BUDGET_MS.turn_end,
10577
10784
  signal: runnerDrainSignal,
10578
10785
  hook: "turn_end",
@@ -10599,9 +10806,15 @@ async function handleTurnEnd(deps) {
10599
10806
  part: failedNote,
10600
10807
  onHeld: () => requeueRunnerFindings({
10601
10808
  ...pending2,
10602
- result: { ...result, diagnostics: [] }
10809
+ result: { ...result, diagnostics: [] },
10810
+ carriedFromTurnKey: deliveryTurnKey
10603
10811
  })
10604
10812
  });
10813
+ const carriedFailure = pending2.carriedFromTurnKey !== void 0 && pending2.carriedFromTurnKey < deliveryTurnKey;
10814
+ if (carriedFailure)
10815
+ markCarriedPart(failedNote);
10816
+ else
10817
+ markFilelessPart(failedNote);
10605
10818
  advisoryParts.push(failedNote);
10606
10819
  }
10607
10820
  const verdict = judgeDeferredRunnerFindings(pending2, cwd);
@@ -10664,6 +10877,9 @@ ${lines.join("\n")}`;
10664
10877
  deliveredIds: runnerFindingsDeliveredIds
10665
10878
  }
10666
10879
  });
10880
+ if (runtime.retireForeignRowsOfMissingFiles({ sessionId }).length > 0) {
10881
+ runtime.updateGitGuardStatus(false, "");
10882
+ }
10667
10883
  const blockerPastEofStart = Date.now();
10668
10884
  const blockerPastEof = sweepInlineBlockerPastEof(runtime, cwd, {
10669
10885
  sessionId
@@ -10695,18 +10911,18 @@ ${lines.join("\n")}`;
10695
10911
  reason: `file shrank past cited line(s) ${deadLines.join(", ")}; retired after one degraded delivery`
10696
10912
  });
10697
10913
  };
10698
- const countDriftDeliveryOnDelivery = (bPath, displayPath) => () => {
10914
+ const countDriftDeliveryOnDelivery = (bPath, displayPath, reason, cap) => () => {
10699
10915
  const deliveryCount = runtime.incrementInlineBlockerStaleDelivery(bPath);
10700
- if (deliveryCount < DEPENDENCY_DRIFT_MAX_DELIVERIES)
10916
+ if (deliveryCount < cap)
10701
10917
  return;
10702
- if (!runtime.retireDemotedDependencyDriftBlocker(bPath))
10918
+ if (!runtime.retireDemotedDriftBlocker(bPath, reason))
10703
10919
  return;
10704
10920
  runtime.updateGitGuardStatus(false, "");
10705
10921
  demotedFindingsRetired += 1;
10706
10922
  incrementDegradationCount({
10707
10923
  kind: "demoted-finding-retired",
10708
10924
  subject: `inline-blocker:${displayPath}`,
10709
- reason: `capped after ${deliveryCount} deliveries with no re-run; re-run can still confirm`
10925
+ reason: `capped after ${deliveryCount} deliveries of a ${reason} advisory with no re-run; re-run can still confirm`
10710
10926
  });
10711
10927
  };
10712
10928
  const blockerFreshnessStart = Date.now();
@@ -10743,36 +10959,43 @@ ${lines.join("\n")}`;
10743
10959
  const policySuppressedPaths = [];
10744
10960
  const inlinePolicyStart = Date.now();
10745
10961
  for (const record of unresolvedBlockers) {
10746
- const { filePath: bPath, summary, stale, staleReason } = record;
10962
+ const { filePath: bPath, stale, staleReason } = record;
10747
10963
  const displayPath = toRunnerDisplayPath(cwd, bPath);
10748
10964
  const tally = { displayPath, sources: record.sources };
10749
10965
  if (stale) {
10750
- inlinePolicyEntries.push({ ...tally, stale: true });
10966
+ const policy = applyInlineBlockerPolicy(record, cwd);
10967
+ inlinePolicyEntries.push({ ...tally, stale: true, outcome: policy });
10968
+ if (policy.body === void 0) {
10969
+ policySuppressedPaths.push(bPath);
10970
+ continue;
10971
+ }
10751
10972
  const deadLines = blockerPastEof.deadLinesByPath.get(bPath) ?? [];
10752
- const degraded = degradeDemotedFindingBody(summary, { deadLines });
10973
+ const degraded = degradeDemotedFindingBody(policy.body, { deadLines });
10753
10974
  const retires = runtime.wouldRetireDemotedPastEofBlocker(bPath, deadLines);
10975
+ const drift = driftDeliveryCap(staleReason);
10754
10976
  let retirementNote;
10755
10977
  if (retires) {
10756
10978
  retirementNote = formatRetirementNote(deadLines);
10757
- } else if (staleReason === "dependency-drift") {
10979
+ } else if (drift !== void 0) {
10758
10980
  const tentativeCount = runtime.peekInlineBlockerStaleDeliveryCount(bPath) + 1;
10759
- if (tentativeCount >= DEPENDENCY_DRIFT_MAX_DELIVERIES) {
10981
+ if (tentativeCount >= drift.cap) {
10760
10982
  retirementNote = formatDeliveryCapNote(tentativeCount);
10761
10983
  }
10762
10984
  }
10763
- const advisoryPart = `${STALE_LINE_MARKER} ${displayPath}:
10985
+ const advisoryPart = `${STALE_LINE_MARKER} ${displayPath}${suppressedByDispositionNote(policy.suppressed)}:
10764
10986
  ${degraded.body}` + (retirementNote ? `
10765
10987
  ${retirementNote}` : "");
10766
10988
  advisoryParts.push(advisoryPart);
10989
+ citePart(advisoryPart, [bPath]);
10767
10990
  if (retires) {
10768
10991
  deliveryHolds.push({
10769
10992
  part: advisoryPart,
10770
10993
  onDelivered: retirePastEofOnDelivery(bPath, deadLines, displayPath)
10771
10994
  });
10772
- } else if (staleReason === "dependency-drift") {
10995
+ } else if (drift !== void 0) {
10773
10996
  deliveryHolds.push({
10774
10997
  part: advisoryPart,
10775
- onDelivered: countDriftDeliveryOnDelivery(bPath, displayPath),
10998
+ onDelivered: countDriftDeliveryOnDelivery(bPath, displayPath, drift.axis, drift.cap),
10776
10999
  skipOnSuppressed: true
10777
11000
  });
10778
11001
  }
@@ -10783,8 +11006,7 @@ ${retirementNote}` : "");
10783
11006
  policySuppressedPaths.push(bPath);
10784
11007
  continue;
10785
11008
  }
10786
- const suppressedNote = policy.suppressed > 0 ? ` (suppressed by disposition: ${policy.suppressed} finding(s))` : "";
10787
- const replayPart = `Unresolved from this turn \u2014 ${displayPath}${suppressedNote}:
11009
+ const replayPart = `Unresolved from this turn \u2014 ${displayPath}${suppressedByDispositionNote(policy.suppressed)}:
10788
11010
  ${policy.body}`;
10789
11011
  blockerParts.push(replayPart);
10790
11012
  citePart(replayPart, [bPath]);
@@ -10910,6 +11132,11 @@ ${policy.body}`;
10910
11132
  lastObserver.set(nk, { run, filePath: neighborPath });
10911
11133
  }
10912
11134
  }
11135
+ const primaryUnanswered = /* @__PURE__ */ new Set();
11136
+ for (const [nk, { run }] of lastObserver) {
11137
+ if (run.result?.neighbors.some((n) => normalizeMapKey(n.filePath) === nk && n.primaryUnavailable !== void 0))
11138
+ primaryUnanswered.add(nk);
11139
+ }
10913
11140
  for (const [nk, { run, filePath }] of lastObserver) {
10914
11141
  const observedClean = run.observedNeighborPaths?.some((p) => normalizeMapKey(p) === nk) && !run.result?.neighbors.some((n) => normalizeMapKey(n.filePath) === nk && n.diagnostics.length > 0);
10915
11142
  if (observedClean)
@@ -10964,6 +11191,8 @@ ${carrySuffix}` : rendered.text);
10964
11191
  continue;
10965
11192
  if (editedKeys.has(normalizeMapKey(n.filePath)))
10966
11193
  continue;
11194
+ if (primaryUnanswered.has(normalizeMapKey(n.filePath)))
11195
+ continue;
10967
11196
  sectionObservations.push({
10968
11197
  filePath: n.filePath,
10969
11198
  diagnostics: n.diagnostics,
@@ -11003,6 +11232,7 @@ ${testLines.join("\n")}`;
11003
11232
  ... and ${testSuggestions.length - 5} more`;
11004
11233
  }
11005
11234
  parts.push(testSection);
11235
+ sectionPrimaries.push(...testSuggestions.map((s) => s.testFile));
11006
11236
  }
11007
11237
  }
11008
11238
  if (unansweredLines.length > 0)
@@ -11050,7 +11280,9 @@ ${testLines.join("\n")}`;
11050
11280
  }
11051
11281
  const pendingCandidates = listCascadePendingNeighbors().filter((entry) => {
11052
11282
  const key = normalizeMapKey(entry.filePath);
11053
- if (lastObserver.has(key) || editedKeys.has(key))
11283
+ if (editedKeys.has(key))
11284
+ return false;
11285
+ if (lastObserver.has(key) && !primaryUnanswered.has(key))
11054
11286
  return false;
11055
11287
  return isUnderDir(entry.filePath, cwd);
11056
11288
  });
@@ -11200,7 +11432,8 @@ ${suffix}`;
11200
11432
  return `${frame.lead(fileCount2, reasons)}
11201
11433
  ${lines.join("\n")}`;
11202
11434
  };
11203
- const graphRuns = indeterminateRuns.filter((r) => r.indeterminate?.reason !== "lsp_binding_rejected" && r.indeterminate?.reason !== "excluded_by_role" && r.indeterminate?.reason !== "budget_truncated" && r.indeterminate?.budget === void 0);
11435
+ const graphRuns = indeterminateRuns.filter((r) => r.indeterminate?.reason !== "lsp_binding_rejected" && r.indeterminate?.reason !== "excluded_by_role" && r.indeterminate?.reason !== "budget_truncated" && r.indeterminate?.reason !== "unresolved_reference" && r.indeterminate?.budget === void 0);
11436
+ const referenceRuns = indeterminateRuns.filter((r) => r.indeterminate?.reason === "unresolved_reference" && r.indeterminate?.budget === void 0);
11204
11437
  const bindingRuns = indeterminateRuns.filter((r) => r.indeterminate?.reason === "lsp_binding_rejected" && r.indeterminate?.budget === void 0);
11205
11438
  const budgetRuns = indeterminateRuns.filter((r) => r.indeterminate?.reason === "budget_truncated" || r.indeterminate?.budget !== void 0);
11206
11439
  const graphNamed = [];
@@ -11213,6 +11446,18 @@ ${lines.join("\n")}`;
11213
11446
  if (graphAdvisory)
11214
11447
  citePart(graphAdvisory, graphNamed);
11215
11448
  holdAdvisory(graphAdvisory, graphRuns, "indeterminate");
11449
+ const referenceNamed = [];
11450
+ const referenceAdvisory = withCarryLabel(buildAdvisory(referenceRuns, {
11451
+ // The bullet below carries the cause and the files, so the lead
11452
+ // does not say it again.
11453
+ lead: (fileCount2) => `Cascade could not place every dependent of ${fileCount2} edited file(s) this turn, so a clean cascade result does not cover them.`,
11454
+ fallbackDetail: () => "some files reference a changed symbol by an ambiguous name"
11455
+ }, referenceNamed), referenceRuns);
11456
+ if (referenceAdvisory)
11457
+ advisoryParts.push(referenceAdvisory);
11458
+ if (referenceAdvisory)
11459
+ citePart(referenceAdvisory, referenceNamed);
11460
+ holdAdvisory(referenceAdvisory, referenceRuns, "indeterminate");
11216
11461
  const bindingNamed = [];
11217
11462
  const bindingAdvisory = withCarryLabel(buildAdvisory(bindingRuns, {
11218
11463
  lead: (fileCount2, reasons) => `Cascade identified dependents for ${fileCount2} edited file(s) this turn, but their diagnostics could not be freshly confirmed (${reasons}) and were withheld \u2014 a clean cascade result does not cover them.`,
@@ -11247,6 +11492,9 @@ ${lines.join("\n")}`;
11247
11492
  ...r.indeterminate?.budget && { budget: r.indeterminate.budget },
11248
11493
  ...r.indeterminate?.diagnostic && {
11249
11494
  diagnostic: r.indeterminate.diagnostic
11495
+ },
11496
+ ...r.indeterminate?.unplacedReferrerCount !== void 0 && {
11497
+ unplacedReferrerCount: r.indeterminate.unplacedReferrerCount
11250
11498
  }
11251
11499
  }));
11252
11500
  logCascade({
@@ -11275,7 +11523,11 @@ ${lines.join("\n")}`;
11275
11523
  const observer = lastObserver.get(nk)?.run;
11276
11524
  if (observer && (runOrder.get(observer) ?? -1) > (runOrder.get(run) ?? -1))
11277
11525
  continue;
11278
- const bucket = byServer.get(group.serverId) ?? {
11526
+ const reason = group.reason ?? "no-answer";
11527
+ const bucketKey = `${reason}:${group.serverId}`;
11528
+ const bucket = byServer.get(bucketKey) ?? {
11529
+ serverId: group.serverId,
11530
+ reason,
11279
11531
  waitMs: group.waitMs,
11280
11532
  primaries: /* @__PURE__ */ new Set(),
11281
11533
  paths: /* @__PURE__ */ new Map(),
@@ -11288,7 +11540,7 @@ ${lines.join("\n")}`;
11288
11540
  bucket.paths.set(nk, neighborDisplay);
11289
11541
  bucket.raw.set(primaryDisplay, run.filePath);
11290
11542
  bucket.raw.set(neighborDisplay, neighborPath);
11291
- byServer.set(group.serverId, bucket);
11543
+ byServer.set(bucketKey, bucket);
11292
11544
  }
11293
11545
  }
11294
11546
  }
@@ -11296,7 +11548,8 @@ ${lines.join("\n")}`;
11296
11548
  const blocks = [];
11297
11549
  const unconfirmedNamed = [];
11298
11550
  let pathCount = 0;
11299
- for (const [serverId, bucket] of byServer) {
11551
+ for (const bucket of byServer.values()) {
11552
+ const serverId = bucket.serverId;
11300
11553
  const paths = [...bucket.paths.values()];
11301
11554
  for (const display of [
11302
11555
  ...[...bucket.primaries].slice(0, 3),
@@ -11306,7 +11559,9 @@ ${lines.join("\n")}`;
11306
11559
  }
11307
11560
  pathCount += paths.length;
11308
11561
  const within = bucket.waitMs > 0 ? ` within ${bucket.waitMs} ms` : "";
11309
- blocks.push(`Cascade sent ${paths.length} dependent(s) of ${capped([...bucket.primaries], 3)} to ${serverId}, but no answer arrived${within}; a clean cascade result does not cover them.
11562
+ const dependents = capped([...bucket.primaries], 3);
11563
+ const cause = bucket.reason === "pre-edit-answer" ? `Cascade asked ${serverId} about ${paths.length} dependent(s) of ${dependents}, but its cached answer predates this edit; a clean cascade result does not cover them.` : `Cascade sent ${paths.length} dependent(s) of ${dependents} to ${serverId}, but no answer arrived${within}; a clean cascade result does not cover them.`;
11564
+ blocks.push(`${cause}
11310
11565
  \u2022 ${serverId}: ${capped(paths, 5)}`);
11311
11566
  }
11312
11567
  if (blocks.length > 0) {
@@ -11320,7 +11575,10 @@ ${lines.join("\n")}`;
11320
11575
  phase: "cascade_unconfirmed_rendered",
11321
11576
  filePath: cascadeLogFilePath,
11322
11577
  metadata: {
11323
- servers: byServer.size,
11578
+ // `servers` stays the distinct server count it was before the
11579
+ // buckets were keyed by cause; `groups` counts the cause buckets.
11580
+ servers: new Set([...byServer.values()].map((b) => b.serverId)).size,
11581
+ groups: byServer.size,
11324
11582
  paths: pathCount,
11325
11583
  runs: unconfirmedRuns.length
11326
11584
  }
@@ -11450,6 +11708,7 @@ ${lines.join("\n")}`;
11450
11708
  `;
11451
11709
  }
11452
11710
  blockerParts.push(report);
11711
+ citePart(report, blockerIssues.flatMap((issue) => issue.file ? [resolveRunnerPath(scanRoot, issue.file)] : []));
11453
11712
  deliveryHolds.push(cutAdvisoryHold("knip", knipBlockerLane, report, blockerIssues.slice(0, KNIP_MAX_SHOWN), (issue) => reOfferedKeys.has(issueKey(issue))));
11454
11713
  }
11455
11714
  const unusedExportDelta = knipDeliverable.kept.filter((i) => i.type === "export" || i.type === "enumMember");
@@ -11461,6 +11720,7 @@ ${lines.join("\n")}`;
11461
11720
  `;
11462
11721
  }
11463
11722
  advisoryParts.push(report);
11723
+ citePart(report, unusedExportDelta.flatMap((issue) => issue.file ? [resolveRunnerPath(scanRoot, issue.file)] : []));
11464
11724
  deliveryHolds.push(cutAdvisoryHold("knip", knipAdvisoryLane, report, unusedExportDelta.slice(0, KNIP_MAX_SHOWN), (issue) => reOfferedKeys.has(issueKey(issue))));
11465
11725
  }
11466
11726
  }
@@ -11602,6 +11862,7 @@ ${lines.join("\n")}`;
11602
11862
  }
11603
11863
  const deadCodePart = formatDeadCodeDelta(deadCodeDeliverable.kept, result.language);
11604
11864
  advisoryParts.push(deadCodePart);
11865
+ citePart(deadCodePart, deadCodeDeliverable.kept.flatMap((issue) => issue.file ? [resolveRunnerPath(cwd, issue.file)] : []));
11605
11866
  const reOfferedKeys = new Set(reOffered.map(deadCodeIssueKey));
11606
11867
  deliveryHolds.push(cutAdvisoryHold("dead-code", deadCodeLane, deadCodePart, deadCodeDeliverable.kept.slice(0, DEAD_CODE_DELTA_MAX_SHOWN), (issue) => reOfferedKeys.has(deadCodeIssueKey(issue))));
11607
11868
  };
@@ -11802,7 +12063,10 @@ ${lines.join("\n")}`;
11802
12063
  for (const [store, count] of Object.entries(govDelivery.dispositionSuppressed ?? {})) {
11803
12064
  recordDispositionSuppressed(store, count);
11804
12065
  }
11805
- advisoryParts.push(...govDelivery.advisoryParts ?? []);
12066
+ for (const lanePart of govDelivery.advisoryParts ?? []) {
12067
+ registerLanePart(lanePart);
12068
+ advisoryParts.push(lanePart.part);
12069
+ }
11806
12070
  const secretsDelivery = allowProjectWideFindings ? secretsLane.render(secretsLane.gate({
11807
12071
  gitleaks: gitleaksGate,
11808
12072
  "trivy-secrets": trivySecretsGate
@@ -11811,8 +12075,14 @@ ${lines.join("\n")}`;
11811
12075
  recordDispositionSuppressed(store, count);
11812
12076
  }
11813
12077
  const secretBlockedLocations = secretsDelivery.deliveredLocationKeys ?? /* @__PURE__ */ new Set();
11814
- blockerParts.push(...secretsDelivery.blockerParts ?? []);
11815
- staleSecretParts.push(...secretsDelivery.staleSecretParts ?? []);
12078
+ for (const lanePart of secretsDelivery.blockerParts ?? []) {
12079
+ registerLanePart(lanePart);
12080
+ blockerParts.push(lanePart.part);
12081
+ }
12082
+ for (const lanePart of secretsDelivery.staleSecretParts ?? []) {
12083
+ registerLanePart(lanePart);
12084
+ staleSecretParts.push(lanePart.part);
12085
+ }
11816
12086
  const trivyAgeLabel = formatCacheAgeLabel(trivyCacheEntry?.data?.scannedAt);
11817
12087
  const trivyFindingsFiltered = filterFindingsByDisposition(trivyCacheEntry?.data?.findings ?? [], cwd, (f) => trivyFindingToProjectDiagnostic(cwd, f));
11818
12088
  recordDispositionSuppressed("trivy", trivyFindingsFiltered.suppressed);
@@ -11837,6 +12107,7 @@ ${lines.join("\n")}`;
11837
12107
  `;
11838
12108
  }
11839
12109
  blockerParts.push(report);
12110
+ citePart(report, trivyEvidenceFiles(cwd, shown2.map((f) => f.target)));
11840
12111
  }
11841
12112
  if (advisory.length) {
11842
12113
  const shown2 = advisory.slice(0, 5);
@@ -11849,6 +12120,7 @@ ${lines.join("\n")}`;
11849
12120
  `;
11850
12121
  }
11851
12122
  advisoryParts.push(report);
12123
+ citePart(report, trivyEvidenceFiles(cwd, shown2.map((f) => f.target)));
11852
12124
  }
11853
12125
  }
11854
12126
  const licenses = trivyCacheEntry?.data?.licenses ?? [];
@@ -11866,10 +12138,13 @@ ${lines.join("\n")}`;
11866
12138
  `;
11867
12139
  }
11868
12140
  advisoryParts.push(report);
12141
+ citePart(report, trivyEvidenceFiles(cwd, shown2.map((l) => l.filePath)));
11869
12142
  }
11870
12143
  if (dispositionSuppressedTotal > 0) {
11871
12144
  const byLane = Object.entries(dispositionSuppressedByLane).map(([lane, count]) => `${lane} ${count}`).join(", ");
11872
- advisoryParts.push(`suppressed by disposition: ${dispositionSuppressedTotal} finding(s) dropped from this turn's gitleaks/govulncheck/trivy sections (${byLane}) (marked false-positive or won't-fix).`);
12145
+ const suppressedNotice = `suppressed by disposition: ${dispositionSuppressedTotal} finding(s) dropped from this turn's gitleaks/govulncheck/trivy sections (${byLane}) (marked false-positive or won't-fix).`;
12146
+ advisoryParts.push(suppressedNotice);
12147
+ markFilelessPart(suppressedNotice);
11873
12148
  }
11874
12149
  const t3 = Date.now();
11875
12150
  let madgeStats;
@@ -12469,12 +12744,14 @@ ${lines.join("\n")}`;
12469
12744
  if (runtime.callGraph && files.length > 0) {
12470
12745
  const coverage = runtime.callGraph.coverage;
12471
12746
  if (!coverage || coverage.complete !== true) {
12472
- advisoryParts.push("Call-graph impact was not emitted because call-graph extraction coverage is incomplete; the affected files may have unreported callers.");
12747
+ const incompleteGraphNotice = "Call-graph impact was not emitted because call-graph extraction coverage is incomplete; the affected files may have unreported callers.";
12748
+ advisoryParts.push(incompleteGraphNotice);
12749
+ markFilelessPart(incompleteGraphNotice);
12473
12750
  } else {
12474
12751
  const callGraphStart = Date.now();
12475
12752
  try {
12476
- const { impact, formatImpact, parseSymbolKey } = await import("../chunk-2TF6RXWB.js");
12477
- const { callGraphImpactToProjectDiagnostics } = await import("../chunk-LUBPZN36.js");
12753
+ const { impact, formatImpact, parseSymbolKey } = await import("../chunk-TV6RXRYH.js");
12754
+ const { callGraphImpactToProjectDiagnostics } = await import("../chunk-R4QWJQ2H.js");
12478
12755
  const impactLines = [];
12479
12756
  let callGraphDispositionSuppressed = 0;
12480
12757
  const impactFindings = [];
@@ -12516,6 +12793,7 @@ ${lines.join("\n")}`;
12516
12793
  const impactPart = `\u{1F4CA} Call-graph impact (changed symbols have callers):
12517
12794
  ${impactLines.join("\n")}`;
12518
12795
  advisoryParts.push(impactPart);
12796
+ citePart(impactPart, shownImpactFiles);
12519
12797
  deliveryHolds.push(cutAdvisoryHold("call-graph", carryLane("call-graph"), impactPart, shownImpactFiles, (file) => !impactFiles.includes(file)));
12520
12798
  }
12521
12799
  if (impactFindings.length > 0) {
@@ -12650,6 +12928,7 @@ ${impactLines.join("\n")}`;
12650
12928
  getFileSeq: getFileSeq ? (filePath) => getFileSeq.call(runtime, filePath) : void 0,
12651
12929
  dbg
12652
12930
  });
12931
+ let actionableNamedFiles = [];
12653
12932
  const advisory = formatActionableWarningsAdvisory(publishResult.report, cwd, host, (report2) => {
12654
12933
  let dispositionSuppressed = 0;
12655
12934
  const files2 = report2.files.map((file) => {
@@ -12674,10 +12953,13 @@ ${impactLines.join("\n")}`;
12674
12953
  return kept.length > 0 ? { ...file, warnings: kept } : void 0;
12675
12954
  }).filter((file) => file !== void 0);
12676
12955
  recordDispositionSuppressed("actionable-warnings", dispositionSuppressed);
12956
+ actionableNamedFiles = files2.map((file) => file.filePath);
12677
12957
  return { files: files2, suppressed: dispositionSuppressed };
12678
12958
  });
12679
12959
  if (advisory)
12680
12960
  advisoryParts.push(advisory);
12961
+ if (advisory)
12962
+ citePart(advisory, actionableNamedFiles);
12681
12963
  logActionableWarningsEvent({
12682
12964
  event: advisory ? "advisory_injected" : "advisory_skipped",
12683
12965
  sessionId: runtime.telemetrySessionId,
@@ -12733,6 +13015,8 @@ ${impactLines.join("\n")}`;
12733
13015
  const advisory = formatCodeQualityWarningsAdvisory(qualityReport, cwd, host);
12734
13016
  if (advisory)
12735
13017
  advisoryParts.push(advisory);
13018
+ if (advisory)
13019
+ citePart(advisory, qualityWarnings.map((warning) => warning.filePath));
12736
13020
  logLatency({
12737
13021
  type: "phase",
12738
13022
  toolName: "turn_end",
@@ -13114,15 +13398,17 @@ ${raw}`
13114
13398
  const findingParts = composedParts.map((part) => part.text);
13115
13399
  let heldSections = 0;
13116
13400
  const logTurnEndRow = (deliverySuppressed) => {
13401
+ let turnResult = "clean";
13402
+ if (blockerParts.length > 0)
13403
+ turnResult = "blockers_found";
13404
+ else if (staleSecretParts.length > 0)
13405
+ turnResult = "stale_secrets_pending";
13117
13406
  logLatency({
13118
13407
  type: "tool_result",
13119
13408
  toolName: "turn_end",
13120
13409
  filePath: cwd,
13121
13410
  durationMs: Date.now() - turnEndStart,
13122
- // #1622 review M2: a pending stale secret is NOT a clean turn. It gets its
13123
- // own result rather than being promoted to `blockers_found`, which would
13124
- // undo the demotion the freshness gate just made.
13125
- result: blockerParts.length > 0 ? "blockers_found" : staleSecretParts.length > 0 ? "stale_secrets_pending" : "clean",
13411
+ result: turnResult,
13126
13412
  metadata: {
13127
13413
  fileCount: files.length,
13128
13414
  blockerSections: blockerParts.length,
@@ -13252,7 +13538,9 @@ ${raw}`
13252
13538
  }
13253
13539
  const { stored: existingGuard, carried, dropped } = readTurnEndGuardRecord(cacheManager2, runtime, cwd, sessionId);
13254
13540
  const deliveredCitedFiles = holdPlan.reachedParts.flatMap((part) => provenanceCitations.get(part.raw) ?? []);
13255
- const uncitedPartReached = holdPlan.reachedParts.some((part) => (provenanceCitations.get(part.raw)?.length ?? 0) === 0);
13541
+ const unaccountedPartReached = holdPlan.reachedParts.some((part) => (provenanceCitations.get(part.raw)?.length ?? 0) === 0 && !filelessParts.has(part.raw));
13542
+ const carriedPartReached = holdPlan.reachedParts.some((part) => filelessParts.get(part.raw) === "carried");
13543
+ const filelessPartReached = holdPlan.reachedParts.some((part) => filelessParts.get(part.raw) !== void 0);
13256
13544
  const stampProvenance = (affectedFiles, affectedTruncated = false) => {
13257
13545
  const byKey = /* @__PURE__ */ new Map();
13258
13546
  const add = (file, role) => {
@@ -13274,7 +13562,8 @@ ${raw}`
13274
13562
  runtime,
13275
13563
  generation: 0,
13276
13564
  files: stamped,
13277
- truncated: affectedTruncated || byKey.size > stamped.length || affectedFiles.length === 0 && uncitedPartReached
13565
+ ...filelessPartReached ? { filelessParts: true } : {},
13566
+ truncated: affectedTruncated || byKey.size > stamped.length || carriedPartReached || affectedFiles.length === 0 && unaccountedPartReached
13278
13567
  });
13279
13568
  };
13280
13569
  if (getFlag("lens-guard") || carried.length > 0) {
@@ -13511,7 +13800,7 @@ var inFlightIpcTurnEnds = /* @__PURE__ */ new Map();
13511
13800
  async function runTurnEndNowImpl(cwd, files = [], deferredDelivery = false) {
13512
13801
  const ctx = await getMcpSessionContext();
13513
13802
  const host = createMcpHost(void 0, cwd);
13514
- let registered = 0;
13803
+ let registered2 = 0;
13515
13804
  for (const file of files) {
13516
13805
  const abs = path25.isAbsolute(file) ? file : path25.resolve(cwd, file);
13517
13806
  let lineCount3 = 1;
@@ -13521,7 +13810,7 @@ async function runTurnEndNowImpl(cwd, files = [], deferredDelivery = false) {
13521
13810
  continue;
13522
13811
  }
13523
13812
  ctx.cacheManager.addModifiedRange(abs, { start: 1, end: lineCount3 }, true, cwd, MCP_TURN_STATE_OWNER_ID, "mcp");
13524
- registered++;
13813
+ registered2++;
13525
13814
  }
13526
13815
  const owner = {
13527
13816
  kind: "mcp",
@@ -13550,11 +13839,11 @@ async function runTurnEndNowImpl(cwd, files = [], deferredDelivery = false) {
13550
13839
  const outcome = deferredDelivery ? {
13551
13840
  turnEnd: joinMessages(peekTurnEndFindings(ctx.cacheManager, cwd, ctx.runtime, true, reader, MCP_DELIVERY_ADDRESS)),
13552
13841
  tests: joinMessages(peekTestFindings(ctx.cacheManager, cwd, ctx.runtime, true)),
13553
- filesRegistered: registered
13842
+ filesRegistered: registered2
13554
13843
  } : {
13555
13844
  turnEnd: joinMessages(consumeTurnEndFindings(ctx.cacheManager, cwd, ctx.runtime, reader, MCP_DELIVERY_ADDRESS)),
13556
13845
  tests: joinMessages(consumeTestFindings(ctx.cacheManager, cwd, ctx.runtime)),
13557
- filesRegistered: registered
13846
+ filesRegistered: registered2
13558
13847
  };
13559
13848
  return {
13560
13849
  outcome,
@@ -14206,7 +14495,7 @@ function blastReadArgs(graph, normalizedFile) {
14206
14495
  return { path: normalizedFile, offset: 1, limit };
14207
14496
  }
14208
14497
  async function computeBlastRadius(graph, normalizedPath, projectRoot, maxDepth) {
14209
- const { computeTransitiveImpact } = await import("../chunk-LSC3VADM.js");
14498
+ const { computeTransitiveImpact } = await import("../chunk-WXUDRAG6.js");
14210
14499
  const result = computeTransitiveImpact(graph, normalizedPath, { maxDepth });
14211
14500
  const byFile = /* @__PURE__ */ new Map();
14212
14501
  for (const hit of result.hits) {
@@ -14823,7 +15112,7 @@ async function moduleReport(file, cwd, options) {
14823
15112
  let callGraphIdentity;
14824
15113
  let revisionDriftNote;
14825
15114
  try {
14826
- const { getCachedReviewGraph, getReviewGraphCacheIdentity, getReviewGraphSizeSkipVerdict, getReviewGraphRevisionDrift, formatReviewGraphRevisionDriftNote: formatReviewGraphRevisionDriftNote2 } = await import("../chunk-3K2F6UDZ.js");
15115
+ const { getCachedReviewGraph, getReviewGraphCacheIdentity, getReviewGraphSizeSkipVerdict, getReviewGraphRevisionDrift, formatReviewGraphRevisionDriftNote: formatReviewGraphRevisionDriftNote2 } = await import("../chunk-T2S3FNNJ.js");
14827
15116
  graph = getCachedReviewGraph(cwd);
14828
15117
  graphFileCap = getReviewGraphSizeSkipVerdict(cwd)?.maxFileCount;
14829
15118
  const drift = graph ? getReviewGraphRevisionDrift(cwd) : void 0;
@@ -15498,7 +15787,7 @@ function focusScore2(text, terms) {
15498
15787
  }
15499
15788
  function buildFileDegrees(graph) {
15500
15789
  const fanIn = /* @__PURE__ */ new Map();
15501
- const fanOut = /* @__PURE__ */ new Map();
15790
+ const fanOut2 = /* @__PURE__ */ new Map();
15502
15791
  for (const edge of graph.edges) {
15503
15792
  if (edge.kind !== "imports")
15504
15793
  continue;
@@ -15510,10 +15799,10 @@ function buildFileDegrees(graph) {
15510
15799
  continue;
15511
15800
  if (!toNode || toNode.kind !== "file")
15512
15801
  continue;
15513
- let outSet = fanOut.get(edge.from);
15802
+ let outSet = fanOut2.get(edge.from);
15514
15803
  if (!outSet) {
15515
15804
  outSet = /* @__PURE__ */ new Set();
15516
- fanOut.set(edge.from, outSet);
15805
+ fanOut2.set(edge.from, outSet);
15517
15806
  }
15518
15807
  outSet.add(edge.to);
15519
15808
  let inSet = fanIn.get(edge.to);
@@ -15523,7 +15812,7 @@ function buildFileDegrees(graph) {
15523
15812
  }
15524
15813
  inSet.add(edge.from);
15525
15814
  }
15526
- return { fanIn, fanOut };
15815
+ return { fanIn, fanOut: fanOut2 };
15527
15816
  }
15528
15817
  function computeTrust(graph, cwd, drift) {
15529
15818
  const filesCovered = graph.fileNodes.size;
@@ -15616,7 +15905,7 @@ function roleFor(graph, filePath) {
15616
15905
  return top.length > 0 ? top.map((s) => s.name).join(", ") : void 0;
15617
15906
  }
15618
15907
  async function computeHubs(graph, degrees, cwd, limit, focusTerms) {
15619
- const { computeTransitiveImpact } = await import("../chunk-LSC3VADM.js");
15908
+ const { computeTransitiveImpact } = await import("../chunk-WXUDRAG6.js");
15620
15909
  const ranked = [...graph.fileNodes.entries()].map(([filePath, fileNodeId]) => ({
15621
15910
  filePath,
15622
15911
  fileNodeId,
@@ -15868,7 +16157,7 @@ async function projectReport(cwd, options) {
15868
16157
  const limit = clampLimit(options?.limit);
15869
16158
  const focusTerms = normalizeFocus2(options?.focus);
15870
16159
  const view = options?.view;
15871
- const { getCachedReviewGraph, getReviewGraphSizeSkipVerdict, getLastReviewGraphBuildAttempt, buildOrUpdateGraph, isGraphBuildInFlight, getReviewGraphRevisionDrift } = await import("../chunk-3K2F6UDZ.js");
16160
+ const { getCachedReviewGraph, getReviewGraphSizeSkipVerdict, getLastReviewGraphBuildAttempt, buildOrUpdateGraph, isGraphBuildInFlight, getReviewGraphRevisionDrift } = await import("../chunk-T2S3FNNJ.js");
15872
16161
  let graph;
15873
16162
  try {
15874
16163
  graph = getCachedReviewGraph(cwd);
@@ -15892,7 +16181,7 @@ async function projectReport(cwd, options) {
15892
16181
  };
15893
16182
  }
15894
16183
  const previousAttempt = getLastReviewGraphBuildAttempt(cwd);
15895
- const { FactStore: FactStore2 } = await import("../chunk-F6X3YJWD.js");
16184
+ const { FactStore: FactStore2 } = await import("../chunk-PIQQM32Y.js");
15896
16185
  const trigger = triggerBackgroundGraphBuild(cwd, {
15897
16186
  buildOrUpdateGraph,
15898
16187
  isGraphBuildInFlight,
@@ -15993,7 +16282,7 @@ function renderCompactProjectReport(report) {
15993
16282
  }
15994
16283
 
15995
16284
  // dist/clients/effective-config.js
15996
- import * as os4 from "node:os";
16285
+ import * as os3 from "node:os";
15997
16286
  import * as path28 from "node:path";
15998
16287
  function isEffectiveFileViewError(file) {
15999
16288
  return "error" in file;
@@ -16011,8 +16300,14 @@ function redactServerSpec(entry) {
16011
16300
  return void 0;
16012
16301
  }
16013
16302
  const record = entry;
16014
- const command = typeof record.command === "string" ? record.command : void 0;
16015
- const args = Array.isArray(record.args) ? record.args : [];
16303
+ const rawCommand = record.command;
16304
+ const commandArray = Array.isArray(rawCommand) ? rawCommand : void 0;
16305
+ const head = commandArray ? commandArray[0] : rawCommand;
16306
+ const command = typeof head === "string" ? head : void 0;
16307
+ const args = [
16308
+ ...commandArray?.slice(1) ?? [],
16309
+ ...Array.isArray(record.args) ? record.args : []
16310
+ ];
16016
16311
  const env = typeof record.env === "object" && record.env !== null ? Object.keys(record.env).sort(compareOrdinal) : [];
16017
16312
  const rawCovers = record.covers;
16018
16313
  let covers;
@@ -16059,7 +16354,7 @@ function decidedByOrNothing(entry) {
16059
16354
  }
16060
16355
  async function effectiveConfig(options = {}) {
16061
16356
  const cwd = options.cwd ?? process.cwd();
16062
- const homeDir = options.homeDir ?? os4.homedir();
16357
+ const homeDir = options.homeDir ?? os3.homedir();
16063
16358
  const resolveAt = (dir) => resolvePiLensConfig({
16064
16359
  cwd: dir,
16065
16360
  globalDir: getGlobalPiLensDir(),
@@ -16083,7 +16378,10 @@ async function effectiveConfig(options = {}) {
16083
16378
  documents: summary.documents,
16084
16379
  provenance: provenanceView(resolved, homeDir).entries,
16085
16380
  provenanceCounts: summary.countsByTier,
16086
- recordCounts: countBy(resolution.records, (record) => record.code),
16381
+ // The unknown `dispatch.disabledRunners` ids are records too: the pure
16382
+ // `disabledRunnersOf` derives them without reporting (this query is not a
16383
+ // dispatch), so a typo'd id shows here even where notifications are off.
16384
+ recordCounts: countBy([...resolution.records, ...disabledRunnersOf(resolution).records], (record) => record.code),
16087
16385
  tools: LENS_TOOL_NAMES.map((name) => ({
16088
16386
  name,
16089
16387
  enabled: resolveLensToolEnabled(name, resolved.value, void 0, options.noTools)
@@ -16095,6 +16393,7 @@ async function effectiveConfig(options = {}) {
16095
16393
  } : absolute === void 0 ? {} : {
16096
16394
  file: await fileView(
16097
16395
  absolute,
16396
+ resolution,
16098
16397
  resolved,
16099
16398
  homeDir,
16100
16399
  cwd,
@@ -16111,12 +16410,14 @@ async function effectiveConfig(options = {}) {
16111
16410
  };
16112
16411
  return view;
16113
16412
  }
16114
- function toolReason(selected, kind) {
16413
+ function toolReason(selected, disabled, kind) {
16414
+ if (disabled)
16415
+ return "disabled-by-config";
16115
16416
  if (selected)
16116
16417
  return "selected";
16117
16418
  return kind === void 0 ? "no-dispatch-plan" : "not-registered-for-kind";
16118
16419
  }
16119
- async function fileView(absolute, resolved, homeDir, workspaceCwd, lspConfig) {
16420
+ async function fileView(absolute, resolution, resolved, homeDir, workspaceCwd, lspConfig) {
16120
16421
  const language = resolveLanguage(absolute);
16121
16422
  const kind = detectFileKind(absolute);
16122
16423
  const section = lspSectionOf(resolved.value);
@@ -16145,11 +16446,13 @@ async function fileView(absolute, resolved, homeDir, workspaceCwd, lspConfig) {
16145
16446
  });
16146
16447
  const available = new Set(await getAvailableRunners(absolute));
16147
16448
  const planned = kind ? getToolPlan(kind)?.groups.flatMap((group) => group.runnerIds) ?? [] : [];
16449
+ const disabledRunners = new Map(disabledRunnersOf(resolution).runners.map((runner) => [runner.id, runner]));
16148
16450
  const ids = [.../* @__PURE__ */ new Set([...planned, ...available])].sort(compareOrdinal);
16149
16451
  const tools = ids.map((id) => ({
16150
16452
  id,
16151
- selected: available.has(id),
16152
- reason: toolReason(available.has(id), kind),
16453
+ selected: available.has(id) && !disabledRunners.has(id),
16454
+ reason: toolReason(available.has(id), disabledRunners.has(id), kind),
16455
+ ...decidedByOrNothing(viewOf(disabledRunners.get(id)?.decidedBy, homeDir)),
16153
16456
  resolvedCwd: homeRelativePath(resolveToolCwd("runner", id, absolute, {
16154
16457
  cwd: workspaceCwd,
16155
16458
  suppressTelemetry: true
@@ -16168,8 +16471,8 @@ async function fileView(absolute, resolved, homeDir, workspaceCwd, lspConfig) {
16168
16471
  function recentLatency(limit = 5, fileFilter) {
16169
16472
  let reports = getLatencyReports();
16170
16473
  if (fileFilter) {
16171
- const needle = fileFilter.replace(/\\/g, "/");
16172
- reports = reports.filter((report) => report.filePath.replace(/\\/g, "/").endsWith(needle));
16474
+ const needle = toPosix(fileFilter);
16475
+ reports = reports.filter((report) => toPosix(report.filePath).endsWith(needle));
16173
16476
  }
16174
16477
  return reports.slice(-limit).reverse();
16175
16478
  }
@@ -16243,14 +16546,19 @@ function symbolSearchFileMatchesLang(file, lang) {
16243
16546
  }
16244
16547
  function fileMatchesPathGlobs(file, cwd, globs) {
16245
16548
  const rel = path29.relative(cwd, file).split(path29.sep).join("/");
16549
+ const abs = path29.resolve(file).split(path29.sep).join("/");
16246
16550
  const options = { dot: true, nocase: process.platform === "win32" };
16551
+ const matches = (candidate, pattern) => minimatch(candidate, pattern, options) || minimatch(candidate, `${pattern}/**`, options);
16247
16552
  return globs.some((raw) => {
16248
- const pattern = raw.split("\\").join("/");
16249
- return minimatch(rel, pattern, options) || minimatch(rel, `${pattern}/**`, options);
16553
+ const within = path29.isAbsolute(raw) ? relativeInside(cwd, raw) : void 0;
16554
+ if (within !== void 0)
16555
+ return matches(rel, toPosix(within) || "**");
16556
+ const pattern = toPosix(raw);
16557
+ return matches(rel, pattern) || abs !== rel && matches(abs, pattern);
16250
16558
  });
16251
16559
  }
16252
16560
  function buildSymbolSearchFileFilter(cwd, options) {
16253
- const paths = options.paths?.filter((p) => p.trim().length > 0);
16561
+ const paths = options.paths;
16254
16562
  const lang = options.lang?.trim();
16255
16563
  if (!paths?.length && !lang)
16256
16564
  return void 0;
@@ -16290,6 +16598,7 @@ function toSymbolSearchHit(result) {
16290
16598
  };
16291
16599
  }
16292
16600
  async function symbolSearch(query, cwd, limit = 20, options = {}) {
16601
+ const effectiveLimit = Number.isFinite(limit) ? Math.max(1, Math.floor(limit)) : 20;
16293
16602
  const warmLease = acquireWarmWordIndex(cwd);
16294
16603
  const snapshot = loadProjectSnapshotWithoutWordIndex(cwd);
16295
16604
  const index = warmLease.index;
@@ -16312,12 +16621,16 @@ async function symbolSearch(query, cwd, limit = 20, options = {}) {
16312
16621
  try {
16313
16622
  centrality = centralityFromReverseDeps(index, snapshot?.reverseDeps, (file) => normalizeMapKey(path29.resolve(file)));
16314
16623
  const fileFilter = buildSymbolSearchFileFilter(cwd, options);
16315
- results = searchWordIndex(index, query, { limit, centrality, fileFilter });
16624
+ results = searchWordIndex(index, query, {
16625
+ limit: effectiveLimit,
16626
+ centrality,
16627
+ fileFilter
16628
+ });
16316
16629
  } finally {
16317
16630
  warmLease.release();
16318
16631
  }
16319
16632
  const hits = results.map(toSymbolSearchHit);
16320
- const { getCachedReviewGraph } = await import("../chunk-3K2F6UDZ.js");
16633
+ const { getCachedReviewGraph } = await import("../chunk-T2S3FNNJ.js");
16321
16634
  const graph = getCachedReviewGraph(cwd);
16322
16635
  if (graph)
16323
16636
  annotateSymbolSearchHitsWithGraph(hits, centrality, graph);
@@ -16329,6 +16642,43 @@ async function symbolSearch(query, cwd, limit = 20, options = {}) {
16329
16642
  snapshotGeneratedAt: snapshot?.generatedAt
16330
16643
  };
16331
16644
  }
16645
+ function coverageLine(coverage) {
16646
+ if (!coverage)
16647
+ return void 0;
16648
+ return `Index covers ${coverage.files} files${coverage.truncated ? " (capped \u2014 results may be incomplete)" : ""}.`;
16649
+ }
16650
+ function formatSymbolSearchRow(hit, position, cwd) {
16651
+ const annotations = hit.annotations;
16652
+ const detail = [
16653
+ `score ${hit.score.toFixed(2)}`,
16654
+ `${hit.hits} hit(s)`,
16655
+ ...typeof annotations?.fanIn === "number" ? [`fanIn ${annotations.fanIn}`] : [],
16656
+ ...typeof annotations?.complexity === "number" ? [`complexity ${annotations.complexity}`] : []
16657
+ ];
16658
+ return ` ${position}. ${path29.relative(cwd, hit.file)} ${hit.startLine} (${detail.join(", ")})`;
16659
+ }
16660
+ function renderCompactSymbolSearch(result, options) {
16661
+ const hits = result.results;
16662
+ const sections = [
16663
+ hits.length > 0 ? [
16664
+ `Top ${hits.length} file(s) for "${result.query}":`,
16665
+ ...hits.map((hit, index) => formatSymbolSearchRow(hit, index + 1, options.cwd))
16666
+ ].join("\n") : `No files matched "${result.query}".`
16667
+ ];
16668
+ const footer = [];
16669
+ const coverage = coverageLine(result.coverage);
16670
+ if (coverage)
16671
+ footer.push(coverage);
16672
+ if (options.stalenessNote)
16673
+ footer.push(options.stalenessNote);
16674
+ const top = hits[0];
16675
+ if (top) {
16676
+ footer.push(`Next: ${options.reportTool ?? "module_report"} ${path29.relative(options.cwd, top.file)}`);
16677
+ }
16678
+ if (footer.length > 0)
16679
+ sections.push(footer.join("\n"));
16680
+ return sections.join("\n\n");
16681
+ }
16332
16682
 
16333
16683
  // dist/clients/deps/typebox.js
16334
16684
  import { Type } from "typebox";
@@ -16514,12 +16864,86 @@ function canonicalLanguage(lang) {
16514
16864
  }
16515
16865
 
16516
16866
  // dist/tools/shared.js
16867
+ import * as os4 from "node:os";
16517
16868
  import * as path31 from "node:path";
16518
- function resolveAstGrepPaths(paths, cwd) {
16519
- const base = cwd || ".";
16520
- if (!paths?.length)
16521
- return [path31.resolve(base)];
16522
- return paths.map((p) => resolveHostToolPath(p, base));
16869
+ var MAX_PATHS_ENTRIES = 100;
16870
+ var FILE_PATH_KEYS = ["path", "file", "filePath"];
16871
+ function readFilePath(params) {
16872
+ const sent = [];
16873
+ const blanks = [];
16874
+ for (const key of FILE_PATH_KEYS) {
16875
+ const raw = params[key];
16876
+ if (raw === void 0 || raw === null)
16877
+ continue;
16878
+ if (typeof raw !== "string")
16879
+ return { path: "", key, refusal: `\`${key}\` must be a string path` };
16880
+ if (!raw.trim()) {
16881
+ blanks.push(key);
16882
+ continue;
16883
+ }
16884
+ sent.push({ key, value: raw });
16885
+ }
16886
+ const first = sent[0];
16887
+ if (!first) {
16888
+ const blank = blanks[0];
16889
+ return blank ? { path: "", key: blank, refusal: `\`${blank}\` is blank \u2014 name a file` } : { path: "" };
16890
+ }
16891
+ if (new Set(sent.map((entry) => entry.value)).size > 1) {
16892
+ return {
16893
+ path: "",
16894
+ refusal: `${sent.map((entry) => `\`${entry.key}\`: ${entry.value}`).join(", ")} name different files \u2014 send one spelling`
16895
+ };
16896
+ }
16897
+ return { path: first.value, key: first.key };
16898
+ }
16899
+ function describeEntryType(value) {
16900
+ if (value === null)
16901
+ return "null";
16902
+ if (Array.isArray(value))
16903
+ return "an array";
16904
+ return typeof value;
16905
+ }
16906
+ function readPathsArgument(raw, options) {
16907
+ const base = options.cwd || ".";
16908
+ const absent = options.absent ?? "none";
16909
+ if (raw === void 0 || raw === null) {
16910
+ return { entries: absent === "cwd" ? [path31.resolve(base)] : [] };
16911
+ }
16912
+ if (!Array.isArray(raw))
16913
+ return { entries: [], refusal: "paths must be an array of strings" };
16914
+ if (raw.length === 0)
16915
+ return {
16916
+ entries: [],
16917
+ refusal: "paths is empty: it names no entry, so the call would widen to the tool's default. Omit `paths` to use that default."
16918
+ };
16919
+ if (raw.length > MAX_PATHS_ENTRIES)
16920
+ return {
16921
+ entries: [],
16922
+ refusal: `paths must contain at most ${MAX_PATHS_ENTRIES} string entries, got ${raw.length}`
16923
+ };
16924
+ const entries = [];
16925
+ for (const [index, entry] of raw.entries()) {
16926
+ if (typeof entry !== "string")
16927
+ return {
16928
+ entries: [],
16929
+ refusal: `paths entry ${index + 1} must be a string, not ${describeEntryType(entry)}`
16930
+ };
16931
+ if (!entry.trim())
16932
+ return { entries: [], refusal: `paths entry ${index + 1} is blank` };
16933
+ entries.push(resolveHostToolPath(entry, base));
16934
+ }
16935
+ return { entries };
16936
+ }
16937
+ function defaultedCwdHomeRefusal(paths, cwd) {
16938
+ if (paths?.length)
16939
+ return void 0;
16940
+ const spelling = cwd || ".";
16941
+ if (!isAtOrAboveHomeDir(realpathOrResolve(spelling), realpathOrResolve(os4.homedir())))
16942
+ return void 0;
16943
+ return {
16944
+ reason: "defaulted cwd resolves at or above home directory",
16945
+ text: `Refused: no \`paths\` given and the working directory (${spelling}) resolves at or above the home directory \u2014 this would reach every unrelated tree under your home. Pass explicit \`paths\`, or run from a project directory.`
16946
+ };
16523
16947
  }
16524
16948
  var LANGUAGES = [
16525
16949
  "bash",
@@ -16628,6 +17052,7 @@ function createAstGrepReplaceTool(astGrepClient2, captureLineage) {
16628
17052
  }),
16629
17053
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
16630
17054
  const lineage = captureLineage?.();
17055
+ const sessionId = ctx.sessionManager?.getSessionId?.();
16631
17056
  const startedAt = Date.now();
16632
17057
  const { pattern, rewrite, paths, apply, strictness, insideKind, hasKind, hasDescendantKind, follows, precedes } = params;
16633
17058
  const { lang, refusal: langError } = readAstGrepLang(params.lang, true);
@@ -16663,6 +17088,20 @@ function createAstGrepReplaceTool(astGrepClient2, captureLineage) {
16663
17088
  details: {}
16664
17089
  };
16665
17090
  }
17091
+ const pathsRead = readPathsArgument(paths, {
17092
+ cwd: ctx.cwd,
17093
+ absent: "cwd"
17094
+ });
17095
+ if (pathsRead.refusal) {
17096
+ logOutcome("error", { errorRaw: pathsRead.refusal });
17097
+ return {
17098
+ content: [
17099
+ { type: "text", text: `Error: ${pathsRead.refusal}` }
17100
+ ],
17101
+ isError: true,
17102
+ details: {}
17103
+ };
17104
+ }
16666
17105
  if (!await astGrepClient2.ensureAvailable()) {
16667
17106
  logOutcome("error", { errorRaw: "ast-grep CLI not found" });
16668
17107
  return {
@@ -16676,7 +17115,16 @@ function createAstGrepReplaceTool(astGrepClient2, captureLineage) {
16676
17115
  details: {}
16677
17116
  };
16678
17117
  }
16679
- const searchPaths = resolveAstGrepPaths(paths, ctx.cwd);
17118
+ const homeRefusal = defaultedCwdHomeRefusal(paths, ctx.cwd);
17119
+ if (homeRefusal) {
17120
+ logOutcome("error", { errorRaw: homeRefusal.reason });
17121
+ return {
17122
+ content: [{ type: "text", text: homeRefusal.text }],
17123
+ isError: true,
17124
+ details: {}
17125
+ };
17126
+ }
17127
+ const searchPaths = pathsRead.entries;
16680
17128
  if (hasStructuralIntent({
16681
17129
  insideKind,
16682
17130
  hasKind,
@@ -16709,7 +17157,7 @@ function createAstGrepReplaceTool(astGrepClient2, captureLineage) {
16709
17157
  details: {}
16710
17158
  };
16711
17159
  }
16712
- const ruleResult = await astGrepClient2.replaceWithRule(ruleYaml, searchPaths, applyFlag, { lineage, toolCallId: _toolCallId });
17160
+ const ruleResult = await astGrepClient2.replaceWithRule(ruleYaml, searchPaths, applyFlag, { lineage, toolCallId: _toolCallId, sessionId });
16713
17161
  if (ruleResult.stalePreview) {
16714
17162
  logOutcome("error", { errorRaw: "stale_preview" });
16715
17163
  return {
@@ -16748,7 +17196,7 @@ function createAstGrepReplaceTool(astGrepClient2, captureLineage) {
16748
17196
  }
16749
17197
  };
16750
17198
  }
16751
- const result = await astGrepClient2.replace(pattern, rewrite, lang, searchPaths, applyFlag, { strictness, lineage, toolCallId: _toolCallId });
17199
+ const result = await astGrepClient2.replace(pattern, rewrite, lang, searchPaths, applyFlag, { strictness, lineage, toolCallId: _toolCallId, sessionId });
16752
17200
  if (result.stalePreview) {
16753
17201
  logOutcome("error", { errorRaw: "stale_preview" });
16754
17202
  return {
@@ -16798,7 +17246,6 @@ function createAstGrepReplaceTool(astGrepClient2, captureLineage) {
16798
17246
  }
16799
17247
 
16800
17248
  // dist/tools/ast-grep-search.js
16801
- import * as os5 from "node:os";
16802
17249
  function errorTextWithHint2(raw, host) {
16803
17250
  const hint = astGrepRemediationHint(classifyAstGrepError(raw));
16804
17251
  return hint ? `Error: ${raw}
@@ -16829,7 +17276,6 @@ function toSearchReads(matches) {
16829
17276
  }
16830
17277
  var DEFAULT_PAGE_SIZE = 50;
16831
17278
  var MAX_PAGE_SIZE = 200;
16832
- var MAX_PATHS = 200;
16833
17279
  var AST_GREP_SEARCH_TIMEOUT_MS = 3e4;
16834
17280
  function formatGroupedByFile(matches) {
16835
17281
  const byFile = /* @__PURE__ */ new Map();
@@ -17036,7 +17482,7 @@ function createAstGrepSearchTool(astGrepClient2) {
17036
17482
  description: "Language id, e.g. typescript, tsx, python, go."
17037
17483
  }),
17038
17484
  paths: Type.Optional(Type.Array(Type.String(), {
17039
- maxItems: MAX_PATHS,
17485
+ maxItems: MAX_PATHS_ENTRIES,
17040
17486
  description: "Files or directories to search."
17041
17487
  })),
17042
17488
  selector: Type.Optional(Type.String({
@@ -17139,8 +17585,12 @@ function createAstGrepSearchTool(astGrepClient2) {
17139
17585
  const hasPattern = Boolean(pattern.trim());
17140
17586
  const hasNodeKind = normalizedNodeKind.length > 0;
17141
17587
  const rawPaths = params.paths;
17142
- if (rawPaths !== void 0 && (!Array.isArray(rawPaths) || rawPaths.length > MAX_PATHS || rawPaths.some((value) => typeof value !== "string"))) {
17143
- const errorRaw = `paths must contain at most ${MAX_PATHS} string entries`;
17588
+ const pathsRead = readPathsArgument(rawPaths, {
17589
+ cwd: ctx.cwd,
17590
+ absent: "cwd"
17591
+ });
17592
+ if (pathsRead.refusal) {
17593
+ const errorRaw = pathsRead.refusal;
17144
17594
  logOutcome("error", { errorRaw });
17145
17595
  return {
17146
17596
  content: [{ type: "text", text: `Error: ${errorRaw}` }],
@@ -17261,17 +17711,11 @@ function createAstGrepSearchTool(astGrepClient2) {
17261
17711
  details: {}
17262
17712
  };
17263
17713
  }
17264
- if (!paths?.length && isAtOrAboveHomeDir(realpathOrResolve(ctx.cwd || "."), realpathOrResolve(os5.homedir()))) {
17265
- logOutcome("error", {
17266
- errorRaw: "defaulted cwd resolves at or above home directory"
17267
- });
17714
+ const homeRefusal = defaultedCwdHomeRefusal(paths, ctx.cwd);
17715
+ if (homeRefusal) {
17716
+ logOutcome("error", { errorRaw: homeRefusal.reason });
17268
17717
  return {
17269
- content: [
17270
- {
17271
- type: "text",
17272
- text: `Refused: no \`paths\` given and the working directory (${ctx.cwd || "."}) resolves at or above the home directory \u2014 searching it would scan every unrelated tree under your home. Pass explicit \`paths\`, or run from a project directory.`
17273
- }
17274
- ],
17718
+ content: [{ type: "text", text: homeRefusal.text }],
17275
17719
  isError: true,
17276
17720
  details: {}
17277
17721
  };
@@ -17294,7 +17738,7 @@ function createAstGrepSearchTool(astGrepClient2) {
17294
17738
  details: {}
17295
17739
  };
17296
17740
  }
17297
- const searchPaths = resolveAstGrepPaths(paths, ctx.cwd);
17741
+ const searchPaths = pathsRead.entries;
17298
17742
  const PAGE_SIZE = Math.max(1, Math.min(MAX_PAGE_SIZE, Number.isFinite(maxMatches) ? Math.floor(maxMatches) : DEFAULT_PAGE_SIZE));
17299
17743
  let effectiveRule = hasRawRule ? rawRule : void 0;
17300
17744
  if (!effectiveRule && (hasNodeKind || hasStructuralIntent({
@@ -17550,7 +17994,7 @@ function reasonFromAvailabilityVerdict(tool, verdict) {
17550
17994
 
17551
17995
  // dist/clients/project-diagnostics/fresh-fetch.js
17552
17996
  import * as fs20 from "node:fs";
17553
- import * as os6 from "node:os";
17997
+ import * as os5 from "node:os";
17554
17998
  import * as path36 from "node:path";
17555
17999
 
17556
18000
  // dist/clients/project-diagnostics/runner-adapters/jscpd.js
@@ -17789,7 +18233,7 @@ async function fetchFreshProjectDiagnostics(cacheManager2, cwd, clients, signal,
17789
18233
  analysisRoot = realpathOrResolve(cwd);
17790
18234
  }
17791
18235
  const unsafeRootReason = "the analysis root resolves at or above the home directory; heavyweight analyzers refuse to walk from there (#747)";
17792
- const homeRoot = realpathOrResolve(options.homeDir ?? os6.homedir());
18236
+ const homeRoot = realpathOrResolve(options.homeDir ?? os5.homedir());
17793
18237
  if (options.analysisRoot !== void 0) {
17794
18238
  const unsafeExplicitRoot = !isSameOrWithin(homeRoot, analysisRoot) || isSameOrWithin(analysisRoot, homeRoot);
17795
18239
  analysisRootValidation = unsafeExplicitRoot ? {
@@ -18146,18 +18590,7 @@ async function fetchFreshProjectDiagnostics(cacheManager2, cwd, clients, signal,
18146
18590
  })
18147
18591
  ];
18148
18592
  const allSettled = Promise.all(tasks).then(() => "completed").catch(() => "completed");
18149
- const outcome = signal ? await Promise.race([
18150
- allSettled,
18151
- new Promise((resolve32) => {
18152
- if (signal.aborted) {
18153
- resolve32("aborted");
18154
- return;
18155
- }
18156
- signal.addEventListener("abort", () => resolve32("aborted"), {
18157
- once: true
18158
- });
18159
- })
18160
- ]) : await allSettled;
18593
+ const outcome = await untilAborted(allSettled, signal, "aborted");
18161
18594
  if (outcome === "aborted") {
18162
18595
  const abortedIds = ANALYZER_IDS.filter((id) => !settledIds.has(id));
18163
18596
  for (const id of abortedIds)
@@ -18235,6 +18668,698 @@ function makeProgressReporter(onUpdate, label, throttleMs = 250) {
18235
18668
  // dist/tools/lsp-diagnostics.js
18236
18669
  import * as fs21 from "node:fs";
18237
18670
  import * as path37 from "node:path";
18671
+
18672
+ // dist/clients/out-of-band-changes.js
18673
+ import { promises as fsp } from "node:fs";
18674
+ import * as os6 from "node:os";
18675
+ import { basename as basename7, join as join17 } from "node:path";
18676
+
18677
+ // dist/clients/disk-changes.js
18678
+ var DISK_CHANGE_ORIGINS = [
18679
+ "out-of-band",
18680
+ "bash-recovery",
18681
+ "head-move",
18682
+ "settled-sweep",
18683
+ "drift-heartbeat"
18684
+ ];
18685
+ var DISK_CHANGE_MAX_RECORDED_PATHS = 64;
18686
+ var REGISTRY_FAMILY = "disk-changes.subscribers";
18687
+ var REGISTRY_VERSION = 1;
18688
+ function subscribers() {
18689
+ return getProcessSingleton(REGISTRY_FAMILY, REGISTRY_VERSION, () => /* @__PURE__ */ new Map());
18690
+ }
18691
+ function subscribeDiskChange(id, handler, origins = DISK_CHANGE_ORIGINS) {
18692
+ subscribers().set(id, { id, handler, origins });
18693
+ return () => {
18694
+ if (subscribers().get(id)?.handler === handler)
18695
+ subscribers().delete(id);
18696
+ };
18697
+ }
18698
+ function publishFailure(cause) {
18699
+ return cause instanceof Error ? cause.message : String(cause);
18700
+ }
18701
+ async function publishDiskChange(input, runtime, onAppendError) {
18702
+ const at = input.at ?? Date.now();
18703
+ const root = normalizeMapKey(input.root);
18704
+ const { recorded, truncated } = input.paths === "unknown" ? { recorded: [], truncated: false } : recordedPopulation(input.paths);
18705
+ const { seq, fileSeqs } = allocateSequence(recorded, input, runtime, appendFailureHandler(root, onAppendError));
18706
+ if (truncated) {
18707
+ recordDegradationOnce({
18708
+ kind: "disk-change-paths-truncated",
18709
+ subject: root,
18710
+ reason: `one publish carried more than ${DISK_CHANGE_MAX_RECORDED_PATHS} paths; the first ${DISK_CHANGE_MAX_RECORDED_PATHS} are named and the rest are reported as unenumerable${seq === 0 ? " (this publish allocated no sequence: it ran with no runtime)" : ""}`
18711
+ });
18712
+ }
18713
+ const unknown = input.paths === "unknown" || truncated;
18714
+ const change = {
18715
+ seq,
18716
+ fileSeqs,
18717
+ root,
18718
+ origin: input.origin,
18719
+ sources: input.sources ?? [input.origin],
18720
+ kind: input.kind ?? "inferred",
18721
+ paths: unknown ? "unknown" : recorded,
18722
+ ...input.pathChanges ? { pathChanges: input.pathChanges } : {},
18723
+ ...input.after ? { after: input.after } : {},
18724
+ at,
18725
+ sessionScopeId: runtime?.sessionGeneration ?? 0
18726
+ };
18727
+ const started = Date.now();
18728
+ const { results, failed } = await fanOut(change);
18729
+ logLatency({
18730
+ type: "phase",
18731
+ phase: "disk_change_published",
18732
+ filePath: root,
18733
+ durationMs: Date.now() - started,
18734
+ result: `${input.origin}:${recorded.length}`,
18735
+ metadata: {
18736
+ origin: input.origin,
18737
+ sources: change.sources.join(","),
18738
+ kind: change.kind,
18739
+ recorded: recorded.length,
18740
+ unknown: unknown ? 1 : 0,
18741
+ truncated: truncated ? 1 : 0,
18742
+ seq,
18743
+ subscribers: [...subscribers().keys()].join(",").slice(0, 200)
18744
+ }
18745
+ });
18746
+ return { change, results, failedSubscribers: failed };
18747
+ }
18748
+ function recordedPopulation(paths) {
18749
+ const named = /* @__PURE__ */ new Set();
18750
+ const raw = [];
18751
+ let truncated = false;
18752
+ for (const filePath of paths) {
18753
+ if (named.has(filePath))
18754
+ continue;
18755
+ if (raw.length === DISK_CHANGE_MAX_RECORDED_PATHS) {
18756
+ truncated = true;
18757
+ break;
18758
+ }
18759
+ named.add(filePath);
18760
+ raw.push(filePath);
18761
+ }
18762
+ const seen = /* @__PURE__ */ new Set();
18763
+ const recorded = [];
18764
+ for (const filePath of raw) {
18765
+ const key = normalizeMapKey(filePath);
18766
+ if (seen.has(key))
18767
+ continue;
18768
+ seen.add(key);
18769
+ recorded.push(key);
18770
+ }
18771
+ return { recorded, truncated };
18772
+ }
18773
+ function appendFailureHandler(root, onAppendError) {
18774
+ return (err) => {
18775
+ incrementDegradationCount({
18776
+ kind: "disk-change-append-failed",
18777
+ subject: root,
18778
+ reason: `the change log did not record this publish: ${publishFailure(err)}`
18779
+ });
18780
+ onAppendError?.(err);
18781
+ };
18782
+ }
18783
+ function allocateSequence(recorded, input, runtime, onAppendError) {
18784
+ if (recorded.length === 0)
18785
+ return { seq: 0, fileSeqs: /* @__PURE__ */ new Map() };
18786
+ const allocated = runtime?.recordProjectMutations?.({
18787
+ paths: recorded,
18788
+ source: "external",
18789
+ cwd: input.root,
18790
+ onAppendError
18791
+ });
18792
+ return {
18793
+ seq: allocated?.projectSeq ?? 0,
18794
+ fileSeqs: allocated?.fileSeqs ?? /* @__PURE__ */ new Map()
18795
+ };
18796
+ }
18797
+ async function fanOut(change) {
18798
+ const results = /* @__PURE__ */ new Map();
18799
+ const failed = /* @__PURE__ */ new Set();
18800
+ const registered2 = Array.from(subscribers().values());
18801
+ for (const subscriber of registered2) {
18802
+ if (subscriber.origins && !subscriber.origins.includes(change.origin))
18803
+ continue;
18804
+ try {
18805
+ results.set(subscriber.id, await subscriber.handler(change));
18806
+ } catch (cause) {
18807
+ failed.add(subscriber.id);
18808
+ recordDegradationOnce({
18809
+ kind: "disk-change-subscriber-failed",
18810
+ subject: `${subscriber.id}:${change.root}`,
18811
+ reason: `subscriber threw: ${publishFailure(cause)}`
18812
+ });
18813
+ }
18814
+ }
18815
+ return { results, failed };
18816
+ }
18817
+
18818
+ // dist/clients/disk-change-subscribers.js
18819
+ import * as nodeFs3 from "node:fs";
18820
+ var WATCHED_FILE_TYPE = {
18821
+ created: 1,
18822
+ changed: 2,
18823
+ deleted: 3
18824
+ };
18825
+ function diagnosticsCacheSubscriber(change) {
18826
+ if (change.sources.includes("install") || change.paths === "unknown")
18827
+ noteWorkspaceDependenciesChanged(change.at);
18828
+ if (change.paths === "unknown")
18829
+ return;
18830
+ if (change.paths.length === 0)
18831
+ return;
18832
+ noteWorkspaceFilesChangedOnDisk(change.root, change.paths, change.at);
18833
+ }
18834
+ var BASH_RECOVERY_DRIFT_SOURCE = "recovered-drift";
18835
+ var HELD_PRIMARY_CAP = 64;
18836
+ var HEAD_MOVE_RESYNC_MAX_PASSES = 16;
18837
+ var NO_HELD_DOCUMENTS = {
18838
+ held: 0,
18839
+ targets: [],
18840
+ primary: 0,
18841
+ unheld: 0,
18842
+ failed: false,
18843
+ drained: true
18844
+ };
18845
+ async function sendToHeldPrimaries(root, candidates, drainMs) {
18846
+ const service = peekLSPService();
18847
+ if (!service || candidates.length === 0)
18848
+ return { targets: [], primary: 0, failed: false, drained: true };
18849
+ const held = new Set(service.getOpenDocumentPaths(root));
18850
+ const targets = (await Promise.all(candidates.map(async (filePath) => {
18851
+ if (!held.has(filePath))
18852
+ return void 0;
18853
+ const sent = service.getTrackedContent(filePath, root)?.hash;
18854
+ try {
18855
+ const disk = await nodeFs3.promises.readFile(filePath, "utf8");
18856
+ return sent === hashContentBytes(Buffer.from(disk, "utf8")) ? void 0 : filePath;
18857
+ } catch {
18858
+ return filePath;
18859
+ }
18860
+ }))).filter((filePath) => filePath !== void 0);
18861
+ if (targets.length === 0)
18862
+ return { targets, primary: 0, failed: false, drained: true };
18863
+ try {
18864
+ const { sent, drained } = await service.resyncHeldPrimaries(targets.slice(0, HELD_PRIMARY_CAP), drainMs);
18865
+ return { targets, primary: sent, failed: false, drained };
18866
+ } catch {
18867
+ return { targets, primary: 0, failed: true, drained: false };
18868
+ }
18869
+ }
18870
+ function notifyUnheldPaths(service, change, held) {
18871
+ if (change.paths === "unknown")
18872
+ return 0;
18873
+ const unheld = change.paths.flatMap((filePath) => held.has(filePath) ? [] : [filePath]);
18874
+ if (unheld.length === 0)
18875
+ return 0;
18876
+ try {
18877
+ const events = unheld.map((filePath) => ({
18878
+ filePath,
18879
+ type: WATCHED_FILE_TYPE[nodeFs3.statSync(filePath, { throwIfNoEntry: false }) === void 0 ? "deleted" : "changed"]
18880
+ }));
18881
+ service.notifyOutOfBandFileChanges(events);
18882
+ service.announceCreatedFiles(unheld);
18883
+ return events.length;
18884
+ } catch (cause) {
18885
+ recordDegradationOnce({
18886
+ kind: "disk-change-unheld-notify-failed",
18887
+ subject: change.root,
18888
+ reason: `the watched-files events for ${unheld.length} unheld path(s) were not delivered, so a closed module changed on disk may keep its old bytes in a live server: ${cause instanceof Error ? cause.message : String(cause)}`
18889
+ });
18890
+ return 0;
18891
+ }
18892
+ }
18893
+ async function resyncHeldDocuments(change, options) {
18894
+ const service = peekLSPService();
18895
+ if (!service)
18896
+ return NO_HELD_DOCUMENTS;
18897
+ const held = new Set(service.getOpenDocumentPaths(change.root));
18898
+ const candidates = change.paths === "unknown" ? [...held] : change.paths.filter((filePath) => held.has(filePath));
18899
+ const unheld = notifyUnheldPaths(service, change, held);
18900
+ const { targets, primary, failed, drained } = await sendToHeldPrimaries(change.root, candidates, options.drainMs);
18901
+ const answer = {
18902
+ held: candidates.length,
18903
+ targets,
18904
+ primary,
18905
+ unheld,
18906
+ failed,
18907
+ drained
18908
+ };
18909
+ if (!options.drift || targets.length === 0 || failed)
18910
+ return answer;
18911
+ answer.drift = service.resyncGitChangedFiles(targets, options.maxPasses === void 0 ? {} : { maxPasses: options.maxPasses });
18912
+ return answer;
18913
+ }
18914
+ function driftRecoveredFiles(change) {
18915
+ const service = peekLSPService();
18916
+ if (!service)
18917
+ return NO_HELD_DOCUMENTS;
18918
+ const population = change.paths === "unknown" ? service.getOpenDocumentPaths(change.root) : change.paths;
18919
+ if (population.length === 0)
18920
+ return NO_HELD_DOCUMENTS;
18921
+ return {
18922
+ ...NO_HELD_DOCUMENTS,
18923
+ drift: service.resyncGitChangedFiles(population)
18924
+ };
18925
+ }
18926
+ async function outOfBandLsp(change) {
18927
+ const service = peekLSPService();
18928
+ if (!service)
18929
+ return { restarted: 0 };
18930
+ let restarted = 0;
18931
+ if (change.sources.includes("install"))
18932
+ restarted = await service.restartPrimaryClientsUnder(change.root) ?? 0;
18933
+ const events = change.pathChanges ?? [];
18934
+ if (events.length === 0)
18935
+ return { restarted };
18936
+ service.notifyOutOfBandFileChanges(events.map((event) => ({
18937
+ filePath: event.filePath,
18938
+ type: WATCHED_FILE_TYPE[event.type]
18939
+ })));
18940
+ return { restarted };
18941
+ }
18942
+ async function lspSubscriber(change) {
18943
+ switch (change.origin) {
18944
+ case "out-of-band":
18945
+ return outOfBandLsp(change);
18946
+ case "head-move":
18947
+ return resyncHeldDocuments(change, {
18948
+ drift: true,
18949
+ maxPasses: HEAD_MOVE_RESYNC_MAX_PASSES,
18950
+ drainMs: HOOK_WALL_BUDGET_MS.tool_result_read_only
18951
+ });
18952
+ case "bash-recovery":
18953
+ return change.sources.includes(BASH_RECOVERY_DRIFT_SOURCE) ? driftRecoveredFiles(change) : resyncHeldDocuments(change, {
18954
+ drift: false,
18955
+ drainMs: HOOK_WALL_BUDGET_MS.tool_result_edit
18956
+ });
18957
+ case "settled-sweep":
18958
+ return resyncHeldDocuments(change, {
18959
+ drift: true,
18960
+ drainMs: HOOK_WALL_BUDGET_MS.agent_settled
18961
+ });
18962
+ case "drift-heartbeat":
18963
+ return void 0;
18964
+ }
18965
+ const unreachable = change.origin;
18966
+ return unreachable;
18967
+ }
18968
+ var DIAGNOSTICS_CACHE_CONSUMER = "diagnostics-cache";
18969
+ var LSP_CONSUMER = "lsp";
18970
+ var LSP_ORIGINS = DISK_CHANGE_ORIGINS.flatMap((origin) => origin === "drift-heartbeat" ? [] : [origin]);
18971
+ var registered = false;
18972
+ function ensureDiskChangeSubscribers() {
18973
+ if (registered)
18974
+ return;
18975
+ registered = true;
18976
+ subscribeDiskChange(DIAGNOSTICS_CACHE_CONSUMER, diagnosticsCacheSubscriber, DISK_CHANGE_ORIGINS);
18977
+ subscribeDiskChange(LSP_CONSUMER, lspSubscriber, LSP_ORIGINS);
18978
+ }
18979
+
18980
+ // dist/clients/out-of-band-changes.js
18981
+ var INSTALL_LOCKFILES = [
18982
+ "package-lock.json",
18983
+ "npm-shrinkwrap.json",
18984
+ "pnpm-lock.yaml",
18985
+ "yarn.lock",
18986
+ "bun.lock",
18987
+ "bun.lockb",
18988
+ "uv.lock",
18989
+ "poetry.lock",
18990
+ "Pipfile.lock",
18991
+ "pdm.lock",
18992
+ "go.sum",
18993
+ "Cargo.lock"
18994
+ ];
18995
+ var INSTALL_MARKERS = [
18996
+ ".package-lock.json",
18997
+ ".modules.yaml",
18998
+ ".yarn-state.yml",
18999
+ ".yarn-integrity"
19000
+ ];
19001
+ var VENV_LIB_DIR = "lib";
19002
+ var VENV_WINDOWS_SITE_PACKAGES = join17("Lib", "site-packages");
19003
+ var VENV_INTERPRETER_DIRS_MAX = 4;
19004
+ var DECLARATION_WALK_MAX_DIRS = 4096;
19005
+ var DECLARATION_WALK_MAX_FILES = 2048;
19006
+ var DECLARATION_WALK_CONCURRENCY = 16;
19007
+ var DECLARATION_FILE = /(?:\.d\.[cm]?ts|\.pyi)$/i;
19008
+ var MAX_ROOTS = 64;
19009
+ function declarationLookIntervalMs() {
19010
+ const raw = Number(process.env.PI_LENS_DECLARATION_LOOK_MS);
19011
+ return Number.isFinite(raw) && raw >= 0 ? raw : 2e3;
19012
+ }
19013
+ var records = new BoundedFifoMap(MAX_ROOTS);
19014
+ var looks = createSingleFlight({ coalesceTrailing: true });
19015
+ var owedWalks = new BoundedFifoMap(MAX_ROOTS);
19016
+ function oweDeclarationWalk(root, trigger, walk = "trigger") {
19017
+ if (demandsWalk(trigger, walk))
19018
+ owedWalks.set(normalizeMapKey(root), true);
19019
+ }
19020
+ function demandsWalk(trigger, walk) {
19021
+ return walk === "always" || trigger === "tool_result" && walk !== "interval";
19022
+ }
19023
+ var fingerprint = (stat) => `${stat.ino}:${stat.size}:${stat.mtimeMs}`;
19024
+ function diffServerConfigs(root, before, after) {
19025
+ return diffDeclarations(new Map([...before].map(([name, print]) => [join17(root, name), print])), new Map([...after].map(([name, print]) => [join17(root, name), print])));
19026
+ }
19027
+ async function readVenvInstallParts(root, listed) {
19028
+ const targets = [];
19029
+ for (const name of PROJECT_VENV_DIR_NAMES) {
19030
+ if (!listed.has(name))
19031
+ continue;
19032
+ const venvRoot = join17(root, name);
19033
+ targets.push({
19034
+ label: `${name}/${VENV_WINDOWS_SITE_PACKAGES}`,
19035
+ dir: join17(venvRoot, VENV_WINDOWS_SITE_PACKAGES)
19036
+ });
19037
+ let interpreters;
19038
+ try {
19039
+ interpreters = await fsp.readdir(join17(venvRoot, VENV_LIB_DIR), {
19040
+ withFileTypes: true
19041
+ });
19042
+ } catch {
19043
+ continue;
19044
+ }
19045
+ interpreters.sort((a, b) => compareOrdinal(a.name, b.name));
19046
+ const interpreterDirs = interpreters.filter((entry) => entry.isDirectory() || entry.isSymbolicLink()).slice(0, VENV_INTERPRETER_DIRS_MAX);
19047
+ for (const interpreter of interpreterDirs) {
19048
+ targets.push({
19049
+ label: `${name}/${VENV_LIB_DIR}/${interpreter.name}/site-packages`,
19050
+ dir: join17(venvRoot, VENV_LIB_DIR, interpreter.name, "site-packages")
19051
+ });
19052
+ }
19053
+ }
19054
+ return Promise.all(targets.map(async (target) => {
19055
+ try {
19056
+ const stat = await fsp.stat(target.dir);
19057
+ return {
19058
+ part: `${target.label}=${fingerprint(stat)}`,
19059
+ changedAt: stat.mtimeMs
19060
+ };
19061
+ } catch {
19062
+ return { part: `${target.label}=-`, changedAt: 0 };
19063
+ }
19064
+ }));
19065
+ }
19066
+ async function readInstallStamp(root) {
19067
+ let listed;
19068
+ try {
19069
+ listed = new Set(await fsp.readdir(root));
19070
+ } catch {
19071
+ return { stamp: "-", newestChangeMs: 0, configs: void 0 };
19072
+ }
19073
+ const names = [];
19074
+ for (const name of INSTALL_LOCKFILES)
19075
+ if (listed.has(name))
19076
+ names.push(name);
19077
+ let linkPrint;
19078
+ let linkChangedAt = 0;
19079
+ if (listed.has("node_modules")) {
19080
+ for (const marker of INSTALL_MARKERS)
19081
+ names.push(`node_modules/${marker}`);
19082
+ let link;
19083
+ try {
19084
+ link = await fsp.lstat(join17(root, "node_modules"));
19085
+ } catch {
19086
+ link = void 0;
19087
+ }
19088
+ if (link?.isSymbolicLink()) {
19089
+ linkPrint = `node_modules=${fingerprint(link)}`;
19090
+ linkChangedAt = link.mtimeMs;
19091
+ }
19092
+ }
19093
+ const configNames = [];
19094
+ for (const name of SERVER_CONFIG_FILE_NAMES)
19095
+ if (listed.has(name))
19096
+ configNames.push(name);
19097
+ const [statted, venvParts] = await Promise.all([
19098
+ Promise.all([...names, ...configNames].map(async (name) => {
19099
+ try {
19100
+ const stat = await fsp.stat(join17(root, name));
19101
+ return {
19102
+ part: `${name}=${fingerprint(stat)}`,
19103
+ changedAt: stat.mtimeMs
19104
+ };
19105
+ } catch {
19106
+ return { part: `${name}=-`, changedAt: 0 };
19107
+ }
19108
+ })),
19109
+ readVenvInstallParts(root, listed)
19110
+ ]);
19111
+ const parts = statted.slice(0, names.length);
19112
+ const configs = /* @__PURE__ */ new Map();
19113
+ for (const [index, name] of configNames.entries()) {
19114
+ const print = statted[names.length + index].part.slice(name.length + 1);
19115
+ if (print !== "-")
19116
+ configs.set(name, print);
19117
+ }
19118
+ if (linkPrint !== void 0)
19119
+ parts.push({ part: linkPrint, changedAt: linkChangedAt });
19120
+ parts.push(...venvParts);
19121
+ return {
19122
+ configs,
19123
+ stamp: parts.map((entry) => entry.part).join("|"),
19124
+ newestChangeMs: parts.reduce((newest, entry) => Math.max(newest, entry.changedAt), 0)
19125
+ };
19126
+ }
19127
+ var COARSE_MTIME_SLACK_MS = 1e3;
19128
+ function firstLookSawInstall(install, since) {
19129
+ return since !== void 0 && since > 0 && install.newestChangeMs >= since - COARSE_MTIME_SLACK_MS;
19130
+ }
19131
+ async function walkDeclarations(root) {
19132
+ const found = [];
19133
+ const unreadable = [];
19134
+ const unreadableFiles = [];
19135
+ const queue = [root];
19136
+ let next = 0;
19137
+ let capped = false;
19138
+ const worker = async () => {
19139
+ while (!capped && next < queue.length) {
19140
+ if (next >= DECLARATION_WALK_MAX_DIRS) {
19141
+ capped = true;
19142
+ return;
19143
+ }
19144
+ const dir = queue[next++];
19145
+ let entries;
19146
+ try {
19147
+ entries = await fsp.readdir(dir, { withFileTypes: true });
19148
+ } catch {
19149
+ unreadable.push(dir);
19150
+ continue;
19151
+ }
19152
+ for (const entry of entries) {
19153
+ if (entry.isDirectory()) {
19154
+ if (!isExcludedDirName(entry.name))
19155
+ queue.push(join17(dir, entry.name));
19156
+ } else if (entry.isFile() && DECLARATION_FILE.test(entry.name)) {
19157
+ found.push(join17(dir, entry.name));
19158
+ }
19159
+ }
19160
+ if (found.length > DECLARATION_WALK_MAX_FILES)
19161
+ capped = true;
19162
+ }
19163
+ };
19164
+ while (!capped && next < queue.length)
19165
+ await Promise.all(Array.from({ length: DECLARATION_WALK_CONCURRENCY }, worker));
19166
+ if (capped)
19167
+ return void 0;
19168
+ found.sort(compareOrdinal);
19169
+ const declarations = /* @__PURE__ */ new Map();
19170
+ const prints = await Promise.all(found.map(async (filePath) => {
19171
+ try {
19172
+ return [filePath, fingerprint(await fsp.stat(filePath))];
19173
+ } catch (err) {
19174
+ const code = err?.code;
19175
+ if (code === "ENOENT" || code === "ENOTDIR") {
19176
+ return void 0;
19177
+ }
19178
+ return [filePath, void 0];
19179
+ }
19180
+ }));
19181
+ for (const print of prints) {
19182
+ if (print === void 0)
19183
+ continue;
19184
+ if (print[1] === void 0)
19185
+ unreadableFiles.push(print[0]);
19186
+ else
19187
+ declarations.set(print[0], print[1]);
19188
+ }
19189
+ return { declarations, unreadable, unreadableFiles };
19190
+ }
19191
+ function carryUnreadable(declarations, previous, walk) {
19192
+ if (!declarations || !previous || !walk || walk.unreadable.length === 0 && walk.unreadableFiles.length === 0)
19193
+ return { carried: 0, dropped: 0 };
19194
+ const unreadableFiles = new Set(walk.unreadableFiles);
19195
+ const carried = [];
19196
+ for (const filePath of previous.keys()) {
19197
+ if (declarations.has(filePath))
19198
+ continue;
19199
+ const underUnreadableDir = walk.unreadable.some((dir) => isUnderDir(filePath, dir));
19200
+ if (!underUnreadableDir && !unreadableFiles.has(filePath))
19201
+ continue;
19202
+ carried.push(filePath);
19203
+ }
19204
+ carried.sort(compareOrdinal);
19205
+ let dropped = 0;
19206
+ for (const filePath of carried) {
19207
+ if (declarations.size >= DECLARATION_WALK_MAX_FILES) {
19208
+ dropped++;
19209
+ continue;
19210
+ }
19211
+ declarations.set(filePath, previous.get(filePath));
19212
+ }
19213
+ return { carried: carried.length - dropped, dropped };
19214
+ }
19215
+ function diffDeclarations(before, after) {
19216
+ const changes = [];
19217
+ for (const [filePath, print] of after) {
19218
+ const prior = before.get(filePath);
19219
+ if (prior === void 0)
19220
+ changes.push({ filePath, type: 1 });
19221
+ else if (prior !== print)
19222
+ changes.push({ filePath, type: 2 });
19223
+ }
19224
+ for (const filePath of before.keys())
19225
+ if (!after.has(filePath))
19226
+ changes.push({ filePath, type: 3 });
19227
+ return changes;
19228
+ }
19229
+ function lookForOutOfBandChanges(root, trigger, runtime, options = {}) {
19230
+ if (options.signal?.aborted)
19231
+ return Promise.resolve();
19232
+ const homeRoot = isAtOrAboveHomeDir(realpathOrResolve(root), realpathOrResolve(os6.homedir()));
19233
+ if (homeRoot)
19234
+ recordDegradationOnce({
19235
+ kind: "lsp-declaration-look-capped",
19236
+ subject: "home-root",
19237
+ reason: "a session root that is the home folder or above it is not walked for declaration files changed outside pi-lens; such a change under it is not looked for (a dependency install still is)"
19238
+ });
19239
+ const key = normalizeMapKey(root);
19240
+ oweDeclarationWalk(root, trigger, options.walk);
19241
+ const look = looks.run(key, () => lookOnce(root, key, trigger, runtime, options, homeRoot));
19242
+ return untilAborted(look, options.signal);
19243
+ }
19244
+ var CONFIG_SOURCE = "config";
19245
+ var CHANGE_TYPE = {
19246
+ 1: "created",
19247
+ 2: "changed",
19248
+ 3: "deleted"
19249
+ };
19250
+ function outOfBandChange(root, installed, changes, configChanges, at) {
19251
+ const sources = [
19252
+ ...installed ? ["install"] : [],
19253
+ ...changes.length > 0 ? ["declarations"] : [],
19254
+ ...configChanges.length > 0 ? [CONFIG_SOURCE] : []
19255
+ ];
19256
+ const pathChanges = [...changes, ...configChanges].map((change) => ({
19257
+ filePath: change.filePath,
19258
+ type: CHANGE_TYPE[change.type]
19259
+ }));
19260
+ return {
19261
+ root,
19262
+ origin: "out-of-band",
19263
+ sources,
19264
+ // A stat fingerprint, not the bytes: an `inferred` change may never by
19265
+ // itself confirm that a finding was not reproduced.
19266
+ kind: "inferred",
19267
+ // A config file changes the analysis of every file under its root, so it
19268
+ // cannot be enumerated any more than an install can: the cache refuses
19269
+ // everything scanned before it (`"unknown"`), never just the config path.
19270
+ paths: configChanges.length > 0 ? "unknown" : changes.length > 0 ? changes.map((change) => normalizeMapKey(change.filePath)) : installed ? "unknown" : [],
19271
+ ...pathChanges.length > 0 ? { pathChanges } : {},
19272
+ at
19273
+ };
19274
+ }
19275
+ async function lookOnce(root, key, trigger, runtime, options, skipWalk) {
19276
+ const walkOwed = owedWalks.delete(key);
19277
+ const started = Date.now();
19278
+ const prior = records.get(key);
19279
+ const walkDue = !skipWalk && (walkOwed || prior === void 0 || started - prior.walkedAt >= declarationLookIntervalMs());
19280
+ const [install, walked] = await Promise.all([
19281
+ readInstallStamp(root),
19282
+ walkDue ? walkDeclarations(root) : Promise.resolve(void 0)
19283
+ ]);
19284
+ const observed = walkDue ? walked : void 0;
19285
+ const carry = carryUnreadable(observed?.declarations, prior?.declarations, observed);
19286
+ const incomplete = carry.dropped > 0;
19287
+ const declarations = incomplete ? prior?.declarations : observed?.declarations ?? prior?.declarations;
19288
+ records.set(key, {
19289
+ stamp: install.stamp,
19290
+ // An unlistable root keeps the previous baseline: reading it as "no
19291
+ // config files" would publish every one as created on the next look.
19292
+ configs: install.configs ?? prior?.configs,
19293
+ declarations,
19294
+ walkedAt: walkDue && !incomplete ? started : prior?.walkedAt ?? started
19295
+ });
19296
+ if (walkDue && walked === void 0)
19297
+ recordDegradationOnce({
19298
+ kind: "lsp-declaration-look-capped",
19299
+ subject: key,
19300
+ reason: `the declaration-file walk passed ${DECLARATION_WALK_MAX_DIRS} directories or ${DECLARATION_WALK_MAX_FILES} files; declaration files created, edited or deleted outside pi-lens under this root reach no language server and no diagnostics-cache entry is refused for them`
19301
+ });
19302
+ const unreadableFiles = observed?.unreadableFiles ?? [];
19303
+ if (observed && (observed.unreadable.length > 0 || unreadableFiles.length > 0)) {
19304
+ const firstUnreadable = observed.unreadable[0] ?? unreadableFiles[0];
19305
+ incrementDegradationCount({
19306
+ kind: "lsp-declaration-walk-unreadable",
19307
+ subject: key,
19308
+ reason: `${incomplete ? `${carry.dropped} declaration file(s) could not be carried past the ${DECLARATION_WALK_MAX_FILES}-file cap, so the previous walk's map stands; ` : ""}${observed.unreadable.length} unreadable dir(s) and ${unreadableFiles.length} unreadable file(s) under this root, first \`${firstUnreadable}\`; ${carry.carried} declaration file(s) kept their previous fingerprint, so a change there is not read as a deletion`,
19309
+ metadata: {
19310
+ unreadableDirs: observed.unreadable.length,
19311
+ firstUnreadableDir: observed.unreadable[0],
19312
+ unreadableFiles: unreadableFiles.length,
19313
+ firstUnreadableFile: unreadableFiles[0],
19314
+ heldBackDeclarations: carry.carried,
19315
+ carriedDropped: carry.dropped
19316
+ }
19317
+ });
19318
+ }
19319
+ const installed = prior === void 0 ? firstLookSawInstall(install, options.since) : install.stamp !== prior.stamp;
19320
+ if (prior === void 0 && !installed)
19321
+ return;
19322
+ const changes = walkDue && !incomplete && declarations && prior?.declarations ? diffDeclarations(prior.declarations, declarations) : [];
19323
+ const configChanges = install.configs && prior?.configs ? diffServerConfigs(root, prior.configs, install.configs) : [];
19324
+ if (!installed && changes.length === 0 && configChanges.length === 0)
19325
+ return;
19326
+ const at = Date.now();
19327
+ ensureDiskChangeSubscribers();
19328
+ const { results, failedSubscribers } = await publishDiskChange(outOfBandChange(root, installed, changes, configChanges, at), runtime);
19329
+ const restarted = failedSubscribers.has(LSP_CONSUMER) ? -1 : results.get(LSP_CONSUMER)?.restarted ?? 0;
19330
+ const count = (type) => changes.reduce((n, change) => n + (change.type === type ? 1 : 0), 0);
19331
+ logLatency({
19332
+ type: "phase",
19333
+ phase: "lsp_out_of_band_change",
19334
+ filePath: root,
19335
+ durationMs: Date.now() - started,
19336
+ result: [
19337
+ ...installed ? ["install"] : [],
19338
+ ...changes.length > 0 ? ["declarations"] : [],
19339
+ ...configChanges.length > 0 ? [CONFIG_SOURCE] : []
19340
+ ].join("+"),
19341
+ metadata: {
19342
+ trigger,
19343
+ restarted,
19344
+ // Which look produced this row: the root's FIRST look (no record yet,
19345
+ // so only `since` can make it publish — the #4532 live-client epoch)
19346
+ // or a later look compared against the recorded stamp. Both the
19347
+ // session-cwd root and a live client's root write the same record,
19348
+ // so this names the look, not the caller.
19349
+ scope: prior === void 0 ? "first-look" : "recorded",
19350
+ // #4532 gap 6: the walk served a demand this row's own trigger did not
19351
+ // make: a bash result that joined this flight (`owedWalks`).
19352
+ joinedWalk: walkOwed && !demandsWalk(trigger, options.walk),
19353
+ created: count(1),
19354
+ changed: count(2),
19355
+ deleted: count(3),
19356
+ // The server config files this look forwarded (#4532), by name.
19357
+ configs: configChanges.map((change) => `${CHANGE_TYPE[change.type]}:${basename7(change.filePath)}`)
19358
+ }
19359
+ });
19360
+ }
19361
+
19362
+ // dist/tools/lsp-diagnostics.js
18238
19363
  var MAX_FILES = 100;
18239
19364
  var MAX_BATCH_FILES = 100;
18240
19365
  var MAX_DIAGNOSTICS = 200;
@@ -18387,6 +19512,10 @@ function createLspDiagnosticsTool(nextWriteIndex, onConfirmedNoBlockers, getServ
18387
19512
  details: {}
18388
19513
  };
18389
19514
  }
19515
+ await lookForOutOfBandChanges(cwd, "tool_call", void 0, {
19516
+ walk: "always",
19517
+ signal
19518
+ });
18390
19519
  await lspService.sweepDocumentDrift({ force: true, full: true });
18391
19520
  if (Array.isArray(typedParams.paths) && typedParams.paths.length > 0) {
18392
19521
  if (typedParams.paths.length > MAX_BATCH_FILES) {
@@ -18541,7 +19670,11 @@ async function collectDiagnosticsForFile(absPath, lspService, scanRoot, waitMs,
18541
19670
  content,
18542
19671
  ...attached.response.projectIdentity !== void 0 && {
18543
19672
  projectIdentity: attached.response.projectIdentity
18544
- }
19673
+ },
19674
+ // #5030: the incumbent's content binding, so a stale-bound answer
19675
+ // is demoted to unconfirmed (`boundMismatch`) like a local one. An
19676
+ // incumbent that sends none reads as not current.
19677
+ binding: warmAnswerBinding(answer)
18545
19678
  };
18546
19679
  }
18547
19680
  }
@@ -18609,7 +19742,7 @@ function describePrimaryUnavailable(touched, fallbackHealth) {
18609
19742
  }
18610
19743
  const cause = carriedCause ?? primaryUnavailableCause(serverIds, disabledServerIds);
18611
19744
  return {
18612
- text: `Primary LSP (${serverIds.join(", ")}): not available \u2014 no language server answered for this file (${PRIMARY_UNAVAILABLE_CAUSE[cause]}). NOT the same as 0 diagnostics; auxiliary scanners do not check the language itself.`,
19745
+ text: `Primary LSP (${serverIds.join(", ")}): not available \u2014 no primary language server answered for this file (${PRIMARY_UNAVAILABLE_CAUSE[cause]}). NOT the same as 0 diagnostics; auxiliary scanners do not check the language itself.`,
18613
19746
  cause
18614
19747
  };
18615
19748
  }
@@ -18688,7 +19821,7 @@ function applyProbeFindingPolicy(file, diagnostics, cwd, content, severity, tool
18688
19821
  cwd,
18689
19822
  filePath: file,
18690
19823
  content,
18691
- policyMap: loadProjectRulePolicyMap(cwd),
19824
+ policyMap: loadProjectRulePolicy(cwd),
18692
19825
  fileRole: detectFileRole(file, content)
18693
19826
  });
18694
19827
  const { kept: delivered, dropped } = partitionOutrankedPythonCompileVerdicts(result.kept, pythonCompileTarget);
@@ -18812,9 +19945,7 @@ async function collectFileDiagnosticResult(file, severity, lspService, waitMs, n
18812
19945
  const health = lspService.getDiagnosticsHealth?.(file);
18813
19946
  let effectiveRawDiags = rawDiags;
18814
19947
  let confirmation;
18815
- if (diagnosticsUnsupportedServerIds.length > 0) {
18816
- confirmation = void 0;
18817
- } else if (skipReason !== void 0 || primaryUnavailable !== void 0) {
19948
+ if (diagnosticsUnsupportedServerIds.length > 0 || skipReason !== void 0 || primaryUnavailable !== void 0) {
18818
19949
  confirmation = "unconfirmed";
18819
19950
  } else if (timedOut) {
18820
19951
  if (applySeverityFilter(rawDiags, severity).length === 0) {
@@ -18899,7 +20030,6 @@ async function collectFileDiagnosticResult(file, severity, lspService, waitMs, n
18899
20030
  },
18900
20031
  ...noClientAnswered && { noClientAnswered },
18901
20032
  primaryServerId: primaryServerId(file),
18902
- diagnosticsUnsupported: diagnosticsUnsupportedServerIds.length > 0,
18903
20033
  ...policy.suppressed > 0 && {
18904
20034
  dispositionSuppressed: policy.suppressed
18905
20035
  },
@@ -18933,9 +20063,7 @@ async function runFileDiagnostics(absPath, severity, lspService, waitMs, nextWri
18933
20063
  const unavailable = lspUnavailableMessage(absPath, lspHealth);
18934
20064
  let effectiveRawDiags = rawDiags;
18935
20065
  let confirmation;
18936
- if (diagnosticsUnsupportedServerIds.length > 0) {
18937
- confirmation = void 0;
18938
- } else if (skipReason !== void 0 || primaryUnavailable !== void 0) {
20066
+ if (diagnosticsUnsupportedServerIds.length > 0 || skipReason !== void 0 || primaryUnavailable !== void 0) {
18939
20067
  confirmation = "unconfirmed";
18940
20068
  } else if (timedOut) {
18941
20069
  if (applySeverityFilter(rawDiags, severity).length === 0) {
@@ -18993,7 +20121,7 @@ async function runFileDiagnostics(absPath, severity, lspService, waitMs, nextWri
18993
20121
  return rootFallback ? `${primaryUnavailable} ${describeRootFallback(rootFallback, false)}.` : primaryUnavailable;
18994
20122
  }
18995
20123
  if (diagnosticsUnsupportedServerIds.length > 0) {
18996
- return `Primary LSP${primaryId ? ` (${primaryId})` : ""}: navigation-only \u2014 diagnostics unsupported (no pull provider or publish evidence).`;
20124
+ return `Primary LSP${primaryId ? ` (${primaryId})` : ""}: unconfirmed \u2014 a custom server with no pull provider has not published diagnostics yet. NOT the same as 0 diagnostics; it is checked again once the server publishes.`;
18997
20125
  }
18998
20126
  if (timedOut) {
18999
20127
  return "Primary LSP: check timed out \u2014 NOT the same as 0 diagnostics; the file may still have errors that just hadn't been reported yet. Re-check after the server settles, or increase waitMs.";
@@ -19009,7 +20137,7 @@ async function runFileDiagnostics(absPath, severity, lspService, waitMs, nextWri
19009
20137
  }
19010
20138
  return `Primary LSP${primaryId ? ` (${primaryId})` : ""}: ${primaryDiags.length} diagnostic${primaryDiags.length === 1 ? "" : "s"}.`;
19011
20139
  })();
19012
- const coverageLine = unconfirmedServerIds.length > 0 ? `Auxiliary coverage INCOMPLETE \u2014 ${[...unconfirmedServerIds].join(", ")} did not answer within the wait budget, so ${unconfirmedServerIds.length === 1 ? "its findings are" : "their findings are"} NOT included here. This is not a clean bill of health for ${unconfirmedServerIds.length === 1 ? "that scanner" : "those scanners"}; re-check after the next edit. waitMs can extend an ordinary wait, but it cannot override a session-demoted scanner.` : void 0;
20140
+ const coverageLine2 = unconfirmedServerIds.length > 0 ? `Auxiliary coverage INCOMPLETE \u2014 ${[...unconfirmedServerIds].join(", ")} did not answer within the wait budget, so ${unconfirmedServerIds.length === 1 ? "its findings are" : "their findings are"} NOT included here. This is not a clean bill of health for ${unconfirmedServerIds.length === 1 ? "that scanner" : "those scanners"}; re-check after the next edit. waitMs can extend an ordinary wait, but it cannot override a session-demoted scanner.` : void 0;
19013
20141
  const suppressedLine = dispositionSuppressedLine(policy.suppressed);
19014
20142
  const withheldLine = withheldCompileNote(policy.withheld);
19015
20143
  const notRunServerIds = serverScope === "all" && excludeServerIds && excludeServerIds.size > 0 ? getServersForFileWithConfig(absPath).flatMap((server) => excludeServerIds.has(server.id) ? [server.id] : []) : [];
@@ -19026,7 +20154,7 @@ async function runFileDiagnostics(absPath, severity, lspService, waitMs, nextWri
19026
20154
  primaryLine,
19027
20155
  "",
19028
20156
  unavailable ?? noAuxiliaryLine,
19029
- ...coverageLine ? [coverageLine] : [],
20157
+ ...coverageLine2 ? [coverageLine2] : [],
19030
20158
  ...suppressedLine ? [suppressedLine] : [],
19031
20159
  ...withheldLine ? [withheldLine] : []
19032
20160
  ].join("\n");
@@ -19039,8 +20167,8 @@ async function runFileDiagnostics(absPath, severity, lspService, waitMs, nextWri
19039
20167
  lines.push(`Auxiliary findings (${auxiliaryDiags.length}):`);
19040
20168
  lines.push(...auxiliaryDiags.map(formatDiag));
19041
20169
  }
19042
- if (coverageLine)
19043
- lines.push("", coverageLine);
20170
+ if (coverageLine2)
20171
+ lines.push("", coverageLine2);
19044
20172
  if (suppressedLine)
19045
20173
  lines.push("", suppressedLine);
19046
20174
  if (withheldLine)
@@ -19081,7 +20209,6 @@ async function runFileDiagnostics(absPath, severity, lspService, waitMs, nextWri
19081
20209
  truncated,
19082
20210
  unconfirmed,
19083
20211
  timedOut: unconfirmed ? timedOut : void 0,
19084
- navigationOnlyFiles: diagnosticsUnsupportedServerIds.length > 0 ? 1 : void 0,
19085
20212
  ...skipReason !== void 0 && { skipReason },
19086
20213
  ...primaryUnavailable !== void 0 && { primaryUnavailable },
19087
20214
  ...rootFallback && {
@@ -19105,17 +20232,12 @@ function tallyConfirmation(results) {
19105
20232
  const primaryUnavailableCauses = [];
19106
20233
  const primaryUnavailableRootReasons = /* @__PURE__ */ new Set();
19107
20234
  const rootFallbackReasons = /* @__PURE__ */ new Set();
19108
- let navigationOnly = 0;
19109
20235
  let tooLarge = 0;
19110
20236
  for (const result of results) {
19111
20237
  if (result.tooLargeReason) {
19112
20238
  tooLarge += 1;
19113
20239
  continue;
19114
20240
  }
19115
- if (result.diagnosticsUnsupported) {
19116
- navigationOnly += 1;
19117
- continue;
19118
- }
19119
20241
  if (result.diagnostics.length > 0)
19120
20242
  continue;
19121
20243
  if (result.confirmation === "unconfirmed") {
@@ -19148,7 +20270,6 @@ function tallyConfirmation(results) {
19148
20270
  rootFallbackReasons: [...primaryUnavailableRootReasons]
19149
20271
  },
19150
20272
  rootFallbackReasons: [...rootFallbackReasons],
19151
- navigationOnly,
19152
20273
  tooLarge
19153
20274
  };
19154
20275
  }
@@ -19157,8 +20278,6 @@ function classifyBatchFileOutcome(result) {
19157
20278
  return "failed";
19158
20279
  if (result.tooLargeReason)
19159
20280
  return "too_large";
19160
- if (result.diagnosticsUnsupported)
19161
- return "unsupported";
19162
20281
  if (result.noClientAnswered && result.primaryUnavailable !== void 0) {
19163
20282
  return "unavailable";
19164
20283
  }
@@ -19194,7 +20313,7 @@ function auxiliaryOnlyFindingsLine(results) {
19194
20313
  if (count === 0)
19195
20314
  return void 0;
19196
20315
  const cause = combinePrimaryUnavailableCauses(auxiliaryOnly.flatMap((result) => result.primaryUnavailableCause ?? [])) ?? "unstarted";
19197
- return `${count} file${count === 1 ? "" : "s"} with auxiliary findings only: no language server answered (${PRIMARY_UNAVAILABLE_CAUSE[cause]}), so the language itself was not checked.`;
20316
+ return `${count} file${count === 1 ? "" : "s"} with auxiliary or fallback findings only: no primary language server answered (${PRIMARY_UNAVAILABLE_CAUSE[cause]}), so the language itself was not confirmed.`;
19198
20317
  }
19199
20318
  function unconfirmedReasonClause(unconfirmed, timedOut, rootFallbackReasons = [], primaryUnavailable = {
19200
20319
  count: 0,
@@ -19202,7 +20321,7 @@ function unconfirmedReasonClause(unconfirmed, timedOut, rootFallbackReasons = []
19202
20321
  rootFallbackReasons: []
19203
20322
  }) {
19204
20323
  if (primaryUnavailable.count > 0) {
19205
- const head = `${primaryUnavailable.count} with no language server answer (${PRIMARY_UNAVAILABLE_CAUSE[primaryUnavailable.cause ?? "unstarted"]})` + (primaryUnavailable.rootFallbackReasons.length > 0 ? `: ${primaryUnavailable.rootFallbackReasons.join("; ")}` : "");
20324
+ const head = `${primaryUnavailable.count} with no primary language server answer (${PRIMARY_UNAVAILABLE_CAUSE[primaryUnavailable.cause ?? "unstarted"]})` + (primaryUnavailable.rootFallbackReasons.length > 0 ? `: ${primaryUnavailable.rootFallbackReasons.join("; ")}` : "");
19206
20325
  const rest = unconfirmed - primaryUnavailable.count;
19207
20326
  return rest > 0 ? `${head}; the other ${rest}: ${unconfirmedReasonClause(rest, timedOut, rootFallbackReasons)}` : `${head}.`;
19208
20327
  }
@@ -19265,18 +20384,7 @@ async function collectBatchDiagnostics(files, severity, lspService, options) {
19265
20384
  onTimeout: "undefined",
19266
20385
  onReject: "undefined"
19267
20386
  });
19268
- const result = options.signal ? await Promise.race([
19269
- bounded2,
19270
- new Promise((resolve32) => {
19271
- if (options.signal?.aborted) {
19272
- resolve32(void 0);
19273
- return;
19274
- }
19275
- options.signal?.addEventListener("abort", () => resolve32(void 0), {
19276
- once: true
19277
- });
19278
- })
19279
- ]) : await bounded2;
20387
+ const result = await untilAborted(bounded2, options.signal);
19280
20388
  resultsByIndex.set(index, result ?? inconclusiveBatchResult(file, options.signal?.aborted ? "Batch aborted before this file completed." : `File check exceeded ${batchFileDeadlineMs()}ms.`));
19281
20389
  completed += 1;
19282
20390
  options.onProgress?.(completed, files.length);
@@ -19378,7 +20486,6 @@ async function runBatchFileDiagnostics(absPaths, severity, lspService, options,
19378
20486
  };
19379
20487
  }
19380
20488
  const { results, fileErrors, lspHealthWarnings, total, truncated, display, primaryDisplay, auxiliaryDisplay, clean, unconfirmed, timedOut, rootFallbackReasons, primaryUnavailable, outcomeCounts, incompleteFiles } = await collectBatchDiagnostics(absPaths, severity, lspService, options);
19381
- const navigationOnly = results.filter((result) => result.diagnosticsUnsupported).length;
19382
20489
  const dispositionSuppressed = results.reduce((sum, result) => sum + (result.dispositionSuppressed ?? 0), 0);
19383
20490
  const lines = [
19384
20491
  `Files checked: ${results.length}${capped ? ` (capped at ${MAX_FILES})` : ""}`,
@@ -19463,7 +20570,6 @@ async function runBatchFileDiagnostics(absPaths, severity, lspService, options,
19463
20570
  truncated,
19464
20571
  cleanFiles: clean,
19465
20572
  unconfirmedFiles: unconfirmed,
19466
- navigationOnlyFiles: navigationOnly > 0 ? navigationOnly : void 0,
19467
20573
  timedOutFiles: timedOut > 0 ? timedOut : void 0,
19468
20574
  outcomes: results.map((result) => ({
19469
20575
  file: result.file,
@@ -19537,7 +20643,6 @@ async function runDirectoryDiagnostics(absPath, severity, lspService, options) {
19537
20643
  };
19538
20644
  }
19539
20645
  const { results, fileErrors, lspHealthWarnings, total, truncated, display, primaryDisplay, auxiliaryDisplay, clean, unconfirmed, timedOut, rootFallbackReasons, primaryUnavailable, outcomeCounts } = await collectBatchDiagnostics(filesToProcess, severity, lspService, options);
19540
- const navigationOnly = results.filter((result) => result.diagnosticsUnsupported).length;
19541
20646
  const dispositionSuppressed = results.reduce((sum, result) => sum + (result.dispositionSuppressed ?? 0), 0);
19542
20647
  const suppressedLine = dispositionSuppressedLine(dispositionSuppressed);
19543
20648
  const outcomeDetails = results.map((result) => ({
@@ -19639,7 +20744,6 @@ async function runDirectoryDiagnostics(absPath, severity, lspService, options) {
19639
20744
  unconfirmedFiles: unconfirmed,
19640
20745
  outcomes: outcomeDetails,
19641
20746
  outcomeCounts,
19642
- navigationOnlyFiles: navigationOnly > 0 ? navigationOnly : void 0,
19643
20747
  timedOutFiles: timedOut > 0 ? timedOut : void 0,
19644
20748
  fileErrors: fileErrors.length > 0 ? fileErrors : void 0,
19645
20749
  lspHealthWarnings: lspHealthWarnings.length > 0 ? lspHealthWarnings : void 0,
@@ -19679,7 +20783,6 @@ function formatDiag(diag) {
19679
20783
 
19680
20784
  // dist/tools/lens-diagnostics.js
19681
20785
  var MAX_DIAGNOSTICS_PER_FILE = 50;
19682
- var MAX_PATHS_ENTRIES = MAX_BATCH_FILES;
19683
20786
  function notRequestedReason(host) {
19684
20787
  return `refreshRunners not requested this call (quick mode) \u2014 pass refreshRunners=cheap/all/cached to ${resolveLensToolName("lens_diagnostics", host) ?? "diagnostics"} mode=full to run it`;
19685
20788
  }
@@ -19743,7 +20846,7 @@ function createLensDiagnosticsTool(cacheManager2, getCwd, getLspService = getLSP
19743
20846
  logExtension({
19744
20847
  subsystem: "git-guard",
19745
20848
  level: "debug",
19746
- message: `inline_blocker: retired for ${info.filePath}`
20849
+ message: `inline_blocker: retired or narrowed to its uncovered source rows for ${info.filePath}`
19747
20850
  });
19748
20851
  }
19749
20852
  }, getLspService, getFlag);
@@ -19762,8 +20865,6 @@ function createLensDiagnosticsTool(cacheManager2, getCwd, getLspService = getLSP
19762
20865
  const scope = files2 > 1 ? ` across ${files2} files` : singleFile;
19763
20866
  if (isError)
19764
20867
  return `lens_diagnostics lsp \u2014 ${text.split("\n")[0] ?? "error"}`;
19765
- if ((details.navigationOnlyFiles ?? 0) > 0)
19766
- return `lens_diagnostics${scope} \u2014 ${count} ${noun} \xB7 ${details.cleanFiles ?? 0} clean \xB7 ${details.navigationOnlyFiles} navigation-only`;
19767
20868
  if ((details.unconfirmedFiles ?? 0) > 0)
19768
20869
  return `lens_diagnostics${scope} \u2014 ${count} ${noun} \xB7 ${details.cleanFiles ?? 0} clean \xB7 ${details.unconfirmedFiles} unconfirmed${details.timedOutFiles ? ` (${details.timedOutFiles} timed out)` : ""}`;
19769
20870
  const outcomeCounts = details.outcomeCounts;
@@ -19778,7 +20879,7 @@ function createLensDiagnosticsTool(cacheManager2, getCwd, getLspService = getLSP
19778
20879
  if (count === 0 && details.unconfirmed)
19779
20880
  return details.timedOut ? `lens_diagnostics${scope} \u2014 timed out (result may be incomplete)` : (
19780
20881
  // #4322: no language server answered; it is not a silent server.
19781
- details.primaryUnavailable !== void 0 ? `lens_diagnostics${scope} \u2014 unconfirmed (no language server answered)` : `lens_diagnostics${scope} \u2014 unconfirmed (server cannot confirm clean)`
20882
+ details.primaryUnavailable !== void 0 ? `lens_diagnostics${scope} \u2014 unconfirmed (no primary language server answered)` : `lens_diagnostics${scope} \u2014 unconfirmed (server cannot confirm clean)`
19782
20883
  );
19783
20884
  return `lens_diagnostics${scope} \u2014 ${count} ${noun}`;
19784
20885
  }
@@ -19838,6 +20939,8 @@ function createLensDiagnosticsTool(cacheManager2, getCwd, getLspService = getLSP
19838
20939
  path: Type.Optional(Type.String({
19839
20940
  description: "One file or directory for source=lsp checks."
19840
20941
  })),
20942
+ file: Type.Optional(Type.String({ description: "Alias for `path`." })),
20943
+ filePath: Type.Optional(Type.String({ description: "Alias for `path`." })),
19841
20944
  concurrency: Type.Optional(Type.Number({
19842
20945
  description: "Source=lsp batch concurrency (maximum 16)."
19843
20946
  })),
@@ -19882,6 +20985,30 @@ function createLensDiagnosticsTool(cacheManager2, getCwd, getLspService = getLSP
19882
20985
  const source = requestedSource ?? "session";
19883
20986
  const scope = requestedScope ?? (legacyMode === "delta" || legacyMode === void 0 ? source === "lsp" ? "paths" : "delta" : "workspace");
19884
20987
  const cwd = ctx.cwd ?? getCwd();
20988
+ const singlePath = readFilePath(params);
20989
+ if (singlePath.refusal) {
20990
+ return {
20991
+ content: [{ type: "text", text: singlePath.refusal }],
20992
+ isError: true,
20993
+ details: {}
20994
+ };
20995
+ }
20996
+ const pathsRead = readPathsArgument(params.paths, { cwd });
20997
+ if (pathsRead.refusal) {
20998
+ return {
20999
+ content: [{ type: "text", text: pathsRead.refusal }],
21000
+ isError: true,
21001
+ details: { mode: legacyMode ?? "delta", pathsError: true }
21002
+ };
21003
+ }
21004
+ params = {
21005
+ ...params,
21006
+ ...singlePath.path ? { path: singlePath.path } : {}
21007
+ };
21008
+ const pathEntries = singlePath.path ? [
21009
+ ...pathsRead.entries,
21010
+ ...readPathsArgument([singlePath.path], { cwd }).entries
21011
+ ] : pathsRead.entries;
19885
21012
  if (source === "lsp") {
19886
21013
  const lspParams = { ...params };
19887
21014
  delete lspParams.source;
@@ -19927,21 +21054,7 @@ function createLensDiagnosticsTool(cacheManager2, getCwd, getLspService = getLSP
19927
21054
  const maxProjectFiles = parsePositiveInt(params.maxProjectFiles);
19928
21055
  const maxLspFiles = parsePositiveInt(params.maxLspFiles);
19929
21056
  const includeGenerated = params.includeGenerated === true;
19930
- let pathsScope;
19931
- try {
19932
- pathsScope = resolvePathsScope(cwd, params.paths);
19933
- } catch (err) {
19934
- return {
19935
- content: [
19936
- {
19937
- type: "text",
19938
- text: err instanceof Error ? err.message : String(err)
19939
- }
19940
- ],
19941
- isError: true,
19942
- details: { mode, pathsError: true }
19943
- };
19944
- }
21057
+ const pathsScope = resolvePathsScope(pathEntries);
19945
21058
  const abortSignal = combineAbortSignals(signal, ctx.signal);
19946
21059
  await flushPending();
19947
21060
  const stalePaths = [];
@@ -20164,7 +21277,7 @@ function formatDeltaMode(cacheManager2, cwd, severity, pathsScope) {
20164
21277
  const reverifyIncompletePaths = new Set((actionableEntry?.data?.files ?? []).filter((file) => file.reVerifyIncomplete).map((file) => normalizeMapKey(file.filePath)));
20165
21278
  const actionable = actionableEntry?.data;
20166
21279
  const quality = qualityEntry?.data;
20167
- const policyMap = loadProjectRulePolicyMap(cwd);
21280
+ const policyMap = loadProjectRulePolicy(cwd);
20168
21281
  const projectDelta = filterDeltaReportDispositions(loadProjectDiagnosticsDeltaReport(cwd), cwd, policyMap);
20169
21282
  const includeFile = createScopedFileFilter(cwd, pathsScope);
20170
21283
  const visibleWarningFiles = (files) => (files ?? []).filter((file) => includeFile(file.filePath)).map((file) => ({
@@ -20273,13 +21386,9 @@ function createCurrentIgnoreFilter(cwd) {
20273
21386
  return () => true;
20274
21387
  }
20275
21388
  }
20276
- function resolvePathsScope(cwd, rawPaths) {
20277
- if (!Array.isArray(rawPaths) || rawPaths.length === 0)
21389
+ function resolvePathsScope(entries) {
21390
+ if (entries.length === 0)
20278
21391
  return void 0;
20279
- if (rawPaths.length > MAX_PATHS_ENTRIES) {
20280
- throw new Error(`paths has ${rawPaths.length} entries, over the ${MAX_PATHS_ENTRIES} cap. Narrow the list or omit paths to scan without a restriction.`);
20281
- }
20282
- const entries = rawPaths.filter((entry) => typeof entry === "string" && entry.trim().length > 0).map((entry) => resolveHostToolPath(entry, cwd));
20283
21392
  const missing = [];
20284
21393
  const fileEntries = [];
20285
21394
  const existingEntries = [];
@@ -20469,10 +21578,7 @@ function runnerRetirementDecision(diagnostic, filePath, authoritativeRunnerIds,
20469
21578
  }
20470
21579
  const realFilePath = realpathOrResolve(filePath);
20471
21580
  for (const entry of coverage) {
20472
- const root = entry.root;
20473
- const relative8 = path38.relative(root, realFilePath);
20474
- const underRoot = relative8 === "" || !relative8.startsWith("..") && !path38.isAbsolute(relative8);
20475
- if (!underRoot)
21581
+ if (!isWithinPathForm(realFilePath, entry.root))
20476
21582
  continue;
20477
21583
  if (entry.files.has(realFilePath)) {
20478
21584
  return "retire";
@@ -20875,7 +21981,7 @@ async function formatFullMode(cwd, severity, lspService, cacheManager2, options
20875
21981
  const unconfirmedLspResults = lspResults.filter((result2) => result2.timedOut || result2.error || mismatchedLspResults.has(result2));
20876
21982
  const authoritativeLspFiles = /* @__PURE__ */ new Set();
20877
21983
  const unreconciledFiles = /* @__PURE__ */ new Set();
20878
- const policyMap = loadProjectRulePolicyMap(cwd);
21984
+ const policyMap = loadProjectRulePolicy(cwd);
20879
21985
  for (const result2 of fullyCoveredLspResults) {
20880
21986
  const fileKey = normalizeMapKey(result2.filePath);
20881
21987
  try {
@@ -21224,7 +22330,7 @@ async function projectResolvedCwd(summary, cwd) {
21224
22330
  async function formatAllMode(cwd, severity, summaries = getFileDiagnosticSummaries(), detailOverrides = { mode: "all" }, staleDropped = 0, pathsScope, fullModeDisposition = { dropped: [], analyzers: 0, analyzersByLane: {} }, sessionEvidence) {
21225
22331
  const isFullMode = detailOverrides.mode === "full";
21226
22332
  const includeFile = createScopedFileFilter(cwd, pathsScope);
21227
- const policyMap = loadProjectRulePolicyMap(cwd);
22333
+ const policyMap = loadProjectRulePolicy(cwd);
21228
22334
  const inScope = (rows) => rows.reduce((n, d) => n + (matchesSeverity(d, severity) ? 1 : 0), 0);
21229
22335
  const sweepSuppressed = isFullMode ? inScope(fullModeDisposition.dropped) : 0;
21230
22336
  const lanes = [];
@@ -21433,7 +22539,7 @@ Summary (${visibleSummaries.length} files diagnosed this session):`,
21433
22539
  }
21434
22540
 
21435
22541
  // dist/tools/lsp-navigation.js
21436
- import * as nodeFs3 from "node:fs";
22542
+ import * as nodeFs4 from "node:fs";
21437
22543
  import * as path39 from "node:path";
21438
22544
  import { fileURLToPath as fileURLToPath2, pathToFileURL as pathToFileURL2 } from "node:url";
21439
22545
 
@@ -22248,7 +23354,7 @@ function classifyCodeActions(actions) {
22248
23354
  async function openFileBestEffort(lspService, filePath, waitForDiagnostics = false, excludeServerIds) {
22249
23355
  let fileContent;
22250
23356
  try {
22251
- fileContent = nodeFs3.readFileSync(filePath, "utf-8");
23357
+ fileContent = nodeFs4.readFileSync(filePath, "utf-8");
22252
23358
  } catch {
22253
23359
  return void 0;
22254
23360
  }
@@ -22290,6 +23396,8 @@ function createLspNavigationTool(getFlag, mutationDeps) {
22290
23396
  path: Type.Optional(Type.String({
22291
23397
  description: "Target file path."
22292
23398
  })),
23399
+ file: Type.Optional(Type.String({ description: "Alias for `path`." })),
23400
+ filePath: Type.Optional(Type.String({ description: "Alias for `path`." })),
22293
23401
  line: Type.Optional(Type.Number({
22294
23402
  description: "1-based line number."
22295
23403
  })),
@@ -22357,7 +23465,7 @@ function createLspNavigationTool(getFlag, mutationDeps) {
22357
23465
  if (payload.isError && requestedApply && mutationContext && ["rename", "rename_file", "executeCommand"].includes(meta.operation)) {
22358
23466
  recordLspMutationOutcome(mutationContext, "failed");
22359
23467
  }
22360
- const normalizedFilePath = meta.filePath.replace(/\\/g, "/");
23468
+ const normalizedFilePath = toPosix(meta.filePath);
22361
23469
  logLatency({
22362
23470
  type: "phase",
22363
23471
  phase: "lsp_navigation_result",
@@ -22416,6 +23524,20 @@ function createLspNavigationTool(getFlag, mutationDeps) {
22416
23524
  resultCount: 0
22417
23525
  });
22418
23526
  }
23527
+ const pathRead = readFilePath(params);
23528
+ if (pathRead.refusal) {
23529
+ return finalize({
23530
+ content: [{ type: "text", text: pathRead.refusal }],
23531
+ isError: true
23532
+ }, {
23533
+ operation: String(params.operation ?? "lsp"),
23534
+ filePath: "(workspace)",
23535
+ failureKind: "invalid_path",
23536
+ resultCount: 0
23537
+ });
23538
+ }
23539
+ if (pathRead.path)
23540
+ params = { ...params, path: pathRead.path };
22419
23541
  const { operation: rawOperation, path: rawPath, line, character, symbol, endLine, endCharacter, newName, newFilePath, apply, command, commandArguments, query, kinds, exactMatch, topLevelOnly, maxResults, callHierarchyItem } = params;
22420
23542
  const normalizedOperation = normalizeOperation(rawOperation);
22421
23543
  if (!isValidOperation(normalizedOperation)) {
@@ -22499,7 +23621,7 @@ function createLspNavigationTool(getFlag, mutationDeps) {
22499
23621
  let filePathIsDirectory = false;
22500
23622
  if (filePath) {
22501
23623
  try {
22502
- filePathIsDirectory = nodeFs3.statSync(filePath).isDirectory();
23624
+ filePathIsDirectory = nodeFs4.statSync(filePath).isDirectory();
22503
23625
  } catch {
22504
23626
  }
22505
23627
  }
@@ -22733,7 +23855,7 @@ Note: ${snapshotWithheldLine}` : ""}`
22733
23855
  "implementation",
22734
23856
  "prepareCallHierarchy"
22735
23857
  ].includes(operation);
22736
- const resolvedCharacter = needsPosition && filePath ? resolveSymbolColumn(nodeFs3.existsSync(filePath) ? nodeFs3.readFileSync(filePath, "utf-8") : "", line ?? 1, character, symbol) : {
23858
+ const resolvedCharacter = needsPosition && filePath ? resolveSymbolColumn(nodeFs4.existsSync(filePath) ? nodeFs4.readFileSync(filePath, "utf-8") : "", line ?? 1, character, symbol) : {
22737
23859
  character: character ?? 1,
22738
23860
  strategy: "explicit"
22739
23861
  };
@@ -22925,7 +24047,7 @@ Note: ${snapshotWithheldLine}` : ""}`
22925
24047
  }
22926
24048
  const stillEmpty = !result || Array.isArray(result) && result.length === 0;
22927
24049
  if (stillEmpty && needsFilePath && operation === "definition") {
22928
- const content = nodeFs3.readFileSync(filePath, "utf-8");
24050
+ const content = nodeFs4.readFileSync(filePath, "utf-8");
22929
24051
  const token = line && character ? tokenAtPosition(content, line, character) : void 0;
22930
24052
  if (token) {
22931
24053
  const docSymbols = await lspService.documentSymbol(filePath);
@@ -23094,13 +24216,16 @@ function classifyKey(key, declared) {
23094
24216
  }
23095
24217
  return equal.length > 0 ? { matches: equal, retargeted: [] } : { matches: suffix, retargeted };
23096
24218
  }
24219
+ function spellingsOf(key) {
24220
+ return FILE_PATH_KEYS.includes(key) ? FILE_PATH_KEYS : [key];
24221
+ }
23097
24222
  function findIgnoredArguments(schema, args) {
23098
24223
  const properties = schema.properties ?? {};
23099
24224
  const declared = Object.keys(properties);
23100
24225
  const unsentSuggestions = [];
23101
24226
  const ignored = Object.keys(args).filter((key) => !Object.hasOwn(properties, key)).map((key) => {
23102
24227
  const { matches, retargeted } = classifyKey(key, declared);
23103
- const unsent = matches.some((match) => Object.hasOwn(args, match)) ? void 0 : matches[0];
24228
+ const unsent = matches.some((match) => spellingsOf(match).some((spelling) => Object.hasOwn(args, spelling) && Object.hasOwn(properties, spelling))) ? void 0 : matches[0];
23104
24229
  if (unsent !== void 0 && !unsentSuggestions.some((entry) => entry.suggestion === unsent))
23105
24230
  unsentSuggestions.push({ key, suggestion: unsent });
23106
24231
  const suggestion = matches[0] ?? nearestDeclaredKey(key, declared.filter((name) => !retargeted.includes(name)));
@@ -23256,8 +24381,7 @@ function isWarmBuildStale() {
23256
24381
  return STALENESS_GATE.isStale();
23257
24382
  }
23258
24383
  function findRepoRoot(start) {
23259
- let dir = start;
23260
- for (let depth = 0; depth < 6; depth++) {
24384
+ for (const dir of walkUpDirs(start, { maxDepth: 6 })) {
23261
24385
  const pkgPath = path40.join(dir, "package.json");
23262
24386
  if (fs24.existsSync(pkgPath)) {
23263
24387
  try {
@@ -23267,10 +24391,6 @@ function findRepoRoot(start) {
23267
24391
  } catch {
23268
24392
  }
23269
24393
  }
23270
- const parent = path40.dirname(dir);
23271
- if (parent === dir)
23272
- break;
23273
- dir = parent;
23274
24394
  }
23275
24395
  return path40.resolve(start, "..", "..");
23276
24396
  }
@@ -23327,9 +24447,7 @@ function rejectForeignTurnCwd(route, cwd) {
23327
24447
  return message;
23328
24448
  }
23329
24449
  function isWithinServerWorkspace(cwd) {
23330
- const target = path40.resolve(cwd);
23331
- const rel = path40.relative(DEFAULT_CWD, target);
23332
- return !rel.startsWith("..") && !path40.isAbsolute(rel);
24450
+ return isUnderDir(path40.resolve(cwd), DEFAULT_CWD);
23333
24451
  }
23334
24452
  function startIpcServer() {
23335
24453
  unlinkStaleUnixSocket(IPC_PATH);
@@ -23525,10 +24643,12 @@ var ALL_TOOLS = [
23525
24643
  inputSchema: {
23526
24644
  type: "object",
23527
24645
  properties: {
23528
- file: {
24646
+ path: {
23529
24647
  type: "string",
23530
24648
  description: "Path to the file to analyze (absolute, or relative to cwd)."
23531
24649
  },
24650
+ file: { type: "string", description: "Alias for `path`." },
24651
+ filePath: { type: "string", description: "Alias for `path`." },
23532
24652
  cwd: {
23533
24653
  type: "string",
23534
24654
  description: "Project root. Defaults to the server's workspace."
@@ -23542,8 +24662,7 @@ var ALL_TOOLS = [
23542
24662
  type: "object",
23543
24663
  description: 'Optional pi-lens flag overrides for this run, e.g. {"no-lsp": true} to bench the non-LSP path.'
23544
24664
  }
23545
- },
23546
- required: ["file"]
24665
+ }
23547
24666
  }
23548
24667
  },
23549
24668
  {
@@ -23590,7 +24709,7 @@ var ALL_TOOLS = [
23590
24709
  },
23591
24710
  {
23592
24711
  name: "pilens_symbol_search",
23593
- description: "Find relevant files by ranked identifier search. On a cold cache, project_report and symbol_search return available: false with a retry hint and start a non-blocking background build; module_report degrades to outline-only with cache freshness explicit. Example: search `authenticate user` before pilens_module_report.",
24712
+ description: "Find relevant files by ranked identifier search. On a cold cache, project_report and symbol_search return available: false with a retry hint and start a non-blocking background build; module_report degrades to outline-only with cache freshness explicit. Example: search `authenticate user` before pilens_module_report. Read a listed line with offset=<line>, limit=1.",
23594
24713
  inputSchema: {
23595
24714
  type: "object",
23596
24715
  properties: {
@@ -23626,6 +24745,11 @@ var ALL_TOOLS = [
23626
24745
  type: "string",
23627
24746
  description: "File to report on (absolute or relative to cwd)."
23628
24747
  },
24748
+ path: {
24749
+ type: "string",
24750
+ description: "File to report on (the canonical spelling of `file`)."
24751
+ },
24752
+ filePath: { type: "string", description: "Alias for `path`." },
23629
24753
  cwd: { type: "string" },
23630
24754
  maxRefsPerSymbol: {
23631
24755
  type: "number",
@@ -23656,8 +24780,7 @@ var ALL_TOOLS = [
23656
24780
  type: "number",
23657
24781
  description: "Per-direction cap for call-graph relations (default 20)."
23658
24782
  }
23659
- },
23660
- required: ["file"]
24783
+ }
23661
24784
  }
23662
24785
  },
23663
24786
  {
@@ -23690,6 +24813,11 @@ var ALL_TOOLS = [
23690
24813
  type: "object",
23691
24814
  properties: {
23692
24815
  file: { type: "string", description: "File containing the symbol." },
24816
+ path: {
24817
+ type: "string",
24818
+ description: "File containing the symbol (the canonical spelling of `file`)."
24819
+ },
24820
+ filePath: { type: "string", description: "Alias for `path`." },
23693
24821
  symbol: {
23694
24822
  type: "string",
23695
24823
  description: "Exact symbol name to read, or a dotted `Class.method` to disambiguate a member."
@@ -23700,7 +24828,7 @@ var ALL_TOOLS = [
23700
24828
  },
23701
24829
  cwd: { type: "string" }
23702
24830
  },
23703
- required: ["file", "symbol"]
24831
+ required: ["symbol"]
23704
24832
  }
23705
24833
  },
23706
24834
  {
@@ -23713,6 +24841,11 @@ var ALL_TOOLS = [
23713
24841
  type: "string",
23714
24842
  description: "Absolute or workspace-relative path to the source file."
23715
24843
  },
24844
+ path: {
24845
+ type: "string",
24846
+ description: "Absolute or workspace-relative path to the source file (the canonical spelling of `file`)."
24847
+ },
24848
+ filePath: { type: "string", description: "Alias for `path`." },
23716
24849
  line: {
23717
24850
  type: "number",
23718
24851
  description: "1-based line number inside the desired symbol/callback."
@@ -23737,7 +24870,7 @@ var ALL_TOOLS = [
23737
24870
  description: "Maximum lines for onOversize=slice; defaults to maxLines, then 80."
23738
24871
  }
23739
24872
  },
23740
- required: ["file", "line"]
24873
+ required: ["line"]
23741
24874
  }
23742
24875
  },
23743
24876
  {
@@ -23755,7 +24888,12 @@ var ALL_TOOLS = [
23755
24888
  file: {
23756
24889
  type: "string",
23757
24890
  description: "Path to explain: adds the resolved language plus the per-server and per-runner selection decisions for it. Must resolve inside `cwd` (a sibling package in the same monorepo does not count) \u2014 a file outside it is rejected with the `cwd` it was measured against; re-query with `cwd` set to that file's own workspace instead."
23758
- }
24891
+ },
24892
+ path: {
24893
+ type: "string",
24894
+ description: "Path to explain (the canonical spelling of `file`)."
24895
+ },
24896
+ filePath: { type: "string", description: "Alias for `path`." }
23759
24897
  }
23760
24898
  }
23761
24899
  },
@@ -23883,10 +25021,13 @@ async function callTool(name, args) {
23883
25021
  return astGrepDumpCompatibilityResult(args, "mcp");
23884
25022
  }
23885
25023
  if (name === "pilens_analyze") {
23886
- const file = args.file;
23887
- if (typeof file !== "string" || file.length === 0) {
25024
+ const fileRead = readFilePath(args);
25025
+ if (fileRead.refusal)
25026
+ return { ...renderToolText(fileRead.refusal), isError: true };
25027
+ const file = fileRead.path;
25028
+ if (!file) {
23888
25029
  return {
23889
- ...renderToolText("pilens_analyze requires a 'file' string."),
25030
+ ...renderToolText("pilens_analyze requires a `path` string."),
23890
25031
  isError: true
23891
25032
  };
23892
25033
  }
@@ -23987,58 +25128,31 @@ ${outcome.output}`, {
23987
25128
  if (!query.trim())
23988
25129
  return renderToolText("Provide a non-empty `query`.");
23989
25130
  const cwd = typeof args.cwd === "string" ? args.cwd : DEFAULT_CWD;
23990
- const limit = typeof args.limit === "number" && Number.isFinite(args.limit) ? Math.max(1, Math.floor(args.limit)) : 20;
23991
- const paths = Array.isArray(args.paths) ? args.paths.filter((p) => typeof p === "string") : void 0;
25131
+ const pathsRead = readPathsArgument(args.paths, { cwd });
25132
+ if (pathsRead.refusal)
25133
+ return { ...renderToolText(pathsRead.refusal), isError: true };
25134
+ const limit = typeof args.limit === "number" && Number.isFinite(args.limit) ? args.limit : void 0;
25135
+ const paths = pathsRead.entries.length > 0 ? pathsRead.entries : void 0;
23992
25136
  const lang = typeof args.lang === "string" ? args.lang : void 0;
23993
- const { available, results, hint, unavailableReason, coverage, snapshotGeneratedAt } = await symbolSearch(query, cwd, limit, { paths, lang });
23994
- if (!available) {
23995
- return renderToolText(hint ?? "No word index for this workspace yet \u2014 run pilens_session_start first.", { available: false, query, hint, unavailableReason }, true);
23996
- }
23997
- const stalenessNote = graphStalenessNote(snapshotGeneratedAt, "Project snapshot");
23998
- if (results.length === 0) {
23999
- return renderToolText(`No files matched "${query}".` + (coverage ? `
24000
- Index covers ${coverage.files} files${coverage.truncated ? " (capped \u2014 results may be incomplete)" : ""}.` : "") + (stalenessNote ? `
24001
-
24002
- ${stalenessNote}` : ""), {
24003
- available: true,
24004
- query,
24005
- results: [],
24006
- coverage,
24007
- ...stalenessNote ? { staleness: stalenessNote } : {}
24008
- }, true);
25137
+ const result = await symbolSearch(query, cwd, limit, { paths, lang });
25138
+ if (!result.available) {
25139
+ return renderToolText(result.hint ?? "No word index for this workspace yet \u2014 run pilens_session_start first.");
24009
25140
  }
24010
- const lines = [
24011
- `Top ${results.length} file(s) for "${query}":`,
24012
- ...results.map((result, i) => ` ${i + 1}. ${path40.relative(cwd, result.file)} (score ${result.score.toFixed(2)}, ${result.hits} hit(s), line ${result.startLine})`),
24013
- ...stalenessNote ? ["", stalenessNote] : [],
24014
- ...coverage ? [
24015
- `Index covers ${coverage.files} files${coverage.truncated ? " (capped \u2014 results may be incomplete)" : ""}.`
24016
- ] : []
24017
- ];
24018
- return renderToolText(lines.join("\n"), {
24019
- query,
24020
- coverage,
24021
- results: results.map((result) => {
24022
- const relFile = path40.relative(cwd, result.file);
24023
- return {
24024
- file: relFile,
24025
- score: result.score,
24026
- hits: result.hits,
24027
- startLine: result.startLine,
24028
- endLine: result.endLine,
24029
- ...result.annotations ? { annotations: result.annotations } : {},
24030
- // #771: machine-actionable discovery-funnel hint, mirroring the
24031
- // pi-tool-surface's suggestedNext (tools/symbol-search.ts).
24032
- suggestedNext: { tool: "pilens_module_report", path: relFile }
24033
- };
24034
- }),
24035
- ...stalenessNote ? { staleness: stalenessNote } : {}
24036
- }, true);
25141
+ const stalenessNote = graphStalenessNote(result.snapshotGeneratedAt, "Project snapshot");
25142
+ return renderToolText(renderCompactSymbolSearch(result, {
25143
+ cwd,
25144
+ // exactOptionalPropertyTypes: an absent note is an absent key.
25145
+ ...stalenessNote ? { stalenessNote } : {},
25146
+ reportTool: "pilens_module_report"
25147
+ }));
24037
25148
  }
24038
25149
  if (name === "pilens_module_report") {
24039
- const file = typeof args.file === "string" ? args.file : "";
24040
- if (!file.trim())
24041
- return { ...renderToolText("Provide a `file`."), isError: true };
25150
+ const fileRead = readFilePath(args);
25151
+ if (fileRead.refusal)
25152
+ return { ...renderToolText(fileRead.refusal), isError: true };
25153
+ const file = fileRead.path;
25154
+ if (!file)
25155
+ return { ...renderToolText("Provide a `path`."), isError: true };
24042
25156
  const cwd = typeof args.cwd === "string" ? args.cwd : DEFAULT_CWD;
24043
25157
  const maxRefsPerSymbol = typeof args.maxRefsPerSymbol === "number" && Number.isFinite(args.maxRefsPerSymbol) ? Math.max(1, Math.floor(args.maxRefsPerSymbol)) : void 0;
24044
25158
  const blastRadius = args.blastRadius === true;
@@ -24113,10 +25227,13 @@ ${graphStaleness}` : "");
24113
25227
  return renderToolText(summary, graphStaleness ? { ...report, graphStalenessNote: graphStaleness } : report, true);
24114
25228
  }
24115
25229
  if (name === "pilens_read_symbol") {
24116
- const file = typeof args.file === "string" ? args.file : "";
25230
+ const fileRead = readFilePath(args);
25231
+ if (fileRead.refusal)
25232
+ return { ...renderToolText(fileRead.refusal), isError: true };
25233
+ const file = fileRead.path;
24117
25234
  const symbol = typeof args.symbol === "string" ? args.symbol : "";
24118
- if (!file.trim() || !symbol.trim()) {
24119
- return { ...renderToolText("Provide `file` and `symbol`."), isError: true };
25235
+ if (!file || !symbol.trim()) {
25236
+ return { ...renderToolText("Provide `path` and `symbol`."), isError: true };
24120
25237
  }
24121
25238
  const cwd = typeof args.cwd === "string" ? args.cwd : DEFAULT_CWD;
24122
25239
  const kind = typeof args.kind === "string" ? args.kind : void 0;
@@ -24147,11 +25264,14 @@ ${result.source ?? ""}`
24147
25264
  };
24148
25265
  }
24149
25266
  if (name === "pilens_read_enclosing") {
24150
- const file = typeof args.file === "string" ? args.file : "";
25267
+ const fileRead = readFilePath(args);
25268
+ if (fileRead.refusal)
25269
+ return { ...renderToolText(fileRead.refusal), isError: true };
25270
+ const file = fileRead.path;
24151
25271
  const line = typeof args.line === "number" ? args.line : Number.NaN;
24152
- if (!file.trim() || !Number.isFinite(line)) {
25272
+ if (!file || !Number.isFinite(line)) {
24153
25273
  return {
24154
- ...renderToolText("Provide `file` and a numeric `line`."),
25274
+ ...renderToolText("Provide `path` and a numeric `line`."),
24155
25275
  isError: true
24156
25276
  };
24157
25277
  }
@@ -24246,9 +25366,12 @@ ${result.source ?? ""}`
24246
25366
  }
24247
25367
  if (name === "pilens_effective_config") {
24248
25368
  const cwd = typeof args.cwd === "string" ? args.cwd : DEFAULT_CWD;
25369
+ const fileRead = readFilePath(args);
25370
+ if (fileRead.refusal)
25371
+ return { ...renderToolText(fileRead.refusal), isError: true };
24249
25372
  const view = await effectiveConfig({
24250
25373
  cwd,
24251
- ...typeof args.file === "string" ? { file: args.file } : {},
25374
+ ...fileRead.path ? { file: fileRead.path } : {},
24252
25375
  redact: true
24253
25376
  });
24254
25377
  const fileLines = view.file === void 0 ? [] : isEffectiveFileViewError(view.file) ? [`File: ${view.file.error}`] : [