Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
fix(ingest): resolve a package's imports of itself by its package.json
KageBinary2f98ca62676c
diff --git a/core-ingestion/src/__tests__/resolveEdges.scope.test.ts b/core-ingestion/src/__tests__/resolveEdges.scope.test.tsindex 99b06c22..9a18c349 100644--- a/core-ingestion/src/__tests__/resolveEdges.scope.test.ts+++ b/core-ingestion/src/__tests__/resolveEdges.scope.test.ts@@ -207,6 +207,32 @@ describe('call resolution respects lexical scope (JS/TS)', () => {]);});+ it('resolves a library\'s own tests importing it by package name', () => {+ // No directory is called `mylib`, so only the package.json declaration can+ // place it: the root declares it here, packages/tools declares another.+ const test = parse(+ 'test/parse.test.ts',+ 'import { parse } from "mylib";\nimport { lint } from "mylib-tools/lint";\nexport function t() { parse(); lint(); }\n',+ );+ const lib = parse('src/parse.ts', 'export function parse() { return 1; }\n');+ const tools = parse('packages/tools/src/lint.ts', 'export function lint() { return 1; }\n');+ const dirs = new Map([['mylib', ''], ['mylib-tools', 'packages/tools']]);++ expect(callsTo(resolveEdges([test, lib, tools]), 'src/parse.ts'), 'the directory-name guess alone').toEqual([]);+ const edges = resolveEdges([test, lib, tools], undefined, undefined, { packageDirOf: name => dirs.get(name) });+ expect(callsTo(edges, 'src/parse.ts')).toEqual([expect.objectContaining({ dstName: 'parse' })]);+ expect(callsTo(edges, 'packages/tools/src/lint.ts')).toEqual([expect.objectContaining({ dstName: 'lint' })]);+ });++ it('keeps a declared package\'s names inside its own directory', () => {+ const caller = parse('app/main.ts', 'import { parse } from "mylib-tools";\nexport function main() { return parse(); }\n');+ const elsewhere = parse('src/parse.ts', 'export function parse() { return 1; }\n');+ const dirs = new Map([['mylib-tools', 'packages/tools']]);++ const edges = resolveEdges([caller, elsewhere], undefined, undefined, { packageDirOf: name => dirs.get(name) });+ expect(callsTo(edges, 'src/parse.ts')).toEqual([]);+ });+it('leaves non-JS languages on name-based resolution', () => {const caller = parse('app/main.py', 'def main():\n return helper_fn()\n');const target = parse('lib/helpers.py', 'def helper_fn():\n return 1\n');diff --git a/core-ingestion/src/index.ts b/core-ingestion/src/index.tsindex 118ce600..a4d367cd 100644--- a/core-ingestion/src/index.ts+++ b/core-ingestion/src/index.ts@@ -3781,7 +3781,20 @@ function isBarePackageSpecifier(spec: string): boolean {* `.../utils/...`) or its unscoped monorepo spelling (`@babel/types` ->* `.../babel-types/...`). Node builtins (`node:fs`) are never in-repo.*/-function fileIsInsidePackage(filePath: string, spec: string): boolean {+function fileIsInsidePackage(+ filePath: string,+ spec: string,+ packageDirOf?: (packageName: string) => string | undefined,+): boolean {+ // A package this repo declares (its tracked package.json names it) is+ // exactly that directory, whatever it is called: a library's own tests+ // import it by name (`from "mylib"`) from a folder no directory name+ // matches. The directory-name guess below is for everything else.+ const declared = packageDirOf?.(packageNameOf(spec));+ if (declared !== undefined) {+ const file = filePath.replace(/\\/g, '/');+ return declared === '' || file.startsWith(`${declared}/`);+ }if (spec.startsWith('node:')) return false;const parts = spec.split('/');const scope = spec.startsWith('@') ? parts[0].slice(1) : undefined;@@ -3791,6 +3804,12 @@ function fileIsInsidePackage(filePath: string, spec: string): boolean {return dirs.includes(name) || (scope !== undefined && dirs.includes(`${scope}-${name}`));}+/** The package part of a bare specifier: `@acme/utils/dates` -> `@acme/utils`, `lodash/fp` -> `lodash`. */+function packageNameOf(spec: string): string {+ const parts = spec.split('/');+ return spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];+}+// A symbol defined in this many or more distinct files across the resolution// set is a project-level commodity; a single narrowed fuzzy-tier match for it is// not trustworthy. (Tunable; the named-list above carries the builtin-method load.)@@ -3844,6 +3863,9 @@ export function resolveEdges(// cross-repo gate so genuine edges survive even where import-to-package matching// can't bridge the gap (e.g. Java's Maven artifactId vs `import com.google...`).declaredRepoDeps?: Record<string, string[]>;+ // JS/TS package name -> the directory (workspace-relative, POSIX, '' for+ // the root) whose package.json declares it, when exactly one does.+ packageDirOf?: (packageName: string) => string | undefined;// Workspace-aware JS/TS module resolution supplied by the CLI. `undefined`// preserves the existing fallback; an empty array is authoritative and// prevents a configured import from falling through to an unrelated stem.@@ -4954,7 +4976,7 @@ export function resolveEdges(const insideBoundPackage = (fp: string): boolean => {if (boundPackage === undefined) return true;if (boundPackageRepo !== undefined && repoOf) return repoOf(fp) === boundPackageRepo;- return fileIsInsidePackage(fp, boundPackage);+ return fileIsInsidePackage(fp, boundPackage, opts?.packageDirOf);};const reachable = (fp: string): boolean =>(!bareCall || definesAtModuleScope(fp)) && insideBoundPackage(fp);diff --git a/ix-cli/src/cli/__tests__/package-dirs.test.ts b/ix-cli/src/cli/__tests__/package-dirs.test.tsnew file mode 100644index 00000000..49803773--- /dev/null+++ b/ix-cli/src/cli/__tests__/package-dirs.test.ts@@ -0,0 +1,56 @@+// Copyright 2026 Ix Infrastructure Inc.++import { afterEach, beforeEach, describe, expect, it } from "vitest";+import * as fs from "node:fs";+import * as os from "node:os";+import * as path from "node:path";++import { declaredPackageDirs } from "../package-dirs.js";++let root: string;++function write(rel: string, content: string): string {+ const file = path.join(root, rel);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, content);+ return file;+}++beforeEach(() => {+ root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "ix-package-dirs-")));+});++afterEach(() => {+ fs.rmSync(root, { recursive: true, force: true });+});++describe("declaredPackageDirs", () => {+ it("maps each declared package to its directory, the root as ''", () => {+ write("package.json", JSON.stringify({ name: "mylib" }));+ write("packages/tools/package.json", JSON.stringify({ name: "@acme/tools" }));+ const files = [write("src/a.ts", ""), write("packages/tools/src/deep/b.ts", "")];++ const dirOf = declaredPackageDirs(root, files);+ expect(dirOf("mylib")).toBe("");+ expect(dirOf("@acme/tools")).toBe("packages/tools");+ expect(dirOf("lodash")).toBeUndefined();+ });++ it("leaves out a name two package.json files declare", () => {+ write("a/package.json", JSON.stringify({ name: "dup" }));+ write("b/package.json", JSON.stringify({ name: "dup" }));+ const dirOf = declaredPackageDirs(root, [write("a/x.js", ""), write("b/y.js", "")]);+ expect(dirOf("dup")).toBeUndefined();+ });++ it("reads only directories holding JS/TS files, and nothing above the root", () => {+ write("py/package.json", JSON.stringify({ name: "py-only" }));+ const inner = path.join(root, "inner");+ write("inner/broken/package.json", "{ not json");+ write("inner/package.json", JSON.stringify({ name: "inner" }));+ const dirOf = declaredPackageDirs(inner, [write("py/main.py", ""), write("inner/broken/c.mts", ""), write("inner/d.tsx", "")]);+ expect(dirOf("py-only")).toBeUndefined();+ expect(dirOf("inner")).toBe("");+ expect(dirOf("{ not json")).toBeUndefined();+ });+});diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.tsindex 93b8c63a..3ddfaddd 100644--- a/ix-cli/src/cli/commands/ingest.ts+++ b/ix-cli/src/cli/commands/ingest.ts@@ -17,6 +17,7 @@ import { extractorChanged, isRev, loadIngestBaseline, saveIngestBaseline } fromimport { resolveGitHubToken } from '../github/auth.js';import { parseGitHubRepo, fetchGitHubData } from '../github/fetch.js';import { loadIngestionModules } from './ingestion-loader.js';+import { declaredPackageDirs } from '../package-dirs.js';import { ensureWorkspaceIdState } from '../bootstrap.js';import { detectSystem, repoWorkspaceIdFor, lookupPackage, readPackageNames, readPackageDeps } from '../system.js';import { CLIENT_EXPECTED_SCHEMA_VERSION } from '../backend-status.js';@@ -1919,6 +1920,7 @@ export async function ingestFiles(const resolveOpts = {...crossRepoResolveOpts,resolveModuleSpecifier: createTypeScriptModuleResolver(workspaceRoot, filePaths),+ packageDirOf: declaredPackageDirs(workspaceRoot, filePaths),};filesDiscovered = filePaths.length;diff --git a/ix-cli/src/cli/package-dirs.ts b/ix-cli/src/cli/package-dirs.tsnew file mode 100644index 00000000..ef27fbf4--- /dev/null+++ b/ix-cli/src/cli/package-dirs.ts@@ -0,0 +1,52 @@+// Copyright 2026 Ix Infrastructure Inc.++import * as fs from "node:fs";+import * as nodePath from "node:path";++const JS_TS_FILE = /\.[cm]?[jt]sx?$/i;++/**+ * JS/TS package name -> the workspace-relative POSIX directory ('' for the+ * root) whose package.json declares it, for core-ingestion's `packageDirOf`.+ *+ * Call resolution only follows a bare import (`from "mylib"`) into files that+ * belong to that package. Without this it can only guess from directory names,+ * and a library's own tests importing it by name from a folder called anything+ * else lost every edge.+ *+ * Reads the package.json of each directory holding an ingested JS/TS file and+ * of its ancestors up to the workspace root, each directory once. A name that+ * two package.json files declare (a fixture copy, a vendored duplicate) is left+ * out, and the resolver falls back to its directory-name guess for it.+ */+export function declaredPackageDirs(+ workspaceRoot: string,+ absoluteFilePaths: string[],+): (packageName: string) => string | undefined {+ const root = nodePath.resolve(workspaceRoot);+ const visited = new Set<string>();+ const dirs = new Map<string, string | null>();+ for (const file of absoluteFilePaths) {+ if (!JS_TS_FILE.test(file)) continue;+ let dir = nodePath.dirname(nodePath.resolve(file));+ while (!visited.has(dir)) {+ visited.add(dir);+ const rel = nodePath.relative(root, dir);+ if (rel === ".." || rel.startsWith(`..${nodePath.sep}`) || nodePath.isAbsolute(rel)) break;+ const name = readPackageName(dir);+ if (name !== undefined) dirs.set(name, dirs.has(name) ? null : rel.split(nodePath.sep).join("/"));+ if (dir === root) break;+ dir = nodePath.dirname(dir);+ }+ }+ return (packageName) => dirs.get(packageName) ?? undefined;+}++function readPackageName(dir: string): string | undefined {+ try {+ const name = (JSON.parse(fs.readFileSync(nodePath.join(dir, "package.json"), "utf8")) as { name?: unknown }).name;+ return typeof name === "string" && name.trim() ? name.trim() : undefined;+ } catch {+ return undefined;+ }+}