knodin 0.14.1 → 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.
@@ -61,10 +61,13 @@ import { componentBindings, componentCatalog, visualforceInlineScripts, } from "
61
61
  import { readSarifLog, SARIF_DEFAULT_LIMITS, } from "./sarif-import.js";
62
62
  import { readScipIndex, SCIP_DEFAULT_LIMITS, } from "./scip-import.js";
63
63
  import { isSealedDatabase, listSealedFiles, readSealedSource } from "./seal.js";
64
+ import { buildRepositorySemanticDelta, } from "./semantic-graph-delta.js";
65
+ export * from "./retrieval-governance-eval.js";
64
66
  import { isIndexableSourcePath } from "./source-policy.js";
65
67
  import { Database } from "./sqlite.js";
66
68
  import { isMirror, lookupMirror, mayWriteToRepository, resolveDbPath, resolveStateDir, } from "./state-paths.js";
67
69
  import { deleteAllSymbols, deleteSymbolsForFile, deleteSymbolsMatchingPath, ORPHANED_EMBEDDING_PREDICATE, purgeOrphanEmbeddings, } from "./symbol-delete.js";
70
+ import { analyzeSymbolTargetUncertainty, buildUncertaintyAwareTestSelection, evaluateSymbolUntestedState, } from "./target-uncertainty.js";
68
71
  import { searchRepoText } from "./text-matches.js";
69
72
  // ES Module resolution
70
73
  const __filename = fileURLToPath(import.meta.url);
