Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix: resolve relative imports by path (#406)

Hiro-Chiba38807f9d3ca2
diff --git a/core-ingestion/src/__tests__/queries.python.test.ts b/core-ingestion/src/__tests__/queries.python.test.ts
index c8b986b9..2c0980f7 100644
--- a/core-ingestion/src/__tests__/queries.python.test.ts
+++ b/core-ingestion/src/__tests__/queries.python.test.ts
@@ -35,6 +35,11 @@ def top_level():
dstName: 'User',
predicate: 'IMPORTS',
});
+ expect(result!.importBindings).toContainEqual({
+ pkg: '.models',
+ local: 'User',
+ imported: 'User',
+ });
expect(result!.relationships).toContainEqual({
srcName: 'example.py',
dstName: 'package.helpers',
@@ -66,6 +71,38 @@ def top_level():
});
});
+ it('preserves the module path for from-dot imports', () => {
+ const result = parseFile(
+ '/repo/pkg/caller.py',
+ 'from . import utils\n\ndef caller():\n return utils.target()\n',
+ );
+
+ expect(result!.relationships).toContainEqual({
+ srcName: 'caller.py',
+ dstName: 'utils',
+ predicate: 'IMPORTS',
+ importRaw: '.utils',
+ });
+ expect(result!.importBindings).toContainEqual({
+ pkg: '.utils',
+ local: 'utils',
+ imported: 'utils',
+ });
+ });
+
+ it('preserves Python from-import aliases as local bindings', () => {
+ const result = parseFile(
+ '/repo/pkg/caller.py',
+ 'from .utils import target as local\n\ndef caller():\n return local()\n',
+ );
+
+ expect(result!.importBindings).toContainEqual({
+ pkg: '.utils',
+ local: 'local',
+ imported: 'target',
+ });
+ });
+
it('resolves qualifier from constructor call assignment (Pattern 1)', () => {
const result = parseFile(
'/repo/views.py',
diff --git a/core-ingestion/src/__tests__/resolveEdges.test.ts b/core-ingestion/src/__tests__/resolveEdges.test.ts
index 8d1fb05f..649faa56 100644
--- a/core-ingestion/src/__tests__/resolveEdges.test.ts
+++ b/core-ingestion/src/__tests__/resolveEdges.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { buildGlobalResolutionIndex, resolveEdges, type FileParseResult, type ParsedEntity, type ParsedRelationship } from '../index.js';
+import { buildGlobalResolutionIndex, parseFile, resolveEdges, type FileParseResult, type ParsedEntity, type ParsedRelationship } from '../index.js';
import { SupportedLanguages } from '../languages.js';
function entity(
@@ -443,6 +443,436 @@ describe('resolveEdges', () => {
expect(resolved.filter(edge => edge.predicate === 'CALLS')).toEqual([]);
});
+ it('uses a TypeScript relative import path to disambiguate duplicate file stems', () => {
+ const caller = parseFile(
+ '/repo/a/caller.ts',
+ 'import { target } from "./utils";\nexport function caller() { return target(); }\n',
+ )!;
+ const localUtils = fileResult(
+ '/repo/a/utils.ts',
+ SupportedLanguages.TypeScript,
+ [entity('target', SupportedLanguages.TypeScript)],
+ );
+ const unrelatedUtils = fileResult(
+ '/repo/b/utils.ts',
+ SupportedLanguages.TypeScript,
+ [entity('target', SupportedLanguages.TypeScript)],
+ );
+
+ const resolved = resolveEdges([caller, localUtils, unrelatedUtils]);
+ expect(resolved).toContainEqual({
+ srcFilePath: '/repo/a/caller.ts',
+ srcName: 'caller.ts',
+ dstFilePath: '/repo/a/utils.ts',
+ dstName: 'utils',
+ dstQualifiedKey: 'utils.ts',
+ predicate: 'IMPORTS',
+ confidence: 0.9,
+ });
+ expect(resolved).toContainEqual({
+ srcFilePath: '/repo/a/caller.ts',
+ srcName: 'caller',
+ dstFilePath: '/repo/a/utils.ts',
+ dstName: 'target',
+ dstQualifiedKey: 'target',
+ predicate: 'CALLS',
+ confidence: 0.9,
+ });
+ expect(resolved.some(edge => edge.dstFilePath === '/repo/b/utils.ts')).toBe(false);
+ });
+
+ it('resolves parent-relative JavaScript imports to TypeScript source files', () => {
+ const caller = fileResult(
+ '/repo/features/a/caller.ts',
+ SupportedLanguages.TypeScript,
+ [entity('caller', SupportedLanguages.TypeScript)],
+ [
+ { srcName: 'caller.ts', dstName: 'utils.js', predicate: 'IMPORTS', importRaw: '../../shared/utils.js' },
+ { srcName: 'caller', dstName: 'target', predicate: 'CALLS' },
+ ],
+ );
+ const target = fileResult(
+ '/repo/shared/utils.ts',
+ SupportedLanguages.TypeScript,
+ [entity('target', SupportedLanguages.TypeScript)],
+ );
+ const runtimeTarget = fileResult(
+ '/repo/shared/utils.js',
+ SupportedLanguages.JavaScript,
+ [entity('target', SupportedLanguages.JavaScript)],
+ );
+ const collision = fileResult(
+ '/repo/other/utils.ts',
+ SupportedLanguages.TypeScript,
+ [entity('target', SupportedLanguages.TypeScript)],
+ );
+
+ const resolved = resolveEdges([caller, target, runtimeTarget, collision]);
+ expect(resolved).toContainEqual({
+ srcFilePath: '/repo/features/a/caller.ts',
+ srcName: 'caller',
+ dstFilePath: '/repo/shared/utils.ts',
+ dstName: 'target',
+ dstQualifiedKey: 'target',
+ predicate: 'CALLS',
+ confidence: 0.9,
+ });
+ expect(resolved.some(edge => edge.dstFilePath === '/repo/shared/utils.js')).toBe(false);
+ });
+
+ it('prefers the runtime JavaScript file for a JavaScript caller', () => {
+ const caller = parseFile(
+ '/repo/a/caller.js',
+ 'import { target } from "./utils.js";\nexport function caller() { return target(); }\n',
+ )!;
+ const runtimeTarget = fileResult(
+ '/repo/a/utils.js',
+ SupportedLanguages.JavaScript,
+ [entity('target', SupportedLanguages.JavaScript)],
+ );
+ const typeScriptTarget = fileResult(
+ '/repo/a/utils.ts',
+ SupportedLanguages.TypeScript,
+ [entity('target', SupportedLanguages.TypeScript)],
+ );
+
+ const resolved = resolveEdges([caller, runtimeTarget, typeScriptTarget]);
+ expect(resolved.some(edge => edge.dstFilePath === '/repo/a/utils.js')).toBe(true);
+ expect(resolved.some(edge => edge.dstFilePath === '/repo/a/utils.ts')).toBe(false);
+ });
+
+ it('resolves relative JavaScript imports with URL query and fragment suffixes', () => {
+ const caller = parseFile(
+ '/repo/a/caller.ts',
+ 'import { target } from "./utils.ts?worker#entry";\nexport function caller() { return target(); }\n',
+ )!;
+ const target = fileResult(
+ '/repo/a/utils.ts',
+ SupportedLanguages.TypeScript,
+ [entity('target', SupportedLanguages.TypeScript)],
+ );
+
+ expect(resolveEdges([caller, target])).toContainEqual(expect.objectContaining({
+ srcFilePath: '/repo/a/caller.ts',
+ dstFilePath: '/repo/a/utils.ts',
+ predicate: 'CALLS',
+ }));
+ });
+
+ it('does not emit a file self-edge for a relative self-import', () => {
+ const caller = parseFile(
+ '/repo/a/caller.ts',
+ 'import "./caller";\nexport function caller() {}\n',
+ )!;
+
+ expect(resolveEdges([caller])).toEqual([]);
+ });
+
+ it.runIf(process.platform === 'win32')('matches relative paths case-insensitively on Windows', () => {
+ const caller = parseFile(
+ 'repo\\a\\caller.ts',
+ 'import { target } from "./Utils";\nexport function caller() { return target(); }\n',
+ )!;
+ const target = fileResult(
+ 'repo\\a\\utils.ts',
+ SupportedLanguages.TypeScript,
+ [entity('target', SupportedLanguages.TypeScript)],
+ );
+
+ expect(resolveEdges([caller, target])).toContainEqual(expect.objectContaining({
+ srcFilePath: 'repo\\a\\caller.ts',
+ dstFilePath: 'repo\\a\\utils.ts',
+ predicate: 'CALLS',
+ }));
+ });
+
+ it('does not fall back to an unrelated same-stem file when the relative target is missing', () => {
+ const caller = parseFile(
+ '/repo/a/caller.ts',
+ 'import { target } from "./utils";\nexport function caller() { return target(); }\n',
+ )!;
+ const unrelatedUtils = fileResult(
+ '/repo/b/utils.ts',
+ SupportedLanguages.TypeScript,
+ [entity('target', SupportedLanguages.TypeScript)],
+ );
+
+ expect(resolveEdges([caller, unrelatedUtils])).toEqual([]);
+ });
+
+ it('resolves a relative import to a directory index', () => {
+ const caller = fileResult(
+ '/repo/a/caller.ts',
+ SupportedLanguages.TypeScript,
+ [entity('caller', SupportedLanguages.TypeScript)],
+ [
+ { srcName: 'caller.ts', dstName: 'services', predicate: 'IMPORTS', importRaw: './services' },
+ { srcName: 'caller', dstName: 'target', predicate: 'CALLS' },
+ ],
+ );
+ const index = fileResult(
+ '/repo/a/services/index.ts',
+ SupportedLanguages.TypeScript,
+ [entity('target', SupportedLanguages.TypeScript)],
+ );
+ const collision = fileResult(
+ '/repo/b/services/index.ts',
+ SupportedLanguages.TypeScript,
+ [entity('target', SupportedLanguages.TypeScript)],
+ );
+
+ expect(resolveEdges([caller, index, collision])).toContainEqual({
+ srcFilePath: '/repo/a/caller.ts',
+ srcName: 'caller',
+ dstFilePath: '/repo/a/services/index.ts',
+ dstName: 'target',
+ dstQualifiedKey: 'target',
+ predicate: 'CALLS',
+ confidence: 0.9,
+ });
+ });
+
+ it('prefers a direct TypeScript module over its directory index', () => {
+ const caller = parseFile(
+ '/repo/a/caller.ts',
+ 'import { target } from "./services";\nexport function caller() { return target(); }\n',
+ )!;
+ const direct = fileResult(
+ '/repo/a/services.ts',
+ SupportedLanguages.TypeScript,
+ [entity('target', SupportedLanguages.TypeScript)],
+ );
+ const index = fileResult(
+ '/repo/a/services/index.ts',
+ SupportedLanguages.TypeScript,
+ [entity('target', SupportedLanguages.TypeScript)],
+ );
+
+ const resolved = resolveEdges([caller, direct, index]);
+ expect(resolved).toContainEqual({
+ srcFilePath: '/repo/a/caller.ts',
+ srcName: 'caller',
+ dstFilePath: '/repo/a/services.ts',
+ dstName: 'target',
+ dstQualifiedKey: 'target',
+ predicate: 'CALLS',
+ confidence: 0.9,
+ });
+ expect(resolved.some(edge => edge.dstFilePath === '/repo/a/services/index.ts')).toBe(false);
+ });
+
+ it('uses a Python relative import path to disambiguate duplicate modules', () => {
+ const caller = parseFile(
+ '/repo/pkg/a/caller.py',
+ 'from .utils import target\n\ndef caller():\n return target()\n',
+ )!;
+ const localUtils = fileResult(
+ '/repo/pkg/a/utils.py',
+ SupportedLanguages.Python,
+ [entity('target', SupportedLanguages.Python)],
+ );
+ const unrelatedUtils = fileResult(
+ '/repo/pkg/b/utils.py',
+ SupportedLanguages.Python,
+ [entity('target', SupportedLanguages.Python)],
+ );
+
+ expect(resolveEdges([caller, localUtils, unrelatedUtils])).toContainEqual({
+ srcFilePath: '/repo/pkg/a/caller.py',
+ srcName: 'caller',
+ dstFilePath: '/repo/pkg/a/utils.py',
+ dstName: 'target',
+ dstQualifiedKey: 'target',
+ predicate: 'CALLS',
+ confidence: 0.9,
+ });
+ });
+
+ it('resolves a Python from-dot import to the local module', () => {
+ const caller = parseFile(
+ '/repo/pkg/a/caller.py',
+ 'from . import utils\n\ndef caller():\n return utils.target()\n',
+ )!;
+ const localUtils = fileResult(
+ '/repo/pkg/a/utils.py',
+ SupportedLanguages.Python,
+ [entity('target', SupportedLanguages.Python)],
+ );
+ const unrelatedUtils = fileResult(
+ '/repo/pkg/b/utils.py',
+ SupportedLanguages.Python,
+ [entity('target', SupportedLanguages.Python)],
+ );
+
+ expect(resolveEdges([caller, localUtils, unrelatedUtils])).toContainEqual({
+ srcFilePath: '/repo/pkg/a/caller.py',
+ srcName: 'caller',
+ dstFilePath: '/repo/pkg/a/utils.py',
+ dstName: 'target',
+ dstQualifiedKey: 'target',
+ predicate: 'CALLS',
+ confidence: 0.9,
+ });
+ });
+
+ it('resolves a Python relative import through its local alias', () => {
+ const caller = parseFile(
+ '/repo/pkg/a/caller.py',
+ 'from .utils import target as local\n\ndef caller():\n return local()\n',
+ )!;
+ const localUtils = fileResult(
+ '/repo/pkg/a/utils.py',
+ SupportedLanguages.Python,
+ [entity('target', SupportedLanguages.Python)],
+ );
+ const unrelatedLocal = fileResult(
+ '/repo/other/local.py',
+ SupportedLanguages.Python,
+ [entity('local', SupportedLanguages.Python)],
+ );
+
+ const resolved = resolveEdges([caller, localUtils, unrelatedLocal]);
+ expect(resolved).toContainEqual(expect.objectContaining({
+ srcFilePath: '/repo/pkg/a/caller.py',
+ srcName: 'caller',
+ dstFilePath: '/repo/pkg/a/utils.py',
+ dstName: 'local',
+ dstQualifiedKey: 'target',
+ predicate: 'CALLS',
+ confidence: 0.9,
+ }));
+ expect(resolved.some(edge => edge.dstFilePath === '/repo/other/local.py')).toBe(false);
+ });
+
+ it('does not globally resolve a missing Python relative import when other imports exist', () => {
+ const caller = parseFile(
+ '/repo/pkg/a/caller.py',
+ 'from .missing import target\nimport os\n\ndef caller():\n return target()\n',
+ )!;
+ const unrelatedTarget = fileResult(
+ '/repo/other/target.py',
+ SupportedLanguages.Python,
+ [entity('target', SupportedLanguages.Python)],
+ );
+
+ expect(resolveEdges([caller, unrelatedTarget])).toEqual([]);
+ });
+
+ it('keeps a Python imported symbol scoped to its relative module', () => {
+ const caller = fileResult(
+ '/repo/pkg/a/caller.py',
+ SupportedLanguages.Python,
+ [entity('caller', SupportedLanguages.Python)],
+ [
+ { srcName: 'caller.py', dstName: 'utils', predicate: 'IMPORTS', importRaw: '.utils' },
+ { srcName: 'caller.py', dstName: 'target', predicate: 'IMPORTS' },
+ { srcName: 'caller', dstName: 'target', predicate: 'CALLS' },
+ ],
+ );
+ const localUtils = fileResult(
+ '/repo/pkg/a/utils.py',
+ SupportedLanguages.Python,
+ [entity('target', SupportedLanguages.Python)],
+ );
+ const unrelatedTarget = fileResult(
+ '/repo/other/target.py',
+ SupportedLanguages.Python,
+ [entity('target', SupportedLanguages.Python)],
+ );
+
+ expect(resolveEdges([caller, localUtils, unrelatedTarget])).toContainEqual({
+ srcFilePath: '/repo/pkg/a/caller.py',
+ srcName: 'caller',
+ dstFilePath: '/repo/pkg/a/utils.py',
+ dstName: 'target',
+ dstQualifiedKey: 'target',
+ predicate: 'CALLS',
+ confidence: 0.9,
+ });
+ });
+
+ it('resolves a parent-relative Python import from its package path', () => {
+ const caller = fileResult(
+ '/repo/pkg/sub/caller.py',
+ SupportedLanguages.Python,
+ [entity('caller', SupportedLanguages.Python)],
+ [
+ { srcName: 'caller.py', dstName: 'shared.utils', predicate: 'IMPORTS', importRaw: '..shared.utils' },
+ { srcName: 'caller', dstName: 'target', predicate: 'CALLS' },
+ ],
+ );
+ const target = fileResult(
+ '/repo/pkg/shared/utils.py',
+ SupportedLanguages.Python,
+ [entity('target', SupportedLanguages.Python)],
+ );
+ const collision = fileResult(
+ '/repo/other/shared/utils.py',
+ SupportedLanguages.Python,
+ [entity('target', SupportedLanguages.Python)],
+ );
+
+ expect(resolveEdges([caller, target, collision])).toContainEqual({
+ srcFilePath: '/repo/pkg/sub/caller.py',
+ srcName: 'caller',
+ dstFilePath: '/repo/pkg/shared/utils.py',
+ dstName: 'target',
+ dstQualifiedKey: 'target',
+ predicate: 'CALLS',
+ confidence: 0.9,
+ });
+ });
+
+ it('uses relative paths when candidates come from the global index', () => {
+ const caller = parseFile(
+ '/repo/a/caller.ts',
+ 'import { target } from "./utils";\nexport function caller() { return target(); }\n',
+ )!;
+ const localPath = '/repo/a/utils.ts';
+ const unrelatedPath = '/repo/b/utils.ts';
+ const globalIndex = buildGlobalResolutionIndex(
+ [localPath, unrelatedPath],
+ new Map([
+ [localPath, 'export function target() { return 1; }\n'],
+ [unrelatedPath, 'export function target() { return 2; }\n'],
+ ]),
+ );
+
+ expect(resolveEdges([caller], undefined, globalIndex)).toContainEqual({
+ srcFilePath: '/repo/a/caller.ts',
+ srcName: 'caller',
+ dstFilePath: '/repo/a/utils.ts',
+ dstName: 'target',
+ dstQualifiedKey: 'target',
+ predicate: 'CALLS',
+ confidence: 0.9,
+ });
+ });
+
+ it('does not use path narrowing for bare module imports', () => {
+ const caller = fileResult(
+ '/repo/a/caller.ts',
+ SupportedLanguages.TypeScript,
+ [entity('caller', SupportedLanguages.TypeScript)],
+ [
+ { srcName: 'caller.ts', dstName: 'utils', predicate: 'IMPORTS', importRaw: 'utils' },
+ { srcName: 'caller', dstName: 'target', predicate: 'CALLS' },
+ ],
+ );
+ const first = fileResult(
+ '/repo/a/utils.ts',
+ SupportedLanguages.TypeScript,
+ [entity('target', SupportedLanguages.TypeScript)],
+ );
+ const second = fileResult(
+ '/repo/b/utils.ts',
+ SupportedLanguages.TypeScript,
+ [entity('target', SupportedLanguages.TypeScript)],
+ );
+
+ expect(resolveEdges([caller, first, second])).toEqual([]);
+ });
+
it('resolves tier-2.5 transitive imports', () => {
const caller = fileResult(
'/repo/consumer.ts',
diff --git a/core-ingestion/src/index.ts b/core-ingestion/src/index.ts
index b4e17505..545419ef 100644
--- a/core-ingestion/src/index.ts
+++ b/core-ingestion/src/index.ts
@@ -175,7 +175,7 @@ export interface ParsedRelationship {
}
/**
- * A single named/default import binding in a JS/TS file: the in-file local name
+ * A single named/default import binding: the in-file local name
* mapped to the PUBLIC symbol it refers to in the source package. `imported` is
* the public export name ("default" for a default import). Lets a consumer's
* call to the LOCAL name (e.g. `fmt()` from `import { format as fmt }`) be
@@ -205,7 +205,7 @@ export interface FileParseResult {
chunks: ParsedChunk[];
relationships: ParsedRelationship[];
importAliases?: Record<string, string>;
- /** JS/TS named/default import bindings (local → public symbol). */
+ /** Named/default import bindings (local → public symbol). */
importBindings?: ImportBinding[];
/** JS/TS provider-side aliased/default public export names. */
exportPublicNames?: ExportPublicName[];
@@ -2291,6 +2291,18 @@ export function parseFile(filePath: string, source: string): FileParseResult | n
if (importName) {
const name = importName.node.text;
if (name && name !== '*' && name.length > 1) {
+ const rawModule = match.captures.find((c: any) => c.name === 'import.module')?.node.text;
+ if (language === SupportedLanguages.Python && rawModule) {
+ const local = match.captures.find((c: any) => c.name === 'import.local')?.node.text ?? name;
+ const dotsOnly = /^\.+$/.test(rawModule);
+ const pkg = dotsOnly ? `${rawModule}${name}` : rawModule;
+ importBindings.push({ pkg, local, imported: name });
+ if (dotsOnly) {
+ entities.push({ name, kind: 'module', lineStart: importName.node.startPosition.row + 1, lineEnd: importName.node.startPosition.row + 1, language });
+ relationships.push({ srcName: fileName, dstName: name, predicate: 'IMPORTS', importRaw: pkg });
+ continue;
+ }
+ }
entities.push({ name, kind: 'module', lineStart: importName.node.startPosition.row + 1, lineEnd: importName.node.startPosition.row + 1, language });
relationships.push({ srcName: fileName, dstName: name, predicate: 'IMPORTS' });
}
@@ -2961,9 +2973,18 @@ export function resolveEdges(
// imports (imported == "default" is not a by-name symbol in the provider; those are
// handled in the cross-repo stitch path) and no-op named imports (local == imported).
const callBindings = new Map<string, Map<string, string>>();
+ const relativeCallBindings = new Map<string, Set<string>>();
for (const r of results) {
if (!r.importBindings) continue;
for (const b of r.importBindings) {
+ if (
+ b.pkg.startsWith('./') || b.pkg.startsWith('../') ||
+ (r.language === SupportedLanguages.Python && b.pkg.startsWith('.'))
+ ) {
+ let bindings = relativeCallBindings.get(r.filePath);
+ if (!bindings) { bindings = new Set(); relativeCallBindings.set(r.filePath, bindings); }
+ bindings.add(b.local);
+ }
if (b.imported === 'default' || b.local === b.imported) continue;
let m = callBindings.get(r.filePath);
if (!m) { m = new Map(); callBindings.set(r.filePath, m); }
@@ -3141,6 +3162,27 @@ export function resolveEdges(
}
}
+ // Relative imports must be resolved against the importing file's directory.
+ // Keep a normalized path lookup so they do not fall back to a same-named file
+ // elsewhere in the repository.
+ const normalizedPathToFiles = new Map<string, string[]>();
+ const normalizedPathKey = (filePath: string): string => {
+ const normalized = nodePath.posix.normalize(filePath.replace(/\\/g, '/'));
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
+ };
+ const addIndexedPath = (filePath: string): void => {
+ const normalized = normalizedPathKey(filePath);
+ const files = normalizedPathToFiles.get(normalized) ?? [];
+ if (!files.includes(filePath)) files.push(filePath);
+ normalizedPathToFiles.set(normalized, files);
+ };
+ for (const files of stemToFiles.values()) {
+ for (const filePath of files) addIndexedPath(filePath);
+ }
+ for (const files of dirToIndexFiles.values()) {
+ for (const filePath of files) addIndexedPath(filePath);
+ }
+
// packageToFiles: seed from global index, then add batch entries.
// e.g. "ix.memory.model" → all .scala files under .../ix/memory/model/
const packageToFiles = globalIndex
@@ -3338,12 +3380,101 @@ export function resolveEdges(
return langFamily(src) === langFamily(dst);
};
- function resolveImportTargets(srcFilePath: string, srcLanguage: SupportedLanguages, modName: unknown): string[] {
+ function relativeImportTarget(srcFilePath: string, srcLanguage: SupportedLanguages, importRaw: unknown): string | null {
+ if (typeof importRaw !== 'string') return null;
+ const sourceDir = nodePath.posix.dirname(srcFilePath.replace(/\\/g, '/'));
+
+ if (
+ (srcLanguage === SupportedLanguages.JavaScript || srcLanguage === SupportedLanguages.TypeScript) &&
+ (importRaw.startsWith('./') || importRaw.startsWith('../'))
+ ) {
+ // Bundlers use query/hash suffixes to select loaders or virtual variants;
+ // the on-disk module path is the portion before that URL metadata.
+ const queryIndex = importRaw.indexOf('?');
+ const fragmentIndex = importRaw.indexOf('#');
+ const suffixIndex = queryIndex === -1
+ ? fragmentIndex
+ : fragmentIndex === -1 ? queryIndex : Math.min(queryIndex, fragmentIndex);
+ const pathSpecifier = suffixIndex === -1 ? importRaw : importRaw.slice(0, suffixIndex);
+ return nodePath.posix.normalize(nodePath.posix.join(sourceDir, pathSpecifier));
+ }
+
+ if (srcLanguage === SupportedLanguages.Python && importRaw.startsWith('.')) {
+ const dots = importRaw.match(/^\.+/)?.[0].length ?? 0;
+ let packageDir = sourceDir;
+ for (let i = 1; i < dots; i++) packageDir = nodePath.posix.dirname(packageDir);
+ const modulePath = importRaw.slice(dots).replace(/\./g, '/');
+ return nodePath.posix.normalize(nodePath.posix.join(packageDir, modulePath));
+ }
+
+ return null;
+ }
+
+ function resolveRelativeImportTargets(
+ srcFilePath: string,
+ srcLanguage: SupportedLanguages,
+ importRaw: unknown,
+ ): string[] | null {
+ const target = relativeImportTarget(srcFilePath, srcLanguage, importRaw);
+ if (target === null) return null;
+
+ const candidatePaths: string[] = [];
+ if (srcLanguage === SupportedLanguages.Python) {
+ if (target.endsWith('.py')) {
+ candidatePaths.push(target);
+ } else {
+ candidatePaths.push(nodePath.posix.join(target, '__init__.py'), `${target}.py`);
+ }
+ } else {
+ const extension = nodePath.posix.extname(target).toLowerCase();
+ const base = extension.length > 0 ? target.slice(0, -extension.length) : target;
+ const addSourceVariants = (pathBase: string): void => {
+ const suffixes = srcLanguage === SupportedLanguages.JavaScript
+ ? ['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx', '.d.ts']
+ : ['.ts', '.tsx', '.d.ts', '.js', '.jsx', '.mjs', '.cjs'];
+ for (const suffix of suffixes) {
+ candidatePaths.push(`${pathBase}${suffix}`);
+ }
+ };
+
+ if (extension.length === 0) {
+ addSourceVariants(target);
+ addSourceVariants(nodePath.posix.join(target, 'index'));
+ } else if (extension === '.js') {
+ const suffixes = srcLanguage === SupportedLanguages.JavaScript
+ ? ['.js', '.ts', '.tsx', '.d.ts']
+ : ['.ts', '.tsx', '.d.ts', '.js'];
+ for (const suffix of suffixes) candidatePaths.push(`${base}${suffix}`);
+ } else if (extension === '.jsx') {
+ const suffixes = srcLanguage === SupportedLanguages.JavaScript
+ ? ['.jsx', '.tsx', '.d.ts']
+ : ['.tsx', '.d.ts', '.jsx'];
+ for (const suffix of suffixes) candidatePaths.push(`${base}${suffix}`);
+ } else {
+ candidatePaths.push(target);
+ }
+ }
+
+ for (const candidatePath of candidatePaths) {
+ const matches = (normalizedPathToFiles.get(normalizedPathKey(candidatePath)) ?? [])
+ .filter(filePath => normalizedPathKey(filePath) !== normalizedPathKey(srcFilePath));
+ if (matches.length > 0) return matches;
+ }
+ return [];
+ }
+
+ function resolveImportTargets(
+ srcFilePath: string,
+ srcLanguage: SupportedLanguages,
+ modName: unknown,
+ importRaw?: unknown,
+ ): string[] {
// fileLanguage only covers the current parse batch; cross-batch candidates
// come from the global stem index, so fall back to the extension-derived
// language (always available) — otherwise an undefined dst language would
// slip cross-language matches (e.g. a Python import -> a Rust/Elixir file).
- const importMatches = modNameToFiles(modName, srcFilePath)
+ const importMatches = (resolveRelativeImportTargets(srcFilePath, srcLanguage, importRaw) ??
+ modNameToFiles(modName, srcFilePath))
.filter(fp => importLanguageCompatible(srcLanguage, fileLanguage.get(fp) ?? languageFromPath(fp)));
if (srcLanguage !== SupportedLanguages.Go || importMatches.length <= 1) return importMatches;
return narrowGoImportCandidates(srcFilePath, modName, importMatches, files => {
@@ -3490,12 +3621,15 @@ export function resolveEdges(
const srcFilePath = result.filePath;
const srcLanguage = result.language;
const srcSymbols = fileHasSymbol.get(srcFilePath)!;
+ const pythonHasRelativeModuleImport = srcLanguage === SupportedLanguages.Python &&
+ result.relationships.some(rel => rel.predicate === 'IMPORTS' && rel.importRaw?.startsWith('.'));
// Build the set of file paths this file explicitly imports.
const importedFilePaths = new Set<string>();
for (const rel of result.relationships) {
if (rel.predicate !== 'IMPORTS') continue;
- for (const fp of resolveImportTargets(srcFilePath, srcLanguage, rel.dstName)) {
+ if (pythonHasRelativeModuleImport && rel.importRaw === undefined) continue;
+ for (const fp of resolveImportTargets(srcFilePath, srcLanguage, rel.dstName, rel.importRaw)) {
importedFilePaths.add(fp);
}
}
@@ -3508,7 +3642,7 @@ export function resolveEdges(
if (!fpResult) continue;
for (const rel of fpResult.relationships) {
if (rel.predicate !== 'IMPORTS') continue;
- for (const transitiveFp of resolveImportTargets(fp, fpResult.language, rel.dstName)) {
+ for (const transitiveFp of resolveImportTargets(fp, fpResult.language, rel.dstName, rel.importRaw)) {
if (!importedFilePaths.has(transitiveFp)) transitiveFilePaths.add(transitiveFp);
}
}
@@ -3545,7 +3679,9 @@ export function resolveEdges(
}
}
- const importMatches = resolveImportTargets(srcFilePath, result.language, rel.dstName);
+ const importMatches = pythonHasRelativeModuleImport && rel.importRaw === undefined
+ ? []
+ : resolveImportTargets(srcFilePath, result.language, rel.dstName, rel.importRaw);
if (importMatches.length === 1) {
const fp = importMatches[0];
resolved.push({
@@ -3572,7 +3708,7 @@ export function resolveEdges(
// import specifier IS the dependency. Down-weighted by G3 at the map layer;
// the post-resolution dep gate keeps it (the same import seeds repoDeps).
// No-op for single-repo (no repoOf/entryFileOf).
- if (repoOf && packageOf && entryFileOf) {
+ if (repoOf && packageOf && entryFileOf && !(pythonHasRelativeModuleImport && rel.importRaw === undefined)) {
const srcRepo = repoOf(srcFilePath);
const mod = typeof rel.importRaw === 'string' ? rel.importRaw : rel.dstName;
const depRepo = mod ? packageOf(mod) : undefined;
@@ -3711,6 +3847,10 @@ export function resolveEdges(
resolved.push({ srcFilePath, srcName, dstFilePath: fp, dstName: origDstName, dstQualifiedKey, predicate: rel.predicate, confidence: 0.8 });
continue;
}
+ if (rel.predicate === 'CALLS' && relativeCallBindings.get(srcFilePath)?.has(origDstName)) {
+ stats.skippedAmbiguous++;
+ continue;
+ }
// Tier 3: global fallback (confidence 0.5) — uses inverted symbol index
// instead of scanning all files.
// Skip for C/C++ REFERENCES: struct/type references that don't resolve via the
diff --git a/core-ingestion/src/queries.ts b/core-ingestion/src/queries.ts
index ad3d95f3..261032ad 100644
--- a/core-ingestion/src/queries.ts
+++ b/core-ingestion/src/queries.ts
@@ -213,15 +213,27 @@ export const PYTHON_QUERIES = `
; from . import utils / from .models import User — capture imported symbol names (relative imports)
(import_from_statement
- module_name: (relative_import)
+ module_name: (relative_import) @import.module
name: (dotted_name (identifier) @import.name)) @import.names
+(import_from_statement
+ module_name: (relative_import) @import.module
+ name: (aliased_import
+ name: (dotted_name (identifier) @import.name)
+ alias: (identifier) @import.local)) @import.names
+
; from module import Class — capture imported symbol names (absolute imports)
; e.g. from sqlalchemy.sql.schema import Column → import.name = Column
(import_from_statement
- module_name: (dotted_name)
+ module_name: (dotted_name) @import.module
name: (dotted_name (identifier) @import.name)) @import.names
+(import_from_statement
+ module_name: (dotted_name) @import.module
+ name: (aliased_import
+ name: (dotted_name (identifier) @import.name)
+ alias: (identifier) @import.local)) @import.names
+
(call
function: (identifier) @call.name) @call