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 co-ingest: stable identity, read scoping, baseline scoping, migration (Ix#225 Path 1) (#241)

Joseph Mikhail28921ca36915
diff --git a/core-ingestion/src/__tests__/patchBuilder.resolution.test.ts b/core-ingestion/src/__tests__/patchBuilder.resolution.test.ts
index 19652fcc..c7754545 100644
--- a/core-ingestion/src/__tests__/patchBuilder.resolution.test.ts
+++ b/core-ingestion/src/__tests__/patchBuilder.resolution.test.ts
@@ -321,3 +321,84 @@ describe('buildPatch', () => {
);
});
});
+
+// Ix#225 Path 1: a repo's node/edge IDENTITY must be byte-identical whether it is
+// ingested standalone or as a member of a multi-repo system. Identity is folded over
+// the MEMBER-relative path (repo-dir prefix stripped) paired with the member's own
+// workspace_id, so `ix map svc-a` and `ix map <parent-of-svc-a>` produce the same
+// node and edge ids; a cross-repo edge resolves onto the very node the target repo's
+// own ingest creates. PROVENANCE (source_uri / patch id) deliberately stays
+// workspace-relative (repo-prefixed in a co-ingest) so reads reconstruct the right
+// absolute path under the workspace root — it is NOT expected to converge.
+describe('multi-repo co-ingest identity convergence', () => {
+ const WS_A = 'aaaaaaaa'; // svc-a's path-based workspace_id (same value in both modes)
+ const WS_B = 'bbbbbbbb';
+ const repoWorkspaceOf = (fp: string): string | undefined => {
+ const repo = fp.replace(/\\/g, '/').split('/')[0];
+ return repo === 'svc-a' ? WS_A : repo === 'svc-b' ? WS_B : undefined;
+ };
+ const ids = (patch: { ops: { type: string; id: string }[] }, type: string): string[] =>
+ patch.ops.filter(op => op.type === type).map(op => op.id).sort();
+
+ const svcAResult = (filePath: string): FileParseResult =>
+ fileResult(
+ filePath,
+ SupportedLanguages.TypeScript,
+ [entity('handler', SupportedLanguages.TypeScript, 'function')],
+ [{ srcName: 'handler', dstName: 'localHelper', predicate: 'CALLS' }],
+ );
+
+ it('produces byte-identical node and edge ids solo vs co-ingested', () => {
+ // Solo: filePath is already member-relative; no multiRepo context.
+ const solo = buildPatchWithResolution(svcAResult('src/index.ts'), 'h', WS_A, [], undefined, undefined);
+ // Co-ingest: filePath is repo-prefixed, multiRepo present, same member workspace_id.
+ const co = buildPatchWithResolution(
+ svcAResult('svc-a/src/index.ts'), 'h', WS_A, [],
+ undefined, { systemId: 'sys', repoId: 'svc-a', repoWorkspaceOf });
+
+ // Identity converges (folded over the member-relative path).
+ expect(ids(co, 'UpsertNode')).toEqual(ids(solo, 'UpsertNode'));
+ expect(ids(co, 'UpsertEdge')).toEqual(ids(solo, 'UpsertEdge'));
+ // Provenance stays workspace-relative — repo-prefixed in the co-ingest so `ix read`
+ // resolves parent/svc-a/src/index.ts, not parent/src/index.ts.
+ expect(co.source.uri).toBe('svc-a/src/index.ts');
+ expect(solo.source.uri).toBe('src/index.ts');
+ });
+
+ it('stamps systemId/repoId only in co-ingest, never solo', () => {
+ const solo = buildPatchWithResolution(svcAResult('src/index.ts'), 'h', WS_A, [], undefined, undefined);
+ const co = buildPatchWithResolution(
+ svcAResult('svc-a/src/index.ts'), 'h', WS_A, [],
+ undefined, { systemId: 'sys', repoId: 'svc-a', repoWorkspaceOf });
+ expect(co.source.systemId).toBe('sys');
+ expect(co.source.repoId).toBe('svc-a');
+ expect(solo.source.systemId).toBeUndefined();
+ expect(solo.source.repoId).toBeUndefined();
+ });
+
+ it('folds a cross-repo edge onto the exact node the target repo ingests standalone', () => {
+ // svc-a.handler CALLS util, resolved to svc-b/src/util.ts.
+ const src = fileResult(
+ 'svc-a/src/index.ts', SupportedLanguages.TypeScript,
+ [entity('handler', SupportedLanguages.TypeScript, 'function')],
+ [{ srcName: 'handler', dstName: 'util', predicate: 'CALLS' }],
+ );
+ const resolved: ResolvedEdge[] = [{
+ srcFilePath: 'svc-a/src/index.ts', srcName: 'handler', predicate: 'CALLS',
+ dstName: 'util', dstFilePath: 'svc-b/src/util.ts', dstQualifiedKey: 'util',
+ }];
+ const co = buildPatchWithResolution(
+ src, 'h', WS_A, resolved, undefined,
+ { systemId: 'sys', repoId: 'svc-a', repoWorkspaceOf });
+ const callsDst = co.ops.find(op => op.type === 'UpsertEdge' && op.predicate === 'CALLS')!.dst;
+
+ // svc-b's OWN standalone ingest of util in src/util.ts:
+ const svcbSolo = buildPatchWithResolution(
+ fileResult('src/util.ts', SupportedLanguages.TypeScript,
+ [entity('util', SupportedLanguages.TypeScript, 'function')], []),
+ 'h2', WS_B, [], undefined, undefined);
+ const svcbUtilNode = svcbSolo.ops.find(op => op.type === 'UpsertNode' && op.name === 'util')!.id;
+
+ expect(callsDst).toBe(svcbUtilNode);
+ });
+});
diff --git a/core-ingestion/src/patch-builder.ts b/core-ingestion/src/patch-builder.ts
index f2f84848..5b4d316b 100644
--- a/core-ingestion/src/patch-builder.ts
+++ b/core-ingestion/src/patch-builder.ts
@@ -78,6 +78,25 @@ export const PREVIOUS_EXTRACTORS = ['tree-sitter/1.23', 'tree-sitter/1.22', 'tre
// nodeId / edgeId / chunkId / computePatchId / legacyPatchId are produced by
// makeIds(workspaceId) above so every id is scoped to its workspace.
+/**
+ * In a multi-repo co-ingest, file paths are workspace-relative AND repo-prefixed:
+ * the first path segment is the member repo directory (see `repoOf` in the CLI).
+ * Node / edge / chunk IDENTITY is folded over the MEMBER-relative path (that prefix
+ * stripped) paired with the member's own workspace_id, so a repo's ids are
+ * byte-identical whether it is ingested alone or as part of a system. PROVENANCE
+ * (source_uri / file_uri / patch id) deliberately keeps the full workspace-relative
+ * path so reads can reconstruct an absolute path under the workspace root. Edge
+ * *matching* (resolvedEdges keyed on srcFilePath) also uses the full path, and
+ * repoWorkspaceOf is given the full path to identify the owning repo. Single-repo
+ * ingest (no multiRepo) is unchanged (idPath === filePath).
+ */
+function toMemberRelativePath(filePath: string, multiRepo?: MultiRepoContext): string {
+ if (!multiRepo) return filePath;
+ const norm = filePath.replace(/\\/g, '/');
+ const slash = norm.indexOf('/');
+ return slash >= 0 ? norm.slice(slash + 1) : norm;
+}
+
// ---------------------------------------------------------------------------
// Build a GraphPatchPayload from a FileParseResult
// ---------------------------------------------------------------------------
@@ -89,7 +108,16 @@ export function buildPatch(
previousSourceHash?: string,
multiRepo?: MultiRepoContext,
): GraphPatchPayload {
- const { filePath, entities, chunks, relationships } = result;
+ const { entities, chunks, relationships } = result;
+ // Two paths, deliberately distinct (see toMemberRelativePath):
+ // - filePath (workspace-relative, repo-prefixed in a co-ingest) is PROVENANCE:
+ // source_uri / file_uri / patch id. Reads reconstruct an absolute path by
+ // joining it to the workspace root, so it must stay relative to that root.
+ // - idPath (member-relative) is IDENTITY: node / edge / chunk ids fold it so a
+ // member's ids are byte-identical whether ingested alone or in a system.
+ // Single repo: idPath === filePath.
+ const filePath = result.filePath;
+ const idPath = toMemberRelativePath(result.filePath, multiRepo);
const { nodeId, edgeId, chunkId, computePatchId, legacyPatchId } = makeIds(workspaceId);
const ops: PatchOp[] = [];
@@ -139,7 +167,7 @@ export function buildPatch(
const seenNodeIds = new Set<string>();
for (const e of entities) {
const qk = entityQKey.get(e)!;
- const id = nodeId(filePath, qk);
+ const id = nodeId(idPath, qk);
if (!seenNodeIds.has(id)) {
seenNodeIds.add(id);
const roleAttrs = e.kind === 'file'
@@ -161,9 +189,9 @@ export function buildPatch(
}
// UpsertNode + edges for each chunk
- const fileNodeId = nodeId(filePath, entities.find(e => e.kind === 'file')?.name ?? filePath);
+ const fileNodeId = nodeId(idPath, entities.find(e => e.kind === 'file')?.name ?? idPath);
for (const chunk of chunks) {
- const cid = chunkId(filePath, chunk.chunkKind, chunk.name, chunk.lineStart);
+ const cid = chunkId(idPath, chunk.chunkKind, chunk.name, chunk.lineStart);
const chunkName = chunk.name ?? `file_body:${chunk.lineStart}`;
const chunkNodeKind = chunk.chunkKind === 'section' ? 'section' : 'chunk';
ops.push({
@@ -186,7 +214,7 @@ export function buildPatch(
// File -[CONTAINS]-> Chunk
ops.push({
type: 'UpsertEdge',
- id: edgeId(filePath, 'file', chunkName, 'CONTAINS_CHUNK'),
+ id: edgeId(idPath, 'file', chunkName, 'CONTAINS_CHUNK'),
src: fileNodeId,
dst: cid,
predicate: 'CONTAINS_CHUNK',
@@ -195,10 +223,10 @@ export function buildPatch(
// Chunk -[DEFINES]-> Symbol (only for named chunks)
if (chunk.name !== null) {
const symbolKey = chunk.container ? `${chunk.container}.${chunk.name}` : chunk.name;
- const symbolNid = nodeId(filePath, symbolKey);
+ const symbolNid = nodeId(idPath, symbolKey);
ops.push({
type: 'UpsertEdge',
- id: edgeId(filePath, chunkName, symbolKey, 'DEFINES'),
+ id: edgeId(idPath, chunkName, symbolKey, 'DEFINES'),
src: cid,
dst: symbolNid,
predicate: 'DEFINES',
@@ -213,13 +241,13 @@ export function buildPatch(
const b = chunks[i + 1];
// Only link top-level chunks (no container) to avoid intra-class ordering noise
if (a.container == null && b.container == null) {
- const aid = chunkId(filePath, a.chunkKind, a.name, a.lineStart);
- const bid = chunkId(filePath, b.chunkKind, b.name, b.lineStart);
+ const aid = chunkId(idPath, a.chunkKind, a.name, a.lineStart);
+ const bid = chunkId(idPath, b.chunkKind, b.name, b.lineStart);
const aName = a.name ?? `file_body:${a.lineStart}`;
const bName = b.name ?? `file_body:${b.lineStart}`;
ops.push({
type: 'UpsertEdge',
- id: edgeId(filePath, aName, bName, 'NEXT'),
+ id: edgeId(idPath, aName, bName, 'NEXT'),
src: aid,
dst: bid,
predicate: 'NEXT',
@@ -255,13 +283,13 @@ export function buildPatch(
});
}
} else {
- dstNid = nodeId(filePath, dstKey);
+ dstNid = nodeId(idPath, dstKey);
}
ops.push({
type: 'UpsertEdge',
- id: edgeId(filePath, srcKey, dstKey, r.predicate),
- src: nodeId(filePath, srcKey),
+ id: edgeId(idPath, srcKey, dstKey, r.predicate),
+ src: nodeId(idPath, srcKey),
dst: dstNid,
predicate: r.predicate,
attrs: {},
@@ -273,7 +301,7 @@ export function buildPatch(
const srcKey = resolveKey(r.srcName);
ops.push({
type: 'AssertClaim',
- entityId: nodeId(filePath, srcKey),
+ entityId: nodeId(idPath, srcKey),
field: `${r.predicate.toLowerCase()}:${r.dstName}`,
value: r.dstName,
confidence: null,
@@ -351,19 +379,27 @@ export function buildPatchWithResolution(
});
}
- const { filePath, entities, chunks, relationships } = result;
+ const { entities, chunks, relationships } = result;
+ // filePath = workspace-relative PROVENANCE (source_uri / file_uri / patch id);
+ // idPath = member-relative IDENTITY (node / edge / chunk ids) so a member's ids are
+ // byte-identical solo vs. co-ingested. Edge matching still keys on the full
+ // result.filePath above. Single-repo: idPath === filePath.
+ const filePath = result.filePath;
+ const idPath = toMemberRelativePath(result.filePath, multiRepo);
const { nodeId, edgeId, chunkId, computePatchId, legacyPatchId } = makeIds(workspaceId);
// Resolve a dst node id in the namespace of the repo that OWNS dstFilePath.
// For same-repo (or single-repo) dsts this is just nodeId; for a cross-repo
// edge it folds with the dst repo's workspace_id so the id matches the node
- // that repo's own ingest produced.
+ // that repo's own ingest produced. repoWorkspaceOf needs the full (repo-prefixed)
+ // dstFilePath to find the owning repo; the id itself uses the member-relative path.
const crossRepoIdsCache = new Map<string, ReturnType<typeof makeIds>>();
const dstNodeIdInRepo = (dstFilePath: string, key: string): string => {
const ws = multiRepo?.repoWorkspaceOf?.(dstFilePath);
- if (!ws || ws === workspaceId) return nodeId(dstFilePath, key);
+ const dstIdPath = toMemberRelativePath(dstFilePath, multiRepo);
+ if (!ws || ws === workspaceId) return nodeId(dstIdPath, key);
let ids = crossRepoIdsCache.get(ws);
if (!ids) { ids = makeIds(ws); crossRepoIdsCache.set(ws, ids); }
- return ids.nodeId(dstFilePath, key);
+ return ids.nodeId(dstIdPath, key);
};
const ops: PatchOp[] = [];
@@ -396,7 +432,7 @@ export function buildPatchWithResolution(
const seenNodeIds2 = new Set<string>();
for (const e of entities) {
const qk = entityQKey.get(e)!;
- const id = nodeId(filePath, qk);
+ const id = nodeId(idPath, qk);
if (!seenNodeIds2.has(id)) {
seenNodeIds2.add(id);
const roleAttrs = e.kind === 'file'
@@ -413,9 +449,9 @@ export function buildPatchWithResolution(
}
// UpsertNode + edges for each chunk (same logic as buildPatch)
- const fileNodeId2 = nodeId(filePath, entities.find(e => e.kind === 'file')?.name ?? filePath);
+ const fileNodeId2 = nodeId(idPath, entities.find(e => e.kind === 'file')?.name ?? idPath);
for (const chunk of chunks) {
- const cid = chunkId(filePath, chunk.chunkKind, chunk.name, chunk.lineStart);
+ const cid = chunkId(idPath, chunk.chunkKind, chunk.name, chunk.lineStart);
const chunkName = chunk.name ?? `file_body:${chunk.lineStart}`;
const chunkNodeKind2 = chunk.chunkKind === 'section' ? 'section' : 'chunk';
ops.push({
@@ -437,7 +473,7 @@ export function buildPatchWithResolution(
});
ops.push({
type: 'UpsertEdge',
- id: edgeId(filePath, 'file', chunkName, 'CONTAINS_CHUNK'),
+ id: edgeId(idPath, 'file', chunkName, 'CONTAINS_CHUNK'),
src: fileNodeId2,
dst: cid,
predicate: 'CONTAINS_CHUNK',
@@ -445,10 +481,10 @@ export function buildPatchWithResolution(
});
if (chunk.name !== null) {
const symbolKey = chunk.container ? `${chunk.container}.${chunk.name}` : chunk.name;
- const symbolNid = nodeId(filePath, symbolKey);
+ const symbolNid = nodeId(idPath, symbolKey);
ops.push({
type: 'UpsertEdge',
- id: edgeId(filePath, chunkName, symbolKey, 'DEFINES'),
+ id: edgeId(idPath, chunkName, symbolKey, 'DEFINES'),
src: cid,
dst: symbolNid,
predicate: 'DEFINES',
@@ -461,13 +497,13 @@ export function buildPatchWithResolution(
const a = chunks[i];
const b = chunks[i + 1];
if (a.container == null && b.container == null) {
- const aid = chunkId(filePath, a.chunkKind, a.name, a.lineStart);
- const bid = chunkId(filePath, b.chunkKind, b.name, b.lineStart);
+ const aid = chunkId(idPath, a.chunkKind, a.name, a.lineStart);
+ const bid = chunkId(idPath, b.chunkKind, b.name, b.lineStart);
const aName = a.name ?? `file_body:${a.lineStart}`;
const bName = b.name ?? `file_body:${b.lineStart}`;
ops.push({
type: 'UpsertEdge',
- id: edgeId(filePath, aName, bName, 'NEXT'),
+ id: edgeId(idPath, aName, bName, 'NEXT'),
src: aid,
dst: bid,
predicate: 'NEXT',
@@ -508,13 +544,13 @@ export function buildPatchWithResolution(
});
}
} else {
- dstNodeId = nodeId(filePath, dstKey);
+ dstNodeId = nodeId(idPath, dstKey);
}
ops.push({
type: 'UpsertEdge',
- id: edgeId(filePath, srcKey, dstKey, r.predicate),
- src: nodeId(filePath, srcKey),
+ id: edgeId(idPath, srcKey, dstKey, r.predicate),
+ src: nodeId(idPath, srcKey),
dst: dstNodeId,
predicate: r.predicate,
attrs: {},
@@ -525,7 +561,7 @@ export function buildPatchWithResolution(
const srcKey = resolveKey(r.srcName);
ops.push({
type: 'AssertClaim',
- entityId: nodeId(filePath, srcKey),
+ entityId: nodeId(idPath, srcKey),
field: `${r.predicate.toLowerCase()}:${r.dstName}`,
value: r.dstName,
confidence: null,
diff --git a/ix-cli/src/cli/__tests__/bootstrap-migration.test.ts b/ix-cli/src/cli/__tests__/bootstrap-migration.test.ts
new file mode 100644
index 00000000..70edad11
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/bootstrap-migration.test.ts
@@ -0,0 +1,88 @@
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import * as fs from "node:fs";
+import * as os from "node:os";
+import * as nodePath from "node:path";
+
+import { ensureWorkspaceIdState } from "../bootstrap.js";
+import { workspaceIdForPath } from "../system.js";
+
+// Isolate ~/.ix by pointing HOME/USERPROFILE at a temp dir per test.
+let home: string;
+let savedHome: string | undefined;
+let savedProfile: string | undefined;
+
+beforeEach(() => {
+ home = fs.mkdtempSync(nodePath.join(os.tmpdir(), "ix-bootmig-"));
+ savedHome = process.env.HOME;
+ savedProfile = process.env.USERPROFILE;
+ process.env.HOME = home;
+ process.env.USERPROFILE = home;
+ fs.mkdirSync(nodePath.join(home, ".ix"), { recursive: true });
+});
+
+afterEach(() => {
+ process.env.HOME = savedHome;
+ process.env.USERPROFILE = savedProfile;
+ try { fs.rmSync(home, { recursive: true, force: true }); } catch { /* ignore */ }
+});
+
+function writeConfig(workspaces: object[]) {
+ const body = "endpoint: http://localhost:8090\n" +
+ "workspaces:\n" +
+ workspaces.map((w: any) =>
+ ` - workspace_id: ${w.workspace_id}\n workspace_name: ${w.workspace_name}\n root_path: ${w.root_path}\n default: ${w.default ?? false}\n`).join("");
+ fs.writeFileSync(nodePath.join(home, ".ix", "config.yaml"), body);
+}
+
+function readWorkspaceId(rootPath: string): string | undefined {
+ const raw = fs.readFileSync(nodePath.join(home, ".ix", "config.yaml"), "utf8");
+ // crude: find the block for rootPath and read its workspace_id
+ const lines = raw.split(/\r?\n/);
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i].includes("workspace_id:")) {
+ const id = lines[i].split("workspace_id:")[1].trim();
+ for (let j = i; j < i + 4 && j < lines.length; j++) {
+ if (lines[j].includes("root_path:") && lines[j].includes(rootPath)) return id;
+ }
+ }
+ }
+ return undefined;
+}
+
+describe("workspace_id migration (Ix#225 gap 2)", () => {
+ it("re-keys a legacy random workspace_id to the path-based id and reports migrated", () => {
+ const root = nodePath.join(home, "repoOne");
+ fs.mkdirSync(root, { recursive: true });
+ writeConfig([{ workspace_id: "rand0001", workspace_name: "repoOne", root_path: root, default: true }]);
+
+ const pathId = workspaceIdForPath(root);
+ expect(pathId).not.toBe("rand0001");
+
+ const state = ensureWorkspaceIdState(root);
+ expect(state.workspaceId).toBe(pathId);
+ expect(state.migrated).toBe(true);
+ expect(state.previousWorkspaceId).toBe("rand0001"); // captured for orphan cleanup
+ expect(readWorkspaceId(root)).toBe(pathId); // persisted
+ });
+
+ it("does NOT migrate (or churn) a workspace already on the path-based id", () => {
+ const root = nodePath.join(home, "repoTwo");
+ fs.mkdirSync(root, { recursive: true });
+ const pathId = workspaceIdForPath(root);
+ writeConfig([{ workspace_id: pathId, workspace_name: "repoTwo", root_path: root, default: true }]);
+
+ const state = ensureWorkspaceIdState(root);
+ expect(state.workspaceId).toBe(pathId);
+ expect(state.migrated).toBe(false);
+ });
+
+ it("creates a fresh workspace with the path-based id (not random), not flagged migrated", () => {
+ const root = nodePath.join(home, "repoThree");
+ fs.mkdirSync(root, { recursive: true });
+ writeConfig([]); // no workspaces yet
+
+ const state = ensureWorkspaceIdState(root);
+ expect(state.workspaceId).toBe(workspaceIdForPath(root));
+ expect(state.migrated).toBe(false);
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/loadExistingHashes.test.ts b/ix-cli/src/cli/__tests__/loadExistingHashes.test.ts
new file mode 100644
index 00000000..f563d969
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/loadExistingHashes.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from "vitest";
+
+import { loadExistingHashes } from "../commands/ingest.js";
+
+type Row = { workspaceId: string | null; uri: string; hash: string };
+
+// Stub the workspace-scoped source-hashes endpoint. Records what was queried and
+// returns the configured rows (each tagged with its workspace_id, like the server).
+function stubClient(rows: Row[]) {
+ const calls: Array<{ uris: string[]; workspaceIds?: string[] }> = [];
+ return {
+ calls,
+ getSourceHashes: async (uris: string[], workspaceIds?: string[]) => {
+ calls.push({ uris, workspaceIds });
+ // Mimic the server: return rows whose uri was asked for (and, if workspaceIds
+ // given, whose workspace is in scope).
+ return rows.filter(r => uris.includes(r.uri) && (!workspaceIds || workspaceIds.length === 0 || (r.workspaceId != null && workspaceIds.includes(r.workspaceId))));
+ },
+ };
+}
+
+describe("loadExistingHashes — workspace-scoped baseline (Ix#225 gap 3)", () => {
+ it("matches each file to ITS OWN workspace's hash, never another workspace's", async () => {
+ // Two files share the member-relative uri "src/x.ts" but live in different
+ // workspaces with DIFFERENT stored hashes. Each must get its own.
+ const client = stubClient([
+ { workspaceId: "wsA1aaaa", uri: "src/x.ts", hash: "hashA" },
+ { workspaceId: "wsB2bbbb", uri: "src/x.ts", hash: "hashB" },
+ ]);
+ const toRel = (abs: string) => abs.replace(/^\/(a|b)\//, ""); // /a/src/x.ts -> src/x.ts
+ const wsOf = (abs: string) => (abs.startsWith("/a/") ? "wsA1aaaa" : "wsB2bbbb");
+ const out = await loadExistingHashes(client, ["/a/src/x.ts", "/b/src/x.ts"], toRel, wsOf);
+
+ expect(out.get("/a/src/x.ts")).toBe("hashA"); // A's own hash, NOT hashB
+ expect(out.get("/b/src/x.ts")).toBe("hashB");
+ // It must send the workspace scope so the server can bound + tag rows.
+ expect(client.calls[0].workspaceIds?.sort()).toEqual(["wsA1aaaa", "wsB2bbbb"]);
+ expect(client.calls[0].uris).toEqual(["src/x.ts"]); // deduped
+ });
+
+ it("returns no hash for a file whose workspace has no stored row (fresh repo, identical path elsewhere)", async () => {
+ // Only workspace A has src/common.ts; a fresh workspace B querying the same uri
+ // must NOT inherit A's hash (the cross-workspace collision that wrong-skipped).
+ const client = stubClient([{ workspaceId: "wsA1aaaa", uri: "src/common.ts", hash: "hashA" }]);
+ const toRel = (abs: string) => abs.replace(/^\/b\//, "");
+ const out = await loadExistingHashes(client, ["/b/src/common.ts"], toRel, () => "wsB2bbbb");
+ expect(out.has("/b/src/common.ts")).toBe(false); // re-ingested, not matched to A
+ });
+
+ it("returns an empty map (not a throw) when the lookup fails", async () => {
+ const failing = { getSourceHashes: async () => { throw new Error("network"); } };
+ const out = await loadExistingHashes(failing, ["/a.ts"], a => a, () => "ws");
+ expect(out.size).toBe(0);
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/system.test.ts b/ix-cli/src/cli/__tests__/system.test.ts
index ed31b4c5..a94cd673 100644
--- a/ix-cli/src/cli/__tests__/system.test.ts
+++ b/ix-cli/src/cli/__tests__/system.test.ts
@@ -3,7 +3,7 @@ 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";
+import { buildPackageRegistry, detectSystem, readPackageNames, readPackageDeps, repoWorkspaceIdFor, workspaceIdForPath } from "../system.js";
// Real on-disk fixtures: buildPackageRegistry reads each member's build manifest.
let root: string;
@@ -138,3 +138,20 @@ describe("git-aware system detection (no flags, monorepo vs separate repos)", ()
expect(d!.members.sort()).toEqual(["proj-a", "proj-b"]);
});
});
+
+describe("workspace_id convergence (solo vs co-ingest)", () => {
+ // The solo path (bootstrap.getOrCreateWorkspace) and the co-ingest member path
+ // (repoWorkspaceIdFor) must derive the SAME path-based id for a given repo root,
+ // else a repo's nodes diverge between `ix map <repo>` and `ix map <parent>`.
+ it("repoWorkspaceIdFor(parent, member) === workspaceIdForPath(parent/member)", () => {
+ const memberAbs = nodePath.join(root, "app");
+ expect(repoWorkspaceIdFor(root, "app")).toBe(workspaceIdForPath(memberAbs));
+ });
+
+ it("is stable and path-distinct (different roots -> different ids)", () => {
+ expect(workspaceIdForPath(root)).toBe(workspaceIdForPath(root)); // deterministic
+ expect(workspaceIdForPath(nodePath.join(root, "app")))
+ .not.toBe(workspaceIdForPath(nodePath.join(root, "lib")));
+ expect(workspaceIdForPath(root)).toMatch(/^[0-9a-f]{8}$/); // 8-hex, not a random UUID slice
+ });
+});
diff --git a/ix-cli/src/cli/bootstrap.ts b/ix-cli/src/cli/bootstrap.ts
index 213e80c7..6bff6c6d 100644
--- a/ix-cli/src/cli/bootstrap.ts
+++ b/ix-cli/src/cli/bootstrap.ts
@@ -1,11 +1,11 @@
import { mkdirSync, existsSync, writeFileSync } from "node:fs";
import { join, basename, resolve } from "node:path";
import { homedir } from "node:os";
-import { randomUUID } from "node:crypto";
import { execFileSync } from "node:child_process";
import chalk from "chalk";
import { IxClient } from "../client/api.js";
import { getEndpoint, loadConfig, saveConfig, findWorkspaceForCwd, getDefaultWorkspace, type WorkspaceConfig } from "./config.js";
+import { workspaceIdForPath } from "./system.js";
export interface BootstrapResult {
createdConfig: boolean;
@@ -26,27 +26,55 @@ export function ensureLocalConfig(): boolean {
return true;
}
+// Roots whose workspace_id was re-keyed to the path-based id during THIS process,
+// mapped to the OLD (pre-migration) id. getOrCreateWorkspace is called more than once
+// per `ix map` (bootstrap() registers, then ingest resolves the id); the first call
+// does the actual re-key, so without this the second call would report migrated=false
+// (and ingest would skip the forced re-ingest + the old-id cleanup). Keyed by resolved
+// root path. The old id is what ingest deletes to clean up the migration's orphans.
+const migratedRootsThisRun = new Map<string, string>();
+
+interface WorkspaceState { ws: WorkspaceConfig; created: boolean; migrated: boolean; previousWorkspaceId?: string }
+
/**
* Ensure the current directory (or given path) is registered as a workspace.
* Returns the workspace name. Does nothing if already registered.
*/
-function getOrCreateWorkspace(cwd: string): { ws: WorkspaceConfig; created: boolean } {
+function getOrCreateWorkspace(cwd: string): WorkspaceState {
const rootPath = resolve(cwd);
const config = loadConfig();
+ const pathId = workspaceIdForPath(rootPath);
const existing = (config.workspaces ?? []).find(w => w.root_path === rootPath);
- if (existing) return { ws: existing, created: false };
+ if (existing) {
+ // Migrate a legacy random workspace_id to the path-based id (Ix#225 gap 2) so
+ // an already-registered repo converges with co-ingest. This changes the
+ // workspace_id that node identity folds, so the next map must re-ingest under
+ // the new id (the caller forces that) and delete the old id's orphaned nodes.
+ if (existing.workspace_id !== pathId) {
+ const previousWorkspaceId = existing.workspace_id;
+ existing.workspace_id = pathId;
+ saveConfig(config);
+ migratedRootsThisRun.set(rootPath, previousWorkspaceId);
+ return { ws: existing, created: false, migrated: true, previousWorkspaceId };
+ }
+ const previousWorkspaceId = migratedRootsThisRun.get(rootPath);
+ return { ws: existing, created: false, migrated: previousWorkspaceId !== undefined, previousWorkspaceId };
+ }
const workspaces = config.workspaces ?? [];
const hasDefault = workspaces.some(w => w.default);
const ws: WorkspaceConfig = {
- workspace_id: randomUUID().slice(0, 8),
+ // Path-based id (NOT random): a repo mapped standalone must get the same
+ // workspace_id it gets as a member of a system, so its node identity is
+ // byte-identical across both. Shared with repoWorkspaceIdFor via system.ts.
+ workspace_id: pathId,
workspace_name: basename(rootPath),
root_path: rootPath,
default: !hasDefault,
};
config.workspaces = [...workspaces, ws];
saveConfig(config);
- return { ws, created: true };
+ return { ws, created: true, migrated: false };
}
export function ensureWorkspaceRegistered(cwd = process.cwd()): { registered: boolean; name: string } {
@@ -54,6 +82,17 @@ export function ensureWorkspaceRegistered(cwd = process.cwd()): { registered: bo
return { registered: created, name: ws.workspace_name };
}
+/**
+ * Like ensureWorkspaceId, but also reports whether the workspace_id was just migrated
+ * from a legacy random id to the path-based id (and, if so, the previous id). The
+ * map/ingest flow uses `migrated` to force a full re-ingest under the new id and
+ * `previousWorkspaceId` to delete the old id's orphaned nodes afterward.
+ */
+export function ensureWorkspaceIdState(cwd = process.cwd()): { workspaceId: string; migrated: boolean; previousWorkspaceId?: string } {
+ const { ws, migrated, previousWorkspaceId } = getOrCreateWorkspace(cwd);
+ return { workspaceId: ws.workspace_id, migrated, previousWorkspaceId };
+}
+
/**
* Resolve the stable workspace id for a root, registering the workspace (and
* persisting a fresh id) on first use. This id is folded into node identity by
diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.ts
index 39e58561..8cdd19dc 100644
--- a/ix-cli/src/cli/commands/ingest.ts
+++ b/ix-cli/src/cli/commands/ingest.ts
@@ -10,11 +10,11 @@ import { ParsePool } from './parse-pool.js';
import chalk from 'chalk';
import { IxClient } from '../../client/api.js';
import type { GraphPatchPayload } from '../../client/types.js';
-import { getEndpoint, resolveWorkspaceRoot } from '../config.js';
+import { getEndpoint, resolveWorkspaceRoot, ingestMtimeCachePath } from '../config.js';
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 { ensureWorkspaceIdState } from '../bootstrap.js';
import { detectSystem, repoWorkspaceIdFor, lookupPackage } from '../system.js';
import {
deterministicId,
@@ -314,14 +314,9 @@ interface MtimeCache {
files: Record<string, number>; // absolute path → mtime (ms)
}
-function mtimeCachePath(projectRoot: string): string {
- const key = crypto.createHash('sha256').update(projectRoot).digest('hex').slice(0, 12);
- return nodePath.join(os.homedir(), '.ix', `ingest_mtimes_${key}.json`);
-}
-
function loadMtimeCache(projectRoot: string): Map<string, number> {
try {
- const raw = fs.readFileSync(mtimeCachePath(projectRoot), 'utf-8');
+ const raw = fs.readFileSync(ingestMtimeCachePath(projectRoot), 'utf-8');
const data = JSON.parse(raw) as MtimeCache;
if (data.root !== projectRoot) return new Map();
return new Map(Object.entries(data.files));
@@ -335,7 +330,7 @@ function saveMtimeCache(projectRoot: string, mtimes: Map<string, number>): void
const dir = nodePath.join(os.homedir(), '.ix');
fs.mkdirSync(dir, { recursive: true });
const data: MtimeCache = { root: projectRoot, files: Object.fromEntries(mtimes) };
- fs.writeFileSync(mtimeCachePath(projectRoot), JSON.stringify(data));
+ fs.writeFileSync(ingestMtimeCachePath(projectRoot), JSON.stringify(data));
} catch {
// Non-critical: ignore write errors
}
@@ -422,13 +417,26 @@ export async function ingestFiles(
// The backend used to dereference provenance.source_uri against the host
// filesystem (via a broad HOME bind mount). We now emit workspace-relative
// paths as the canonical source_uri, plus a stable workspace_id (persisted in
- // ~/.ix/config.yaml, NOT derived from the absolute path) that core-ingestion
- // folds into every node id so two workspaces with the same relative layout do
- // not collide. The backend treats both as opaque strings; it never reads host files.
+ // ~/.ix/config.yaml, derived from the workspace's absolute path) that
+ // core-ingestion folds into every node id so two workspaces with the same
+ // relative layout do not collide. The id is path-based (not random) so a repo
+ // mapped standalone gets the SAME workspace_id it gets as a member of a system
+ // (see workspaceIdForPath / repoWorkspaceIdFor), keeping its node identity
+ // byte-identical across both. The backend treats both as opaque strings; it
+ // never reads host files.
const workspaceRoot = fs.statSync(resolvedPath).isDirectory()
? resolvedPath
: nodePath.dirname(resolvedPath);
- const workspaceId = ensureWorkspaceId(workspaceRoot);
+ const { workspaceId, migrated: workspaceMigrated, previousWorkspaceId } = ensureWorkspaceIdState(workspaceRoot);
+ if (workspaceMigrated) {
+ // Legacy random workspace_id was just re-keyed to the path-based id (Ix#225
+ // gap 2). Node identity folds the workspace_id, so the previously-ingested
+ // nodes live under the old id; force a full re-ingest under the new id (below)
+ // and delete the old id's orphaned nodes after that succeeds.
+ process.stderr.write(
+ `Migrated workspace to a stable path-based id; re-ingesting this workspace once.\n`,
+ );
+ }
const toWorkspaceRelative = (absPath: string): string => {
// Force workspace-local POSIX separators so IDs are stable across OS.
const rel = nodePath.relative(workspaceRoot, absPath);
@@ -453,6 +461,9 @@ export async function ingestFiles(
const repoWorkspaceOf = systemId ? (relPath: string) => repoWorkspaceId(repoOf(relPath)) : undefined;
// Per-file workspace id + multi-repo context fed to buildPatchWithResolution.
const fileWorkspaceId = (relPath: string): string => systemId ? repoWorkspaceId(repoOf(relPath)) : workspaceId;
+ // The workspace_id a file's nodes are folded under (same value the patch builder
+ // stamps on source.workspaceId) — used to scope the baseline hash lookup per file.
+ const sourceWorkspaceIdOf = (absPath: string): string => fileWorkspaceId(toWorkspaceRelative(absPath));
const fileMultiRepo = (relPath: string) =>
systemId ? { systemId, repoId: repoOf(relPath), repoWorkspaceOf } : undefined;
// Cross-repo dependency gate: map an import module name to the member repo that
@@ -618,7 +629,9 @@ export async function ingestFiles(
// Phase: mtime pre-filter — skip readFileSync+sha256 for files whose mtime
// is unchanged since the last successful ingest (common "ix map" re-run case).
const projectRoot = fs.statSync(resolvedPath).isDirectory() ? resolvedPath : nodePath.dirname(resolvedPath);
- const mtimeCache = opts.force ? new Map<string, number>() : loadMtimeCache(projectRoot);
+ // A just-migrated workspace (new path-based id) has no nodes under the new id, so
+ // skip the mtime pre-filter and re-ingest everything, exactly like --force.
+ const mtimeCache = (opts.force || workspaceMigrated) ? new Map<string, number>() : loadMtimeCache(projectRoot);
const currentMtimes = new Map<string, number>();
// DB-reset guard: if the mtime cache has entries but the server returns no hashes
@@ -626,7 +639,7 @@ export async function ingestFiles(
// so the cache wasn't cleared). Invalidate the cache so files are re-ingested.
if (!opts.force && mtimeCache.size > 0) {
const samplePaths = [...mtimeCache.keys()].slice(0, 5);
- const sampleHashes = await loadExistingHashes(client, samplePaths, toWorkspaceRelative, debug);
+ const sampleHashes = await loadExistingHashes(client, samplePaths, toWorkspaceRelative, sourceWorkspaceIdOf, debug);
if (sampleHashes.size === 0) {
mtimeCache.clear();
if (debug) process.stderr.write(`\n DB reset detected — invalidating mtime cache\n`);
@@ -658,7 +671,7 @@ export async function ingestFiles(
// Phase: hash lookup — only needed when mtime-changed files exist.
let knownHashes: Map<string, string>;
if (opts.force || mtimeChangedPaths.length > 0) {
- knownHashes = await loadExistingHashes(client, opts.force ? filePaths : mtimeChangedPaths, toWorkspaceRelative, debug);
+ knownHashes = await loadExistingHashes(client, opts.force ? filePaths : mtimeChangedPaths, toWorkspaceRelative, sourceWorkspaceIdOf, debug);
if (debug) process.stderr.write(`\n Source hash lookup: ${knownHashes.size} known hashes (${mtimeChangedPaths.length} mtime-changed)\n`);
} else {
// All files are mtime-clean — skip server round-trip entirely.
@@ -1156,6 +1169,18 @@ export async function ingestFiles(
if (!opts.force && parseErrors === 0 && currentMtimes.size > 0) {
saveMtimeCache(projectRoot, currentMtimes);
}
+
+ // Migration cleanup (Ix#225 gap 2): the re-ingest under the new path-based id has
+ // committed, so delete the OLD id's now-orphaned nodes/edges/patches. Best-effort —
+ // a failure here is non-fatal (orphans are harmless dead storage, cleanable later).
+ if (workspaceMigrated && previousWorkspaceId && parseErrors === 0) {
+ try {
+ await client.deleteWorkspace(previousWorkspaceId);
+ if (debug) process.stderr.write(` Cleaned up pre-migration nodes under ${previousWorkspaceId}.\n`);
+ } catch (err) {
+ if (debug) process.stderr.write(` [migration cleanup skipped] ${err}\n`);
+ }
+ }
} finally {
if (pool) {
await pool.destroy();
@@ -1267,26 +1292,29 @@ export async function ingestFiles(
// tracks files internally by absolute path (needed for fs reads), so this
// helper converts to relative before the wire call and maps the server's
// response back onto the caller's absolute keys.
-async function loadExistingHashes(
- client: IxClient,
+export async function loadExistingHashes(
+ client: Pick<IxClient, "getSourceHashes">,
filePaths: string[],
toRelative: (absPath: string) => string,
+ workspaceIdOf: (absPath: string) => string,
debug = false,
): Promise<Map<string, string>> {
try {
- const relPaths: string[] = new Array(filePaths.length);
- const relToAbs = new Map<string, string>();
- for (let i = 0; i < filePaths.length; i++) {
- const abs = filePaths[i];
- const rel = toRelative(abs);
- relPaths[i] = rel;
- relToAbs.set(rel, abs);
- }
- const serverHashes = await client.getSourceHashes(relPaths);
+ // Each file is matched against its OWN workspace's stored hash. The server keys
+ // source_uri globally, so without the workspace_id two members (or two unrelated
+ // repos) sharing a relative path + content would collide; pairing (workspace_id,
+ // uri) makes the baseline collision-free (Ix#225 gap 3).
+ const entries = filePaths.map(abs => ({ abs, uri: toRelative(abs), ws: workspaceIdOf(abs) }));
+ const uris = [...new Set(entries.map(e => e.uri))];
+ const workspaceIds = [...new Set(entries.map(e => e.ws).filter(Boolean))];
+ const rows = await client.getSourceHashes(uris, workspaceIds);
+ const sep = "\u0000";
+ const index = new Map<string, string>();
+ for (const r of rows) index.set(`${r.workspaceId ?? ""}${sep}${r.uri}`, r.hash);
const out = new Map<string, string>();
- for (const [rel, hash] of serverHashes) {
- const abs = relToAbs.get(rel);
- if (abs !== undefined) out.set(abs, hash);
+ for (const e of entries) {
+ const hash = index.get(`${e.ws}${sep}${e.uri}`);
+ if (hash !== undefined) out.set(e.abs, hash);
}
return out;
} catch (err) {
diff --git a/ix-cli/src/cli/commands/rank.ts b/ix-cli/src/cli/commands/rank.ts
index 0813d6ab..08292998 100644
--- a/ix-cli/src/cli/commands/rank.ts
+++ b/ix-cli/src/cli/commands/rank.ts
@@ -2,7 +2,7 @@ import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
-import { resolveWorkspaceId } from "../bootstrap.js";
+import { activeReadScope } from "../resolve.js";
import { llmLine } from "../llm.js";
type Metric = "dependents" | "callers" | "importers" | "members";
@@ -172,7 +172,7 @@ export function registerRankCommand(program: Command): void {
const diagnostics: string[] = [];
// 1. Fetch all entities of the given kind
- const allNodes = await client.listByKind(opts.kind, { limit: 2000, workspaceId: resolveWorkspaceId() });
+ const allNodes = await client.listByKind(opts.kind, { limit: 2000, ...activeReadScope() });
if (allNodes.length === 0) {
if (opts.format === "llm") {
diff --git a/ix-cli/src/cli/commands/read.ts b/ix-cli/src/cli/commands/read.ts
index 0643c3d9..a4ab4751 100644
--- a/ix-cli/src/cli/commands/read.ts
+++ b/ix-cli/src/cli/commands/read.ts
@@ -4,7 +4,7 @@ import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { absoluteFromSourceUri, getEndpoint, resolveWorkspaceRoot } from "../config.js";
-import { resolveEntityFull } from "../resolve.js";
+import { resolveEntityFull, activeReadScope } from "../resolve.js";
import { stderr } from "../stderr.js";
import { isFileStale } from "../stale.js";
import { relativePath } from "../format.js";
@@ -255,22 +255,27 @@ async function tryFilenameMatch(
): Promise<Array<{ name: string; path: string }>> {
const basename = path.basename(target);
const hasExtension = path.extname(basename) !== "";
+ // Scope to the active workspace / co-ingest system server-side, like trySymbolMatch.
+ const scope = activeReadScope();
// Strategy 1: Search with the exact target (may include extension)
- let nodes = await client.search(basename, { limit: 20, kind: "file" });
+ let nodes = await client.search(basename, { limit: 20, kind: "file", ...scope });
// Strategy 2: If bare name (no extension), also search with common extensions
- // to avoid being crowded out by unrelated results
+ // to avoid being crowded out by unrelated results. Fire the per-extension searches
+ // CONCURRENTLY — sequentially they were ~9 round trips that hung `ix read <symbol>`
+ // on large backends. Results are merged in extension-priority order (a .scala hit
+ // still ranks before a .ts hit), and the downstream filter/sort picks the winner.
if (!hasExtension && !filterMatches(nodes, basename).length) {
const extensions = [".scala", ".ts", ".tsx", ".py", ".rs", ".go", ".java", ".js", ".md"];
- for (const ext of extensions) {
- const extNodes = await client.search(basename + ext, { limit: 5, kind: "file" });
- const extMatches = filterMatches(extNodes, basename);
- if (extMatches.length > 0) {
- nodes = [...extNodes, ...nodes];
- break;
- }
- }
+ const perExt = await Promise.all(
+ extensions.map(ext =>
+ client.search(basename + ext, { limit: 5, kind: "file", ...scope })
+ .then(r => (filterMatches(r, basename).length ? r : []))
+ .catch(() => [] as any[])),
+ );
+ const merged = perExt.flat();
+ if (merged.length) nodes = [...merged, ...nodes];
}
const matches = filterMatches(nodes, basename);
diff --git a/ix-cli/src/cli/commands/reset.ts b/ix-cli/src/cli/commands/reset.ts
index 897547fb..b459dfc5 100644
--- a/ix-cli/src/cli/commands/reset.ts
+++ b/ix-cli/src/cli/commands/reset.ts
@@ -1,25 +1,8 @@
-import * as nodePath from "node:path";
-import * as fs from "node:fs";
-import * as crypto from "node:crypto";
-import * as os from "node:os";
import type { Command } from "commander";
import chalk from "chalk";
import { spawnSync } from "child_process";
import { IxClient } from "../../client/api.js";
-import { getEndpoint } from "../config.js";
-
-function mtimeCachePath(projectRoot: string): string {
- const key = crypto.createHash("sha256").update(projectRoot).digest("hex").slice(0, 12);
- return nodePath.join(os.homedir(), ".ix", `ingest_mtimes_${key}.json`);
-}
-
-function clearMtimeCache(projectRoot: string): void {
- try {
- fs.rmSync(mtimeCachePath(projectRoot), { force: true });
- } catch {
- // Non-critical
- }
-}
+import { getEndpoint, clearIngestMtimeCache } from "../config.js";
export function registerResetCommand(program: Command): void {
program
@@ -61,14 +44,14 @@ export function registerResetCommand(program: Command): void {
clearInterval(interval);
process.stderr.write("\r\x1b[K");
// Clear the mtime cache so the next ix map re-ingests all files
- clearMtimeCache(process.cwd());
+ clearIngestMtimeCache(process.cwd());
console.log(chalk.green("✓") + " Code graph wiped. Planning artifacts preserved.");
console.log(chalk.dim(" Run `ix map` to rebuild the code graph."));
} else {
await client.reset();
clearInterval(interval);
process.stderr.write("\r\x1b[K");
- clearMtimeCache(process.cwd());
+ clearIngestMtimeCache(process.cwd());
console.log(chalk.green("✓") + " Graph wiped.");
}
} catch (err: any) {
diff --git a/ix-cli/src/cli/commands/trace.ts b/ix-cli/src/cli/commands/trace.ts
index 17c9c244..2cf4abf8 100644
--- a/ix-cli/src/cli/commands/trace.ts
+++ b/ix-cli/src/cli/commands/trace.ts
@@ -2,7 +2,7 @@ import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
-import { resolveFileOrEntity, isRawId } from "../resolve.js";
+import { resolveFileOrEntity, isRawId, activeReadScope } from "../resolve.js";
import type { ResolvedEntity } from "../resolve.js";
import { stderr } from "../stderr.js";
import { renderSection, renderKeyValue, renderResolvedHeader, colorizeKind } from "../ui.js";
@@ -93,6 +93,7 @@ export async function pickTraceTarget(
limit: 50,
kind: "config_entry",
nameOnly: true,
+ ...activeReadScope(),
}))
.filter((node: any) => isExactSymbolMatch(node, symbol))
.filter((node: any, index: number, all: any[]) =>
diff --git a/ix-cli/src/cli/commands/watch.ts b/ix-cli/src/cli/commands/watch.ts
index 5b067551..5300a9df 100644
--- a/ix-cli/src/cli/commands/watch.ts
+++ b/ix-cli/src/cli/commands/watch.ts
@@ -3,9 +3,10 @@ import * as path from "node:path";
import * as crypto from "node:crypto";
import type { Command } from "commander";
import chalk from "chalk";
+import { spawnSync } from "node:child_process";
import { IxClient } from "../../client/api.js";
-import { getEndpoint, resolveWorkspaceRoot } from "../config.js";
-import { bootstrap, ensureWorkspaceId } from "../bootstrap.js";
+import { getEndpoint, resolveWorkspaceRoot, clearIngestMtimeCache } from "../config.js";
+import { bootstrap, ensureWorkspaceId, ensureWorkspaceIdState } from "../bootstrap.js";
import { loadWatchIngestionModules } from "./ingestion-loader.js";
import { readFileContent } from "./watch-utils.js";
const SUPPORTED_EXTENSIONS = new Set([
@@ -61,7 +62,16 @@ export function registerWatchCommand(program: Command): void {
}
const root = resolveWorkspaceRoot(opts.root);
- const workspaceId = ensureWorkspaceId(root);
+ const { workspaceId, migrated } = ensureWorkspaceIdState(root);
+ // If the workspace_id was just migrated to the path-based id (Ix#225 gap 2), the
+ // new id has no nodes yet and watch only ingests files as they change — so do a
+ // one-time full re-ingest under the new id first (clear the mtime cache so the
+ // spawned map re-ingests everything, then run it synchronously before watching).
+ if (migrated) {
+ console.error(chalk.dim("[watch] Workspace migrated to a stable id; re-ingesting once before watching..."));
+ clearIngestMtimeCache(root);
+ spawnSync(process.argv[0], [process.argv[1], "map", root, "--silent"], { stdio: "inherit" });
+ }
const watchPath = opts.path
? path.resolve(root, opts.path)
: root;
diff --git a/ix-cli/src/cli/config.ts b/ix-cli/src/cli/config.ts
index b53d1479..87157374 100644
--- a/ix-cli/src/cli/config.ts
+++ b/ix-cli/src/cli/config.ts
@@ -1,10 +1,26 @@
-import { readFileSync, writeFileSync, existsSync } from "node:fs";
-import { join } from "node:path";
+import { readFileSync, writeFileSync, existsSync, rmSync } from "node:fs";
+import { join, resolve as resolvePath } from "node:path";
import { homedir } from "node:os";
+import { createHash } from "node:crypto";
import { execSync } from "node:child_process";
import { parse, stringify } from "yaml";
import { IxClient } from "../client/api.js";
+/**
+ * Path to the per-project ingest mtime cache (the "skip unchanged files on re-map"
+ * pre-filter). Keyed on a hash of the project root. Single source of truth shared by
+ * ingest (load/save), reset, and watch (clear) — all three MUST agree on this path.
+ */
+export function ingestMtimeCachePath(projectRoot: string): string {
+ const key = createHash("sha256").update(projectRoot).digest("hex").slice(0, 12);
+ return join(homedir(), ".ix", `ingest_mtimes_${key}.json`);
+}
+
+/** Remove the ingest mtime cache so the next map re-ingests every file. Best-effort. */
+export function clearIngestMtimeCache(projectRoot: string): void {
+ try { rmSync(ingestMtimeCachePath(projectRoot), { force: true }); } catch { /* non-critical */ }
+}
+
export interface WorkspaceConfig {
workspace_id: string;
workspace_name: string;
@@ -128,7 +144,7 @@ export function absoluteFromSourceUri(sourceUri: string, explicitRoot?: string):
const root = resolveWorkspaceRoot(explicitRoot);
// POSIX-normalize the relative segment before joining.
const normalized = sourceUri.replace(/\\/g, "/");
- return require("node:path").resolve(root, normalized);
+ return resolvePath(root, normalized);
}
export function resolveWorkspaceRoot(explicitRoot?: string): string {
diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.ts
index e54fb268..3646b48f 100644
--- a/ix-cli/src/cli/resolve.ts
+++ b/ix-cli/src/cli/resolve.ts
@@ -1,9 +1,32 @@
import * as path from "node:path";
import chalk from "chalk";
import type { IxClient } from "../client/api.js";
-import { getActiveWorkspaceRoot } from "./config.js";
import { stderr } from "./stderr.js";
import { applyRoleFilter } from "./role-filter.js";
+import { detectSystem } from "./system.js";
+import { resolveWorkspaceId } from "./bootstrap.js";
+
+/**
+ * The read scope for the current working directory: a co-ingested multi-repo system
+ * scopes by system_id (spanning all members); otherwise by the single workspace_id.
+ * Computed once per cwd (detectSystem does FS reads) since a command never changes cwd.
+ * Mirrors the server-side scoping that search/inventory/stats already apply — without
+ * it, entity resolution searched the whole backend and a stale absolute path filter
+ * (getActiveWorkspaceRoot vs. workspace-relative source_uri) dropped every candidate
+ * (issue #228, originally fixed in search.ts only).
+ */
+let _scopeCache: { cwd: string; workspaceId?: string; systemId?: string } | undefined;
+export function activeReadScope(): { workspaceId?: string; systemId?: string } {
+ return activeScope();
+}
+function activeScope(): { workspaceId?: string; systemId?: string } {
+ const cwd = process.cwd();
+ if (_scopeCache?.cwd === cwd) return _scopeCache;
+ const systemId = detectSystem(cwd)?.systemId;
+ const workspaceId = systemId ? undefined : resolveWorkspaceId(cwd);
+ _scopeCache = { cwd, workspaceId, systemId };
+ return _scopeCache;
+}
export type ResolutionMode = "exact" | "preferred-kind" | "scored" | "ambiguous" | "heuristic";
@@ -148,12 +171,18 @@ export async function resolveEntityFull(
preferredKinds: string[],
opts?: { kind?: string; path?: string; pick?: number; includeTests?: boolean; testsOnly?: boolean; searchLimit?: number }
): Promise<ResolveResult> {
- const effectivePath = opts?.path ?? getActiveWorkspaceRoot();
+ // Scope is applied server-side (workspace_id, or system_id for a co-ingest). Only an
+ // EXPLICIT --path narrows further, client-side; we no longer default the path filter
+ // to the absolute workspace root, which never matched workspace-relative source_uris.
+ const effectivePath = opts?.path;
+ const { workspaceId, systemId } = activeScope();
const kindFilter = opts?.kind;
const nodes = await client.search(symbol, {
- limit: opts?.searchLimit ?? (effectivePath ? 200 : looksTypeLikeSymbol(symbol) ? 50 : 20),
+ limit: opts?.searchLimit ?? (effectivePath ? 200 : looksTypeLikeSymbol(symbol) ? 50 : 30),
kind: kindFilter,
nameOnly: true,
+ workspaceId,
+ systemId,
});
if (nodes.length === 0) {
@@ -596,13 +625,17 @@ async function tryFileGraphMatch(
): Promise<ResolvedEntity | null> {
const basename = path.basename(target);
const targetHasPath = target.includes("/") || target.includes("\\");
- const effectivePath = opts?.path ?? getActiveWorkspaceRoot();
+ // Explicit --path only (not the absolute workspace root); scope server-side instead.
+ const effectivePath = opts?.path;
+ const { workspaceId, systemId } = activeScope();
// Search for file entities matching the basename
const nodes = await client.search(basename, {
- limit: effectivePath ? 200 : 20,
+ limit: effectivePath ? 200 : 50,
kind: "file",
nameOnly: true,
+ workspaceId,
+ systemId,
});
// Filter to actual matches
diff --git a/ix-cli/src/cli/system.ts b/ix-cli/src/cli/system.ts
index f4a45c06..25112bc5 100644
--- a/ix-cli/src/cli/system.ts
+++ b/ix-cli/src/cli/system.ts
@@ -359,12 +359,24 @@ export function detectSystem(rootPath: string): DetectedSystem | undefined {
};
}
+/**
+ * The canonical, path-based workspace_id for a repo root. A repo gets the SAME
+ * id whether it is ingested standalone (`ix map <repo>`) or as a member of a
+ * system (`ix map <parent>`), which is exactly what keeps a member's node
+ * identity byte-identical across both modes. Single source of truth shared by the
+ * solo path (bootstrap.getOrCreateWorkspace) and the co-ingest path
+ * (repoWorkspaceIdFor); both MUST agree or solo and co-ingest nodes diverge.
+ */
+export function workspaceIdForPath(absPath: string): string {
+ const abs = nodePath.resolve(absPath).split(nodePath.sep).join("/");
+ return stableId(`repo:${abs}`);
+}
+
/**
* A member repo's stable workspace_id, derived from its absolute path so it is
* independent of which system it sits in (Path-2 friendly) and stable across
* re-ingests of the same location.
*/
export function repoWorkspaceIdFor(rootPath: string, repoDir: string): string {
- const abs = nodePath.resolve(rootPath, repoDir).split(nodePath.sep).join("/");
- return stableId(`repo:${abs}`);
+ return workspaceIdForPath(nodePath.resolve(rootPath, repoDir));
}
diff --git a/ix-cli/src/client/api.ts b/ix-cli/src/client/api.ts
index 3c9d17a3..0f311200 100644
--- a/ix-cli/src/client/api.ts
+++ b/ix-cli/src/client/api.ts
@@ -208,9 +208,15 @@ export class IxClient {
return this.post("/v1/patches/batch", patches);
}
- async getSourceHashes(filePaths: string[]): Promise<Map<string, string>> {
- const result = await this.post<Record<string, string>>('/v1/source-hashes', { uris: filePaths });
- return new Map(Object.entries(result));
+ // Workspace-scoped baseline lookup (Ix#225). Returns one row per (workspace_id, uri)
+ // so the caller can match each file against its OWN workspace's hash, instead of a
+ // bare uri->hash map that collides across workspaces sharing a relative path. Passing
+ // workspaceIds bounds the query server-side. workspaceId is null for legacy patches.
+ async getSourceHashes(
+ filePaths: string[],
+ workspaceIds?: string[],
+ ): Promise<Array<{ workspaceId: string | null; uri: string; hash: string }>> {
+ return this.post('/v1/source-hashes', { uris: filePaths, workspaceIds });
}
async map(opts?: { full?: boolean; workspaceId?: string; systemId?: string }): Promise<any> {
@@ -320,6 +326,13 @@ export class IxClient {
);
}
+ // Delete all nodes/edges/patches under a single workspace_id (Ix#225 gap 2: clean up
+ // the orphans left when a workspace's id is migrated to the path-based id). Scoped to
+ // exactly that id server-side; other workspaces are untouched.
+ async deleteWorkspace(workspaceId: string): Promise<void> {
+ await this.post("/v1/reset/workspace", { workspaceId });
+ }
+
// True when the configured endpoint is a local memory-layer. A local
// backend has no proxy in front of it, so the sync reset path connects
// directly and returns in milliseconds — there is nothing to fix there.