@@ -2914,12 +2917,6 @@ const LINE_COMMENT_NODE_TYPES = new Set(["comment", "line_comment", "hash_commen
2914
2917
  * Shared by `explain`'s `untested`, `tests_for`, and `detectKnowledgeGaps` so the
2915
2918
  * definition of "covered by a test" cannot drift between them.
2916
2919
  */
2917
- function testCallerFilesFor(db, symbol, relativeFile) {
2918
- const statement = db.query('SELECT DISTINCT callerFile FROM "references" WHERE calleeSymbol = ? AND (calleeFile = ? OR calleeFile IS NULL)');
2919
- const rows = statement.all(symbol, relativeFile);
2920
- statement.finalize();
2921
- return rows.map((row) => row.callerFile).filter((file) => isTestFilePath(file));
2922
- }
2923
2920
  /** Clean up and format comment/docstring blocks in JavaScript/TypeScript. */
2924
2921
  function getPrecedingComment(node) {
2925
2922
  let target = node;
@@ -15372,7 +15369,23 @@ export function createEngine(openPolicy = DEFAULT_ENGINE_OPEN_POLICY) {
15372
15369
  };
15373
15370
  })
15374
15371
  : [];
15375
- const allBlastFiles = Array.from(new Set(allCallers.map((c) => c.filePath)));
15372
+ const importerBlastFiles = [];
15373
+ if (targetDb && primaryDef.filePath) {
15374
+ const importerRows = targetDb
15375
+ .query("SELECT DISTINCT fromFile FROM dependencies WHERE toFile = ? ORDER BY fromFile LIMIT 200")
15376
+ .all(primaryDef.filePath);
15377
+ const escapedName = primaryDef.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
15378
+ const tokenPattern = new RegExp(String.raw `\b${escapedName}\b`);
15379
+ for (const { fromFile } of importerRows) {
15380
+ if (fromFile === primaryDef.filePath)
15381
+ continue;
15382
+ const whole = readWholeSource(targetRepoPath, fromFile);
15383
+ if (whole.availability.state === "available" && tokenPattern.test(whole.text)) {
15384
+ importerBlastFiles.push(formatPath(targetRepoPath, fromFile));
15385
+ }
15386
+ }
15387
+ }
15388
+ const allBlastFiles = Array.from(new Set([...allCallers.map((c) => c.filePath), ...importerBlastFiles]));
15376
15389
  // Asked of raw reference rows, not of resolved callers: a test that calls
15377
15390
  // this symbol from inside an anonymous `it(...)` callback has no caller
15378
15391
  // symbol and is invisible to `allCallers` (KNODIN-36). `untested: true`
@@ -15385,7 +15398,7 @@ export function createEngine(openPolicy = DEFAULT_ENGINE_OPEN_POLICY) {
15385
15398
  // `true`. `untested` is now simply absent when the evidence is absent,
15386
15399
  // so a caller reading it gets a fact or nothing, never a guess.
15387
15400
  const untested = targetDb
15388
- ? testCallerFilesFor(targetDb, primaryDef.name, primaryDef.filePath).length === 0
15401
+ ? evaluateSymbolUntestedState(targetDb, targetRepoPath, primaryDef.name, primaryDef.filePath, primaryDef.identity ?? null)
15389
15402
  : undefined;
15390
15403
  const minimal = detailLevel === "minimal";
15391
15404
  const cap = minimal ? 25 : 200;
@@ -15600,6 +15613,9 @@ export function createEngine(openPolicy = DEFAULT_ENGINE_OPEN_POLICY) {
15600
15613
  changedList.length > MINIMAL_CAP ||
15601
15614
  flowsList.length > MINIMAL_CAP ||
15602
15615
  gapsList.length > MINIMAL_CAP);
15616
+ const semanticDelta = !minimal
15617
+ ? buildRepositorySemanticDelta(repoPath, options.from ?? base, options.to, changedFiles, mappedChangedFiles, unmappedChangedFiles, changedList, 0)
15618
+ : undefined;
15603
15619
  return {
15604
15620
  base,
15605
15621
  scope: options.scope ?? "all",
@@ -15634,6 +15650,7 @@ export function createEngine(openPolicy = DEFAULT_ENGINE_OPEN_POLICY) {
15634
15650
  affectedFlowCount: flowsList.length,
15635
15651
  testGaps: minimal ? gapsList.slice(0, MINIMAL_CAP) : gapsList,
15636
15652
  testGapCount: gapsList.length,
15653
+ ...(semanticDelta ? { semanticDelta } : {}),
15637
15654
  ...(truncated ? { truncated: true } : {}),
15638
15655
  };
15639
15656
  },
@@ -17774,6 +17791,17 @@ export function createEngine(openPolicy = DEFAULT_ENGINE_OPEN_POLICY) {
17774
17791
  const expansionWorkLimit = Math.min(200, Math.max(candidateLimit * 4, 20));
17775
17792
  const selected = seeds.slice(0, expansionWorkLimit);
17776
17793
  const seen = new Set(selected.map(({ repo, row }) => `${repo.path}:${row.id}`));
17794
+ const importerLinesCache = new Map();
17795
+ const getImporterLines = (repoPath, relFile) => {
17796
+ const cacheKey = `${repoPath}:${relFile}`;
17797
+ const cached = importerLinesCache.get(cacheKey);
17798
+ if (cached)
17799
+ return cached;
17800
+ const whole = readWholeSource(repoPath, relFile);
17801
+ const lines = whole.availability.state === "available" ? whole.text.split(/\r?\n/) : [];
17802
+ importerLinesCache.set(cacheKey, lines);
17803
+ return lines;
17804
+ };
17777
17805
  let frontier = [...seeds];
17778
17806
  for (let depth = 0; depth < 2 && frontier.length > 0 && selected.length < expansionWorkLimit; depth++) {
17779
17807
  const next = [];
@@ -17806,6 +17834,45 @@ export function createEngine(openPolicy = DEFAULT_ENGINE_OPEN_POLICY) {
17806
17834
  next.push({ repo: current.repo, row });
17807
17835
  }
17808
17836
  }
17837
+ if (seen.size < expansionWorkLimit) {
17838
+ const depImporters = current.repo.db
17839
+ .query("SELECT DISTINCT fromFile FROM dependencies WHERE toFile = ? ORDER BY fromFile LIMIT 200")
17840
+ .all(current.row.filePath);
17841
+ if (depImporters.length > 0) {
17842
+ const escapedName = current.row.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
17843
+ const tokenPattern = new RegExp(String.raw `\b${escapedName}\b`);
17844
+ for (const { fromFile } of depImporters) {
17845
+ if (fromFile === current.row.filePath || seen.size >= expansionWorkLimit)
17846
+ continue;
17847
+ const lines = getImporterLines(current.repo.path, fromFile);
17848
+ if (lines.length === 0 || !lines.some((line) => tokenPattern.test(line)))
17849
+ continue;
17850
+ const fileRows = snapshot.rows.filter((row) => row.filePath === fromFile && accepts(row));
17851
+ let matchedSymbolInFile = false;
17852
+ for (const row of fileRows) {
17853
+ const spanLines = lines.slice(Math.max(0, row.startLine - 1), Math.min(lines.length, row.endLine));
17854
+ if (!spanLines.some((line) => tokenPattern.test(line)))
17855
+ continue;
17856
+ matchedSymbolInFile = true;
17857
+ const key = `${current.repo.path}:${row.id}`;
17858
+ if (seen.has(key))
17859
+ continue;
17860
+ if (seen.size >= expansionWorkLimit)
17861
+ break;
17862
+ seen.add(key);
17863
+ next.push({ repo: current.repo, row });
17864
+ }
17865
+ if (!matchedSymbolInFile && fileRows[0] && seen.size < expansionWorkLimit) {
17866
+ const firstRow = fileRows[0];
17867
+ const key = `${current.repo.path}:${firstRow.id}`;
17868
+ if (!seen.has(key)) {
17869
+ seen.add(key);
17870
+ next.push({ repo: current.repo, row: firstRow });
17871
+ }
17872
+ }
17873
+ }
17874
+ }
17875
+ }
17809
17876
  }
17810
17877
  next.sort((a, b) => a.repo.path.localeCompare(b.repo.path) ||
17811
17878
  a.row.filePath.localeCompare(b.row.filePath) ||
@@ -18708,12 +18775,56 @@ export function createEngine(openPolicy = DEFAULT_ENGINE_OPEN_POLICY) {
18708
18775
  byCaller.set(key, row);
18709
18776
  rows.push(row);
18710
18777
  }
18778
+ const defRepoEntry = allRepos.find((r) => r.path === defRepo) ?? primary;
18779
+ const analyzedUncertainty = analyzeSymbolTargetUncertainty(defRepoEntry.db, defRepoEntry.path, targetName, defFile, selectedTarget?.identity ?? null, pattern === "callers_of" ? "upstream" : "downstream", rows.length);
18780
+ for (const edge of analyzedUncertainty.exactEdges) {
18781
+ const edgeFile = formatPath(defRepoEntry.path, pattern === "callers_of" ? edge.callerFile : edge.calleeFile);
18782
+ const edgeSymbol = pattern === "callers_of" ? edge.callerSymbol : edge.calleeSymbol;
18783
+ const key = `${edgeSymbol}|${edgeFile}|call`;
18784
+ callSiteCount++;
18785
+ const existing = byCaller.get(key);
18786
+ if (existing) {
18787
+ if (edge.line !== undefined && !existing.callSiteLines?.includes(edge.line)) {
18788
+ existing.callSiteLines?.push(edge.line);
18789
+ }
18790
+ continue;
18791
+ }
18792
+ const rr = edge.callerOrigin
18793
+ ? undefined
18794
+ : defRepoEntry.db
18795
+ .query("SELECT * FROM symbols WHERE name = ? AND filePath = ? LIMIT 1")
18796
+ .get(edgeSymbol, pattern === "callers_of" ? edge.callerFile : edge.calleeFile);
18797
+ const row = {
18798
+ symbol: edgeSymbol,
18799
+ ...(edge.callerOrigin
18800
+ ? {
18801
+ callerOrigin: edge.callerOrigin,
18802
+ sourceEvidence: "Resolved call site; no named enclosing caller was extracted. Anonymous nesting is not established.",
18803
+ }
18804
+ : {}),
18805
+ file: edgeFile,
18806
+ line: edge.line,
18807
+ kind: "call",
18808
+ targetUncertainty: "exact",
18809
+ uncertaintyReason: edge.uncertaintyReason,
18810
+ callSiteLines: [edge.line],
18811
+ ...(rr ? { identity: symbolIdentity(defRepoEntry.path, rr) } : {}),
18812
+ };
18813
+ byCaller.set(key, row);
18814
+ rows.push(row);
18815
+ }
18711
18816
  for (const row of rows) {
18817
+ row.targetUncertainty ??= "exact";
18712
18818
  row.callSiteLines?.sort((a, b) => a - b);
18713
18819
  row.bindingSiteLines?.sort((a, b) => a - b);
18714
18820
  row.line = row.callSiteLines?.[0] ?? row.bindingSiteLines?.[0] ?? row.line;
18715
18821
  }
18716
- return finish(rows, { callSiteCount, ...(bindingSiteCount ? { bindingSiteCount } : {}) });
18822
+ analyzedUncertainty.report.exactCount = rows.length;
18823
+ return finish(rows, {
18824
+ callSiteCount,
18825
+ ...(bindingSiteCount ? { bindingSiteCount } : {}),
18826
+ targetUncertainty: analyzedUncertainty.report,
18827
+ });
18717
18828
  }
18718
18829
  case "imports_of": {
18719
18830
  const stmt = db.query("SELECT DISTINCT toFile, kind FROM dependencies WHERE fromFile = ?");
@@ -19011,6 +19122,8 @@ export function createEngine(openPolicy = DEFAULT_ENGINE_OPEN_POLICY) {
19011
19122
  break;
19012
19123
  }
19013
19124
  }
19125
+ const defRepoEntry = allRepos.find((r) => r.path === defRepo) ?? primary;
19126
+ const { testSelection, uncertaintyReport, disjointCallers } = buildUncertaintyAwareTestSelection(defRepoEntry.db, defRepoEntry.path, target, defFile, selectedTarget?.identity ?? null, formatPath);
19014
19127
  const refs = findCallersFederated(allRepos, defRepo, target, 1, new Set(), defFile, selectedTarget?.identity ?? null);
19015
19128
  const seen = new Set();
19016
19129
  const rows = [];
@@ -19022,7 +19135,13 @@ export function createEngine(openPolicy = DEFAULT_ENGINE_OPEN_POLICY) {
19022
19135
  if (seen.has(key))
19023
19136
  continue;
19024
19137
  seen.add(key);
19025
- rows.push({ symbol: r.symbol, file, line: r.lineNumber });
19138
+ rows.push({
19139
+ symbol: r.symbol,
19140
+ file,
19141
+ line: r.lineNumber,
19142
+ targetUncertainty: "exact",
19143
+ uncertaintyReason: "direct-call",
19144
+ });
19026
19145
  }
19027
19146
  // Resolved callers miss almost every real test. A call inside an
19028
19147
  // anonymous `it(...)` callback has no enclosing named symbol, so it
@@ -19067,18 +19186,48 @@ export function createEngine(openPolicy = DEFAULT_ENGINE_OPEN_POLICY) {
19067
19186
  return out;
19068
19187
  })();
19069
19188
  for (const row of anonymous) {
19189
+ if (disjointCallers.has(`|${row.callerFile}|${row.line}`))
19190
+ continue;
19070
19191
  const file = formatPath(repo.path, row.callerFile);
19071
19192
  if (!isTestFilePath(file))
19072
19193
  continue;
19194
+ if (testSelection.possibleTests.some((p) => p.file === file) ||
19195
+ testSelection.unknownReachability.some((u) => u.file === file && u.line === row.line)) {
19196
+ continue;
19197
+ }
19073
19198
  const key = `|${file}`;
19074
19199
  if (seen.has(key))
19075
19200
  continue;
19076
19201
  seen.add(key);
19077
- rows.push({ file, line: row.line });
19202
+ rows.push({
19203
+ file,
19204
+ line: row.line,
19205
+ targetUncertainty: "exact",
19206
+ uncertaintyReason: "direct-call",
19207
+ });
19078
19208
  }
19079
19209
  }
