pi-lens 4.4.2 → 4.4.4

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 (143) hide show
  1. package/CHANGELOG.md +306 -0
  2. package/README.md +13 -1
  3. package/dist/{chunk-VITUCP5A.js → chunk-24AKHFGP.js} +9 -7
  4. package/dist/{chunk-JSQFTSC6.js → chunk-2FN63LPV.js} +11 -11
  5. package/dist/{chunk-CF24OIYI.js → chunk-2KXTHF3M.js} +20 -20
  6. package/dist/{chunk-ESBQHFMJ.js → chunk-3DA2JDOL.js} +543 -349
  7. package/dist/{chunk-RWWYJ623.js → chunk-3KAZU3VR.js} +1 -1
  8. package/dist/chunk-3PTHXJXR.js +28 -0
  9. package/dist/chunk-3QED2P4V.js +31 -0
  10. package/dist/{chunk-N2H3ZPZY.js → chunk-3RKP3FMS.js} +1 -0
  11. package/dist/{chunk-XVF2VVXP.js → chunk-5HSRT26B.js} +2 -2
  12. package/dist/{chunk-XKIZ2HNN.js → chunk-5IUSNGOC.js} +18 -16
  13. package/dist/{chunk-EJIUXPBX.js → chunk-5OFV52AM.js} +1 -1
  14. package/dist/{chunk-AW7R2GWG.js → chunk-5VSF4UUQ.js} +12 -7
  15. package/dist/{chunk-NW7BOILN.js → chunk-5WRPDP2A.js} +18 -18
  16. package/dist/{chunk-7ULNCDCO.js → chunk-6DLWKFEX.js} +35 -34
  17. package/dist/{chunk-WOA4LN2R.js → chunk-7D6L4MTX.js} +2 -2
  18. package/dist/{chunk-GAEGEPOC.js → chunk-7HXE67BN.js} +2 -2
  19. package/dist/chunk-AGSS7277.js +84 -0
  20. package/dist/{chunk-R3PCY3YS.js → chunk-AMERCH6V.js} +13 -13
  21. package/dist/{chunk-WU567RSC.js → chunk-ATKJFDQN.js} +14 -10
  22. package/dist/{chunk-VSSBEUFT.js → chunk-AWSCPCN2.js} +16 -16
  23. package/dist/{chunk-VCHXCQFG.js → chunk-BWD5EPKO.js} +3 -3
  24. package/dist/{chunk-ODBNXWT4.js → chunk-CT4MN5IU.js} +1271 -262
  25. package/dist/{chunk-34WSVGEM.js → chunk-CUHSHSB6.js} +83 -5
  26. package/dist/{chunk-CHOW74WE.js → chunk-CYRKQRPM.js} +7 -10
  27. package/dist/{chunk-Q7DUK4LX.js → chunk-DEL2U6CM.js} +5 -5
  28. package/dist/{chunk-6C7JWPCP.js → chunk-DGUKIYSI.js} +26 -23
  29. package/dist/{chunk-PHDMFAKM.js → chunk-DUO2TU77.js} +2 -2
  30. package/dist/{chunk-MRXKYPCS.js → chunk-EBC36LNN.js} +2 -2
  31. package/dist/chunk-ED36RF6Y.js +17 -0
  32. package/dist/{chunk-76MWC2K6.js → chunk-EUXZEFTV.js} +90 -97
  33. package/dist/{chunk-QOZXJ4NA.js → chunk-FM4RDMKT.js} +11 -8
  34. package/dist/{chunk-66VMUL7Q.js → chunk-GAQ7OQG6.js} +31 -28
  35. package/dist/{chunk-Q6ZWTCLY.js → chunk-GL5LUMZE.js} +23 -24
  36. package/dist/{chunk-BKE7E7TC.js → chunk-GMX5OS7B.js} +9 -9
  37. package/dist/{chunk-ZHFZWTZV.js → chunk-GSLNCYGG.js} +11 -11
  38. package/dist/{chunk-ARJ6PLFH.js → chunk-GSM5UU7A.js} +26 -34
  39. package/dist/{chunk-724UL2TJ.js → chunk-GXFV6MYU.js} +3 -3
  40. package/dist/chunk-HAD7QRQI.js +30 -0
  41. package/dist/{chunk-QOBUHWHX.js → chunk-HRNHZA3N.js} +6 -6
  42. package/dist/{chunk-VWCXW2E7.js → chunk-HWCCCQNX.js} +1 -1
  43. package/dist/{chunk-7DYBLXYA.js → chunk-HYGZEMX6.js} +3 -3
  44. package/dist/chunk-IJYGIDF4.js +186 -0
  45. package/dist/{chunk-4W4VLAPJ.js → chunk-IQWN5JCP.js} +11 -11
  46. package/dist/{chunk-GZYBXISR.js → chunk-IUE7SSKV.js} +9 -9
  47. package/dist/{chunk-IBGIOBEE.js → chunk-IWDLU6K3.js} +68 -5
  48. package/dist/{chunk-XCJN5IJU.js → chunk-IYNJ6YPZ.js} +4 -4
  49. package/dist/{chunk-JAU72XNY.js → chunk-J64T55EI.js} +3 -3
  50. package/dist/{chunk-2BBLFX75.js → chunk-J6MPGQTS.js} +5 -5
  51. package/dist/chunk-JORED7EX.js +44 -0
  52. package/dist/{chunk-6SDEP3AJ.js → chunk-JUKMK5Y4.js} +8 -8
  53. package/dist/{chunk-IBRALRBR.js → chunk-JW3YWBVB.js} +15 -14
  54. package/dist/{chunk-L3BLXZG7.js → chunk-KAPJINKN.js} +30 -69
  55. package/dist/{chunk-2B73ZPOK.js → chunk-KN35K52N.js} +3 -3
  56. package/dist/{chunk-C34ZXZ7O.js → chunk-KUA4OJ5Y.js} +24 -11
  57. package/dist/chunk-KYUB6QDC.js +72 -0
  58. package/dist/{chunk-67WMNWEE.js → chunk-LLJNQKQW.js} +12 -10
  59. package/dist/chunk-LZSEQW6A.js +57 -0
  60. package/dist/{chunk-ZANLILYD.js → chunk-M2IFVFWU.js} +2 -2
  61. package/dist/chunk-M2UD3LPU.js +88 -0
  62. package/dist/{chunk-WOKKRCJ5.js → chunk-MBKQHGA7.js} +15 -14
  63. package/dist/{chunk-P7266HLM.js → chunk-MPNJLASA.js} +2 -2
  64. package/dist/{chunk-6GFRNVYR.js → chunk-MZGQNL3Y.js} +10 -10
  65. package/dist/{chunk-QZVW3AAK.js → chunk-N5FLEO7W.js} +33 -31
  66. package/dist/{chunk-3JNKMP3B.js → chunk-O4NWQT6I.js} +4 -4
  67. package/dist/{chunk-PFNSLWU5.js → chunk-OHKJ7PQF.js} +33 -31
  68. package/dist/{chunk-VRZP76YM.js → chunk-P63GXC37.js} +4 -1
  69. package/dist/{chunk-XTMJ7XDT.js → chunk-POMLXPMY.js} +1 -1
  70. package/dist/{chunk-QQNQ7SJW.js → chunk-QBFBRV2B.js} +10 -4
  71. package/dist/{chunk-3UUPUE3O.js → chunk-R3T7CLQ2.js} +84 -60
  72. package/dist/{chunk-23WOO7TX.js → chunk-R7YOCSNV.js} +10 -10
  73. package/dist/{chunk-2CD5RS6M.js → chunk-RKBXZN3A.js} +23 -2
  74. package/dist/{chunk-OG5UUPN7.js → chunk-RKKOYPRA.js} +14 -14
  75. package/dist/{chunk-52FUZI6K.js → chunk-RMLC67LF.js} +1 -1
  76. package/dist/{chunk-XMSXXAHW.js → chunk-ROYSX2S5.js} +2 -2
  77. package/dist/{chunk-PV6LR5P5.js → chunk-RVK72CZX.js} +9605 -14776
  78. package/dist/{chunk-FLKWCIZH.js → chunk-S2HEXIWI.js} +5 -5
  79. package/dist/{chunk-UZ3TUTRV.js → chunk-S67KYG37.js} +1 -1
  80. package/dist/{chunk-JWA5I3SR.js → chunk-SD4I7ZO4.js} +16 -18
  81. package/dist/{chunk-Z527N6YQ.js → chunk-SKAMFC7A.js} +12 -12
  82. package/dist/{chunk-MQLUAEOC.js → chunk-SRYEJNES.js} +2 -2
  83. package/dist/{chunk-BRGDSBJE.js → chunk-SYE6T2EB.js} +12 -12
  84. package/dist/{chunk-GXW6K4YJ.js → chunk-T57LYLZT.js} +1 -1
  85. package/dist/{chunk-ZXYDQ3TZ.js → chunk-T7FEBKXN.js} +48 -15
  86. package/dist/{chunk-IXXDFY73.js → chunk-TIQ2PKDW.js} +3 -3
  87. package/dist/{chunk-QILIYSJF.js → chunk-TLX72JTG.js} +1 -1
  88. package/dist/{chunk-TYM6OUIT.js → chunk-TOY6QKOH.js} +12 -12
  89. package/dist/{chunk-IZSHAIJ7.js → chunk-TRETHTQO.js} +12 -12
  90. package/dist/{chunk-3VPVG5SU.js → chunk-U44DJXQP.js} +10 -6
  91. package/dist/{chunk-PNQDPDRC.js → chunk-UA7ZXYDR.js} +1 -1
  92. package/dist/{chunk-OXXKQCSV.js → chunk-UBOQLVT2.js} +4 -4
  93. package/dist/{chunk-QGQ5CCCG.js → chunk-UMS2MFPZ.js} +2 -2
  94. package/dist/{chunk-QHJ6DQ2R.js → chunk-US7ECLD7.js} +55 -13
  95. package/dist/{chunk-EETY4LF7.js → chunk-UZ2XCLYS.js} +8 -8
  96. package/dist/chunk-V35JG4JB.js +2667 -0
  97. package/dist/{chunk-N3X6Q4YT.js → chunk-VOOAPROD.js} +3 -3
  98. package/dist/{chunk-SAEFPSB6.js → chunk-W66O5E25.js} +21 -11
  99. package/dist/{chunk-KBG47GHP.js → chunk-WMYE35PX.js} +15 -11
  100. package/dist/{chunk-5NGR67U5.js → chunk-XBJVAEEO.js} +32 -5
  101. package/dist/chunk-XHJBS436.js +4217 -0
  102. package/dist/{chunk-GBPP5P7X.js → chunk-XTBDCR27.js} +4 -4
  103. package/dist/{chunk-4UNXBNE2.js → chunk-XTFDJI3T.js} +11 -11
  104. package/dist/{chunk-UXGETRP4.js → chunk-XYURS6EN.js} +13 -12
  105. package/dist/{chunk-RPLINGVB.js → chunk-Y6GZHWSJ.js} +6 -6
  106. package/dist/{chunk-2ZGIZPDG.js → chunk-YCWYO6TQ.js} +41 -38
  107. package/dist/{chunk-66SXUJCA.js → chunk-YH5MVY2U.js} +10 -8
  108. package/dist/{chunk-AOHZU2BM.js → chunk-YNE3RP52.js} +1 -1
  109. package/dist/{chunk-GOYRYZ2R.js → chunk-ZHH37KZL.js} +72 -20
  110. package/dist/{chunk-ZGDGW2V3.js → chunk-ZIVJBOO3.js} +2 -2
  111. package/dist/{chunk-GHB6AYCP.js → chunk-ZVUL7QYY.js} +29 -28
  112. package/dist/index.js +11559 -6213
  113. package/dist/mcp/analyze-cli.js +10 -9
  114. package/dist/mcp/cli.js +41 -38
  115. package/dist/mcp/server.js +1142 -495
  116. package/dist/mcp/worker.js +61 -57
  117. package/dist/probes/installer.js +19 -19
  118. package/dist/workers/project-snapshot-persist-worker.js +28 -9
  119. package/dist/workers/review-graph-persist-worker.js +1 -1
  120. package/docs/configuration.md +11 -0
  121. package/docs/engineering-principles.md +32 -0
  122. package/docs/lsp-capability-matrix.md +1 -1
  123. package/docs/lsp-idle-eviction.md +15 -26
  124. package/docs/pi-lens-fixer.md +117 -13
  125. package/docs/pi-lens-merge-policy.md +109 -11
  126. package/docs/pi-lens-monitor.md +8 -2
  127. package/docs/pi-lens-retro.md +4 -1
  128. package/docs/pi-lens-reviewer.md +114 -3
  129. package/docs/pi-lens-subagent.md +27 -14
  130. package/docs/release-qa-baseline.md +3 -1
  131. package/docs/servercapabilities.md +9 -19
  132. package/package.json +7 -5
  133. package/scripts/download-grammars.js +40 -7
  134. package/scripts/lib/latency-log-phases.mjs +95 -0
  135. package/scripts/rpc-load-check.mjs +570 -81
  136. package/dist/chunk-3WA4HP4I.js +0 -55
  137. package/dist/chunk-466Z26MG.js +0 -30
  138. package/dist/chunk-5JM2524W.js +0 -84
  139. package/dist/chunk-CO2G5PHH.js +0 -84
  140. package/dist/chunk-LOP6GRPH.js +0 -31
  141. package/dist/chunk-UOPVJQ4N.js +0 -103
  142. package/dist/chunk-XPZPXCBV.js +0 -28
  143. /package/dist/{chunk-FC4RP4I2.js → chunk-6HWVI6MI.js} +0 -0
