knodin 0.14.0 → 0.14.2

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.
@@ -0,0 +1,1068 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ const TEST_FILE_PATTERN = /((^|\/)(test|tests|__tests__)(\/|$))|(\.(test|spec)\.[^.]+$)/i;
4
+ function isTestPath(filePath) {
5
+ return TEST_FILE_PATTERN.test(filePath);
6
+ }
7
+ function escapeRegExp(value) {
8
+ return value.replace(/[.*+?^${}()|[\]\\]/g, String.raw `\$&`);
9
+ }
10
+ function readSourceLines(repoPath, relativeFile, cache) {
11
+ const existing = cache.get(relativeFile);
12
+ if (existing)
13
+ return existing;
14
+ try {
15
+ const content = fs.readFileSync(path.join(repoPath, relativeFile), "utf8");
16
+ const lines = content.split(/\r?\n/);
17
+ cache.set(relativeFile, lines);
18
+ return lines;
19
+ }
20
+ catch {
21
+ cache.set(relativeFile, []);
22
+ return [];
23
+ }
24
+ }
25
+ function findEnclosingOwner(db, filePath, startLine, endLine) {
26
+ const rows = db
27
+ .query(`SELECT id, identity, name, kind, filePath, startLine, endLine
28
+ FROM symbols
29
+ WHERE filePath = ?
30
+ AND kind IN ('class', 'interface', 'variable')
31
+ AND startLine <= ?
32
+ AND endLine >= ?
33
+ AND NOT (startLine = ? AND endLine = ?)
34
+ ORDER BY (endLine - startLine) ASC
35
+ LIMIT 1`)
36
+ .all(filePath, startLine, endLine, startLine, endLine);
37
+ return rows[0];
38
+ }
39
+ function findEnclosingFunction(db, filePath, line) {
40
+ const rows = db
41
+ .query(`SELECT id, identity, name, kind, filePath, startLine, endLine
42
+ FROM symbols
43
+ WHERE filePath = ?
44
+ AND kind IN ('function', 'method')
45
+ AND startLine <= ?
46
+ AND endLine >= ?
47
+ ORDER BY (endLine - startLine) ASC
48
+ LIMIT 1`)
49
+ .all(filePath, line, line);
50
+ return rows[0];
51
+ }
52
+ function findImplementorsOfType(db, typeName, methodName) {
53
+ const heritageRows = db
54
+ .query(`SELECT DISTINCT callerSymbol, callerFile
55
+ FROM "references"
56
+ WHERE calleeSymbol = ?
57
+ AND kind IN ('implements', 'extends', 'structural_implements')
58
+ AND callerSymbol IS NOT NULL
59
+ ORDER BY callerFile, callerSymbol`)
60
+ .all(typeName);
61
+ const candidates = [];
62
+ const seen = new Set();
63
+ const addMethodForOwner = (ownerName, ownerFile) => {
64
+ const owner = db
65
+ .query(`SELECT id, identity, name, kind, filePath, startLine, endLine
66
+ FROM symbols
67
+ WHERE name = ? AND filePath = ? AND kind IN ('class', 'interface', 'variable')
68
+ LIMIT 1`)
69
+ .get(ownerName, ownerFile);
70
+ if (!owner)
71
+ return;
72
+ const method = db
73
+ .query(`SELECT id, identity, name, kind, filePath, startLine, endLine
74
+ FROM symbols
75
+ WHERE name = ? AND filePath = ? AND startLine >= ? AND endLine <= ?
76
+ LIMIT 1`)
77
+ .get(methodName, ownerFile, owner.startLine, owner.endLine);
78
+ if (!method)
79
+ return;
80
+ const key = `${method.name}|${method.filePath}|${owner.name}`;
81
+ if (seen.has(key))
82
+ return;
83
+ seen.add(key);
84
+ candidates.push({
85
+ symbol: method.name,
86
+ file: method.filePath,
87
+ ...(method.identity ? { identity: method.identity } : {}),
88
+ owner: owner.name,
89
+ line: method.startLine,
90
+ });
91
+ };
92
+ // Check if typeName itself is a concrete class that defines methodName
93
+ const selfClass = db
94
+ .query(`SELECT id, identity, name, kind, filePath, startLine, endLine
95
+ FROM symbols
96
+ WHERE name = ? AND kind = 'class'
97
+ LIMIT 1`)
98
+ .get(typeName);
99
+ if (selfClass) {
100
+ addMethodForOwner(selfClass.name, selfClass.filePath);
101
+ }
102
+ for (const row of heritageRows) {
103
+ addMethodForOwner(row.callerSymbol, row.callerFile);
104
+ }
105
+ return candidates;
106
+ }
107
+ export function classifyMemberCallAtSite(db, repoPath, callerFile, line, calleeSymbol, sourceCache) {
108
+ const lines = readSourceLines(repoPath, callerFile, sourceCache);
109
+ const lineText = (lines[line - 1] ?? "").trim();
110
+ if (!lineText) {
111
+ return { kind: "unresolved", sourceEvidence: "" };
112
+ }
113
+ const escapedCallee = escapeRegExp(calleeSymbol);
114
+ // 1. Check inline construction: `new ClassName(...).calleeSymbol(`
115
+ const inlineNewMatch = new RegExp(String.raw `\bnew\s+([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*\.\s*${escapedCallee}\s*\(`).exec(lineText);
116
+ if (inlineNewMatch) {
117
+ const className = inlineNewMatch[1];
118
+ const candidates = findImplementorsOfType(db, className, calleeSymbol);
119
+ const exact = candidates.find((c) => c.owner === className);
120
+ if (exact && candidates.length === 1) {
121
+ return {
122
+ kind: "exact-class",
123
+ ownerClass: className,
124
+ targetFile: exact.file,
125
+ targetIdentity: exact.identity,
126
+ sourceEvidence: lineText,
127
+ };
128
+ }
129
+ if (candidates.length > 1) {
130
+ return {
131
+ kind: "possible-interface",
132
+ interfaceName: className,
133
+ candidates,
134
+ sourceEvidence: lineText,
135
+ };
136
+ }
137
+ }
138
+ // 2. Check explicit cast: `(x as any).calleeSymbol(` or `(x as unknown).calleeSymbol(`
139
+ const castCallMatch = new RegExp(String.raw `\(\s*([A-Za-z_$][\w$]*)\s+as\s+(any|unknown|Record<[^>]+>|object|Function)\s*\)\s*\.\s*${escapedCallee}\s*\(`).exec(lineText);
140
+ if (castCallMatch) {
141
+ return {
142
+ kind: "unknown",
143
+ reason: "untyped-receiver",
144
+ expression: castCallMatch[0].replace(/\s*\($/, ""),
145
+ sourceEvidence: lineText,
146
+ };
147
+ }
148
+ // 3. Check identifier receiver: `recv.calleeSymbol(`
149
+ const recvMatch = new RegExp(String.raw `\b([A-Za-z_$][\w$]*)\s*\.\s*${escapedCallee}\s*\(`).exec(lineText);
150
+ if (!recvMatch) {
151
+ return { kind: "unresolved", sourceEvidence: lineText };
152
+ }
153
+ const recvIdent = recvMatch[1];
154
+ if (recvIdent === "this") {
155
+ const enclosingClass = findEnclosingOwner(db, callerFile, line, line);
156
+ if (enclosingClass && enclosingClass.kind === "class") {
157
+ const candidates = findImplementorsOfType(db, enclosingClass.name, calleeSymbol);
158
+ const exact = candidates.find((c) => c.owner === enclosingClass.name);
159
+ if (exact && candidates.length === 1) {
160
+ return {
161
+ kind: "exact-class",
162
+ ownerClass: enclosingClass.name,
163
+ targetFile: exact.file,
164
+ targetIdentity: exact.identity,
165
+ sourceEvidence: lineText,
166
+ };
167
+ }
168
+ }
169
+ return { kind: "unresolved", sourceEvidence: lineText };
170
+ }
171
+ // Inspect enclosing function or nearby lines for type annotations / `new` initializers
172
+ const enclosingFn = findEnclosingFunction(db, callerFile, line);
173
+ const scopeStart = enclosingFn ? Math.max(1, enclosingFn.startLine) : Math.max(1, line - 30);
174
+ const scopeEnd = enclosingFn ? Math.min(lines.length, enclosingFn.endLine) : line;
175
+ const scopeText = lines.slice(scopeStart - 1, scopeEnd).join("\n");
176
+ const fullFileHeader = lines.slice(0, Math.min(lines.length, 40)).join("\n");
177
+ const combinedScope = `${fullFileHeader}\n${scopeText}`;
178
+ const escapedRecv = escapeRegExp(recvIdent);
179
+ // Check `const recv = new ClassName(` or `const recv: TypeName = new ClassName(`
180
+ const newAssignMatch = new RegExp(String.raw `\b(?:const|let|var)\s+${escapedRecv}(?:\s*:\s*([A-Za-z_$][\w$]*))?\s*=\s*new\s+([A-Za-z_$][\w$]*)\s*\(`).exec(combinedScope);
181
+ if (newAssignMatch) {
182
+ const annotated = newAssignMatch[1];
183
+ const constructed = newAssignMatch[2];
184
+ const effectiveType = annotated || constructed;
185
+ const isInterface = annotated &&
186
+ db
187
+ .query("SELECT id FROM symbols WHERE name = ? AND kind = 'interface' LIMIT 1")
188
+ .get(annotated) != null;
189
+ if (!isInterface) {
190
+ const candidates = findImplementorsOfType(db, constructed, calleeSymbol);
191
+ const exact = candidates.find((c) => c.owner === constructed);
192
+ if (exact && candidates.length === 1) {
193
+ return {
194
+ kind: "exact-class",
195
+ ownerClass: constructed,
196
+ targetFile: exact.file,
197
+ targetIdentity: exact.identity,
198
+ sourceEvidence: lineText,
199
+ };
200
+ }
201
+ }
202
+ else if (effectiveType) {
203
+ const candidates = findImplementorsOfType(db, effectiveType, calleeSymbol);
204
+ if (candidates.length > 0) {
205
+ return {
206
+ kind: "possible-interface",
207
+ interfaceName: effectiveType,
208
+ candidates,
209
+ sourceEvidence: lineText,
210
+ };
211
+ }
212
+ }
213
+ }
214
+ // Check explicit type annotation on parameter or variable: `recv: TypeName`
215
+ const typeAnnotationMatch = new RegExp(String.raw `\b${escapedRecv}\s*\??\s*:\s*(any|unknown|Function|Object|Record<[^>]+>|[A-Za-z_$][\w$]*)`).exec(combinedScope);
216
+ if (typeAnnotationMatch) {
217
+ const typeName = typeAnnotationMatch[1];
218
+ if (typeName === "any" ||
219
+ typeName === "unknown" ||
220
+ typeName === "Function" ||
221
+ typeName === "Object" ||
222
+ typeName.startsWith("Record<")) {
223
+ return {
224
+ kind: "unknown",
225
+ reason: "untyped-receiver",
226
+ expression: `${recvIdent}.${calleeSymbol}`,
227
+ sourceEvidence: lineText,
228
+ };
229
+ }
230
+ const typeSymbols = db
231
+ .query(`SELECT id, identity, name, kind, filePath, startLine, endLine
232
+ FROM symbols
233
+ WHERE name = ? AND kind IN ('interface', 'class', 'type')`)
234
+ .all(typeName);
235
+ const isInterface = typeSymbols.some((s) => s.kind === "interface");
236
+ const candidates = findImplementorsOfType(db, typeName, calleeSymbol);
237
+ if (isInterface || candidates.length > 1) {
238
+ if (candidates.length > 0) {
239
+ return {
240
+ kind: "possible-interface",
241
+ interfaceName: typeName,
242
+ candidates,
243
+ sourceEvidence: lineText,
244
+ };
245
+ }
246
+ }
247
+ else if (candidates.length === 1) {
248
+ return {
249
+ kind: "exact-class",
250
+ ownerClass: typeName,
251
+ targetFile: candidates[0].file,
252
+ targetIdentity: candidates[0].identity,
253
+ sourceEvidence: lineText,
254
+ };
255
+ }
256
+ }
257
+ return { kind: "unresolved", sourceEvidence: lineText };
258
+ }
259
+ function parseParameterNames(headerText) {
260
+ const openParen = headerText.indexOf("(");
261
+ if (openParen < 0)
262
+ return [];
263
+ let depth = 0;
264
+ let closeParen = -1;
265
+ for (let i = openParen; i < headerText.length; i++) {
266
+ const ch = headerText[i];
267
+ if (ch === "(")
268
+ depth++;
269
+ else if (ch === ")") {
270
+ depth--;
271
+ if (depth === 0) {
272
+ closeParen = i;
273
+ break;
274
+ }
275
+ }
276
+ }
277
+ if (closeParen < 0)
278
+ return [];
279
+ const inner = headerText.slice(openParen + 1, closeParen).trim();
280
+ if (!inner)
281
+ return [];
282
+ const parts = [];
283
+ let start = 0;
284
+ let angle = 0;
285
+ let paren = 0;
286
+ let brace = 0;
287
+ for (let i = 0; i < inner.length; i++) {
288
+ const ch = inner[i];
289
+ if (ch === "<")
290
+ angle++;
291
+ else if (ch === ">" && angle > 0)
292
+ angle--;
293
+ else if (ch === "(")
294
+ paren++;
295
+ else if (ch === ")" && paren > 0)
296
+ paren--;
297
+ else if (ch === "{")
298
+ brace++;
299
+ else if (ch === "}" && brace > 0)
300
+ brace--;
301
+ else if (ch === "," && angle === 0 && paren === 0 && brace === 0) {
302
+ parts.push(inner.slice(start, i).trim());
303
+ start = i + 1;
304
+ }
305
+ }
306
+ parts.push(inner.slice(start).trim());
307
+ return parts.map((param) => {
308
+ const clean = param.replace(/^(?:public|private|protected|readonly|\.\.\.)\s+/, "").trim();
309
+ const idMatch = /^([A-Za-z_$][\w$]*)/.exec(clean);
310
+ return idMatch ? idMatch[1] : "";
311
+ });
312
+ }
313
+ function extractCallArgumentsForCallee(lineText, calleeName) {
314
+ const escaped = escapeRegExp(calleeName);
315
+ const match = new RegExp(String.raw `\b${escaped}\s*\(`).exec(lineText);
316
+ if (!match)
317
+ return null;
318
+ const openIdx = (match.index ?? 0) + match[0].length - 1;
319
+ let depth = 0;
320
+ let closeIdx = -1;
321
+ for (let i = openIdx; i < lineText.length; i++) {
322
+ const ch = lineText[i];
323
+ if (ch === "(")
324
+ depth++;
325
+ else if (ch === ")") {
326
+ depth--;
327
+ if (depth === 0) {
328
+ closeIdx = i;
329
+ break;
330
+ }
331
+ }
332
+ }
333
+ if (closeIdx < 0)
334
+ return null;
335
+ const inner = lineText.slice(openIdx + 1, closeIdx).trim();
336
+ if (!inner)
337
+ return [];
338
+ const args = [];
339
+ let start = 0;
340
+ let nested = 0;
341
+ for (let i = 0; i < inner.length; i++) {
342
+ const ch = inner[i];
343
+ if ("({[".includes(ch))
344
+ nested++;
345
+ else if (")}]".includes(ch) && nested > 0)
346
+ nested--;
347
+ else if (ch === "," && nested === 0) {
348
+ args.push(inner.slice(start, i).trim());
349
+ start = i + 1;
350
+ }
351
+ }
352
+ args.push(inner.slice(start).trim());
353
+ return args;
354
+ }
355
+ export function findCallbackHandoffEdges(db, repoPath, sourceCache, scopeFiles) {
356
+ // Find unresolved bare calls inside named functions where calleeSymbol matches a parameter name
357
+ const unresolvedCalls = db
358
+ .query(`SELECT id, callerSymbol, callerFile, calleeSymbol, calleeFile, callerIdentity, calleeIdentity, line, column, kind, confidence
359
+ FROM "references"
360
+ WHERE callerSymbol IS NOT NULL
361
+ AND calleeFile IS NULL
362
+ AND kind = 'call'`)
363
+ .all();
364
+ const edges = [];
365
+ const seenRunnerParams = new Set();
366
+ for (const callRef of unresolvedCalls) {
367
+ if (!callRef.callerSymbol)
368
+ continue;
369
+ if (scopeFiles &&
370
+ !scopeFiles.has(callRef.callerFile) &&
371
+ db
372
+ .query("SELECT COUNT(*) AS count FROM \"references\" WHERE calleeSymbol = ? AND kind = 'call'")
373
+ .get(callRef.callerSymbol)?.count === 0) {
374
+ continue;
375
+ }
376
+ const runnerKey = `${callRef.callerSymbol}|${callRef.callerFile}|${callRef.calleeSymbol}`;
377
+ if (seenRunnerParams.has(runnerKey))
378
+ continue;
379
+ const fnRow = db
380
+ .query(`SELECT id, identity, name, kind, filePath, startLine, endLine
381
+ FROM symbols
382
+ WHERE name = ? AND filePath = ? AND kind IN ('function', 'method')
383
+ LIMIT 1`)
384
+ .get(callRef.callerSymbol, callRef.callerFile);
385
+ if (!fnRow)
386
+ continue;
387
+ const lines = readSourceLines(repoPath, callRef.callerFile, sourceCache);
388
+ const headerLines = lines
389
+ .slice(fnRow.startLine - 1, Math.min(lines.length, fnRow.startLine + 6))
390
+ .join(" ");
391
+ const paramNames = parseParameterNames(headerLines);
392
+ const paramIndex = paramNames.indexOf(callRef.calleeSymbol);
393
+ if (paramIndex < 0)
394
+ continue;
395
+ // Ensure the call on callRef.line is a bare parameter invocation `paramName(`, not `.paramName(`
396
+ const invokeLineText = (lines[callRef.line - 1] ?? "").trim();
397
+ const bareCallRegex = new RegExp(String.raw `(?<!\.)\b${escapeRegExp(callRef.calleeSymbol)}\s*\(`);
398
+ if (!bareCallRegex.test(invokeLineText))
399
+ continue;
400
+ seenRunnerParams.add(runnerKey);
401
+ // Find all call sites to `fnRow.name`
402
+ const runnerCallSites = db
403
+ .query(`SELECT id, callerSymbol, callerFile, calleeSymbol, calleeFile, callerIdentity, calleeIdentity, line, column, kind, confidence
404
+ FROM "references"
405
+ WHERE calleeSymbol = ?
406
+ AND (calleeFile = ? OR calleeFile IS NULL)
407
+ AND kind = 'call'`)
408
+ .all(fnRow.name, fnRow.filePath);
409
+ const siteTargets = [];
410
+ const candidateMap = new Map();
411
+ for (const site of runnerCallSites) {
412
+ if (scopeFiles && !scopeFiles.has(site.callerFile) && !scopeFiles.has(fnRow.filePath)) {
413
+ continue;
414
+ }
415
+ const siteLines = readSourceLines(repoPath, site.callerFile, sourceCache);
416
+ const siteLineText = (siteLines[site.line - 1] ?? "").trim();
417
+ const args = extractCallArgumentsForCallee(siteLineText, fnRow.name);
418
+ if (!args || paramIndex >= args.length)
419
+ continue;
420
+ const argExpr = args[paramIndex].trim();
421
+ const identMatch = /^([A-Za-z_$][\w$]*)$/.exec(argExpr);
422
+ if (!identMatch)
423
+ continue;
424
+ const passedSymbol = identMatch[1];
425
+ // Resolve passedSymbol to a definition in site.callerFile or an imported file of site.callerFile
426
+ const candidateFiles = [
427
+ site.callerFile,
428
+ ...db
429
+ .query("SELECT DISTINCT toFile FROM dependencies WHERE fromFile = ? AND kind = 'import'")
430
+ .all(site.callerFile)
431
+ .map((r) => r.toFile),
432
+ ];
433
+ let resolvedSym;
434
+ for (const fileCandidate of candidateFiles) {
435
+ const sym = db
436
+ .query(`SELECT id, identity, name, kind, filePath, startLine, endLine
437
+ FROM symbols
438
+ WHERE name = ? AND filePath = ? AND kind IN ('function', 'method', 'variable')
439
+ LIMIT 1`)
440
+ .get(passedSymbol, fileCandidate);
441
+ if (sym) {
442
+ resolvedSym = sym;
443
+ break;
444
+ }
445
+ }
446
+ if (!resolvedSym)
447
+ continue;
448
+ const targetCandidate = {
449
+ symbol: resolvedSym.name,
450
+ file: resolvedSym.filePath,
451
+ ...(resolvedSym.identity ? { identity: resolvedSym.identity } : {}),
452
+ line: resolvedSym.startLine,
453
+ };
454
+ candidateMap.set(`${targetCandidate.symbol}|${targetCandidate.file}`, targetCandidate);
455
+ siteTargets.push({ site, target: targetCandidate, siteEvidence: siteLineText });
456
+ }
457
+ if (siteTargets.length === 0)
458
+ continue;
459
+ const candidateTargets = [...candidateMap.values()];
460
+ const viaParamLabel = `${fnRow.name}:${callRef.calleeSymbol}`;
461
+ for (const { site, target, siteEvidence } of siteTargets) {
462
+ const callerName = site.callerSymbol ?? "(anonymous or top-level)";
463
+ edges.push({
464
+ callerSymbol: callerName,
465
+ callerFile: site.callerFile,
466
+ ...(site.callerIdentity ? { callerIdentity: site.callerIdentity } : {}),
467
+ ...(site.callerSymbol === null ? { callerOrigin: "anonymous-or-top-level" } : {}),
468
+ line: site.line,
469
+ calleeSymbol: target.symbol,
470
+ calleeFile: target.file,
471
+ ...(target.identity ? { calleeIdentity: target.identity } : {}),
472
+ targetUncertainty: "possible-set",
473
+ uncertaintyReason: "callback-handoff",
474
+ viaParameter: viaParamLabel,
475
+ candidateTargets,
476
+ confidence: 0.5,
477
+ heuristic: true,
478
+ sourceEvidence: siteEvidence,
479
+ });
480
+ edges.push({
481
+ callerSymbol: fnRow.name,
482
+ callerFile: fnRow.filePath,
483
+ ...(fnRow.identity ? { callerIdentity: fnRow.identity } : {}),
484
+ line: callRef.line,
485
+ calleeSymbol: target.symbol,
486
+ calleeFile: target.file,
487
+ ...(target.identity ? { calleeIdentity: target.identity } : {}),
488
+ targetUncertainty: "possible-set",
489
+ uncertaintyReason: "callback-handoff",
490
+ viaParameter: viaParamLabel,
491
+ candidateTargets,
492
+ confidence: 0.5,
493
+ heuristic: true,
494
+ sourceEvidence: invokeLineText,
495
+ });
496
+ }
497
+ }
498
+ const deduped = new Map();
499
+ for (const edge of edges) {
500
+ const key = `${edge.callerSymbol}|${edge.callerFile}|${edge.line}|${edge.calleeSymbol}|${edge.calleeFile}|${edge.viaParameter ?? ""}`;
501
+ if (!deduped.has(key))
502
+ deduped.set(key, edge);
503
+ }
504
+ return [...deduped.values()];
505
+ }
506
+ export function scanUnknownCallSitesInFiles(db, repoPath, filesToScan, sourceCache, onlyCallerSymbol) {
507
+ const results = [];
508
+ const seen = new Set();
509
+ const subscriptCallRegex = /\b([A-Za-z_$][\w$]*)\s*\[\s*([^\]]+)\s*\]\s*\(/g;
510
+ const castMemberCallRegex = /\(\s*([A-Za-z_$][\w$]*)\s+as\s+(?:any|unknown|Record<[^>]+>|object|Function)\s*\)\s*\.\s*([A-Za-z_$][\w$]*)\s*\(/g;
511
+ for (const filePath of filesToScan) {
512
+ if (!/\.(?:[cm]?ts|tsx|[cm]?js|jsx)$/i.test(filePath))
513
+ continue;
514
+ const lines = readSourceLines(repoPath, filePath, sourceCache);
515
+ if (lines.length === 0)
516
+ continue;
517
+ const symbolsInFile = db
518
+ .query(`SELECT id, identity, name, kind, filePath, startLine, endLine
519
+ FROM symbols
520
+ WHERE filePath = ? AND kind IN ('function', 'method')
521
+ ORDER BY (endLine - startLine) ASC`)
522
+ .all(filePath);
523
+ const findEnclosing = (lineNum) => {
524
+ for (const sym of symbolsInFile) {
525
+ if (sym.startLine <= lineNum && sym.endLine >= lineNum)
526
+ return sym.name;
527
+ }
528
+ return null;
529
+ };
530
+ // Track untyped identifiers (`param: any`, `param: unknown`, `param: Record<...>`) per function
531
+ for (let idx = 0; idx < lines.length; idx++) {
532
+ const lineNum = idx + 1;
533
+ const rawLine = lines[idx] ?? "";
534
+ const trimmed = rawLine.trim();
535
+ if (!trimmed || trimmed.startsWith("//") || trimmed.startsWith("*"))
536
+ continue;
537
+ const enclosing = findEnclosing(lineNum);
538
+ if (onlyCallerSymbol && enclosing !== onlyCallerSymbol)
539
+ continue;
540
+ subscriptCallRegex.lastIndex = 0;
541
+ let subMatch = subscriptCallRegex.exec(trimmed);
542
+ while (subMatch !== null) {
543
+ const receiver = subMatch[1];
544
+ const keyExpr = subMatch[2].trim();
545
+ // Ignore numeric array index followed by call only if it is a known syntax keyword
546
+ if (!["if", "for", "while", "switch", "catch"].includes(receiver) &&
547
+ !/^['"`]/.test(keyExpr)) {
548
+ const expr = `${receiver}[${keyExpr}]`;
549
+ const key = `${filePath}:${lineNum}:${expr}`;
550
+ if (!seen.has(key)) {
551
+ seen.add(key);
552
+ results.push({
553
+ callerSymbol: enclosing,
554
+ callerFile: filePath,
555
+ line: lineNum,
556
+ expression: expr,
557
+ calleeSymbol: null,
558
+ targetUncertainty: "unknown",
559
+ uncertaintyReason: "dynamic-subscript",
560
+ sourceEvidence: trimmed,
561
+ });
562
+ }
563
+ }
564
+ subMatch = subscriptCallRegex.exec(trimmed);
565
+ }
566
+ castMemberCallRegex.lastIndex = 0;
567
+ let castMatch = castMemberCallRegex.exec(trimmed);
568
+ while (castMatch !== null) {
569
+ const recv = castMatch[1];
570
+ const member = castMatch[2];
571
+ const expr = `${recv}.${member}`;
572
+ const key = `${filePath}:${lineNum}:${expr}`;
573
+ if (!seen.has(key)) {
574
+ seen.add(key);
575
+ results.push({
576
+ callerSymbol: enclosing,
577
+ callerFile: filePath,
578
+ line: lineNum,
579
+ expression: expr,
580
+ calleeSymbol: member,
581
+ targetUncertainty: "unknown",
582
+ uncertaintyReason: "untyped-receiver",
583
+ sourceEvidence: trimmed,
584
+ });
585
+ }
586
+ castMatch = castMemberCallRegex.exec(trimmed);
587
+ }
588
+ }
589
+ }
590
+ return results;
591
+ }
592
+ export function analyzeSymbolTargetUncertainty(db, repoPath, targetSymbol, targetFile, targetIdentity = null, direction = "upstream", existingExactCount = 0, budgetBytes = null) {
593
+ const sourceCache = new Map();
594
+ const exactEdges = [];
595
+ const possibleEdges = [];
596
+ const unknownCalls = [];
597
+ const disjointCallers = new Set();
598
+ if (direction === "downstream") {
599
+ if (targetFile) {
600
+ // Scan outbound unresolved member calls from targetSymbol in targetFile
601
+ const outboundUnresolved = db
602
+ .query(`SELECT id, callerSymbol, callerFile, calleeSymbol, calleeFile, callerIdentity, calleeIdentity, line, column, kind, confidence
603
+ FROM "references"
604
+ WHERE callerSymbol = ?
605
+ AND callerFile = ?
606
+ AND calleeFile IS NULL
607
+ AND kind = 'call'`)
608
+ .all(targetSymbol, targetFile);
609
+ for (const ref of outboundUnresolved) {
610
+ const classification = classifyMemberCallAtSite(db, repoPath, ref.callerFile, ref.line, ref.calleeSymbol, sourceCache);
611
+ if (classification.kind === "exact-class") {
612
+ exactEdges.push({
613
+ callerSymbol: targetSymbol,
614
+ callerFile: targetFile,
615
+ line: ref.line,
616
+ calleeSymbol: ref.calleeSymbol,
617
+ calleeFile: classification.targetFile,
618
+ ...(classification.targetIdentity
619
+ ? { calleeIdentity: classification.targetIdentity }
620
+ : {}),
621
+ targetUncertainty: "exact",
622
+ uncertaintyReason: "resolved-receiver",
623
+ confidence: 1,
624
+ sourceEvidence: classification.sourceEvidence,
625
+ });
626
+ }
627
+ else if (classification.kind === "possible-interface") {
628
+ for (const cand of classification.candidates) {
629
+ possibleEdges.push({
630
+ callerSymbol: targetSymbol,
631
+ callerFile: targetFile,
632
+ line: ref.line,
633
+ calleeSymbol: cand.symbol,
634
+ calleeFile: cand.file,
635
+ ...(cand.identity ? { calleeIdentity: cand.identity } : {}),
636
+ targetUncertainty: "possible-set",
637
+ uncertaintyReason: "interface-dispatch",
638
+ viaInterface: classification.interfaceName,
639
+ candidateTargets: classification.candidates,
640
+ confidence: 0.5,
641
+ heuristic: true,
642
+ sourceEvidence: classification.sourceEvidence,
643
+ });
644
+ }
645
+ }
646
+ else if (classification.kind === "unknown") {
647
+ unknownCalls.push({
648
+ callerSymbol: targetSymbol,
649
+ callerFile: targetFile,
650
+ line: ref.line,
651
+ expression: classification.expression,
652
+ calleeSymbol: ref.calleeSymbol,
653
+ targetUncertainty: "unknown",
654
+ uncertaintyReason: classification.reason,
655
+ sourceEvidence: classification.sourceEvidence,
656
+ });
657
+ }
658
+ }
659
+ // Outbound callback handoffs from targetSymbol
660
+ const callbackEdges = findCallbackHandoffEdges(db, repoPath, sourceCache, new Set([targetFile])).filter((e) => e.callerSymbol === targetSymbol && e.callerFile === targetFile);
661
+ possibleEdges.push(...callbackEdges);
662
+ // Outbound dynamic subscript / cast unknown calls in targetSymbol
663
+ for (const site of scanUnknownCallSitesInFiles(db, repoPath, [targetFile], sourceCache, targetSymbol)) {
664
+ if (!unknownCalls.some((u) => u.callerFile === site.callerFile && u.line === site.line)) {
665
+ unknownCalls.push(site);
666
+ }
667
+ }
668
+ }
669
+ }
670
+ else {
671
+ // Upstream analysis for (targetSymbol, targetFile)
672
+ const targetRow = targetFile
673
+ ? db
674
+ .query(`SELECT id, identity, name, kind, filePath, startLine, endLine
675
+ FROM symbols
676
+ WHERE name = ? AND filePath = ? AND (? IS NULL OR identity = ?)
677
+ LIMIT 1`)
678
+ .get(targetSymbol, targetFile, targetIdentity, targetIdentity)
679
+ : db
680
+ .query(`SELECT id, identity, name, kind, filePath, startLine, endLine
681
+ FROM symbols
682
+ WHERE name = ?
683
+ LIMIT 1`)
684
+ .get(targetSymbol);
685
+ const effectiveFile = targetRow?.filePath ?? targetFile;
686
+ const owner = targetRow && effectiveFile
687
+ ? findEnclosingOwner(db, effectiveFile, targetRow.startLine, targetRow.endLine)
688
+ : undefined;
689
+ // 1. Inspect all unresolved member calls `WHERE calleeSymbol = targetSymbol AND calleeFile IS NULL`
690
+ const unresolvedRefs = db
691
+ .query(`SELECT id, callerSymbol, callerFile, calleeSymbol, calleeFile, callerIdentity, calleeIdentity, line, column, kind, confidence
692
+ FROM "references"
693
+ WHERE calleeSymbol = ?
694
+ AND calleeFile IS NULL
695
+ AND kind = 'call'`)
696
+ .all(targetSymbol);
697
+ for (const ref of unresolvedRefs) {
698
+ const classification = classifyMemberCallAtSite(db, repoPath, ref.callerFile, ref.line, ref.calleeSymbol, sourceCache);
699
+ const callerLabel = ref.callerSymbol ?? "(anonymous or top-level)";
700
+ if (classification.kind === "exact-class") {
701
+ if (effectiveFile &&
702
+ classification.targetFile === effectiveFile &&
703
+ (!owner || classification.ownerClass === owner.name)) {
704
+ exactEdges.push({
705
+ callerSymbol: callerLabel,
706
+ callerFile: ref.callerFile,
707
+ ...(ref.callerIdentity ? { callerIdentity: ref.callerIdentity } : {}),
708
+ ...(ref.callerSymbol === null
709
+ ? { callerOrigin: "anonymous-or-top-level" }
710
+ : {}),
711
+ line: ref.line,
712
+ calleeSymbol: targetSymbol,
713
+ calleeFile: effectiveFile,
714
+ ...(targetRow?.identity ? { calleeIdentity: targetRow.identity } : {}),
715
+ targetUncertainty: "exact",
716
+ uncertaintyReason: "resolved-receiver",
717
+ confidence: 1,
718
+ sourceEvidence: classification.sourceEvidence,
719
+ });
720
+ }
721
+ else {
722
+ disjointCallers.add(`${ref.callerSymbol ?? ""}|${ref.callerFile}|${ref.line}`);
723
+ }
724
+ }
725
+ else if (classification.kind === "possible-interface") {
726
+ const matchesTarget = effectiveFile
727
+ ? classification.candidates.some((c) => c.file === effectiveFile && (!owner || c.owner === owner.name))
728
+ : classification.candidates.length > 0;
729
+ if (matchesTarget && effectiveFile) {
730
+ possibleEdges.push({
731
+ callerSymbol: callerLabel,
732
+ callerFile: ref.callerFile,
733
+ ...(ref.callerIdentity ? { callerIdentity: ref.callerIdentity } : {}),
734
+ ...(ref.callerSymbol === null
735
+ ? { callerOrigin: "anonymous-or-top-level" }
736
+ : {}),
737
+ line: ref.line,
738
+ calleeSymbol: targetSymbol,
739
+ calleeFile: effectiveFile,
740
+ ...(targetRow?.identity ? { calleeIdentity: targetRow.identity } : {}),
741
+ targetUncertainty: "possible-set",
742
+ uncertaintyReason: "interface-dispatch",
743
+ viaInterface: classification.interfaceName,
744
+ candidateTargets: classification.candidates,
745
+ confidence: 0.5,
746
+ heuristic: true,
747
+ sourceEvidence: classification.sourceEvidence,
748
+ });
749
+ }
750
+ else {
751
+ disjointCallers.add(`${ref.callerSymbol ?? ""}|${ref.callerFile}|${ref.line}`);
752
+ }
753
+ }
754
+ else if (classification.kind === "unknown") {
755
+ unknownCalls.push({
756
+ callerSymbol: ref.callerSymbol,
757
+ callerFile: ref.callerFile,
758
+ line: ref.line,
759
+ expression: classification.expression,
760
+ calleeSymbol: ref.calleeSymbol,
761
+ targetUncertainty: "unknown",
762
+ uncertaintyReason: classification.reason,
763
+ sourceEvidence: classification.sourceEvidence,
764
+ });
765
+ }
766
+ }
767
+ // 2. Callback handoffs targeting (targetSymbol, effectiveFile)
768
+ if (effectiveFile) {
769
+ const importerFiles = new Set([
770
+ effectiveFile,
771
+ ...db
772
+ .query("SELECT DISTINCT fromFile FROM dependencies WHERE toFile = ? AND kind = 'import'")
773
+ .all(effectiveFile)
774
+ .map((r) => r.fromFile),
775
+ ]);
776
+ const callbackEdges = findCallbackHandoffEdges(db, repoPath, sourceCache, importerFiles).filter((e) => e.calleeSymbol === targetSymbol && e.calleeFile === effectiveFile);
777
+ for (const edge of callbackEdges) {
778
+ if (!possibleEdges.some((p) => p.callerSymbol === edge.callerSymbol &&
779
+ p.callerFile === edge.callerFile &&
780
+ p.line === edge.line)) {
781
+ possibleEdges.push(edge);
782
+ }
783
+ }
784
+ // 3. Scan neighborhood files for dynamic subscript / untyped receiver calls
785
+ const totalIndexedCount = db.query("SELECT COUNT(*) AS count FROM index_state").get()?.count ??
786
+ 0;
787
+ const candidateUnknownFiles = totalIndexedCount <= 64
788
+ ? db
789
+ .query("SELECT filePath FROM index_state ORDER BY filePath")
790
+ .all()
791
+ .map((r) => r.filePath)
792
+ : [...importerFiles];
793
+ for (const site of scanUnknownCallSitesInFiles(db, repoPath, candidateUnknownFiles, sourceCache)) {
794
+ if (!unknownCalls.some((u) => u.callerFile === site.callerFile && u.line === site.line)) {
795
+ unknownCalls.push(site);
796
+ }
797
+ }
798
+ }
799
+ }
800
+ const totalExact = existingExactCount + exactEdges.length;
801
+ const totalPossible = possibleEdges.length;
802
+ const totalUnknown = unknownCalls.length;
803
+ const precisionDenominator = totalExact + totalPossible;
804
+ const recallDenominator = totalExact + totalPossible + totalUnknown;
805
+ const reportPayload = {
806
+ exactCount: totalExact,
807
+ possibleCount: totalPossible,
808
+ unknownCount: totalUnknown,
809
+ possibleSet: possibleEdges,
810
+ unknownCalls,
811
+ };
812
+ const serializedBytes = Buffer.byteLength(JSON.stringify(reportPayload), "utf8");
813
+ const report = {
814
+ ...reportPayload,
815
+ metrics: {
816
+ precision: {
817
+ numerator: totalExact + totalPossible,
818
+ denominator: Math.max(1, precisionDenominator),
819
+ value: precisionDenominator > 0 ? 1 : null,
820
+ },
821
+ recall: {
822
+ numerator: totalExact + totalPossible,
823
+ denominator: Math.max(1, recallDenominator),
824
+ value: recallDenominator > 0
825
+ ? Math.round(((totalExact + totalPossible) / recallDenominator) * 1000) / 1000
826
+ : null,
827
+ },
828
+ unknownCoverage: {
829
+ numerator: totalUnknown,
830
+ denominator: Math.max(1, totalUnknown),
831
+ value: totalUnknown > 0 ? 1 : null,
832
+ },
833
+ outputSize: {
834
+ bytes: serializedBytes,
835
+ budgetBytes,
836
+ },
837
+ },
838
+ };
839
+ return {
840
+ exactEdges,
841
+ possibleEdges,
842
+ unknownCalls,
843
+ disjointCallers,
844
+ report,
845
+ };
846
+ }
847
+ export function buildUncertaintyAwareTestSelection(db, repoPath, targetSymbol, targetFile, targetIdentity, formatPath, maxDepth = 4) {
848
+ const analyzed = analyzeSymbolTargetUncertainty(db, repoPath, targetSymbol, targetFile, targetIdentity, "upstream");
849
+ const exactTestsMap = new Map();
850
+ const possibleTestsMap = new Map();
851
+ const unknownReachabilityMap = new Map();
852
+ const queue = [];
853
+ const visited = new Set();
854
+ const recordTestOrEnqueue = (callerSymbol, callerFile, line, uncertainty, reason, via, depth, extra) => {
855
+ const formattedFile = formatPath(repoPath, callerFile);
856
+ if (isTestPath(formattedFile)) {
857
+ const entry = {
858
+ file: formattedFile,
859
+ line,
860
+ ...(callerSymbol && callerSymbol !== "(anonymous or top-level)"
861
+ ? { symbol: callerSymbol }
862
+ : {}),
863
+ targetUncertainty: uncertainty,
864
+ uncertaintyReason: reason,
865
+ via,
866
+ ...(extra?.viaInterface ? { viaInterface: extra.viaInterface } : {}),
867
+ ...(extra?.viaParameter ? { viaParameter: extra.viaParameter } : {}),
868
+ ...(extra?.candidateTargets ? { candidateTargets: extra.candidateTargets } : {}),
869
+ ...(uncertainty === "possible-set" ? { heuristic: true } : {}),
870
+ ...(extra?.sourceEvidence ? { sourceEvidence: extra.sourceEvidence } : {}),
871
+ };
872
+ if (uncertainty === "exact") {
873
+ const existing = exactTestsMap.get(formattedFile);
874
+ if (!existing || line < existing.line) {
875
+ exactTestsMap.set(formattedFile, entry);
876
+ }
877
+ possibleTestsMap.delete(formattedFile);
878
+ }
879
+ else if (!exactTestsMap.has(formattedFile)) {
880
+ const existing = possibleTestsMap.get(formattedFile);
881
+ if (!existing || line < existing.line) {
882
+ possibleTestsMap.set(formattedFile, entry);
883
+ }
884
+ }
885
+ }
886
+ if (callerSymbol && callerSymbol !== "(anonymous or top-level)" && depth < maxDepth) {
887
+ const visitKey = `${callerSymbol}|${callerFile}|${uncertainty}`;
888
+ if (!visited.has(visitKey)) {
889
+ visited.add(visitKey);
890
+ queue.push({
891
+ symbol: callerSymbol,
892
+ file: callerFile,
893
+ uncertainty,
894
+ reason,
895
+ via: [...via, callerSymbol],
896
+ viaInterface: extra?.viaInterface,
897
+ viaParameter: extra?.viaParameter,
898
+ candidateTargets: extra?.candidateTargets,
899
+ sourceEvidence: extra?.sourceEvidence,
900
+ depth,
901
+ });
902
+ }
903
+ }
904
+ };
905
+ // 1. Seed direct resolved references to targetSymbol
906
+ const directRefs = targetFile
907
+ ? db
908
+ .query(`SELECT id, callerSymbol, callerFile, calleeSymbol, calleeFile, callerIdentity, calleeIdentity, line, column, kind, confidence
909
+ FROM "references"
910
+ WHERE calleeSymbol = ?
911
+ AND calleeFile = ?
912
+ AND kind IN ('call', 'di_binding', 'di_resolution', 'flow_apex_action', 'apex_method')
913
+ ORDER BY callerFile, line`)
914
+ .all(targetSymbol, targetFile)
915
+ : db
916
+ .query(`SELECT id, callerSymbol, callerFile, calleeSymbol, calleeFile, callerIdentity, calleeIdentity, line, column, kind, confidence
917
+ FROM "references"
918
+ WHERE calleeSymbol = ?
919
+ AND kind IN ('call', 'di_binding', 'di_resolution', 'flow_apex_action', 'apex_method')
920
+ ORDER BY callerFile, line`)
921
+ .all(targetSymbol);
922
+ for (const ref of directRefs) {
923
+ recordTestOrEnqueue(ref.callerSymbol, ref.callerFile, ref.line, "exact", "direct-call", [targetSymbol], 1);
924
+ }
925
+ // 2. Seed exact-class member calls
926
+ for (const edge of analyzed.exactEdges) {
927
+ recordTestOrEnqueue(edge.callerOrigin ? null : edge.callerSymbol, edge.callerFile, edge.line, "exact", edge.uncertaintyReason, [targetSymbol], 1, { sourceEvidence: edge.sourceEvidence });
928
+ }
929
+ // 3. Seed possible-set edges (interface dispatch & callback handoffs)
930
+ for (const edge of analyzed.possibleEdges) {
931
+ recordTestOrEnqueue(edge.callerOrigin ? null : edge.callerSymbol, edge.callerFile, edge.line, "possible-set", edge.uncertaintyReason, [
932
+ ...(edge.viaInterface ? [edge.viaInterface] : []),
933
+ ...(edge.viaParameter ? [edge.viaParameter] : []),
934
+ targetSymbol,
935
+ ], 1, {
936
+ viaInterface: edge.viaInterface,
937
+ viaParameter: edge.viaParameter,
938
+ candidateTargets: edge.candidateTargets,
939
+ sourceEvidence: edge.sourceEvidence,
940
+ });
941
+ }
942
+ // 4. Multi-hop BFS upward through callers
943
+ while (queue.length > 0) {
944
+ const current = queue.shift();
945
+ if (!current)
946
+ break;
947
+ const parentRefs = db
948
+ .query(`SELECT id, callerSymbol, callerFile, calleeSymbol, calleeFile, callerIdentity, calleeIdentity, line, column, kind, confidence
949
+ FROM "references"
950
+ WHERE calleeSymbol = ?
951
+ AND calleeFile = ?
952
+ AND kind = 'call'
953
+ ORDER BY callerFile, line`)
954
+ .all(current.symbol, current.file);
955
+ for (const ref of parentRefs) {
956
+ if (analyzed.disjointCallers.has(`${ref.callerSymbol ?? ""}|${ref.callerFile}|${ref.line}`)) {
957
+ continue;
958
+ }
959
+ recordTestOrEnqueue(ref.callerSymbol, ref.callerFile, ref.line, current.uncertainty, current.reason, current.via, current.depth + 1, {
960
+ viaInterface: current.viaInterface,
961
+ viaParameter: current.viaParameter,
962
+ candidateTargets: current.candidateTargets,
963
+ sourceEvidence: current.sourceEvidence,
964
+ });
965
+ }
966
+ }
967
+ // 5. Trace unknown call sites to test files
968
+ for (const unknownSite of analyzed.unknownCalls) {
969
+ const siteFormattedFile = formatPath(repoPath, unknownSite.callerFile);
970
+ if (isTestPath(siteFormattedFile)) {
971
+ unknownReachabilityMap.set(`${siteFormattedFile}:${unknownSite.line}`, {
972
+ file: siteFormattedFile,
973
+ line: unknownSite.line,
974
+ callerSymbol: unknownSite.callerSymbol,
975
+ via: unknownSite.callerSymbol ? [unknownSite.callerSymbol] : [],
976
+ expression: unknownSite.expression,
977
+ uncertaintyReason: unknownSite.uncertaintyReason,
978
+ sourceEvidence: unknownSite.sourceEvidence,
979
+ });
980
+ }
981
+ else if (unknownSite.callerSymbol) {
982
+ const callerTestRefs = db
983
+ .query(`SELECT id, callerSymbol, callerFile, calleeSymbol, calleeFile, line, column, kind, confidence
984
+ FROM "references"
985
+ WHERE calleeSymbol = ?
986
+ AND calleeFile = ?
987
+ AND kind = 'call'
988
+ ORDER BY callerFile, line`)
989
+ .all(unknownSite.callerSymbol, unknownSite.callerFile);
990
+ for (const testRef of callerTestRefs) {
991
+ const testFile = formatPath(repoPath, testRef.callerFile);
992
+ if (!isTestPath(testFile))
993
+ continue;
994
+ const key = `${testFile}:${testRef.line}:${unknownSite.expression}`;
995
+ if (!unknownReachabilityMap.has(key)) {
996
+ unknownReachabilityMap.set(key, {
997
+ file: testFile,
998
+ line: testRef.line,
999
+ callerSymbol: unknownSite.callerSymbol,
1000
+ via: [
1001
+ ...(testRef.callerSymbol ? [testRef.callerSymbol] : []),
1002
+ unknownSite.callerSymbol,
1003
+ ],
1004
+ expression: unknownSite.expression,
1005
+ uncertaintyReason: unknownSite.uncertaintyReason,
1006
+ sourceEvidence: unknownSite.sourceEvidence,
1007
+ });
1008
+ }
1009
+ }
1010
+ }
1011
+ }
1012
+ const exactTests = [...exactTestsMap.values()].sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
1013
+ const possibleTests = [...possibleTestsMap.values()].sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
1014
+ const unknownReachability = [...unknownReachabilityMap.values()].sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
1015
+ return {
1016
+ testSelection: {
1017
+ exactTests,
1018
+ possibleTests,
1019
+ unknownReachability,
1020
+ },
1021
+ uncertaintyReport: analyzed.report,
1022
+ disjointCallers: analyzed.disjointCallers,
1023
+ };
1024
+ }
1025
+ /**
1026
+ * Three-valued ADR 008 test-coverage state for `explain().untested`:
1027
+ * - `false`: at least one proven exact test covers the symbol (or an unambiguous
1028
+ * single-definition test reference exists).
1029
+ * - `undefined`: no exact test exists, but possible-set (interface/callback) or
1030
+ * explicit unknown receiver test reachability exists — never collapse static
1031
+ * possibility or unknown reachability into a confident `true` or `false`.
1032
+ * - `true`: zero exact tests and zero possible-set/unknown test reachability
1033
+ * (including when same-named method calls in tests belong to disjoint classes).
1034
+ */
1035
+ export function evaluateSymbolUntestedState(db, repoPath, symbol, relativeFile, identity = null) {
1036
+ const { testSelection, disjointCallers } = buildUncertaintyAwareTestSelection(db, repoPath, symbol, relativeFile, identity, (_repo, file) => file);
1037
+ if (testSelection.exactTests.length > 0) {
1038
+ return false;
1039
+ }
1040
+ // Check raw anonymous test references (`calleeFile IS NULL`) that were not classified
1041
+ // as disjoint, possible-interface, or untyped-unknown. When the symbol has only one
1042
+ // definition in the repository, preserve existing KNODIN-36 behavior (`untested: false`).
1043
+ const rawTestRefs = db
1044
+ .query(`SELECT callerSymbol, callerFile, line
1045
+ FROM "references"
1046
+ WHERE calleeSymbol = ?
1047
+ AND (calleeFile = ? OR calleeFile IS NULL)`)
1048
+ .all(symbol, relativeFile)
1049
+ .filter((row) => isTestPath(row.callerFile));
1050
+ const definitionCount = db
1051
+ .query("SELECT COUNT(*) AS count FROM symbols WHERE name = ?")
1052
+ .get(symbol)?.count ?? 0;
1053
+ for (const raw of rawTestRefs) {
1054
+ const key = `${raw.callerSymbol ?? ""}|${raw.callerFile}|${raw.line}`;
1055
+ if (disjointCallers.has(key))
1056
+ continue;
1057
+ const isPossible = testSelection.possibleTests.some((p) => p.file === raw.callerFile);
1058
+ const isUnknown = testSelection.unknownReachability.some((u) => u.file === raw.callerFile && u.line === raw.line);
1059
+ if (!isPossible && !isUnknown && definitionCount <= 1) {
1060
+ return false;
1061
+ }
1062
+ }
1063
+ if (testSelection.possibleTests.length > 0 ||
1064
+ testSelection.unknownReachability.some((u) => u.expression.endsWith(`.${symbol}`))) {
1065
+ return undefined;
1066
+ }
1067
+ return true;
1068
+ }