19210
+ for (const entry of [...testSelection.exactTests, ...testSelection.possibleTests]) {
19211
+ if (rows.some((r) => r.file === entry.file))
19212
+ continue;
19213
+ rows.push({
19214
+ ...(entry.symbol ? { symbol: entry.symbol } : {}),
19215
+ file: entry.file,
19216
+ line: entry.line,
19217
+ targetUncertainty: entry.targetUncertainty,
19218
+ uncertaintyReason: entry.uncertaintyReason,
19219
+ ...(entry.viaInterface ? { viaInterface: entry.viaInterface } : {}),
19220
+ ...(entry.viaParameter ? { viaParameter: entry.viaParameter } : {}),
19221
+ ...(entry.candidateTargets ? { candidateTargets: entry.candidateTargets } : {}),
19222
+ ...(entry.heuristic ? { heuristic: true } : {}),
19223
+ ...(entry.sourceEvidence ? { sourceEvidence: entry.sourceEvidence } : {}),
19224
+ });
19225
+ }
19080
19226
  rows.sort((a, b) => (a.file ?? "").localeCompare(b.file ?? "") || (a.line ?? 0) - (b.line ?? 0));
19081
- return finish(rows);
19227
+ return finish(rows, {
19228
+ testSelection,
19229
+ targetUncertainty: uncertaintyReport,
19230
+ });
19082
19231
  }
