pi-lens 4.4.3 → 4.4.5

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 (185) hide show
  1. package/CHANGELOG.md +721 -0
  2. package/README.md +25 -3
  3. package/config/dependency-cruiser-eager-allowlist.json +1 -0
  4. package/dist/chunk-22Y2BM7H.js +23 -0
  5. package/dist/{chunk-WU567RSC.js → chunk-27VWVB23.js} +16 -14
  6. package/dist/{chunk-FLKWCIZH.js → chunk-2FYKETQJ.js} +10 -6
  7. package/dist/{chunk-MQLUAEOC.js → chunk-2LDMXL2M.js} +2 -2
  8. package/dist/{chunk-YSZNHOBY.js → chunk-2SDHYHHO.js} +17 -17
  9. package/dist/chunk-2Y6OJRSI.js +38 -0
  10. package/dist/chunk-3SNDVPOR.js +507 -0
  11. package/dist/{chunk-EJIUXPBX.js → chunk-3WCEHYOI.js} +1 -1
  12. package/dist/chunk-44X7VIKR.js +73 -0
  13. package/dist/{chunk-Q7DUK4LX.js → chunk-4FHUGDKU.js} +16 -14
  14. package/dist/{chunk-H6MF6EVN.js → chunk-4ODSZ35Z.js} +1498 -534
  15. package/dist/{chunk-ZGDGW2V3.js → chunk-4U7GDSZQ.js} +2 -2
  16. package/dist/chunk-54NIOJJZ.js +25 -0
  17. package/dist/{chunk-ZWFS3OEF.js → chunk-5DKE4HGX.js} +38 -37
  18. package/dist/{chunk-VRZP76YM.js → chunk-5LRUKYFA.js} +34 -4
  19. package/dist/{chunk-QOBUHWHX.js → chunk-63NMUNYP.js} +12 -16
  20. package/dist/{chunk-VWCXW2E7.js → chunk-6XSESGWD.js} +13 -6
  21. package/dist/{chunk-QGQ5CCCG.js → chunk-72J27ICO.js} +2 -3
  22. package/dist/{chunk-CSHFH5IN.js → chunk-7FLRUH6B.js} +1 -1
  23. package/dist/chunk-7IYC4ENJ.js +297 -0
  24. package/dist/chunk-7WWQAW5P.js +30 -0
  25. package/dist/{chunk-EU63SDCG.js → chunk-7ZS7MC24.js} +885 -451
  26. package/dist/{chunk-KBG47GHP.js → chunk-AHWA4AKM.js} +18 -12
  27. package/dist/{chunk-FMSO6RDZ.js → chunk-AI3GP74G.js} +17 -19
  28. package/dist/chunk-APFJKOP6.js +67 -0
  29. package/dist/{chunk-RXCOMYPY.js → chunk-ASRAO7KG.js} +31 -33
  30. package/dist/{chunk-BW5KFIQC.js → chunk-AWQWXSW4.js} +1 -0
  31. package/dist/{chunk-QILIYSJF.js → chunk-CG5V25HX.js} +1 -1
  32. package/dist/chunk-CKEQFGLT.js +32 -0
  33. package/dist/{chunk-RPLINGVB.js → chunk-COOUUC5W.js} +6 -6
  34. package/dist/{chunk-GBPP5P7X.js → chunk-CPZ5JJW6.js} +4 -4
  35. package/dist/{chunk-OCAGUNBC.js → chunk-DS2USX5G.js} +13 -15
  36. package/dist/chunk-EA2ZRG44.js +27 -0
  37. package/dist/{chunk-ZHFZWTZV.js → chunk-EDMLIW6W.js} +13 -14
  38. package/dist/{chunk-2EECBNC5.js → chunk-EIKRZ32J.js} +75 -0
  39. package/dist/chunk-EKNWOL2I.js +27 -0
  40. package/dist/{chunk-CMMHNUZ2.js → chunk-ELZRSR5N.js} +65 -43
  41. package/dist/{chunk-BKE7E7TC.js → chunk-EN5AM7PX.js} +11 -12
  42. package/dist/{chunk-N2H3ZPZY.js → chunk-EWXXLS26.js} +227 -24
  43. package/dist/chunk-EX4EXBW7.js +37 -0
  44. package/dist/{chunk-YYOIQFRS.js → chunk-EXVXBSGN.js} +130 -52
  45. package/dist/{chunk-6GFRNVYR.js → chunk-F7BO6FWH.js} +12 -13
  46. package/dist/chunk-FEDWAYDS.js +2485 -0
  47. package/dist/{chunk-JAU72XNY.js → chunk-FWZRGGGY.js} +73 -9
  48. package/dist/{chunk-GXW6K4YJ.js → chunk-G224FADB.js} +1 -1
  49. package/dist/chunk-G5UCJFT7.js +26 -0
  50. package/dist/{chunk-67WMNWEE.js → chunk-GLW3YDZZ.js} +22 -13
  51. package/dist/{chunk-724UL2TJ.js → chunk-GTDSYEA2.js} +72 -39
  52. package/dist/{chunk-PHDMFAKM.js → chunk-GYRZ72R4.js} +10 -4
  53. package/dist/chunk-HYVXA3BB.js +49 -0
  54. package/dist/{chunk-SAEFPSB6.js → chunk-IEBJF3PN.js} +23 -15
  55. package/dist/chunk-IJYGIDF4.js +186 -0
  56. package/dist/{chunk-ACXEQZOU.js → chunk-IL7K66ZQ.js} +101 -109
  57. package/dist/{chunk-ZXYDQ3TZ.js → chunk-JWOVP5BL.js} +50 -19
  58. package/dist/{chunk-OXXKQCSV.js → chunk-K2GUZ4DN.js} +4 -4
  59. package/dist/{chunk-AW7R2GWG.js → chunk-K4SZB56V.js} +39 -39
  60. package/dist/{chunk-WOA4LN2R.js → chunk-KCBRHV5E.js} +3 -3
  61. package/dist/{chunk-3W7IEVVL.js → chunk-KFXCL4OV.js} +47 -45
  62. package/dist/{chunk-2BBLFX75.js → chunk-KJJAVH3X.js} +81 -15
  63. package/dist/{chunk-VCHXCQFG.js → chunk-KPVLQHCZ.js} +4 -6
  64. package/dist/{chunk-P7266HLM.js → chunk-KX56K73G.js} +10 -13
  65. package/dist/{chunk-VSSBEUFT.js → chunk-LMCTHJ2H.js} +19 -19
  66. package/dist/{chunk-IBGIOBEE.js → chunk-MEFLGBCS.js} +69 -8
  67. package/dist/{chunk-TYM6OUIT.js → chunk-MKPCELNI.js} +17 -17
  68. package/dist/{chunk-XTMJ7XDT.js → chunk-N3PLNNCW.js} +1 -1
  69. package/dist/chunk-N5FBM25N.js +22 -0
  70. package/dist/{chunk-CHOW74WE.js → chunk-NFNVDDGB.js} +7 -12
  71. package/dist/{chunk-52FUZI6K.js → chunk-NLIVE7L6.js} +2 -30
  72. package/dist/{chunk-SS36ZX4J.js → chunk-OMJ3OFBJ.js} +6 -6
  73. package/dist/{chunk-4W4VLAPJ.js → chunk-OZNCKLOX.js} +13 -14
  74. package/dist/chunk-P5XUGPIX.js +31 -0
  75. package/dist/{chunk-5UCAH366.js → chunk-PJXNTPB2.js} +253 -33
  76. package/dist/chunk-PKOXJIVT.js +88 -0
  77. package/dist/{chunk-6C7JWPCP.js → chunk-PP2A5V2T.js} +27 -26
  78. package/dist/{chunk-L3BLXZG7.js → chunk-Q42LJANT.js} +31 -70
  79. package/dist/{chunk-AB3YYG6N.js → chunk-Q4BKKOVC.js} +8 -8
  80. package/dist/{chunk-3EFKIGZN.js → chunk-QT66NEYN.js} +4 -4
  81. package/dist/{chunk-3VPVG5SU.js → chunk-RCHO5W7M.js} +19 -18
  82. package/dist/{chunk-77M37OKR.js → chunk-RG3MXTRI.js} +7 -7
  83. package/dist/chunk-RG7OODGM.js +57 -0
  84. package/dist/{chunk-T6CPIZNT.js → chunk-RU34BA4D.js} +44 -39
  85. package/dist/{chunk-JMYYOTQG.js → chunk-S26LC76R.js} +13 -1
  86. package/dist/{chunk-5NGR67U5.js → chunk-S55TEC7I.js} +33 -5
  87. package/dist/{chunk-M6HSLBWY.js → chunk-SJHC3BCZ.js} +7956 -8047
  88. package/dist/{chunk-XCJN5IJU.js → chunk-SNEUMLM7.js} +4 -4
  89. package/dist/{chunk-UZ3TUTRV.js → chunk-T4NGVFYI.js} +2 -2
  90. package/dist/{chunk-2VUQMUMT.js → chunk-THEXI2QO.js} +49 -43
  91. package/dist/{chunk-R3PCY3YS.js → chunk-TL2TCJYL.js} +15 -16
  92. package/dist/{chunk-C34ZXZ7O.js → chunk-TPYYEDP5.js} +838 -352
  93. package/dist/{chunk-AOHZU2BM.js → chunk-TVZRLTG6.js} +8 -1
  94. package/dist/{chunk-XMSXXAHW.js → chunk-UCVMSOXF.js} +2 -2
  95. package/dist/chunk-UL5SXQVX.js +32 -0
  96. package/dist/{chunk-GAEGEPOC.js → chunk-UO66IMVP.js} +2 -2
  97. package/dist/{chunk-N3X6Q4YT.js → chunk-UVY4TOJH.js} +3 -3
  98. package/dist/{chunk-2CD5RS6M.js → chunk-VIDEKABZ.js} +23 -2
  99. package/dist/{chunk-JSQFTSC6.js → chunk-VITFDI3O.js} +13 -14
  100. package/dist/{chunk-YIUAVF7E.js → chunk-VUAVE3QC.js} +42 -42
  101. package/dist/{chunk-QOZXJ4NA.js → chunk-WUY4BZEP.js} +21 -20
  102. package/dist/{chunk-VCO24T4L.js → chunk-X3UTCXAA.js} +43 -53
  103. package/dist/chunk-XHDBJODR.js +45 -0
  104. package/dist/{chunk-MXGY6KPT.js → chunk-XHLK33VM.js} +28 -21
  105. package/dist/{chunk-RWWYJ623.js → chunk-XI34NWDI.js} +2 -2
  106. package/dist/{chunk-QQNQ7SJW.js → chunk-XWFIHYCH.js} +12 -4
  107. package/dist/{chunk-6SDEP3AJ.js → chunk-Y2TPADJR.js} +10 -11
  108. package/dist/{chunk-MRXKYPCS.js → chunk-Y5KTA2OB.js} +17 -17
  109. package/dist/{chunk-7DYBLXYA.js → chunk-YKVDBNPO.js} +11 -5
  110. package/dist/{chunk-2B73ZPOK.js → chunk-YSDPVDFC.js} +3 -3
  111. package/dist/chunk-YWNO5Q4R.js +44 -0
  112. package/dist/{chunk-QHJ6DQ2R.js → chunk-YWWG4AQA.js} +165 -32
  113. package/dist/{chunk-3JNKMP3B.js → chunk-YXDCRUKQ.js} +4 -4
  114. package/dist/{chunk-UXGETRP4.js → chunk-YXGRRORB.js} +16 -17
  115. package/dist/{chunk-SQ4TVJBR.js → chunk-ZAPSUBLU.js} +13 -7
  116. package/dist/{chunk-76MWC2K6.js → chunk-ZPJM7DID.js} +90 -97
  117. package/dist/{chunk-XVF2VVXP.js → chunk-ZSUX7KEM.js} +16 -15
  118. package/dist/index.js +31038 -20893
  119. package/dist/mcp/analyze-cli.js +11 -11
  120. package/dist/mcp/cli.js +47 -43
  121. package/dist/mcp/server.js +2188 -906
  122. package/dist/mcp/worker.js +66 -63
  123. package/dist/probes/installer.js +21 -23
  124. package/dist/workers/project-snapshot-persist-worker.js +28 -9
  125. package/dist/workers/review-graph-persist-worker.js +1 -1
  126. package/docs/adr/0010-trace-validation-session-lifecycle.md +390 -0
  127. package/docs/adr/README.md +1 -0
  128. package/docs/ast-grep_rules_catalog.md +5 -3
  129. package/docs/configuration.md +20 -0
  130. package/docs/engineering-principles.md +44 -0
  131. package/docs/environment-variables.md +20 -0
  132. package/docs/features.md +16 -1
  133. package/docs/globalconfig.md +37 -8
  134. package/docs/lsp-capability-matrix.md +105 -12
  135. package/docs/lsp-idle-eviction.md +44 -36
  136. package/docs/pi-lens-fixer.md +139 -14
  137. package/docs/pi-lens-investigator.md +14 -0
  138. package/docs/pi-lens-merge-policy.md +120 -17
  139. package/docs/pi-lens-monitor.md +71 -9
  140. package/docs/pi-lens-retro.md +6 -3
  141. package/docs/pi-lens-reviewer.md +160 -5
  142. package/docs/pi-lens-subagent.md +29 -14
  143. package/docs/release-qa-baseline.md +21 -7
  144. package/docs/servercapabilities.md +53 -63
  145. package/docs/settings.md +9 -5
  146. package/docs/subagent-compat.md +1 -1
  147. package/docs/usage.md +1 -0
  148. package/package.json +9 -5
  149. package/rules/ast-grep-rules/rule-tests/no-return-value-in-generator-test.yml +17 -0
  150. package/rules/ast-grep-rules/rule-tests/no-sql-in-code-execute-js-test.yml +86 -0
  151. package/rules/ast-grep-rules/rule-tests/no-sql-in-code-execute-test.yml +86 -0
  152. package/rules/ast-grep-rules/rule-tests/unchecked-numeric-parse-python-test.yml +15 -0
  153. package/rules/ast-grep-rules/rules/no-return-value-in-generator.yml +9 -4
  154. package/rules/ast-grep-rules/rules/no-sql-in-code-execute-js.yml +119 -0
  155. package/rules/ast-grep-rules/rules/no-sql-in-code-execute.yml +119 -0
  156. package/rules/ast-grep-rules/rules/unchecked-numeric-parse-python.yml +13 -2
  157. package/rules/rule-catalog.json +25 -1
  158. package/scripts/analyze-pi-lens-logs.mjs +15 -5
  159. package/scripts/download-grammars.js +40 -7
  160. package/scripts/lib/is-main-module.mjs +27 -0
  161. package/scripts/lib/latency-log-phases.mjs +95 -0
  162. package/scripts/lib/scratch-home-env.mjs +21 -0
  163. package/scripts/rpc-load-check.mjs +568 -81
  164. package/scripts/warm-loader-cache.mjs +2 -5
  165. package/dist/chunk-23WOO7TX.js +0 -23
  166. package/dist/chunk-3YN6V5TV.js +0 -85
  167. package/dist/chunk-466Z26MG.js +0 -30
  168. package/dist/chunk-4UNXBNE2.js +0 -24
  169. package/dist/chunk-6STA6Z7I.js +0 -47
  170. package/dist/chunk-ABBOA7UD.js +0 -157
  171. package/dist/chunk-BRGDSBJE.js +0 -28
  172. package/dist/chunk-EC47DWFA.js +0 -56
  173. package/dist/chunk-FCSOVF55.js +0 -273
  174. package/dist/chunk-IZSHAIJ7.js +0 -26
  175. package/dist/chunk-KDERNTCQ.js +0 -28
  176. package/dist/chunk-KSX3TXSZ.js +0 -69
  177. package/dist/chunk-LOP6GRPH.js +0 -31
  178. package/dist/chunk-PNQDPDRC.js +0 -184
  179. package/dist/chunk-UOPVJQ4N.js +0 -103
  180. package/dist/chunk-XAGLWMJ4.js +0 -51
  181. package/dist/chunk-XIJZVPD5.js +0 -39
  182. package/dist/chunk-Z3CCVDUB.js +0 -76
  183. package/dist/chunk-Z527N6YQ.js +0 -28
  184. package/dist/chunk-ZANLILYD.js +0 -79
  185. /package/dist/{chunk-FC4RP4I2.js → chunk-6HWVI6MI.js} +0 -0
