Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

feat(ingest): no edge without both endpoints; unresolved calls named on their caller; extractor 1.28 (#761)

Ian Hock762ebb955fc1
diff --git a/core-ingestion/src/__tests__/helpers/untiered.ts b/core-ingestion/src/__tests__/helpers/untiered.ts
new file mode 100644
index 00000000..458af004
--- /dev/null
+++ b/core-ingestion/src/__tests__/helpers/untiered.ts
@@ -0,0 +1,11 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { resolveEdges as resolveEdgesWithTier } from '../../index.js';
+
+/**
+ * `resolveEdges` without the `tier` field. The tests that use it predate
+ * tiers and assert edges by whole shape; `resolveEdges.tier.test.ts` covers
+ * which tier each resolution path reports.
+ */
+export const resolveEdges = (...args: Parameters<typeof resolveEdgesWithTier>) =>
+ resolveEdgesWithTier(...args).map(({ tier: _tier, ...edge }) => edge);
diff --git a/core-ingestion/src/__tests__/parseFile.test.ts b/core-ingestion/src/__tests__/parseFile.test.ts
index 3a2cbca0..022936bc 100644
--- a/core-ingestion/src/__tests__/parseFile.test.ts
+++ b/core-ingestion/src/__tests__/parseFile.test.ts
@@ -5,7 +5,8 @@ import path from 'node:path';
import { describe, expect, it } from 'vitest';
-import { parseFile, resolveEdges } from '../index.js';
+import { parseFile } from '../index.js';
+import { resolveEdges } from './helpers/untiered.js';
const repoRoot = path.resolve(import.meta.dirname, '../../..');
diff --git a/core-ingestion/src/__tests__/patchBuilder.endpoints.test.ts b/core-ingestion/src/__tests__/patchBuilder.endpoints.test.ts
new file mode 100644
index 00000000..8bba2771
--- /dev/null
+++ b/core-ingestion/src/__tests__/patchBuilder.endpoints.test.ts
@@ -0,0 +1,120 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import path from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+import { parseFile, resolveEdges, type FileParseResult, type ResolvedEdge } from '../index.js';
+import { buildPatchWithResolution, UNRESOLVED_CALLS_CAP } from '../patch-builder.js';
+
+/**
+ * No edge without both endpoints: every `UpsertEdge` in a repository's patch
+ * set must point from and to a node some patch in that set upserts. Before,
+ * calls to builtins, library functions and names that resolved nowhere were
+ * written as edges to ids no patch ever created -- over half the edges in a
+ * typical graph.
+ */
+
+const repoRoot = path.resolve(import.meta.dirname, '../../..');
+
+function sourceFiles(dir: string, out: string[] = []): string[] {
+ for (const name of readdirSync(dir).sort()) {
+ const full = path.join(dir, name);
+ if (statSync(full).isDirectory()) {
+ if (name !== '__tests__' && name !== 'node_modules' && name !== 'dist') sourceFiles(full, out);
+ } else if (/\.(ts|py|java|scala)$/.test(name) && !name.endsWith('.d.ts')) {
+ out.push(full);
+ }
+ }
+ return out;
+}
+
+function parseCorpus(): FileParseResult[] {
+ const files = [
+ ...sourceFiles(path.join(repoRoot, 'core-ingestion/src')),
+ ...sourceFiles(path.join(repoRoot, 'core-ingestion/test-fixtures')),
+ ];
+ return files
+ .map((abs) => parseFile(path.relative(repoRoot, abs), readFileSync(abs, 'utf8'), { budgetMs: 0 }))
+ .filter((r): r is FileParseResult => r !== null);
+}
+
+describe('every edge has a node at both ends', () => {
+ const results = parseCorpus();
+ const resolved = resolveEdges(results);
+ const byFile = new Map<string, ResolvedEdge[]>();
+ for (const edge of resolved) {
+ const list = byFile.get(edge.srcFilePath) ?? [];
+ list.push(edge);
+ byFile.set(edge.srcFilePath, list);
+ }
+ const patches = results.map((r) => buildPatchWithResolution(r, 'hash', 'ws', byFile.get(r.filePath) ?? []));
+ const nodes = new Set(patches.flatMap((p) => p.ops.filter((op) => op.type === 'UpsertNode').map((op) => op.id as string)));
+ const edges = patches.flatMap((p) => p.ops.filter((op) => op.type === 'UpsertEdge')) as Array<{
+ id: string; src: string; dst: string; predicate: string; attrs: Record<string, unknown>;
+ }>;
+
+ it('holds over this package and its fixtures', () => {
+ expect(results.length).toBeGreaterThan(10);
+ expect(edges.length).toBeGreaterThan(100);
+ const dangling = edges.filter((e) => !nodes.has(e.src) || !nodes.has(e.dst));
+ expect(dangling.map((e) => `${e.predicate} ${e.id}`)).toEqual([]);
+ });
+
+ it('writes confidence and tier on every cross-file edge', () => {
+ const crossFile = edges.filter((e) => e.attrs.confidence !== undefined);
+ expect(crossFile.length).toBeGreaterThan(10);
+ for (const e of crossFile) {
+ expect(['binding', 'import', 'transitive', 'qualifier', 'global']).toContain(e.attrs.tier);
+ }
+ });
+
+ it('records the calls it could not place on the node that makes them', () => {
+ const upserts = patches.flatMap((p) => p.ops.filter((op) => op.type === 'UpsertNode')) as Array<{
+ kind: string; attrs: Record<string, unknown>;
+ }>;
+ const recording = upserts.filter((n) => n.attrs.unresolved_call_count !== undefined);
+ // This package calls plenty of builtins (`.map`, `push`, `Math.max`...),
+ // and mostly from inside functions.
+ expect(recording.filter((n) => n.kind === 'function' || n.kind === 'method').length).toBeGreaterThan(10);
+ for (const n of recording) {
+ const names = n.attrs.unresolved_calls as string[];
+ expect(names.length).toBe(Math.min(n.attrs.unresolved_call_count as number, UNRESOLVED_CALLS_CAP));
+ expect(new Set(names).size).toBe(names.length);
+ }
+ // No node is ever handed both a count and nothing to show for it.
+ expect(upserts.filter((n) => n.attrs.unresolved_calls !== undefined && n.attrs.unresolved_call_count === undefined)).toEqual([]);
+ });
+});
+
+describe('resolveEdges reports the tier that resolved each edge', () => {
+ const parse = (file: string, source: string) => parseFile(file, source)!;
+ const edgesFor = (files: Array<[string, string]>) => resolveEdges(files.map(([f, s]) => parse(f, s)));
+ const find = (edges: ResolvedEdge[], predicate: string, dstName: string) =>
+ edges.find((e) => e.predicate === predicate && e.dstName === dstName);
+
+ it('import: an IMPORTS edge to the imported file', () => {
+ const edges = edgesFor([
+ ['/repo/a.ts', 'export function helper() { return 1; }\n'],
+ ['/repo/b.ts', "import { helper } from './a';\nexport function run() { return helper(); }\n"],
+ ]);
+ expect(edges.find((e) => e.predicate === 'IMPORTS' && e.dstFilePath === '/repo/a.ts')?.tier).toBe('import');
+ });
+
+ it('binding: a call through a named import binding', () => {
+ const edges = edgesFor([
+ ['/repo/a.ts', 'export function helper() { return 1; }\n'],
+ ['/repo/b.ts', "import { helper } from './a';\nexport function run() { return helper(); }\n"],
+ ]);
+ expect(find(edges, 'CALLS', 'helper')).toMatchObject({ tier: 'binding', confidence: 0.9 });
+ });
+
+ it('global: the only definition of a name, in a file not imported', () => {
+ const edges = edgesFor([
+ ['/repo/lonely.py', 'def lonely_fn():\n return 1\n'],
+ ['/repo/caller.py', 'def go():\n return lonely_fn()\n'],
+ ]);
+ expect(find(edges, 'CALLS', 'lonely_fn')).toMatchObject({ tier: 'global', confidence: 0.5 });
+ });
+});
diff --git a/core-ingestion/src/__tests__/patchBuilder.resolution.test.ts b/core-ingestion/src/__tests__/patchBuilder.resolution.test.ts
index cbb3838c..f0f131ab 100644
--- a/core-ingestion/src/__tests__/patchBuilder.resolution.test.ts
+++ b/core-ingestion/src/__tests__/patchBuilder.resolution.test.ts
@@ -143,7 +143,7 @@ function run(): void { new Helper(); Helper(); }
const result = fileResult(
file,
SupportedLanguages.R,
- [entity('fitModel', SupportedLanguages.R)],
+ [entity('fitModel', SupportedLanguages.R), entity('localHelper', SupportedLanguages.R)],
[
{ srcName: 'fitModel', dstName: 'dplyr::filter', predicate: 'CALLS' },
{ srcName: 'fitModel', dstName: 'localHelper', predicate: 'CALLS' },
@@ -205,9 +205,13 @@ function run(): void { new Helper(); Helper(); }
);
const rPatch = buildPatchWithResolution(rResult, 'hash', '', []);
expect(rPatch.ops.filter(op => op.type === 'UpsertNode' && String((op as any).id).startsWith('external://'))).toEqual([]);
- expect(rPatch.ops).toContainEqual(
- expect.objectContaining({ type: 'UpsertEdge', predicate: 'CALLS', dst: nodeId(rFile, 'is.null') }),
- );
+ // Not externalised -- and with no node to point at, not written at all.
+ // The caller records the name instead.
+ expect(rPatch.ops).not.toContainEqual(expect.objectContaining({ type: 'UpsertEdge', predicate: 'CALLS' }));
+ expect(rPatch.ops).toContainEqual(expect.objectContaining({
+ type: 'UpsertNode', name: 'validate',
+ attrs: expect.objectContaining({ unresolved_calls: ['is.null'], unresolved_call_count: 1 }),
+ }));
const goFile = '/repo/main.go';
const goResult = fileResult(
@@ -218,9 +222,7 @@ function run(): void { new Helper(); Helper(); }
);
const goPatch = buildPatchWithResolution(goResult, 'hash', '', []);
expect(goPatch.ops.filter(op => op.type === 'UpsertNode' && String((op as any).id).startsWith('external://'))).toEqual([]);
- expect(goPatch.ops).toContainEqual(
- expect.objectContaining({ type: 'UpsertEdge', predicate: 'CALLS', dst: nodeId(goFile, 'fmt.Println') }),
- );
+ expect(goPatch.ops).not.toContainEqual(expect.objectContaining({ type: 'UpsertEdge', predicate: 'CALLS' }));
});
it('keeps resolved qualified CALLS that cross-file resolution found', () => {
@@ -281,6 +283,7 @@ struct Trajectory {};
dstQualifiedKey: 'GraphUtils.h',
predicate: 'IMPORTS',
confidence: 0.9,
+ tier: 'import',
});
const patch = buildPatchWithResolution(importer!, 'test-hash', '', resolvedEdges);
@@ -302,7 +305,7 @@ describe('buildPatch', () => {
const result = fileResult(
file,
SupportedLanguages.R,
- [entity('fitModel', SupportedLanguages.R)],
+ [entity('fitModel', SupportedLanguages.R), entity('localHelper', SupportedLanguages.R)],
[
{ srcName: 'fitModel', dstName: 'dplyr::filter', predicate: 'CALLS' },
{ srcName: 'fitModel', dstName: 'localHelper', predicate: 'CALLS' },
@@ -489,7 +492,8 @@ describe('colliding edge ids (#554)', () => {
const result = fileResult(
sourceFile,
SupportedLanguages.TypeScript,
- [entity('run', SupportedLanguages.TypeScript, 'function', 'A')],
+ // A local `helper` too: an edge is only written to a node that exists.
+ [entity('run', SupportedLanguages.TypeScript, 'function', 'A'), entity('helper', SupportedLanguages.TypeScript)],
[
{ srcName: 'run', dstName: 'helper', predicate: 'CALLS' },
{ srcName: 'A.run', dstName: 'helper', predicate: 'CALLS' },
@@ -543,7 +547,7 @@ describe('colliding edge ids (#554)', () => {
const result = fileResult(
'/repo/plain.ts',
SupportedLanguages.TypeScript,
- [entity('alpha', SupportedLanguages.TypeScript)],
+ [entity('alpha', SupportedLanguages.TypeScript), entity('beta', SupportedLanguages.TypeScript)],
[{ srcName: 'alpha', dstName: 'beta', predicate: 'CALLS' }],
);
const edge: any = buildPatchWithResolution(result, 'test-hash', '', []).ops
diff --git a/core-ingestion/src/__tests__/patchBuilder.unresolvedCalls.test.ts b/core-ingestion/src/__tests__/patchBuilder.unresolvedCalls.test.ts
new file mode 100644
index 00000000..748bc386
--- /dev/null
+++ b/core-ingestion/src/__tests__/patchBuilder.unresolvedCalls.test.ts
@@ -0,0 +1,113 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { describe, expect, it } from 'vitest';
+
+import { parseFile, resolveEdges } from '../index.js';
+import { buildPatch, buildPatchWithResolution, UNRESOLVED_CALLS_CAP } from '../patch-builder.js';
+
+/**
+ * A call that resolves to no node writes no edge, so the names on its caller
+ * are the only record `ix explain` has of it. These pin which node gets them,
+ * the cap, and the count that makes a cut list visible.
+ */
+
+type Node = { type: string; kind?: string; name?: string; attrs?: Record<string, unknown> };
+
+function nodesOf(ops: unknown[]): Node[] {
+ return (ops as Node[]).filter((op) => op.type === 'UpsertNode');
+}
+
+function byName(ops: unknown[], name: string, kind?: string): Node {
+ const node = nodesOf(ops).find((n) => n.name === name && (kind === undefined || n.kind === kind));
+ if (!node) throw new Error(`no node ${name}`);
+ return node;
+}
+
+const SOURCE = `
+import { helper } from './helper';
+
+export function first(): number {
+ return helper() + Math.max(1, 2);
+}
+
+export function second(xs: number[]): number[] {
+ return xs.map((x) => x + 1).filter(Boolean);
+}
+
+export function quiet(): number {
+ return first();
+}
+
+setupGlobalThing();
+`;
+
+const HELPER = 'export function helper(): number { return 1; }\n';
+
+describe('unresolved callee names', () => {
+ const main = parseFile('/repo/main.ts', SOURCE)!;
+ const helper = parseFile('/repo/helper.ts', HELPER)!;
+ const resolved = resolveEdges([main, helper]).filter((e) => e.srcFilePath === '/repo/main.ts');
+ const ops = buildPatchWithResolution(main, 'hash', 'ws', resolved).ops;
+
+ it('go on the function that makes the calls, not on its neighbours', () => {
+ // The parser records a member call by its member name.
+ expect(byName(ops, 'first', 'function').attrs).toMatchObject({
+ unresolved_calls: ['max'],
+ unresolved_call_count: 1,
+ });
+ expect(byName(ops, 'second', 'function').attrs).toMatchObject({
+ unresolved_calls: ['map', 'filter'],
+ unresolved_call_count: 2,
+ });
+ });
+
+ it('leave a function whose calls all resolved without the attrs', () => {
+ const quiet = byName(ops, 'quiet', 'function').attrs!;
+ expect(quiet).not.toHaveProperty('unresolved_calls');
+ expect(quiet).not.toHaveProperty('unresolved_call_count');
+ });
+
+ it('keep the resolved calls as edges', () => {
+ const calls = (ops as Array<{ type: string; predicate?: string }>).filter(
+ (op) => op.type === 'UpsertEdge' && op.predicate === 'CALLS');
+ // first -> helper (cross-file) and quiet -> first (same file).
+ expect(calls).toHaveLength(2);
+ expect(byName(ops, 'first', 'function').attrs!.unresolved_calls).not.toContain('helper');
+ });
+
+ it('put module-level calls on the file node', () => {
+ expect(byName(ops, 'main.ts', 'file').attrs).toMatchObject({
+ unresolved_calls: ['setupGlobalThing'],
+ unresolved_call_count: 1,
+ });
+ });
+
+ it('are recorded the same way without cross-file resolution', () => {
+ const plain = buildPatch(main, 'hash', 'ws').ops;
+ expect(byName(plain, 'second', 'function').attrs).toMatchObject({
+ unresolved_calls: ['map', 'filter'],
+ unresolved_call_count: 2,
+ });
+ expect(byName(plain, 'main.ts', 'file').attrs).toMatchObject({ unresolved_calls: ['setupGlobalThing'] });
+ });
+});
+
+describe('the cap', () => {
+ const calls = Array.from({ length: UNRESOLVED_CALLS_CAP + 7 }, (_, i) => `ext${String(i).padStart(2, '0')}();`);
+ // Every name twice: the count is of distinct names, not call sites.
+ const source = `export function busy(): void {\n ${[...calls, ...calls].join('\n ')}\n}\n`;
+ const result = parseFile('/repo/busy.ts', source)!;
+
+ it.each([
+ ['buildPatchWithResolution', () => buildPatchWithResolution(result, 'hash', 'ws', []).ops],
+ ['buildPatch', () => buildPatch(result, 'hash', 'ws').ops],
+ ])('%s keeps the first names in source order, up to the cap, and the full distinct count', (_label, build) => {
+ const attrs = byName(build(), 'busy', 'function').attrs!;
+ expect(attrs.unresolved_call_count).toBe(UNRESOLVED_CALLS_CAP + 7);
+ expect(attrs.unresolved_calls).toEqual(calls.slice(0, UNRESOLVED_CALLS_CAP).map((c) => c.slice(0, -3)));
+ });
+
+ it('is 20', () => {
+ expect(UNRESOLVED_CALLS_CAP).toBe(20);
+ });
+});
diff --git a/core-ingestion/src/__tests__/resolveEdges.integration.test.ts b/core-ingestion/src/__tests__/resolveEdges.integration.test.ts
index f0f6ab4c..d427dbab 100644
--- a/core-ingestion/src/__tests__/resolveEdges.integration.test.ts
+++ b/core-ingestion/src/__tests__/resolveEdges.integration.test.ts
@@ -5,7 +5,8 @@ import path from 'node:path';
import { describe, expect, it } from 'vitest';
-import { parseFile, resolveEdges } from '../index.js';
+import { parseFile } from '../index.js';
+import { resolveEdges } from './helpers/untiered.js';
const repoRoot = path.resolve(import.meta.dirname, '../../..');
// Frozen in-repo fixtures. This walked `memory-layer/` until #557 -- a
diff --git a/core-ingestion/src/__tests__/resolveEdges.scope.test.ts b/core-ingestion/src/__tests__/resolveEdges.scope.test.ts
index a1f795e7..56d6976e 100644
--- a/core-ingestion/src/__tests__/resolveEdges.scope.test.ts
+++ b/core-ingestion/src/__tests__/resolveEdges.scope.test.ts
@@ -10,7 +10,8 @@
import { describe, expect, it } from 'vitest';
-import { parseFile, resolveEdges, type FileParseResult, type ResolvedEdge } from '../index.js';
+import { parseFile, type FileParseResult, type ResolvedEdge } from '../index.js';
+import { resolveEdges } from './helpers/untiered.js';
import { buildPatch, buildPatchWithResolution } from '../patch-builder.js';
function parse(filePath: string, source: string): FileParseResult {
diff --git a/core-ingestion/src/__tests__/resolveEdges.test.ts b/core-ingestion/src/__tests__/resolveEdges.test.ts
index 8b7beb30..fefce6d9 100644
--- a/core-ingestion/src/__tests__/resolveEdges.test.ts
+++ b/core-ingestion/src/__tests__/resolveEdges.test.ts
@@ -2,7 +2,8 @@
import { describe, expect, it } from 'vitest';
-import { buildGlobalResolutionIndex, parseFile, resolveEdges, type FileParseResult, type ParsedEntity, type ParsedRelationship } from '../index.js';
+import { buildGlobalResolutionIndex, parseFile, type FileParseResult, type ParsedEntity, type ParsedRelationship } from '../index.js';
+import { resolveEdges } from './helpers/untiered.js';
import { SupportedLanguages } from '../languages.js';
function entity(
diff --git a/core-ingestion/src/index.ts b/core-ingestion/src/index.ts
index d1527967..99ccc30e 100644
--- a/core-ingestion/src/index.ts
+++ b/core-ingestion/src/index.ts
@@ -3489,9 +3489,19 @@ export interface ResolvedEdge {
dstQualifiedKey: string; // qualified key used for nodeId in the defining file
predicate: string; // "CALLS" | "EXTENDS"
confidence: number; // 0.9 import-scoped | 0.8 transitive | 0.5 global
+ /** Which resolution tier produced the edge; written on the edge with `confidence`. */
+ tier?: ResolutionTier;
phpCallKind?: ParsedRelationship['phpCallKind'];
}
+/**
+ * `binding`: an explicit import binding names the target. `import`: the
+ * target is in a file this one imports (or the import itself). `transitive`:
+ * one re-export hop away. `qualifier`: a dotted name's qualifier picked the
+ * file. `global`: the only definition of the name anywhere.
+ */
+export type ResolutionTier = 'binding' | 'import' | 'transitive' | 'qualifier' | 'global';
+
// ---------------------------------------------------------------------------
// resolveCallEdges helpers
// ---------------------------------------------------------------------------
@@ -4841,6 +4851,7 @@ export function resolveEdges(
dstQualifiedKey: fileEntityName(fp),
predicate: 'IMPORTS',
confidence: 0.9,
+ tier: 'import',
});
stats.resolvedImport++;
} else if (phpType.entries.length > 1) {
@@ -4861,7 +4872,7 @@ export function resolveEdges(
const fp = matchFiles[0];
const dstQualifiedKey = bestQKey(fileQKeys, fp, entityName);
if (dstQualifiedKey !== null) {
- resolved.push({ srcFilePath, srcName: rel.srcName, dstFilePath: fp, dstName, dstQualifiedKey, predicate: 'IMPORTS', confidence: 0.9 });
+ resolved.push({ srcFilePath, srcName: rel.srcName, dstFilePath: fp, dstName, dstQualifiedKey, predicate: 'IMPORTS', confidence: 0.9, tier: 'import' });
stats.resolvedImport++;
continue;
}
@@ -4890,6 +4901,7 @@ export function resolveEdges(
dstQualifiedKey: fileEntityName(fp),
predicate: 'IMPORTS',
confidence: 0.9,
+ tier: 'import',
});
stats.resolvedImport++;
continue;
@@ -4913,7 +4925,7 @@ export function resolveEdges(
if (srcRepo !== undefined && depRepo !== undefined && depRepo !== srcRepo) {
const entryFp = entryFileOf.get(depRepo);
if (entryFp && entryFp !== srcFilePath) {
- resolved.push({ srcFilePath, srcName: rel.srcName, dstFilePath: entryFp, dstName: rel.dstName, dstQualifiedKey: fileEntityName(entryFp), predicate: 'IMPORTS', confidence: 0.7 });
+ resolved.push({ srcFilePath, srcName: rel.srcName, dstFilePath: entryFp, dstName: rel.dstName, dstQualifiedKey: fileEntityName(entryFp), predicate: 'IMPORTS', confidence: 0.7, tier: 'import' });
stats.resolvedImport++;
continue;
}
@@ -4946,6 +4958,7 @@ export function resolveEdges(
dstQualifiedKey,
predicate: rel.predicate,
confidence: 0.9,
+ tier: 'binding',
...(rel.phpCallKind ? { phpCallKind: rel.phpCallKind } : {}),
});
stats.resolvedQualifier++;
@@ -5022,6 +5035,7 @@ export function resolveEdges(
dstQualifiedKey,
predicate: rel.predicate,
confidence: 0.9,
+ tier: 'binding',
});
continue;
}
@@ -5049,6 +5063,7 @@ export function resolveEdges(
dstQualifiedKey,
predicate: rel.predicate,
confidence: 0.9,
+ tier: 'binding',
});
continue;
}
@@ -5125,7 +5140,7 @@ export function resolveEdges(
const dstQualifiedKey = bestQKey(fileQKeys, qfp, memberPart, preferredQKey);
if (dstQualifiedKey !== null) {
// dstName must match rel.dstName so buildPatchWithResolution can look it up
- resolved.push({ srcFilePath, srcName, dstFilePath: qfp, dstName: origDstName, dstQualifiedKey, predicate: rel.predicate, confidence: 0.9 });
+ resolved.push({ srcFilePath, srcName, dstFilePath: qfp, dstName: origDstName, dstQualifiedKey, predicate: rel.predicate, confidence: 0.9, tier: 'qualifier' });
}
}
continue;
@@ -5150,7 +5165,7 @@ export function resolveEdges(
if (fileHasSymbol.get(qfp)?.has(memberPart)) {
const dstQualifiedKey = bestQKey(fileQKeys, qfp, memberPart, `${qualifierPart}.${memberPart}`);
if (dstQualifiedKey !== null) {
- resolved.push({ srcFilePath, srcName, dstFilePath: qfp, dstName: origDstName, dstQualifiedKey, predicate: rel.predicate, confidence: 0.7 });
+ resolved.push({ srcFilePath, srcName, dstFilePath: qfp, dstName: origDstName, dstQualifiedKey, predicate: rel.predicate, confidence: 0.7, tier: 'qualifier' });
}
}
}
@@ -5169,7 +5184,7 @@ export function resolveEdges(
const fp = narrowedImportMatches[0];
const dstQualifiedKey = targetQKey(fp);
if (dstQualifiedKey === null) continue; // ambiguous — do not emit bad nodeId
- resolved.push({ srcFilePath, srcName, dstFilePath: fp, dstName: origDstName, dstQualifiedKey, predicate: rel.predicate, confidence: 0.9 });
+ resolved.push({ srcFilePath, srcName, dstFilePath: fp, dstName: origDstName, dstQualifiedKey, predicate: rel.predicate, confidence: 0.9, tier: 'import' });
continue;
}
if (unboundAmbientCall) continue;
@@ -5197,7 +5212,7 @@ export function resolveEdges(
const fp = narrowedTransitiveMatches[0];
const dstQualifiedKey = targetQKey(fp);
if (dstQualifiedKey === null) continue;
- resolved.push({ srcFilePath, srcName, dstFilePath: fp, dstName: origDstName, dstQualifiedKey, predicate: rel.predicate, confidence: 0.8 });
+ resolved.push({ srcFilePath, srcName, dstFilePath: fp, dstName: origDstName, dstQualifiedKey, predicate: rel.predicate, confidence: 0.8, tier: 'transitive' });
continue;
}
if (configuredBindingTargets?.length === 0) continue;
@@ -5240,7 +5255,7 @@ export function resolveEdges(
if (bareCall && !definesAtModuleScope(fp)) continue; // only a member of that name
const dstQualifiedKey = targetQKey(fp);
if (dstQualifiedKey === null) continue; // ambiguous — do not emit bad nodeId
- resolved.push({ srcFilePath, srcName, dstFilePath: fp, dstName: origDstName, dstQualifiedKey, predicate: rel.predicate, confidence: 0.5 });
+ resolved.push({ srcFilePath, srcName, dstFilePath: fp, dstName: origDstName, dstQualifiedKey, predicate: rel.predicate, confidence: 0.5, tier: 'global' });
stats.resolvedGlobal++;
continue;
}
diff --git a/core-ingestion/src/patch-builder.ts b/core-ingestion/src/patch-builder.ts
index 8352d89b..204ee0de 100644
--- a/core-ingestion/src/patch-builder.ts
+++ b/core-ingestion/src/patch-builder.ts
@@ -3,7 +3,7 @@
import * as crypto from 'node:crypto';
import * as nodePath from 'node:path';
import type { GraphPatchPayload, PatchOp } from './types.js';
-import type { FileParseResult, ParsedEntity, ResolvedEdge } from './index.js';
+import type { FileParseResult, ParsedEntity, ResolutionTier, ResolvedEdge } from './index.js';
// ---------------------------------------------------------------------------
// Deterministic UUID from a string (matches existing CLI convention)
@@ -134,7 +134,9 @@ function deduplicateUpsertEdges(ops: PatchOp[]): PatchOp[] {
* old id and the new output never lands -- 1.26: JS/TS calls resolve by scope,
* not name alone, and helper-loaded / dist/ imports link to their sources.
* 1.27: Python, Rust and PHP bare calls no longer resolve to another file's
- * class member.
+ * class member. 1.28: no edge is written without a node at both ends (calls
+ * that resolve nowhere go on their caller as `unresolved_calls`), and
+ * cross-file edges carry `confidence` and `tier`.
*
* `ix map` skips files whose mtime or source hash is unchanged, which would
* keep the old extractor's edges on them, so the ingest baseline records this
@@ -152,11 +154,11 @@ export function patchActor(): string {
}
export function extractorName(): string {
- return `tree-sitter/1.27`;
+ return `tree-sitter/1.28`;
}
/** Previous extractor versions — their patches are superseded when re-ingesting. */
-export const PREVIOUS_EXTRACTORS = ['tree-sitter/1.26', 'tree-sitter/1.25', 'tree-sitter/1.24', 'tree-sitter/1.23', 'tree-sitter/1.22', 'tree-sitter/1.21', 'tree-sitter/1.20', 'tree-sitter/1.19', 'tree-sitter/1.18', 'tree-sitter/1.17', 'tree-sitter/1.16', 'tree-sitter/1.15', 'tree-sitter/1.14', 'tree-sitter/1.13', 'tree-sitter/1.12', 'tree-sitter/1.11', 'tree-sitter/1.10', 'tree-sitter/1.9', 'tree-sitter/1.8', 'tree-sitter/1.7', 'tree-sitter/1.6', 'tree-sitter/1.5', 'tree-sitter/1.4', 'tree-sitter/1.3', 'tree-sitter/1.2', 'tree-sitter/1.1'];
+export const PREVIOUS_EXTRACTORS = ['tree-sitter/1.27', 'tree-sitter/1.26', 'tree-sitter/1.25', 'tree-sitter/1.24', 'tree-sitter/1.23', 'tree-sitter/1.22', 'tree-sitter/1.21', 'tree-sitter/1.20', 'tree-sitter/1.19', 'tree-sitter/1.18', 'tree-sitter/1.17', 'tree-sitter/1.16', 'tree-sitter/1.15', 'tree-sitter/1.14', 'tree-sitter/1.13', 'tree-sitter/1.12', 'tree-sitter/1.11', 'tree-sitter/1.10', 'tree-sitter/1.9', 'tree-sitter/1.8', 'tree-sitter/1.7', 'tree-sitter/1.6', 'tree-sitter/1.5', 'tree-sitter/1.4', 'tree-sitter/1.3', 'tree-sitter/1.2', 'tree-sitter/1.1'];
/** Patch ids that may own the active graph entities for a stored source hash. */
export function sourcePatchIdCandidates(
@@ -194,6 +196,50 @@ function toMemberRelativePath(filePath: string, multiRepo?: MultiRepoContext): s
return slash >= 0 ? norm.slice(slash + 1) : norm;
}
+/** Most unresolved callee names kept on one node; the count covers them all. */
+export const UNRESOLVED_CALLS_CAP = 20;
+
+/**
+ * Calls that wrote no edge, by the node that makes them. An edge needs a node
+ * at both ends, so a call to a builtin, a library or a name that resolved
+ * nowhere leaves no trace in the graph but these attrs, which is what `ix
+ * explain` reads to say which calls it could not follow:
+ *
+ * - `unresolved_calls`: the distinct callee names as written at the call
+ * site, in first-seen (source) order, at most UNRESOLVED_CALLS_CAP;
+ * - `unresolved_call_count`: how many distinct names there were, so a cut
+ * list is visible as one.
+ *
+ * A call goes on the function, method or class that makes it; one from
+ * module-level code, or from a caller no node was written for, on the file.
+ * Nodes with none get neither attr.
+ */
+function unresolvedCallRecorder(knownNodeIds: ReadonlySet<string>, fileNodeId: string) {
+ const byNode = new Map<string, Set<string>>();
+ return {
+ add(srcNodeId: string, calleeName: string): void {
+ const owner = knownNodeIds.has(srcNodeId) ? srcNodeId : fileNodeId;
+ let names = byNode.get(owner);
+ if (!names) { names = new Set<string>(); byNode.set(owner, names); }
+ names.add(calleeName);
+ },
+ /** Write the attrs onto the UpsertNode ops already in `ops`. */
+ applyTo(ops: PatchOp[]): void {
+ if (byNode.size === 0) return;
+ for (const op of ops) {
+ if (op.type !== 'UpsertNode') continue;
+ const names = byNode.get(op.id as string);
+ if (!names) continue;
+ op.attrs = {
+ ...((op.attrs as Record<string, unknown> | undefined) ?? {}),
+ unresolved_calls: [...names].slice(0, UNRESOLVED_CALLS_CAP),
+ unresolved_call_count: names.size,
+ };
+ }
+ },
+ };
+}
+
// ---------------------------------------------------------------------------
// Build a GraphPatchPayload from a FileParseResult
// ---------------------------------------------------------------------------
@@ -320,11 +366,12 @@ export function buildPatch(
predicate: 'CONTAINS_CHUNK',
attrs: {},
});
- // Chunk -[DEFINES]-> Symbol (only for named chunks)
+ // Chunk -[DEFINES]-> Symbol (only for named chunks whose symbol this patch
+ // writes; any other would point at a node that does not exist)
if (chunk.name !== null) {
const symbolKey = chunk.container ? `${chunk.container}.${chunk.name}` : chunk.name;
const symbolNid = nodeId(idPath, symbolKey);
- ops.push({
+ if (seenNodeIds.has(symbolNid)) ops.push({
type: 'UpsertEdge',
id: edgeId(idPath, cid, symbolNid, 'DEFINES'),
src: cid,
@@ -354,17 +401,25 @@ export function buildPatch(
}
}
- // UpsertEdge for each relationship
+ // UpsertEdge for each relationship -- only those with a node at both ends; see
+ // `keepEdge` in buildPatchWithResolution. Without resolution, that means a
+ // node this patch writes or an external node it mints.
const seenExternalNodes = new Set<string>();
+ const unresolvedCalls = unresolvedCallRecorder(seenNodeIds, fileNodeId);
for (const r of relationships) {
// For CONTAINS edges, srcName is the container of dstName — use that to disambiguate.
const srcKey = resolveKey(r.srcName);
const dstKey = r.predicate === 'CONTAINS'
? resolveKey(r.dstName, r.srcName)
: resolveKey(r.dstName);
+ const external = r.predicate === 'CALLS' && dstKey.includes('::') && !allQKeys.has(dstKey);
+ if (!seenNodeIds.has(nodeId(idPath, srcKey)) || (!external && !seenNodeIds.has(nodeId(idPath, dstKey)))) {
+ if (r.predicate === 'CALLS') unresolvedCalls.add(nodeId(idPath, srcKey), r.dstName);
+ continue;
+ }
let dstNid: string;
- if (r.predicate === 'CALLS' && dstKey.includes('::') && !allQKeys.has(dstKey)) {
+ if (external) {
const sep = dstKey.indexOf('::');
const pkgName = dstKey.slice(0, sep);
const funcName = dstKey.slice(sep + 2);
@@ -393,6 +448,7 @@ export function buildPatch(
attrs: {},
});
}
+ unresolvedCalls.applyTo(ops);
// AssertClaim for each relationship (feeds the confidence/conflict engine)
// phpCallKind splits the relationship dedup key, so `handle(); $obj->handle();`
@@ -513,13 +569,20 @@ export function buildPatchWithResolution(
// Build lookup: `${srcName}:${predicate}:${dstName}` → { dstFilePath, dstQualifiedKey }
// Callers should pass only edges for this file (pre-grouped) for best performance,
// but we still tolerate the full array for backward compatibility.
- const edgeResolution = new Map<string, { dstFilePath: string; dstQualifiedKey: string }>();
+ const edgeResolution = new Map<string, {
+ dstFilePath: string;
+ dstQualifiedKey: string;
+ confidence: number;
+ tier: ResolutionTier | undefined;
+ }>();
for (const edge of resolvedEdges) {
if (edge.srcFilePath !== result.filePath) continue;
const callKind = edge.phpCallKind ? `:${edge.phpCallKind}` : '';
edgeResolution.set(`${edge.srcName}:${edge.predicate}:${edge.dstName}${callKind}`, {
dstFilePath: edge.dstFilePath,
dstQualifiedKey: edge.dstQualifiedKey,
+ confidence: edge.confidence,
+ tier: edge.tier,
});
}
@@ -630,7 +693,7 @@ export function buildPatchWithResolution(
if (chunk.name !== null) {
const symbolKey = chunk.container ? `${chunk.container}.${chunk.name}` : chunk.name;
const symbolNid = nodeId(idPath, symbolKey);
- ops.push({
+ if (seenNodeIds2.has(symbolNid)) ops.push({
type: 'UpsertEdge',
id: edgeId(idPath, cid, symbolNid, 'DEFINES'),
src: cid,
@@ -660,6 +723,8 @@ export function buildPatchWithResolution(
const seenExternalNodes2 = new Set<string>();
const emittedEdgeIdentities = new Set<string>();
+ /** CALLS dropped for want of a destination node; recorded on their caller. */
+ const unresolvedCalls = unresolvedCallRecorder(seenNodeIds2, fileNodeId2);
const relationshipShapeCounts = new Map<string, number>();
for (const relationship of relationships) {
const key = `${relationship.srcName}:${relationship.predicate}:${relationship.dstName}`;
@@ -675,6 +740,8 @@ export function buildPatchWithResolution(
const resolveDst = (r: (typeof relationships)[number], dstKey: string): {
dstNodeId: string;
externalPkg: { pkgName: string; funcName: string } | null;
+ /** Set when resolveEdges tied the edge to another file. */
+ resolution: { confidence: number; tier: ResolutionTier | undefined } | null;
} => {
const baseKey = `${r.srcName}:${r.predicate}:${r.dstName}`;
const salted = r.phpCallKind ? `${baseKey}:${r.phpCallKind}` : baseKey;
@@ -683,8 +750,12 @@ export function buildPatchWithResolution(
if (edgeResolution.has(matched)) {
// Cross-file resolved — use the defining file's nodeId, in the dst repo's
// workspace namespace (matters only for cross-repo edges in a co-ingest).
- const { dstFilePath, dstQualifiedKey } = edgeResolution.get(matched)!;
- return { dstNodeId: dstNodeIdInRepo(dstFilePath, dstQualifiedKey), externalPkg: null };
+ const { dstFilePath, dstQualifiedKey, confidence, tier } = edgeResolution.get(matched)!;
+ return {
+ dstNodeId: dstNodeIdInRepo(dstFilePath, dstQualifiedKey),
+ externalPkg: null,
+ resolution: { confidence, tier },
+ };
}
if (r.predicate === 'CALLS' && dstKey.includes('::') && !allQKeys2.has(dstKey)) {
const sep = dstKey.indexOf('::');
@@ -693,11 +764,24 @@ export function buildPatchWithResolution(
return {
dstNodeId: nodeId(`external://${pkgName}`, dstKey),
externalPkg: { pkgName, funcName },
+ resolution: null,
};
}
- return { dstNodeId: nodeId(idPath, dstKey), externalPkg: null };
+ return { dstNodeId: nodeId(idPath, dstKey), externalPkg: null, resolution: null };
};
+ /**
+ * Whether the edge has a node at both ends. The source must be one this
+ * patch upserts; the destination one this patch upserts, an external node it
+ * mints, or a node in the file resolveEdges tied it to. Anything else used to
+ * be written anyway, pointing at an id no patch ever creates: a call to a
+ * builtin, a library, or a name that resolved nowhere. Those dangling edges
+ * were over half the edges in a typical graph.
+ */
+ const keepEdge = (srcNodeId: string, dst: ReturnType<typeof resolveDst>): boolean =>
+ seenNodeIds2.has(srcNodeId) &&
+ (dst.resolution !== null || dst.externalPkg !== null || seenNodeIds2.has(dst.dstNodeId));
+
const relationshipDstKey = (r: (typeof relationships)[number]): string =>
r.predicate === 'CONTAINS' ? resolveKey(r.dstName, r.srcName) : resolveKey(r.dstName);
@@ -728,10 +812,13 @@ export function buildPatchWithResolution(
const edgeDstKey = r.phpCallKind && (relationshipShapeCounts.get(baseKey) ?? 0) > 1
? `${dstKey}:${r.phpCallKind}`
: dstKey;
+ const dst = resolveDst(r, dstKey);
+ // Only edges that are written can collide.
+ if (!keepEdge(nodeId(idPath, srcKey), dst)) continue;
const tuple = edgeIdTuple(srcKey, edgeDstKey, r.predicate);
let seen = dstsByTuple.get(tuple);
if (!seen) { seen = new Set<string>(); dstsByTuple.set(tuple, seen); }
- seen.add(resolveDst(r, dstKey).dstNodeId);
+ seen.add(dst.dstNodeId);
}
for (const [tuple, dsts] of dstsByTuple) {
if (dsts.size > 1) collidingIdTuples.add(tuple);
@@ -745,7 +832,12 @@ export function buildPatchWithResolution(
: resolveKey(r.dstName);
const baseResolutionKey = `${r.srcName}:${r.predicate}:${r.dstName}`;
- const { dstNodeId, externalPkg } = resolveDst(r, dstKey);
+ const dst = resolveDst(r, dstKey);
+ const { dstNodeId, externalPkg, resolution } = dst;
+ if (!keepEdge(nodeId(idPath, srcKey), dst)) {
+ if (r.predicate === 'CALLS') unresolvedCalls.add(nodeId(idPath, srcKey), r.dstName);
+ continue;
+ }
if (externalPkg && !seenExternalNodes2.has(dstNodeId)) {
seenExternalNodes2.add(dstNodeId);
ops.push({
@@ -779,9 +871,12 @@ export function buildPatchWithResolution(
src: nodeId(idPath, srcKey),
dst: dstNodeId,
predicate: r.predicate,
- attrs: {},
+ attrs: resolution
+ ? { confidence: resolution.confidence, ...(resolution.tier ? { tier: resolution.tier } : {}) }
+ : {},
});
}
+ unresolvedCalls.applyTo(ops);
// phpCallKind splits the relationship dedup key, so `handle(); $obj->handle();`
// arrives as two relationships that produce byte-identical claims. The kind is
diff --git a/ix-cli/src/cli/__tests__/explain-unresolved-calls.test.ts b/ix-cli/src/cli/__tests__/explain-unresolved-calls.test.ts
new file mode 100644
index 00000000..2190c309
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/explain-unresolved-calls.test.ts
@@ -0,0 +1,88 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { describe, expect, it } from "vitest";
+
+import type { IxClient } from "../../client/api.js";
+import { collectFacts, unresolvedCallNames, unresolvedCallsOf } from "../explain/facts.js";
+import { inferImportance } from "../explain/importance.js";
+import { renderExplainLlm } from "../explain/llm.js";
+import { renderExplanation } from "../explain/render.js";
+import { inferRole } from "../explain/role-inference.js";
+
+/**
+ * Since tree-sitter/1.28 a call with no node behind it writes no edge, so
+ * `ix explain` can no longer find it by following a dangling CALLS edge. It
+ * reads the names ingest recorded on the caller instead.
+ */
+
+const TARGET = "00000000-0000-0000-0000-000000000001";
+
+/** A function with no outbound CALLS edge at all, only the recorded names. */
+function graphWith(attrs: Record<string, unknown>): IxClient {
+ return {
+ async entity(id: string) {
+ return {
+ node: { id, name: "runJob", kind: "function", attrs, provenance: { sourceUri: "src/job.ts" } },
+ claims: [],
+ decisions: [],
+ edges: [],
+ };
+ },
+ async expand() {
+ return { nodes: [], edges: [] };
+ },
+ async provenance(id: string) {
+ return { entityId: id, chain: [] };
+ },
+ } as unknown as IxClient;
+}
+
+const RECORDED = { unresolved_calls: ["fetch", "JSON.parse", "retry"], unresolved_call_count: 5 };
+
+describe("ix explain on a function with unresolved calls", () => {
+ it("names them in the facts and the diagnostic", async () => {
+ const facts = await collectFacts(graphWith(RECORDED), TARGET, "runJob", "function");
+
+ expect(facts.unresolvedCalls).toEqual({ names: ["fetch", "JSON.parse", "retry"], total: 5 });
+ const diagnostic = facts.diagnostics.find((d) => d.code === "unresolved_call_target");
+ expect(diagnostic?.message).toContain("fetch, JSON.parse, retry and 2 more");
+ });
+
+ it("names them in the rendered note and the llm output", async () => {
+ const facts = await collectFacts(graphWith(RECORDED), TARGET, "runJob", "function");
+ const role = inferRole(facts);
+ const importance = inferImportance(facts);
+ const rendered = renderExplanation(facts, role, importance);
+
+ expect(rendered.notes.join("\n")).toContain("fetch, JSON.parse, retry and 2 more");
+ expect(renderExplainLlm(facts, role, importance, rendered).join("\n")).toContain("fetch, JSON.parse, retry");
+ });
+
+ it("says nothing when ingest recorded none", async () => {
+ const facts = await collectFacts(graphWith({}), TARGET, "runJob", "function");
+
+ expect(facts.unresolvedCalls).toBeUndefined();
+ expect(facts.diagnostics.map((d) => d.code)).not.toContain("unresolved_call_target");
+ });
+
+ it("leaves them out of `ix context`, which never rendered unresolved calls", async () => {
+ const facts = await collectFacts(graphWith(RECORDED), TARGET, "runJob", "function", "context");
+
+ expect(facts).not.toHaveProperty("unresolvedCalls");
+ });
+});
+
+describe("unresolvedCallsOf", () => {
+ it("reads the two attrs, tolerating junk and a missing count", () => {
+ expect(unresolvedCallsOf({ unresolved_calls: ["a", 3, ""], unresolved_call_count: 4 })).toEqual({ names: ["a"], total: 4 });
+ expect(unresolvedCallsOf({ unresolved_calls: ["a", "b"] })).toEqual({ names: ["a", "b"], total: 2 });
+ expect(unresolvedCallsOf({ unresolved_call_count: 0 })).toBeUndefined();
+ expect(unresolvedCallsOf(undefined)).toBeUndefined();
+ });
+
+ it("shows a cut list as one", () => {
+ expect(unresolvedCallNames({ names: ["a", "b"], total: 2 })).toBe("a, b");
+ expect(unresolvedCallNames({ names: ["a", "b"], total: 9 })).toBe("a, b and 7 more");
+ expect(unresolvedCallNames({ names: [], total: 3 })).toBe("3 more");
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/ingest-equivalence.test.ts b/ix-cli/src/cli/__tests__/ingest-equivalence.test.ts
index 3b207b3e..a3ed11d5 100644
--- a/ix-cli/src/cli/__tests__/ingest-equivalence.test.ts
+++ b/ix-cli/src/cli/__tests__/ingest-equivalence.test.ts
@@ -271,10 +271,12 @@ describe("incremental ix map equals a fresh map (fake backend)", () => {
});
// F-03. Files that call a renamed or deleted function are unchanged, so
- // nothing re-resolves them. Fresh, their calls are unresolved; incremental,
- // the edges are simply gone, and after a restore they never come back.
- it.fails("IN-11: renaming a called function re-resolves its callers", async () => {
- await runSequence("head", [edit("renameFunction", "web/math.ts", 0)]);
+ // nothing re-resolves them. Their edges go when the name goes, and when it
+ // comes back -- renamed back, or the file restored -- they never return.
+ // (A plain rename now passes: since IN-08 an unresolved call writes no edge,
+ // fresh or incremental, so the rename back is what shows the defect.)
+ it.fails("IN-11: a called function renamed and renamed back re-binds its callers", async () => {
+ await runSequence("head", [edit("renameFunction", "web/math.ts", 0), { kind: "revert", a: 0, b: 0 }]);
});
it.fails("IN-11: restoring a deleted file re-binds its callers", async () => {
diff --git a/ix-cli/src/cli/__tests__/ingest-extractor-bump.test.ts b/ix-cli/src/cli/__tests__/ingest-extractor-bump.test.ts
new file mode 100644
index 00000000..f3be581f
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/ingest-extractor-bump.test.ts
@@ -0,0 +1,174 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { execFileSync } from "node:child_process";
+
+import { ingestFiles } from "../commands/ingest.js";
+import { loadIngestionModules } from "../commands/ingestion-loader.js";
+import { FakeBackend } from "./helpers/fake-backend.js";
+import { initialRepo, render, type Repo } from "./helpers/edit-fixture.js";
+
+/**
+ * tree-sitter/1.28 stops writing an edge whose destination has no node, so a
+ * graph built by 1.27 holds edges no fresh map would write. `ix map` re-ingests
+ * every file once when the extractor changes; this checks that the re-ingest
+ * takes those edges with it, against the fake backend with the real backend's
+ * commit semantics (see `ingest-equivalence.test.ts`).
+ *
+ * The 1.27 graph is made by the current parser with 1.27's two differences
+ * put back: the extractor name (so the patch ids and the baseline say 1.27),
+ * and a CALLS edge to `nodeId(file, callee)` -- an id no patch writes -- for
+ * every call that resolved to nothing, which is what 1.27 wrote for them.
+ */
+
+const OLD_EXTRACTOR = "tree-sitter/1.27";
+
+const legacy = vi.hoisted(() => ({ on: false }));
+
+vi.mock("../commands/ingestion-loader.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../commands/ingestion-loader.js")>();
+ return {
+ ...actual,
+ loadIngestionModules: async () => {
+ const [ingestion, patchBuilder, languages] = await actual.loadIngestionModules();
+ if (!legacy.on) return [ingestion, patchBuilder, languages];
+ const asOldExtractor = {
+ ...patchBuilder,
+ extractorName: () => OLD_EXTRACTOR,
+ buildPatchWithResolution: (parsed: any, hash: string, workspaceId: string, ...rest: any[]) => {
+ const patch = (patchBuilder.buildPatchWithResolution as any)(parsed, hash, workspaceId, ...rest);
+ const dangling: unknown[] = [];
+ for (const op of patch.ops) {
+ const names = op.type === "UpsertNode" ? op.attrs?.unresolved_calls : undefined;
+ if (!Array.isArray(names)) continue;
+ delete op.attrs.unresolved_calls;
+ delete op.attrs.unresolved_call_count;
+ for (const name of names) {
+ dangling.push({
+ type: "UpsertEdge", id: `old-${op.id}-${name}`, src: op.id,
+ dst: patchBuilder.symbolNodeId(workspaceId, parsed.filePath, name), predicate: "CALLS", attrs: {},
+ });
+ }
+ }
+ patch.ops.push(...dangling);
+ // The id 1.27 gave this file and content: the first previous extractor.
+ patch.patchId = patchBuilder.sourcePatchIdCandidates(parsed.filePath, hash, workspaceId)[1];
+ return patch;
+ },
+ };
+ return [ingestion, asOldExtractor, languages];
+ },
+ };
+});
+
+vi.mock("node:os", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("node:os")>();
+ return { ...actual, cpus: () => actual.cpus().slice(0, 3) };
+});
+
+const ENV_KEYS = [
+ "HOME", "USERPROFILE", "IX_ENDPOINT", "IX_LOCK_DIR", "IX_HOME", "IX_DEBUG",
+ "IX_COMMIT_FAILURE_LIMIT", "IX_COMMIT_HTTP_MAX_FILES", "IX_COMMIT_CONCURRENCY",
+ "IX_STITCH_COOLDOWN_MS", "IX_STITCH_WAIT_MS", "IX_MAP_DEADLINE_MS",
+] as const;
+
+/** The fixture, plus calls in every language to names defined nowhere. */
+function repoWithUnresolvedCalls(): Repo {
+ const repo = initialRepo();
+ for (const [path, fns] of repo) {
+ fns[0]!.calls.push({ path, name: "notDefinedAnywhere" });
+ }
+ return repo;
+}
+
+/** Live edges with an end that is not a live node. */
+function danglingEdges(backend: FakeBackend): string[] {
+ const { nodes, edges } = backend.graphSignature();
+ const live = new Set(nodes.map((line) => line.split(" ")[0]));
+ return edges.filter((line) => {
+ const [, src, dst] = line.split(" ");
+ return !live.has(src!) || !live.has(dst!);
+ });
+}
+
+describe("the tree-sitter/1.28 extractor bump", () => {
+ vi.setConfig({ testTimeout: 120_000 });
+
+ const root = realpathSync.native(mkdtempSync(join(tmpdir(), "ix-extractor-bump-")));
+ const repoDir = join(root, "repo");
+ const saved: Record<string, string | undefined> = {};
+
+ beforeAll(() => {
+ for (const k of ENV_KEYS) {
+ saved[k] = process.env[k];
+ delete process.env[k];
+ }
+ mkdirSync(repoDir);
+ execFileSync("git", ["init", "-q"], { cwd: repoDir, stdio: "ignore" });
+ for (const [p, fns] of repoWithUnresolvedCalls()) {
+ mkdirSync(dirname(join(repoDir, p)), { recursive: true });
+ writeFileSync(join(repoDir, p), render(p, fns), "utf8");
+ }
+ execFileSync("git", ["add", "-A"], { cwd: repoDir, stdio: "ignore" });
+ });
+ afterAll(() => {
+ for (const [k, v] of Object.entries(saved)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ async function map(home: string, endpoint: string): Promise<string> {
+ mkdirSync(home, { recursive: true });
+ process.env.HOME = home;
+ process.env.USERPROFILE = home;
+ process.env.IX_ENDPOINT = endpoint;
+ process.env.IX_LOCK_DIR = join(home, "locks");
+ const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
+ try {
+ await ingestFiles(repoDir, { recursive: true, format: "json", printSummary: false, suppressOutput: true, mapMode: true });
+ return stderr.mock.calls.map(([chunk]) => String(chunk)).join("");
+ } finally {
+ stderr.mockRestore();
+ }
+ }
+
+ it("re-ingests a 1.27 graph once and leaves no edge without both ends", async () => {
+ const current = (await loadIngestionModules())[1].extractorName();
+ const backend = new FakeBackend({ semantics: "head" });
+ const fresh = new FakeBackend({ semantics: "head" });
+ const home = join(root, "home");
+ try {
+ const endpoint = await backend.start();
+
+ legacy.on = true;
+ await map(home, endpoint);
+ legacy.on = false;
+ // 12 files, one call to a missing name in each.
+ expect(danglingEdges(backend), "the 1.27 graph").toHaveLength(12);
+
+ backend.resetRequests();
+ const log = await map(home, endpoint);
+ expect(log).toContain(`[extractor changed] ${OLD_EXTRACTOR} -> ${current}`);
+ expect(backend.acceptedPatches(), "every file re-ingested").toBe(12);
+ expect(danglingEdges(backend)).toEqual([]);
+
+ // The same graph a fresh map writes, edges and all.
+ await map(join(root, "fresh-home"), await fresh.start());
+ expect(backend.graphSignature().edges).toEqual(fresh.graphSignature().edges);
+
+ // Once: the next map has nothing to do.
+ backend.resetRequests();
+ expect(await map(home, endpoint)).not.toContain("[extractor changed]");
+ expect(backend.acceptedPatches()).toBe(0);
+ } finally {
+ legacy.on = false;
+ await backend.stop();
+ await fresh.stop();
+ }
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/ingest-map-mode-ops.test.ts b/ix-cli/src/cli/__tests__/ingest-map-mode-ops.test.ts
new file mode 100644
index 00000000..6e46f96c
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/ingest-map-mode-ops.test.ts
@@ -0,0 +1,30 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { describe, expect, it } from "vitest";
+
+import { stripMapModeOps } from "../commands/ingest.js";
+import type { GraphPatchPayload } from "../../client/types.js";
+
+describe("stripMapModeOps", () => {
+ it("drops chunks and every edge that touches one, and nothing else", () => {
+ const patch = {
+ patchId: "p",
+ ops: [
+ { type: "UpsertNode", id: "file", kind: "file", name: "a.ts", attrs: {} },
+ { type: "UpsertNode", id: "fn", kind: "function", name: "run", attrs: {} },
+ { type: "UpsertNode", id: "c1", kind: "chunk", name: "run", attrs: {} },
+ { type: "UpsertNode", id: "c2", kind: "chunk", name: "file_body:9", attrs: {} },
+ { type: "UpsertEdge", id: "e1", src: "file", dst: "c1", predicate: "CONTAINS_CHUNK", attrs: {} },
+ { type: "UpsertEdge", id: "e2", src: "c1", dst: "c2", predicate: "NEXT", attrs: {} },
+ // The one that used to survive: its chunk is gone, so it dangled.
+ { type: "UpsertEdge", id: "e3", src: "c1", dst: "fn", predicate: "DEFINES", attrs: {} },
+ { type: "UpsertEdge", id: "e4", src: "file", dst: "fn", predicate: "CONTAINS", attrs: {} },
+ { type: "AssertClaim", entityId: "fn", field: "calls:x", value: "x", confidence: null },
+ ],
+ } as unknown as GraphPatchPayload;
+
+ const kept = stripMapModeOps(patch).ops.map((op) => String(op.id ?? op.type));
+
+ expect(kept).toEqual(["file", "fn", "e4"]);
+ });
+});
diff --git a/ix-cli/src/cli/commands/explain.ts b/ix-cli/src/cli/commands/explain.ts
index c602528f..365ee52d 100644
--- a/ix-cli/src/cli/commands/explain.ts
+++ b/ix-cli/src/cli/commands/explain.ts
@@ -6,7 +6,7 @@ import { createClient } from "../../client/factory.js";
import { formatExplain, relativePath, printJson, type ExplainResult, type EntityRef, type Diagnostic } from "../format.js";
import { resolveFileOrReport, isRawId, activeReadScope } from "../resolve.js";
import { isFileStale } from "../stale.js";
-import { collectFacts } from "../explain/facts.js";
+import { collectFacts, unresolvedCallNames, unresolvedCallsOf } from "../explain/facts.js";
import { inferRole } from "../explain/role-inference.js";
import { inferImportance } from "../explain/importance.js";
import { renderExplanation } from "../explain/render.js";
@@ -206,6 +206,26 @@ async function rawExplain(
});
}
}
+ // Calls with no node to point at write no edge (tree-sitter/1.28 on); ingest
+ // names them on the caller instead. Listed after the resolved ones, unless
+ // there were too many of those to list: then the diagnostic alone names them.
+ const unresolvedCalls = unresolvedCallsOf(node.attrs);
+ if (unresolvedCalls) {
+ if (callList || calleeEdges.length === 0) {
+ callList = [
+ ...(callList ?? []),
+ ...unresolvedCalls.names.map((name): EntityRef => ({
+ name,
+ resolved: false,
+ suggestedCommand: forMcp() ? toolCall("ix_text", { pattern: name }) : `ix text "${name}"`,
+ })),
+ ];
+ }
+ diagnostics.push({
+ code: "unresolved_call_target",
+ message: `${unresolvedCalls.total} called name(s) have no definition in the graph: ${unresolvedCallNames(unresolvedCalls)}.`,
+ });
+ }
if (stale) {
diagnostics.push({
diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.ts
index 0b3c7eb2..b7c7e070 100644
--- a/ix-cli/src/cli/commands/ingest.ts
+++ b/ix-cli/src/cli/commands/ingest.ts
@@ -276,14 +276,24 @@ function stripChunkOps(patch: GraphPatchPayload): GraphPatchPayload {
};
}
-/** Strip chunks and claims from patches — mapMode only needs nodes + edges. */
-function stripMapModeOps(patch: GraphPatchPayload): GraphPatchPayload {
+/**
+ * Strip chunks and claims from patches — mapMode only needs nodes + edges.
+ *
+ * Every edge that touches a dropped chunk goes too, not only the chunk
+ * predicates: a named chunk also DEFINES its symbol, and keeping that edge
+ * once its chunk is gone left one dangling DEFINES per function in every
+ * `ix map` graph.
+ */
+export function stripMapModeOps(patch: GraphPatchPayload): GraphPatchPayload {
+ const droppedNodes = new Set<unknown>(
+ patch.ops.filter(op => op.type === 'UpsertNode' && op['kind'] === 'chunk').map(op => op['id']),
+ );
return {
...patch,
ops: patch.ops.filter(op => {
if (op.type === 'AssertClaim' || op.type === 'RetractClaim') return false;
if (op.type === 'UpsertNode' && op['kind'] === 'chunk') return false;
- if (op.type === 'UpsertEdge' && (op['predicate'] === 'CONTAINS_CHUNK' || op['predicate'] === 'NEXT')) return false;
+ if (op.type === 'UpsertEdge' && (droppedNodes.has(op['src']) || droppedNodes.has(op['dst']))) return false;
return true;
}),
};
diff --git a/ix-cli/src/cli/explain/facts.ts b/ix-cli/src/cli/explain/facts.ts
index a2a94d86..7d490594 100644
--- a/ix-cli/src/cli/explain/facts.ts
+++ b/ix-cli/src/cli/explain/facts.ts
@@ -103,6 +103,12 @@ export interface EntityFacts {
// Call details
callList?: EntityRef[];
+ /**
+ * Calls the target makes that the graph has no node for -- builtins,
+ * library functions, names that resolved nowhere. Ingest writes no edge for
+ * them, so they are read off the target's own attrs (`unresolvedCallsOf`).
+ */
+ unresolvedCalls?: UnresolvedCalls;
// Hierarchy (scene graph)
systemPath?: Array<{ name: string; kind: string }>;
@@ -116,11 +122,44 @@ export interface EntityFacts {
diagnostics: Diagnostic[];
}
+/**
+ * Calls a node makes that no edge records. `names` is capped at ingest (in
+ * source order); `total` counts every distinct name, so `total > names.length`
+ * means the list was cut.
+ */
+export interface UnresolvedCalls {
+ names: string[];
+ total: number;
+}
+
+/**
+ * The unresolved calls ingest recorded on a node (`unresolved_calls`,
+ * `unresolved_call_count`; tree-sitter/1.28 on), or undefined when it recorded
+ * none. A graph built before then has dangling CALLS edges instead, which
+ * `resolveCallList` still reports.
+ */
+export function unresolvedCallsOf(attrs: unknown): UnresolvedCalls | undefined {
+ const a = (attrs ?? {}) as { unresolved_calls?: unknown; unresolved_call_count?: unknown };
+ const names = Array.isArray(a.unresolved_calls)
+ ? a.unresolved_calls.filter((n): n is string => typeof n === "string" && n.length > 0)
+ : [];
+ const count = typeof a.unresolved_call_count === "number" ? a.unresolved_call_count : 0;
+ const total = Math.max(count, names.length);
+ return total > 0 ? { names, total } : undefined;
+}
+
+/** `a, b, c` -- or `a, b, c and 4 more` when the list was cut. */
+export function unresolvedCallNames(calls: UnresolvedCalls): string {
+ const more = calls.total - calls.names.length;
+ return calls.names.join(", ") + (more > 0 ? `${calls.names.length > 0 ? " and " : ""}${more} more` : "");
+}
+
/** Facts only `ix explain` renders. */
type ExplainOnlyFact =
| "downstreamDependents"
| "downstreamDepth"
| "callList"
+ | "unresolvedCalls"
| "systemPath"
| "subsystemName"
| "moduleName";
@@ -476,14 +515,18 @@ export async function collectFacts(
const topCallers = topCallerRefs.map((r) => r.name);
const topDependents = topDependentRefs.map((r) => r.name);
- if (callList) {
- const unresolvedCount = callList.filter((r) => !r.resolved).length;
- if (unresolvedCount > 0) {
- diagnostics.push({
- code: "unresolved_call_target",
- message: `${unresolvedCount} callee(s) could not be resolved to named entities.`,
- });
+ // Calls with no node behind them. Since tree-sitter/1.28 ingest writes no
+ // edge for those and names them on the caller instead; a graph built before
+ // then still has them as dangling edges, which the call list finds.
+ const unresolvedCalls = unresolvedCallsOf(node.attrs);
+ const danglingCallees = callList?.filter((r) => !r.resolved).length ?? 0;
+ if (unresolvedCalls || danglingCallees > 0) {
+ const parts: string[] = [];
+ if (unresolvedCalls) {
+ parts.push(`${unresolvedCalls.total} called name(s) have no definition in the graph: ${unresolvedCallNames(unresolvedCalls)}.`);
}
+ if (danglingCallees > 0) parts.push(`${danglingCallees} callee(s) could not be resolved to named entities.`);
+ diagnostics.push({ code: "unresolved_call_target", message: parts.join(" ") });
}
// Staleness
@@ -546,6 +589,7 @@ export async function collectFacts(
introducedRev: node.createdRev ?? node.created_rev,
historyLength: history?.chain?.length ?? 0,
callList,
+ unresolvedCalls,
systemPath: systemPathMapped,
subsystemName,
moduleName,
@@ -557,6 +601,7 @@ export async function collectFacts(
downstreamDependents: _downstreamDependents,
downstreamDepth: _downstreamDepth,
callList: _callList,
+ unresolvedCalls: _unresolvedCalls,
systemPath: _systemPath,
subsystemName: _subsystemName,
moduleName: _moduleName,
diff --git a/ix-cli/src/cli/explain/render.ts b/ix-cli/src/cli/explain/render.ts
index 359397fc..503b9951 100644
--- a/ix-cli/src/cli/explain/render.ts
+++ b/ix-cli/src/cli/explain/render.ts
@@ -1,6 +1,6 @@
// Copyright 2026 Ix Infrastructure Inc.
-import type { EntityFacts } from "./facts.js";
+import { unresolvedCallNames, type EntityFacts } from "./facts.js";
import type { RoleInference, RoleLabel } from "./role-inference.js";
import type { ImportanceInference } from "./importance.js";
import {
@@ -536,7 +536,11 @@ function renderNotes(facts: EntityFacts): string[] {
for (const d of facts.diagnostics) {
switch (d.code) {
case "unresolved_call_target":
- notes.push(`Some downstream calls could not be resolved to named entities. Run ${forMcp() ? "ix_map" : "`ix map`"} to improve coverage.`);
+ // Named when ingest recorded them; a pre-1.28 graph only has dangling
+ // edges, and the next map rebuilds it.
+ notes.push(facts.unresolvedCalls
+ ? `Calls with no definition in the graph (builtins, libraries or unresolved names): ${unresolvedCallNames(facts.unresolvedCalls)}.`
+ : `Some downstream calls could not be resolved to named entities. Run ${forMcp() ? "ix_map" : "`ix map`"} to improve coverage.`);
break;
case "stale_source":
notes.push("Source file has changed since last ingest — results may be incomplete.");
diff --git a/ix-cli/src/cli/graph-health.ts b/ix-cli/src/cli/graph-health.ts
index 9318dbdb..1bb4724a 100644
--- a/ix-cli/src/cli/graph-health.ts
+++ b/ix-cli/src/cli/graph-health.ts
@@ -93,7 +93,11 @@ const STRUCTURAL_PREDICATES = new Set(["CONTAINS", "DEFINES", "CONTAINS_CHUNK"])
/** Below this many symbols the coverage ratio is too noisy to judge by. */
const MIN_SYMBOLS_FOR_RATIO = 50;
-/** Structural edges per symbol below which a graph is called hollow. Healthy: ~1.2. */
+/**
+ * Structural edges per symbol below which a graph is called hollow. Healthy:
+ * about 1.0 for an `ix map` graph (one CONTAINS per symbol; chunks and their
+ * DEFINES are not written), more after `ix ingest`, which adds chunks.
+ */
const MIN_STRUCTURAL_COVERAGE = 0.2;
/** A graph with at least this many symbols and no structural edge at all is hollow. */
const MIN_SYMBOLS_FOR_ZERO = 5;
diff --git a/ix-cli/test/e2e/scenarios.e2e.ts b/ix-cli/test/e2e/scenarios.e2e.ts
index 18a0ef83..f6fba73c 100644
--- a/ix-cli/test/e2e/scenarios.e2e.ts
+++ b/ix-cli/test/e2e/scenarios.e2e.ts
@@ -75,22 +75,23 @@ describe("revert to earlier content", () => {
}),
);
- it(
- "[fails until BEW-03] rename a function and back equals the original",
- failsUntil(["BEW-03"], async () => {
- const co = checkout("polyglot");
- map(env, co);
- const a = await signature(env, co);
+ // Marked [fails until BEW-03] until tree-sitter/1.28. All that was left of
+ // the renamed state was edges with no live node at either end: the renamed
+ // function's CALLS to names that resolve nowhere (`re.sub`, `lower`) and
+ // its chunk's DEFINES. 1.28 writes neither. A -> B -> A still covers BEW-03.
+ it("rename a function and back equals the original", async () => {
+ const co = checkout("polyglot");
+ map(env, co);
+ const a = await signature(env, co);
- for (const f of ["app/utils.py", "app/repository.py"])
- edit(co, f, replaceAll("to_snake_case", "to_snake_case_renamed"));
- map(env, co);
- git(co.dir, "checkout", "--", ".");
- map(env, co);
+ for (const f of ["app/utils.py", "app/repository.py"])
+ edit(co, f, replaceAll("to_snake_case", "to_snake_case_renamed"));
+ map(env, co);
+ git(co.dir, "checkout", "--", ".");
+ map(env, co);
- expectSameGraph("rename and back", await signature(env, co), a);
- }),
- );
+ expectSameGraph("rename and back", await signature(env, co), a);
+ });
it(
"[fails until BEW-03, IN-04] delete a file and restore it equals the original",
diff --git a/ix-cli/test/perf/budgets.json b/ix-cli/test/perf/budgets.json
index 61a003d7..bcc84054 100644
--- a/ix-cli/test/perf/budgets.json
+++ b/ix-cli/test/perf/budgets.json
@@ -40,12 +40,12 @@
},
"rank dependents/function": {
"requests": 1819,
- "bytes": 5494180,
+ "bytes": 6158281,
"wallMs": 6464
},
"callers getEndpoint": {
"requests": 3,
- "bytes": 41825,
+ "bytes": 48362,
"wallMs": 353
}
}