19083
19232
  case "rename_preview": {
19084
19233
  // Read-only rename plan: every site that renaming `target` -> `to`
@@ -19455,11 +19604,15 @@ export function createEngine(openPolicy = DEFAULT_ENGINE_OPEN_POLICY) {
19455
19604
  name: selectedTarget.name,
19456
19605
  file: selectedTarget.filePath,
19457
19606
  depth: 0,
19607
+ uncertainty: "exact",
19458
19608
  },
19459
19609
  ];
19460
19610
  const visited = new Set();
19461
19611
  const emitted = new Set([`${selectedTarget.name}|${selectedTarget.filePath}`]);
19462
19612
  const rows = [];
19613
+ const rootUncertainty = analyzeSymbolTargetUncertainty(db, primary.path, selectedTarget.name, selectedTarget.filePath, selectedTarget.identity ?? null, direction === "downstream" ? "downstream" : "upstream");
19614
+ const collectedUnknownCalls = [...rootUncertainty.unknownCalls];
19615
+ const collectedPossibleEdges = [...rootUncertainty.possibleEdges];
19463
19616
  while (queue.length > 0) {
19464
19617
  const current = queue.shift();
19465
19618
  if (!current)
@@ -19475,7 +19628,61 @@ export function createEngine(openPolicy = DEFAULT_ENGINE_OPEN_POLICY) {
19475
19628
  refs.push(...inbound.map((ref) => ({
19476
19629
  ...ref,
19477
19630
  traversal: "upstream",
19631
+ uncertainty: "exact",
19632
+ uncertaintyReason: "direct-call",
19478
19633
  })));
19634
+ const stepUncertainty = analyzeSymbolTargetUncertainty(db, primary.path, current.name, current.file, null, "upstream");
19635
+ for (const edge of stepUncertainty.exactEdges) {
19636
+ if (edge.callerOrigin)
19637
+ continue;
19638
+ refs.push({
19639
+ id: 0,
19640
+ callerSymbol: edge.callerSymbol,
19641
+ callerFile: edge.callerFile,
19642
+ calleeSymbol: edge.calleeSymbol,
19643
+ calleeFile: edge.calleeFile,
19644
+ line: edge.line,
19645
+ column: 1,
19646
+ kind: "call",
19647
+ confidence: edge.confidence,
19648
+ traversal: "upstream",
19649
+ uncertainty: "exact",
19650
+ uncertaintyReason: edge.uncertaintyReason,
19651
+ explicitSourceEvidence: edge.sourceEvidence,
19652
+ });
19653
+ }
19654
+ for (const edge of stepUncertainty.possibleEdges) {
19655
+ if (edge.callerOrigin)
19656
+ continue;
19657
+ refs.push({
19658
+ id: 0,
19659
+ callerSymbol: edge.callerSymbol,
19660
+ callerFile: edge.callerFile,
19661
+ calleeSymbol: edge.calleeSymbol,
19662
+ calleeFile: edge.calleeFile,
19663
+ line: edge.line,
19664
+ column: 1,
19665
+ kind: "call",
19666
+ confidence: edge.confidence,
19667
+ traversal: "upstream",
19668
+ uncertainty: "possible-set",
19669
+ uncertaintyReason: edge.uncertaintyReason,
19670
+ viaInterface: edge.viaInterface,
19671
+ viaParameter: edge.viaParameter,
19672
+ candidateTargets: edge.candidateTargets,
19673
+ explicitSourceEvidence: edge.sourceEvidence,
19674
+ });
19675
+ if (!collectedPossibleEdges.some((p) => p.callerSymbol === edge.callerSymbol &&
19676
+ p.callerFile === edge.callerFile &&
19677
+ p.line === edge.line)) {
19678
+ collectedPossibleEdges.push(edge);
19679
+ }
19680
+ }
19681
+ for (const u of stepUncertainty.unknownCalls) {
19682
+ if (!collectedUnknownCalls.some((existing) => existing.callerFile === u.callerFile && existing.line === u.line)) {
19683
+ collectedUnknownCalls.push(u);
19684
+ }
19685
+ }
19479
19686
  }
19480
19687
  if (current.traversal === "downstream" ||
19481
19688
  (!current.traversal && direction !== "upstream")) {
@@ -19485,25 +19692,93 @@ export function createEngine(openPolicy = DEFAULT_ENGINE_OPEN_POLICY) {
19485
19692
  refs.push(...outbound.map((ref) => ({
19486
19693
  ...ref,
19487
19694
  traversal: "downstream",
19695
+ uncertainty: "exact",
19696
+ uncertaintyReason: "direct-call",
19488
19697
  })));
19698
+ const stepDownstream = analyzeSymbolTargetUncertainty(db, primary.path, current.name, current.file, null, "downstream");
19699
+ for (const edge of stepDownstream.exactEdges) {
19700
+ refs.push({
19701
+ id: 0,
19702
+ callerSymbol: edge.callerSymbol,
19703
+ callerFile: edge.callerFile,
19704
+ calleeSymbol: edge.calleeSymbol,
19705
+ calleeFile: edge.calleeFile,
19706
+ line: edge.line,
19707
+ column: 1,
19708
+ kind: "call",
19709
+ confidence: edge.confidence,
19710
+ traversal: "downstream",
19711
+ uncertainty: "exact",
19712
+ uncertaintyReason: edge.uncertaintyReason,
19713
+ explicitSourceEvidence: edge.sourceEvidence,
19714
+ });
19715
+ }
19716
+ for (const edge of stepDownstream.possibleEdges) {
19717
+ refs.push({
19718
+ id: 0,
19719
+ callerSymbol: edge.callerSymbol,
19720
+ callerFile: edge.callerFile,
19721
+ calleeSymbol: edge.calleeSymbol,
19722
+ calleeFile: edge.calleeFile,
19723
+ line: edge.line,
19724
+ column: 1,
19725
+ kind: "call",
19726
+ confidence: edge.confidence,
19727
+ traversal: "downstream",
19728
+ uncertainty: "possible-set",
19729
+ uncertaintyReason: edge.uncertaintyReason,
19730
+ viaInterface: edge.viaInterface,
19731
+ viaParameter: edge.viaParameter,
19732
+ candidateTargets: edge.candidateTargets,
19733
+ explicitSourceEvidence: edge.sourceEvidence,
19734
+ });
19735
+ if (!collectedPossibleEdges.some((p) => p.callerSymbol === edge.callerSymbol &&
19736
+ p.callerFile === edge.callerFile &&
19737
+ p.line === edge.line &&
19738
+ p.calleeFile === edge.calleeFile)) {
19739
+ collectedPossibleEdges.push(edge);
19740
+ }
19741
+ }
19742
+ for (const u of stepDownstream.unknownCalls) {
19743
+ if (!collectedUnknownCalls.some((existing) => existing.callerFile === u.callerFile && existing.line === u.line)) {
19744
+ collectedUnknownCalls.push(u);
19745
+ }
19746
+ }
19489
19747
  }
19490
19748
  for (const ref of refs) {
19491
19749
  const next = ref.traversal === "upstream"
19492
19750
  ? { name: ref.callerSymbol ?? "", file: ref.callerFile }
19493
19751
  : { name: ref.calleeSymbol, file: ref.calleeFile ?? "" };
19494
- const confidence = edgeConfidence(ref);
19752
+ const stepConfidence = ref.uncertainty === "possible-set" ? (ref.confidence ?? 0.5) : edgeConfidence(ref);
19753
+ const propagatedUncertainty = current.uncertainty === "possible-set" || ref.uncertainty === "possible-set"
19754
+ ? "possible-set"
19755
+ : "exact";
19756
+ const confidence = propagatedUncertainty === "possible-set"
19757
+ ? Math.min(stepConfidence, 0.5)
19758
+ : stepConfidence;
19495
19759
  if (!next.name || !next.file || !allowed(ref.kind, confidence, next.file))
19496
19760
  continue;
19497
19761
  const key = `${next.name}|${next.file}`;
19498
- const traversalKey = `${ref.traversal}|${key}`;
19762
+ const traversalKey = `${ref.traversal}|${key}|${propagatedUncertainty}`;
19499
19763
  if (visited.has(traversalKey))
19500
19764
  continue;
19501
19765
  visited.add(traversalKey);
19502
19766
  const nextDepth = current.depth + 1;
19767
+ const propagatedReason = ref.uncertainty === "possible-set"
19768
+ ? ref.uncertaintyReason
19769
+ : (current.uncertaintyReason ?? ref.uncertaintyReason);
19770
+ const propagatedInterface = ref.viaInterface ?? current.viaInterface;
19771
+ const propagatedParameter = ref.viaParameter ?? current.viaParameter;
19772
+ const propagatedCandidates = ref.candidateTargets ?? current.candidateTargets;
19503
19773
  queue.push({
19504
19774
  ...next,
19505
19775
  depth: nextDepth,
19506
19776
  traversal: ref.traversal,
19777
+ uncertainty: propagatedUncertainty,
19778
+ uncertaintyReason: propagatedReason,
19779
+ viaInterface: propagatedInterface,
19780
+ viaParameter: propagatedParameter,
19781
+ candidateTargets: propagatedCandidates,
19507
19782
  });
19508
19783
  if (emitted.has(key))
19509
19784
  continue;
@@ -19515,6 +19790,15 @@ export function createEngine(openPolicy = DEFAULT_ENGINE_OPEN_POLICY) {
19515
19790
  depth: nextDepth,
19516
19791
  line: ref.line,
19517
19792
  kind: ref.kind,
19793
+ targetUncertainty: propagatedUncertainty,
19794
+ ...(propagatedReason ? { uncertaintyReason: propagatedReason } : {}),
19795
+ ...(propagatedInterface ? { viaInterface: propagatedInterface } : {}),
19796
+ ...(propagatedParameter ? { viaParameter: propagatedParameter } : {}),
19797
+ ...(propagatedCandidates ? { candidateTargets: propagatedCandidates } : {}),
19798
+ ...(propagatedUncertainty === "possible-set" ? { heuristic: true } : {}),
19799
+ ...(ref.explicitSourceEvidence
19800
+ ? { sourceEvidence: ref.explicitSourceEvidence }
19801
+ : {}),
19518
19802
  impactEdge: {
19519
19803
  from: ref.callerSymbol ?? ref.callerFile,
19520
19804
  fromFile: ref.callerFile,
@@ -19523,12 +19807,39 @@ export function createEngine(openPolicy = DEFAULT_ENGINE_OPEN_POLICY) {
19523
19807
  kind: ref.kind,
19524
19808
  confidence,
19525
19809
  line: ref.line,
19810
+ ...(ref.explicitSourceEvidence
19811
+ ? { sourceEvidence: ref.explicitSourceEvidence }
19812
+ : {}),
19526
19813
  ...(evidence ? { dataFlow: evidence } : {}),
19527
19814
  },
19528
19815
  });
19529
19816
  }
19530
19817
  }
19531
- return decorate(rows, direction);
19818
+ const decorated = await decorate(rows, direction);
19819
+ const exactRowCount = rows.filter((r) => r.targetUncertainty === "exact").length;
19820
+ const possibleRowCount = rows.filter((r) => r.targetUncertainty === "possible-set").length;
19821
+ rootUncertainty.report.exactCount = exactRowCount;
19822
+ rootUncertainty.report.possibleCount = Math.max(possibleRowCount, collectedPossibleEdges.length);
19823
+ rootUncertainty.report.unknownCount = collectedUnknownCalls.length;
19824
+ rootUncertainty.report.possibleSet = collectedPossibleEdges;
19825
+ rootUncertainty.report.unknownCalls = collectedUnknownCalls;
19826
+ decorated.targetUncertainty = rootUncertainty.report;
19827
+ if (collectedUnknownCalls.length > 0 && decorated.impact) {
19828
+ decorated.impact.traversal = {
19829
+ maxFiles: 256,
19830
+ maxEdges: 4096,
19831
+ maxSeeds: 1,
19832
+ visitedFiles: new Set(rows.map((r) => r.file ?? "")).size + 1,
19833
+ examinedEdges: rows.length + collectedUnknownCalls.length,
19834
+ truncated: false,
19835
+ reasons: ["dynamic-unknown-dispatch"],
19836
+ omissions: [
19837
+ "Dynamic or untyped call targets cannot be resolved statically and are reported in targetUncertainty.unknownCalls.",
19838
+ ],
19839
+ countIsLowerBound: true,
19840
+ };
19841
+ }
19842
+ return decorated;
19532
19843
  }