@@ -0,0 +1,2485 @@
1
+ import { createRequire as __pilensCreateRequire } from "node:module"; const require = __pilensCreateRequire(import.meta.url);
2
+ import {
3
+ buildModuleGraph
4
+ } from "./chunk-CPZ5JJW6.js";
5
+ import {
6
+ aliasedImportTargets,
7
+ referencedProjectImportTarget
8
+ } from "./chunk-7IYC4ENJ.js";
9
+ import {
10
+ getSharedTreeSitterClient,
11
+ loadWebTreeSitter,
12
+ logTreeSitterDiagnostic,
13
+ resolveTreeSitterLanguage,
14
+ wasmQueryInput
15
+ } from "./chunk-YWWG4AQA.js";
16
+ import {
17
+ EXTENSION_TO_GRAMMAR,
18
+ KIND_TO_GRAMMAR
19
+ } from "./chunk-GTDSYEA2.js";
20
+ import {
21
+ HOOK_WALL_BUDGET_MS
22
+ } from "./chunk-CKEQFGLT.js";
23
+ import {
24
+ bounded
25
+ } from "./chunk-NLIVE7L6.js";
26
+ import {
27
+ hashContentBytes,
28
+ toRunnerDisplayPath
29
+ } from "./chunk-APFJKOP6.js";
30
+ import {
31
+ loadPiLensGlobalConfig
32
+ } from "./chunk-TPYYEDP5.js";
33
+ import {
34
+ isFileKind
35
+ } from "./chunk-GYRZ72R4.js";
36
+ import {
37
+ isDeclarationFile
38
+ } from "./chunk-KJJAVH3X.js";
39
+ import {
40
+ incrementDegradationCount,
41
+ recordDegradationOnce
42
+ } from "./chunk-FWZRGGGY.js";
43
+ import {
44
+ freshnessFromMtime
45
+ } from "./chunk-S26LC76R.js";
46
+ import {
47
+ toPositiveFinite
48
+ } from "./chunk-TVZRLTG6.js";
49
+ import {
50
+ BoundedFifoMap,
51
+ BoundedLruCache,
52
+ isUnderDir,
53
+ normalizeEphemeralMapKey,
54
+ normalizeMapKey
55
+ } from "./chunk-EWXXLS26.js";
56
+
57
+ // dist/clients/blocker-freshness.js
58
+ import * as fs4 from "node:fs";
59
+ import * as nodePath from "node:path";
60
+
61
+ // dist/clients/lsp/implicit-scope.js
62
+ import * as fs from "node:fs";
63
+ import * as path from "node:path";
64
+
65
+ // dist/clients/deps/ast-grep-napi.js
66
+ import { createRequire } from "node:module";
67
+ import { pathToFileURL } from "node:url";
68
+ var _require = createRequire(import.meta.url);
69
+ function loadAstGrepNapi() {
70
+ try {
71
+ const entry = _require.resolve("@ast-grep/napi");
72
+ return import(pathToFileURL(entry).href);
73
+ } catch {
74
+ return import("@ast-grep/napi");
75
+ }
76
+ }
77
+ function loadAstGrepNapiSync() {
78
+ try {
79
+ return _require("@ast-grep/napi");
80
+ } catch {
81
+ return void 0;
82
+ }
83
+ }
84
+
85
+ // dist/clients/runtime-config.js
86
+ var _runnerTimeoutFloorCache;
87
+ function getRunnerTimeoutFloorMs() {
88
+ if (_runnerTimeoutFloorCache !== void 0)
89
+ return _runnerTimeoutFloorCache;
90
+ const config = loadPiLensGlobalConfig();
91
+ const configFloor = toPositiveFinite(config?.dispatch?.runnerTimeoutFloorMs);
92
+ const envFloor = toPositiveFinite(process.env.PI_LENS_RUNNER_TIMEOUT_FLOOR_MS);
93
+ _runnerTimeoutFloorCache = Math.max(configFloor, envFloor, 0);
94
+ return _runnerTimeoutFloorCache;
95
+ }
96
+ var RUNTIME_CONFIG = {
97
+ pipeline: {
98
+ lspMaxFileBytes: 2 * 1024 * 1024,
99
+ lspMaxFileLines: 5e3,
100
+ cascadeMaxFiles: 5,
101
+ cascadeMaxDiagnosticsPerFile: 20,
102
+ // Hard cap on how long the pipeline will wait for an LSP client to spawn.
103
+ // Keeps tool_result from blocking the TUI during cold LSP start (e.g.
104
+ // pyright workspace indexing). The LSP server continues spawning in the
105
+ // background; subsequent edits get full diagnostics once it is ready.
106
+ lspSpawnBudgetMs: 5e3
107
+ },
108
+ dispatch: {
109
+ runnerTimeoutMs: 3e4
110
+ },
111
+ crashNotice: {
112
+ alwaysShowFirstN: 2,
113
+ showEveryNth: 5
114
+ },
115
+ reviewGraph: {
116
+ // Deprecated (#776): no longer read by `review-graph/builder.ts`, which
117
+ // now derives its fallback from `project-scale.ts`'s `maxProjectFiles`
118
+ // knob (reproducing this same 1,000 default at the default base). Left
119
+ // in place only in case an external caller still reads the constant.
120
+ maxFiles: 1e3,
121
+ maxFileBytes: 1 * 1024 * 1024
122
+ },
123
+ turnEnd: {
124
+ maxLines: 20,
125
+ maxChars: 1e3
126
+ }
127
+ };
128
+
129
+ // dist/clients/lsp/content-scan.js
130
+ function walkLfLines(content) {
131
+ let lfNewlineCount = 0;
132
+ let lastStart = 0;
133
+ for (let i = content.indexOf("\n"); i !== -1; i = content.indexOf("\n", i + 1)) {
134
+ lfNewlineCount++;
135
+ lastStart = i + 1;
136
+ }
137
+ return { lfNewlineCount, lastStart };
138
+ }
139
+ var lastNewlineWalk;
140
+ function countLfNewlines(content) {
141
+ const lfNewlineCount = walkLfLines(content).lfNewlineCount;
142
+ lastNewlineWalk = { content, lfNewlineCount };
143
+ return lfNewlineCount;
144
+ }
145
+ function reusedNewlineCount(content) {
146
+ return lastNewlineWalk?.content === content ? lastNewlineWalk.lfNewlineCount : void 0;
147
+ }
148
+ function lastLfLineStart(content) {
149
+ const lastNewline = content.lastIndexOf("\n");
150
+ return lastNewline === -1 ? 0 : lastNewline + 1;
151
+ }
152
+ function scanDocumentContent(content) {
153
+ const reused = reusedNewlineCount(content);
154
+ if (content.indexOf("\r") === -1) {
155
+ if (reused !== void 0) {
156
+ return {
157
+ lfNewlineCount: reused,
158
+ lastLine: { index: reused, start: lastLfLineStart(content) }
159
+ };
160
+ }
161
+ const { lfNewlineCount: lfNewlineCount2, lastStart } = walkLfLines(content);
162
+ return {
163
+ lfNewlineCount: lfNewlineCount2,
164
+ lastLine: { index: lfNewlineCount2, start: lastStart }
165
+ };
166
+ }
167
+ const lfNewlineCount = reused ?? walkLfLines(content).lfNewlineCount;
168
+ let index = 0;
169
+ let start = 0;
170
+ for (let i = 0; i < content.length; i++) {
171
+ const code = content.charCodeAt(i);
172
+ if (code !== 10 && code !== 13)
173
+ continue;
174
+ if (code === 13 && content.charCodeAt(i + 1) === 10)
175
+ i++;
176
+ index++;
177
+ start = i + 1;
178
+ }
179
+ return { lfNewlineCount, lastLine: { index, start } };
180
+ }
181
+ function lineTextAt(content, line) {
182
+ if (!Number.isInteger(line) || line < 0)
183
+ return "";
184
+ let start = 0;
185
+ for (let current = 0; current < line; current++) {
186
+ const next = content.indexOf("\n", start);
187
+ if (next === -1)
188
+ return "";
189
+ start = next + 1;
190
+ }
191
+ const end = content.indexOf("\n", start);
192
+ return end === -1 ? content.slice(start) : content.slice(start, end);
193
+ }
194
+
195
+ // dist/clients/lsp/content-limits.js
196
+ var LSP_MAX_FILE_BYTES = RUNTIME_CONFIG.pipeline.lspMaxFileBytes;
197
+ var LSP_MAX_FILE_LINES = RUNTIME_CONFIG.pipeline.lspMaxFileLines;
198
+ function exceedsLspSyncLimits(content) {
199
+ const sizeBytes = Buffer.byteLength(content, "utf-8");
200
+ if (sizeBytes > LSP_MAX_FILE_BYTES) {
201
+ return {
202
+ tooLarge: true,
203
+ reason: `${sizeBytes} bytes > ${LSP_MAX_FILE_BYTES} limit`
204
+ };
205
+ }
206
+ const lineCount = countLfNewlines(content) + 1;
207
+ if (lineCount > LSP_MAX_FILE_LINES) {
208
+ return {
209
+ tooLarge: true,
210
+ reason: `${lineCount} lines > ${LSP_MAX_FILE_LINES} limit`
211
+ };
212
+ }
213
+ return { tooLarge: false, reason: "" };
214
+ }
215
+
216
+ // dist/clients/lsp/implicit-scope.js
217
+ function isGoSourceFile(filePath) {
218
+ return path.extname(filePath).toLowerCase() === ".go";
219
+ }
220
+ function seesJsTsGlobalScope(filePath) {
221
+ return isFileKind(filePath, "jsts");
222
+ }
223
+ function inOneGoPackage(a, b) {
224
+ return isGoSourceFile(a) && isGoSourceFile(b) && path.posix.dirname(a) === path.posix.dirname(b);
225
+ }
226
+ function recordUnknownRole(filePath, cause, err) {
227
+ incrementDegradationCount({
228
+ kind: "lsp-implicit-scope-unknown",
229
+ subject: cause,
230
+ reason: `${cause}: ${filePath}${err === void 0 ? "" : ` (${err instanceof Error ? err.message : String(err)})`} \u2014 unresolved, so the diagnostics cache refuses its entry and the blocker sweep and the cascade see no role for it`,
231
+ metadata: {
232
+ file: filePath,
233
+ cause,
234
+ ...err === void 0 ? {} : { err: err instanceof Error ? err.message : String(err) }
235
+ }
236
+ });
237
+ }
238
+ function goPackageFiles(dir) {
239
+ let entries;
240
+ try {
241
+ entries = fs.readdirSync(dir, { withFileTypes: true });
242
+ } catch (err) {
243
+ recordUnknownRole(dir, "unreadable-go-dir", err);
244
+ return void 0;
245
+ }
246
+ return entries.flatMap((entry) => entry.isFile() && isGoSourceFile(entry.name) ? [path.join(dir, entry.name)] : []);
247
+ }
248
+ function implicitScopeOf(filePath, feeds = feedsJsTsGlobalScope) {
249
+ if (isGoSourceFile(filePath)) {
250
+ return (other) => other !== filePath && inOneGoPackage(filePath, other);
251
+ }
252
+ if (seesJsTsGlobalScope(filePath)) {
253
+ return (other) => other !== filePath && feeds(other);
254
+ }
255
+ return void 0;
256
+ }
257
+ function goPackageChangedAt(dir) {
258
+ try {
259
+ let changedAt = fs.statSync(dir).mtimeMs;
260
+ for (const peer of goPackageFiles(dir) ?? []) {
261
+ changedAt = Math.max(changedAt, fs.statSync(peer).mtimeMs);
262
+ }
263
+ return changedAt;
264
+ } catch (err) {
265
+ recordUnknownRole(dir, "unreadable-mtime", err);
266
+ return void 0;
267
+ }
268
+ }
269
+ var GO_HEADER_BYTES = 8 * 1024;
270
+ var KNOWN_GOOS = new Set("aix android darwin dragonfly freebsd hurd illumos ios js linux netbsd openbsd plan9 solaris wasip1 windows zos".split(" "));
271
+ var KNOWN_GOARCH = new Set("386 amd64 arm arm64 loong64 mips mips64 mips64le mipsle ppc64 ppc64le riscv64 s390x wasm".split(" "));
272
+ var GOOS_BY_PLATFORM = {
273
+ win32: "windows",
274
+ sunos: "solaris"
275
+ };
276
+ var GOARCH_BY_ARCH = { x64: "amd64", ia32: "386" };
277
+ var UNIX_GOOS = new Set("aix android darwin dragonfly freebsd hurd illumos ios linux netbsd openbsd solaris".split(" "));
278
+ function hostSatisfiesGoTag(tag) {
279
+ const goos = process.env.GOOS || GOOS_BY_PLATFORM[process.platform] || process.platform;
280
+ const goarch = process.env.GOARCH || GOARCH_BY_ARCH[process.arch] || process.arch;
281
+ return tag === goos || tag === goarch || tag === "unix" && UNIX_GOOS.has(goos);
282
+ }
283
+ function goBuildExcludesHost(filePath, header) {
284
+ const parts = path.basename(filePath, ".go").replace(/_test$/, "").split("_");
285
+ const last = parts.at(-1) ?? "";
286
+ const prev = parts.length > 2 ? parts.at(-2) ?? "" : "";
287
+ if (parts.length > 1 && KNOWN_GOARCH.has(last)) {
288
+ if (!hostSatisfiesGoTag(last))
289
+ return true;
290
+ if (KNOWN_GOOS.has(prev) && !hostSatisfiesGoTag(prev))
291
+ return true;
292
+ } else if (parts.length > 1 && KNOWN_GOOS.has(last) && !hostSatisfiesGoTag(last)) {
293
+ return true;
294
+ }
295
+ const line = /^\/\/go:build[ \t](.*)$/m.exec(header);
296
+ if (!line)
297
+ return /^\/\/[ \t]*\+build[ \t]/m.test(header);
298
+ const term = /^\s*(!?)([\w.]+)\s*$/.exec(line[1]);
299
+ const tag = term?.[2] ?? "";
300
+ if (!(KNOWN_GOOS.has(tag) || KNOWN_GOARCH.has(tag) || tag === "unix"))
301
+ return true;
302
+ return hostSatisfiesGoTag(tag) === (term?.[1] === "!");
303
+ }
304
+ function goHeaderOf(filePath) {
305
+ let fd;
306
+ try {
307
+ fd = fs.openSync(filePath, "r");
308
+ const buffer = Buffer.alloc(GO_HEADER_BYTES);
309
+ const read = fs.readSync(fd, buffer, 0, GO_HEADER_BYTES, 0);
310
+ return buffer.toString("utf8", 0, read);
311
+ } catch (err) {
312
+ recordUnknownRole(filePath, "unreadable-go-peer", err);
313
+ return void 0;
314
+ } finally {
315
+ if (fd !== void 0)
316
+ fs.closeSync(fd);
317
+ }
318
+ }
319
+ function goPackageClauseOf(header) {
320
+ const code = header.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/\/\/[^\n]*/g, "");
321
+ return /^\s*package\s+([\p{L}_][\p{L}\p{N}_]*)/mu.exec(code)?.[1];
322
+ }
323
+ function goPackagePeersOf(filePath) {
324
+ const inScope = isGoSourceFile(filePath) ? implicitScopeOf(filePath) : void 0;
325
+ const ownHeader = inScope && goHeaderOf(filePath);
326
+ const clause = ownHeader ? goPackageClauseOf(ownHeader) : void 0;
327
+ if (!inScope || !clause)
328
+ return void 0;
329
+ const testFile = isGoTestFile(filePath);
330
+ return (peer) => {
331
+ if (!inScope(peer) || isGoTestFile(peer) && !testFile)
332
+ return false;
333
+ const header = goHeaderOf(peer);
334
+ return header !== void 0 && goPackageClauseOf(header) === clause && !goBuildExcludesHost(peer, header);
335
+ };
336
+ }
337
+ function isGoTestFile(filePath) {
338
+ return filePath.toLowerCase().endsWith("_test.go");
339
+ }
340
+ function probeFor(filePath) {
341
+ switch (path.extname(filePath).toLowerCase()) {
342
+ case ".ts":
343
+ case ".tsx":
344
+ return "ts-script-or-ambient";
345
+ // ES and CommonJS module extensions: never a script, but a TS one can
346
+ // still hold `declare global`.
347
+ case ".mts":
348
+ case ".cts":
349
+ return "ambient";
350
+ case ".js":
351
+ case ".jsx":
352
+ return "js-script";
353
+ default:
354
+ return void 0;
355
+ }
356
+ }
357
+ function globalScopeRoleByName(filePath) {
358
+ if (isDeclarationFile(filePath))
359
+ return "feeds";
360
+ return probeFor(filePath) ? void 0 : "none";
361
+ }
362
+ var MODULE_LINE = /^[ \t]*(?:import|export)\b/m;
363
+ var AMBIENT_DECLARATION = /\bdeclare\s+(?:global|module)\b/;
364
+ function globalScopeRoleByText(content) {
365
+ return MODULE_LINE.test(content) && !AMBIENT_DECLARATION.test(content) ? "none" : void 0;
366
+ }
367
+ function classifyJsTsGlobalScope(filePath) {
368
+ const byName = globalScopeRoleByName(filePath);
369
+ if (byName)
370
+ return byName;
371
+ const probe = probeFor(filePath);
372
+ let content;
373
+ try {
374
+ content = fs.readFileSync(filePath, "utf8");
375
+ } catch (err) {
376
+ recordUnknownRole(filePath, "unreadable-file", err);
377
+ return "unknown";
378
+ }
379
+ if (exceedsLspSyncLimits(content).tooLarge)
380
+ return "unknown";
381
+ const napi = loadAstGrepNapiSync();
382
+ if (!napi) {
383
+ recordDegradationOnce({
384
+ kind: "ast-grep-napi-unavailable",
385
+ subject: "implicit-scope",
386
+ reason: "native addon failed to load; every created JS/TS file counts as feeding the global scope in the diagnostics cache, and its role is unknown to the blocker sweep and the cascade"
387
+ });
388
+ return "unknown";
389
+ }
390
+ const lang = probe === "js-script" ? napi.Lang.JavaScript : path.extname(filePath).toLowerCase() === ".tsx" ? napi.Lang.Tsx : napi.Lang.TypeScript;
391
+ let root;
392
+ try {
393
+ root = napi.parse(lang, content).root();
394
+ } catch (err) {
395
+ recordUnknownRole(filePath, "parse-failed", err);
396
+ return "unknown";
397
+ }
398
+ let isModule = false;
399
+ for (const child of root.children()) {
400
+ const kind = child.kind();
401
+ if (kind === "import_statement" || kind === "export_statement") {
402
+ isModule = true;
403
+ } else if (kind === "ambient_declaration" && child.children().some((part) => part.kind() === "global" || part.kind() === "module")) {
404
+ return "feeds";
405
+ }
406
+ }
407
+ if (probe === "ambient" || isModule)
408
+ return "none";
409
+ if (probe === "js-script") {
410
+ return ["require($$$ARGS)", "module.exports", "exports.$NAME"].some((pattern) => root.find(pattern) !== null) ? "none" : "feeds";
411
+ }
412
+ return "feeds";
413
+ }
414
+ function feedsJsTsGlobalScope(filePath) {
415
+ return classifyJsTsGlobalScope(filePath) !== "none";
416
+ }
417
+
418
+ // dist/clients/path-birth.js
419
+ import * as fs2 from "node:fs";
420
+ var replacedPathBirths = new BoundedFifoMap(1024);
421
+ var inodeKey = (stat) => `${stat.dev}:${stat.ino}:${stat.birthtimeMs}`;
422
+ var appearedPaths = new BoundedFifoMap(1024);
423
+ function notePathAppeared(filePath, atMs = Date.now()) {
424
+ appearedPaths.set(normalizeMapKey(filePath), atMs);
425
+ }
426
+ var birthIsCtimeAlias;
427
+ function birthTimeIsCtimeAlias() {
428
+ if (birthIsCtimeAlias !== void 0)
429
+ return birthIsCtimeAlias;
430
+ birthIsCtimeAlias = false;
431
+ if (process.platform === "linux") {
432
+ try {
433
+ const proc = fs2.statSync("/proc");
434
+ birthIsCtimeAlias = proc.birthtimeMs !== 0 && proc.birthtimeMs === proc.ctimeMs;
435
+ } catch {
436
+ }
437
+ }
438
+ return birthIsCtimeAlias;
439
+ }
440
+ function pathBirthtimeMs(stat, filePath) {
441
+ const appeared = filePath === void 0 ? void 0 : appearedPaths.get(normalizeMapKey(filePath));
442
+ const inode = inodeBirthtimeMs(stat);
443
+ if (appeared === void 0)
444
+ return inode;
445
+ return inode === void 0 ? appeared : Math.max(inode, appeared);
446
+ }
447
+ function inodeBirthtimeMs(stat) {
448
+ if (!(stat.birthtimeMs > 0)) {
449
+ recordDegradationOnce({
450
+ kind: "lsp-file-birth-unknown",
451
+ subject: "no-birth-time",
452
+ reason: "the filesystem reports no birth time; a file created while a language server runs is announced as Changed (#4320)"
453
+ });
454
+ return void 0;
455
+ }
456
+ if (birthTimeIsCtimeAlias()) {
457
+ recordDegradationOnce({
458
+ kind: "lsp-file-birth-unknown",
459
+ subject: "ctime-alias",
460
+ reason: "Node reports ctime as the birth time (no statx); a file created while a language server runs is announced as Changed (#4320)"
461
+ });
462
+ return void 0;
463
+ }
464
+ return replacedPathBirths.get(inodeKey(stat)) ?? stat.birthtimeMs;
465
+ }
466
+
467
+ // dist/clients/review-graph/import-resolvers.js
468
+ import * as fs3 from "node:fs";
469
+ import * as path2 from "node:path";
470
+ function isWithin(cwd, p) {
471
+ return isUnderDir(path2.resolve(p), path2.resolve(cwd));
472
+ }
473
+ function isFile(p) {
474
+ try {
475
+ return fs3.statSync(p).isFile();
476
+ } catch {
477
+ return false;
478
+ }
479
+ }
480
+ function isDir(p) {
481
+ try {
482
+ return fs3.statSync(p).isDirectory();
483
+ } catch {
484
+ return false;
485
+ }
486
+ }
487
+ function firstExistingFile(cwd, candidates) {
488
+ for (const c of candidates) {
489
+ if (isFile(c) && isWithin(cwd, c))
490
+ return [normalizeMapKey(c)];
491
+ }
492
+ return [];
493
+ }
494
+ function sourceFilesIn(cwd, dir, ext) {
495
+ if (!isDir(dir) || !isWithin(cwd, dir))
496
+ return [];
497
+ try {
498
+ return fs3.readdirSync(dir).filter((n) => n.endsWith(ext)).map((n) => normalizeMapKey(path2.join(dir, n))).sort();
499
+ } catch {
500
+ return [];
501
+ }
502
+ }
503
+ function resolveRelative(cwd, filePath, source, exts) {
504
+ const base = path2.resolve(path2.dirname(filePath), source);
505
+ return firstExistingFile(cwd, [base, ...exts.map((e) => base + e)]);
506
+ }
507
+ function resolveDart(cwd, filePath, source) {
508
+ if (source.startsWith("package:") || source.startsWith("dart:"))
509
+ return [];
510
+ return resolveRelative(cwd, filePath, source, [".dart"]);
511
+ }
512
+ var JS_TS_EXT_RE = /\.(mjs|cjs|mts|cts|jsx?|tsx?)$/i;
513
+ function jsTsExtensionCandidates(base, strippedBase, ext) {
514
+ const candidates = [];
515
+ if (ext === ".mjs")
516
+ candidates.push(`${strippedBase}.mts`);
517
+ if (ext === ".cjs")
518
+ candidates.push(`${strippedBase}.cts`);
519
+ if (ext === ".mts")
520
+ candidates.push(`${strippedBase}.mts`);
521
+ if (ext === ".cts")
522
+ candidates.push(`${strippedBase}.cts`);
523
+ candidates.push(`${strippedBase}.ts`, `${strippedBase}.tsx`, `${strippedBase}.mts`, `${strippedBase}.cts`);
524
+ candidates.push(base, `${strippedBase}.js`, `${strippedBase}.jsx`, `${strippedBase}.mjs`, `${strippedBase}.cjs`);
525
+ for (const index of [
526
+ "index.ts",
527
+ "index.tsx",
528
+ "index.mts",
529
+ "index.cts",
530
+ "index.js",
531
+ "index.jsx",
532
+ "index.mjs",
533
+ "index.cjs"
534
+ ]) {
535
+ candidates.push(path2.join(base, index));
536
+ }
537
+ return [...new Set(candidates)];
538
+ }
539
+ function jsTsCandidatePaths(filePath, source) {
540
+ const base = path2.resolve(path2.dirname(filePath), source);
541
+ const strippedSource = source.replace(JS_TS_EXT_RE, "");
542
+ const strippedBase = strippedSource === source ? base : path2.resolve(path2.dirname(filePath), strippedSource);
543
+ const ext = path2.extname(source).toLowerCase();
544
+ return jsTsExtensionCandidates(base, strippedBase, ext);
545
+ }
546
+ function findWorkspaceModuleForSpecifier(modules, source) {
547
+ let best;
548
+ for (const mod of modules) {
549
+ let subpath;
550
+ if (source === mod.name)
551
+ subpath = "";
552
+ else if (source.startsWith(`${mod.name}/`))
553
+ subpath = source.slice(mod.name.length + 1);
554
+ if (subpath === void 0)
555
+ continue;
556
+ if (!best || mod.name.length > best.mod.name.length)
557
+ best = { mod, subpath };
558
+ }
559
+ return best;
560
+ }
561
+ function pickExportsMain(exportsField) {
562
+ if (typeof exportsField === "string")
563
+ return exportsField;
564
+ if (!exportsField || typeof exportsField !== "object")
565
+ return void 0;
566
+ const obj = exportsField;
567
+ const dot = obj["."] ?? obj;
568
+ if (typeof dot === "string")
569
+ return dot;
570
+ if (dot && typeof dot === "object") {
571
+ for (const key of ["import", "require", "default"]) {
572
+ const v = dot[key];
573
+ if (typeof v === "string")
574
+ return v;
575
+ }
576
+ }
577
+ return void 0;
578
+ }
579
+ function workspaceEntryCandidates(pkgRoot) {
580
+ let main;
581
+ try {
582
+ const pkg = JSON.parse(fs3.readFileSync(path2.join(pkgRoot, "package.json"), "utf-8"));
583
+ main = pickExportsMain(pkg.exports) ?? pkg.module ?? pkg.main;
584
+ } catch {
585
+ }
586
+ const candidates = [];
587
+ if (main) {
588
+ const mainPath = path2.resolve(pkgRoot, main);
589
+ const ext = path2.extname(mainPath).toLowerCase();
590
+ const stripped = mainPath.replace(JS_TS_EXT_RE, "");
591
+ candidates.push(...jsTsExtensionCandidates(mainPath, stripped, ext));
592
+ }
593
+ for (const base of [pkgRoot, path2.join(pkgRoot, "src")]) {
594
+ candidates.push(path2.join(base, "index.ts"), path2.join(base, "index.tsx"), path2.join(base, "index.mts"), path2.join(base, "index.cts"), path2.join(base, "index.js"), path2.join(base, "index.jsx"), path2.join(base, "index.mjs"), path2.join(base, "index.cjs"));
595
+ }
596
+ return [...new Set(candidates)];
597
+ }
598
+ function workspaceSubpathCandidates(pkgRoot, subpath) {
599
+ const base = path2.join(pkgRoot, subpath);
600
+ const strippedSubpath = subpath.replace(JS_TS_EXT_RE, "");
601
+ const strippedBase = strippedSubpath === subpath ? base : path2.join(pkgRoot, strippedSubpath);
602
+ const ext = path2.extname(subpath).toLowerCase();
603
+ return jsTsExtensionCandidates(base, strippedBase, ext);
604
+ }
605
+ function resolveAliasedImport(cwd, specifier, importerDir) {
606
+ for (const target of aliasedImportTargets(specifier, importerDir)) {
607
+ const ext = path2.extname(target).toLowerCase();
608
+ const stripped = target.replace(JS_TS_EXT_RE, "");
609
+ const found = firstExistingFile(cwd, jsTsExtensionCandidates(target, stripped, ext));
610
+ if (found.length)
611
+ return found;
612
+ }
613
+ return [];
614
+ }
615
+ function resolveProjectReferenceImport(cwd, specifier, importerDir) {
616
+ const target = referencedProjectImportTarget(specifier, importerDir);
617
+ return target ? firstExistingFile(cwd, [target]) : [];
618
+ }
619
+ function resolveWorkspacePackageImport(cwd, source) {
620
+ if (source.startsWith("."))
621
+ return [];
622
+ const graph = buildModuleGraph(cwd);
623
+ if (!graph)
624
+ return [];
625
+ const match = findWorkspaceModuleForSpecifier(graph.modules.values(), source);
626
+ if (!match)
627
+ return [];
628
+ const candidates = match.subpath ? workspaceSubpathCandidates(match.mod.root, match.subpath) : workspaceEntryCandidates(match.mod.root);
629
+ return firstExistingFile(cwd, candidates);
630
+ }
631
+ function resolveJsTs(cwd, filePath, source) {
632
+ if (!source.startsWith(".")) {
633
+ const aliased = resolveAliasedImport(cwd, source, path2.dirname(filePath));
634
+ if (aliased.length)
635
+ return aliased;
636
+ const referenced = resolveProjectReferenceImport(cwd, source, path2.dirname(filePath));
637
+ return referenced.length ? referenced : resolveWorkspacePackageImport(cwd, source);
638
+ }
639
+ return firstExistingFile(cwd, jsTsCandidatePaths(filePath, source));
640
+ }
641
+ function resolveCxx(cwd, filePath, source) {
642
+ if (source.startsWith("<"))
643
+ return [];
644
+ const dir = path2.dirname(path2.resolve(filePath));
645
+ return firstExistingFile(cwd, [
646
+ path2.resolve(dir, source),
647
+ path2.resolve(cwd, source),
648
+ path2.resolve(cwd, "include", source),
649
+ path2.resolve(cwd, "src", source)
650
+ ]);
651
+ }
652
+ function pythonRoots(cwd, fileDir) {
653
+ let p = fileDir;
654
+ const root = path2.resolve(cwd);
655
+ while (isFile(path2.join(p, "__init__.py")) && isWithin(cwd, p)) {
656
+ const parent = path2.dirname(p);
657
+ if (parent === p)
658
+ break;
659
+ p = parent;
660
+ }
661
+ const roots = /* @__PURE__ */ new Set([p, root, path2.join(root, "src")]);
662
+ return [...roots].filter((r) => isDir(r));
663
+ }
664
+ function resolvePython(cwd, filePath, source) {
665
+ const fileDir = path2.dirname(path2.resolve(filePath));
666
+ if (source.startsWith(".")) {
667
+ const m = source.match(/^(\.+)(.*)$/);
668
+ if (!m)
669
+ return [];
670
+ const dots = m[1].length;
671
+ let baseDir = fileDir;
672
+ for (let i = 1; i < dots; i++)
673
+ baseDir = path2.dirname(baseDir);
674
+ const rest = m[2] ? m[2].split(".") : [];
675
+ const target = path2.join(baseDir, ...rest);
676
+ return firstExistingFile(cwd, [
677
+ `${target}.py`,
678
+ path2.join(target, "__init__.py")
679
+ ]);
680
+ }
681
+ const parts = source.split(".");
682
+ for (const root of pythonRoots(cwd, fileDir)) {
683
+ const target = path2.join(root, ...parts);
684
+ const found = firstExistingFile(cwd, [
685
+ `${target}.py`,
686
+ path2.join(target, "__init__.py")
687
+ ]);
688
+ if (found.length)
689
+ return found;
690
+ }
691
+ return [];
692
+ }
693
+ function findGoModule(cwd, filePath) {
694
+ let dir = path2.dirname(path2.resolve(filePath));
695
+ const root = path2.resolve(cwd);
696
+ while (true) {
697
+ try {
698
+ const content = fs3.readFileSync(path2.join(dir, "go.mod"), "utf-8");
699
+ const m = content.match(/^[^\S\n\r\u2028\u2029]*module\s+(\S+)/m);
700
+ if (m)
701
+ return { moduleDir: dir, modulePath: m[1] };
702
+ } catch {
703
+ }
704
+ if (dir === root)
705
+ break;
706
+ const parent = path2.dirname(dir);
707
+ if (parent === dir || !isWithin(cwd, parent))
708
+ break;
709
+ dir = parent;
710
+ }
711
+ return null;
712
+ }
713
+ function resolveGo(cwd, filePath, source) {
714
+ const mod = findGoModule(cwd, filePath);
715
+ if (!mod)
716
+ return [];
717
+ if (source !== mod.modulePath && !source.startsWith(`${mod.modulePath}/`)) {
718
+ return [];
719
+ }
720
+ const rel = source === mod.modulePath ? "" : source.slice(mod.modulePath.length + 1);
721
+ return sourceFilesIn(cwd, path2.join(mod.moduleDir, rel), ".go");
722
+ }
723
+ function javaSourceRoots(cwd, filePath) {
724
+ const root = path2.resolve(cwd);
725
+ const roots = /* @__PURE__ */ new Set();
726
+ for (const c of ["src/main/java", "src/test/java", "src", ""]) {
727
+ roots.add(path2.join(root, c));
728
+ }
729
+ let p = path2.dirname(path2.resolve(filePath));
730
+ while (true) {
731
+ roots.add(p);
732
+ if (p === root)
733
+ break;
734
+ const parent = path2.dirname(p);
735
+ if (parent === p || !isWithin(cwd, parent))
736
+ break;
737
+ p = parent;
738
+ }
739
+ return [...roots].filter((r) => isDir(r));
740
+ }
741
+ function resolveJava(cwd, filePath, source) {
742
+ const parts = source.split(".");
743
+ for (const root of javaSourceRoots(cwd, filePath)) {
744
+ const asFile = firstExistingFile(cwd, [
745
+ `${path2.join(root, ...parts)}.java`
746
+ ]);
747
+ if (asFile.length)
748
+ return asFile;
749
+ const asPkg = sourceFilesIn(cwd, path2.join(root, ...parts), ".java");
750
+ if (asPkg.length)
751
+ return asPkg;
752
+ if (parts.length > 1) {
753
+ const dropLast = firstExistingFile(cwd, [
754
+ `${path2.join(root, ...parts.slice(0, -1))}.java`
755
+ ]);
756
+ if (dropLast.length)
757
+ return dropLast;
758
+ }
759
+ }
760
+ return [];
761
+ }
762
+ function importSourceNameParts(source) {
763
+ return source.match(/[\w$-]+/g) ?? [];
764
+ }
765
+ function fileAnswerNames(file) {
766
+ return [
767
+ path2.basename(file).split(".")[0] ?? "",
768
+ path2.basename(path2.dirname(file))
769
+ ].flatMap((name) => name.length > 0 ? [name] : []);
770
+ }
771
+ function resolveImportToFiles(cwd, filePath, languageId, source) {
772
+ switch (languageId) {
773
+ case "typescript":
774
+ case "tsx":
775
+ case "javascript":
776
+ case "jsts":
777
+ return resolveJsTs(cwd, filePath, source);
778
+ case "c":
779
+ case "cpp":
780
+ return resolveCxx(cwd, filePath, source);
781
+ case "ruby":
782
+ return resolveRelative(cwd, filePath, source, [".rb"]);
783
+ case "zig":
784
+ return resolveRelative(cwd, filePath, source, [".zig"]);
785
+ case "bash":
786
+ return resolveRelative(cwd, filePath, source, [".sh", ".bash"]);
787
+ case "dart":
788
+ return resolveDart(cwd, filePath, source);
789
+ case "python":
790
+ return resolvePython(cwd, filePath, source);
791
+ case "go":
792
+ return resolveGo(cwd, filePath, source);
793
+ case "java":
794
+ return resolveJava(cwd, filePath, source);
795
+ default:
796
+ return [];
797
+ }
798
+ }
799
+
800
+ // dist/clients/tree-sitter-symbol-extractor.js
801
+ import * as path3 from "node:path";
802
+ var SYMBOL_QUERIES = {
803
+ typescript: {
804
+ defs: `
805
+ ;; Function declarations: function foo(params) { }
806
+ (function_declaration
807
+ name: (identifier) @funcName
808
+ parameters: (formal_parameters) @funcParams
809
+ body: (statement_block) @funcBody) @funcDef
810
+
811
+ ;; Arrow functions: const foo = (params) => { }
812
+ (variable_declarator
813
+ name: (identifier) @arrowName
814
+ value: (arrow_function
815
+ parameters: (formal_parameters) @arrowParams
816
+ body: (_) @arrowBody)) @arrowDef
817
+
818
+ ;; Class declarations: class Foo { }
819
+ (class_declaration
820
+ name: (type_identifier) @className) @classDef
821
+
822
+ ;; Method definitions: class Foo { bar() { } }
823
+ (method_definition
824
+ name: (property_identifier) @methodName
825
+ parameters: (formal_parameters) @methodParams) @methodDef
826
+
827
+ ;; Interface declarations: interface Foo { }
828
+ (interface_declaration
829
+ name: (type_identifier) @interfaceName) @interfaceDef
830
+
831
+ ;; Type alias: type Foo = ...
832
+ (type_alias_declaration
833
+ name: (type_identifier) @typeName) @typeDef
834
+ `,
835
+ refs: `
836
+ ;; Function/method calls: foo() or obj.bar()
837
+ (call_expression
838
+ function: (identifier) @callIdent) @callRef
839
+
840
+ (call_expression
841
+ function: (member_expression
842
+ object: (_)
843
+ property: (property_identifier) @callMethod)) @callMethodRef
844
+
845
+ ;; New expressions: new Foo()
846
+ (new_expression
847
+ constructor: (identifier) @newIdent) @newRef
848
+
849
+ ;; Type references: type T = Foo
850
+ (type_identifier) @typeIdent
851
+ `
852
+ },
853
+ python: {
854
+ defs: `
855
+ ;; Function definitions: def foo(params):
856
+ (function_definition
857
+ name: (identifier) @funcName
858
+ parameters: (parameters) @funcParams) @funcDef
859
+
860
+ ;; Class definitions: class Foo:
861
+ (class_definition
862
+ name: (identifier) @className) @classDef
863
+
864
+ ;; Method definitions (within class)
865
+ (class_definition
866
+ body: (block
867
+ (function_definition
868
+ name: (identifier) @methodName
869
+ parameters: (parameters) @methodParams) @methodDef))
870
+ `,
871
+ refs: `
872
+ ;; Function calls: foo() or obj.bar()
873
+ (call
874
+ function: (identifier) @callIdent) @callRef
875
+
876
+ (call
877
+ function: (attribute
878
+ object: (_)
879
+ attribute: (identifier) @callMethod)) @callMethodRef
880
+ `
881
+ },
882
+ rust: {
883
+ defs: `
884
+ ;; Function definitions: fn foo(params) { }
885
+ (function_item
886
+ name: (identifier) @funcName
887
+ parameters: (parameters) @funcParams) @funcDef
888
+
889
+ ;; Struct definitions: struct Foo { }
890
+ (struct_item
891
+ name: (type_identifier) @structName) @structDef
892
+
893
+ ;; Impl blocks: impl Foo { fn bar() { } }
894
+ (impl_item
895
+ type: (type_identifier) @implType
896
+ body: (declaration_list
897
+ (function_item
898
+ name: (identifier) @implMethodName) @implMethodDef))
899
+ `,
900
+ refs: `
901
+ ;; Function calls: foo() or obj.bar()
902
+ (call_expression
903
+ function: (identifier) @callIdent) @callRef
904
+
905
+ (call_expression
906
+ function: (field_expression
907
+ value: (_)
908
+ field: (field_identifier) @callField)) @callFieldRef
909
+ `
910
+ },
911
+ go: {
912
+ defs: `
913
+ (function_declaration
914
+ name: (identifier) @funcName
915
+ parameters: (parameter_list) @funcParams) @funcDef
916
+
917
+ (method_declaration
918
+ name: (field_identifier) @methodName
919
+ parameters: (parameter_list) @methodParams) @methodDef
920
+
921
+ (type_spec
922
+ name: (type_identifier) @typeName) @typeDef
923
+ `,
924
+ refs: `
925
+ (call_expression
926
+ function: (identifier) @callIdent) @callRef
927
+
928
+ (call_expression
929
+ function: (selector_expression
930
+ field: (field_identifier) @callMethod)) @callMethodRef
931
+ `
932
+ },
933
+ ruby: {
934
+ defs: `
935
+ (method
936
+ name: (identifier) @methodName) @methodDef
937
+
938
+ (singleton_method
939
+ name: (identifier) @methodName) @methodDef
940
+
941
+ (class
942
+ name: (constant) @className) @classDef
943
+
944
+ (module
945
+ name: (constant) @moduleName) @moduleDef
946
+ `,
947
+ refs: `
948
+ (call
949
+ method: (identifier) @callIdent) @callRef
950
+
951
+ (call
952
+ method: (constant) @typeIdent) @typeRef
953
+ `
954
+ },
955
+ c: {
956
+ defs: `
957
+ (function_definition
958
+ declarator: (function_declarator
959
+ declarator: (identifier) @funcName
960
+ parameters: (parameter_list) @funcParams)) @funcDef
961
+
962
+ (type_definition
963
+ declarator: (type_identifier) @typeName) @typeDef
964
+
965
+ (struct_specifier
966
+ name: (type_identifier) @typeName) @typeDef
967
+
968
+ (enum_specifier
969
+ name: (type_identifier) @typeName) @typeDef
970
+ `,
971
+ refs: `
972
+ (call_expression
973
+ function: (identifier) @callIdent) @callRef
974
+
975
+ (call_expression
976
+ function: (field_expression
977
+ field: (field_identifier) @callField)) @callFieldRef
978
+
979
+ (type_identifier) @typeIdent
980
+ `
981
+ },
982
+ cpp: {
983
+ defs: `
984
+ (function_definition
985
+ declarator: (function_declarator
986
+ declarator: (identifier) @funcName
987
+ parameters: (parameter_list) @funcParams)) @funcDef
988
+
989
+ (class_specifier
990
+ name: (type_identifier) @className) @classDef
991
+
992
+ (struct_specifier
993
+ name: (type_identifier) @className) @classDef
994
+
995
+ (type_definition
996
+ declarator: (type_identifier) @typeName) @typeDef
997
+ `,
998
+ refs: `
999
+ (call_expression
1000
+ function: (identifier) @callIdent) @callRef
1001
+
1002
+ (call_expression
1003
+ function: (field_expression
1004
+ field: (field_identifier) @callField)) @callFieldRef
1005
+
1006
+ (type_identifier) @typeIdent
1007
+ `
1008
+ },
1009
+ java: {
1010
+ defs: `
1011
+ (method_declaration
1012
+ name: (identifier) @methodName
1013
+ parameters: (formal_parameters) @methodParams) @methodDef
1014
+
1015
+ (class_declaration
1016
+ name: (identifier) @className) @classDef
1017
+
1018
+ (interface_declaration
1019
+ name: (identifier) @interfaceName) @interfaceDef
1020
+
1021
+ (constructor_declaration
1022
+ name: (identifier) @funcName
1023
+ parameters: (formal_parameters) @funcParams) @funcDef
1024
+
1025
+ (enum_declaration
1026
+ name: (identifier) @className) @classDef
1027
+ `,
1028
+ refs: `
1029
+ (method_invocation
1030
+ name: (identifier) @callMethod) @callRef
1031
+
1032
+ (object_creation_expression
1033
+ type: (type_identifier) @newIdent) @newRef
1034
+
1035
+ (type_identifier) @typeIdent
1036
+ `
1037
+ },
1038
+ kotlin: {
1039
+ // #251: class_declaration's name is type_identifier; the old extra
1040
+ // `(class_declaration (simple_identifier) @className)` was a bad pattern that
1041
+ // failed query compilation (taking the whole language down). Call refs use
1042
+ // no field name in the shipped grammar (the old `calleeExpression:` field
1043
+ // also failed to compile).
1044
+ defs: `
1045
+ (function_declaration
1046
+ (simple_identifier) @funcName) @funcDef
1047
+
1048
+ (class_declaration
1049
+ (type_identifier) @className) @classDef
1050
+
1051
+ (object_declaration
1052
+ (type_identifier) @className) @classDef
1053
+ `,
1054
+ refs: `
1055
+ (call_expression
1056
+ (simple_identifier) @callIdent) @callRef
1057
+
1058
+ (user_type (type_identifier) @typeIdent)
1059
+ `
1060
+ },
1061
+ dart: {
1062
+ // #251: function_signature/class_definition take their name/params as direct
1063
+ // children in the shipped grammar — the old `name:`/`parameters:` fields did
1064
+ // not exist and failed query compilation. method bodies' inner
1065
+ // function_signature also matches @funcDef (methods surface as functions).
1066
+ defs: `
1067
+ (function_signature
1068
+ (identifier) @funcName
1069
+ (formal_parameter_list) @funcParams) @funcDef
1070
+
1071
+ (class_definition
1072
+ (identifier) @className) @classDef
1073
+ `,
1074
+ refs: `
1075
+ (type_identifier) @typeIdent
1076
+ `
1077
+ },
1078
+ elixir: {
1079
+ defs: `
1080
+ (call
1081
+ target: (identifier) @_kw
1082
+ (arguments
1083
+ (call
1084
+ target: (identifier) @funcName
1085
+ (arguments) @funcParams) @funcDef)
1086
+ (#match? @_kw "^def[pm]?$"))
1087
+
1088
+ (call
1089
+ target: (identifier) @_kw
1090
+ (arguments (alias) @moduleName) @moduleDef
1091
+ (#match? @_kw "^defmodule$"))
1092
+ `,
1093
+ refs: `
1094
+ (call
1095
+ target: (identifier) @callIdent) @callRef
1096
+
1097
+ (alias) @typeIdent
1098
+ `
1099
+ },
1100
+ csharp: {
1101
+ defs: `
1102
+ (method_declaration
1103
+ name: (identifier) @methodName
1104
+ parameters: (parameter_list) @methodParams) @methodDef
1105
+
1106
+ (class_declaration
1107
+ name: (identifier) @className) @classDef
1108
+
1109
+ (struct_declaration
1110
+ name: (identifier) @className) @classDef
1111
+
1112
+ (interface_declaration
1113
+ name: (identifier) @interfaceName) @interfaceDef
1114
+
1115
+ (constructor_declaration
1116
+ name: (identifier) @funcName
1117
+ parameters: (parameter_list) @funcParams) @funcDef
1118
+
1119
+ (enum_declaration
1120
+ name: (identifier) @className) @classDef
1121
+ `,
1122
+ refs: `
1123
+ (invocation_expression
1124
+ function: (identifier) @callIdent) @callRef
1125
+
1126
+ (invocation_expression
1127
+ function: (member_access_expression
1128
+ name: (identifier) @callMethod)) @callMethodRef
1129
+
1130
+ (object_creation_expression
1131
+ type: (identifier) @newIdent) @newRef
1132
+ `
1133
+ },
1134
+ php: {
1135
+ defs: `
1136
+ (function_definition
1137
+ name: (name) @funcName
1138
+ parameters: (formal_parameters) @funcParams) @funcDef
1139
+
1140
+ (method_declaration
1141
+ name: (name) @methodName
1142
+ parameters: (formal_parameters) @methodParams) @methodDef
1143
+
1144
+ (class_declaration
1145
+ name: (name) @className) @classDef
1146
+
1147
+ (interface_declaration
1148
+ name: (name) @interfaceName) @interfaceDef
1149
+
1150
+ (trait_declaration
1151
+ name: (name) @className) @classDef
1152
+ `,
1153
+ refs: `
1154
+ (function_call_expression
1155
+ function: (name) @callIdent) @callRef
1156
+
1157
+ (member_call_expression
1158
+ name: (name) @callMethod) @callMethodRef
1159
+
1160
+ (object_creation_expression
1161
+ (name) @newIdent) @newRef
1162
+ `
1163
+ },
1164
+ swift: {
1165
+ defs: `
1166
+ (function_declaration
1167
+ (simple_identifier) @funcName) @funcDef
1168
+
1169
+ (class_declaration
1170
+ (type_identifier) @className) @classDef
1171
+
1172
+ (protocol_declaration
1173
+ (type_identifier) @interfaceName) @interfaceDef
1174
+ `,
1175
+ refs: `
1176
+ (call_expression
1177
+ (simple_identifier) @callIdent) @callRef
1178
+
1179
+ (navigation_expression
1180
+ (simple_identifier) @callMethod) @callMethodRef
1181
+
1182
+ (type_identifier) @typeIdent
1183
+ `
1184
+ },
1185
+ lua: {
1186
+ // #255: pulled from @tree-sitter-grammars/tree-sitter-lua (the aggregator's
1187
+ // build corrupts once a 2nd grammar loads). That grammar names function defs
1188
+ // `function_declaration` — the name is either a direct (identifier) (global /
1189
+ // `local function`) or a (dot_index_expression) for `function M.run`. Calls
1190
+ // are `function_call` with an (identifier) or (dot_index_expression) callee.
1191
+ defs: `
1192
+ (function_declaration
1193
+ (identifier) @funcName) @funcDef
1194
+
1195
+ (function_declaration
1196
+ (dot_index_expression) @funcName) @funcDef
1197
+ `,
1198
+ refs: `
1199
+ (function_call (identifier) @callIdent) @callRef
1200
+
1201
+ (function_call (dot_index_expression) @callIdent) @callRef
1202
+ `
1203
+ },
1204
+ ocaml: {
1205
+ // #251: let_binding holds value_name as a direct child (no `pattern:` /
1206
+ // value_pattern wrapper), and module_binding's module_name is a direct child
1207
+ // (no `name:` field) — the old patterns failed query compilation.
1208
+ defs: `
1209
+ (value_definition
1210
+ (let_binding (value_name) @funcName)) @funcDef
1211
+
1212
+ (module_definition
1213
+ (module_binding (module_name) @moduleName)) @moduleDef
1214
+ `,
1215
+ refs: `
1216
+ (application_expression
1217
+ (value_path (value_name) @callIdent)) @callRef
1218
+
1219
+ (value_path (value_name) @callIdent) @callRef
1220
+ `
1221
+ },
1222
+ zig: {
1223
+ defs: `
1224
+ (function_declaration
1225
+ (identifier) @funcName) @funcDef
1226
+ `,
1227
+ // #251: the old `field_access` node name doesn't exist in this grammar and
1228
+ // failed to compile; call_expression refs are valid.
1229
+ refs: `
1230
+ (call_expression
1231
+ (identifier) @callIdent) @callRef
1232
+ `
1233
+ },
1234
+ bash: {
1235
+ defs: `
1236
+ (function_definition
1237
+ name: (word) @funcName) @funcDef
1238
+ `,
1239
+ refs: `
1240
+ (command
1241
+ name: (command_name (word) @callIdent)) @callRef
1242
+ `
1243
+ },
1244
+ // #1522: tree-sitter-cue (eonpatapon/tree-sitter-cue, vendored per #1520) has
1245
+ // no `label:`/`value:` field names on `field` — verified directly against the
1246
+ // committed wasm (`value:` fails query compilation with "Bad field name");
1247
+ // only `let_clause`'s `left:`/`right:` and `call_expression`'s `function:`
1248
+ // are real fields. A `#Definition` is not a distinct node kind: `#Service`
1249
+ // parses as a plain (identifier) whose text happens to start with "#", so
1250
+ // definitions are told apart from ordinary struct fields with a `#match?`/
1251
+ // `#not-match?` text predicate rather than a grammar-level distinction —
1252
+ // both predicates must sit INSIDE the pattern's own parens (this repo's
1253
+ // tree-sitter gotcha). `#Definition`s map to `type` (the closest existing
1254
+ // SymbolKind to a reusable CUE schema); plain fields map to `property`;
1255
+ // `let` bindings map to `variable`.
1256
+ //
1257
+ // Two known upstream grammar rough edges (#1522 review round 1, F4;
1258
+ // docs/language-coverage.md's CUE row has the same note, kept in sync):
1259
+ // (1) an aliased field label (`X=name: value`) exposes BOTH identifiers
1260
+ // as untagged siblings under one `label` node — `(label alias:
1261
+ // (identifier) (identifier))` — with no field/structural way to tell the
1262
+ // alias from the real name, so `fieldDef` spuriously captures the alias
1263
+ // too, alongside the correct symbol for `name`. (2) a multi-hash raw
1264
+ // string (`##"..."##`, 2+ `#` delimiters) mis-parses regardless of
1265
+ // content — the field's value becomes a bare `identifier` instead of a
1266
+ // `string`, which can surface as a spurious `#`-prefixed ref via the
1267
+ // `typeIdent` pattern below. Both are grammar bugs, not query bugs — no
1268
+ // query change here can distinguish what the parse tree doesn't.
1269
+ cue: {
1270
+ defs: `
1271
+ (field
1272
+ (label (identifier) @defName)
1273
+ (#match? @defName "^#")) @defDef
1274
+
1275
+ (field
1276
+ (label (identifier) @fieldName)
1277
+ (value (_)) @fieldValue
1278
+ (#not-match? @fieldName "^#")) @fieldDef
1279
+
1280
+ (let_clause
1281
+ left: (identifier) @letName
1282
+ right: (_) @letValue) @letDef
1283
+ `,
1284
+ // `#Service` used as a value (e.g. `#Other: #Service & {...}`) is the same
1285
+ // (identifier) node kind as its own definition label — there is no
1286
+ // separate reference/definition node kind in this grammar, so the
1287
+ // definition's own label also matches this pattern, mirroring the same
1288
+ // self-match already accepted for swift/java's broad `type_identifier`
1289
+ // ref patterns above.
1290
+ refs: `
1291
+ ((identifier) @typeIdent
1292
+ (#match? @typeIdent "^#"))
1293
+
1294
+ (call_expression
1295
+ function: (identifier) @callIdent) @callRef
1296
+
1297
+ (call_expression
1298
+ function: (selector_expression (identifier) (identifier) @callMethod)) @callMethodRef
1299
+ `
1300
+ }
1301
+ };
1302
+ SYMBOL_QUERIES.tsx = SYMBOL_QUERIES.typescript;
1303
+ SYMBOL_QUERIES.javascript = {
1304
+ defs: `
1305
+ ;; Function declarations: function foo(params) { }
1306
+ (function_declaration
1307
+ name: (identifier) @funcName
1308
+ parameters: (formal_parameters) @funcParams
1309
+ body: (statement_block) @funcBody) @funcDef
1310
+
1311
+ ;; Arrow functions: const foo = (params) => { }
1312
+ (variable_declarator
1313
+ name: (identifier) @arrowName
1314
+ value: (arrow_function
1315
+ parameters: (formal_parameters) @arrowParams
1316
+ body: (_) @arrowBody)) @arrowDef
1317
+
1318
+ ;; Class declarations: class Foo { } \u2014 (identifier) name on this grammar.
1319
+ (class_declaration
1320
+ name: (identifier) @className) @classDef
1321
+
1322
+ ;; Method definitions: class Foo { bar() { } }
1323
+ (method_definition
1324
+ name: (property_identifier) @methodName
1325
+ parameters: (formal_parameters) @methodParams) @methodDef
1326
+ `,
1327
+ refs: `
1328
+ ;; Function/method calls: foo() or obj.bar()
1329
+ (call_expression
1330
+ function: (identifier) @callIdent) @callRef
1331
+
1332
+ (call_expression
1333
+ function: (member_expression
1334
+ object: (_)
1335
+ property: (property_identifier) @callMethod)) @callMethodRef
1336
+
1337
+ ;; New expressions: new Foo()
1338
+ (new_expression
1339
+ constructor: (identifier) @newIdent) @newRef
1340
+ `
1341
+ };
1342
+ function symbolExtractionGrammar(kind, filePath) {
1343
+ if (!kind)
1344
+ return void 0;
1345
+ const kindGrammar = KIND_TO_GRAMMAR[kind];
1346
+ if (!kindGrammar)
1347
+ return void 0;
1348
+ const byExtension = filePath ? EXTENSION_TO_GRAMMAR[path3.extname(filePath).toLowerCase()] : void 0;
1349
+ const grammar = byExtension ?? kindGrammar;
1350
+ return grammar in SYMBOL_QUERIES ? grammar : void 0;
1351
+ }
1352
+ var JS_TS_IMPORT_QUERY = `
1353
+ (comment) @importComment
1354
+ (import_statement source: (string) @importSource)
1355
+ (export_statement source: (string) @importSource)
1356
+ (call_expression
1357
+ function: (import)
1358
+ arguments: (arguments . (string) @importSource))
1359
+ (call_expression
1360
+ function: (identifier) @_m
1361
+ arguments: (arguments . (string) @importSource)
1362
+ (#eq? @_m "require"))
1363
+ `;
1364
+ var IMPORT_QUERIES = {
1365
+ // ESM import + re-export source strings; `source:` is a (string) on both the
1366
+ // typescript and tsx grammars (validated). parseImportMatch strips the quotes.
1367
+ // #4438: a dynamic `import("x")` and a `require("x")` call with a string
1368
+ // argument count too, as the review graph's import facts already count them
1369
+ // (`dispatch/facts/import-facts.ts`): the inline-blocker sweep and the
1370
+ // created-module producer read this query, and a dependency it missed
1371
+ // stayed stale there. Node names probed on the shipped typescript, tsx and
1372
+ // javascript grammars; a pattern one grammar lacks would fail the whole
1373
+ // query. The ambient-module extension is TS/TSX-only; JavaScript uses
1374
+ // the common query. `import x = require()` remains outside this query.
1375
+ typescript: `${JS_TS_IMPORT_QUERY}
1376
+ (ambient_declaration (module name: (string) @importSource))`,
1377
+ tsx: `${JS_TS_IMPORT_QUERY}
1378
+ (ambient_declaration (module name: (string) @importSource))`,
1379
+ // #include "foo.h" (string_literal) and #include <stdio.h> (system_lib_string)
1380
+ // on both the c and cpp grammars (validated). parseImportMatch strips the quotes
1381
+ // from the local form; the system form keeps its <> so the resolver/bucketer can
1382
+ // tell a system header from a local include.
1383
+ c: `
1384
+ (preproc_include path: (string_literal) @importSource)
1385
+ (preproc_include path: (system_lib_string) @importSource)
1386
+ `,
1387
+ cpp: `
1388
+ (preproc_include path: (string_literal) @importSource)
1389
+ (preproc_include path: (system_lib_string) @importSource)
1390
+ `,
1391
+ python: `
1392
+ (import_statement name: (dotted_name) @importSource)
1393
+ (import_statement name: (aliased_import name: (dotted_name) @importSource))
1394
+ (import_from_statement module_name: (dotted_name) @importSource)
1395
+ (import_from_statement module_name: (relative_import) @importSource)
1396
+ `,
1397
+ go: `(import_spec path: (interpreted_string_literal) @importSource)`,
1398
+ rust: `(use_declaration argument: (_) @importSource)`,
1399
+ java: `(import_declaration (scoped_identifier) @importSource)`,
1400
+ kotlin: `(import_header (identifier) @importSource)`,
1401
+ csharp: `
1402
+ (using_directive (identifier) @importSource)
1403
+ (using_directive (qualified_name) @importSource)
1404
+ `,
1405
+ swift: `(import_declaration (identifier) @importSource)`,
1406
+ php: `(namespace_use_clause (name) @importSource)`,
1407
+ ocaml: `(open_module (module_path) @importSource)`,
1408
+ dart: `(import_specification (configurable_uri (uri (string_literal) @importSource)))`,
1409
+ // local x = require("mod.a") — a plain function call, not a statement. The
1410
+ // pulled @tree-sitter-grammars grammar (#255) names it function_call.
1411
+ lua: `
1412
+ (function_call
1413
+ (identifier) @_m
1414
+ (arguments (string) @importSource)
1415
+ (#match? @_m "^require$"))
1416
+ `,
1417
+ // require "x" / require_relative "x" — covers both via the "^require" prefix.
1418
+ ruby: `
1419
+ (call
1420
+ method: (identifier) @_m
1421
+ (argument_list (string (string_content) @importSource))
1422
+ (#match? @_m "^require"))
1423
+ `,
1424
+ // @import("std") — a builtin call, not a statement.
1425
+ zig: `
1426
+ (builtin_function (builtin_identifier) @_m
1427
+ (arguments (string (string_content) @importSource))
1428
+ (#match? @_m "^@import$"))
1429
+ `,
1430
+ // import/alias/require/use Foo — macro calls; excludes defmodule and friends.
1431
+ elixir: `
1432
+ (call target: (identifier) @_m
1433
+ (arguments (alias) @importSource)
1434
+ (#match? @_m "^(import|alias|require|use)$"))
1435
+ `,
1436
+ // source ./x.sh and . ./x.sh — the two POSIX file-include builtins.
1437
+ bash: `
1438
+ (command (command_name (word) @_m)
1439
+ (word) @importSource
1440
+ (#match? @_m "^(source|\\.)$"))
1441
+ `,
1442
+ // import "strings" / import x "encoding/json" — `import_spec`'s `path:`
1443
+ // field is verified against the committed wasm. Block-form
1444
+ // (`import (\n\t"strings"\n)`) nests each `import_spec` one level deeper,
1445
+ // under `import_spec_list`, rather than as a direct child of
1446
+ // `import_declaration` — a second pattern is needed, not a reshaped first
1447
+ // one (#1522 review round 1, F2: the single-line-only pattern extracted
1448
+ // zero imports from the block form).
1449
+ cue: `
1450
+ (import_declaration (import_spec path: (string) @importSource))
1451
+ (import_declaration (import_spec_list (import_spec path: (string) @importSource)))
1452
+ `
1453
+ };
1454
+ IMPORT_QUERIES.javascript = JS_TS_IMPORT_QUERY;
1455
+ function parseImportMatch(match) {
1456
+ const imports = [];
1457
+ for (const capture of match.captures) {
1458
+ if (capture.name === "importComment") {
1459
+ for (const tag of capture.node.text.matchAll(/@import\b[^@]*?\bfrom\s*(["'])([^"'\r\n]+)\1/g)) {
1460
+ imports.push({
1461
+ source: tag[2],
1462
+ line: capture.node.startPosition.row + 1
1463
+ });
1464
+ }
1465
+ continue;
1466
+ }
1467
+ if (capture.name !== "importSource")
1468
+ continue;
1469
+ const raw = String(capture.node.text ?? "").trim();
1470
+ const source = raw.replace(/^["'`]+|["'`]+$/g, "");
1471
+ if (!source)
1472
+ continue;
1473
+ imports.push({ source, line: capture.node.startPosition.row + 1 });
1474
+ }
1475
+ return imports;
1476
+ }
1477
+ var TreeSitterSymbolExtractor = class _TreeSitterSymbolExtractor {
1478
+ languageId;
1479
+ client;
1480
+ // biome-ignore lint/suspicious/noExplicitAny: Query type from web-tree-sitter
1481
+ defQuery = null;
1482
+ // biome-ignore lint/suspicious/noExplicitAny: Query type from web-tree-sitter
1483
+ refQuery = null;
1484
+ // biome-ignore lint/suspicious/noExplicitAny: Query type from web-tree-sitter
1485
+ importQuery = null;
1486
+ constructor(languageId, client) {
1487
+ this.languageId = languageId;
1488
+ this.client = client;
1489
+ }
1490
+ async init() {
1491
+ try {
1492
+ if (!await this.client.isLanguageSupported(this.languageId))
1493
+ return false;
1494
+ const language = this.client.getLanguage(this.languageId);
1495
+ if (!language)
1496
+ return false;
1497
+ const { Query } = await loadWebTreeSitter();
1498
+ const queries = SYMBOL_QUERIES[this.languageId];
1499
+ if (queries) {
1500
+ this.defQuery = this.compileQuery(Query, language, queries.defs, "defs");
1501
+ this.refQuery = this.compileQuery(Query, language, queries.refs, "refs");
1502
+ }
1503
+ const importQuerySrc = IMPORT_QUERIES[this.languageId];
1504
+ if (importQuerySrc) {
1505
+ this.importQuery = this.compileQuery(Query, language, importQuerySrc, "imports");
1506
+ }
1507
+ return Boolean(this.defQuery || this.importQuery);
1508
+ } catch (err) {
1509
+ this.client.reportWasmAbort(err);
1510
+ logTreeSitterDiagnostic({
1511
+ subsystem: "symbol-extractor",
1512
+ languageId: this.languageId,
1513
+ message: `Failed to init ${this.languageId}: ${err instanceof Error ? err.message : String(err)}`
1514
+ });
1515
+ return false;
1516
+ }
1517
+ }
1518
+ // biome-ignore lint/suspicious/noExplicitAny: web-tree-sitter Query/Language types
1519
+ compileQuery(Query, language, src, label) {
1520
+ const input = wasmQueryInput(`${this.languageId}:${label}:${src}`);
1521
+ try {
1522
+ return new Query(language, src);
1523
+ } catch (err) {
1524
+ if (this.client.reportWasmAbort(err, input))
1525
+ throw err;
1526
+ logTreeSitterDiagnostic({
1527
+ subsystem: "symbol-extractor",
1528
+ languageId: this.languageId,
1529
+ message: `${this.languageId} ${label} query failed: ${err.message}`,
1530
+ metadata: { query: label }
1531
+ });
1532
+ return null;
1533
+ }
1534
+ }
1535
+ /**
1536
+ * Extract symbols from a parsed tree-sitter tree
1537
+ */
1538
+ extract(tree, filePath, content) {
1539
+ const symbols = [];
1540
+ const refs = [];
1541
+ const relativePath = path3.relative(process.cwd(), filePath);
1542
+ if (this.defQuery) {
1543
+ let lines;
1544
+ const lineAt = (row) => (lines ??= content.split("\n"))[row] ?? "";
1545
+ for (const match of this.queryMatches(this.defQuery, tree.rootNode)) {
1546
+ const symbol = this.parseDefMatch(match, relativePath, lineAt);
1547
+ if (symbol)
1548
+ symbols.push(symbol);
1549
+ }
1550
+ }
1551
+ if (this.refQuery) {
1552
+ for (const match of this.queryMatches(this.refQuery, tree.rootNode)) {
1553
+ const ref = this.parseRefMatch(match, relativePath);
1554
+ if (ref)
1555
+ refs.push(ref);
1556
+ }
1557
+ }
1558
+ return {
1559
+ symbols,
1560
+ refs,
1561
+ imports: this.extractImports(tree),
1562
+ coverage: {
1563
+ definitions: this.defQuery ? "complete" : "unavailable",
1564
+ references: this.refQuery ? "complete" : "unavailable",
1565
+ imports: this.importQuery ? "complete" : "unavailable"
1566
+ }
1567
+ };
1568
+ }
1569
+ /**
1570
+ * The import references alone (optional: only for languages with an
1571
+ * IMPORT_QUERIES entry). #4368 r1 F2: a caller that needs only imports
1572
+ * (the forward-import resolver) runs this instead of {@link extract}, whose
1573
+ * definitions pass is the cost of a large file.
1574
+ */
1575
+ // biome-ignore lint/suspicious/noExplicitAny: Tree type
1576
+ extractImports(tree) {
1577
+ const imports = [];
1578
+ if (!this.importQuery)
1579
+ return imports;
1580
+ for (const match of this.queryMatches(this.importQuery, tree.rootNode)) {
1581
+ imports.push(...parseImportMatch(match));
1582
+ }
1583
+ return imports;
1584
+ }
1585
+ queryMatches(query, rootNode) {
1586
+ try {
1587
+ return query.matches(rootNode);
1588
+ } catch (error) {
1589
+ this.client.reportWasmAbort(error);
1590
+ throw error;
1591
+ }
1592
+ }
1593
+ // biome-ignore lint/suspicious/noExplicitAny: Match type
1594
+ parseDefMatch(match, filePath, lineAt) {
1595
+ const captures = {};
1596
+ for (const capture of match.captures) {
1597
+ captures[capture.name] = {
1598
+ text: capture.node.text,
1599
+ // biome-ignore lint/suspicious/noExplicitAny: Node type
1600
+ node: capture.node
1601
+ };
1602
+ }
1603
+ let name;
1604
+ let kind;
1605
+ let params;
1606
+ let defNode;
1607
+ if (captures.funcName) {
1608
+ name = captures.funcName.text;
1609
+ kind = "function";
1610
+ params = captures.funcParams?.text;
1611
+ defNode = captures.funcDef?.node;
1612
+ } else if (captures.arrowName) {
1613
+ name = captures.arrowName.text;
1614
+ kind = "function";
1615
+ params = captures.arrowParams?.text;
1616
+ defNode = captures.arrowDef?.node;
1617
+ } else if (captures.className) {
1618
+ name = captures.className.text;
1619
+ kind = "class";
1620
+ defNode = captures.classDef?.node;
1621
+ } else if (captures.methodName) {
1622
+ name = captures.methodName.text;
1623
+ kind = "method";
1624
+ params = captures.methodParams?.text;
1625
+ defNode = captures.methodDef?.node;
1626
+ } else if (captures.interfaceName) {
1627
+ name = captures.interfaceName.text;
1628
+ kind = "interface";
1629
+ defNode = captures.interfaceDef?.node;
1630
+ } else if (captures.typeName) {
1631
+ name = captures.typeName.text;
1632
+ kind = "type";
1633
+ defNode = captures.typeDef?.node;
1634
+ } else if (captures.moduleName) {
1635
+ name = captures.moduleName.text;
1636
+ kind = "class";
1637
+ defNode = captures.moduleDef?.node;
1638
+ } else if (captures.defName) {
1639
+ name = captures.defName.text;
1640
+ kind = "type";
1641
+ defNode = captures.defDef?.node;
1642
+ } else if (captures.fieldName) {
1643
+ name = captures.fieldName.text;
1644
+ kind = "property";
1645
+ defNode = captures.fieldDef?.node;
1646
+ } else if (captures.letName) {
1647
+ name = captures.letName.text;
1648
+ kind = "variable";
1649
+ defNode = captures.letDef?.node;
1650
+ }
1651
+ if (!name || !kind || !defNode)
1652
+ return null;
1653
+ const isExported = this.isExported(defNode, lineAt);
1654
+ const signature = params ? this.extractSignature(params, kind) : void 0;
1655
+ const local = this.isFunctionLocal(defNode);
1656
+ const visibility = kind === "method" ? this.detectVisibility(defNode, name) : void 0;
1657
+ const decorators = this.extractDecorators(defNode);
1658
+ const isAsync = (kind === "function" || kind === "method") && this.isAsyncDecl(defNode);
1659
+ const docInfo = this.extractDocCommentInfo(defNode);
1660
+ return {
1661
+ id: `${filePath}:${name}`,
1662
+ name,
1663
+ kind,
1664
+ filePath,
1665
+ line: defNode.startPosition.row + 1,
1666
+ endLine: defNode.endPosition.row + 1,
1667
+ column: defNode.startPosition.column + 1,
1668
+ signature,
1669
+ isExported,
1670
+ ...local ? { local: true } : {},
1671
+ ...visibility ? { visibility } : {},
1672
+ ...decorators.length > 0 ? { decorators } : {},
1673
+ ...isAsync ? { isAsync: true } : {},
1674
+ ...docInfo ? { doc: docInfo.text, docStartLine: docInfo.startLine } : {}
1675
+ };
1676
+ }
1677
+ // Comment node kinds across grammars that use tree-sitter's conventional
1678
+ // name. Line/block comments (`//`, `/* */`, `/** */`, `#`) all parse to a
1679
+ // single "comment" node type in every grammar checked (JS/TS, Python, Go,
1680
+ // Rust, Java, Kotlin, C#, C/C++, Ruby, PHP, Swift, Lua) — no per-grammar
1681
+ // query needed, unlike decorators/annotations which vary by node shape.
1682
+ static COMMENT_NODE_KIND = "comment";
1683
+ /**
1684
+ * First sentence/line of the doc comment immediately preceding a declaration,
1685
+ * whitespace-collapsed and capped ~120 chars — the highest-signal token for an
1686
+ * agent deciding which symbol to read (#512). Structural, not per-language:
1687
+ * walks contiguous preceding-sibling `comment` nodes (same traversal shape as
1688
+ * `extractDecorators`), stopping at the nearest non-comment/non-decorator named
1689
+ * sibling, and takes the LAST contiguous comment block (the one directly above
1690
+ * the declaration — an earlier unrelated comment separated by blank lines still
1691
+ * parses as a preceding sibling, but a real gap makes it not "attached").
1692
+ * JSDoc/TSDoc block comments strip the leading/trailing block markers and
1693
+ * per-line `*` gutters; plain `//`/`#` line comments strip the marker only.
1694
+ * Returns undefined when no comment is directly attached. Returns both the
1695
+ * summarized text (`doc`) and the 1-based start line of the attached comment
1696
+ * block (`docStartLine`, #523) — readSymbol extends its returned range to that
1697
+ * line so an agent reading a symbol sees its contract, not just its body.
1698
+ */
1699
+ // biome-ignore lint/suspicious/noExplicitAny: web-tree-sitter node
1700
+ extractDocCommentInfo(declNode) {
1701
+ const isComment = (n) => !!n && n.type === _TreeSitterSymbolExtractor.COMMENT_NODE_KIND;
1702
+ const isDeco = (n) => !!n && _TreeSitterSymbolExtractor.DECORATOR_NODE_KINDS.has(n.type);
1703
+ const sameStartRow = (a, b) => a?.startPosition?.row === b?.startPosition?.row;
1704
+ let node = declNode;
1705
+ for (let hops = 0; hops < 4; hops++) {
1706
+ const parent = node.parent;
1707
+ if (!parent || !sameStartRow(parent, node))
1708
+ break;
1709
+ node = parent;
1710
+ }
1711
+ let cursor = node.previousSibling;
1712
+ while (cursor && isDeco(cursor))
1713
+ cursor = cursor.previousSibling;
1714
+ let boundaryRow = node.startPosition?.row;
1715
+ const run = [];
1716
+ while (cursor && isComment(cursor)) {
1717
+ const gapRows = boundaryRow !== void 0 && typeof cursor.endPosition?.row === "number" ? boundaryRow - cursor.endPosition.row : 0;
1718
+ if (gapRows > 1)
1719
+ break;
1720
+ run.push(cursor);
1721
+ boundaryRow = cursor.startPosition?.row;
1722
+ cursor = cursor.previousSibling;
1723
+ }
1724
+ if (run.length === 0)
1725
+ return void 0;
1726
+ run.reverse();
1727
+ const raw = run.map((n) => String(n.text ?? "")).join("\n");
1728
+ const text = this.summarizeDocComment(raw);
1729
+ if (!text)
1730
+ return void 0;
1731
+ const startLine = (run[0].startPosition?.row ?? 0) + 1;
1732
+ return { text, startLine };
1733
+ }
1734
+ static DOC_MAX_CHARS = 120;
1735
+ /** Strip comment markers, take the first sentence (or first line if no
1736
+ * sentence terminator), collapse whitespace, cap at ~120 chars. */
1737
+ summarizeDocComment(raw) {
1738
+ const cleaned = raw.replace(/^\s*\/\*\*?/, "").replace(/\*\/\s*$/, "").split(/\r?\n/).map((line) => line.replace(/^\s*(\*|\/\/\/?|#)\s?/, "").trimEnd()).filter((line) => line.trim().length > 0).join(" ").trim();
1739
+ if (!cleaned)
1740
+ return void 0;
1741
+ const sentenceMatch = cleaned.match(/^.*?[.!?](?:\s|$)/);
1742
+ let first = (sentenceMatch ? sentenceMatch[0] : cleaned).trim();
1743
+ first = first.replace(/\s+/g, " ");
1744
+ if (first.length > _TreeSitterSymbolExtractor.DOC_MAX_CHARS) {
1745
+ first = `${first.slice(0, _TreeSitterSymbolExtractor.DOC_MAX_CHARS - 1).trimEnd()}\u2026`;
1746
+ }
1747
+ return first || void 0;
1748
+ }
1749
+ /**
1750
+ * Structural async/suspend detection: an `async` keyword node (Python/JS/TS
1751
+ * have it as a direct child of the declaration) or `async`/`suspend` inside a
1752
+ * `*modifiers*` container (Rust `function_modifiers`, Kotlin/Java/C#
1753
+ * `modifiers`). Conservative — a grammar that spells it differently just
1754
+ * yields false (no false positives).
1755
+ */
1756
+ // biome-ignore lint/suspicious/noExplicitAny: web-tree-sitter node
1757
+ isAsyncDecl(node) {
1758
+ const isAsyncTok = (n) => !!n && (n.type === "async" || n.type === "suspend" || /modifier/.test(String(n.type)) && /^(?:async|suspend)$/.test(String(n.text ?? "").trim()));
1759
+ for (const child of node.children ?? []) {
1760
+ if (isAsyncTok(child))
1761
+ return true;
1762
+ if (/modifiers/.test(String(child?.type))) {
1763
+ for (const gc of child.children ?? []) {
1764
+ if (isAsyncTok(gc))
1765
+ return true;
1766
+ }
1767
+ }
1768
+ }
1769
+ return false;
1770
+ }
1771
+ // Decorator/attribute/annotation node kinds across grammars. Python/TS/JS use
1772
+ // `decorator`; Rust `attribute_item`; Java/Kotlin/C# `marker_annotation` /
1773
+ // `annotation` (often nested inside a `modifiers` container).
1774
+ static DECORATOR_NODE_KINDS = /* @__PURE__ */ new Set([
1775
+ "decorator",
1776
+ "attribute_item",
1777
+ "marker_annotation",
1778
+ "annotation"
1779
+ ]);
1780
+ // Containers that hold annotations as children (Java/Kotlin `modifiers`).
1781
+ static MODIFIERS_CONTAINER_KINDS = /* @__PURE__ */ new Set(["modifiers"]);
1782
+ /**
1783
+ * Decorators/attributes/annotations attached to a declaration node, in source
1784
+ * order. Structural (tree-sitter), not text heuristics, so it handles the three
1785
+ * placement shapes seen across grammars:
1786
+ * - preceding siblings: Python (`decorated_definition` children), Rust
1787
+ * (`attribute_item`), TS methods (`decorator`);
1788
+ * - own children: TS class decorators;
1789
+ * - nested in a `modifiers` container: Java/Kotlin/C# annotations.
1790
+ * Languages without these node kinds simply yield none.
1791
+ */
1792
+ // biome-ignore lint/suspicious/noExplicitAny: web-tree-sitter node
1793
+ extractDecorators(node) {
1794
+ const isDeco = (n) => !!n && _TreeSitterSymbolExtractor.DECORATOR_NODE_KINDS.has(n.type);
1795
+ const text = (n) => {
1796
+ const first = String(n?.text ?? "").split(/\r?\n/, 1)[0]?.trim() ?? "";
1797
+ return first.length > 120 ? `${first.slice(0, 117)}\u2026` : first;
1798
+ };
1799
+ const out = [];
1800
+ const above = [];
1801
+ for (let sib = node.previousSibling; sib; sib = sib.previousSibling) {
1802
+ if (isDeco(sib))
1803
+ above.push(text(sib));
1804
+ else if (sib.isNamed)
1805
+ break;
1806
+ }
1807
+ out.push(...above.reverse());
1808
+ for (const child of node.children ?? []) {
1809
+ if (isDeco(child))
1810
+ out.push(text(child));
1811
+ else if (_TreeSitterSymbolExtractor.MODIFIERS_CONTAINER_KINDS.has(child?.type)) {
1812
+ for (const gc of child.children ?? []) {
1813
+ if (isDeco(gc))
1814
+ out.push(text(gc));
1815
+ }
1816
+ }
1817
+ }
1818
+ return [...new Set(out.filter(Boolean))].slice(0, 8);
1819
+ }
1820
+ // biome-ignore lint/suspicious/noExplicitAny: Match type
1821
+ parseRefMatch(match, filePath) {
1822
+ let name;
1823
+ let refNode;
1824
+ let referenceKind = "unknown";
1825
+ for (const capture of match.captures) {
1826
+ const captureName = String(capture.name);
1827
+ if (captureName.endsWith("Ident") || captureName.endsWith("Method") || captureName.endsWith("Field")) {
1828
+ name = capture.node.text;
1829
+ refNode = capture.node;
1830
+ if (captureName.startsWith("type"))
1831
+ referenceKind = "type";
1832
+ else if (captureName.startsWith("call") || captureName.startsWith("new")) {
1833
+ referenceKind = "call";
1834
+ }
1835
+ }
1836
+ if (captureName.endsWith("Ref") && !refNode) {
1837
+ refNode = capture.node;
1838
+ if (captureName.startsWith("type"))
1839
+ referenceKind = "type";
1840
+ else if (captureName.startsWith("call") || captureName.startsWith("new")) {
1841
+ referenceKind = "call";
1842
+ }
1843
+ }
1844
+ }
1845
+ if (!name || !refNode)
1846
+ return null;
1847
+ return {
1848
+ symbolId: `${filePath}:${name}`,
1849
+ // Will be resolved later
1850
+ symbolName: name,
1851
+ filePath,
1852
+ line: refNode.startPosition.row + 1,
1853
+ column: refNode.startPosition.column + 1,
1854
+ referenceKind
1855
+ };
1856
+ }
1857
+ // biome-ignore lint/suspicious/noExplicitAny: Node type
1858
+ isExported(node, lineAt) {
1859
+ const line = lineAt(node.startPosition.row);
1860
+ return /^\s*export\b/.test(line) || this.hasExportModifier(node);
1861
+ }
1862
+ // biome-ignore lint/suspicious/noExplicitAny: Node type
1863
+ hasExportModifier(node) {
1864
+ let current = node.parent;
1865
+ while (current) {
1866
+ if (current.type === "statement_block")
1867
+ return false;
1868
+ if (current.type === "export_statement" || current.type === "export_declaration") {
1869
+ return true;
1870
+ }
1871
+ current = current.parent;
1872
+ }
1873
+ return false;
1874
+ }
1875
+ // biome-ignore lint/suspicious/noExplicitAny: Node type
1876
+ isFunctionLocal(node) {
1877
+ let current = node.parent;
1878
+ while (current) {
1879
+ if (current.type === "statement_block")
1880
+ return true;
1881
+ current = current.parent;
1882
+ }
1883
+ return false;
1884
+ }
1885
+ // biome-ignore lint/suspicious/noExplicitAny: Node type
1886
+ detectVisibility(node, nameText) {
1887
+ if (nameText.startsWith("#"))
1888
+ return "private";
1889
+ for (const child of node?.children ?? []) {
1890
+ if (child?.type === "accessibility_modifier") {
1891
+ if (child.text === "private")
1892
+ return "private";
1893
+ if (child.text === "protected")
1894
+ return "protected";
1895
+ return void 0;
1896
+ }
1897
+ }
1898
+ return void 0;
1899
+ }
1900
+ extractSignature(paramsText, kind) {
1901
+ if (kind === "function" || kind === "method") {
1902
+ return paramsText.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/.*$/gm, "").replace(/\s+/g, " ").trim();
1903
+ }
1904
+ return void 0;
1905
+ }
1906
+ };
1907
+
1908
+ // dist/clients/blocker-freshness.js
1909
+ var DEPENDENCY_DRIFT_MAX_DELIVERIES = 3;
1910
+ var SELF_DRIFT_HASH_BUDGET_BYTES = 8 * 1024 * 1024;
1911
+ var MAX_IMPLICIT_SCOPE_PARSES = 32;
1912
+ var GLOBAL_SCOPE_ROLE_MEMO_ENTRIES = 1024;
1913
+ var globalScopeRoleMemo = new BoundedLruCache(GLOBAL_SCOPE_ROLE_MEMO_ENTRIES);
1914
+ function roleByTextOf(filePath) {
1915
+ try {
1916
+ return globalScopeRoleByText(fs4.readFileSync(filePath, "utf8"));
1917
+ } catch {
1918
+ return void 0;
1919
+ }
1920
+ }
1921
+ function createImplicitScopeCheck(runtime, cwd) {
1922
+ let receipts;
1923
+ let receiptsDropped = false;
1924
+ const roles = /* @__PURE__ */ new Map();
1925
+ let parses = 0;
1926
+ const roleOf = (other) => {
1927
+ const known = roles.get(other);
1928
+ if (known !== void 0)
1929
+ return known;
1930
+ let stat;
1931
+ try {
1932
+ stat = fs4.statSync(other);
1933
+ } catch {
1934
+ roles.set(other, "none");
1935
+ return "none";
1936
+ }
1937
+ const memo = globalScopeRoleMemo.get(other);
1938
+ let role;
1939
+ if (memo?.mtimeMs === stat.mtimeMs && memo.ctimeMs === stat.ctimeMs && memo.size === stat.size) {
1940
+ role = memo.role;
1941
+ } else {
1942
+ const byName = globalScopeRoleByName(other);
1943
+ const byText = byName ? void 0 : roleByTextOf(other);
1944
+ if (byName ?? byText) {
1945
+ role = byName ?? byText;
1946
+ } else if (parses >= MAX_IMPLICIT_SCOPE_PARSES) {
1947
+ return "unknown";
1948
+ } else {
1949
+ parses += 1;
1950
+ role = classifyJsTsGlobalScope(other);
1951
+ }
1952
+ globalScopeRoleMemo.set(other, {
1953
+ mtimeMs: stat.mtimeMs,
1954
+ ctimeMs: stat.ctimeMs,
1955
+ size: stat.size,
1956
+ role
1957
+ });
1958
+ }
1959
+ roles.set(other, role);
1960
+ return role;
1961
+ };
1962
+ const rootKey = normalizeMapKey(nodePath.resolve(cwd));
1963
+ const rootPrefix = rootKey.endsWith("/") ? rootKey : `${rootKey}/`;
1964
+ const inRoot = (file) => file === rootKey || file.startsWith(rootPrefix);
1965
+ let scanned;
1966
+ const feeding = [];
1967
+ let newestUnknownTs = Number.NEGATIVE_INFINITY;
1968
+ const scanBackTo = (all, recordedAtMs) => {
1969
+ scanned ??= all.length;
1970
+ while (scanned > 0 && all[scanned - 1].ts > recordedAtMs) {
1971
+ const receipt = all[--scanned];
1972
+ if (!inRoot(receipt.filePath))
1973
+ continue;
1974
+ const role = roleOf(receipt.filePath);
1975
+ if (role === "feeds")
1976
+ feeding.push(receipt);
1977
+ else if (role === "unknown") {
1978
+ newestUnknownTs = Math.max(newestUnknownTs, receipt.ts);
1979
+ }
1980
+ }
1981
+ };
1982
+ const feedsGlobalScope = (other) => roles.get(other) === "feeds";
1983
+ return (filePath, recordedAtMs) => {
1984
+ const key = normalizeMapKey(filePath);
1985
+ const goFile = isGoSourceFile(key);
1986
+ const inScope = goFile ? goPackagePeersOf(key) : implicitScopeOf(key, feedsGlobalScope);
1987
+ if (!inScope)
1988
+ return { drifted: [], truncated: false };
1989
+ if (receipts === void 0) {
1990
+ const coordinator = runtime;
1991
+ receipts = coordinator.getMutationsSince?.(0) ?? [];
1992
+ receiptsDropped = (coordinator.droppedMutationReceiptCount ?? 0) > 0;
1993
+ }
1994
+ let drifted;
1995
+ let unknownAfter = false;
1996
+ if (goFile) {
1997
+ for (let i = receipts.length - 1; i >= 0; i--) {
1998
+ const receipt = receipts[i];
1999
+ if (receipt.ts <= recordedAtMs)
2000
+ break;
2001
+ if (inScope(receipt.filePath)) {
2002
+ drifted = receipt.filePath;
2003
+ break;
2004
+ }
2005
+ }
2006
+ } else {
2007
+ scanBackTo(receipts, recordedAtMs);
2008
+ drifted = feeding.find((receipt) => receipt.ts > recordedAtMs && inScope(receipt.filePath))?.filePath;
2009
+ unknownAfter = newestUnknownTs > recordedAtMs;
2010
+ }
2011
+ if (drifted)
2012
+ return { drifted: [drifted], truncated: false };
2013
+ const evictedAfter = receiptsDropped && (receipts.length === 0 || receipts[0].ts > recordedAtMs);
2014
+ return { drifted: [], truncated: unknownAfter || evictedAfter };
2015
+ };
2016
+ }
2017
+ var MAX_DRIFT_CHECK_IMPORTS = 128;
2018
+ var extractorCache = /* @__PURE__ */ new Map();
2019
+ function getExtractor(languageId) {
2020
+ let cached = extractorCache.get(languageId);
2021
+ if (!cached) {
2022
+ cached = (async () => {
2023
+ const client = getSharedTreeSitterClient();
2024
+ if (!client)
2025
+ return null;
2026
+ const extractor = new TreeSitterSymbolExtractor(languageId, client);
2027
+ const ok = await extractor.init();
2028
+ return ok ? extractor : null;
2029
+ })().catch(() => null);
2030
+ extractorCache.set(languageId, cached);
2031
+ }
2032
+ return cached;
2033
+ }
2034
+ var importResolutionMemo = /* @__PURE__ */ new Map();
2035
+ var importResolutionMemoTurnIndex;
2036
+ function noteImportResolutionMemoTurn(turnIndex) {
2037
+ if (turnIndex === void 0)
2038
+ return;
2039
+ if (importResolutionMemoTurnIndex !== turnIndex) {
2040
+ importResolutionMemo.clear();
2041
+ importResolutionMemoTurnIndex = turnIndex;
2042
+ }
2043
+ }
2044
+ async function resolveForwardImportsMemoized(cwd, filePath, resolveForwardImports) {
2045
+ const sig = await statSignature(filePath);
2046
+ if (sig === void 0) {
2047
+ try {
2048
+ return await resolveForwardImports(cwd, filePath);
2049
+ } catch {
2050
+ return [];
2051
+ }
2052
+ }
2053
+ const cached = importResolutionMemo.get(filePath);
2054
+ if (cached && cached.mtimeMs === sig.mtimeMs && cached.size === sig.size)
2055
+ return cached.imports;
2056
+ let imports;
2057
+ try {
2058
+ imports = await resolveForwardImports(cwd, filePath);
2059
+ } catch {
2060
+ imports = [];
2061
+ }
2062
+ importResolutionMemo.set(filePath, {
2063
+ mtimeMs: sig.mtimeMs,
2064
+ size: sig.size,
2065
+ imports
2066
+ });
2067
+ return imports;
2068
+ }
2069
+ var FORWARD_IMPORT_SOURCE_MEMO_ENTRIES = 1024;
2070
+ var JS_TS_LANGUAGES = /* @__PURE__ */ new Set(["typescript", "tsx", "javascript"]);
2071
+ var RELATIVE_SPECIFIER = /(["'])(\.{1,2}\/(?:(?!\1)[^\n])*)\1/g;
2072
+ var DEPENDENCY_CALL = /\bimport\s*\(|\brequire\s*\(|@import\b|\bdeclare\s+module\s*["']|\/\/\/\s*<reference\s+(?:path|types)/;
2073
+ function holdsUncapturedDependency(content, sources) {
2074
+ if (DEPENDENCY_CALL.test(content))
2075
+ return true;
2076
+ const captured = new Set(sources);
2077
+ for (const match of content.matchAll(RELATIVE_SPECIFIER)) {
2078
+ if (!captured.has(match[2]))
2079
+ return true;
2080
+ }
2081
+ return false;
2082
+ }
2083
+ var forwardImportSourceMemo = new BoundedLruCache(FORWARD_IMPORT_SOURCE_MEMO_ENTRIES);
2084
+ var forwardImportParses = 0;
2085
+ function _getForwardImportParsesForTests() {
2086
+ return forwardImportParses;
2087
+ }
2088
+ async function forwardImportSources(filePath, languageId) {
2089
+ let stat;
2090
+ try {
2091
+ stat = fs4.statSync(filePath);
2092
+ } catch {
2093
+ return void 0;
2094
+ }
2095
+ const key = normalizeMapKey(filePath);
2096
+ const memo = forwardImportSourceMemo.get(key);
2097
+ if (memo?.mtimeMs === stat.mtimeMs && memo.ctimeMs === stat.ctimeMs && memo.size === stat.size) {
2098
+ return memo;
2099
+ }
2100
+ const client = getSharedTreeSitterClient();
2101
+ if (!client)
2102
+ return void 0;
2103
+ const extractor = await getExtractor(languageId);
2104
+ if (!extractor)
2105
+ return void 0;
2106
+ let content;
2107
+ try {
2108
+ content = fs4.readFileSync(filePath, "utf-8");
2109
+ } catch {
2110
+ return void 0;
2111
+ }
2112
+ const outcome = await client.withParsedTree(
2113
+ filePath,
2114
+ languageId,
2115
+ content,
2116
+ // Imports only (#4368 r1 F2): the definitions pass of a full extract is
2117
+ // what made a large file cost seconds.
2118
+ (tree) => extractor.extractImports(tree),
2119
+ "blocker-freshness"
2120
+ );
2121
+ if (!outcome.parsed)
2122
+ return void 0;
2123
+ forwardImportParses++;
2124
+ const sources = [...new Set(outcome.value.map((ref) => ref.source))];
2125
+ const entry = {
2126
+ mtimeMs: stat.mtimeMs,
2127
+ ctimeMs: stat.ctimeMs,
2128
+ size: stat.size,
2129
+ sources,
2130
+ unresolved: memo?.unresolved ?? /* @__PURE__ */ new Set(),
2131
+ uncaptured: JS_TS_LANGUAGES.has(languageId) && holdsUncapturedDependency(content, sources)
2132
+ };
2133
+ forwardImportSourceMemo.set(key, entry);
2134
+ return entry;
2135
+ }
2136
+ async function extractForwardImports(cwd, filePath) {
2137
+ const languageId = resolveTreeSitterLanguage(filePath);
2138
+ if (!languageId)
2139
+ return { targets: [], unresolved: [], complete: false };
2140
+ const entry = await forwardImportSources(filePath, languageId);
2141
+ if (!entry)
2142
+ return { targets: [], unresolved: [], complete: false };
2143
+ const resolved = /* @__PURE__ */ new Set();
2144
+ const unresolved = /* @__PURE__ */ new Set();
2145
+ for (const source of entry.sources) {
2146
+ const targets = resolveImportToFiles(cwd, filePath, languageId, source);
2147
+ if (targets.length === 0)
2148
+ unresolved.add(source);
2149
+ for (const target of targets) {
2150
+ if (entry.unresolved.has(source))
2151
+ notePathAppeared(target);
2152
+ resolved.add(target);
2153
+ }
2154
+ }
2155
+ entry.unresolved = unresolved;
2156
+ return {
2157
+ targets: [...resolved],
2158
+ unresolved: [...unresolved],
2159
+ complete: !entry.uncaptured
2160
+ };
2161
+ }
2162
+ function extractForwardImportPaths(cwd, filePath) {
2163
+ return extractForwardImports(cwd, filePath).then(({ targets }) => targets);
2164
+ }
2165
+ async function statSignature(filePath) {
2166
+ try {
2167
+ const stat = await fs4.promises.stat(filePath);
2168
+ return { mtimeMs: stat.mtimeMs, size: stat.size };
2169
+ } catch {
2170
+ return void 0;
2171
+ }
2172
+ }
2173
+ async function statMtimeMs(filePath) {
2174
+ try {
2175
+ const stat = await fs4.promises.stat(filePath);
2176
+ return stat.mtimeMs;
2177
+ } catch {
2178
+ return void 0;
2179
+ }
2180
+ }
2181
+ async function detectSelfDrift(args) {
2182
+ const boundOptions = (label) => ({
2183
+ ms: HOOK_WALL_BUDGET_MS.turn_end,
2184
+ signal: args.signal,
2185
+ hook: "turn_end",
2186
+ label
2187
+ });
2188
+ const stat = await bounded(fs4.promises.stat(args.filePath), boundOptions("selfDriftStat"));
2189
+ if (stat === void 0)
2190
+ return { verdict: "unverifiable", unverifiableReason: "stat-unavailable" };
2191
+ if (args.recordedSize === void 0)
2192
+ return { verdict: "unverifiable", unverifiableReason: "missing-baseline" };
2193
+ if (stat.size !== args.recordedSize)
2194
+ return { verdict: "drift" };
2195
+ if (args.recordedHash === void 0)
2196
+ return { verdict: "unverifiable", unverifiableReason: "missing-baseline" };
2197
+ if (stat.size > args.budget.bytesLeft) {
2198
+ args.budget.exhausted = true;
2199
+ return {
2200
+ verdict: "unverifiable",
2201
+ unverifiableReason: "hash-budget-exhausted"
2202
+ };
2203
+ }
2204
+ const content = await bounded(fs4.promises.readFile(args.filePath), boundOptions("selfDriftHash"));
2205
+ if (content === void 0)
2206
+ return { verdict: "unverifiable", unverifiableReason: "hash-unavailable" };
2207
+ args.budget.bytesLeft -= content.byteLength;
2208
+ const hash = hashContentBytes(content);
2209
+ return { verdict: hash === args.recordedHash ? "unchanged" : "drift" };
2210
+ }
2211
+ async function collectForwardImportMtimes(cwd, filePath, resolveForwardImports = extractForwardImportPaths, turnIndex) {
2212
+ noteImportResolutionMemoTurn(turnIndex);
2213
+ let imports = [];
2214
+ try {
2215
+ imports = await resolveForwardImportsMemoized(cwd, filePath, resolveForwardImports);
2216
+ } catch {
2217
+ imports = [];
2218
+ }
2219
+ const truncated = imports.length > MAX_DRIFT_CHECK_IMPORTS;
2220
+ const out = [];
2221
+ for (const dep of imports.slice(0, MAX_DRIFT_CHECK_IMPORTS)) {
2222
+ const mtimeMs = await statMtimeMs(dep);
2223
+ if (mtimeMs !== void 0)
2224
+ out.push({ path: dep, mtimeMs });
2225
+ }
2226
+ return { mtimes: out, truncated };
2227
+ }
2228
+ async function detectDrift(cwd, filePath, recordedAtMs, resolveForwardImports, turnIndex, implicitScope, skipOwnFile = false) {
2229
+ const drifted = [];
2230
+ if (!skipOwnFile) {
2231
+ const ownFreshness = freshnessFromMtime({
2232
+ mtimeMs: await statMtimeMs(filePath),
2233
+ referenceMs: recordedAtMs
2234
+ });
2235
+ if (ownFreshness.verdict === "stale")
2236
+ drifted.push(filePath);
2237
+ }
2238
+ const { mtimes, truncated } = await collectForwardImportMtimes(cwd, filePath, resolveForwardImports, turnIndex);
2239
+ for (const { path: depPath, mtimeMs } of mtimes) {
2240
+ const verdict = freshnessFromMtime({
2241
+ mtimeMs,
2242
+ referenceMs: recordedAtMs
2243
+ });
2244
+ if (verdict.verdict === "stale")
2245
+ drifted.push(depPath);
2246
+ }
2247
+ const implicit = implicitScope(filePath, recordedAtMs);
2248
+ drifted.push(...implicit.drifted);
2249
+ return { drifted, truncated: truncated || implicit.truncated };
2250
+ }
2251
+ function isEligibleForDriftCheck(entry) {
2252
+ if (entry.stale)
2253
+ return false;
2254
+ if (entry.recordedAtMs === void 0)
2255
+ return false;
2256
+ return entry.sources !== void 0 && entry.sources.length > 0;
2257
+ }
2258
+ function isAllLspSourced(sources) {
2259
+ return sources !== void 0 && sources.length > 0 && sources.every((source) => source === "lsp");
2260
+ }
2261
+ function canSubsumeLspWidgetRow(entry) {
2262
+ return isEligibleForDriftCheck(entry) && isAllLspSourced(entry.sources);
2263
+ }
2264
+ async function sweepInlineBlockerFreshness(runtime, cwd, options) {
2265
+ const counts = {
2266
+ total: 0,
2267
+ kept: 0,
2268
+ revalidated: 0,
2269
+ alreadyStale: 0,
2270
+ truncatedImports: 0,
2271
+ selfHealed: 0,
2272
+ selfUnverifiable: 0,
2273
+ hashBudgetExhausted: 0
2274
+ };
2275
+ const resolveForwardImports = options?.resolveForwardImports ?? extractForwardImportPaths;
2276
+ const implicitScope = createImplicitScopeCheck(runtime, cwd);
2277
+ let turnIndex;
2278
+ try {
2279
+ turnIndex = runtime.turnIndex;
2280
+ } catch {
2281
+ turnIndex = void 0;
2282
+ }
2283
+ let inlineEntries;
2284
+ try {
2285
+ inlineEntries = runtime.getInlineBlockersSnapshot();
2286
+ } catch {
2287
+ return counts;
2288
+ }
2289
+ const population = inlineEntries.map((entry) => ({
2290
+ filePath: entry.filePath,
2291
+ stale: entry.stale ?? false,
2292
+ recordedAtMs: entry.recordedAtMs,
2293
+ sources: entry.sources,
2294
+ staleReason: entry.staleReason,
2295
+ recordedSize: entry.recordedSize,
2296
+ recordedHash: entry.recordedHash,
2297
+ demote: () => runtime.markInlineBlockerStale(entry.filePath, "dependency-drift"),
2298
+ setSelfDrift: (isSelfDrift) => runtime.setInlineBlockerSelfDriftStale(entry.filePath, isSelfDrift)
2299
+ }));
2300
+ const inlineByKey = /* @__PURE__ */ new Map();
2301
+ for (const entry of population) {
2302
+ inlineByKey.set(normalizeEphemeralMapKey(entry.filePath), entry);
2303
+ }
2304
+ for (const extra of options?.additionalEntries ?? []) {
2305
+ const key = normalizeEphemeralMapKey(extra.filePath);
2306
+ const inlineEntry = inlineByKey.get(key);
2307
+ if (inlineEntry && canSubsumeLspWidgetRow(inlineEntry)) {
2308
+ const demoteInline = inlineEntry.demote;
2309
+ const demoteWidget = extra.demote;
2310
+ inlineEntry.demote = () => {
2311
+ const inlineChanged = demoteInline();
2312
+ const widgetChanged = demoteWidget();
2313
+ return inlineChanged || widgetChanged;
2314
+ };
2315
+ continue;
2316
+ }
2317
+ population.push({
2318
+ filePath: extra.filePath,
2319
+ stale: false,
2320
+ recordedAtMs: extra.recordedAtMs,
2321
+ sources: ["lsp"],
2322
+ demote: extra.demote,
2323
+ // A widget row is pure-LSP by construction, so it takes the import
2324
+ // axis and never reaches the self axis. No `setSelfDrift` (#2982):
2325
+ // the widget store has no re-arming self-drift setter, and an entry
2326
+ // without one is not eligible for that axis.
2327
+ staleReason: void 0,
2328
+ recordedSize: void 0,
2329
+ recordedHash: void 0
2330
+ });
2331
+ }
2332
+ counts.total = population.length;
2333
+ const hashBudget = {
2334
+ bytesLeft: SELF_DRIFT_HASH_BUDGET_BYTES,
2335
+ exhausted: false
2336
+ };
2337
+ for (const entry of population) {
2338
+ try {
2339
+ const selfDriftDemoted = entry.stale && entry.staleReason === "self-drift";
2340
+ if (entry.stale && !selfDriftDemoted) {
2341
+ counts.alreadyStale += 1;
2342
+ continue;
2343
+ }
2344
+ if (entry.recordedAtMs === void 0) {
2345
+ counts.kept += 1;
2346
+ continue;
2347
+ }
2348
+ const recordedSources = entry.sources !== void 0 && entry.sources.length > 0 ? entry.sources : void 0;
2349
+ if (recordedSources === void 0) {
2350
+ counts.kept += 1;
2351
+ continue;
2352
+ }
2353
+ const setSelfDrift = entry.setSelfDrift;
2354
+ const isLspSourced = isAllLspSourced(recordedSources);
2355
+ let ownVerdict;
2356
+ if (setSelfDrift) {
2357
+ const hashBudgetWasExhausted = hashBudget.exhausted;
2358
+ const selfDrift = await bounded(detectSelfDrift({
2359
+ filePath: entry.filePath,
2360
+ recordedSize: entry.recordedSize,
2361
+ recordedHash: entry.recordedHash,
2362
+ signal: options?.signal,
2363
+ budget: hashBudget
2364
+ }), {
2365
+ ms: HOOK_WALL_BUDGET_MS.turn_end,
2366
+ signal: options?.signal,
2367
+ hook: "turn_end",
2368
+ label: "detectSelfDrift"
2369
+ }) ?? {
2370
+ verdict: "unverifiable",
2371
+ unverifiableReason: "bound-expired"
2372
+ };
2373
+ ownVerdict = selfDrift.verdict;
2374
+ if (ownVerdict === "unverifiable") {
2375
+ counts.selfUnverifiable += 1;
2376
+ const reason = selfDrift.unverifiableReason ?? (hashBudgetWasExhausted || hashBudget.exhausted ? "hash-budget-exhausted" : "hash-unavailable");
2377
+ recordDegradationOnce({
2378
+ kind: "self-drift-unverifiable",
2379
+ subject: `inline-blocker:${toRunnerDisplayPath(cwd, entry.filePath)}#${reason}`,
2380
+ reason: `the self-drift check was unverifiable: ${reason}`
2381
+ });
2382
+ if (reason === "hash-budget-exhausted") {
2383
+ recordDegradationOnce({
2384
+ kind: "self-drift-hash-budget-exhausted",
2385
+ subject: `inline-blocker:${toRunnerDisplayPath(cwd, entry.filePath)}`,
2386
+ reason: "the aggregate self-drift hash budget was exhausted"
2387
+ });
2388
+ }
2389
+ }
2390
+ }
2391
+ if (!isLspSourced) {
2392
+ if (!setSelfDrift || ownVerdict === void 0) {
2393
+ counts.kept += 1;
2394
+ continue;
2395
+ }
2396
+ if (ownVerdict === "unverifiable") {
2397
+ if (selfDriftDemoted)
2398
+ counts.alreadyStale += 1;
2399
+ else
2400
+ counts.kept += 1;
2401
+ continue;
2402
+ }
2403
+ const shouldDemote = ownVerdict === "drift";
2404
+ const transitioned = setSelfDrift(shouldDemote);
2405
+ if (shouldDemote) {
2406
+ if (transitioned)
2407
+ counts.revalidated += 1;
2408
+ else
2409
+ counts.alreadyStale += 1;
2410
+ } else if (transitioned) {
2411
+ counts.selfHealed += 1;
2412
+ } else {
2413
+ counts.kept += 1;
2414
+ }
2415
+ continue;
2416
+ }
2417
+ let contentDecidedOwnFile = false;
2418
+ if (setSelfDrift !== void 0 && ownVerdict !== void 0 && entry.recordedSize !== void 0) {
2419
+ if (ownVerdict === "drift") {
2420
+ const transitioned = setSelfDrift(true);
2421
+ if (transitioned)
2422
+ counts.revalidated += 1;
2423
+ else
2424
+ counts.alreadyStale += 1;
2425
+ continue;
2426
+ }
2427
+ if (ownVerdict === "unchanged") {
2428
+ contentDecidedOwnFile = true;
2429
+ const transitioned = setSelfDrift(false);
2430
+ if (transitioned)
2431
+ counts.selfHealed += 1;
2432
+ } else {
2433
+ if (selfDriftDemoted) {
2434
+ counts.alreadyStale += 1;
2435
+ continue;
2436
+ }
2437
+ }
2438
+ }
2439
+ const skipOwnFile = contentDecidedOwnFile;
2440
+ const { drifted, truncated } = await detectDrift(cwd, entry.filePath, entry.recordedAtMs, resolveForwardImports, turnIndex, implicitScope, skipOwnFile);
2441
+ if (truncated)
2442
+ counts.truncatedImports += 1;
2443
+ if (drifted.length > 0) {
2444
+ entry.demote();
2445
+ counts.revalidated += 1;
2446
+ } else {
2447
+ counts.kept += 1;
2448
+ }
2449
+ } catch {
2450
+ counts.kept += 1;
2451
+ }
2452
+ }
2453
+ counts.hashBudgetExhausted = hashBudget.exhausted ? 1 : 0;
2454
+ return counts;
2455
+ }
2456
+
2457
+ export {
2458
+ getRunnerTimeoutFloorMs,
2459
+ RUNTIME_CONFIG,
2460
+ scanDocumentContent,
2461
+ lineTextAt,
2462
+ exceedsLspSyncLimits,
2463
+ loadAstGrepNapi,
2464
+ isGoSourceFile,
2465
+ goPackageFiles,
2466
+ implicitScopeOf,
2467
+ goPackageChangedAt,
2468
+ feedsJsTsGlobalScope,
2469
+ pathBirthtimeMs,
2470
+ jsTsCandidatePaths,
2471
+ resolveAliasedImport,
2472
+ resolveProjectReferenceImport,
2473
+ resolveWorkspacePackageImport,
2474
+ importSourceNameParts,
2475
+ fileAnswerNames,
2476
+ resolveImportToFiles,
2477
+ symbolExtractionGrammar,
2478
+ TreeSitterSymbolExtractor,
2479
+ DEPENDENCY_DRIFT_MAX_DELIVERIES,
2480
+ _getForwardImportParsesForTests,
2481
+ extractForwardImports,
2482
+ extractForwardImportPaths,
2483
+ collectForwardImportMtimes,
2484
+ sweepInlineBlockerFreshness
2485
+ };