@@ -0,0 +1,4217 @@
1
+ import { createRequire as __pilensCreateRequire } from "node:module"; const require = __pilensCreateRequire(import.meta.url);
2
+ import {
3
+ buildSymbolId
4
+ } from "./chunk-3MED75HT.js";
5
+ import {
6
+ buildReverseDependencyIndexFromGraph,
7
+ getLSPService,
8
+ rankFilesByReverseDependencyCentrality
9
+ } from "./chunk-RVK72CZX.js";
10
+ import {
11
+ createGitIdentityResolver,
12
+ resolveGitIdentity
13
+ } from "./chunk-UA7ZXYDR.js";
14
+ import {
15
+ notePersistWorkerMessageFault,
16
+ readWorkerHeapStatistics
17
+ } from "./chunk-T7FEBKXN.js";
18
+ import {
19
+ buildQualifiedName,
20
+ findOwnerName
21
+ } from "./chunk-5W3R6LFT.js";
22
+ import {
23
+ RUNTIME_CONFIG,
24
+ TreeSitterSymbolExtractor,
25
+ fileAnswerNames,
26
+ importSourceNameParts,
27
+ jsTsCandidatePaths,
28
+ resolveAliasedImport,
29
+ resolveImportToFiles,
30
+ resolveProjectReferenceImport,
31
+ resolveWorkspacePackageImport,
32
+ symbolExtractionGrammar
33
+ } from "./chunk-V35JG4JB.js";
34
+ import {
35
+ classifyTreeSitterWasmError,
36
+ getSharedTreeSitterClient,
37
+ logTreeSitterCacheStats,
38
+ withTreeSitterRoot
39
+ } from "./chunk-US7ECLD7.js";
40
+ import {
41
+ getReviewGraphMaxFilesDerived
42
+ } from "./chunk-7HXE67BN.js";
43
+ import {
44
+ readGzipStageWorkerResult,
45
+ reapStageFile
46
+ } from "./chunk-IJYGIDF4.js";
47
+ import {
48
+ collectSourceFilesWithBudgetAsync
49
+ } from "./chunk-DGUKIYSI.js";
50
+ import {
51
+ collectUntrackedIgnoredIds,
52
+ getProjectDataDir,
53
+ isStaleStageFile
54
+ } from "./chunk-KUA4OJ5Y.js";
55
+ import {
56
+ KIND_EXTENSIONS,
57
+ detectFileKind
58
+ } from "./chunk-DUO2TU77.js";
59
+ import {
60
+ detectFileRole
61
+ } from "./chunk-J6MPGQTS.js";
62
+ import {
63
+ writeFileAtomic
64
+ } from "./chunk-2EECBNC5.js";
65
+ import {
66
+ compareOrdinal,
67
+ escapeRegExp,
68
+ incrementDegradationCount
69
+ } from "./chunk-J64T55EI.js";
70
+ import {
71
+ logLatency
72
+ } from "./chunk-QBFBRV2B.js";
73
+ import {
74
+ createNdjsonLogger,
75
+ getGlobalPiLensLogDir,
76
+ getMaxLogSizeMB,
77
+ getTurnId,
78
+ isTestMode,
79
+ lazyEnvNumber
80
+ } from "./chunk-YNE3RP52.js";
81
+ import {
82
+ FactStore
83
+ } from "./chunk-CYRKQRPM.js";
84
+ import {
85
+ BoundedFifoMap,
86
+ BoundedLruCache
87
+ } from "./chunk-ABBOA7UD.js";
88
+ import {
89
+ isAtOrAboveHomeDir,
90
+ isUnderDir,
91
+ normalizeFilePath,
92
+ normalizeMapKey,
93
+ toProjectRelativePath
94
+ } from "./chunk-3RKP3FMS.js";
95
+
96
+ // dist/clients/review-graph/builder.js
97
+ import { createHash as createHash2 } from "node:crypto";
98
+ import * as fs2 from "node:fs";
99
+ import * as path2 from "node:path";
100
+ import { Worker } from "node:worker_threads";
101
+ import { constants as zlibConstants, gunzipSync, gzipSync } from "node:zlib";
102
+ import { fileURLToPath } from "node:url";
103
+
104
+ // dist/clients/dispatch/facts/file-content.js
105
+ import * as fs from "node:fs/promises";
106
+ var fileContentProvider = {
107
+ id: "fact.file.content",
108
+ provides: ["file.content"],
109
+ requires: [],
110
+ appliesTo(_ctx) {
111
+ return true;
112
+ },
113
+ async run(ctx, store) {
114
+ let content;
115
+ try {
116
+ content = await fs.readFile(ctx.filePath, "utf-8");
117
+ } catch {
118
+ content = null;
119
+ }
120
+ store.setFileFact(ctx.filePath, "file.content", content);
121
+ }
122
+ };
123
+
124
+ // dist/clients/feature-hints.js
125
+ function normalizeHintInput(value) {
126
+ return value.replace(/\\/g, "/");
127
+ }
128
+ function hasHintToken(value, tokens) {
129
+ const escaped = tokens.map((token) => escapeRegExp(token));
130
+ const alternatives = escaped.join("|");
131
+ return new RegExp(`(?:^|[/_.\\-\\s])(?:${alternatives})(?=[/_.\\-\\s]|$)`, "i").test(value) || new RegExp(`(?:^|(?<=[a-z0-9]))(?:${tokens.flatMap((token) => [
132
+ token[0].toUpperCase() + token.slice(1),
133
+ ...token === "openai" ? ["OpenAI"] : [],
134
+ ...token === "github" ? ["GitHub"] : [],
135
+ ...token === "gitlab" ? ["GitLab"] : []
136
+ ]).join("|")})(?=[A-Z]|[/_.\\-\\s]|$)`).test(value);
137
+ }
138
+ function inferFeatureKind(nameOrPath) {
139
+ const normalized = normalizeHintInput(nameOrPath);
140
+ if (hasHintToken(normalized, [
141
+ "config",
142
+ "store",
143
+ "db",
144
+ "database",
145
+ "github",
146
+ "openai",
147
+ "sync",
148
+ "service"
149
+ ])) {
150
+ return "service";
151
+ }
152
+ if (/(^|[/_.\-\s])(cli|command|bin)([/_.\-\s]|$)/i.test(normalized)) {
153
+ return "cli-command";
154
+ }
155
+ return "library";
156
+ }
157
+ function inferTrustBoundaries(nameOrPath) {
158
+ const normalized = normalizeHintInput(nameOrPath);
159
+ const boundaries = /* @__PURE__ */ new Set();
160
+ if (hasHintToken(normalized, [
161
+ "config",
162
+ "store",
163
+ "db",
164
+ "database",
165
+ "repo",
166
+ "repository",
167
+ "model",
168
+ "migration"
169
+ ])) {
170
+ boundaries.add("filesystem");
171
+ boundaries.add("database");
172
+ }
173
+ if (hasHintToken(normalized, [
174
+ "github",
175
+ "gitlab",
176
+ "openai",
177
+ "anthropic",
178
+ "stripe",
179
+ "slack",
180
+ "sync",
181
+ "webhook",
182
+ "api",
183
+ "client"
184
+ ])) {
185
+ boundaries.add("network");
186
+ boundaries.add("external-api");
187
+ boundaries.add("serialization");
188
+ }
189
+ if (/(^|[/_.\-\s])(cli|command|bin|exec|spawn|process|shell)([/_.\-\s]|$)/i.test(normalized)) {
190
+ boundaries.add("user-input");
191
+ boundaries.add("process-exec");
192
+ }
193
+ if (hasHintToken(normalized, [
194
+ "auth",
195
+ "login",
196
+ "token",
197
+ "session",
198
+ "oauth",
199
+ "jwt"
200
+ ])) {
201
+ boundaries.add("auth");
202
+ boundaries.add("user-input");
203
+ }
204
+ return [...boundaries];
205
+ }
206
+ function featureHintMetadata(nameOrPath) {
207
+ return {
208
+ featureKind: inferFeatureKind(nameOrPath),
209
+ trustBoundaries: inferTrustBoundaries(nameOrPath)
210
+ };
211
+ }
212
+
213
+ // dist/clients/lsp-document-symbols.js
214
+ var LSP_DOCUMENT_SYMBOL_TIMEOUT_MS = 150;
215
+ var SYMBOL_KIND_NAMES = {
216
+ 1: "file",
217
+ 2: "module",
218
+ 3: "namespace",
219
+ 4: "package",
220
+ 5: "class",
221
+ 6: "method",
222
+ 7: "property",
223
+ 8: "field",
224
+ 9: "constructor",
225
+ 10: "enum",
226
+ 11: "interface",
227
+ 12: "function",
228
+ 13: "variable",
229
+ 14: "constant",
230
+ 15: "string",
231
+ 16: "number",
232
+ 17: "boolean",
233
+ 18: "array",
234
+ 19: "object",
235
+ 20: "key",
236
+ 21: "null",
237
+ 22: "enum-member",
238
+ 23: "struct",
239
+ 24: "event",
240
+ 25: "operator",
241
+ 26: "type-parameter"
242
+ };
243
+ function lspSymbolKindName(kind) {
244
+ return SYMBOL_KIND_NAMES[kind] ?? `lsp-symbol-${kind}`;
245
+ }
246
+ async function getOpenDocumentSymbols(filePath, timeoutMs = LSP_DOCUMENT_SYMBOL_TIMEOUT_MS) {
247
+ const spawned = await getLSPService().getWarmClientForFile(filePath);
248
+ if (!spawned || !spawned.client.isDocumentOpen(filePath) || !spawned.client.getOperationSupport().documentSymbol) {
249
+ return void 0;
250
+ }
251
+ let timer;
252
+ try {
253
+ return await Promise.race([
254
+ spawned.client.documentSymbol(filePath),
255
+ new Promise((resolve2) => {
256
+ timer = setTimeout(() => resolve2(void 0), timeoutMs);
257
+ })
258
+ ]);
259
+ } catch {
260
+ return void 0;
261
+ } finally {
262
+ if (timer)
263
+ clearTimeout(timer);
264
+ }
265
+ }
266
+ function containerNameChain(symbol, allSymbols) {
267
+ const chain = [];
268
+ const seen = /* @__PURE__ */ new Set();
269
+ let container = symbol.containerName;
270
+ while (container && !seen.has(container) && chain.length < 10) {
271
+ chain.unshift(container);
272
+ seen.add(container);
273
+ container = allSymbols?.find((candidate) => candidate.name === container)?.containerName;
274
+ }
275
+ return chain;
276
+ }
277
+
278
+ // dist/clients/project-scan-policy.js
279
+ function collectProjectSourceFilesWithBudgetAsync(rootDir, options) {
280
+ return collectSourceFilesWithBudgetAsync(rootDir, options);
281
+ }
282
+
283
+ // dist/clients/review-graph-logger.js
284
+ import * as path from "node:path";
285
+ var REVIEW_GRAPH_LOG_DIR = getGlobalPiLensLogDir();
286
+ var REVIEW_GRAPH_LOG_FILE = path.join(REVIEW_GRAPH_LOG_DIR, "review-graph.log");
287
+ var writer = createNdjsonLogger({
288
+ filePath: REVIEW_GRAPH_LOG_FILE,
289
+ maxBytes: getMaxLogSizeMB() * 1024 * 1024,
290
+ backupPath: `${REVIEW_GRAPH_LOG_FILE}.1`
291
+ });
292
+ function makeReviewGraphBuildMetadata(graph, options = {}) {
293
+ return {
294
+ ...options.buildId === void 0 ? {} : { buildId: options.buildId },
295
+ ...graph.buildGeneration === void 0 ? {} : { graphGeneration: graph.buildGeneration },
296
+ builtAt: graph.builtAt,
297
+ ...options.projectSeq === void 0 ? {} : { projectSeq: options.projectSeq },
298
+ ...options.seqHint === void 0 ? {} : { seqHint: options.seqHint },
299
+ ...options.mode === void 0 ? {} : { mode: options.mode },
300
+ sourceFiles: options.sourceFileCount ?? graph.fileNodes.size,
301
+ ...options.sourceFileCountTruncated || graph.persistCoverage?.sourceFilesTruncated ? { sourceFilesTruncated: true } : {},
302
+ ...options.pathNormalizeCalls === void 0 ? {} : { pathNormalizeCalls: options.pathNormalizeCalls },
303
+ nodes: graph.nodes.size,
304
+ edges: graph.edges.length,
305
+ ...graph.persistCoverage ? { persistCoverage: graph.persistCoverage } : {}
306
+ };
307
+ }
308
+ function logReviewGraph(entry) {
309
+ if (isTestMode()) {
310
+ return;
311
+ }
312
+ writer.log({
313
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
314
+ ...entry,
315
+ cwd: normalizeFilePath(entry.cwd),
316
+ pid: process.pid,
317
+ turnId: getTurnId()
318
+ });
319
+ }
320
+ function flushReviewGraphLogSync() {
321
+ writer.flushSync();
322
+ }
323
+
324
+ // dist/clients/review-graph/revision-drift.js
325
+ function formatReviewGraphRevisionDriftNote(drift) {
326
+ return `Graph was built at commit ${drift.stampedHead.slice(0, 8)}; HEAD is now ${drift.currentHead.slice(0, 8)}. Results below reflect the earlier revision \u2014 run pilens_rebuild or re-analyze to refresh.`;
327
+ }
328
+
329
+ // dist/clients/review-graph/shared-extraction-ir.js
330
+ import { createHash } from "node:crypto";
331
+ function reviewGraphIrContentHash(content) {
332
+ return createHash("sha256").update(content).digest("hex");
333
+ }
334
+ var MAX_ROOTS = 8;
335
+ var MAX_FILES_PER_ROOT = 2e4;
336
+ var roots = new BoundedFifoMap(MAX_ROOTS);
337
+ var accepted = 0;
338
+ var rejected = 0;
339
+ function rootKey(cwd) {
340
+ return normalizeMapKey(cwd);
341
+ }
342
+ function publishReviewGraphFileIr(cwd, entry) {
343
+ if (!entry.complete || !entry.structural)
344
+ return;
345
+ const key = rootKey(cwd);
346
+ let files = roots.get(key);
347
+ if (!files) {
348
+ files = new BoundedFifoMap(MAX_FILES_PER_ROOT);
349
+ roots.set(key, files);
350
+ }
351
+ const fileKey = normalizeMapKey(entry.filePath);
352
+ files.delete(fileKey);
353
+ files.set(fileKey, { ...entry, filePath: fileKey });
354
+ }
355
+ function getFreshReviewGraphFileIr(cwd, filePath, contentHash) {
356
+ const files = roots.get(rootKey(cwd));
357
+ const fileKey = normalizeMapKey(filePath);
358
+ const entry = files?.get(fileKey);
359
+ if (!entry)
360
+ return void 0;
361
+ if (entry.contentHash !== contentHash) {
362
+ rejected++;
363
+ return void 0;
364
+ }
365
+ files?.delete(fileKey);
366
+ accepted++;
367
+ return entry;
368
+ }
369
+ function clearReviewGraphFileIr(cwd) {
370
+ if (cwd === void 0)
371
+ roots.clear();
372
+ else
373
+ roots.delete(rootKey(cwd));
374
+ }
375
+
376
+ // dist/clients/review-graph/builder.js
377
+ var REVIEW_GRAPH_VERSION = "v8";
378
+ var MAIN_KINDS = /* @__PURE__ */ new Set([
379
+ "jsts",
380
+ "python",
381
+ "go",
382
+ "rust",
383
+ "ruby",
384
+ "cxx",
385
+ // Languages added in #152: WASMs + symbol queries now available
386
+ "java",
387
+ "kotlin",
388
+ "dart",
389
+ "elixir",
390
+ "csharp",
391
+ "php",
392
+ "swift",
393
+ "lua",
394
+ "ocaml",
395
+ "zig",
396
+ "shell"
397
+ ]);
398
+ var MAIN_KIND_EXTENSIONS = Array.from(MAIN_KINDS).flatMap((kind) => KIND_EXTENSIONS[kind] ?? []);
399
+ var CHANGED_SYMBOLS_PREFIX = "session.reviewGraph.changedSymbols:";
400
+ var extractorCache = /* @__PURE__ */ new Map();
401
+ var REVIEW_GRAPH_MAX_WARM_WORKSPACES = 8;
402
+ var REVIEW_GRAPH_SOURCE_PATH_MEMO_ENTRIES = 16384;
403
+ var _sourcePathMemos = new BoundedLruCache(REVIEW_GRAPH_MAX_WARM_WORKSPACES);
404
+ function sourcePathMemo(cwd) {
405
+ const key = normalizeMapKey(path2.resolve(cwd));
406
+ const existing = _sourcePathMemos.get(key);
407
+ if (existing)
408
+ return existing;
409
+ const memo = {
410
+ cache: new BoundedLruCache(REVIEW_GRAPH_SOURCE_PATH_MEMO_ENTRIES),
411
+ normalizeCalls: { value: 0 }
412
+ };
413
+ _sourcePathMemos.set(key, memo);
414
+ return memo;
415
+ }
416
+ function normalizeGraphSourcePath(memo, raw) {
417
+ const cached = memo.cache.get(raw);
418
+ if (cached !== void 0)
419
+ return cached;
420
+ const normalized = normalizeMapKey(raw);
421
+ if (fs2.existsSync(raw))
422
+ memo.cache.set(raw, normalized);
423
+ memo.normalizeCalls.value++;
424
+ return normalized;
425
+ }
426
+ function _resetReviewGraphSourcePathMemoForTests() {
427
+ _sourcePathMemos.clear();
428
+ }
429
+ var _buildCache = /* @__PURE__ */ new Map();
430
+ var _workspaceGraphCache = /* @__PURE__ */ new Map();
431
+ var REVIEW_GRAPH_IDLE_EVICT_MS_DEFAULT = 20 * 6e4;
432
+ var _workspaceCacheEpoch = 0;
433
+ var _workspaceCacheEpochs = /* @__PURE__ */ new Map();
434
+ function workspaceCacheEpoch(key) {
435
+ return _workspaceCacheEpoch + (_workspaceCacheEpochs.get(key) ?? 0);
436
+ }
437
+ function reviewGraphIdleEvictMs() {
438
+ const value = Number.parseInt(process.env.PI_LENS_REVIEW_GRAPH_IDLE_EVICT_MS ?? "", 10);
439
+ return Number.isSafeInteger(value) && value > 0 ? value : REVIEW_GRAPH_IDLE_EVICT_MS_DEFAULT;
440
+ }
441
+ function clearWorkspaceGraphTimer(entry) {
442
+ if (entry.idleTimer)
443
+ clearTimeout(entry.idleTimer);
444
+ entry.idleTimer = void 0;
445
+ }
446
+ function buildCacheWorkspaceKey(cwd) {
447
+ return normalizeMapKey(path2.resolve(cwd));
448
+ }
449
+ function buildCacheKeyWorkspace(buildKey) {
450
+ const separator = buildKey.indexOf("|");
451
+ return separator >= 0 ? buildKey.slice(0, separator) : void 0;
452
+ }
453
+ function evictWorkspaceGraph(key, entry) {
454
+ if (_workspaceGraphCache.get(key) !== entry)
455
+ return;
456
+ clearWorkspaceGraphTimer(entry);
457
+ const buildWorkspace = buildCacheWorkspaceKey(key);
458
+ for (const buildKey of _buildCache.keys()) {
459
+ if (buildCacheKeyWorkspace(buildKey) === buildWorkspace) {
460
+ _buildCache.delete(buildKey);
461
+ }
462
+ }
463
+ _sourcePathMemos.delete(key);
464
+ _workspaceCacheEpochs.set(key, (_workspaceCacheEpochs.get(key) ?? 0) + 1);
465
+ _workspaceGraphCache.delete(key);
466
+ }
467
+ function scheduleWorkspaceGraphEviction(key, entry) {
468
+ clearWorkspaceGraphTimer(entry);
469
+ const epoch = workspaceCacheEpoch(key);
470
+ entry.idleTimer = setTimeout(() => {
471
+ entry.idleTimer = void 0;
472
+ if (_workspaceGraphCache.get(key) !== entry || workspaceCacheEpoch(key) !== epoch)
473
+ return;
474
+ evictWorkspaceGraph(key, entry);
475
+ }, reviewGraphIdleEvictMs());
476
+ entry.idleTimer.unref?.();
477
+ }
478
+ function touchWorkspaceGraph(key) {
479
+ const entry = _workspaceGraphCache.get(key);
480
+ if (!entry)
481
+ return;
482
+ entry.lastUsedAt = Date.now();
483
+ scheduleWorkspaceGraphEviction(key, entry);
484
+ }
485
+ var _wasmTrappedFiles = /* @__PURE__ */ new Map();
486
+ function stampWasmTrapped(entries, includeCharged) {
487
+ let stamped;
488
+ for (const [file, state] of _wasmTrappedFiles) {
489
+ if ((includeCharged || state === "retry") && entries.has(file)) {
490
+ stamped ??= new Map(entries);
491
+ stamped.set(file, "wasm-trapped");
492
+ }
493
+ }
494
+ return stamped ?? entries;
495
+ }
496
+ function stampWasmTrappedFiles(stored, includeCharged) {
497
+ const fileSignatures = stampWasmTrapped(stored.fileSignatures, includeCharged);
498
+ if (fileSignatures === stored.fileSignatures)
499
+ return stored;
500
+ return {
501
+ ...stored,
502
+ signature: sourceSignatureFromMap(fileSignatures),
503
+ fileSignatures,
504
+ fileHashes: stored.fileHashes && stampWasmTrapped(stored.fileHashes, includeCharged)
505
+ };
506
+ }
507
+ function wasmTrappedFileCount(graph) {
508
+ let count = 0;
509
+ for (const file of _wasmTrappedFiles.keys()) {
510
+ if (graph.fileNodes.has(file))
511
+ count++;
512
+ }
513
+ return count;
514
+ }
515
+ function graphWasmTrapDetail(wasmTrappedFiles) {
516
+ return `review graph degraded \u2014 tree-sitter wasm runtime failure in ${wasmTrappedFiles} file(s)`;
517
+ }
518
+ function setWorkspaceGraph(key, entry, epoch) {
519
+ if (epoch !== void 0 && workspaceCacheEpoch(key) !== epoch)
520
+ return false;
521
+ const previous = _workspaceGraphCache.get(key);
522
+ if (previous)
523
+ clearWorkspaceGraphTimer(previous);
524
+ const boundedGraph = retainedGraph(key, entry.graph);
525
+ const resident = {
526
+ ...stampWasmTrappedFiles(entry, false),
527
+ graph: boundedGraph,
528
+ lastUsedAt: Date.now()
529
+ };
530
+ _workspaceGraphCache.set(key, resident);
531
+ scheduleWorkspaceGraphEviction(key, resident);
532
+ while (_workspaceGraphCache.size > REVIEW_GRAPH_MAX_WARM_WORKSPACES) {
533
+ const victim = [..._workspaceGraphCache.entries()].sort(([, a], [, b]) => a.lastUsedAt - b.lastUsedAt)[0];
534
+ if (!victim)
535
+ break;
536
+ evictWorkspaceGraph(victim[0], victim[1]);
537
+ }
538
+ return true;
539
+ }
540
+ var _graphGenerationCounter = 0;
541
+ var _buildIdCounter = 0;
542
+ var SEQ_FASTPATH_MAX_CHANGES = 32;
543
+ var SEQ_FASTPATH_REVERIFY_MS = 5 * 6e4;
544
+ var SEQ_FASTPATH_REVERIFY_EVERY = 20;
545
+ function graphLogMetadata(graph, options = {}) {
546
+ return makeReviewGraphBuildMetadata(graph, options);
547
+ }
548
+ function seqFastpathEnabled() {
549
+ const raw = process.env.PI_LENS_GRAPH_SEQ_FASTPATH;
550
+ return raw !== "0" && raw !== "false";
551
+ }
552
+ var _lastGraphBuildInfo = {
553
+ reused: false,
554
+ mode: "full",
555
+ graphChanged: true
556
+ };
557
+ var _graphBuildInfoByGraph = /* @__PURE__ */ new WeakMap();
558
+ var _anyGraphStamped = false;
559
+ function setGraphBuildInfo(graph, info) {
560
+ _lastGraphBuildInfo = info;
561
+ _graphBuildInfoByGraph.set(graph, info);
562
+ _anyGraphStamped = true;
563
+ }
564
+ function getGraphBuildInfoForGraph(graph) {
565
+ return _graphBuildInfoByGraph.get(graph) ?? _lastGraphBuildInfo;
566
+ }
567
+ function graphBuildInfoIsTrustworthy(graph) {
568
+ return _graphBuildInfoByGraph.has(graph) || !_anyGraphStamped;
569
+ }
570
+ function updateGraphBuildInfo(graph, patch) {
571
+ const info = { ...getGraphBuildInfoForGraph(graph), ...patch };
572
+ setGraphBuildInfo(graph, info);
573
+ return info;
574
+ }
575
+ function clearGraphCache() {
576
+ _buildCache.clear();
577
+ }
578
+ function clearReviewGraphWorkspaceCache(cwd) {
579
+ if (cwd === void 0) {
580
+ _buildCache.clear();
581
+ for (const entry of _workspaceGraphCache.values())
582
+ clearWorkspaceGraphTimer(entry);
583
+ _workspaceGraphCache.clear();
584
+ _sourcePathMemos.clear();
585
+ _workspaceCacheEpoch++;
586
+ _sizeSkipVerdicts.clear();
587
+ _retainedGraphSites.clear();
588
+ } else {
589
+ const normalized = normalizeMapKey(cwd);
590
+ const buildWorkspace = buildCacheWorkspaceKey(cwd);
591
+ for (const key of _buildCache.keys()) {
592
+ if (buildCacheKeyWorkspace(key) === buildWorkspace) {
593
+ _buildCache.delete(key);
594
+ }
595
+ }
596
+ const entry = _workspaceGraphCache.get(normalized);
597
+ if (entry)
598
+ clearWorkspaceGraphTimer(entry);
599
+ _workspaceCacheEpochs.set(normalized, (_workspaceCacheEpochs.get(normalized) ?? 0) + 1);
600
+ _workspaceGraphCache.delete(normalized);
601
+ _sourcePathMemos.delete(normalized);
602
+ _sizeSkipVerdicts.delete(normalized);
603
+ }
604
+ _lastGraphBuildInfo = { reused: false, mode: "full", graphChanged: true };
605
+ _anyGraphStamped = false;
606
+ }
607
+ var _reviewGraphBuildGateForTests;
608
+ function _setReviewGraphBuildGateForTests(gate) {
609
+ _reviewGraphBuildGateForTests = gate;
610
+ }
611
+ var REVIEW_GRAPH_NODE_RESIDENT_BYTES = 450.5;
612
+ var REVIEW_GRAPH_EDGE_RESIDENT_BYTES = 243;
613
+ function estimateReviewGraphStoreBytes(totalNodes, totalEdges) {
614
+ return totalNodes * REVIEW_GRAPH_NODE_RESIDENT_BYTES + totalEdges * REVIEW_GRAPH_EDGE_RESIDENT_BYTES;
615
+ }
616
+ var GRAPH_MAX_IN_MEMORY_BYTES_DEFAULT = 512 * 1024 * 1024;
617
+ function graphMaxInMemoryBytes() {
618
+ const raw = Number(process.env.PI_LENS_GRAPH_MAX_IN_MEMORY_BYTES);
619
+ return Number.isFinite(raw) && raw > 0 ? raw : GRAPH_MAX_IN_MEMORY_BYTES_DEFAULT;
620
+ }
621
+ function retainedGraph(cwd, graph) {
622
+ const nodes = graph.nodes.size;
623
+ const edges = graph.edges.length;
624
+ const bytes = estimateReviewGraphStoreBytes(nodes, edges);
625
+ const budget = graphMaxInMemoryBytes();
626
+ if (bytes <= budget)
627
+ return graph;
628
+ const elementCap = Math.max(1, Math.floor((nodes + edges) * budget / bytes));
629
+ let capped = capGraphForPersist(cwd, graph, elementCap);
630
+ if (capped.nodes.size === 0 && nodes > 0) {
631
+ capped = headSliceGraph(graph, elementCap);
632
+ incrementDegradationCount({
633
+ kind: "review-graph-memory-cap-floor",
634
+ subject: cwd,
635
+ reason: `centrality selection retained 0 of ${nodes} nodes at cap ${elementCap}; fell back to a ${capped.nodes.size}-node head slice`
636
+ });
637
+ }
638
+ const cappedNodes = capped.nodes.size;
639
+ const cappedEdges = capped.edges.length;
640
+ capped.persistCoverage = {
641
+ ...capped.persistCoverage ?? graphCoverage(capped, elementCap),
642
+ partial: true,
643
+ capTrimmed: true
644
+ };
645
+ incrementDegradationCount({
646
+ kind: "review-graph-memory-cap",
647
+ subject: cwd,
648
+ reason: `live graph ${nodes}n/${edges}e ~${Math.round(bytes / (1024 * 1024))}MiB over ${Math.round(budget / (1024 * 1024))}MiB budget; trimmed to ${cappedNodes}n/${cappedEdges}e ~${Math.round(estimateReviewGraphStoreBytes(cappedNodes, cappedEdges) / (1024 * 1024))}MiB`
649
+ });
650
+ return capped;
651
+ }
652
+ function headSliceGraph(graph, cap) {
653
+ const nodeBudget = Math.max(1, Math.floor(cap * graph.nodes.size / (graph.nodes.size + graph.edges.length)));
654
+ const keptIds = /* @__PURE__ */ new Set();
655
+ for (const [id] of graph.nodes) {
656
+ if (keptIds.size >= nodeBudget)
657
+ break;
658
+ keptIds.add(id);
659
+ }
660
+ const nodes = new Map([...graph.nodes].filter(([id]) => keptIds.has(id)));
661
+ const edgeBudget = Math.max(0, cap - nodes.size);
662
+ const edges = graph.edges.filter((edge) => keptIds.has(edge.from) && keptIds.has(edge.to)).slice(0, edgeBudget);
663
+ const sliced = {
664
+ ...graph,
665
+ nodes,
666
+ edges,
667
+ edgesByFrom: /* @__PURE__ */ new Map(),
668
+ edgesByTo: /* @__PURE__ */ new Map(),
669
+ fileNodes: /* @__PURE__ */ new Map(),
670
+ symbolNodesByFile: /* @__PURE__ */ new Map(),
671
+ changedSymbolsByFile: /* @__PURE__ */ new Map(),
672
+ persistCoverage: void 0
673
+ };
674
+ rebuildIndexes(sliced);
675
+ return sliced;
676
+ }
677
+ function setSessionReviewGraphFact(cwd, facts, graph) {
678
+ const retained = retainedGraph(cwd, graph);
679
+ registerRetainedGraph(`fact:${cwd}`, retained);
680
+ facts.setSessionFact("session.reviewGraph", retained);
681
+ }
682
+ var _retainedGraphSites = /* @__PURE__ */ new Map();
683
+ function registerRetainedGraph(site, graph) {
684
+ for (const [key, ref] of _retainedGraphSites) {
685
+ if (ref.deref() === void 0)
686
+ _retainedGraphSites.delete(key);
687
+ }
688
+ _retainedGraphSites.set(site, new WeakRef(graph));
689
+ }
690
+ function getReviewGraphWorkspaceCacheSnapshot() {
691
+ let totalNodes = 0;
692
+ let totalEdges = 0;
693
+ const counted = /* @__PURE__ */ new Set();
694
+ const count = (graph) => {
695
+ if (counted.has(graph))
696
+ return;
697
+ counted.add(graph);
698
+ totalNodes += graph.nodes.size;
699
+ totalEdges += graph.edges.length;
700
+ };
701
+ for (const entry of _workspaceGraphCache.values())
702
+ count(entry.graph);
703
+ for (const [key, ref] of _retainedGraphSites) {
704
+ const graph = ref.deref();
705
+ if (graph === void 0) {
706
+ _retainedGraphSites.delete(key);
707
+ continue;
708
+ }
709
+ count(graph);
710
+ }
711
+ return {
712
+ cacheEntries: _workspaceGraphCache.size,
713
+ totalNodes,
714
+ totalEdges,
715
+ residentBytes: estimateReviewGraphStoreBytes(totalNodes, totalEdges)
716
+ };
717
+ }
718
+ function _getReviewGraphWorkspaceCacheKeysForTests() {
719
+ return [..._workspaceGraphCache.entries()].sort(([, a], [, b]) => a.lastUsedAt - b.lastUsedAt).map(([key]) => key);
720
+ }
721
+ function _setReviewGraphWorkspaceEntryForTests(key, graph) {
722
+ setWorkspaceGraph(key, {
723
+ signature: "test",
724
+ fileSignatures: /* @__PURE__ */ new Map(),
725
+ graph
726
+ });
727
+ }
728
+ function _setSessionReviewGraphFactForTests(cwd, facts, graph) {
729
+ setSessionReviewGraphFact(cwd, facts, graph);
730
+ }
731
+ function _persistedCoverageForTests(coverage) {
732
+ return stripProcessLocalCoverage(coverage);
733
+ }
734
+ function _getReviewGraphWorkspaceGraphForTests(key) {
735
+ return _workspaceGraphCache.get(key)?.graph;
736
+ }
737
+ function _getReviewGraphCacheStateForTests(cwd) {
738
+ const cached = _workspaceGraphCache.get(normalizeMapKey(cwd));
739
+ if (!cached)
740
+ return void 0;
741
+ touchWorkspaceGraph(normalizeMapKey(cwd));
742
+ return {
743
+ signature: cached.signature,
744
+ fileSignatures: new Map(cached.fileSignatures),
745
+ fileHashes: cached.fileHashes ? new Map(cached.fileHashes) : void 0
746
+ };
747
+ }
748
+ function getReviewGraphCacheIdentity(cwd, graph) {
749
+ const cached = _workspaceGraphCache.get(normalizeMapKey(cwd));
750
+ if (!cached)
751
+ return void 0;
752
+ touchWorkspaceGraph(normalizeMapKey(cwd));
753
+ if (graph) {
754
+ if (cached.buildGeneration === void 0 && graph.buildGeneration === void 0) {
755
+ if (cached.graph !== graph)
756
+ return void 0;
757
+ } else if (cached.buildGeneration !== graph.buildGeneration) {
758
+ return void 0;
759
+ }
760
+ }
761
+ const version = graph?.version ?? cached.graph.version;
762
+ if (typeof version !== "string" || version.length === 0 || typeof cached.signature !== "string") {
763
+ return void 0;
764
+ }
765
+ return { version, signature: cached.signature };
766
+ }
767
+ var _cwdWorktreeCheckedCwds = /* @__PURE__ */ new Set();
768
+ function _resetCwdWorktreeMismatchLogForTests() {
769
+ _cwdWorktreeCheckedCwds.clear();
770
+ }
771
+ function logCwdWorktreeMismatchOnce(cwd, resolveIdentity = resolveGitIdentity) {
772
+ const key = normalizeMapKey(cwd);
773
+ if (_cwdWorktreeCheckedCwds.has(key))
774
+ return;
775
+ _cwdWorktreeCheckedCwds.add(key);
776
+ const identity = resolveIdentity(cwd);
777
+ if (!identity)
778
+ return;
779
+ if (identity.worktreeRoot === normalizeFilePath(path2.resolve(cwd)))
780
+ return;
781
+ logLatency({
782
+ type: "phase",
783
+ phase: "review_graph_cwd_worktree_mismatch",
784
+ filePath: cwd,
785
+ durationMs: 0,
786
+ metadata: { cwd, worktreeRoot: identity.worktreeRoot }
787
+ });
788
+ }
789
+ function getLastGraphBuildInfo() {
790
+ return _lastGraphBuildInfo;
791
+ }
792
+ function _setLastGraphBuildInfoForTests(info) {
793
+ _lastGraphBuildInfo = info;
794
+ }
795
+ function ensureIndexed(graph) {
796
+ if (graph.edges.length > 0 && graph.edgesByFrom.size === 0) {
797
+ rebuildIndexes(graph);
798
+ }
799
+ }
800
+ function getCachedReviewGraph(cwd) {
801
+ const key = normalizeMapKey(cwd);
802
+ if (getReviewGraphSizeSkipVerdict(cwd))
803
+ return void 0;
804
+ const cached = _workspaceGraphCache.get(key);
805
+ if (cached) {
806
+ touchWorkspaceGraph(key);
807
+ ensureIndexed(cached.graph);
808
+ return cached.graph;
809
+ }
810
+ const disk = loadPersistedGraph(cwd, {
811
+ verifyWorktreeIdentity: true,
812
+ allowPartial: true
813
+ });
814
+ if (!disk)
815
+ return void 0;
816
+ setWorkspaceGraph(key, {
817
+ signature: disk.signature,
818
+ fileSignatures: disk.fileSignatures,
819
+ fileHashes: disk.fileHashes,
820
+ graph: disk.graph,
821
+ // Durable half of the drift fact. The current-HEAD half is never cached
822
+ // beside it — see getReviewGraphRevisionDrift (#1961 review F3).
823
+ ...disk.stampedHead ? { snapshotStampedHead: disk.stampedHead } : {}
824
+ });
825
+ return disk.graph;
826
+ }
827
+ function getReviewGraphRevisionDrift(cwd) {
828
+ const entry = _workspaceGraphCache.get(normalizeMapKey(cwd));
829
+ const stampedHead = entry?.snapshotStampedHead;
830
+ if (!stampedHead)
831
+ return void 0;
832
+ const current = resolveGitIdentity(cwd);
833
+ if (!current || current.headCommit === stampedHead)
834
+ return void 0;
835
+ return { stampedHead, currentHead: current.headCommit };
836
+ }
837
+ function makeCtx(filePath, cwd, facts) {
838
+ return {
839
+ filePath,
840
+ cwd,
841
+ kind: detectFileKind(filePath),
842
+ fileRole: detectFileRole(filePath),
843
+ pi: { getFlag: () => void 0 },
844
+ autofix: false,
845
+ deltaMode: false,
846
+ facts,
847
+ blockingOnly: false,
848
+ modifiedRanges: void 0,
849
+ hasTool: async () => false,
850
+ log: () => {
851
+ }
852
+ };
853
+ }
854
+ function createEmptyGraph() {
855
+ return {
856
+ version: REVIEW_GRAPH_VERSION,
857
+ builtAt: (/* @__PURE__ */ new Date()).toISOString(),
858
+ nodes: /* @__PURE__ */ new Map(),
859
+ edges: [],
860
+ edgesByFrom: /* @__PURE__ */ new Map(),
861
+ edgesByTo: /* @__PURE__ */ new Map(),
862
+ fileNodes: /* @__PURE__ */ new Map(),
863
+ symbolNodesByFile: /* @__PURE__ */ new Map(),
864
+ changedSymbolsByFile: /* @__PURE__ */ new Map()
865
+ };
866
+ }
867
+ function cloneGraph(graph) {
868
+ return {
869
+ version: graph.version,
870
+ builtAt: graph.builtAt,
871
+ nodes: new Map(graph.nodes),
872
+ // Edges are immutable values: update paths replace/filter entries rather
873
+ // than mutating them, so copying the array is sufficient isolation.
874
+ edges: [...graph.edges],
875
+ edgesByFrom: /* @__PURE__ */ new Map(),
876
+ edgesByTo: /* @__PURE__ */ new Map(),
877
+ fileNodes: /* @__PURE__ */ new Map(),
878
+ symbolNodesByFile: /* @__PURE__ */ new Map(),
879
+ changedSymbolsByFile: new Map(graph.changedSymbolsByFile),
880
+ // Carry the partial-coverage marker so a clone can never silently pose as
881
+ // a complete graph (#936 review). The build path additionally refuses a
882
+ // partial base outright; this keeps any other cloner honest.
883
+ persistCoverage: graph.persistCoverage
884
+ };
885
+ }
886
+ function refreshGraphBuiltAt(graph) {
887
+ graph.builtAt = (/* @__PURE__ */ new Date()).toISOString();
888
+ }
889
+ function sourceSignatureEntry(file) {
890
+ try {
891
+ const stat = fs2.statSync(file);
892
+ return `${stat.size}:${stat.mtimeMs}`;
893
+ } catch {
894
+ return "missing";
895
+ }
896
+ }
897
+ var STAT_YIELD_EVERY = 100;
898
+ var yieldToLoop = () => new Promise((resolve2) => setImmediate(resolve2));
899
+ async function sourceSignatureMapAsync(files) {
900
+ const signatures = /* @__PURE__ */ new Map();
901
+ let sinceYield = 0;
902
+ for (const file of files) {
903
+ signatures.set(file, sourceSignatureEntry(file));
904
+ if (++sinceYield >= STAT_YIELD_EVERY) {
905
+ sinceYield = 0;
906
+ await yieldToLoop();
907
+ }
908
+ }
909
+ return signatures;
910
+ }
911
+ function sourceSignatureFromMap(signatures) {
912
+ return [...signatures.entries()].sort(([a], [b]) => compareOrdinal(a, b)).map(([file, signature]) => `${file}:${signature}`).join("|");
913
+ }
914
+ function contentHashEntry(file) {
915
+ try {
916
+ return createHash2("sha256").update(fs2.readFileSync(file)).digest("hex");
917
+ } catch {
918
+ return "missing";
919
+ }
920
+ }
921
+ async function confirmContentChanged(candidates, previousHashes) {
922
+ const prior = previousHashes ?? /* @__PURE__ */ new Map();
923
+ const hashes = new Map(prior);
924
+ const trulyChanged = [];
925
+ let sinceYield = 0;
926
+ for (const file of candidates) {
927
+ const hash = contentHashEntry(file);
928
+ hashes.set(file, hash);
929
+ if (prior.get(file) !== hash)
930
+ trulyChanged.push(file);
931
+ if (++sinceYield >= STAT_YIELD_EVERY) {
932
+ sinceYield = 0;
933
+ await yieldToLoop();
934
+ }
935
+ }
936
+ return { trulyChanged, hashes };
937
+ }
938
+ function diffSignatureMaps(previous, next) {
939
+ const added = [];
940
+ const changed = [];
941
+ for (const [file, signature] of next) {
942
+ const oldSignature = previous.get(file);
943
+ if (oldSignature === void 0)
944
+ added.push(file);
945
+ else if (oldSignature !== signature)
946
+ changed.push(file);
947
+ }
948
+ const removed = [];
949
+ for (const file of previous.keys()) {
950
+ if (!next.has(file))
951
+ removed.push(file);
952
+ }
953
+ return { added, removed, changed };
954
+ }
955
+ function getReviewGraphMaxFiles(cwd) {
956
+ const override = Number.parseInt(process.env.PI_LENS_REVIEW_GRAPH_MAX_FILES ?? "", 10);
957
+ return Number.isFinite(override) && override > 0 ? override : getReviewGraphMaxFilesDerived(cwd);
958
+ }
959
+ function getReviewGraphMaxFileBytes() {
960
+ const override = Number.parseInt(process.env.PI_LENS_REVIEW_GRAPH_MAX_FILE_BYTES ?? "", 10);
961
+ return Number.isFinite(override) && override > 0 ? override : RUNTIME_CONFIG.reviewGraph.maxFileBytes;
962
+ }
963
+ function isWithinReviewGraphSizeLimit(file) {
964
+ try {
965
+ return fs2.statSync(file).size <= getReviewGraphMaxFileBytes();
966
+ } catch {
967
+ return false;
968
+ }
969
+ }
970
+ var DEFAULT_REVIEW_GRAPH_SIZE_SKIP_TTL_MS = 15 * 6e4;
971
+ var _sizeSkipTtl = lazyEnvNumber("PI_LENS_REVIEW_GRAPH_SIZE_SKIP_TTL_MS", DEFAULT_REVIEW_GRAPH_SIZE_SKIP_TTL_MS);
972
+ var _resetReviewGraphSizeSkipTtlForTests = _sizeSkipTtl._resetForTests;
973
+ var _buildAttempts = /* @__PURE__ */ new Map();
974
+ function getLastReviewGraphBuildAttempt(cwd) {
975
+ return _buildAttempts.get(normalizeMapKey(cwd));
976
+ }
977
+ function _resetReviewGraphBuildAttemptsForTests() {
978
+ _buildAttempts.clear();
979
+ }
980
+ function recordBuildAttempt(cwd, outcome, reason, buildId) {
981
+ const key = normalizeMapKey(cwd);
982
+ const prior = _buildAttempts.get(key);
983
+ if (prior?.buildId !== void 0 && (buildId === void 0 || buildId < prior.buildId)) {
984
+ return;
985
+ }
986
+ _buildAttempts.set(key, {
987
+ when: (/* @__PURE__ */ new Date()).toISOString(),
988
+ outcome,
989
+ ...buildId === void 0 ? {} : { buildId },
990
+ ...reason ? { reason } : {}
991
+ });
992
+ }
993
+ function recordPersistFailure(cwd, reason, error, pending, workerState) {
994
+ const prior = _buildAttempts.get(normalizeMapKey(cwd));
995
+ const pendingBuildId = pending?.graphMetadata.buildId;
996
+ const belongsToCurrentBuild = pendingBuildId === void 0 || prior?.buildId === pendingBuildId;
997
+ if (belongsToCurrentBuild && (prior === void 0 || prior.outcome === "succeeded")) {
998
+ recordBuildAttempt(cwd, "succeeded", `graph built but persistence failed: ${error}`, pendingBuildId);
999
+ }
1000
+ logReviewGraph({
1001
+ cwd,
1002
+ phase: "persist_failed",
1003
+ reason,
1004
+ error,
1005
+ ...pending ? {
1006
+ observability: persistObservability(pending, {
1007
+ status: "failed",
1008
+ reason: workerState?.fallbackReason ?? reason,
1009
+ workerStarted: workerState?.started,
1010
+ workerCompleted: workerState?.completed,
1011
+ ...workerState?.fallbackReason ? { workerFallback: true } : {}
1012
+ })
1013
+ } : {}
1014
+ });
1015
+ }
1016
+ var _sizeSkipVerdicts = /* @__PURE__ */ new Map();
1017
+ function _resetReviewGraphSizeSkipVerdictsForTests() {
1018
+ _sizeSkipVerdicts.clear();
1019
+ }
1020
+ function recordReviewGraphSizeSkip(cwd, sourceFileCount, maxFileCount) {
1021
+ _sizeSkipVerdicts.set(normalizeMapKey(cwd), {
1022
+ sourceFileCount,
1023
+ maxFileCount,
1024
+ sourceFileCountTruncated: true,
1025
+ skippedAt: Date.now()
1026
+ });
1027
+ }
1028
+ function clearReviewGraphSizeSkip(cwd) {
1029
+ _sizeSkipVerdicts.delete(normalizeMapKey(cwd));
1030
+ }
1031
+ var REVIEW_GRAPH_SIZE_NEAR_MISS_RATIO = 0.05;
1032
+ function isReviewGraphSizeNearMiss(sourceFileCount, maxFileCount) {
1033
+ return sourceFileCount > maxFileCount && sourceFileCount <= maxFileCount * (1 + REVIEW_GRAPH_SIZE_NEAR_MISS_RATIO);
1034
+ }
1035
+ function getReviewGraphSizeSkipVerdict(cwd, now = Date.now()) {
1036
+ const key = normalizeMapKey(cwd);
1037
+ const verdict = _sizeSkipVerdicts.get(key);
1038
+ if (!verdict)
1039
+ return void 0;
1040
+ if (now - verdict.skippedAt >= _sizeSkipTtl.get()) {
1041
+ _sizeSkipVerdicts.delete(key);
1042
+ return void 0;
1043
+ }
1044
+ return verdict;
1045
+ }
1046
+ var _reviewGraphEntryBudgetForTests;
1047
+ function _setReviewGraphEntryBudgetForTests(maxScanEntries) {
1048
+ _reviewGraphEntryBudgetForTests = maxScanEntries;
1049
+ }
1050
+ var _reviewGraphEntryCounterForTests;
1051
+ function _setReviewGraphEntryCounterForTests(counter) {
1052
+ _reviewGraphEntryCounterForTests = counter;
1053
+ }
1054
+ async function getGraphSourceFiles(cwd) {
1055
+ const sourceMemo = sourcePathMemo(cwd);
1056
+ const normalizeCallsBefore = sourceMemo.normalizeCalls.value;
1057
+ const maxGraphFiles = getReviewGraphMaxFiles(cwd);
1058
+ const walkStartedAt = Date.now();
1059
+ const { files: collected, entryBudgetExceeded, entriesVisited } = await collectProjectSourceFilesWithBudgetAsync(cwd, {
1060
+ // Only walk graph-relevant extensions so the cap counts what the graph
1061
+ // keeps (post-filter), not JSON/YAML/MD noise it would discard anyway.
1062
+ extensions: MAIN_KIND_EXTENSIONS,
1063
+ maxFiles: maxGraphFiles + 1,
1064
+ ..._reviewGraphEntryBudgetForTests === void 0 ? {} : { maxScanEntries: _reviewGraphEntryBudgetForTests },
1065
+ ..._reviewGraphEntryCounterForTests === void 0 ? {} : { onEntryVisited: _reviewGraphEntryCounterForTests }
1066
+ });
1067
+ const walkMs = Date.now() - walkStartedAt;
1068
+ if (entryBudgetExceeded) {
1069
+ logLatency({
1070
+ type: "phase",
1071
+ phase: "review_graph_source_walk_entry_budget",
1072
+ filePath: cwd,
1073
+ durationMs: 0,
1074
+ metadata: { cwd, collectedFiles: collected.length }
1075
+ });
1076
+ }
1077
+ if (collected.length > maxGraphFiles) {
1078
+ return {
1079
+ files: collected,
1080
+ pathNormalizeCalls: sourceMemo.normalizeCalls.value - normalizeCallsBefore,
1081
+ sourceFileCount: collected.length,
1082
+ maxFileCount: maxGraphFiles,
1083
+ entryBudgetExceeded,
1084
+ entriesVisited,
1085
+ walkMs
1086
+ };
1087
+ }
1088
+ const result = [];
1089
+ let sinceYield = 0;
1090
+ for (const raw of collected) {
1091
+ const file = normalizeGraphSourcePath(sourceMemo, raw);
1092
+ const kind = detectFileKind(file);
1093
+ if (!!kind && MAIN_KINDS.has(kind) && detectFileRole(file) !== "test" && isWithinReviewGraphSizeLimit(file)) {
1094
+ result.push(file);
1095
+ }
1096
+ if (++sinceYield >= STAT_YIELD_EVERY) {
1097
+ sinceYield = 0;
1098
+ await yieldToLoop();
1099
+ }
1100
+ }
1101
+ return {
1102
+ files: result,
1103
+ pathNormalizeCalls: sourceMemo.normalizeCalls.value - normalizeCallsBefore,
1104
+ sourceFileCount: result.length,
1105
+ maxFileCount: maxGraphFiles,
1106
+ entryBudgetExceeded,
1107
+ entriesVisited,
1108
+ walkMs
1109
+ };
1110
+ }
1111
+ function addNode(graph, node) {
1112
+ const isNew = !graph.nodes.has(node.id);
1113
+ graph.nodes.set(node.id, node);
1114
+ if (node.kind === "file" && node.filePath) {
1115
+ graph.fileNodes.set(node.filePath, node.id);
1116
+ return;
1117
+ }
1118
+ if (isNew && node.kind === "symbol" && node.filePath) {
1119
+ const ids = graph.symbolNodesByFile.get(node.filePath) ?? [];
1120
+ ids.push(node.id);
1121
+ graph.symbolNodesByFile.set(node.filePath, ids);
1122
+ }
1123
+ }
1124
+ function indexEdge(graph, edge) {
1125
+ const from = graph.edgesByFrom.get(edge.from) ?? [];
1126
+ from.push(edge);
1127
+ graph.edgesByFrom.set(edge.from, from);
1128
+ const to = graph.edgesByTo.get(edge.to) ?? [];
1129
+ to.push(edge);
1130
+ graph.edgesByTo.set(edge.to, to);
1131
+ }
1132
+ function unindexEdge(graph, edge) {
1133
+ const from = graph.edgesByFrom.get(edge.from);
1134
+ if (from) {
1135
+ _rebuildCounters.removeOwnedEdgePositions += from.length;
1136
+ const at = from.indexOf(edge);
1137
+ if (at >= 0)
1138
+ from.splice(at, 1);
1139
+ if (from.length === 0)
1140
+ graph.edgesByFrom.delete(edge.from);
1141
+ }
1142
+ const to = graph.edgesByTo.get(edge.to);
1143
+ if (to) {
1144
+ _rebuildCounters.removeOwnedEdgePositions += to.length;
1145
+ const at = to.indexOf(edge);
1146
+ if (at >= 0)
1147
+ to.splice(at, 1);
1148
+ if (to.length === 0)
1149
+ graph.edgesByTo.delete(edge.to);
1150
+ }
1151
+ }
1152
+ function unindexEdges(graph, removedEdges) {
1153
+ const fromIds = /* @__PURE__ */ new Set();
1154
+ const toIds = /* @__PURE__ */ new Set();
1155
+ for (const edge of removedEdges) {
1156
+ fromIds.add(edge.from);
1157
+ toIds.add(edge.to);
1158
+ }
1159
+ for (const fromId of fromIds) {
1160
+ const bucket = graph.edgesByFrom.get(fromId);
1161
+ if (!bucket)
1162
+ continue;
1163
+ const kept = [];
1164
+ for (const edge of bucket) {
1165
+ _rebuildCounters.removeOwnedEdgePositions++;
1166
+ if (!removedEdges.has(edge))
1167
+ kept.push(edge);
1168
+ }
1169
+ if (kept.length === 0)
1170
+ graph.edgesByFrom.delete(fromId);
1171
+ else
1172
+ graph.edgesByFrom.set(fromId, kept);
1173
+ }
1174
+ for (const toId of toIds) {
1175
+ const bucket = graph.edgesByTo.get(toId);
1176
+ if (!bucket)
1177
+ continue;
1178
+ const kept = [];
1179
+ for (const edge of bucket) {
1180
+ _rebuildCounters.removeOwnedEdgePositions++;
1181
+ if (!removedEdges.has(edge))
1182
+ kept.push(edge);
1183
+ }
1184
+ if (kept.length === 0)
1185
+ graph.edgesByTo.delete(toId);
1186
+ else
1187
+ graph.edgesByTo.set(toId, kept);
1188
+ }
1189
+ }
1190
+ function addEdge(graph, edge) {
1191
+ graph.edges.push(edge);
1192
+ indexEdge(graph, edge);
1193
+ }
1194
+ function rebuildIndexes(graph) {
1195
+ graph.edgesByFrom = /* @__PURE__ */ new Map();
1196
+ graph.edgesByTo = /* @__PURE__ */ new Map();
1197
+ graph.fileNodes = /* @__PURE__ */ new Map();
1198
+ graph.symbolNodesByFile = /* @__PURE__ */ new Map();
1199
+ for (const node of graph.nodes.values()) {
1200
+ if (node.kind === "file" && node.filePath) {
1201
+ graph.fileNodes.set(node.filePath, node.id);
1202
+ }
1203
+ if (node.kind === "symbol" && node.filePath) {
1204
+ const ids = graph.symbolNodesByFile.get(node.filePath) ?? [];
1205
+ ids.push(node.id);
1206
+ graph.symbolNodesByFile.set(node.filePath, ids);
1207
+ }
1208
+ }
1209
+ for (const edge of graph.edges) {
1210
+ const from = graph.edgesByFrom.get(edge.from) ?? [];
1211
+ from.push(edge);
1212
+ graph.edgesByFrom.set(edge.from, from);
1213
+ const to = graph.edgesByTo.get(edge.to) ?? [];
1214
+ to.push(edge);
1215
+ graph.edgesByTo.set(edge.to, to);
1216
+ }
1217
+ }
1218
+ var GRAPH_CACHE_FILENAME = "review-graph.json.gz";
1219
+ var LEGACY_GRAPH_CACHE_FILENAME = "review-graph.json";
1220
+ var GRAPH_CHECKPOINT_FILENAME = "review-graph.checkpoint.json.gz";
1221
+ function logSnapshotReadVerdict(cwd, phase, reason) {
1222
+ const verdict = phase === "snapshot_read_dropped" ? "dropped" : "drifted";
1223
+ const isRisingEdge = incrementDegradationCount({
1224
+ kind: "review-graph-snapshot-read",
1225
+ // Subject keeps BOTH discriminators, so aggregation still answers which
1226
+ // workspace and which verdict after the detailed records stop.
1227
+ subject: `${verdict}:${normalizeMapKey(cwd)}`,
1228
+ reason
1229
+ });
1230
+ if (!isRisingEdge)
1231
+ return;
1232
+ logReviewGraph({ cwd, phase, reason });
1233
+ }
1234
+ function loadPersistedGraph(cwd, opts, resolveIdentity = resolveGitIdentity) {
1235
+ const cacheDir = path2.join(getProjectDataDir(cwd), "cache");
1236
+ const cachePath = path2.join(cacheDir, GRAPH_CACHE_FILENAME);
1237
+ const legacyPath = path2.join(cacheDir, LEGACY_GRAPH_CACHE_FILENAME);
1238
+ try {
1239
+ const raw = fs2.existsSync(cachePath) ? gunzipSync(fs2.readFileSync(cachePath)).toString("utf-8") : fs2.readFileSync(legacyPath, "utf-8");
1240
+ const data = JSON.parse(raw);
1241
+ if (data.version !== REVIEW_GRAPH_VERSION || typeof data.signature !== "string" || typeof data.builtAt !== "string" || !Array.isArray(data.nodes) || !Array.isArray(data.edges))
1242
+ return null;
1243
+ if (data.coverage?.partial && !opts?.allowPartial)
1244
+ return null;
1245
+ let stampedHead;
1246
+ if (opts?.verifyWorktreeIdentity && data.gitStamp) {
1247
+ const current = resolveIdentity(cwd);
1248
+ if (current && current.worktreeRoot !== data.gitStamp.worktreeRoot) {
1249
+ logSnapshotReadVerdict(cwd, "snapshot_read_dropped", "worktree_mismatch");
1250
+ return null;
1251
+ }
1252
+ if (current && current.headCommit !== data.gitStamp.headCommit) {
1253
+ stampedHead = data.gitStamp.headCommit;
1254
+ logSnapshotReadVerdict(cwd, "snapshot_read_drifted", "head_moved");
1255
+ }
1256
+ }
1257
+ const graph = {
1258
+ version: data.version,
1259
+ builtAt: data.builtAt,
1260
+ nodes: new Map(data.nodes),
1261
+ edges: data.edges,
1262
+ edgesByFrom: /* @__PURE__ */ new Map(),
1263
+ edgesByTo: /* @__PURE__ */ new Map(),
1264
+ fileNodes: /* @__PURE__ */ new Map(),
1265
+ symbolNodesByFile: /* @__PURE__ */ new Map(),
1266
+ changedSymbolsByFile: /* @__PURE__ */ new Map(),
1267
+ persistCoverage: data.coverage
1268
+ };
1269
+ rebuildIndexes(graph);
1270
+ return {
1271
+ signature: data.signature,
1272
+ fileSignatures: new Map(data.fileSignatures ?? []),
1273
+ fileHashes: new Map(data.fileHashes ?? []),
1274
+ graph,
1275
+ ...stampedHead ? { stampedHead } : {}
1276
+ };
1277
+ } catch {
1278
+ return null;
1279
+ }
1280
+ }
1281
+ function getPersistedReviewGraphVersion(cwd) {
1282
+ const cacheDir = path2.join(getProjectDataDir(cwd), "cache");
1283
+ const cachePath = path2.join(cacheDir, GRAPH_CACHE_FILENAME);
1284
+ const legacyPath = path2.join(cacheDir, LEGACY_GRAPH_CACHE_FILENAME);
1285
+ if (fs2.existsSync(cachePath)) {
1286
+ let fd2;
1287
+ try {
1288
+ fd2 = fs2.openSync(cachePath, "r");
1289
+ const compressed = Buffer.alloc(4096);
1290
+ const n = fs2.readSync(fd2, compressed, 0, compressed.length, 0);
1291
+ const head = gunzipSync(compressed.subarray(0, n), {
1292
+ finishFlush: zlibConstants.Z_SYNC_FLUSH
1293
+ }).toString("utf-8");
1294
+ const match = head.match(/"version"\s*:\s*"([^"]+)"/);
1295
+ return match ? match[1] : null;
1296
+ } catch {
1297
+ return null;
1298
+ } finally {
1299
+ if (fd2 !== void 0) {
1300
+ try {
1301
+ fs2.closeSync(fd2);
1302
+ } catch {
1303
+ }
1304
+ }
1305
+ }
1306
+ }
1307
+ let fd;
1308
+ try {
1309
+ fd = fs2.openSync(legacyPath, "r");
1310
+ const buf = Buffer.alloc(200);
1311
+ const n = fs2.readSync(fd, buf, 0, 200, 0);
1312
+ const match = buf.toString("utf-8", 0, n).match(/"version"\s*:\s*"([^"]+)"/);
1313
+ return match ? match[1] : null;
1314
+ } catch {
1315
+ return null;
1316
+ } finally {
1317
+ if (fd !== void 0) {
1318
+ try {
1319
+ fs2.closeSync(fd);
1320
+ } catch {
1321
+ }
1322
+ }
1323
+ }
1324
+ }
1325
+ function isReviewGraphMigrationNeeded(cwd) {
1326
+ const version = getPersistedReviewGraphVersion(cwd);
1327
+ return version !== null && version !== REVIEW_GRAPH_VERSION;
1328
+ }
1329
+ var GRAPH_PERSIST_DEBOUNCE_MS_DEFAULT = 1500;
1330
+ var GRAPH_PERSIST_MAX_ELEMENTS_DEFAULT = 5e5;
1331
+ function graphPersistDebounceMs() {
1332
+ const raw = Number(process.env.PI_LENS_GRAPH_PERSIST_DEBOUNCE_MS);
1333
+ return Number.isFinite(raw) && raw >= 0 ? raw : GRAPH_PERSIST_DEBOUNCE_MS_DEFAULT;
1334
+ }
1335
+ function graphPersistMaxElements() {
1336
+ const raw = Number(process.env.PI_LENS_GRAPH_PERSIST_MAX_ELEMENTS);
1337
+ return Number.isFinite(raw) && raw > 0 ? raw : GRAPH_PERSIST_MAX_ELEMENTS_DEFAULT;
1338
+ }
1339
+ var _pendingPersist = /* @__PURE__ */ new Map();
1340
+ var _persistTimers = /* @__PURE__ */ new Map();
1341
+ var _persistGenerations = /* @__PURE__ */ new Map();
1342
+ var _workerRequests = /* @__PURE__ */ new Map();
1343
+ var _persistWorker;
1344
+ var _persistWorkerRequestId = 0;
1345
+ var _persistAttemptId = 0;
1346
+ var _workerDisabled = false;
1347
+ var _persistWorkerUnavailableReason;
1348
+ var _lastWorkerFallbackReasonForTests;
1349
+ var _persistWorkerHeapStatistics = null;
1350
+ function refreshReviewGraphPersistWorkerHeapStatistics() {
1351
+ const worker = _persistWorker;
1352
+ if (!worker || typeof worker.getHeapStatistics !== "function") {
1353
+ return Promise.resolve();
1354
+ }
1355
+ return readWorkerHeapStatistics(worker).then((stats) => {
1356
+ if (_persistWorker === worker)
1357
+ _persistWorkerHeapStatistics = stats;
1358
+ }).catch(() => {
1359
+ });
1360
+ }
1361
+ function getReviewGraphPersistWorkerHeapStatistics() {
1362
+ return _persistWorkerHeapStatistics;
1363
+ }
1364
+ var _checkpointGenerations = /* @__PURE__ */ new Map();
1365
+ var _checkpointWorkerRequests = /* @__PURE__ */ new Map();
1366
+ var _checkpointOffloadCountForTests = 0;
1367
+ function persistedData(pending) {
1368
+ return {
1369
+ version: pending.graph.version,
1370
+ builtAt: pending.graph.builtAt,
1371
+ signature: pending.signature,
1372
+ fileSignatures: Array.from(pending.fileSignatures.entries()),
1373
+ fileHashes: pending.fileHashes ? Array.from(pending.fileHashes.entries()) : void 0,
1374
+ nodes: Array.from(pending.graph.nodes.entries()),
1375
+ edges: pending.graph.edges,
1376
+ coverage: stripProcessLocalCoverage(pending.graph.persistCoverage),
1377
+ gitStamp: pending.gitStamp
1378
+ };
1379
+ }
1380
+ function stripProcessLocalCoverage(coverage) {
1381
+ if (!coverage?.capTrimmed)
1382
+ return coverage;
1383
+ const { capTrimmed: _capTrimmed, ...persisted } = coverage;
1384
+ return persisted;
1385
+ }
1386
+ function countRetainedSourceFiles(graph, sourceFilePaths) {
1387
+ if (sourceFilePaths === void 0)
1388
+ return graph.fileNodes.size;
1389
+ const sourceKeys = new Set(sourceFilePaths);
1390
+ let retained = 0;
1391
+ for (const filePath of sourceKeys) {
1392
+ if (graph.fileNodes.has(filePath))
1393
+ retained++;
1394
+ }
1395
+ return retained;
1396
+ }
1397
+ function graphCoverage(graph, cap, sourceFileCount = graph.persistCoverage?.totalFiles ?? graph.fileNodes.size, sourceFilesTruncated = graph.persistCoverage?.sourceFilesTruncated === true, sourceFilePaths) {
1398
+ const inherited = graph.persistCoverage;
1399
+ return {
1400
+ partial: inherited?.partial === true || sourceFilesTruncated,
1401
+ cap,
1402
+ totalNodes: graph.nodes.size,
1403
+ totalEdges: graph.edges.length,
1404
+ persistedNodes: graph.nodes.size,
1405
+ persistedEdges: graph.edges.length,
1406
+ totalFiles: sourceFileCount,
1407
+ persistedFiles: countRetainedSourceFiles(graph, sourceFilePaths),
1408
+ ...sourceFilesTruncated ? { sourceFilesTruncated: true } : {},
1409
+ ...inherited?.inProgress ? { inProgress: true } : {}
1410
+ };
1411
+ }
1412
+ function capGraphForPersist(cwd, graph, cap, options = {}) {
1413
+ const totalElements = graph.nodes.size + graph.edges.length;
1414
+ const nodeBudget = Math.max(1, Math.floor(cap * graph.nodes.size / totalElements));
1415
+ const reverseDeps = buildReverseDependencyIndexFromGraph({ cwd, graph });
1416
+ const rankedFiles = rankFilesByReverseDependencyCentrality(reverseDeps);
1417
+ const indexNodesByFile = (fold) => {
1418
+ const byFile = /* @__PURE__ */ new Map();
1419
+ for (const [id, node] of graph.nodes) {
1420
+ if (!node.filePath)
1421
+ continue;
1422
+ const fileKey = fold ? normalizeMapKey(node.filePath) : node.filePath;
1423
+ const ids = byFile.get(fileKey) ?? [];
1424
+ ids.push(id);
1425
+ byFile.set(fileKey, ids);
1426
+ }
1427
+ return byFile;
1428
+ };
1429
+ const reachableNodes = (byFile) => {
1430
+ let reached = 0;
1431
+ for (const filePath of rankedFiles)
1432
+ reached += byFile.get(filePath)?.length ?? 0;
1433
+ return reached;
1434
+ };
1435
+ let placeableNodes = 0;
1436
+ for (const node of graph.nodes.values())
1437
+ if (node.filePath)
1438
+ placeableNodes++;
1439
+ let nodeIdsByFile = indexNodesByFile(false);
1440
+ if (reachableNodes(nodeIdsByFile) < placeableNodes) {
1441
+ const folded = indexNodesByFile(true);
1442
+ if (reachableNodes(folded) > reachableNodes(nodeIdsByFile)) {
1443
+ nodeIdsByFile = folded;
1444
+ }
1445
+ }
1446
+ const keptIds = /* @__PURE__ */ new Set();
1447
+ for (const filePath of rankedFiles) {
1448
+ const ids = nodeIdsByFile.get(filePath) ?? [];
1449
+ if (ids.length === 0)
1450
+ continue;
1451
+ const effectiveNodeBudget = keptIds.size === 0 ? Math.max(nodeBudget, Math.min(cap, ids.length)) : nodeBudget;
1452
+ if (keptIds.size + ids.length > effectiveNodeBudget)
1453
+ continue;
1454
+ for (const id of ids)
1455
+ keptIds.add(id);
1456
+ }
1457
+ const nodes = new Map([...graph.nodes].filter(([id]) => keptIds.has(id)));
1458
+ const edgeBudget = Math.max(0, cap - nodes.size);
1459
+ const edges = graph.edges.filter((edge) => keptIds.has(edge.from) && keptIds.has(edge.to)).slice(0, edgeBudget);
1460
+ const coverage = {
1461
+ partial: true,
1462
+ cap,
1463
+ totalNodes: graph.nodes.size,
1464
+ totalEdges: graph.edges.length,
1465
+ persistedNodes: nodes.size,
1466
+ persistedEdges: edges.length,
1467
+ totalFiles: options.sourceFileCount ?? graph.persistCoverage?.totalFiles ?? graph.fileNodes.size,
1468
+ persistedFiles: 0,
1469
+ ...options.sourceFilesTruncated || graph.persistCoverage?.sourceFilesTruncated ? { sourceFilesTruncated: true } : {},
1470
+ ...graph.persistCoverage?.inProgress ? { inProgress: true } : {}
1471
+ };
1472
+ const capped = {
1473
+ ...graph,
1474
+ nodes,
1475
+ edges,
1476
+ edgesByFrom: /* @__PURE__ */ new Map(),
1477
+ edgesByTo: /* @__PURE__ */ new Map(),
1478
+ fileNodes: /* @__PURE__ */ new Map(),
1479
+ symbolNodesByFile: /* @__PURE__ */ new Map(),
1480
+ changedSymbolsByFile: /* @__PURE__ */ new Map(),
1481
+ persistCoverage: void 0
1482
+ };
1483
+ rebuildIndexes(capped);
1484
+ coverage.persistedFiles = countRetainedSourceFiles(capped, options.sourceFilePaths);
1485
+ capped.persistCoverage = coverage;
1486
+ return capped;
1487
+ }
1488
+ function persistObservability(pending, patch) {
1489
+ return {
1490
+ graph: pending.graphMetadata,
1491
+ persistence: { ...pending.persistenceMetadata, ...patch }
1492
+ };
1493
+ }
1494
+ function logPersistSuccess(key, pending, stats, workerState = { started: false, completed: false }) {
1495
+ logLatency({
1496
+ type: "phase",
1497
+ phase: "review_graph_persist",
1498
+ filePath: pending.cachePath,
1499
+ durationMs: stats.durationMs,
1500
+ metadata: { elements: pending.elementCount, ...stats }
1501
+ });
1502
+ logReviewGraph({
1503
+ cwd: key,
1504
+ phase: "persist_succeeded",
1505
+ elements: pending.elementCount,
1506
+ ...stats,
1507
+ durationMs: stats.durationMs,
1508
+ observability: persistObservability(pending, {
1509
+ status: "succeeded",
1510
+ workerStarted: workerState.started,
1511
+ workerCompleted: workerState.completed,
1512
+ ...workerState.fallback ? { workerFallback: true } : {}
1513
+ })
1514
+ });
1515
+ }
1516
+ function writePendingOnMainThread(key, pending, reason, workerState = { started: false, completed: false }) {
1517
+ const persistStarted = performance.now();
1518
+ const serializeStarted = performance.now();
1519
+ try {
1520
+ const json = JSON.stringify(persistedData(pending));
1521
+ const serializeMs = performance.now() - serializeStarted;
1522
+ const rawBytes = Buffer.byteLength(json);
1523
+ const writeStarted = performance.now();
1524
+ const gzip = gzipSync(json);
1525
+ fs2.mkdirSync(pending.cacheDir, { recursive: true });
1526
+ writeFileAtomic(pending.cachePath, gzip, { bestEffort: false });
1527
+ fs2.rmSync(path2.join(pending.cacheDir, LEGACY_GRAPH_CACHE_FILENAME), {
1528
+ force: true
1529
+ });
1530
+ logPersistSuccess(key, pending, {
1531
+ rawBytes,
1532
+ gzBytes: gzip.byteLength,
1533
+ serializeMs,
1534
+ writeMs: performance.now() - writeStarted,
1535
+ durationMs: performance.now() - persistStarted,
1536
+ offloaded: false
1537
+ }, {
1538
+ started: workerState.started,
1539
+ completed: workerState.completed,
1540
+ fallback: Boolean(reason)
1541
+ });
1542
+ if (reason) {
1543
+ _lastWorkerFallbackReasonForTests = reason;
1544
+ logReviewGraph({
1545
+ cwd: key,
1546
+ phase: "worker_fallback",
1547
+ reason: "worker_fallback",
1548
+ error: reason,
1549
+ offloaded: false,
1550
+ observability: persistObservability(pending, {
1551
+ status: "fallback",
1552
+ workerStarted: workerState.started,
1553
+ workerCompleted: workerState.completed,
1554
+ workerFallback: true,
1555
+ reason: workerState.fallbackReason ?? "worker_fallback"
1556
+ })
1557
+ });
1558
+ }
1559
+ } catch (err) {
1560
+ const message = err instanceof Error ? err.message : String(err);
1561
+ recordPersistFailure(key, "cache_write_failed", message, pending, workerState);
1562
+ }
1563
+ }
1564
+ function handleWorkerMessage(message) {
1565
+ try {
1566
+ const result = readGzipStageWorkerResult(message);
1567
+ if (typeof result === "string") {
1568
+ notePersistWorkerMessageFault("review-graph", "rejected", result);
1569
+ return;
1570
+ }
1571
+ handleWorkerResult(result);
1572
+ } catch (err) {
1573
+ notePersistWorkerMessageFault("review-graph", "threw", err);
1574
+ }
1575
+ }
1576
+ function handleWorkerResult(result) {
1577
+ const checkpoint = _checkpointWorkerRequests.get(result.id);
1578
+ if (checkpoint) {
1579
+ handleCheckpointWorkerResult(checkpoint, result);
1580
+ return;
1581
+ }
1582
+ const request = _workerRequests.get(result.id);
1583
+ if (!request) {
1584
+ if (typeof result.stagePath === "string") {
1585
+ fs2.rm(result.stagePath, { force: true }, () => {
1586
+ });
1587
+ }
1588
+ return;
1589
+ }
1590
+ _workerRequests.delete(result.id);
1591
+ const { key, pending } = request;
1592
+ const currentGeneration = _persistGenerations.get(key);
1593
+ if (currentGeneration !== result.generation) {
1594
+ const reapErr = reapStageFile(request.stagePath);
1595
+ if (reapErr !== void 0) {
1596
+ logReviewGraph({
1597
+ cwd: key,
1598
+ phase: "persist_failed",
1599
+ reason: `superseded-stage reap failed: ${String(reapErr)}`
1600
+ });
1601
+ }
1602
+ logReviewGraph({
1603
+ cwd: key,
1604
+ phase: "persist_skipped",
1605
+ reason: "superseded",
1606
+ observability: persistObservability(pending, {
1607
+ status: "superseded",
1608
+ supersededByGeneration: currentGeneration,
1609
+ reason: "newer_generation_scheduled",
1610
+ workerStarted: true,
1611
+ workerCompleted: true
1612
+ })
1613
+ });
1614
+ return;
1615
+ }
1616
+ if (result.error || result.rawBytes === void 0 || result.gzBytes === void 0 || result.serializeMs === void 0 || result.writeMs === void 0 || result.durationMs === void 0) {
1617
+ fs2.rm(request.stagePath, { force: true }, () => {
1618
+ });
1619
+ writePendingOnMainThread(key, pending, result.error ?? "invalid worker result", {
1620
+ started: true,
1621
+ completed: true,
1622
+ fallbackReason: result.error ? "worker_error" : "invalid_worker_result"
1623
+ });
1624
+ return;
1625
+ }
1626
+ try {
1627
+ fs2.renameSync(request.stagePath, pending.cachePath);
1628
+ fs2.rmSync(path2.join(pending.cacheDir, LEGACY_GRAPH_CACHE_FILENAME), {
1629
+ force: true
1630
+ });
1631
+ logPersistSuccess(key, pending, {
1632
+ rawBytes: result.rawBytes,
1633
+ gzBytes: result.gzBytes,
1634
+ serializeMs: result.serializeMs,
1635
+ writeMs: result.writeMs,
1636
+ durationMs: result.durationMs,
1637
+ offloaded: true
1638
+ }, { started: true, completed: true });
1639
+ } catch (err) {
1640
+ fs2.rm(request.stagePath, { force: true }, () => {
1641
+ });
1642
+ writePendingOnMainThread(key, pending, err instanceof Error ? err.message : String(err), {
1643
+ started: true,
1644
+ completed: true,
1645
+ fallbackReason: "promotion_failed"
1646
+ });
1647
+ }
1648
+ }
1649
+ function handleCheckpointWorkerResult(cp, result) {
1650
+ _checkpointWorkerRequests.delete(result.id);
1651
+ if (result.error || result.gzBytes === void 0) {
1652
+ logReviewGraph({
1653
+ cwd: cp.cwd,
1654
+ phase: "checkpoint_write_failed",
1655
+ reason: "worker_error",
1656
+ error: result.error ?? "worker returned no gz metrics"
1657
+ });
1658
+ fs2.rm(cp.stagePath, { force: true }, () => {
1659
+ });
1660
+ return;
1661
+ }
1662
+ if (_checkpointGenerations.get(cp.cwd) !== cp.generation) {
1663
+ fs2.rm(cp.stagePath, { force: true }, () => {
1664
+ });
1665
+ return;
1666
+ }
1667
+ try {
1668
+ fs2.renameSync(cp.stagePath, cp.checkpointPath);
1669
+ logReviewGraph({
1670
+ cwd: cp.cwd,
1671
+ phase: "checkpoint_written",
1672
+ nodes: cp.nodes,
1673
+ edges: cp.edges,
1674
+ processed: cp.processed,
1675
+ target: cp.target,
1676
+ offloaded: true
1677
+ });
1678
+ } catch (err) {
1679
+ logReviewGraph({
1680
+ cwd: cp.cwd,
1681
+ phase: "checkpoint_write_failed",
1682
+ reason: "promote_failed",
1683
+ error: err instanceof Error ? err.message : String(err)
1684
+ });
1685
+ fs2.rm(cp.stagePath, { force: true }, () => {
1686
+ });
1687
+ }
1688
+ }
1689
+ function handleWorkerDeath(reason) {
1690
+ _persistWorkerUnavailableReason = reason;
1691
+ _persistWorker = void 0;
1692
+ _persistWorkerHeapStatistics = null;
1693
+ _workerDisabled = true;
1694
+ const requests = [..._workerRequests.values()];
1695
+ _workerRequests.clear();
1696
+ for (const { key, pending } of requests) {
1697
+ if (_persistGenerations.get(key) !== pending.generation) {
1698
+ logReviewGraph({
1699
+ cwd: key,
1700
+ phase: "persist_skipped",
1701
+ reason: "superseded",
1702
+ observability: persistObservability(pending, {
1703
+ status: "superseded",
1704
+ supersededByGeneration: _persistGenerations.get(key),
1705
+ reason: "worker_death_after_newer_generation",
1706
+ workerStarted: true,
1707
+ workerCompleted: false
1708
+ })
1709
+ });
1710
+ continue;
1711
+ }
1712
+ writePendingOnMainThread(key, pending, reason, {
1713
+ started: true,
1714
+ completed: false,
1715
+ fallbackReason: "worker_death"
1716
+ });
1717
+ }
1718
+ const checkpoints = [..._checkpointWorkerRequests.values()];
1719
+ _checkpointWorkerRequests.clear();
1720
+ for (const cp of checkpoints) {
1721
+ logReviewGraph({
1722
+ cwd: cp.cwd,
1723
+ phase: "checkpoint_write_failed",
1724
+ reason: "worker_death",
1725
+ error: reason
1726
+ });
1727
+ fs2.rm(cp.stagePath, { force: true }, () => {
1728
+ });
1729
+ }
1730
+ }
1731
+ function resolvePersistWorkerPath() {
1732
+ const candidates = [
1733
+ new URL("./persist-worker.js", import.meta.url),
1734
+ new URL("./workers/review-graph-persist-worker.js", import.meta.url),
1735
+ new URL("../workers/review-graph-persist-worker.js", import.meta.url)
1736
+ ];
1737
+ for (const url of candidates) {
1738
+ try {
1739
+ const resolved = fileURLToPath(url);
1740
+ if (fs2.existsSync(resolved))
1741
+ return resolved;
1742
+ } catch {
1743
+ }
1744
+ }
1745
+ return void 0;
1746
+ }
1747
+ function getPersistWorker() {
1748
+ if (_workerDisabled)
1749
+ return void 0;
1750
+ if (_persistWorker)
1751
+ return _persistWorker;
1752
+ try {
1753
+ const workerPath = resolvePersistWorkerPath();
1754
+ if (workerPath === void 0) {
1755
+ handleWorkerDeath("persist worker script not found in any layout");
1756
+ return void 0;
1757
+ }
1758
+ const worker = new Worker(workerPath);
1759
+ worker.on("message", handleWorkerMessage);
1760
+ worker.on("error", (err) => handleWorkerDeath(err.message));
1761
+ worker.on("exit", (code) => {
1762
+ if (_persistWorker !== worker)
1763
+ return;
1764
+ const hasPendingRequests = _workerRequests.size > 0 || _checkpointWorkerRequests.size > 0;
1765
+ if (code !== 0 || hasPendingRequests) {
1766
+ handleWorkerDeath(code !== 0 ? `persist worker exited with code ${code}` : "persist worker exited with pending requests");
1767
+ } else {
1768
+ _persistWorker = void 0;
1769
+ _persistWorkerHeapStatistics = null;
1770
+ }
1771
+ });
1772
+ worker.unref();
1773
+ _persistWorker = worker;
1774
+ return worker;
1775
+ } catch (err) {
1776
+ handleWorkerDeath(err instanceof Error ? err.message : String(err));
1777
+ return void 0;
1778
+ }
1779
+ }
1780
+ function writePending(key) {
1781
+ const pending = _pendingPersist.get(key);
1782
+ if (!pending)
1783
+ return;
1784
+ _pendingPersist.delete(key);
1785
+ const timer = _persistTimers.get(key);
1786
+ if (timer) {
1787
+ clearTimeout(timer);
1788
+ _persistTimers.delete(key);
1789
+ }
1790
+ const worker = getPersistWorker();
1791
+ if (!worker) {
1792
+ const unavailableReason = _persistWorkerUnavailableReason ?? "persist worker unavailable";
1793
+ writePendingOnMainThread(key, pending, unavailableReason, {
1794
+ started: false,
1795
+ completed: false,
1796
+ fallbackReason: unavailableReason
1797
+ });
1798
+ return;
1799
+ }
1800
+ const id = ++_persistWorkerRequestId;
1801
+ const stagePath = `${pending.cachePath}.stage-${process.pid}-${pending.generation}`;
1802
+ const request = {
1803
+ id,
1804
+ cwd: key,
1805
+ generation: pending.generation,
1806
+ stagePath,
1807
+ data: persistedData(pending),
1808
+ elements: pending.elementCount,
1809
+ testDelayMs: process.env.NODE_ENV === "test" ? Number(process.env.PI_LENS_TEST_PERSIST_WORKER_DELAY_MS) || void 0 : void 0
1810
+ };
1811
+ _workerRequests.set(id, { key, pending, stagePath });
1812
+ worker.postMessage(request);
1813
+ }
1814
+ var _persistExitHookInstalled = false;
1815
+ function flushPendingReviewGraphPersistsAtExit() {
1816
+ const keys = /* @__PURE__ */ new Set([
1817
+ ..._pendingPersist.keys(),
1818
+ ...[..._workerRequests.values()].map((request) => request.key)
1819
+ ]);
1820
+ for (const key of keys) {
1821
+ flushReviewGraphPersist(key, "exit_hook");
1822
+ }
1823
+ flushReviewGraphLogSync();
1824
+ void _persistWorker?.terminate();
1825
+ }
1826
+ function flushReviewGraphPersistsForExitForTests() {
1827
+ flushPendingReviewGraphPersistsAtExit();
1828
+ }
1829
+ function ensurePersistExitHook() {
1830
+ if (_persistExitHookInstalled)
1831
+ return;
1832
+ _persistExitHookInstalled = true;
1833
+ process.once("exit", flushPendingReviewGraphPersistsAtExit);
1834
+ }
1835
+ var _sweptStageDirs = /* @__PURE__ */ new Set();
1836
+ var REVIEW_GRAPH_ARTIFACT_PREFIX = "review-graph.";
1837
+ function sweepStaleStageFiles(cacheDir) {
1838
+ if (_sweptStageDirs.has(cacheDir))
1839
+ return;
1840
+ _sweptStageDirs.add(cacheDir);
1841
+ fs2.readdir(cacheDir, (err, entries) => {
1842
+ if (err)
1843
+ return;
1844
+ for (const entry of entries) {
1845
+ if (!isStaleStageFile(entry, REVIEW_GRAPH_ARTIFACT_PREFIX))
1846
+ continue;
1847
+ fs2.rm(path2.join(cacheDir, entry), { force: true }, () => {
1848
+ });
1849
+ }
1850
+ });
1851
+ }
1852
+ function _resetReviewGraphStageSweepForTests() {
1853
+ _sweptStageDirs.clear();
1854
+ }
1855
+ function persistGraph(cwd, signature, fileSignatures, fileHashes, graph, options = {}) {
1856
+ const totalElementCount = graph.nodes.size + graph.edges.length;
1857
+ const cap = graphPersistMaxElements();
1858
+ const sourceFileCount = options.sourceFileCount ?? fileSignatures.size;
1859
+ const sourceFilePaths = options.sourceFilePaths ?? fileSignatures.keys();
1860
+ const persistedGraph = totalElementCount > cap ? capGraphForPersist(cwd, graph, cap, {
1861
+ sourceFileCount,
1862
+ sourceFilesTruncated: options.sourceFilesTruncated,
1863
+ sourceFilePaths
1864
+ }) : {
1865
+ ...graph,
1866
+ persistCoverage: graphCoverage(graph, cap, sourceFileCount, options.sourceFilesTruncated, sourceFilePaths)
1867
+ };
1868
+ const elementCount = persistedGraph.nodes.size + persistedGraph.edges.length;
1869
+ const sourceWalkPartial = persistedGraph.persistCoverage?.sourceFilesTruncated === true;
1870
+ let persistReason;
1871
+ if (totalElementCount > cap) {
1872
+ const coverage = persistedGraph.persistCoverage;
1873
+ if (!coverage)
1874
+ return;
1875
+ logLatency({
1876
+ type: "phase",
1877
+ phase: "review_graph_persist",
1878
+ filePath: cwd,
1879
+ durationMs: 0,
1880
+ metadata: {
1881
+ partial: true,
1882
+ totalElements: totalElementCount,
1883
+ persistedElements: elementCount,
1884
+ cap
1885
+ }
1886
+ });
1887
+ persistReason = `persisted partial review graph (${elementCount}/${totalElementCount} elements; ${coverage.persistedNodes}/${coverage.totalNodes} nodes, ${coverage.persistedEdges}/${coverage.totalEdges} edges; ${cap} cap)`;
1888
+ } else if (sourceWalkPartial) {
1889
+ persistReason = "persisted partial review graph (source walk entry budget)";
1890
+ }
1891
+ const cacheDir = path2.join(getProjectDataDir(cwd), "cache");
1892
+ const cachePath = path2.join(cacheDir, GRAPH_CACHE_FILENAME);
1893
+ sweepStaleStageFiles(cacheDir);
1894
+ const gitStamp = (options.resolveIdentity ?? resolveGitIdentity)(cwd);
1895
+ const key = normalizeMapKey(cwd);
1896
+ const priorGeneration = _persistGenerations.get(key);
1897
+ const existingPending = _pendingPersist.get(key);
1898
+ const existingTimer = _persistTimers.get(key);
1899
+ const generation = (priorGeneration ?? 0) + 1;
1900
+ const attemptId = ++_persistAttemptId;
1901
+ const coalesced = Boolean(existingPending || existingTimer);
1902
+ _persistGenerations.set(key, generation);
1903
+ const graphMetadata = graphLogMetadata(persistedGraph, {
1904
+ ...options,
1905
+ sourceFileCount,
1906
+ sourceFileCountTruncated: persistedGraph.persistCoverage?.sourceFilesTruncated === true
1907
+ });
1908
+ const persistenceMetadata = {
1909
+ generation,
1910
+ attemptId,
1911
+ status: "scheduled",
1912
+ ...priorGeneration === void 0 ? {} : {
1913
+ supersededGeneration: priorGeneration,
1914
+ coalesced,
1915
+ reason: coalesced ? "debounced_coalescing" : "in_flight_supersession"
1916
+ }
1917
+ };
1918
+ const pending = {
1919
+ cacheDir,
1920
+ cachePath,
1921
+ // #3605: a restart re-extracts every trapped file.
1922
+ ...stampWasmTrappedFiles({ signature, fileSignatures, fileHashes }, true),
1923
+ graph: persistedGraph,
1924
+ gitStamp,
1925
+ elementCount,
1926
+ generation,
1927
+ attemptId,
1928
+ graphMetadata,
1929
+ persistenceMetadata
1930
+ };
1931
+ if (existingPending) {
1932
+ logReviewGraph({
1933
+ cwd: key,
1934
+ phase: "persist_skipped",
1935
+ reason: "superseded",
1936
+ observability: persistObservability(existingPending, {
1937
+ status: "superseded",
1938
+ supersededByGeneration: generation,
1939
+ reason: "newer_generation_scheduled",
1940
+ workerStarted: false,
1941
+ workerCompleted: false
1942
+ })
1943
+ });
1944
+ }
1945
+ _pendingPersist.set(key, pending);
1946
+ if (totalElementCount > cap || sourceWalkPartial) {
1947
+ logReviewGraph({
1948
+ cwd,
1949
+ phase: "persist_partial",
1950
+ reason: totalElementCount > cap ? "element_cap_exceeded" : "source_walk_entry_budget",
1951
+ elements: totalElementCount,
1952
+ persistedElements: elementCount,
1953
+ cap,
1954
+ observability: {
1955
+ graph: graphMetadata,
1956
+ persistence: persistenceMetadata
1957
+ }
1958
+ });
1959
+ }
1960
+ logReviewGraph({
1961
+ cwd,
1962
+ phase: "persist_scheduled",
1963
+ elements: elementCount,
1964
+ cap,
1965
+ observability: {
1966
+ graph: graphMetadata,
1967
+ persistence: persistenceMetadata
1968
+ }
1969
+ });
1970
+ ensurePersistExitHook();
1971
+ const debounce = graphPersistDebounceMs();
1972
+ const existing = _persistTimers.get(key);
1973
+ if (existing)
1974
+ clearTimeout(existing);
1975
+ if (debounce === 0) {
1976
+ writePending(key);
1977
+ return persistReason;
1978
+ }
1979
+ const timer = setTimeout(() => writePending(key), debounce);
1980
+ if (typeof timer.unref === "function")
1981
+ timer.unref();
1982
+ _persistTimers.set(key, timer);
1983
+ return persistReason;
1984
+ }
1985
+ var GRAPH_CHECKPOINT_EVERY_FILES_DEFAULT = 250;
1986
+ var GRAPH_CHECKPOINT_MIN_INTERVAL_MS_DEFAULT = 5e3;
1987
+ function graphCheckpointEveryFiles() {
1988
+ const raw = Number(process.env.PI_LENS_GRAPH_CHECKPOINT_EVERY_FILES);
1989
+ return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : GRAPH_CHECKPOINT_EVERY_FILES_DEFAULT;
1990
+ }
1991
+ function graphCheckpointMinIntervalMs() {
1992
+ const raw = Number(process.env.PI_LENS_GRAPH_CHECKPOINT_MIN_INTERVAL_MS);
1993
+ return Number.isFinite(raw) && raw >= 0 ? raw : GRAPH_CHECKPOINT_MIN_INTERVAL_MS_DEFAULT;
1994
+ }
1995
+ function reviewGraphCheckpointPath(cwd) {
1996
+ return path2.join(getProjectDataDir(cwd), "cache", GRAPH_CHECKPOINT_FILENAME);
1997
+ }
1998
+ function hashIgnoredIds(ignoredIds) {
1999
+ if (ignoredIds === void 0)
2000
+ return "unavailable";
2001
+ const joined = [...ignoredIds].sort((a, b) => compareOrdinal(a, b)).join("\0");
2002
+ return createHash2("sha256").update(joined).digest("hex");
2003
+ }
2004
+ function buildReviewGraphCheckpointData(cwd, graph, processedHashes, targetFileCount, ignoredIds, resolveIdentity = resolveGitIdentity) {
2005
+ return {
2006
+ version: REVIEW_GRAPH_VERSION,
2007
+ builtAt: (/* @__PURE__ */ new Date()).toISOString(),
2008
+ inProgress: true,
2009
+ targetFileCount,
2010
+ processedFiles: Array.from(stampWasmTrapped(processedHashes, true)),
2011
+ ignoredIdsHash: hashIgnoredIds(ignoredIds),
2012
+ nodes: Array.from(graph.nodes.entries()),
2013
+ edges: graph.edges,
2014
+ gitStamp: resolveIdentity(cwd)
2015
+ };
2016
+ }
2017
+ function writeReviewGraphCheckpoint(cwd, graph, processedHashes, targetFileCount, ignoredIds, resolveIdentity = resolveGitIdentity) {
2018
+ const generation = (_checkpointGenerations.get(cwd) ?? 0) + 1;
2019
+ _checkpointGenerations.set(cwd, generation);
2020
+ let data;
2021
+ try {
2022
+ data = buildReviewGraphCheckpointData(cwd, graph, processedHashes, targetFileCount, ignoredIds, resolveIdentity);
2023
+ } catch {
2024
+ return;
2025
+ }
2026
+ const worker = _workerDisabled ? void 0 : getPersistWorker();
2027
+ if (!worker) {
2028
+ writeReviewGraphCheckpointSync(cwd, data, {
2029
+ nodes: graph.nodes.size,
2030
+ edges: graph.edges.length,
2031
+ processed: processedHashes.size,
2032
+ target: targetFileCount
2033
+ });
2034
+ return;
2035
+ }
2036
+ const checkpointPath = reviewGraphCheckpointPath(cwd);
2037
+ const cacheDir = path2.dirname(checkpointPath);
2038
+ try {
2039
+ fs2.mkdirSync(cacheDir, { recursive: true });
2040
+ } catch (err) {
2041
+ logReviewGraph({
2042
+ cwd,
2043
+ phase: "checkpoint_write_failed",
2044
+ reason: "mkdir_failed",
2045
+ error: err instanceof Error ? err.message : String(err)
2046
+ });
2047
+ return;
2048
+ }
2049
+ sweepStaleStageFiles(cacheDir);
2050
+ ensurePersistExitHook();
2051
+ const id = ++_persistWorkerRequestId;
2052
+ const stagePath = `${checkpointPath}.stage-${process.pid}-${generation}`;
2053
+ _checkpointWorkerRequests.set(id, {
2054
+ cwd,
2055
+ generation,
2056
+ checkpointPath,
2057
+ stagePath,
2058
+ nodes: graph.nodes.size,
2059
+ edges: graph.edges.length,
2060
+ processed: processedHashes.size,
2061
+ target: targetFileCount
2062
+ });
2063
+ const request = {
2064
+ id,
2065
+ cwd,
2066
+ generation,
2067
+ stagePath,
2068
+ data,
2069
+ elements: graph.nodes.size + graph.edges.length,
2070
+ testDelayMs: process.env.NODE_ENV === "test" ? Number(process.env.PI_LENS_TEST_PERSIST_WORKER_DELAY_MS) || void 0 : void 0
2071
+ };
2072
+ worker.postMessage(request);
2073
+ _checkpointOffloadCountForTests++;
2074
+ }
2075
+ function writeReviewGraphCheckpointSync(cwd, data, counts) {
2076
+ try {
2077
+ const gzip = gzipSync(JSON.stringify(data));
2078
+ fs2.mkdirSync(path2.dirname(reviewGraphCheckpointPath(cwd)), {
2079
+ recursive: true
2080
+ });
2081
+ writeFileAtomic(reviewGraphCheckpointPath(cwd), gzip, { bestEffort: true });
2082
+ logReviewGraph({
2083
+ cwd,
2084
+ phase: "checkpoint_written",
2085
+ nodes: counts.nodes,
2086
+ edges: counts.edges,
2087
+ processed: counts.processed,
2088
+ target: counts.target
2089
+ });
2090
+ } catch (err) {
2091
+ logReviewGraph({
2092
+ cwd,
2093
+ phase: "checkpoint_write_failed",
2094
+ reason: "sync_write_failed",
2095
+ error: err instanceof Error ? err.message : String(err)
2096
+ });
2097
+ }
2098
+ }
2099
+ function deleteReviewGraphCheckpoint(cwd) {
2100
+ _checkpointGenerations.set(cwd, (_checkpointGenerations.get(cwd) ?? 0) + 1);
2101
+ fs2.rm(reviewGraphCheckpointPath(cwd), { force: true }, () => {
2102
+ });
2103
+ }
2104
+ function loadReviewGraphCheckpoint(cwd, resolveIdentity = resolveGitIdentity) {
2105
+ const checkpointPath = reviewGraphCheckpointPath(cwd);
2106
+ let data;
2107
+ try {
2108
+ if (!fs2.existsSync(checkpointPath))
2109
+ return null;
2110
+ data = JSON.parse(gunzipSync(fs2.readFileSync(checkpointPath)).toString("utf-8"));
2111
+ } catch {
2112
+ logReviewGraph({ cwd, phase: "checkpoint_discarded", reason: "corrupt" });
2113
+ deleteReviewGraphCheckpoint(cwd);
2114
+ return null;
2115
+ }
2116
+ if (data.version !== REVIEW_GRAPH_VERSION || data.inProgress !== true) {
2117
+ logReviewGraph({
2118
+ cwd,
2119
+ phase: "checkpoint_discarded",
2120
+ reason: data.version !== REVIEW_GRAPH_VERSION ? "version_mismatch" : "not_in_progress"
2121
+ });
2122
+ deleteReviewGraphCheckpoint(cwd);
2123
+ return null;
2124
+ }
2125
+ if (data.gitStamp) {
2126
+ const current = resolveIdentity(cwd);
2127
+ if (current && current.worktreeRoot !== data.gitStamp.worktreeRoot) {
2128
+ logReviewGraph({
2129
+ cwd,
2130
+ phase: "checkpoint_discarded",
2131
+ reason: "worktree_mismatch"
2132
+ });
2133
+ deleteReviewGraphCheckpoint(cwd);
2134
+ return null;
2135
+ }
2136
+ }
2137
+ const totalNodes = data.nodes.length;
2138
+ const totalEdges = data.edges.length;
2139
+ const graph = {
2140
+ version: data.version,
2141
+ builtAt: data.builtAt,
2142
+ nodes: new Map(data.nodes),
2143
+ edges: data.edges,
2144
+ edgesByFrom: /* @__PURE__ */ new Map(),
2145
+ edgesByTo: /* @__PURE__ */ new Map(),
2146
+ fileNodes: /* @__PURE__ */ new Map(),
2147
+ symbolNodesByFile: /* @__PURE__ */ new Map(),
2148
+ changedSymbolsByFile: /* @__PURE__ */ new Map(),
2149
+ persistCoverage: {
2150
+ partial: true,
2151
+ inProgress: true,
2152
+ cap: 0,
2153
+ totalNodes,
2154
+ totalEdges,
2155
+ persistedNodes: totalNodes,
2156
+ persistedEdges: totalEdges,
2157
+ totalFiles: data.targetFileCount,
2158
+ persistedFiles: 0
2159
+ }
2160
+ };
2161
+ rebuildIndexes(graph);
2162
+ if (graph.persistCoverage) {
2163
+ graph.persistCoverage.persistedFiles = countRetainedSourceFiles(graph, data.processedFiles.map(([filePath]) => filePath));
2164
+ }
2165
+ return {
2166
+ graph,
2167
+ processedHashes: new Map(data.processedFiles),
2168
+ ignoredIdsHash: data.ignoredIdsHash,
2169
+ targetFileCount: data.targetFileCount
2170
+ };
2171
+ }
2172
+ function pruneOrphanNonFileNodes(graph) {
2173
+ const referenced = /* @__PURE__ */ new Set();
2174
+ for (const edge of graph.edges) {
2175
+ referenced.add(edge.from);
2176
+ referenced.add(edge.to);
2177
+ }
2178
+ for (const [id, node] of graph.nodes) {
2179
+ if (!node.filePath && !referenced.has(id))
2180
+ graph.nodes.delete(id);
2181
+ }
2182
+ }
2183
+ async function tryResumeFromCheckpoint(cwd, filesToBuild, ignoredIds, resolveIdentity = resolveGitIdentity) {
2184
+ const loaded = loadReviewGraphCheckpoint(cwd, resolveIdentity);
2185
+ if (!loaded)
2186
+ return null;
2187
+ if (loaded.ignoredIdsHash !== hashIgnoredIds(ignoredIds)) {
2188
+ logReviewGraph({
2189
+ cwd,
2190
+ phase: "checkpoint_discarded",
2191
+ reason: "ignored_ids_mismatch",
2192
+ processed: loaded.processedHashes.size,
2193
+ target: filesToBuild.length
2194
+ });
2195
+ deleteReviewGraphCheckpoint(cwd);
2196
+ return null;
2197
+ }
2198
+ const targetSet = new Set(filesToBuild);
2199
+ for (const file of loaded.processedHashes.keys()) {
2200
+ if (!targetSet.has(file)) {
2201
+ logReviewGraph({
2202
+ cwd,
2203
+ phase: "checkpoint_discarded",
2204
+ reason: "removed_file",
2205
+ processed: loaded.processedHashes.size,
2206
+ target: filesToBuild.length
2207
+ });
2208
+ deleteReviewGraphCheckpoint(cwd);
2209
+ return null;
2210
+ }
2211
+ }
2212
+ const reusableHashes = /* @__PURE__ */ new Map();
2213
+ const stale = [];
2214
+ let sinceYield = 0;
2215
+ for (const [file, priorHash] of loaded.processedHashes) {
2216
+ const currentHash = contentHashEntry(file);
2217
+ if (currentHash === priorHash)
2218
+ reusableHashes.set(file, currentHash);
2219
+ else
2220
+ stale.push(file);
2221
+ if (++sinceYield >= STAT_YIELD_EVERY) {
2222
+ sinceYield = 0;
2223
+ await yieldToLoop();
2224
+ }
2225
+ }
2226
+ if (reusableHashes.size === 0) {
2227
+ logReviewGraph({
2228
+ cwd,
2229
+ phase: "checkpoint_discarded",
2230
+ reason: "all_stale",
2231
+ stale: stale.length,
2232
+ target: filesToBuild.length
2233
+ });
2234
+ deleteReviewGraphCheckpoint(cwd);
2235
+ return null;
2236
+ }
2237
+ const graph = loaded.graph;
2238
+ const removedEdges = /* @__PURE__ */ new Set();
2239
+ for (const file of stale)
2240
+ removeFileOwnedGraphData(graph, file, removedEdges);
2241
+ if (removedEdges.size > 0) {
2242
+ unindexEdges(graph, removedEdges);
2243
+ graph.edges = graph.edges.filter((edge) => !removedEdges.has(edge));
2244
+ }
2245
+ pruneOrphanNonFileNodes(graph);
2246
+ graph.changedSymbolsByFile = /* @__PURE__ */ new Map();
2247
+ const remaining = filesToBuild.filter((file) => !reusableHashes.has(file));
2248
+ logReviewGraph({
2249
+ cwd,
2250
+ phase: "checkpoint_resumed",
2251
+ reused: reusableHashes.size,
2252
+ stale: stale.length,
2253
+ remaining: remaining.length,
2254
+ target: filesToBuild.length
2255
+ });
2256
+ return { graph, fileHashes: reusableHashes, remaining };
2257
+ }
2258
+ function _readReviewGraphCheckpointForTests(cwd) {
2259
+ const loaded = loadReviewGraphCheckpoint(cwd);
2260
+ if (!loaded)
2261
+ return null;
2262
+ return {
2263
+ inProgress: loaded.graph.persistCoverage?.inProgress === true,
2264
+ processedFiles: [...loaded.processedHashes.keys()],
2265
+ nodeCount: loaded.graph.nodes.size,
2266
+ edgeCount: loaded.graph.edges.length,
2267
+ persistCoverage: loaded.graph.persistCoverage
2268
+ };
2269
+ }
2270
+ function flushReviewGraphPersistsForTests() {
2271
+ for (const key of _pendingPersist.keys()) {
2272
+ const pending = _pendingPersist.get(key);
2273
+ if (!pending)
2274
+ continue;
2275
+ _pendingPersist.delete(key);
2276
+ const timer = _persistTimers.get(key);
2277
+ if (timer)
2278
+ clearTimeout(timer);
2279
+ _persistTimers.delete(key);
2280
+ writePendingOnMainThread(key, pending);
2281
+ }
2282
+ }
2283
+ async function waitForReviewGraphPersistsForTests() {
2284
+ for (let attempts = 0; attempts < 200 && (_workerRequests.size > 0 || _checkpointWorkerRequests.size > 0); attempts++) {
2285
+ await new Promise((resolve2) => setTimeout(resolve2, 10));
2286
+ }
2287
+ }
2288
+ async function terminateReviewGraphPersistWorkerForTests() {
2289
+ const worker = _persistWorker;
2290
+ if (worker)
2291
+ await worker.terminate();
2292
+ }
2293
+ function resetReviewGraphPersistWorkerForTests() {
2294
+ _workerDisabled = false;
2295
+ _persistWorker = void 0;
2296
+ _persistWorkerHeapStatistics = null;
2297
+ _persistWorkerUnavailableReason = void 0;
2298
+ _lastWorkerFallbackReasonForTests = void 0;
2299
+ _checkpointWorkerRequests.clear();
2300
+ _checkpointGenerations.clear();
2301
+ _checkpointOffloadCountForTests = 0;
2302
+ }
2303
+ function getCheckpointOffloadCountForTests() {
2304
+ return _checkpointOffloadCountForTests;
2305
+ }
2306
+ function getReviewGraphWorkerFallbackReasonForTests() {
2307
+ return _lastWorkerFallbackReasonForTests;
2308
+ }
2309
+ function reviewGraphCachePath(cwd) {
2310
+ return path2.join(getProjectDataDir(cwd), "cache", GRAPH_CACHE_FILENAME);
2311
+ }
2312
+ function flushReviewGraphPersist(cwd, source = "cli") {
2313
+ const key = normalizeMapKey(cwd);
2314
+ let pending = _pendingPersist.get(key);
2315
+ const removedWorkerRequests = [];
2316
+ let selectedWorkerRequest;
2317
+ for (const [id, request] of _workerRequests) {
2318
+ if (request.key !== key)
2319
+ continue;
2320
+ _workerRequests.delete(id);
2321
+ removedWorkerRequests.push(request.pending);
2322
+ if (!pending || request.pending.generation > pending.generation) {
2323
+ pending = request.pending;
2324
+ selectedWorkerRequest = request.pending;
2325
+ }
2326
+ }
2327
+ for (const removed of removedWorkerRequests) {
2328
+ if (!pending || removed.generation === pending.generation)
2329
+ continue;
2330
+ logReviewGraph({
2331
+ cwd: key,
2332
+ phase: "persist_skipped",
2333
+ reason: "superseded",
2334
+ observability: persistObservability(removed, {
2335
+ status: "superseded",
2336
+ supersededByGeneration: pending.generation,
2337
+ reason: "forced_flush_newest_generation",
2338
+ workerStarted: true,
2339
+ workerCompleted: false
2340
+ })
2341
+ });
2342
+ }
2343
+ const currentGeneration = _persistGenerations.get(key);
2344
+ if (pending && pending.generation !== currentGeneration) {
2345
+ logReviewGraph({
2346
+ cwd: key,
2347
+ phase: "persist_skipped",
2348
+ reason: "superseded",
2349
+ observability: persistObservability(pending, {
2350
+ status: "superseded",
2351
+ supersededByGeneration: currentGeneration,
2352
+ reason: "forced_flush_superseded",
2353
+ workerStarted: true,
2354
+ workerCompleted: false
2355
+ })
2356
+ });
2357
+ return {
2358
+ ok: false,
2359
+ reason: `queued snapshot generation ${pending.generation} was superseded by generation ${currentGeneration}`
2360
+ };
2361
+ }
2362
+ if (!pending) {
2363
+ return {
2364
+ ok: false,
2365
+ reason: "no graph snapshot was queued for persistence"
2366
+ };
2367
+ }
2368
+ _persistGenerations.set(key, Math.max(_persistGenerations.get(key) ?? 0, pending.generation) + 1);
2369
+ _pendingPersist.delete(key);
2370
+ const timer = _persistTimers.get(key);
2371
+ if (timer) {
2372
+ clearTimeout(timer);
2373
+ _persistTimers.delete(key);
2374
+ }
2375
+ const startedAt = performance.now();
2376
+ try {
2377
+ const serializeStarted = performance.now();
2378
+ const json = JSON.stringify(persistedData(pending));
2379
+ const serializeMs = performance.now() - serializeStarted;
2380
+ const rawBytes = Buffer.byteLength(json);
2381
+ const writeStarted = performance.now();
2382
+ const gzip = gzipSync(json);
2383
+ fs2.mkdirSync(pending.cacheDir, { recursive: true });
2384
+ writeFileAtomic(pending.cachePath, gzip, { bestEffort: false });
2385
+ fs2.rmSync(path2.join(pending.cacheDir, LEGACY_GRAPH_CACHE_FILENAME), {
2386
+ force: true
2387
+ });
2388
+ const writeMs = performance.now() - writeStarted;
2389
+ logLatency({
2390
+ type: "phase",
2391
+ phase: "review_graph_persist",
2392
+ filePath: pending.cachePath,
2393
+ durationMs: performance.now() - startedAt,
2394
+ metadata: {
2395
+ elements: pending.elementCount,
2396
+ rawBytes,
2397
+ gzBytes: gzip.byteLength,
2398
+ serializeMs,
2399
+ writeMs,
2400
+ offloaded: false
2401
+ }
2402
+ });
2403
+ logReviewGraph({
2404
+ cwd,
2405
+ phase: "persist_succeeded",
2406
+ durationMs: performance.now() - startedAt,
2407
+ elements: pending.elementCount,
2408
+ rawBytes,
2409
+ gzBytes: gzip.byteLength,
2410
+ serializeMs,
2411
+ writeMs,
2412
+ offloaded: false,
2413
+ observability: persistObservability(pending, {
2414
+ status: "succeeded",
2415
+ reason: source === "exit_hook" ? "exit_flush" : "forced_flush",
2416
+ workerStarted: selectedWorkerRequest !== void 0,
2417
+ workerCompleted: false
2418
+ })
2419
+ });
2420
+ return {
2421
+ ok: true,
2422
+ path: pending.cachePath,
2423
+ bytes: gzip.byteLength,
2424
+ elements: pending.elementCount,
2425
+ coverage: pending.graph.persistCoverage
2426
+ };
2427
+ } catch (err) {
2428
+ const reason = err instanceof Error ? err.message : String(err);
2429
+ recordPersistFailure(cwd, source === "exit_hook" ? "exit_flush_failed" : "forced_flush_failed", reason, pending, selectedWorkerRequest ? {
2430
+ started: true,
2431
+ completed: false,
2432
+ fallbackReason: "forced_flush_write_failed"
2433
+ } : void 0);
2434
+ return { ok: false, reason };
2435
+ }
2436
+ }
2437
+ function localImportToFile(cwd, filePath, source, ignoredIds) {
2438
+ if (!source.startsWith(".")) {
2439
+ const aliased = resolveAliasedImport(cwd, source, path2.dirname(filePath));
2440
+ const referenced = aliased.length ? [] : resolveProjectReferenceImport(cwd, source, path2.dirname(filePath));
2441
+ const resolved = aliased.length ? aliased : referenced.length ? referenced : resolveWorkspacePackageImport(cwd, source);
2442
+ for (const normalized of resolved) {
2443
+ if (ignoredIds?.has(normalized))
2444
+ continue;
2445
+ return normalized;
2446
+ }
2447
+ return void 0;
2448
+ }
2449
+ const root = path2.resolve(cwd);
2450
+ for (const candidate of jsTsCandidatePaths(filePath, source)) {
2451
+ if (!fs2.existsSync(candidate))
2452
+ continue;
2453
+ const normalized = normalizeMapKey(candidate);
2454
+ if (!isUnderDir(normalized, root))
2455
+ continue;
2456
+ if (ignoredIds?.has(normalized))
2457
+ continue;
2458
+ return normalized;
2459
+ }
2460
+ return void 0;
2461
+ }
2462
+ function upsertChangedSymbols(graph, facts, filePath) {
2463
+ if (detectFileRole(filePath) === "test")
2464
+ return;
2465
+ const normalized = normalizeMapKey(filePath);
2466
+ const changed = facts.getBoundedSessionFact(`${CHANGED_SYMBOLS_PREFIX}${normalized}`);
2467
+ if (changed && changed.length > 0) {
2468
+ graph.changedSymbolsByFile.set(normalized, [...changed]);
2469
+ } else {
2470
+ graph.changedSymbolsByFile.delete(normalized);
2471
+ }
2472
+ }
2473
+ async function ensureReviewGraphFacts(filePath, cwd, facts, contentOverride) {
2474
+ const ctx = makeCtx(filePath, cwd, facts);
2475
+ if (contentOverride === void 0) {
2476
+ await fileContentProvider.run(ctx, facts);
2477
+ } else {
2478
+ facts.setFileFact(filePath, "file.content", contentOverride);
2479
+ }
2480
+ try {
2481
+ const [{ importFactProvider }, { functionFactProvider }] = await Promise.all([
2482
+ import("./chunk-HAD7QRQI.js"),
2483
+ import("./chunk-3QED2P4V.js")
2484
+ ]);
2485
+ await importFactProvider.run(ctx, facts);
2486
+ await functionFactProvider.run(ctx, facts);
2487
+ } catch (err) {
2488
+ logReviewGraph({
2489
+ cwd,
2490
+ phase: "build_skipped",
2491
+ reason: "structural_facts_disabled",
2492
+ error: err?.message ?? String(err)
2493
+ });
2494
+ }
2495
+ }
2496
+ function addJsTsFile(graph, cwd, filePath, facts, ignoredIds) {
2497
+ const normalized = normalizeMapKey(filePath);
2498
+ const hintPath = toProjectRelativePath(normalized, cwd);
2499
+ const content = facts.getFileFact(normalized, "file.content") ?? "";
2500
+ const fileNodeId = `file:${normalized}`;
2501
+ const warmCallCoverage = facts.getFileFact(normalized, "file.functionFactsCoverage") ?? "unavailable";
2502
+ const importCoverage = facts.getFileFact(normalized, "file.importFactsCoverage") ?? "unavailable";
2503
+ addNode(graph, {
2504
+ id: fileNodeId,
2505
+ kind: "file",
2506
+ language: "jsts",
2507
+ filePath: normalized,
2508
+ metadata: {
2509
+ lineCount: content.split("\n").length,
2510
+ extractionCoverage: {
2511
+ definitions: warmCallCoverage,
2512
+ references: warmCallCoverage,
2513
+ imports: importCoverage,
2514
+ calls: warmCallCoverage
2515
+ },
2516
+ ...featureHintMetadata(hintPath)
2517
+ }
2518
+ });
2519
+ const imports = facts.getFileFact(normalized, "file.imports") ?? [];
2520
+ const functions = facts.getFileFact(normalized, "file.functionSummaries") ?? [];
2521
+ for (const entry of imports) {
2522
+ const localFile = localImportToFile(cwd, normalized, entry.source, ignoredIds);
2523
+ if (localFile) {
2524
+ const targetId = `file:${localFile}`;
2525
+ if (!graph.nodes.has(targetId)) {
2526
+ addNode(graph, {
2527
+ id: targetId,
2528
+ kind: "file",
2529
+ language: detectFileKind(localFile) ?? "jsts",
2530
+ filePath: localFile
2531
+ });
2532
+ }
2533
+ addEdge(graph, { from: fileNodeId, to: targetId, kind: "imports" });
2534
+ } else {
2535
+ const targetId = `${entry.source.startsWith(".") ? "module" : "external"}:${entry.source}`;
2536
+ if (!graph.nodes.has(targetId)) {
2537
+ addNode(graph, {
2538
+ id: targetId,
2539
+ kind: entry.source.startsWith(".") ? "module" : "external",
2540
+ language: "jsts",
2541
+ metadata: { source: entry.source }
2542
+ });
2543
+ }
2544
+ addEdge(graph, { from: fileNodeId, to: targetId, kind: "imports" });
2545
+ }
2546
+ }
2547
+ const importedNameToFile = /* @__PURE__ */ new Map();
2548
+ for (const entry of imports) {
2549
+ const localFile = localImportToFile(cwd, normalized, entry.source, ignoredIds);
2550
+ if (!localFile)
2551
+ continue;
2552
+ for (const name of entry.names)
2553
+ importedNameToFile.set(name, localFile);
2554
+ if (entry.defaultName)
2555
+ importedNameToFile.set(entry.defaultName, localFile);
2556
+ }
2557
+ const methodsByQualifiedName = /* @__PURE__ */ new Map();
2558
+ for (const fn of functions) {
2559
+ const symbolId = buildSymbolId(normalized, fn.name, "function", fn.line);
2560
+ const qualifiedName = buildQualifiedName(fn.owner, fn.name);
2561
+ if (qualifiedName) {
2562
+ const existing = methodsByQualifiedName.get(qualifiedName) ?? [];
2563
+ existing.push(symbolId);
2564
+ methodsByQualifiedName.set(qualifiedName, existing);
2565
+ }
2566
+ addNode(graph, {
2567
+ id: symbolId,
2568
+ kind: "symbol",
2569
+ language: "jsts",
2570
+ filePath: normalized,
2571
+ symbolName: fn.name,
2572
+ symbolKind: "function",
2573
+ ...qualifiedName ? { qualifiedName } : {},
2574
+ exported: new RegExp(String.raw`export\s+(?:async\s+)?(?:function|const|let|var)\s+${escapeRegExp(fn.name)}\b`).test(content),
2575
+ metadata: {
2576
+ line: fn.line,
2577
+ endLine: fn.endLine,
2578
+ column: fn.column,
2579
+ cyclomaticComplexity: fn.cyclomaticComplexity,
2580
+ maxNestingDepth: fn.maxNestingDepth,
2581
+ isBoundaryWrapper: fn.isBoundaryWrapper,
2582
+ isPassThroughWrapper: fn.isPassThroughWrapper,
2583
+ ...featureHintMetadata(`${fn.name} ${hintPath}`)
2584
+ }
2585
+ });
2586
+ addEdge(graph, { from: fileNodeId, to: symbolId, kind: "contains" });
2587
+ addEdge(graph, { from: fileNodeId, to: symbolId, kind: "defines" });
2588
+ }
2589
+ for (const fn of functions) {
2590
+ const symbolId = buildSymbolId(normalized, fn.name, "function", fn.line);
2591
+ const memberCallTexts = /* @__PURE__ */ new Set();
2592
+ for (const site of fn.memberCallSites ?? []) {
2593
+ const callText = `${site.receiver}.${site.method}`;
2594
+ memberCallTexts.add(callText);
2595
+ const receiverClass = fn.receiverTypes?.[site.receiver];
2596
+ const candidates = receiverClass ? methodsByQualifiedName.get(`${receiverClass}.${site.method}`) ?? [] : [];
2597
+ if (candidates.length === 1) {
2598
+ addEdge(graph, {
2599
+ from: symbolId,
2600
+ to: candidates[0],
2601
+ kind: "calls",
2602
+ metadata: {
2603
+ unresolvedName: callText,
2604
+ receiver: site.receiver,
2605
+ receiverType: receiverClass
2606
+ },
2607
+ resolution: "receiver-type"
2608
+ });
2609
+ continue;
2610
+ }
2611
+ if (candidates.length > 1) {
2612
+ const qualifiedPlaceholderId = `symbol-qualified-name:${receiverClass}.${site.method}`;
2613
+ if (!graph.nodes.has(qualifiedPlaceholderId)) {
2614
+ addNode(graph, {
2615
+ id: qualifiedPlaceholderId,
2616
+ kind: "symbol",
2617
+ language: "jsts",
2618
+ symbolName: site.method,
2619
+ qualifiedName: `${receiverClass}.${site.method}`,
2620
+ metadata: {
2621
+ unresolvedName: callText,
2622
+ ambiguousCandidates: candidates.length
2623
+ }
2624
+ });
2625
+ }
2626
+ addEdge(graph, {
2627
+ from: symbolId,
2628
+ to: qualifiedPlaceholderId,
2629
+ kind: "calls",
2630
+ metadata: {
2631
+ unresolvedName: callText,
2632
+ receiver: site.receiver,
2633
+ receiverType: receiverClass
2634
+ },
2635
+ resolution: "name-only"
2636
+ });
2637
+ continue;
2638
+ }
2639
+ const externalId = `external:${callText}`;
2640
+ if (!graph.nodes.has(externalId)) {
2641
+ addNode(graph, {
2642
+ id: externalId,
2643
+ kind: "external",
2644
+ language: "jsts",
2645
+ metadata: { unresolvedName: callText }
2646
+ });
2647
+ }
2648
+ addEdge(graph, {
2649
+ from: symbolId,
2650
+ to: externalId,
2651
+ kind: "calls",
2652
+ metadata: { unresolvedName: callText }
2653
+ });
2654
+ }
2655
+ for (const callee of fn.outgoingCalls) {
2656
+ if (memberCallTexts.has(callee))
2657
+ continue;
2658
+ const targetId = callee.includes(".") ? `external:${callee}` : `symbol-name:${callee}`;
2659
+ if (!graph.nodes.has(targetId)) {
2660
+ addNode(graph, {
2661
+ id: targetId,
2662
+ kind: callee.includes(".") ? "external" : "symbol",
2663
+ language: "jsts",
2664
+ symbolName: callee.includes(".") ? void 0 : callee,
2665
+ metadata: { unresolvedName: callee }
2666
+ });
2667
+ }
2668
+ const importHintFile = !callee.includes(".") ? importedNameToFile.get(callee) : void 0;
2669
+ addEdge(graph, {
2670
+ from: symbolId,
2671
+ to: targetId,
2672
+ kind: "calls",
2673
+ metadata: {
2674
+ unresolvedName: callee,
2675
+ ...importHintFile ? { importHintFile } : {}
2676
+ },
2677
+ // A definite external call (`callee.includes(".")`) is never
2678
+ // ambiguous — no in-project candidate to collide with, so no
2679
+ // resolution marker. An in-project bare-name callee starts
2680
+ // "name-only" and resolveDeferredSymbolEdges below may upgrade it
2681
+ // to "import" (when importHintFile narrows it) or "exact" once
2682
+ // every file has been added.
2683
+ ...callee.includes(".") ? {} : { resolution: "name-only" }
2684
+ });
2685
+ }
2686
+ }
2687
+ }
2688
+ function mapKindToTreeSitterLanguage(kind, filePath) {
2689
+ return symbolExtractionGrammar(kind, filePath);
2690
+ }
2691
+ async function getExtractor(languageId) {
2692
+ if (extractorCache.has(languageId))
2693
+ return extractorCache.get(languageId);
2694
+ const client = getSharedTreeSitterClient();
2695
+ if (!client)
2696
+ return null;
2697
+ const extractor = new TreeSitterSymbolExtractor(languageId, client);
2698
+ const ok = await extractor.init();
2699
+ if (!ok) {
2700
+ extractorCache.set(languageId, null);
2701
+ return null;
2702
+ }
2703
+ extractorCache.set(languageId, extractor);
2704
+ return extractor;
2705
+ }
2706
+ async function extractTreeSitterSymbols(filePath, languageId, contentOverride) {
2707
+ const empty = {
2708
+ symbols: [],
2709
+ refs: [],
2710
+ imports: [],
2711
+ coverage: {
2712
+ definitions: "unavailable",
2713
+ references: "unavailable",
2714
+ imports: "unavailable"
2715
+ }
2716
+ };
2717
+ if (contentOverride === null)
2718
+ return empty;
2719
+ const treeSitterClient = getSharedTreeSitterClient();
2720
+ if (!treeSitterClient)
2721
+ return empty;
2722
+ const initialized = await treeSitterClient.init();
2723
+ if (!initialized)
2724
+ return empty;
2725
+ const extractor = await getExtractor(languageId);
2726
+ if (!extractor)
2727
+ return empty;
2728
+ const content = contentOverride ?? fs2.readFileSync(filePath, "utf-8");
2729
+ const extracted = await treeSitterClient.withParsedTree(filePath, languageId, content, (tree) => extractor.extract(tree, filePath, content), "review-graph");
2730
+ return extracted.parsed ? extracted.value : { ...empty, wasmTrap: extracted.wasmTrap };
2731
+ }
2732
+ async function captureReviewGraphStructuralIr(filePath, cwd, content, borrowed) {
2733
+ const kind = detectFileKind(filePath);
2734
+ if (!kind || !MAIN_KINDS.has(kind) || detectFileRole(filePath) === "test") {
2735
+ return { complete: true };
2736
+ }
2737
+ if (kind === "jsts") {
2738
+ const borrowable = borrowed.hasFileFact(filePath, "file.imports") && borrowed.hasFileFact(filePath, "file.reexports") && borrowed.hasFileFact(filePath, "file.functionSummaries") && borrowed.getFileFact(filePath, "file.content") === content;
2739
+ let facts = borrowed;
2740
+ if (!borrowable) {
2741
+ const run = new FactStore("review-graph-run");
2742
+ await ensureReviewGraphFacts(filePath, cwd, run, content);
2743
+ facts = run;
2744
+ }
2745
+ const parsed = await withTreeSitterRoot(filePath, content, () => true, "review-graph-ir");
2746
+ if (!parsed.parsed)
2747
+ return { complete: false };
2748
+ const functionCoverage = facts.getFileFact(filePath, "file.functionFactsCoverage") ?? "unavailable";
2749
+ const importCoverage = facts.getFileFact(filePath, "file.importFactsCoverage") ?? "unavailable";
2750
+ const coverage = {
2751
+ definitions: functionCoverage,
2752
+ references: functionCoverage,
2753
+ imports: importCoverage,
2754
+ calls: functionCoverage
2755
+ };
2756
+ if (Object.values(coverage).some((status) => status !== "complete")) {
2757
+ return { complete: false };
2758
+ }
2759
+ return {
2760
+ complete: true,
2761
+ structural: {
2762
+ kind: "jsts",
2763
+ imports: facts.getFileFact(filePath, "file.imports") ?? [],
2764
+ reexports: facts.getFileFact(filePath, "file.reexports") ?? [],
2765
+ functionSummaries: facts.getFileFact(filePath, "file.functionSummaries") ?? [],
2766
+ coverage
2767
+ }
2768
+ };
2769
+ }
2770
+ const languageId = mapKindToTreeSitterLanguage(kind, filePath);
2771
+ if (!languageId)
2772
+ return { complete: false };
2773
+ const client = getSharedTreeSitterClient();
2774
+ if (!client || !await client.init())
2775
+ return { complete: false };
2776
+ const extractor = await getExtractor(languageId);
2777
+ if (!extractor)
2778
+ return { complete: false };
2779
+ const result = await client.withParsedTree(filePath, languageId, content, (tree) => extractor.extract(tree, filePath, content), "review-graph");
2780
+ if (!result.parsed)
2781
+ return { complete: false };
2782
+ return {
2783
+ complete: true,
2784
+ structural: {
2785
+ kind: "tree-sitter",
2786
+ languageId,
2787
+ extracted: result.value
2788
+ }
2789
+ };
2790
+ }
2791
+ var SYMBOL_KIND_SPECIFICITY = {
2792
+ method: 2,
2793
+ property: 2
2794
+ };
2795
+ function dedupeSamePositionSymbols(symbols) {
2796
+ const bestByKey = /* @__PURE__ */ new Map();
2797
+ for (const symbol of symbols) {
2798
+ const key = `${symbol.name}0000${symbol.line}0000${symbol.column}`;
2799
+ const existing = bestByKey.get(key);
2800
+ if (!existing) {
2801
+ bestByKey.set(key, symbol);
2802
+ continue;
2803
+ }
2804
+ const existingScore = SYMBOL_KIND_SPECIFICITY[existing.kind] ?? 0;
2805
+ const candidateScore = SYMBOL_KIND_SPECIFICITY[symbol.kind] ?? 0;
2806
+ if (candidateScore > existingScore)
2807
+ bestByKey.set(key, symbol);
2808
+ }
2809
+ return [...bestByKey.values()];
2810
+ }
2811
+ function addTreeSitterFile(graph, cwd, filePath, languageId, extracted, ignoredIds) {
2812
+ const normalized = normalizeMapKey(filePath);
2813
+ const hintPath = toProjectRelativePath(normalized, cwd);
2814
+ const fileNodeId = `file:${normalized}`;
2815
+ addNode(graph, {
2816
+ id: fileNodeId,
2817
+ kind: "file",
2818
+ language: languageId,
2819
+ filePath: normalized,
2820
+ metadata: {
2821
+ ...featureHintMetadata(hintPath),
2822
+ extractionCoverage: extracted.coverage
2823
+ }
2824
+ });
2825
+ const dedupedSymbols = dedupeSamePositionSymbols(extracted.symbols);
2826
+ const containers = dedupedSymbols.map((s) => ({
2827
+ name: s.name,
2828
+ startLine: s.line,
2829
+ endLine: s.endLine ?? s.line
2830
+ }));
2831
+ for (const symbol of dedupedSymbols) {
2832
+ const symbolId = buildSymbolId(normalized, symbol.name, symbol.kind, symbol.line);
2833
+ const owner = findOwnerName(containers, symbol.line, symbol.endLine ?? symbol.line);
2834
+ const qualifiedName = buildQualifiedName(owner, symbol.name);
2835
+ addNode(graph, {
2836
+ id: symbolId,
2837
+ kind: "symbol",
2838
+ language: languageId,
2839
+ filePath: normalized,
2840
+ symbolName: symbol.name,
2841
+ symbolKind: symbol.kind,
2842
+ ...qualifiedName ? { qualifiedName } : {},
2843
+ exported: symbol.isExported,
2844
+ metadata: {
2845
+ line: symbol.line,
2846
+ endLine: symbol.endLine,
2847
+ column: symbol.column,
2848
+ signature: symbol.signature,
2849
+ ...featureHintMetadata(`${symbol.name} ${hintPath}`)
2850
+ }
2851
+ });
2852
+ addEdge(graph, { from: fileNodeId, to: symbolId, kind: "contains" });
2853
+ addEdge(graph, { from: fileNodeId, to: symbolId, kind: "defines" });
2854
+ }
2855
+ for (const ref of extracted.refs) {
2856
+ const refName = ref.symbolName ?? ref.symbolId;
2857
+ const targetId = `symbol-name:${refName}`;
2858
+ if (!graph.nodes.has(targetId)) {
2859
+ addNode(graph, {
2860
+ id: targetId,
2861
+ kind: "symbol",
2862
+ language: languageId,
2863
+ symbolName: refName,
2864
+ metadata: { unresolvedName: refName }
2865
+ });
2866
+ }
2867
+ addEdge(graph, {
2868
+ from: fileNodeId,
2869
+ to: targetId,
2870
+ kind: "references",
2871
+ metadata: {
2872
+ line: ref.line,
2873
+ column: ref.column,
2874
+ referenceKind: ref.referenceKind ?? "unknown"
2875
+ },
2876
+ // Always starts bare-name-only (the extractor has no scope/type info);
2877
+ // resolveDeferredSymbolEdges may upgrade this to "exact" below.
2878
+ resolution: "name-only"
2879
+ });
2880
+ }
2881
+ for (const imp of extracted.imports) {
2882
+ const resolved = resolveImportToFiles(cwd, filePath, languageId, imp.source).filter((target) => !ignoredIds?.has(target));
2883
+ if (resolved.length > 0) {
2884
+ for (const target of resolved) {
2885
+ const toNode = ensureFileNode(graph, target, cwd, mapKindToTreeSitterLanguage(detectFileKind(target), target) ?? languageId);
2886
+ addEdge(graph, {
2887
+ from: fileNodeId,
2888
+ to: toNode,
2889
+ kind: "imports",
2890
+ metadata: { line: imp.line, source: imp.source }
2891
+ });
2892
+ }
2893
+ continue;
2894
+ }
2895
+ const isRelative = imp.source.startsWith(".");
2896
+ const targetId = `${isRelative ? "module" : "external"}:${imp.source}`;
2897
+ if (!graph.nodes.has(targetId)) {
2898
+ addNode(graph, {
2899
+ id: targetId,
2900
+ kind: isRelative ? "module" : "external",
2901
+ language: languageId,
2902
+ metadata: { source: imp.source }
2903
+ });
2904
+ }
2905
+ addEdge(graph, {
2906
+ from: fileNodeId,
2907
+ to: targetId,
2908
+ kind: "imports",
2909
+ metadata: { line: imp.line }
2910
+ });
2911
+ }
2912
+ }
2913
+ function addLspFallbackSymbols(graph, filePath, languageId, symbols) {
2914
+ const normalized = normalizeMapKey(filePath);
2915
+ const fileNodeId = `file:${normalized}`;
2916
+ let added = 0;
2917
+ const flatOwnerIds = /* @__PURE__ */ new Map();
2918
+ for (const symbol of symbols) {
2919
+ const range = symbol.range ?? symbol.location?.range;
2920
+ if (!range)
2921
+ continue;
2922
+ const kind = lspSymbolKindName(symbol.kind);
2923
+ const id = buildSymbolId(normalized, symbol.name, kind, range.start.line + 1);
2924
+ flatOwnerIds.set(symbol.name, id);
2925
+ if (symbol.containerName) {
2926
+ flatOwnerIds.set(`${symbol.containerName}.${symbol.name}`, id);
2927
+ }
2928
+ }
2929
+ const visit = (items, parentId, ancestry) => {
2930
+ for (const symbol of items) {
2931
+ const range = symbol.range ?? symbol.location?.range;
2932
+ if (!range)
2933
+ continue;
2934
+ const line = range.start.line + 1;
2935
+ const kind = lspSymbolKindName(symbol.kind);
2936
+ const symbolId = buildSymbolId(normalized, symbol.name, kind, line);
2937
+ const owners = ancestry.length > 0 ? ancestry : containerNameChain(symbol, symbols);
2938
+ const qualifiedName = owners.length > 0 ? [...owners, symbol.name].join(".") : void 0;
2939
+ addNode(graph, {
2940
+ id: symbolId,
2941
+ kind: "symbol",
2942
+ language: languageId,
2943
+ filePath: normalized,
2944
+ symbolName: symbol.name,
2945
+ symbolKind: kind,
2946
+ ...qualifiedName ? { qualifiedName } : {},
2947
+ provenance: "lsp",
2948
+ metadata: {
2949
+ line,
2950
+ column: range.start.character,
2951
+ endLine: range.end.line + 1,
2952
+ ...featureHintMetadata(`${symbol.name} ${normalized}`)
2953
+ }
2954
+ });
2955
+ const resolvedParentId = ancestry.length === 0 && symbol.containerName ? flatOwnerIds.get(symbol.containerName) ?? parentId : parentId;
2956
+ addEdge(graph, {
2957
+ from: resolvedParentId,
2958
+ to: symbolId,
2959
+ kind: "contains"
2960
+ });
2961
+ addEdge(graph, { from: fileNodeId, to: symbolId, kind: "defines" });
2962
+ added++;
2963
+ if (symbol.children) {
2964
+ visit(symbol.children, symbolId, [...owners, symbol.name]);
2965
+ }
2966
+ }
2967
+ };
2968
+ visit(symbols, fileNodeId, []);
2969
+ return added;
2970
+ }
2971
+ function ensureFileNode(graph, filePath, cwd, languageId) {
2972
+ const normalized = normalizeMapKey(filePath);
2973
+ const hintPath = toProjectRelativePath(normalized, cwd);
2974
+ const existing = graph.fileNodes.get(normalized);
2975
+ if (existing)
2976
+ return existing;
2977
+ const fileNodeId = `file:${normalized}`;
2978
+ addNode(graph, {
2979
+ id: fileNodeId,
2980
+ kind: "file",
2981
+ language: languageId,
2982
+ filePath: normalized,
2983
+ metadata: featureHintMetadata(hintPath)
2984
+ });
2985
+ return fileNodeId;
2986
+ }
2987
+ function resolveCxxInclude(cwd, filePath, source) {
2988
+ const candidates = [
2989
+ path2.resolve(path2.dirname(filePath), source),
2990
+ path2.resolve(cwd, source),
2991
+ path2.resolve(cwd, "include", source),
2992
+ path2.resolve(cwd, "src", source)
2993
+ ];
2994
+ const root = path2.resolve(cwd);
2995
+ for (const candidate of candidates) {
2996
+ if (!candidate.startsWith(root + path2.sep) && candidate !== root)
2997
+ continue;
2998
+ if (fs2.existsSync(candidate) && detectFileKind(candidate) === "cxx") {
2999
+ return normalizeMapKey(candidate);
3000
+ }
3001
+ }
3002
+ return void 0;
3003
+ }
3004
+ function parseLocalCxxInclude(line) {
3005
+ let i = 0;
3006
+ while (i < line.length && (line[i] === " " || line[i] === " "))
3007
+ i += 1;
3008
+ if (line[i] !== "#")
3009
+ return void 0;
3010
+ i += 1;
3011
+ while (i < line.length && (line[i] === " " || line[i] === " "))
3012
+ i += 1;
3013
+ if (!line.startsWith("include", i))
3014
+ return void 0;
3015
+ i += "include".length;
3016
+ if (i >= line.length || line[i] !== " " && line[i] !== " ") {
3017
+ return void 0;
3018
+ }
3019
+ while (i < line.length && (line[i] === " " || line[i] === " "))
3020
+ i += 1;
3021
+ if (line[i] !== '"')
3022
+ return void 0;
3023
+ i += 1;
3024
+ const start = i;
3025
+ while (i < line.length && line[i] !== '"')
3026
+ i += 1;
3027
+ if (i >= line.length || i === start)
3028
+ return void 0;
3029
+ return line.slice(start, i);
3030
+ }
3031
+ function addCxxIncludeEdges(graph, cwd, filePath, ignoredIds, contentOverride) {
3032
+ let content = contentOverride;
3033
+ if (content === void 0) {
3034
+ try {
3035
+ content = fs2.readFileSync(filePath, "utf-8");
3036
+ } catch {
3037
+ return;
3038
+ }
3039
+ }
3040
+ if (content === null)
3041
+ return;
3042
+ const fromNode = ensureFileNode(graph, filePath, cwd, "cpp");
3043
+ for (const line of content.split(/\r?\n/)) {
3044
+ const source = parseLocalCxxInclude(line);
3045
+ if (!source)
3046
+ continue;
3047
+ const target = resolveCxxInclude(cwd, filePath, source);
3048
+ if (!target || ignoredIds?.has(target))
3049
+ continue;
3050
+ const languageId = mapKindToTreeSitterLanguage("cxx", target) ?? "cpp";
3051
+ const toNode = ensureFileNode(graph, target, cwd, languageId);
3052
+ addEdge(graph, {
3053
+ from: fromNode,
3054
+ to: toNode,
3055
+ kind: "imports",
3056
+ metadata: { source }
3057
+ });
3058
+ }
3059
+ }
3060
+ function removeFileOwnedGraphData(graph, filePath, removedEdges) {
3061
+ const normalized = normalizeMapKey(filePath);
3062
+ const fileNodeId = graph.fileNodes.get(normalized) ?? `file:${normalized}`;
3063
+ const removedSymbolIds = new Set(graph.symbolNodesByFile.get(normalized));
3064
+ const removedIds = new Set(removedSymbolIds);
3065
+ if (graph.nodes.has(fileNodeId))
3066
+ removedIds.add(fileNodeId);
3067
+ const candidates = /* @__PURE__ */ new Set();
3068
+ for (const id of removedIds) {
3069
+ for (const edge of graph.edgesByFrom.get(id) ?? []) {
3070
+ _rebuildCounters.removeOwnedEdgeVisits++;
3071
+ candidates.add(edge);
3072
+ }
3073
+ for (const edge of graph.edgesByTo.get(id) ?? []) {
3074
+ _rebuildCounters.removeOwnedEdgeVisits++;
3075
+ candidates.add(edge);
3076
+ }
3077
+ }
3078
+ const preservedIncomingSymbolEdges = [];
3079
+ for (const edge of candidates) {
3080
+ if (removedEdges.has(edge))
3081
+ continue;
3082
+ const fromRemoved = removedIds.has(edge.from);
3083
+ if (!fromRemoved && edge.to === fileNodeId)
3084
+ continue;
3085
+ if (!fromRemoved && removedSymbolIds.has(edge.to)) {
3086
+ preservedIncomingSymbolEdges.push({ ...edge });
3087
+ }
3088
+ removedEdges.add(edge);
3089
+ }
3090
+ for (const id of removedIds) {
3091
+ const node = graph.nodes.get(id);
3092
+ graph.nodes.delete(id);
3093
+ if (!node?.filePath)
3094
+ continue;
3095
+ if (node.kind === "file") {
3096
+ if (graph.fileNodes.get(node.filePath) === id) {
3097
+ graph.fileNodes.delete(node.filePath);
3098
+ }
3099
+ } else if (node.kind === "symbol") {
3100
+ const ids = graph.symbolNodesByFile.get(node.filePath);
3101
+ if (!ids)
3102
+ continue;
3103
+ const at = ids.indexOf(id);
3104
+ if (at >= 0)
3105
+ ids.splice(at, 1);
3106
+ if (ids.length === 0)
3107
+ graph.symbolNodesByFile.delete(node.filePath);
3108
+ }
3109
+ }
3110
+ return preservedIncomingSymbolEdges;
3111
+ }
3112
+ async function addFileToGraph(graph, cwd, file, ignoredIds, contentOverride) {
3113
+ const kind = detectFileKind(file);
3114
+ if (!kind || !MAIN_KINDS.has(kind))
3115
+ return;
3116
+ if (detectFileRole(file) === "test")
3117
+ return;
3118
+ const contentHash = typeof contentOverride === "string" ? reviewGraphIrContentHash(contentOverride) : void 0;
3119
+ const sharedIr = contentHash ? getFreshReviewGraphFileIr(cwd, file, contentHash)?.structural : void 0;
3120
+ if (kind === "jsts") {
3121
+ const run = new FactStore("review-graph-run");
3122
+ if (sharedIr?.kind === "jsts") {
3123
+ run.setFileFact(file, "file.content", contentOverride ?? "");
3124
+ run.setFileFact(file, "file.imports", sharedIr.imports);
3125
+ run.setFileFact(file, "file.functionSummaries", sharedIr.functionSummaries);
3126
+ run.setFileFact(file, "file.functionFactsCoverage", sharedIr.coverage.calls);
3127
+ run.setFileFact(file, "file.importFactsCoverage", sharedIr.coverage.imports);
3128
+ } else {
3129
+ await ensureReviewGraphFacts(file, cwd, run, contentOverride);
3130
+ }
3131
+ addJsTsFile(graph, cwd, file, run, ignoredIds);
3132
+ return;
3133
+ }
3134
+ const languageId = mapKindToTreeSitterLanguage(kind, file);
3135
+ if (!languageId)
3136
+ return;
3137
+ const irExtracted = sharedIr?.kind === "tree-sitter" && sharedIr.languageId === languageId ? sharedIr.extracted : void 0;
3138
+ const extracted = irExtracted ?? await extractTreeSitterSymbols(file, languageId, contentOverride);
3139
+ if (extracted.wasmTrap)
3140
+ _wasmTrappedFiles.set(file, extracted.wasmTrap);
3141
+ else
3142
+ _wasmTrappedFiles.delete(file);
3143
+ addTreeSitterFile(graph, cwd, file, languageId, extracted, ignoredIds);
3144
+ if (extracted.symbols.length === 0) {
3145
+ const lspSymbols = await getOpenDocumentSymbols(file);
3146
+ const added = lspSymbols ? addLspFallbackSymbols(graph, file, languageId, lspSymbols) : 0;
3147
+ logReviewGraph({
3148
+ phase: "lsp_symbol_fallback",
3149
+ cwd,
3150
+ reason: lspSymbols ? added > 0 ? "added" : "empty-response" : "unavailable-or-failed",
3151
+ nodes: added
3152
+ });
3153
+ }
3154
+ if (kind === "cxx") {
3155
+ addCxxIncludeEdges(graph, cwd, file, ignoredIds, contentOverride);
3156
+ }
3157
+ }
3158
+ var _rebuildCounters = {
3159
+ restoreComparisons: 0,
3160
+ importTargetEdgeScans: 0,
3161
+ removeOwnedEdgeVisits: 0,
3162
+ removeOwnedEdgePositions: 0,
3163
+ createdImportResolutions: 0
3164
+ };
3165
+ function _getReviewGraphRebuildCountersForTests() {
3166
+ return { ..._rebuildCounters };
3167
+ }
3168
+ function _resetReviewGraphRebuildCountersForTests() {
3169
+ _rebuildCounters.restoreComparisons = 0;
3170
+ _rebuildCounters.importTargetEdgeScans = 0;
3171
+ _rebuildCounters.removeOwnedEdgeVisits = 0;
3172
+ _rebuildCounters.removeOwnedEdgePositions = 0;
3173
+ _rebuildCounters.createdImportResolutions = 0;
3174
+ }
3175
+ function edgeIdentityKey(edge) {
3176
+ _rebuildCounters.restoreComparisons++;
3177
+ return JSON.stringify([edge.from, edge.kind, edge.metadata ?? {}]);
3178
+ }
3179
+ function restoreValidIncomingEdges(graph, edges) {
3180
+ const seenByTarget = /* @__PURE__ */ new Map();
3181
+ for (const edge of edges) {
3182
+ if (!graph.nodes.has(edge.from) || !graph.nodes.has(edge.to))
3183
+ continue;
3184
+ let seen = seenByTarget.get(edge.to);
3185
+ if (!seen) {
3186
+ seen = /* @__PURE__ */ new Set();
3187
+ for (const candidate of graph.edgesByTo.get(edge.to) ?? []) {
3188
+ seen.add(edgeIdentityKey(candidate));
3189
+ }
3190
+ seenByTarget.set(edge.to, seen);
3191
+ }
3192
+ const key = edgeIdentityKey(edge);
3193
+ if (seen.has(key))
3194
+ continue;
3195
+ seen.add(key);
3196
+ addEdge(graph, edge);
3197
+ }
3198
+ }
3199
+ function dedupeResolvedEdges(graph, replacements) {
3200
+ const resolvedEdges = new Set(replacements.map(([, after]) => after));
3201
+ const seenByTarget = /* @__PURE__ */ new Map();
3202
+ const removed = /* @__PURE__ */ new Set();
3203
+ for (const [, edge] of replacements) {
3204
+ if (removed.has(edge))
3205
+ continue;
3206
+ let seen = seenByTarget.get(edge.to);
3207
+ if (!seen) {
3208
+ seen = /* @__PURE__ */ new Set();
3209
+ for (const candidate of graph.edgesByTo.get(edge.to) ?? []) {
3210
+ if (!resolvedEdges.has(candidate)) {
3211
+ seen.add(edgeIdentityKey(candidate));
3212
+ }
3213
+ }
3214
+ seenByTarget.set(edge.to, seen);
3215
+ }
3216
+ const key = edgeIdentityKey(edge);
3217
+ if (seen.has(key)) {
3218
+ removed.add(edge);
3219
+ unindexEdge(graph, edge);
3220
+ continue;
3221
+ }
3222
+ seen.add(key);
3223
+ }
3224
+ if (removed.size > 0) {
3225
+ graph.edges = graph.edges.filter((edge) => !removed.has(edge));
3226
+ }
3227
+ }
3228
+ var _graphImportChanges = /* @__PURE__ */ new WeakMap();
3229
+ function getGraphImportChanges(graph) {
3230
+ return _graphImportChanges.get(graph);
3231
+ }
3232
+ function importTargetsForFile(graph, filePath) {
3233
+ const normalized = normalizeMapKey(filePath);
3234
+ const fileNodeId = graph.fileNodes.get(normalized) ?? `file:${normalized}`;
3235
+ const targets = /* @__PURE__ */ new Set();
3236
+ for (const edge of graph.edgesByFrom.get(fileNodeId) ?? []) {
3237
+ _rebuildCounters.importTargetEdgeScans++;
3238
+ if (edge.kind !== "imports")
3239
+ continue;
3240
+ const target = graph.nodes.get(edge.to)?.filePath;
3241
+ if (target)
3242
+ targets.add(normalizeMapKey(target));
3243
+ }
3244
+ return [...targets].sort((a, b) => compareOrdinal(a, b));
3245
+ }
3246
+ function importersResolvingTo(graph, cwd, created, ignoredIds) {
3247
+ const names = new Set([...created].flatMap(fileAnswerNames));
3248
+ const importers = /* @__PURE__ */ new Set();
3249
+ for (const node of graph.nodes.values()) {
3250
+ if (node.kind !== "module" && node.kind !== "external")
3251
+ continue;
3252
+ const source = node.metadata?.source;
3253
+ if (typeof source !== "string")
3254
+ continue;
3255
+ if (!importSourceNameParts(source).some((part) => names.has(part))) {
3256
+ continue;
3257
+ }
3258
+ for (const edge of graph.edgesByTo.get(node.id) ?? []) {
3259
+ if (edge.kind !== "imports")
3260
+ continue;
3261
+ const importer = graph.nodes.get(edge.from);
3262
+ const importerPath = importer?.filePath;
3263
+ if (!importer || !importerPath || importers.has(importerPath))
3264
+ continue;
3265
+ _rebuildCounters.createdImportResolutions++;
3266
+ const targets = importer.language === "jsts" ? [localImportToFile(cwd, importerPath, source, ignoredIds)] : resolveImportToFiles(cwd, importerPath, importer.language ?? "", source);
3267
+ if (targets.some((target) => target !== void 0 && !ignoredIds?.has(target) && created.has(normalizeMapKey(target)))) {
3268
+ importers.add(importerPath);
3269
+ }
3270
+ }
3271
+ }
3272
+ return [...importers];
3273
+ }
3274
+ async function updateGraphFiles(graph, cwd, files, facts, ignoredIds) {
3275
+ rebuildIndexes(graph);
3276
+ const prior = files.map((file) => ({
3277
+ filePath: normalizeMapKey(file),
3278
+ existedBefore: graph.fileNodes.has(normalizeMapKey(file)),
3279
+ priorTargets: importTargetsForFile(graph, file)
3280
+ }));
3281
+ const preservedIncoming = [];
3282
+ const removedEdges = /* @__PURE__ */ new Set();
3283
+ for (const file of files) {
3284
+ preservedIncoming.push(...removeFileOwnedGraphData(graph, file, removedEdges));
3285
+ await addFileToGraph(graph, cwd, file, ignoredIds);
3286
+ }
3287
+ const created = new Set(prior.filter((entry) => !entry.existedBefore).map((entry) => entry.filePath).filter((file) => graph.fileNodes.has(file)));
3288
+ if (created.size > 0) {
3289
+ const batch = new Set(prior.map((entry) => entry.filePath));
3290
+ for (const importer of importersResolvingTo(graph, cwd, created, ignoredIds)) {
3291
+ if (batch.has(importer))
3292
+ continue;
3293
+ batch.add(importer);
3294
+ prior.push({
3295
+ filePath: importer,
3296
+ existedBefore: true,
3297
+ priorTargets: importTargetsForFile(graph, importer)
3298
+ });
3299
+ preservedIncoming.push(...removeFileOwnedGraphData(graph, importer, removedEdges));
3300
+ await addFileToGraph(graph, cwd, importer, ignoredIds);
3301
+ }
3302
+ }
3303
+ if (removedEdges.size > 0) {
3304
+ unindexEdges(graph, removedEdges);
3305
+ graph.edges = graph.edges.filter((edge) => !removedEdges.has(edge));
3306
+ }
3307
+ restoreValidIncomingEdges(graph, preservedIncoming);
3308
+ resolveDeferredSymbolEdges(graph, false);
3309
+ graph.changedSymbolsByFile.clear();
3310
+ for (const file of files) {
3311
+ upsertChangedSymbols(graph, facts, file);
3312
+ }
3313
+ return prior.map(({ filePath, existedBefore, priorTargets }) => ({
3314
+ filePath,
3315
+ existedBefore,
3316
+ existsAfter: graph.fileNodes.has(filePath),
3317
+ priorTargets,
3318
+ newTargets: importTargetsForFile(graph, filePath)
3319
+ }));
3320
+ }
3321
+ function resolveDeferredSymbolEdges(graph, rebuild = true) {
3322
+ const symbolNameToIds = /* @__PURE__ */ new Map();
3323
+ for (const node of graph.nodes.values()) {
3324
+ if (node.kind !== "symbol" || !node.symbolName)
3325
+ continue;
3326
+ if (node.metadata?.unresolvedName)
3327
+ continue;
3328
+ const ids = symbolNameToIds.get(node.symbolName) ?? [];
3329
+ ids.push(node.id);
3330
+ symbolNameToIds.set(node.symbolName, ids);
3331
+ }
3332
+ const replacements = [];
3333
+ graph.edges = graph.edges.map((edge) => {
3334
+ const targetNode = graph.nodes.get(edge.to);
3335
+ if (!targetNode?.metadata?.unresolvedName)
3336
+ return edge;
3337
+ const candidates = symbolNameToIds.get(targetNode.symbolName ?? "") ?? [];
3338
+ const importHintFile = edge.metadata?.importHintFile;
3339
+ if (importHintFile) {
3340
+ const scoped = candidates.filter((id) => graph.nodes.get(id)?.filePath === importHintFile);
3341
+ if (scoped.length === 1) {
3342
+ const resolved = {
3343
+ ...edge,
3344
+ to: scoped[0],
3345
+ resolution: "import"
3346
+ };
3347
+ replacements.push([edge, resolved]);
3348
+ return resolved;
3349
+ }
3350
+ }
3351
+ if (candidates.length === 1) {
3352
+ const resolved = {
3353
+ ...edge,
3354
+ to: candidates[0],
3355
+ resolution: "exact"
3356
+ };
3357
+ replacements.push([edge, resolved]);
3358
+ return resolved;
3359
+ }
3360
+ return edge;
3361
+ });
3362
+ if (rebuild) {
3363
+ rebuildIndexes(graph);
3364
+ return;
3365
+ }
3366
+ if (replacements.length === 0)
3367
+ return;
3368
+ const affectedTargets = /* @__PURE__ */ new Set();
3369
+ for (const [before, after] of replacements) {
3370
+ const fromBucket = graph.edgesByFrom.get(before.from);
3371
+ if (fromBucket) {
3372
+ const at = fromBucket.indexOf(before);
3373
+ if (at >= 0)
3374
+ fromBucket[at] = after;
3375
+ }
3376
+ affectedTargets.add(before.to);
3377
+ affectedTargets.add(after.to);
3378
+ }
3379
+ for (const target of affectedTargets)
3380
+ graph.edgesByTo.set(target, []);
3381
+ for (const edge of graph.edges) {
3382
+ if (affectedTargets.has(edge.to))
3383
+ graph.edgesByTo.get(edge.to)?.push(edge);
3384
+ }
3385
+ for (const target of affectedTargets) {
3386
+ if (graph.edgesByTo.get(target)?.length === 0) {
3387
+ graph.edgesByTo.delete(target);
3388
+ }
3389
+ }
3390
+ dedupeResolvedEdges(graph, replacements);
3391
+ }
3392
+ function verifiedCacheFields(seqAtBuildStart) {
3393
+ return {
3394
+ builtAtProjectSeq: seqAtBuildStart,
3395
+ lastFullVerifyMs: Date.now(),
3396
+ fastPathSinceVerify: 0
3397
+ };
3398
+ }
3399
+ async function tryIncrementalFromCache(cached, ctx) {
3400
+ if (cached.fileSignatures.size === 0)
3401
+ return void 0;
3402
+ const { added, removed, changed } = diffSignatureMaps(cached.fileSignatures, ctx.fileSignatures);
3403
+ if (removed.length > 0)
3404
+ return void 0;
3405
+ if (added.length === 0 && changed.length === 0)
3406
+ return void 0;
3407
+ const { trulyChanged, hashes } = await confirmContentChanged(changed, cached.fileHashes);
3408
+ const filesToUpdate = [...added, ...trulyChanged];
3409
+ if (filesToUpdate.length === 0) {
3410
+ const generation2 = cached.buildGeneration ?? ++_graphGenerationCounter;
3411
+ const graph2 = cloneGraph(cached.graph);
3412
+ rebuildIndexes(graph2);
3413
+ graph2.changedSymbolsByFile.clear();
3414
+ for (const file of ctx.normalizedChanged) {
3415
+ upsertChangedSymbols(graph2, ctx.facts, file);
3416
+ }
3417
+ setWorkspaceGraph(ctx.normalizedCwd, {
3418
+ signature: ctx.signature,
3419
+ fileSignatures: new Map(ctx.fileSignatures),
3420
+ fileHashes: hashes,
3421
+ graph: cloneGraph(cached.graph),
3422
+ buildGeneration: generation2,
3423
+ ...verifiedCacheFields(ctx.seqAtBuildStart)
3424
+ }, ctx.cacheEpoch);
3425
+ setGraphBuildInfo(graph2, {
3426
+ reused: true,
3427
+ mode: "cached",
3428
+ graphChanged: false
3429
+ });
3430
+ graph2.buildGeneration = generation2;
3431
+ setSessionReviewGraphFact(ctx.cwd, ctx.facts, graph2);
3432
+ return graph2;
3433
+ }
3434
+ for (const file of added) {
3435
+ hashes.set(file, contentHashEntry(file));
3436
+ }
3437
+ const priorGeneration = cached.graph.buildGeneration;
3438
+ const graph = cloneGraph(cached.graph);
3439
+ const importChanges = await updateGraphFiles(graph, ctx.cwd, filesToUpdate, ctx.facts, ctx.ignoredIds);
3440
+ refreshGraphBuiltAt(graph);
3441
+ const generation = ++_graphGenerationCounter;
3442
+ graph.buildGeneration = generation;
3443
+ setWorkspaceGraph(ctx.normalizedCwd, {
3444
+ signature: ctx.signature,
3445
+ fileSignatures: new Map(ctx.fileSignatures),
3446
+ fileHashes: hashes,
3447
+ graph,
3448
+ buildGeneration: generation,
3449
+ ...verifiedCacheFields(ctx.seqAtBuildStart)
3450
+ }, ctx.cacheEpoch);
3451
+ const persistReason = persistGraph(ctx.cwd, ctx.signature, ctx.fileSignatures, hashes, graph, {
3452
+ buildId: ctx.buildId,
3453
+ projectSeq: ctx.seqAtBuildStart,
3454
+ seqHint: ctx.seqHint,
3455
+ mode: ctx.mode,
3456
+ resolveIdentity: ctx.resolveIdentity
3457
+ });
3458
+ setGraphBuildInfo(graph, {
3459
+ reused: true,
3460
+ mode: "incremental",
3461
+ ...persistReason ? { persistReason } : {},
3462
+ graphChanged: true
3463
+ });
3464
+ _graphImportChanges.set(graph, {
3465
+ fromGeneration: priorGeneration,
3466
+ changes: importChanges
3467
+ });
3468
+ setSessionReviewGraphFact(ctx.cwd, ctx.facts, graph);
3469
+ return graph;
3470
+ }
3471
+ function hasGraphKindExtension(file) {
3472
+ const kind = detectFileKind(file);
3473
+ return !!kind && MAIN_KINDS.has(kind) && detectFileRole(file) !== "test";
3474
+ }
3475
+ async function trySeqFastpath(cwd, buildId, normalizedCwd, normalizedChanged, facts, seqHint, seqAtBuildStart, ignoredIds, cacheEpoch, resolveIdentity) {
3476
+ const cached = _workspaceGraphCache.get(normalizedCwd);
3477
+ const cachedCoverage = cached?.graph.persistCoverage;
3478
+ if (cachedCoverage?.partial && cachedCoverage.capTrimmed !== true) {
3479
+ return { fallback: "partial-base" };
3480
+ }
3481
+ if (!cached || cached.builtAtProjectSeq === void 0) {
3482
+ return { fallback: "no-seq" };
3483
+ }
3484
+ const now = Date.now();
3485
+ const ageMs = cached.lastFullVerifyMs === void 0 ? Number.POSITIVE_INFINITY : now - cached.lastFullVerifyMs;
3486
+ const sinceVerify = cached.fastPathSinceVerify ?? 0;
3487
+ if (ageMs > SEQ_FASTPATH_REVERIFY_MS || sinceVerify >= SEQ_FASTPATH_REVERIFY_EVERY) {
3488
+ return { fallback: "verify-due" };
3489
+ }
3490
+ const changedSet = new Set(seqHint.getFilesChangedSince(cached.builtAtProjectSeq).map((file) => normalizeMapKey(file)));
3491
+ for (const file of normalizedChanged)
3492
+ changedSet.add(file);
3493
+ for (const file of _wasmTrappedFiles.keys()) {
3494
+ if (cached.fileSignatures.has(file))
3495
+ changedSet.add(file);
3496
+ }
3497
+ const changed = [...changedSet];
3498
+ if (changed.length > SEQ_FASTPATH_MAX_CHANGES) {
3499
+ return { fallback: "too-many-changes" };
3500
+ }
3501
+ const candidateFiles = [];
3502
+ for (const file of changed) {
3503
+ const known = cached.fileSignatures.has(file);
3504
+ let existsOnDisk = false;
3505
+ try {
3506
+ existsOnDisk = fs2.statSync(file).isFile();
3507
+ } catch {
3508
+ existsOnDisk = false;
3509
+ }
3510
+ if (!existsOnDisk) {
3511
+ if (known) {
3512
+ return { fallback: "removed-file" };
3513
+ }
3514
+ continue;
3515
+ }
3516
+ if (!known) {
3517
+ if (!hasGraphKindExtension(file))
3518
+ continue;
3519
+ }
3520
+ candidateFiles.push(file);
3521
+ }
3522
+ const candidateStats = candidateFiles.map((file) => [file, sourceSignatureEntry(file)]);
3523
+ const { trulyChanged, hashes } = await confirmContentChanged(candidateFiles, cached.fileHashes);
3524
+ if (trulyChanged.length === 0) {
3525
+ const graph2 = cloneGraph(cached.graph);
3526
+ rebuildIndexes(graph2);
3527
+ graph2.changedSymbolsByFile.clear();
3528
+ for (const file of normalizedChanged) {
3529
+ upsertChangedSymbols(graph2, facts, file);
3530
+ }
3531
+ const nextSignatures2 = new Map(cached.fileSignatures);
3532
+ for (const [file, stat] of candidateStats) {
3533
+ nextSignatures2.set(file, stat);
3534
+ }
3535
+ cached.signature = sourceSignatureFromMap(nextSignatures2);
3536
+ cached.fileSignatures = nextSignatures2;
3537
+ cached.fileHashes = hashes;
3538
+ cached.builtAtProjectSeq = seqAtBuildStart;
3539
+ cached.fastPathSinceVerify = sinceVerify + 1;
3540
+ const generation2 = cached.buildGeneration ??= ++_graphGenerationCounter;
3541
+ setGraphBuildInfo(graph2, {
3542
+ reused: true,
3543
+ mode: "seq-fastpath",
3544
+ graphChanged: false
3545
+ });
3546
+ graph2.buildGeneration = generation2;
3547
+ setSessionReviewGraphFact(cwd, facts, graph2);
3548
+ return { graph: graph2 };
3549
+ }
3550
+ const filesToUpdate = trulyChanged;
3551
+ const priorGeneration = cached.graph.buildGeneration;
3552
+ const graph = cloneGraph(cached.graph);
3553
+ let importChanges;
3554
+ try {
3555
+ importChanges = await updateGraphFiles(graph, cwd, filesToUpdate, facts, ignoredIds);
3556
+ } catch {
3557
+ return { fallback: "stat-error" };
3558
+ }
3559
+ refreshGraphBuiltAt(graph);
3560
+ const nextSignatures = new Map(cached.fileSignatures);
3561
+ for (const [file, stat] of candidateStats) {
3562
+ nextSignatures.set(file, stat);
3563
+ }
3564
+ const nextSignature = sourceSignatureFromMap(nextSignatures);
3565
+ const generation = ++_graphGenerationCounter;
3566
+ graph.buildGeneration = generation;
3567
+ setWorkspaceGraph(normalizedCwd, {
3568
+ signature: nextSignature,
3569
+ fileSignatures: nextSignatures,
3570
+ fileHashes: hashes,
3571
+ graph,
3572
+ buildGeneration: generation,
3573
+ // Build-start seq, not stamp-time: see verifiedCacheFields — a bump that
3574
+ // interleaved during updateGraphFiles' awaits must be re-diffed next build.
3575
+ builtAtProjectSeq: seqAtBuildStart,
3576
+ lastFullVerifyMs: cached.lastFullVerifyMs,
3577
+ fastPathSinceVerify: sinceVerify + 1
3578
+ }, cacheEpoch);
3579
+ const persistReason = persistGraph(cwd, nextSignature, nextSignatures, hashes, graph, {
3580
+ buildId,
3581
+ projectSeq: seqAtBuildStart,
3582
+ seqHint: true,
3583
+ mode: "seq-fastpath",
3584
+ resolveIdentity
3585
+ });
3586
+ setGraphBuildInfo(graph, {
3587
+ reused: true,
3588
+ mode: "seq-fastpath",
3589
+ ...persistReason ? { persistReason } : {},
3590
+ graphChanged: true
3591
+ });
3592
+ _graphImportChanges.set(graph, {
3593
+ fromGeneration: priorGeneration,
3594
+ changes: importChanges
3595
+ });
3596
+ setSessionReviewGraphFact(cwd, facts, graph);
3597
+ return { graph };
3598
+ }
3599
+ async function _doBuildGraph(cwd, changedFiles, facts, seqHint, buildId) {
3600
+ const resolveIdentity = createGitIdentityResolver();
3601
+ const normalizedCwd = normalizeMapKey(cwd);
3602
+ const cacheEpoch = workspaceCacheEpoch(normalizedCwd);
3603
+ if (_reviewGraphBuildGateForTests)
3604
+ await _reviewGraphBuildGateForTests();
3605
+ const normalizedChanged = changedFiles.map((file) => normalizeMapKey(file));
3606
+ const normalizedChangedSet = new Set(normalizedChanged);
3607
+ logCwdWorktreeMismatchOnce(cwd, resolveIdentity);
3608
+ if (isAtOrAboveHomeDir(path2.resolve(cwd))) {
3609
+ const graph2 = createEmptyGraph();
3610
+ for (const file of normalizedChanged) {
3611
+ upsertChangedSymbols(graph2, facts, file);
3612
+ }
3613
+ setGraphBuildInfo(graph2, {
3614
+ reused: false,
3615
+ mode: "skipped",
3616
+ skipReason: "unsafe_root",
3617
+ // #459: never persisted/reused, same as the too_many_files skip below —
3618
+ // treat as changed so dependents never trust stale derived state.
3619
+ graphChanged: true
3620
+ });
3621
+ setSessionReviewGraphFact(cwd, facts, graph2);
3622
+ return graph2;
3623
+ }
3624
+ const seqAtBuildStart = seqHint?.projectSeq();
3625
+ const ignoredIdsPromise = collectUntrackedIgnoredIds(cwd);
3626
+ let seqFastpathFallback;
3627
+ if (seqHint && seqAtBuildStart !== void 0 && seqFastpathEnabled()) {
3628
+ const fast = await trySeqFastpath(cwd, buildId, normalizedCwd, normalizedChanged, facts, seqHint, seqAtBuildStart, await ignoredIdsPromise, cacheEpoch, resolveIdentity);
3629
+ if ("graph" in fast)
3630
+ return fast.graph;
3631
+ seqFastpathFallback = fast.fallback;
3632
+ }
3633
+ const sourceCollection = await getGraphSourceFiles(cwd);
3634
+ const filesToBuild = sourceCollection.files;
3635
+ const sourceFileCount = sourceCollection.sourceFileCount;
3636
+ const pathNormalizeCalls = sourceCollection.pathNormalizeCalls;
3637
+ const sourceFilesTruncated = sourceCollection.entryBudgetExceeded;
3638
+ const ignoredIds = await ignoredIdsPromise;
3639
+ const maxGraphFiles = sourceCollection.maxFileCount;
3640
+ if (filesToBuild.length > maxGraphFiles) {
3641
+ const graph2 = createEmptyGraph();
3642
+ graph2.version = REVIEW_GRAPH_VERSION;
3643
+ graph2.builtAt = (/* @__PURE__ */ new Date()).toISOString();
3644
+ for (const file of normalizedChanged) {
3645
+ upsertChangedSymbols(graph2, facts, file);
3646
+ }
3647
+ recordReviewGraphSizeSkip(cwd, sourceFileCount, maxGraphFiles);
3648
+ logLatency({
3649
+ type: "phase",
3650
+ phase: "review_graph_size_skip",
3651
+ filePath: cwd,
3652
+ durationMs: 0,
3653
+ metadata: {
3654
+ cwd,
3655
+ sourceFileCount,
3656
+ maxFileCount: maxGraphFiles,
3657
+ sourceFileCountLabel: `more than ${maxGraphFiles} files`,
3658
+ sourceFileCountTruncated: true,
3659
+ // #1979: the walk's interior, so a slow over-cap first build reads as
3660
+ // many ms per entry (cold filesystem) or many entries (big tree).
3661
+ entriesVisited: sourceCollection.entriesVisited,
3662
+ walkMs: sourceCollection.walkMs
3663
+ }
3664
+ });
3665
+ if (isReviewGraphSizeNearMiss(sourceFileCount, maxGraphFiles)) {
3666
+ logLatency({
3667
+ type: "phase",
3668
+ phase: "review_graph_size_near_miss",
3669
+ filePath: cwd,
3670
+ durationMs: 0,
3671
+ metadata: {
3672
+ cwd,
3673
+ maxFileCount: maxGraphFiles,
3674
+ sourceFileCount,
3675
+ sourceFileCountLabel: `more than ${maxGraphFiles} files`,
3676
+ sourceFileCountTruncated: true
3677
+ }
3678
+ });
3679
+ }
3680
+ setGraphBuildInfo(graph2, {
3681
+ reused: false,
3682
+ mode: "skipped",
3683
+ skipReason: "too_many_files",
3684
+ sourceFileCount,
3685
+ sourceFileCountTruncated: sourceFilesTruncated || filesToBuild.length > maxGraphFiles,
3686
+ maxFileCount: maxGraphFiles,
3687
+ pathNormalizeCalls,
3688
+ seqFastpathFallback,
3689
+ // #459: a fresh empty graph is returned every call on this path (never
3690
+ // persisted/reused) — treat it as changed so dependents never trust stale
3691
+ // derived state across skip/unskip transitions. Deliberately NOT stamped
3692
+ // with a buildGeneration: absent ⇒ derived caches rebuild every time.
3693
+ graphChanged: true
3694
+ });
3695
+ setSessionReviewGraphFact(cwd, facts, graph2);
3696
+ return graph2;
3697
+ }
3698
+ if (!sourceFilesTruncated)
3699
+ clearReviewGraphSizeSkip(cwd);
3700
+ const fileSignatures = await sourceSignatureMapAsync(filesToBuild);
3701
+ const signature = sourceSignatureFromMap(fileSignatures);
3702
+ let memCached = sourceFilesTruncated ? void 0 : _workspaceGraphCache.get(normalizedCwd);
3703
+ const memCoverage = memCached?.graph.persistCoverage;
3704
+ if (memCoverage?.partial && memCoverage.capTrimmed !== true) {
3705
+ memCached = void 0;
3706
+ }
3707
+ if (memCached?.signature === signature) {
3708
+ touchWorkspaceGraph(normalizedCwd);
3709
+ const graph2 = cloneGraph(memCached.graph);
3710
+ rebuildIndexes(graph2);
3711
+ graph2.changedSymbolsByFile.clear();
3712
+ for (const file of normalizedChanged) {
3713
+ upsertChangedSymbols(graph2, facts, file);
3714
+ }
3715
+ Object.assign(memCached, verifiedCacheFields(seqAtBuildStart));
3716
+ const generation2 = memCached.buildGeneration ??= ++_graphGenerationCounter;
3717
+ setGraphBuildInfo(graph2, {
3718
+ reused: true,
3719
+ mode: "cached",
3720
+ seqFastpathFallback,
3721
+ graphChanged: false
3722
+ });
3723
+ graph2.buildGeneration = generation2;
3724
+ setSessionReviewGraphFact(cwd, facts, graph2);
3725
+ return graph2;
3726
+ }
3727
+ if (memCached) {
3728
+ const incremental = await tryIncrementalFromCache(memCached, {
3729
+ cwd,
3730
+ buildId,
3731
+ seqHint: seqHint !== void 0,
3732
+ mode: "incremental",
3733
+ normalizedCwd,
3734
+ normalizedChanged,
3735
+ fileSignatures,
3736
+ signature,
3737
+ facts,
3738
+ seqAtBuildStart,
3739
+ ignoredIds,
3740
+ cacheEpoch,
3741
+ resolveIdentity
3742
+ });
3743
+ if (incremental) {
3744
+ updateGraphBuildInfo(incremental, { seqFastpathFallback });
3745
+ return incremental;
3746
+ }
3747
+ }
3748
+ const diskCached = sourceFilesTruncated ? null : loadPersistedGraph(cwd, void 0, resolveIdentity);
3749
+ if (diskCached?.signature === signature) {
3750
+ const graph2 = cloneGraph(diskCached.graph);
3751
+ rebuildIndexes(graph2);
3752
+ graph2.changedSymbolsByFile.clear();
3753
+ for (const file of normalizedChanged) {
3754
+ upsertChangedSymbols(graph2, facts, file);
3755
+ }
3756
+ const generation2 = ++_graphGenerationCounter;
3757
+ setWorkspaceGraph(normalizedCwd, {
3758
+ signature,
3759
+ fileSignatures: new Map(fileSignatures),
3760
+ fileHashes: diskCached.fileHashes,
3761
+ graph: cloneGraph(diskCached.graph),
3762
+ buildGeneration: generation2,
3763
+ ...verifiedCacheFields(seqAtBuildStart)
3764
+ }, cacheEpoch);
3765
+ setGraphBuildInfo(graph2, {
3766
+ reused: true,
3767
+ mode: "cached",
3768
+ seqFastpathFallback,
3769
+ graphChanged: false
3770
+ });
3771
+ graph2.buildGeneration = generation2;
3772
+ setSessionReviewGraphFact(cwd, facts, graph2);
3773
+ return graph2;
3774
+ }
3775
+ if (diskCached) {
3776
+ const incremental = await tryIncrementalFromCache({
3777
+ signature: diskCached.signature,
3778
+ fileSignatures: diskCached.fileSignatures,
3779
+ fileHashes: diskCached.fileHashes,
3780
+ graph: diskCached.graph
3781
+ }, {
3782
+ cwd,
3783
+ buildId,
3784
+ seqHint: seqHint !== void 0,
3785
+ mode: "incremental",
3786
+ normalizedCwd,
3787
+ normalizedChanged,
3788
+ fileSignatures,
3789
+ signature,
3790
+ facts,
3791
+ seqAtBuildStart,
3792
+ ignoredIds,
3793
+ resolveIdentity
3794
+ });
3795
+ if (incremental) {
3796
+ updateGraphBuildInfo(incremental, { seqFastpathFallback });
3797
+ return incremental;
3798
+ }
3799
+ }
3800
+ const resumed = sourceFilesTruncated ? null : await tryResumeFromCheckpoint(cwd, filesToBuild, ignoredIds, resolveIdentity);
3801
+ const graph = resumed?.graph ?? createEmptyGraph();
3802
+ const filesToExtract = resumed?.remaining ?? filesToBuild;
3803
+ const treeSitterClient = getSharedTreeSitterClient();
3804
+ treeSitterClient?.ensureTreeCacheCapacity(filesToExtract.length);
3805
+ const extractionStartedAt = Date.now();
3806
+ const fileHashes = resumed?.fileHashes ?? /* @__PURE__ */ new Map();
3807
+ const checkpointEvery = graphCheckpointEveryFiles();
3808
+ const checkpointMinIntervalMs = graphCheckpointMinIntervalMs();
3809
+ const testStopAfter = Number(process.env.PI_LENS_GRAPH_CHECKPOINT_TEST_STOP_AFTER);
3810
+ let filesSinceCheckpoint = 0;
3811
+ let lastCheckpointMs = Date.now();
3812
+ let extractedCount = 0;
3813
+ const extractFiles = async () => {
3814
+ for (const file of filesToExtract) {
3815
+ let content;
3816
+ try {
3817
+ const bytes = fs2.readFileSync(file);
3818
+ content = bytes.toString("utf-8");
3819
+ fileHashes.set(file, createHash2("sha256").update(bytes).digest("hex"));
3820
+ } catch {
3821
+ content = null;
3822
+ fileHashes.set(file, "missing");
3823
+ }
3824
+ await addFileToGraph(graph, cwd, file, ignoredIds, content);
3825
+ if (normalizedChangedSet.has(file)) {
3826
+ upsertChangedSymbols(graph, facts, file);
3827
+ }
3828
+ extractedCount++;
3829
+ filesSinceCheckpoint++;
3830
+ if (Number.isFinite(testStopAfter) && testStopAfter > 0 && extractedCount >= testStopAfter) {
3831
+ writeReviewGraphCheckpointSync(cwd, buildReviewGraphCheckpointData(cwd, graph, fileHashes, filesToBuild.length, ignoredIds, resolveIdentity), {
3832
+ nodes: graph.nodes.size,
3833
+ edges: graph.edges.length,
3834
+ processed: fileHashes.size,
3835
+ target: filesToBuild.length
3836
+ });
3837
+ throw new Error("__review_graph_checkpoint_test_abort__");
3838
+ }
3839
+ const remainingAfter = filesToExtract.length - extractedCount;
3840
+ if (filesSinceCheckpoint >= checkpointEvery && remainingAfter >= checkpointEvery && Date.now() - lastCheckpointMs >= checkpointMinIntervalMs) {
3841
+ writeReviewGraphCheckpoint(cwd, graph, fileHashes, filesToBuild.length, ignoredIds, resolveIdentity);
3842
+ filesSinceCheckpoint = 0;
3843
+ lastCheckpointMs = Date.now();
3844
+ }
3845
+ }
3846
+ };
3847
+ const extractAndDrainIr = async () => {
3848
+ try {
3849
+ await extractFiles();
3850
+ } finally {
3851
+ clearReviewGraphFileIr(cwd);
3852
+ }
3853
+ };
3854
+ if (treeSitterClient) {
3855
+ await treeSitterClient.withParseCacheMeasurement(extractAndDrainIr, (stats) => {
3856
+ logTreeSitterCacheStats({
3857
+ scope: "review_graph_full",
3858
+ filePath: cwd,
3859
+ fileCount: filesToBuild.length,
3860
+ durationMs: Date.now() - extractionStartedAt,
3861
+ stats,
3862
+ // #1982: this scope never runs an ast-grep pass (extraction is
3863
+ // tree-sitter only), so durationMs carries none and explicit
3864
+ // zeros keep every cache_stats record uniformly parseable.
3865
+ astGrep: { durationMs: 0, fileCount: 0 }
3866
+ });
3867
+ });
3868
+ } else {
3869
+ await extractAndDrainIr();
3870
+ }
3871
+ if (resumed) {
3872
+ for (const file of normalizedChangedSet) {
3873
+ if (resumed.fileHashes.has(file)) {
3874
+ upsertChangedSymbols(graph, facts, file);
3875
+ }
3876
+ }
3877
+ }
3878
+ resolveDeferredSymbolEdges(graph);
3879
+ graph.version = REVIEW_GRAPH_VERSION;
3880
+ graph.builtAt = (/* @__PURE__ */ new Date()).toISOString();
3881
+ graph.persistCoverage = sourceFilesTruncated ? graphCoverage(graph, graphPersistMaxElements(), sourceFileCount, true, filesToBuild) : void 0;
3882
+ deleteReviewGraphCheckpoint(cwd);
3883
+ const generation = ++_graphGenerationCounter;
3884
+ const retained = retainedGraph(cwd, graph);
3885
+ const wasCapped = retained !== graph;
3886
+ const graphSnapshot = wasCapped ? retained : cloneGraph(graph);
3887
+ if (!wasCapped)
3888
+ rebuildIndexes(graphSnapshot);
3889
+ graphSnapshot.buildGeneration = generation;
3890
+ setWorkspaceGraph(normalizedCwd, {
3891
+ signature,
3892
+ fileSignatures: new Map(fileSignatures),
3893
+ fileHashes,
3894
+ graph: graphSnapshot,
3895
+ buildGeneration: generation,
3896
+ ...verifiedCacheFields(seqAtBuildStart)
3897
+ }, cacheEpoch);
3898
+ const persistReason = persistGraph(cwd, signature, fileSignatures, fileHashes, graphSnapshot, {
3899
+ buildId,
3900
+ projectSeq: seqAtBuildStart,
3901
+ seqHint: seqHint !== void 0,
3902
+ mode: "full",
3903
+ sourceFileCount,
3904
+ sourceFilesTruncated,
3905
+ resolveIdentity
3906
+ });
3907
+ setGraphBuildInfo(graph, {
3908
+ reused: false,
3909
+ mode: "full",
3910
+ sourceFileCount,
3911
+ sourceFileCountTruncated: sourceFilesTruncated,
3912
+ pathNormalizeCalls,
3913
+ seqFastpathFallback,
3914
+ ...persistReason ? { persistReason } : {},
3915
+ graphChanged: true
3916
+ });
3917
+ graph.buildGeneration = generation;
3918
+ setSessionReviewGraphFact(cwd, facts, graphSnapshot);
3919
+ return graph;
3920
+ }
3921
+ function buildCacheKey(cwd, changedFiles) {
3922
+ return `${buildCacheWorkspaceKey(cwd)}|${[...changedFiles].sort((a, b) => compareOrdinal(a, b)).join(",")}`;
3923
+ }
3924
+ function isGraphBuildInFlight(cwd, changedFiles = []) {
3925
+ return _buildCache.has(buildCacheKey(cwd, changedFiles));
3926
+ }
3927
+ function buildOrUpdateGraph(cwd, changedFiles, facts, seqHint) {
3928
+ const cacheKey = buildCacheKey(cwd, changedFiles);
3929
+ const cached = _buildCache.get(cacheKey);
3930
+ if (cached)
3931
+ return cached;
3932
+ const startedAt = Date.now();
3933
+ const buildId = ++_buildIdCounter;
3934
+ recordBuildAttempt(cwd, "running", void 0, buildId);
3935
+ const startedProjectSeq = seqHint?.projectSeq();
3936
+ logReviewGraph({
3937
+ cwd,
3938
+ phase: "build_started",
3939
+ observability: {
3940
+ graph: {
3941
+ buildId,
3942
+ ...startedProjectSeq === void 0 ? {} : { projectSeq: startedProjectSeq },
3943
+ ...seqHint === void 0 ? {} : { seqHint: true },
3944
+ nodes: 0,
3945
+ edges: 0
3946
+ }
3947
+ }
3948
+ });
3949
+ const promise = _doBuildGraph(cwd, changedFiles, facts, seqHint, buildId).then((graph) => {
3950
+ let buildInfo = getGraphBuildInfoForGraph(graph);
3951
+ const wasmTrappedFiles = wasmTrappedFileCount(graph);
3952
+ if (wasmTrappedFiles > 0) {
3953
+ buildInfo = updateGraphBuildInfo(graph, { wasmTrappedFiles });
3954
+ }
3955
+ if (buildInfo.mode === "skipped") {
3956
+ const reason = buildInfo.skipReason ?? "skipped";
3957
+ recordBuildAttempt(cwd, "skipped", reason, buildId);
3958
+ logReviewGraph({
3959
+ cwd,
3960
+ phase: "build_skipped",
3961
+ reason,
3962
+ durationMs: Date.now() - startedAt,
3963
+ observability: {
3964
+ graph: graphLogMetadata(graph, {
3965
+ buildId,
3966
+ projectSeq: startedProjectSeq,
3967
+ seqHint: seqHint !== void 0,
3968
+ mode: buildInfo.mode,
3969
+ sourceFileCount: buildInfo.sourceFileCount,
3970
+ sourceFileCountTruncated: buildInfo.sourceFileCountTruncated,
3971
+ pathNormalizeCalls: buildInfo.pathNormalizeCalls
3972
+ })
3973
+ }
3974
+ });
3975
+ } else {
3976
+ const reason = buildInfo.persistReason;
3977
+ recordBuildAttempt(cwd, "succeeded", reason, buildId);
3978
+ logReviewGraph({
3979
+ cwd,
3980
+ phase: "build_succeeded",
3981
+ durationMs: Date.now() - startedAt,
3982
+ nodes: graph.nodes.size,
3983
+ edges: graph.edges.length,
3984
+ ...reason ? { reason } : {},
3985
+ observability: {
3986
+ graph: graphLogMetadata(graph, {
3987
+ buildId,
3988
+ projectSeq: startedProjectSeq,
3989
+ seqHint: seqHint !== void 0,
3990
+ mode: buildInfo.mode,
3991
+ sourceFileCount: buildInfo.sourceFileCount,
3992
+ sourceFileCountTruncated: buildInfo.sourceFileCountTruncated,
3993
+ pathNormalizeCalls: buildInfo.pathNormalizeCalls
3994
+ })
3995
+ }
3996
+ });
3997
+ }
3998
+ return graph;
3999
+ }).catch((err) => {
4000
+ const reason = err instanceof Error ? err.message : String(err);
4001
+ const wasmFailure = classifyTreeSitterWasmError(err);
4002
+ recordBuildAttempt(cwd, "failed", reason, buildId);
4003
+ logReviewGraph({
4004
+ cwd,
4005
+ phase: "build_failed",
4006
+ // #3605: an internal wasm failure, not a failed build.
4007
+ failureClass: wasmFailure ? `wasm-${wasmFailure}` : "error",
4008
+ reason,
4009
+ durationMs: Date.now() - startedAt,
4010
+ error: reason,
4011
+ observability: {
4012
+ graph: {
4013
+ buildId,
4014
+ ...seqHint === void 0 ? {} : { seqHint: true },
4015
+ nodes: 0,
4016
+ edges: 0
4017
+ }
4018
+ }
4019
+ });
4020
+ throw err;
4021
+ });
4022
+ _buildCache.set(cacheKey, promise);
4023
+ const release = () => {
4024
+ if (_buildCache.get(cacheKey) === promise)
4025
+ _buildCache.delete(cacheKey);
4026
+ };
4027
+ promise.then(release, release);
4028
+ return promise;
4029
+ }
4030
+ function extractSymbolsAndRefsFromGraph(graph) {
4031
+ const allSymbols = /* @__PURE__ */ new Map();
4032
+ const allRefs = /* @__PURE__ */ new Map();
4033
+ const nodeSymbols = /* @__PURE__ */ new Map();
4034
+ const coverage = {
4035
+ totalEvidence: 0,
4036
+ callsEvidence: 0,
4037
+ referencesEvidence: 0,
4038
+ eligibleEvidence: 0,
4039
+ resolvedEvidence: 0,
4040
+ unresolvedEvidence: 0,
4041
+ typeOnlyEvidence: 0,
4042
+ unsupportedEvidence: 0,
4043
+ sameFileEvidence: 0,
4044
+ duplicateEvidence: 0,
4045
+ complete: graph.persistCoverage?.partial !== true && graph.persistCoverage?.inProgress !== true,
4046
+ languages: {}
4047
+ };
4048
+ const numberMetadata = (node, key) => {
4049
+ const value = node?.metadata?.[key];
4050
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
4051
+ };
4052
+ const symbolKind = (node) => {
4053
+ switch (node.symbolKind) {
4054
+ case "class":
4055
+ case "interface":
4056
+ case "type":
4057
+ case "variable":
4058
+ case "method":
4059
+ case "property":
4060
+ case "function":
4061
+ return node.symbolKind;
4062
+ default:
4063
+ return "function";
4064
+ }
4065
+ };
4066
+ for (const node of graph.nodes.values()) {
4067
+ if (node.kind !== "symbol" || !node.filePath || !node.symbolName)
4068
+ continue;
4069
+ const sym = {
4070
+ id: node.id,
4071
+ name: node.symbolName,
4072
+ kind: symbolKind(node),
4073
+ filePath: node.filePath,
4074
+ line: numberMetadata(node, "line") ?? 1,
4075
+ endLine: numberMetadata(node, "endLine"),
4076
+ column: numberMetadata(node, "column") ?? 1,
4077
+ isExported: node.exported === true
4078
+ };
4079
+ nodeSymbols.set(node.id, sym);
4080
+ const list = allSymbols.get(node.filePath) ?? [];
4081
+ list.push(sym);
4082
+ allSymbols.set(node.filePath, list);
4083
+ }
4084
+ const addRef = (ref) => {
4085
+ const list = allRefs.get(ref.filePath) ?? [];
4086
+ list.push(ref);
4087
+ allRefs.set(ref.filePath, list);
4088
+ };
4089
+ for (const edge of graph.edges) {
4090
+ if (edge.kind !== "calls" && edge.kind !== "references")
4091
+ continue;
4092
+ coverage.totalEvidence++;
4093
+ if (edge.kind === "calls")
4094
+ coverage.callsEvidence++;
4095
+ else
4096
+ coverage.referencesEvidence++;
4097
+ const fromNode = graph.nodes.get(edge.from);
4098
+ const targetNode = graph.nodes.get(edge.to);
4099
+ const callerFile = fromNode?.kind === "symbol" ? fromNode.filePath : fromNode?.kind === "file" ? fromNode.filePath : edge.from.startsWith("file:") ? edge.from.slice("file:".length) : void 0;
4100
+ if (!callerFile) {
4101
+ coverage.unsupportedEvidence++;
4102
+ continue;
4103
+ }
4104
+ const metadata = edge.metadata ?? {};
4105
+ const referenceKind = edge.kind === "calls" ? "call" : metadata.referenceKind === "call" ? "call" : metadata.referenceKind === "type" ? "type" : "unknown";
4106
+ const resolution = edge.resolution ?? (targetNode && !targetNode.metadata?.unresolvedName ? "exact" : "unresolved");
4107
+ const targetSymbol = nodeSymbols.get(edge.to);
4108
+ const targetName = targetNode?.symbolName ?? (edge.to.startsWith("symbol-name:") ? edge.to.slice("symbol-name:".length) : void 0);
4109
+ const line = typeof metadata.line === "number" ? metadata.line : numberMetadata(fromNode, "line") ?? 1;
4110
+ const column = typeof metadata.column === "number" ? metadata.column : numberMetadata(fromNode, "column") ?? 1;
4111
+ addRef({
4112
+ symbolId: targetName ? `${callerFile}:${targetName}` : edge.to,
4113
+ filePath: callerFile,
4114
+ line,
4115
+ column,
4116
+ evidenceKind: edge.kind,
4117
+ referenceKind,
4118
+ targetId: edge.to,
4119
+ callerSymbolId: fromNode?.kind === "symbol" ? fromNode.id : void 0,
4120
+ resolution,
4121
+ targetName,
4122
+ targetKind: targetNode?.symbolKind,
4123
+ targetFilePath: targetNode?.filePath,
4124
+ targetLine: numberMetadata(targetNode, "line"),
4125
+ targetColumn: numberMetadata(targetNode, "column")
4126
+ });
4127
+ if (referenceKind === "type")
4128
+ coverage.typeOnlyEvidence++;
4129
+ else if (referenceKind !== "call")
4130
+ coverage.unsupportedEvidence++;
4131
+ else if (!targetSymbol || resolution === "name-only" || resolution === "unresolved") {
4132
+ coverage.unresolvedEvidence++;
4133
+ } else {
4134
+ coverage.eligibleEvidence++;
4135
+ coverage.resolvedEvidence++;
4136
+ }
4137
+ }
4138
+ let sawRelevantFileNode = false;
4139
+ for (const node of graph.nodes.values()) {
4140
+ if (node.kind !== "file")
4141
+ continue;
4142
+ sawRelevantFileNode = true;
4143
+ const extraction = node.metadata?.extractionCoverage;
4144
+ const statuses = extraction ? Object.values(extraction) : [];
4145
+ const languageStatus = !extraction || statuses.length === 0 || statuses.includes("unavailable") ? "unavailable" : statuses.includes("partial") ? "partial" : "complete";
4146
+ if (languageStatus !== "complete")
4147
+ coverage.complete = false;
4148
+ if (node.language) {
4149
+ const prior = coverage.languages[node.language];
4150
+ coverage.languages[node.language] = prior === "unavailable" || languageStatus === "unavailable" ? "unavailable" : prior === "partial" || languageStatus === "partial" ? "partial" : languageStatus;
4151
+ }
4152
+ }
4153
+ if (!sawRelevantFileNode)
4154
+ coverage.complete = false;
4155
+ return { allSymbols, allRefs, coverage };
4156
+ }
4157
+
4158
+ export {
4159
+ fileContentProvider,
4160
+ SYMBOL_KIND_NAMES,
4161
+ formatReviewGraphRevisionDriftNote,
4162
+ reviewGraphIrContentHash,
4163
+ publishReviewGraphFileIr,
4164
+ REVIEW_GRAPH_VERSION,
4165
+ _resetReviewGraphSourcePathMemoForTests,
4166
+ graphWasmTrapDetail,
4167
+ getGraphBuildInfoForGraph,
4168
+ graphBuildInfoIsTrustworthy,
4169
+ clearGraphCache,
4170
+ clearReviewGraphWorkspaceCache,
4171
+ _setReviewGraphBuildGateForTests,
4172
+ estimateReviewGraphStoreBytes,
4173
+ getReviewGraphWorkspaceCacheSnapshot,
4174
+ _getReviewGraphWorkspaceCacheKeysForTests,
4175
+ _setReviewGraphWorkspaceEntryForTests,
4176
+ _setSessionReviewGraphFactForTests,
4177
+ _persistedCoverageForTests,
4178
+ _getReviewGraphWorkspaceGraphForTests,
4179
+ _getReviewGraphCacheStateForTests,
4180
+ getReviewGraphCacheIdentity,
4181
+ _resetCwdWorktreeMismatchLogForTests,
4182
+ getLastGraphBuildInfo,
4183
+ _setLastGraphBuildInfoForTests,
4184
+ getCachedReviewGraph,
4185
+ getReviewGraphRevisionDrift,
4186
+ _resetReviewGraphSizeSkipTtlForTests,
4187
+ getLastReviewGraphBuildAttempt,
4188
+ _resetReviewGraphBuildAttemptsForTests,
4189
+ _resetReviewGraphSizeSkipVerdictsForTests,
4190
+ getReviewGraphSizeSkipVerdict,
4191
+ _setReviewGraphEntryBudgetForTests,
4192
+ _setReviewGraphEntryCounterForTests,
4193
+ getGraphSourceFiles,
4194
+ isReviewGraphMigrationNeeded,
4195
+ GRAPH_PERSIST_MAX_ELEMENTS_DEFAULT,
4196
+ refreshReviewGraphPersistWorkerHeapStatistics,
4197
+ getReviewGraphPersistWorkerHeapStatistics,
4198
+ flushReviewGraphPersistsForExitForTests,
4199
+ _resetReviewGraphStageSweepForTests,
4200
+ _readReviewGraphCheckpointForTests,
4201
+ flushReviewGraphPersistsForTests,
4202
+ waitForReviewGraphPersistsForTests,
4203
+ terminateReviewGraphPersistWorkerForTests,
4204
+ resetReviewGraphPersistWorkerForTests,
4205
+ getCheckpointOffloadCountForTests,
4206
+ getReviewGraphWorkerFallbackReasonForTests,
4207
+ reviewGraphCachePath,
4208
+ flushReviewGraphPersist,
4209
+ mapKindToTreeSitterLanguage,
4210
+ captureReviewGraphStructuralIr,
4211
+ _getReviewGraphRebuildCountersForTests,
4212
+ _resetReviewGraphRebuildCountersForTests,
4213
+ getGraphImportChanges,
4214
+ isGraphBuildInFlight,
4215
+ buildOrUpdateGraph,
4216
+ extractSymbolsAndRefsFromGraph
4217
+ };