19533
19844
  case "file_summary": {
19534
19845
  return cacheStructuralQuery(`${primary.path}\0${pattern}\0${target}\0${cap}`, () => finish(queryFileSymbols(db, target, primary.path)));
@@ -57,33 +57,89 @@ export function resolveParsePoolSize(inputs) {
57
57
  // workers fed.
58
58
  const cpuBound = Math.max(1, Math.floor(inputs.cpuCount) - 1);
59
59
  const usableMemory = Math.max(0, inputs.totalMemoryBytes) * MEMORY_HEADROOM_FRACTION;
60
- const memoryBound = Math.floor(usableMemory / PER_WORKER_MEMORY_ESTIMATE_BYTES);
60
+ const hostMemoryBound = Math.floor(usableMemory / PER_WORKER_MEMORY_ESTIMATE_BYTES);
61
+ const envBudgetMb = positiveIntegerEnv(env.KNODIN_PARSE_POOL_MEMORY_BUDGET_MB);
62
+ const explicitBudgetBytes = inputs.memoryBudgetBytes !== undefined
63
+ ? Math.max(0, inputs.memoryBudgetBytes)
64
+ : envBudgetMb !== null
65
+ ? envBudgetMb * 1024 * 1024
66
+ : null;
67
+ const parentHeadroomBytes = Math.max(0, inputs.parentHeadroomBytes ?? 0);
68
+ const explicitMemoryBudgetBound = explicitBudgetBytes !== null
69
+ ? Math.floor(Math.max(0, explicitBudgetBytes - parentHeadroomBytes) / PER_WORKER_MEMORY_ESTIMATE_BYTES)
70
+ : null;
71
+ const memoryBound = explicitMemoryBudgetBound !== null
72
+ ? Math.min(hostMemoryBound, explicitMemoryBudgetBound)
73
+ : hostMemoryBound;
61
74
  if (env.KNODIN_DISABLE_PARSE_WORKERS === "1")
62
- return { workers: 0, reason: "disabled-by-env", cpuBound, memoryBound };
75
+ return {
76
+ workers: 0,
77
+ reason: "disabled-by-env",
78
+ cpuBound,
79
+ memoryBound,
80
+ ...(explicitMemoryBudgetBound !== null ? { explicitMemoryBudgetBound } : {}),
81
+ };
63
82
  const override = positiveIntegerEnv(env.KNODIN_PARSE_POOL_MAX_WORKERS);
64
- if (override !== null)
83
+ if (override !== null) {
84
+ const clampedOverride = explicitMemoryBudgetBound !== null
85
+ ? Math.min(override, PARSE_POOL_HARD_CAP, explicitMemoryBudgetBound)
86
+ : Math.min(override, PARSE_POOL_HARD_CAP);
65
87
  return {
66
- workers: Math.min(override, PARSE_POOL_HARD_CAP),
67
- reason: "explicit-override",
88
+ workers: clampedOverride,
89
+ reason: explicitMemoryBudgetBound !== null && explicitMemoryBudgetBound < override
90
+ ? "memory-bound"
91
+ : "explicit-override",
68
92
  cpuBound,
69
93
  memoryBound,
94
+ ...(explicitMemoryBudgetBound !== null ? { explicitMemoryBudgetBound } : {}),
70
95
  };
96
+ }
71
97
  // A single-core host has no core to spare once the writer is accounted for,
72
98
  // so the pool would be one worker handing results to an idle main thread --
73
99
  // strictly worse than doing the work inline. Report it distinctly from a
74
100
  // memory refusal: the remedies are completely different.
75
101
  if (cpuBound < 2)
76
- return { workers: 0, reason: "single-core", cpuBound, memoryBound };
102
+ return {
103
+ workers: 0,
104
+ reason: "single-core",
105
+ cpuBound,
106
+ memoryBound,
107
+ ...(explicitMemoryBudgetBound !== null ? { explicitMemoryBudgetBound } : {}),
108
+ };
77
109
  // Too little memory for even one worker's fixed overhead. Sequential
78
110
  // is not a degraded outcome here, it is the correct one.
79
111
  if (memoryBound < 1)
80
- return { workers: 0, reason: "memory-bound", cpuBound, memoryBound };
112
+ return {
113
+ workers: 0,
114
+ reason: "memory-bound",
115
+ cpuBound,
116
+ memoryBound,
117
+ ...(explicitMemoryBudgetBound !== null ? { explicitMemoryBudgetBound } : {}),
118
+ };
81
119
  const workers = Math.min(cpuBound, memoryBound, PARSE_POOL_HARD_CAP);
82
120
  return {
83
121
  workers,
84
122
  reason: memoryBound < cpuBound ? "memory-bound" : "cpu-bound",
85
123
  cpuBound,
86
124
  memoryBound,
125
+ ...(explicitMemoryBudgetBound !== null ? { explicitMemoryBudgetBound } : {}),
126
+ };
127
+ }
128
+ export function evaluateDirectIndexMemoryEnvelope(input) {
129
+ const withinBudget = input.observedProcessFamilyPeakBytes <= input.memoryBudgetBytes &&
130
+ input.omittedFiles.length === 0;
131
+ const status = withinBudget ? "completed" : "budget-exceeded";
132
+ return {
133
+ status,
134
+ withinBudget,
135
+ memoryBudgetBytes: input.memoryBudgetBytes,
136
+ observedProcessFamilyPeakBytes: input.observedProcessFamilyPeakBytes,
137
+ estimatedGraphAndWorkerBytes: input.parentHeapEstimateBytes + input.workerCount * PER_WORKER_MEMORY_ESTIMATE_BYTES,
138
+ completedFiles: [...input.completedFiles],
139
+ omittedFiles: [...input.omittedFiles],
140
+ cleanupStatus: input.cleanupCompleted ? "verified" : "incomplete",
141
+ graphRecoveryVerified: input.graphRecoveryVerified,
142
+ advertisesCompleteIndexing: status === "completed" && input.cleanupCompleted && input.graphRecoveryVerified,
87
143
  };
88
144
  }
89
145
  /** Sample the live machine. Separated from the policy so the policy stays testable. */