Skip to content

armgit / Ix

Public Imported from GitHub
0

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

Multi-repo gate precision: airtight dependency gate + node:/Rust/Java fixes (Ix#225 Path 1) (#239)

Joseph Mikhail8674fc058e77
diff --git a/core-ingestion/src/__tests__/queries.go.test.ts b/core-ingestion/src/__tests__/queries.go.test.ts
index 5eec51c0..b1f847a8 100644
--- a/core-ingestion/src/__tests__/queries.go.test.ts
+++ b/core-ingestion/src/__tests__/queries.go.test.ts
@@ -37,6 +37,7 @@ func (s *Service) Run() {
srcName: 'service.go',
dstName: 'fmt',
predicate: 'IMPORTS',
+ importRaw: 'fmt',
});
});
@@ -165,6 +166,7 @@ func Run(sched *scheduler.Scheduler) error {
srcName: 'server.go',
dstName: 'k8s.io/kubernetes/pkg/scheduler',
predicate: 'IMPORTS',
+ importRaw: 'k8s.io/kubernetes/pkg/scheduler',
});
expect(result!.relationships).toContainEqual({
srcName: 'Run',
diff --git a/core-ingestion/src/__tests__/queries.python.test.ts b/core-ingestion/src/__tests__/queries.python.test.ts
index a7114b38..c8b986b9 100644
--- a/core-ingestion/src/__tests__/queries.python.test.ts
+++ b/core-ingestion/src/__tests__/queries.python.test.ts
@@ -28,6 +28,7 @@ def top_level():
srcName: 'example.py',
dstName: 'models',
predicate: 'IMPORTS',
+ importRaw: '.models',
});
expect(result!.relationships).toContainEqual({
srcName: 'example.py',
@@ -38,6 +39,7 @@ def top_level():
srcName: 'example.py',
dstName: 'package.helpers',
predicate: 'IMPORTS',
+ importRaw: 'package.helpers',
});
expect(result!.relationships).toContainEqual({
srcName: 'Service',
diff --git a/core-ingestion/src/__tests__/queries.typescript.test.ts b/core-ingestion/src/__tests__/queries.typescript.test.ts
index 9bb3ae21..29de16a3 100644
--- a/core-ingestion/src/__tests__/queries.typescript.test.ts
+++ b/core-ingestion/src/__tests__/queries.typescript.test.ts
@@ -33,6 +33,7 @@ describe('TypeScript queries', () => {
srcName: 'example.ts',
dstName: 'bar',
predicate: 'IMPORTS',
+ importRaw: './bar',
});
expect(result!.relationships).toContainEqual({
srcName: 'Example',
diff --git a/core-ingestion/src/__tests__/resolveEdges.test.ts b/core-ingestion/src/__tests__/resolveEdges.test.ts
index 649694a7..5a318884 100644
--- a/core-ingestion/src/__tests__/resolveEdges.test.ts
+++ b/core-ingestion/src/__tests__/resolveEdges.test.ts
@@ -717,4 +717,65 @@ describe('resolveEdges', () => {
expect(resolveEdges([caller, b, c])).toEqual([]);
});
+
+ // ── Multi-repo co-ingest dependency gate (Ix#225 Path 1) ──────────────────
+ // A cross-repo edge survives only when the source repo imports the target
+ // repo's package. The importRaw specifier is what lets the gate tell a relative
+ // intra-repo import (./core) apart from a package import (@acme/core) that
+ // flattens to the same stem ("core").
+ describe('multi-repo dependency gate', () => {
+ // repoOf: first path segment is the member repo (matches the CLI).
+ const repoOf = (fp: string) => fp.split('/')[0];
+ // packageOf mirrors the CLI: rejects relative specifiers; maps the full name
+ // AND the bare stem to the publishing repo.
+ const packageOf = (mod: string) => {
+ if (!mod || mod.startsWith('.') || mod.startsWith('/')) return undefined;
+ if (mod === '@acme/core' || mod === 'core') return 'repo-a';
+ return undefined;
+ };
+ const coreFile = () =>
+ fileResult('repo-a/src/core.ts', SupportedLanguages.TypeScript, [
+ entity('coreFn', SupportedLanguages.TypeScript),
+ ]);
+ const caller = (importRaw: string) =>
+ fileResult('repo-b/src/index.ts', SupportedLanguages.TypeScript,
+ [entity('run', SupportedLanguages.TypeScript)],
+ [
+ { srcName: 'run', dstName: 'coreFn', predicate: 'CALLS' },
+ { srcName: 'index.ts', dstName: 'core', predicate: 'IMPORTS', importRaw },
+ ]);
+
+ it('keeps a cross-repo edge when the import is a genuine package specifier', () => {
+ const edges = resolveEdges([caller('@acme/core'), coreFile()], undefined, undefined, { repoOf, packageOf });
+ const cross = edges.filter(e => repoOf(e.srcFilePath) !== repoOf(e.dstFilePath));
+ expect(cross.find(e => e.predicate === 'CALLS')).toMatchObject({ srcName: 'run', dstName: 'coreFn' });
+ });
+
+ it('drops the cross-repo edge when the same-stem import is relative (./core)', () => {
+ const edges = resolveEdges([caller('./core'), coreFile()], undefined, undefined, { repoOf, packageOf });
+ const cross = edges.filter(e => repoOf(e.srcFilePath) !== repoOf(e.dstFilePath));
+ expect(cross).toEqual([]);
+ });
+
+ it('keeps a cross-repo edge via the declared-dependency graph when import-matching cannot bridge it (e.g. Java artifactId vs package namespace)', () => {
+ // packageOf can never resolve the import (simulates Maven artifactId vs
+ // `import com.x.*`), but the manifest declares repo-b depends on repo-a.
+ const onlyCall = fileResult('repo-b/src/index.ts', SupportedLanguages.TypeScript,
+ [entity('run', SupportedLanguages.TypeScript)],
+ [{ srcName: 'run', dstName: 'coreFn', predicate: 'CALLS' }]);
+ const edges = resolveEdges([onlyCall, coreFile()], undefined, undefined,
+ { repoOf, packageOf: () => undefined, declaredRepoDeps: { 'repo-b': ['repo-a'] } });
+ const cross = edges.filter(e => repoOf(e.srcFilePath) !== repoOf(e.dstFilePath));
+ expect(cross.find(e => e.predicate === 'CALLS')).toMatchObject({ srcName: 'run', dstName: 'coreFn' });
+ });
+
+ it('still drops it when neither import-matching nor declared deps back the dependency', () => {
+ const onlyCall = fileResult('repo-b/src/index.ts', SupportedLanguages.TypeScript,
+ [entity('run', SupportedLanguages.TypeScript)],
+ [{ srcName: 'run', dstName: 'coreFn', predicate: 'CALLS' }]);
+ const edges = resolveEdges([onlyCall, coreFile()], undefined, undefined,
+ { repoOf, packageOf: () => undefined });
+ expect(edges.filter(e => repoOf(e.srcFilePath) !== repoOf(e.dstFilePath))).toEqual([]);
+ });
+ });
});
diff --git a/core-ingestion/src/index.ts b/core-ingestion/src/index.ts
index 8ce35a71..0e377c69 100644
--- a/core-ingestion/src/index.ts
+++ b/core-ingestion/src/index.ts
@@ -97,6 +97,13 @@ export interface ParsedRelationship {
srcName: string;
dstName: string;
predicate: string; // "CONTAINS" | "CALLS" | "IMPORTS" | "EXTENDS"
+ // For path-based IMPORTS only: the unwrapped raw import specifier exactly as
+ // written (e.g. "./core", "../util/x", "@nestjs/core", "alpha"), BEFORE it is
+ // flattened to a bare stem. The multi-repo dependency gate needs this to tell a
+ // relative intra-repo import (./core) apart from a package import (@nestjs/core)
+ // that happens to flatten to the same stem ("core"). Absent on non-import rels
+ // and on dotted/symbol imports where dstName is already the full identifier.
+ importRaw?: string;
}
export interface FileParseResult {
@@ -358,6 +365,18 @@ function normalizeCapturedImport(rawValue: string, language: SupportedLanguages)
return rawMod.replace(/^\.+/, '');
}
+/** Unwrap an import specifier's surrounding quotes/brackets WITHOUT reducing it to
+ * a stem — preserving the leading "./", "../", and "@scope/" so the multi-repo
+ * dependency gate can distinguish relative (intra-repo) from package imports.
+ * Mirrors the pre-normalization in normalizeCapturedImport, minus the stem split. */
+function unwrapImportSpecifier(rawValue: string): string {
+ return rawValue
+ .trim()
+ .replace(/\\\\/g, '/')
+ .replace(/^["'`<]/, '')
+ .replace(/[>"'`]$/, '');
+}
+
function fileEntityName(filePath: string): string {
return nodePath.basename(filePath);
}
@@ -1671,8 +1690,11 @@ export function parseFile(filePath: string, source: string): FileParseResult | n
}
}
if (modName.length > 0 && modName !== '*') {
+ // Preserve the raw specifier (./core vs @nestjs/core) for the multi-repo
+ // dependency gate; modName remains the flattened stem used everywhere else.
+ const importRaw = unwrapImportSpecifier(importSource.node.text);
entities.push({ name: modName, kind: 'module', lineStart: importSource.node.startPosition.row + 1, lineEnd: importSource.node.startPosition.row + 1, language });
- relationships.push({ srcName: fileName, dstName: modName, predicate: 'IMPORTS' });
+ relationships.push({ srcName: fileName, dstName: modName, predicate: 'IMPORTS', importRaw });
}
continue;
}
@@ -2253,6 +2275,11 @@ export function resolveEdges(
// dependency-backed). Absent (single-repo ingest) => no gating, no change.
repoOf?: (filePath: string) => string | undefined;
packageOf?: (moduleName: string) => string | undefined;
+ // Ground-truth member->member dependency graph from build manifests (npm deps,
+ // Cargo [dependencies], go.mod require, Maven <dependency>, ...). Seeds the
+ // 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[]>;
},
): ResolvedEdge[] {
// Provide a default no-op stats bag when caller passes none (backward compat).
@@ -2268,12 +2295,30 @@ export function resolveEdges(
let repoDeps: Map<string, Set<string>> | undefined;
if (repoOf && packageOf) {
repoDeps = new Map<string, Set<string>>();
+ // Seed from the ground-truth declared-dependency graph (manifest deps). This
+ // is the robust signal: it catches deps that import-matching misses (Java).
+ if (opts?.declaredRepoDeps) {
+ for (const [srcRepo, deps] of Object.entries(opts.declaredRepoDeps)) {
+ for (const depRepo of deps) {
+ if (depRepo === srcRepo) continue;
+ let set = repoDeps.get(srcRepo);
+ if (!set) { set = new Set<string>(); repoDeps.set(srcRepo, set); }
+ set.add(depRepo);
+ }
+ }
+ }
for (const r of results) {
const srcRepo = repoOf(r.filePath);
if (srcRepo === undefined) continue;
for (const rel of r.relationships) {
if (rel.predicate !== 'IMPORTS') continue;
- const mod = typeof rel.dstName === 'string' ? rel.dstName : '';
+ // Prefer the raw specifier when the parser preserved it: a relative import
+ // (./x, ../x) is intra-repo by construction and can NEVER denote another
+ // repo's package, so packageOf rejects it and it seeds no cross-repo dep.
+ // Only bare/package specifiers (@scope/name, name) can. Falls back to the
+ // flattened stem for imports without a raw specifier (no behavior change).
+ const mod = typeof rel.importRaw === 'string' ? rel.importRaw
+ : typeof rel.dstName === 'string' ? rel.dstName : '';
const depRepo = mod ? packageOf(mod) : undefined;
if (depRepo !== undefined && depRepo !== srcRepo) {
let set = repoDeps.get(srcRepo);
diff --git a/ix-cli/src/cli/__tests__/system.test.ts b/ix-cli/src/cli/__tests__/system.test.ts
new file mode 100644
index 00000000..6faf3425
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/system.test.ts
@@ -0,0 +1,78 @@
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import * as fs from "node:fs";
+import * as os from "node:os";
+import * as nodePath from "node:path";
+
+import { buildPackageRegistry, detectSystem, readPackageNames, readPackageDeps } from "../system.js";
+
+// Real on-disk fixtures: buildPackageRegistry reads each member's build manifest.
+let root: string;
+
+beforeAll(() => {
+ root = fs.mkdtempSync(nodePath.join(os.tmpdir(), "ix-sysreg-"));
+ const write = (rel: string, content: string) => {
+ const p = nodePath.join(root, rel);
+ fs.mkdirSync(nodePath.dirname(p), { recursive: true });
+ fs.writeFileSync(p, content);
+ };
+ // Rust crate: Cargo name has a hyphen; code imports the underscore form.
+ write("grep-matcher/Cargo.toml", '[package]\nname = "grep-matcher"\nversion = "0.1.0"\n');
+ write("grep-matcher/src/lib.rs", "pub fn m() {}\n");
+ // JS package: scoped, hyphenated; imports keep the hyphen.
+ write("app/package.json", '{ "name": "@scope/helper-foo", "version": "1.0.0" }');
+ write("app/index.js", "export const x = 1;\n");
+ // Maven modules: a library and a dependent module. The dependent's pom has a
+ // <parent> ref (must NOT be read as its name) and a <dependency> on the library.
+ write("lib/pom.xml",
+ '<project><parent><artifactId>acme-parent</artifactId></parent>' +
+ '<artifactId>acme-lib</artifactId></project>');
+ write("lib/src/main/java/A.java", "package com.acme.lib;\npublic class A {}\n");
+ write("consumer/pom.xml",
+ '<project><parent><artifactId>acme-parent</artifactId></parent>' +
+ '<artifactId>acme-consumer</artifactId>' +
+ '<dependencies><dependency><groupId>com.acme</groupId>' +
+ '<artifactId>acme-lib</artifactId></dependency></dependencies></project>');
+ write("consumer/src/main/java/B.java", "package com.acme.consumer;\nimport com.acme.lib.A;\npublic class B { A a; }\n");
+});
+
+afterAll(() => {
+ try { fs.rmSync(root, { recursive: true, force: true }); } catch { /* ignore */ }
+});
+
+describe("buildPackageRegistry", () => {
+ it("indexes the Cargo name, its stem, AND the underscore alias (Rust crate id)", () => {
+ const reg = buildPackageRegistry(root, ["grep-matcher", "app"]);
+ // Cargo hyphen name + its underscore alias both resolve to the rust member.
+ expect(reg["grep-matcher"]).toBe("grep-matcher");
+ expect(reg["grep_matcher"]).toBe("grep-matcher"); // the fix: `use grep_matcher::...`
+ // JS scoped name + stem still resolve; hyphen preserved (no false underscore-only entry needed).
+ expect(reg["@scope/helper-foo"]).toBe("app");
+ expect(reg["helper-foo"]).toBe("app");
+ expect(reg["helper_foo"]).toBe("app"); // alias also present, harmless for JS
+ });
+
+ it("detectSystem recognizes all members", () => {
+ const d = detectSystem(root);
+ expect(d).toBeTruthy();
+ expect(d!.members.sort()).toEqual(["app", "consumer", "grep-matcher", "lib"]);
+ });
+});
+
+describe("Maven name + declared-dependency graph", () => {
+ it("reads the module's OWN artifactId, not the <parent> ref", () => {
+ expect(readPackageNames(nodePath.join(root, "lib"))).toContain("acme-lib");
+ expect(readPackageNames(nodePath.join(root, "consumer"))).toContain("acme-consumer");
+ expect(readPackageNames(nodePath.join(root, "consumer"))).not.toContain("acme-parent");
+ });
+
+ it("readPackageDeps extracts declared <dependency> artifactIds", () => {
+ expect(readPackageDeps(nodePath.join(root, "consumer"))).toContain("acme-lib");
+ });
+
+ it("detectSystem builds the ground-truth repoDeps graph (consumer -> lib)", () => {
+ const d = detectSystem(root)!;
+ expect(d.repoDeps["consumer"]).toContain("lib");
+ // lib declares no intra-system deps.
+ expect(d.repoDeps["lib"]).toBeUndefined();
+ });
+});
diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.ts
index 50599159..39e58561 100644
--- a/ix-cli/src/cli/commands/ingest.ts
+++ b/ix-cli/src/cli/commands/ingest.ts
@@ -15,7 +15,7 @@ import { resolveGitHubToken } from '../github/auth.js';
import { parseGitHubRepo, fetchGitHubData } from '../github/fetch.js';
import { loadIngestionModules } from './ingestion-loader.js';
import { ensureWorkspaceId } from '../bootstrap.js';
-import { detectSystem, repoWorkspaceIdFor } from '../system.js';
+import { detectSystem, repoWorkspaceIdFor, lookupPackage } from '../system.js';
import {
deterministicId,
transformIssue,
@@ -460,32 +460,18 @@ export async function ingestFiles(
// sub-module / sub-path imports like "@babel/types/lib/x", "tokio::sync",
// "sqlalchemy.orm", "github.com/org/repo/sub"). The resolver uses this to keep a
// cross-repo edge only when the source repo actually imports the target repo.
+ // packageOf maps an import specifier to the member repo that publishes it
+ // (exact, lowercased stem, or a package-boundary prefix for scoped / sub-module
+ // / sub-path imports). declaredRepoDeps is the ground-truth member->member
+ // dependency graph from manifests; together they decide whether a cross-repo
+ // edge is dependency-backed. See lookupPackage for the matching rules.
const packageRegistry = detectedSystem?.packageRegistry ?? {};
- const packageEntries = Object.entries(packageRegistry);
- const packageOf = (mod: string): string | undefined => {
- if (!mod) return undefined;
- // A RELATIVE / source-file import (./x, ../x, "core.ts", "lib/foo.js") is
- // intra-repo — it must NOT match another member's package stem. (Without this,
- // babel-types' relative `./core.ts` falsely matches the babel-core package,
- // inventing a fake dependency that whitelists same-named-symbol false edges.)
- // A package specifier is a bare name / namespaced path with no source-file
- // extension and no leading dot/slash.
- if (mod.startsWith('.') || mod.startsWith('/')) return undefined;
- if (/\.(?:ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|go|rb|java|ex|exs|c|h|cc|cpp|hpp|cs|scala|kt|swift)$/i.test(mod)) return undefined;
- if (packageRegistry[mod]) return packageRegistry[mod]; // exact (full name or stem)
- const lower = mod.toLowerCase();
- if (packageRegistry[lower]) return packageRegistry[lower]; // lowercased stem
- for (const [pkg, repo] of packageEntries) { // sub-path / submodule
- if (mod.length > pkg.length && mod.startsWith(pkg)) {
- const sep = mod[pkg.length];
- if (sep === '/' || sep === '.' || sep === ':') return repo;
- }
- }
- return undefined;
- };
- const resolveOpts = systemId ? { repoOf, packageOf } : undefined;
+ const packageOf = (mod: string): string | undefined => lookupPackage(packageRegistry, mod);
+ const declaredRepoDeps = detectedSystem?.repoDeps;
+ const resolveOpts = systemId ? { repoOf, packageOf, declaredRepoDeps } : undefined;
if (systemId && debug) {
- process.stderr.write(`[multi-repo] system "${detectedSystem!.name}" (${systemId}) members=${detectedSystem!.members.join(', ')} packages=${packageEntries.length}\n`);
+ const depCount = declaredRepoDeps ? Object.values(declaredRepoDeps).reduce((a, d) => a + d.length, 0) : 0;
+ process.stderr.write(`[multi-repo] system "${detectedSystem!.name}" (${systemId}) members=${detectedSystem!.members.join(', ')} packages=${Object.keys(packageRegistry).length} declaredDeps=${depCount}\n`);
}
const client = new IxClient(getEndpoint());
diff --git a/ix-cli/src/cli/system.ts b/ix-cli/src/cli/system.ts
index 7ba58ee6..0682f5d1 100644
--- a/ix-cli/src/cli/system.ts
+++ b/ix-cli/src/cli/system.ts
@@ -79,8 +79,19 @@ export function readPackageNames(dir: string): string[] {
const mix = read("mix.exs"); // Elixir
if (mix) { const m = mix.match(/app:\s*:(\w+)/); if (m) add(m[1]); }
- const pom = read("pom.xml"); // Java (best-effort)
- if (pom) { const m = pom.match(/<artifactId>([^<]+)<\/artifactId>/); if (m) add(m[1]); }
+ const pom = read("pom.xml"); // Java / Maven
+ if (pom) {
+ // The module's OWN artifactId is a direct <project> child; it must not be
+ // shadowed by the <parent> ref or by a <dependency>'s artifactId, so strip
+ // those sections before taking the first artifactId.
+ const stripped = pom
+ .replace(/<parent>[\s\S]*?<\/parent>/g, "")
+ .replace(/<dependencyManagement>[\s\S]*?<\/dependencyManagement>/g, "")
+ .replace(/<dependencies>[\s\S]*?<\/dependencies>/g, "")
+ .replace(/<build>[\s\S]*?<\/build>/g, "");
+ const m = stripped.match(/<artifactId>([^<]+)<\/artifactId>/);
+ if (m) add(m[1]);
+ }
try { // Ruby gemspec
for (const f of fs.readdirSync(dir)) {
@@ -93,6 +104,89 @@ export function readPackageNames(dir: string): string[] {
return [...names];
}
+const PACKAGE_SOURCE_EXT =
+ /\.(?:ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|go|rb|java|ex|exs|c|h|cc|cpp|hpp|cs|scala|kt|swift)$/i;
+
+/**
+ * Resolve an import/dependency identifier to the member repo that publishes it,
+ * using the registry. Single source of truth shared by the import-matching gate
+ * (packageOf) and the declared-dependency graph. Rejects relative specifiers and
+ * source-file paths; treats a single ':' as a protocol (node:fs) not a package
+ * boundary, only Rust's '::' (tokio::sync) is. Matches exact, lowercased stem,
+ * then a package-boundary prefix (scoped/sub-path/sub-module imports).
+ */
+export function lookupPackage(registry: Record<string, string>, mod: string): string | undefined {
+ if (!mod) return undefined;
+ if (mod.startsWith(".") || mod.startsWith("/")) return undefined;
+ if (PACKAGE_SOURCE_EXT.test(mod)) return undefined;
+ if (registry[mod]) return registry[mod];
+ const lower = mod.toLowerCase();
+ if (registry[lower]) return registry[lower];
+ for (const pkg in registry) {
+ if (mod.length > pkg.length && mod.startsWith(pkg)) {
+ const sep = mod[pkg.length];
+ if (sep === "/" || sep === ".") return registry[pkg];
+ if (sep === ":" && mod[pkg.length + 1] === ":") return registry[pkg];
+ }
+ }
+ return undefined;
+}
+
+/**
+ * Declared dependency identifiers from a member's build manifest (the ground-truth
+ * dependency graph). Parsed per ecosystem: npm dependencies, Cargo [dependencies],
+ * go.mod require, Maven <dependency> artifactIds, Gradle, pyproject/poetry. These
+ * are matched against member published names to build the inter-repo dep graph,
+ * which is more robust than inferring deps from import matching alone (e.g. Java's
+ * Maven artifactId never appears in `import com.google.common.*`).
+ */
+export function readPackageDeps(dir: string): string[] {
+ const deps = new Set<string>();
+ const read = (f: string): string | null => {
+ try { return fs.readFileSync(nodePath.join(dir, f), "utf8"); } catch { return null; }
+ };
+ const add = (n: unknown) => { if (typeof n === "string" && n.trim()) deps.add(n.trim()); };
+
+ const pkg = read("package.json"); // JS / TS
+ if (pkg) { try {
+ const j = JSON.parse(pkg);
+ for (const s of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"])
+ if (j[s] && typeof j[s] === "object") for (const k of Object.keys(j[s])) add(k);
+ } catch { /* ignore */ } }
+
+ const cargo = read("Cargo.toml"); // Rust
+ if (cargo) {
+ for (const sect of cargo.matchAll(/\[(?:dev-|build-)?dependencies(?:\.[^\]\n]+)?\]([\s\S]*?)(?:\n\[|$)/g)) {
+ for (const dm of sect[1].matchAll(/^\s*([A-Za-z0-9_-]+)\s*(?:=|\.)/gm)) add(dm[1]);
+ }
+ }
+
+ const gomod = read("go.mod"); // Go
+ if (gomod) {
+ for (const m of gomod.matchAll(/^\s*require\s+(\S+)\s+v/gm)) add(m[1]);
+ for (const blk of gomod.matchAll(/require\s*\(([\s\S]*?)\)/g))
+ for (const dm of blk[1].matchAll(/^\s*(\S+)\s+v/gm)) add(dm[1]);
+ }
+
+ const pom = read("pom.xml"); // Java / Maven
+ if (pom) for (const m of pom.matchAll(/<dependency>[\s\S]*?<artifactId>([^<]+)<\/artifactId>[\s\S]*?<\/dependency>/g)) add(m[1]);
+
+ const gradle = read("build.gradle") ?? read("build.gradle.kts"); // Java / Kotlin / Gradle
+ if (gradle) {
+ for (const m of gradle.matchAll(/project\(['"]:?([^'"]+)['"]\)/g)) add(m[1].split(":").pop());
+ for (const m of gradle.matchAll(/['"][\w.-]+:([\w.-]+):[^'"]+['"]/g)) add(m[1]);
+ }
+
+ const pyproj = read("pyproject.toml"); // Python
+ if (pyproj) {
+ for (const m of pyproj.matchAll(/^\s*["']?([A-Za-z0-9_.-]+)["']?\s*(?:[><=~!^]|=\s*["'])/gm)) add(m[1]);
+ for (const blk of pyproj.matchAll(/dependencies\s*=\s*\[([\s\S]*?)\]/g))
+ for (const dm of blk[1].matchAll(/["']([A-Za-z0-9_.-]+)/g)) add(dm[1]);
+ }
+
+ return [...deps];
+}
+
/**
* package identifier -> member repo dir (the repo_id), for cross-repo dep
* detection. Indexed by BOTH the full package name (`@babel/types`,
@@ -104,6 +198,12 @@ export function buildPackageRegistry(rootPath: string, members: string[]): Recor
const reg: Record<string, string> = {};
const stemOwners = new Map<string, Set<string>>();
const stemRepo = new Map<string, string>();
+ // Underscore-normalized aliases: Cargo turns a package name's hyphens into
+ // underscores for the crate identifier used in code (Cargo `grep-matcher` is
+ // imported as `grep_matcher`), so the registry must answer to both forms.
+ // Harmless for JS (its imports keep the hyphen, matched by the exact name).
+ const aliasOwners = new Map<string, Set<string>>();
+ const aliasRepo = new Map<string, string>();
const stemOf = (name: string): string =>
(name.split(/[/.:]/).filter(Boolean).pop() ?? name).toLowerCase();
for (const m of members) {
@@ -113,11 +213,21 @@ export function buildPackageRegistry(rootPath: string, members: string[]): Recor
if (!stemOwners.has(stem)) stemOwners.set(stem, new Set());
stemOwners.get(stem)!.add(m);
stemRepo.set(stem, m);
+ for (const variant of new Set([name.replace(/-/g, '_'), stem.replace(/-/g, '_')])) {
+ if (variant !== name && variant !== stem) {
+ if (!aliasOwners.has(variant)) aliasOwners.set(variant, new Set());
+ aliasOwners.get(variant)!.add(m);
+ aliasRepo.set(variant, m);
+ }
+ }
}
}
for (const [stem, owners] of stemOwners) {
if (owners.size === 1 && !(stem in reg)) reg[stem] = stemRepo.get(stem)!; // unambiguous stem
}
+ for (const [alias, owners] of aliasOwners) {
+ if (owners.size === 1 && !(alias in reg)) reg[alias] = aliasRepo.get(alias)!; // unambiguous underscore alias
+ }
return reg;
}
@@ -130,6 +240,28 @@ export interface DetectedSystem {
members: string[];
/** Published package name -> member repo dir, for cross-repo dependency gating. */
packageRegistry: Record<string, string>;
+ /**
+ * Ground-truth inter-member dependency graph (member dir -> member dirs it
+ * declares a dependency on), read from each member's manifest dependency list
+ * and matched to member published names. Seeds the resolver's cross-repo gate
+ * so genuine cross-repo edges survive even when import-to-package matching
+ * can't bridge the gap (e.g. Java's Maven artifactId vs `com.google.common.*`).
+ */
+ repoDeps: Record<string, string[]>;
+}
+
+/** Member dir -> set of member dirs it declares a dependency on (intra-system only). */
+function buildRepoDeps(rootPath: string, members: string[], registry: Record<string, string>): Record<string, string[]> {
+ const graph: Record<string, string[]> = {};
+ for (const m of members) {
+ const set = new Set<string>();
+ for (const dep of readPackageDeps(nodePath.join(rootPath, m))) {
+ const owner = lookupPackage(registry, dep);
+ if (owner !== undefined && owner !== m) set.add(owner);
+ }
+ if (set.size > 0) graph[m] = [...set];
+ }
+ return graph;
}
/** Returns the detected system, or undefined when `rootPath` is a single repo. */
@@ -146,11 +278,13 @@ export function detectSystem(rootPath: string): DetectedSystem | undefined {
.map(c => c.name);
if (members.length < 2) return undefined;
const abs = nodePath.resolve(rootPath).split(nodePath.sep).join("/");
+ const packageRegistry = buildPackageRegistry(rootPath, members);
return {
systemId: stableId(`system:${abs}`),
name: nodePath.basename(abs),
members,
- packageRegistry: buildPackageRegistry(rootPath, members),
+ packageRegistry,
+ repoDeps: buildRepoDeps(rootPath, members, packageRegistry),
};
}