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): ingest a path into the workspace it belongs to
KageBinary58c2cfeb5239
diff --git a/docs-site/src/content/docs/reference/commands.md b/docs-site/src/content/docs/reference/commands.mdindex 25c885bf..612e2913 100644--- a/docs-site/src/content/docs/reference/commands.md+++ b/docs-site/src/content/docs/reference/commands.md@@ -66,7 +66,11 @@ These commands combine several graph queries into one bounded answer. Reach for| `ix watch` | Re-map on every change | `ix watch` || `ix ingest [path]` | Ingest files, or GitHub data | `ix ingest --github owner/repo --limit 50` |-`ix ingest` honors `--exclude <glob>` and an `.ixignore` file at the ingest root. `.ixignore` supports a subset of+`ix ingest <path>` writes to the workspace the path belongs to: the registered workspace containing it, else its+git repository. A file or directory inside that workspace refreshes just that part of it, and the rest of the+workspace is left alone. A path outside every workspace and repository is ingested as a workspace of its own.++`ix ingest` honors `--exclude <glob>` and an `.ixignore` file at the workspace root. `.ixignore` supports a subset of`.gitignore` syntax: `#` comments, `*`, `?`, `**`, a leading `/` to anchor to the root, a trailing `/` fordirectories, and bare names that match at any depth. There is no `!` negation.diff --git a/ix-cli/src/cli/__tests__/ingest-files.test.ts b/ix-cli/src/cli/__tests__/ingest-files.test.tsindex 0099f82f..b4bfdb36 100644--- a/ix-cli/src/cli/__tests__/ingest-files.test.ts+++ b/ix-cli/src/cli/__tests__/ingest-files.test.ts@@ -9,7 +9,8 @@ import { join } from "node:path";import { execFileSync } from "node:child_process";import { ingestFiles } from "../commands/ingest.js";-import { ingestMtimeCachePath, ingestRebuildPath } from "../config.js";+import { ingestMtimeCachePath, ingestRebuildPath, loadConfig } from "../config.js";+import { workspaceIdForPath } from "../system.js";/*** Integration tests that drive `ingestFiles` end to end against a fake backend.@@ -48,6 +49,10 @@ class FakeBackend {readonly requests: Array<{ path: string; patches: number; code?: number }> = [];/** `source.uri` of every patch sent in a commit request, accepted or not. */readonly sourceUris: string[] = [];+ /** `source.workspaceId` beside each of `sourceUris`, in the same order. */+ readonly sourceWorkspaceIds: Array<string | undefined> = [];+ /** The ops of the last patch sent for each `source.uri`. */+ readonly lastOps = new Map<string, Array<Record<string, unknown>>>();/** Paths this fake does not implement. Asserted empty after every test. */readonly unknownPaths: string[] = [];@@ -232,7 +237,11 @@ class FakeBackend {};if (path === "/v1/patches/bulk" || path === "/v1/patch") {- type SentPatch = { patchId?: string; source?: { uri?: string; sourceHash?: string; workspaceId?: string } };+ type SentPatch = {+ patchId?: string;+ source?: { uri?: string; sourceHash?: string; workspaceId?: string };+ ops?: Array<Record<string, unknown>>;+ };let patches: SentPatch[] = [];try {const parsed = JSON.parse(body) as { patches?: SentPatch[] };@@ -241,7 +250,12 @@ class FakeBackend {/* a body we cannot read is still a request */}this.requests.push({ path, patches: patches.length });- for (const { source } of patches) if (source?.uri) this.sourceUris.push(source.uri);+ for (const { source, ops } of patches) {+ if (!source?.uri) continue;+ this.sourceUris.push(source.uri);+ this.sourceWorkspaceIds.push(source.workspaceId);+ this.lastOps.set(source.uri, ops ?? []);+ }if (this.abortAfterCommits !== undefined && this.commitCount >= this.abortAfterCommits) {this.aborter.abort();}@@ -1047,4 +1061,186 @@ describe("ingestFiles against a fake backend", () => {expect(backend.bulkCount).toBe(1);expect(backend.singleCount, "the fan-out is for failures only").toBe(0);});++ // ── Which workspace a path belongs to ─────────────────────────────────+ //+ // `ix ingest <path>` used to treat the path as its own workspace root: `ix+ // ingest src/a.ts` in a mapped repo registered `repo/src` as a second+ // workspace, sent `a.ts` instead of `src/a.ts` under that workspace's id,+ // and from then on every read under `src/` resolved to the hollow one.++ /** Register `roots` in the config by hand, so no ingest has run yet. */+ const register = (...roots: Array<{ root: string; isDefault?: boolean }>): void => {+ mkdirSync(join(home, ".ix"), { recursive: true });+ writeFileSync(join(home, ".ix", "config.yaml"), [+ "endpoint: http://localhost:8090",+ "format: text",+ "workspaces:",+ ...roots.flatMap(({ root, isDefault }) => [+ ` - workspace_id: "${workspaceIdForPath(root)}"`,+ ` workspace_name: ${root.split(/[\\/]/).pop()}`,+ ` root_path: ${root}`,+ ` default: ${isDefault === true}`,+ ]),+ "",+ ].join("\n"));+ };+ const registered = () =>+ (loadConfig().workspaces ?? []).map(w => ({ root: w.root_path, id: w.workspace_id, isDefault: w.default }));+ const sent = () => backend.sourceUris.map((uri, i) => ({ uri, workspaceId: backend.sourceWorkspaceIds[i] }));+ const quiet = { format: "text", suppressOutput: true, printSummary: false } as const;++ it("ingests a file or subdirectory inside a registered workspace into THAT workspace", async () => {+ fixture(2);+ mkdirSync(join(repo, "src", "util"), { recursive: true });+ writeFileSync(join(repo, "src", "util", "u.ts"), "export const u = 1;\n", "utf8");+ execFileSync("git", ["add", "-A"], { cwd: repo, stdio: "ignore" });+ // Registered, but deliberately NOT the default: a stray registration+ // became the default whenever none was set.+ register({ root: repo, isDefault: false });+ const before = registered();+ const repoId = workspaceIdForPath(repo);++ await ingestFiles(join(repo, "src", "m001.ts"), { ...quiet, force: true });+ expect(sent()).toEqual([{ uri: "src/m001.ts", workspaceId: repoId }]);++ backend.sourceUris.length = 0;+ backend.sourceWorkspaceIds.length = 0;+ await ingestFiles(join(repo, "src", "util"), { ...quiet, force: true });+ expect(sent()).toEqual([{ uri: "src/util/u.ts", workspaceId: repoId }]);++ expect(registered(), "no workspace registered, and the default left alone").toEqual(before);+ });++ it("uses the git root for a path in a repository nobody has registered", async () => {+ fixture(2);+ await ingestFiles(join(repo, "src"), { ...quiet, force: true });++ expect(registered()).toEqual([{ root: repo, id: workspaceIdForPath(repo), isDefault: true }]);+ expect([...new Set(sent().map(s => `${s.workspaceId} ${s.uri}`))].sort()).toEqual([+ `${workspaceIdForPath(repo)} src/m000.ts`,+ `${workspaceIdForPath(repo)} src/m001.ts`,+ ]);+ });++ it("still gives a path in no workspace and no repository a workspace of its own", async () => {+ // `repo` here is a plain directory: no `fixture()`, so no `git init`.+ const outside = join(repo, "loose");+ mkdirSync(outside, { recursive: true });+ writeFileSync(join(outside, "x.ts"), "export const x = 1;\n", "utf8");++ await ingestFiles(join(outside, "x.ts"), { ...quiet, force: true });++ expect(registered()).toEqual([{ root: outside, id: workspaceIdForPath(outside), isDefault: true }]);+ expect(sent()).toEqual([{ uri: "x.ts", workspaceId: workspaceIdForPath(outside) }]);+ });++ it("leaves everything outside a subdirectory run alone: deletions, baseline, extractor, stitch", async () => {+ fixture(2);+ mkdirSync(join(repo, "lib"), { recursive: true });+ writeFileSync(join(repo, "lib", "l0.ts"), "export const l0 = 0;\n", "utf8");+ writeFileSync(join(repo, "lib", "l1.ts"), "export const l1 = 1;\n", "utf8");+ execFileSync("git", ["add", "-A"], { cwd: repo, stdio: "ignore" });+ backend.rememberHashes = true;+ type Stored = { files: Record<string, number>; extractor?: string; lastIngestAt: string };+ const stored = () => JSON.parse(readFileSync(ingestMtimeCachePath(repo), "utf8")) as Stored;++ await ingestFiles(repo, quiet);+ // An older extractor on record: a full run would re-ingest everything and+ // record the new name; a run over `src/` has vouched for none of `lib/`.+ writeFileSync(ingestMtimeCachePath(repo), JSON.stringify({ ...stored(), extractor: "tree-sitter/0.1" }));+ const baselineBefore = stored();+ const deleted = join(repo, "lib", "l0.ts");+ expect(Object.keys(baselineBefore.files)).toContain(deleted);++ // Gone from disk, so a run over the whole root would delete it. A run over+ // `src/` must not: it says nothing about `lib/`. (Were it attempted, the+ // reconcile's `GET /v1/patches/...` would land in `unknownPaths`.)+ rmSync(deleted);+ execFileSync("git", ["add", "-A"], { cwd: repo, stdio: "ignore" });+ backend.resetRequests();+ backend.sourceUris.length = 0;+ const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ try {+ // --force, so nothing is skipped as unchanged: on the whole root that+ // is exactly the run that re-registers the stitch.+ await ingestFiles(join(repo, "src"), { ...quiet, force: true });+ } finally {+ stderr.mockRestore();+ }++ expect([...new Set(backend.sourceUris)].sort()).toEqual(["src/m000.ts", "src/m001.ts"]);+ expect(backend.stitchCount, "a slice of the repo is not its registration").toBe(0);+ const after = stored();+ expect(after.files[deleted], "the deletion is the next full map's").toBe(baselineBefore.files[deleted]);+ expect(after.files[join(repo, "lib", "l1.ts")]).toBe(baselineBefore.files[join(repo, "lib", "l1.ts")]);+ expect(Object.keys(after.files).sort()).toEqual(Object.keys(baselineBefore.files).sort());+ expect(after.extractor, "the rest of the workspace keeps its extractor").toBe("tree-sitter/0.1");+ expect(after.lastIngestAt, "the last full ingest is still the last full ingest").toBe(baselineBefore.lastIngestAt);+ expect(existsSync(ingestRebuildPath(repo)), "no whole-workspace rebuild is started").toBe(false);+ });++ it("resolves a scoped run's edges against the whole workspace, not just the scope", async () => {+ // `src/a.ts` imports `lib/b.ts`. A run over `src/` re-sends a.ts's patch,+ // and resolving it against `src/` alone dropped the import edge from it.+ mkdirSync(join(repo, "src"), { recursive: true });+ mkdirSync(join(repo, "lib"), { recursive: true });+ writeFileSync(join(repo, "lib", "b.ts"), "export function b(): number { return 1; }\n", "utf8");+ writeFileSync(join(repo, "src", "a.ts"), "import { b } from '../lib/b';\nexport function a(): number { return b(); }\n", "utf8");+ execFileSync("git", ["init", "-q"], { cwd: repo, stdio: "ignore" });+ execFileSync("git", ["add", "-A"], { cwd: repo, stdio: "ignore" });+ const edges = () => (backend.lastOps.get("src/a.ts") ?? [])+ .filter(op => op.type === "UpsertEdge")+ .map(op => `${String(op.predicate)} ${String(op.dst)}`)+ .sort();++ await ingestFiles(repo, { ...quiet, force: true });+ const full = edges();+ expect(full.some(e => e.startsWith("IMPORTS ")), "the fixture has an import edge to lose").toBe(true);++ backend.lastOps.clear();+ await ingestFiles(join(repo, "src"), { ...quiet, force: true });+ expect(edges()).toEqual(full);+ });++ it("writes no baseline from a subdirectory run when the workspace has none", async () => {+ // One written from `src/` alone would report the whole graph complete.+ fixture(2);+ mkdirSync(join(repo, "lib"), { recursive: true });+ writeFileSync(join(repo, "lib", "l0.ts"), "export const l0 = 0;\n", "utf8");+ execFileSync("git", ["add", "-A"], { cwd: repo, stdio: "ignore" });+ register({ root: repo, isDefault: true });++ await ingestFiles(join(repo, "src"), { ...quiet, force: true });++ expect(existsSync(ingestMtimeCachePath(repo))).toBe(false);+ expect(existsSync(ingestMtimeCachePath(join(repo, "src")))).toBe(false);+ });++ it("keeps a member repo's own workspace id, inside a registered system or on its own", async () => {+ // `repo` is the plain folder holding two independently cloned repos.+ for (const member of ["alpha", "beta"]) {+ mkdirSync(join(repo, member), { recursive: true });+ writeFileSync(join(repo, member, `${member}.ts`), `export const ${member} = 1;\n`, "utf8");+ execFileSync("git", ["init", "-q"], { cwd: join(repo, member), stdio: "ignore" });+ execFileSync("git", ["add", "-A"], { cwd: join(repo, member), stdio: "ignore" });+ }+ const alpha = join(repo, "alpha");+ const alphaId = workspaceIdForPath(alpha);++ // Standalone: nothing registered, so the member's git root -- exactly+ // what `ix map` inside it produces.+ await ingestFiles(join(alpha, "alpha.ts"), { ...quiet, force: true });+ expect(sent()).toEqual([{ uri: "alpha.ts", workspaceId: alphaId }]);+ expect(registered().map(w => w.root)).toEqual([alpha]);++ // Inside the registered system: the system's workspace, with the uri the+ // co-ingest gave the file and, still, the member's own id.+ register({ root: repo, isDefault: true });+ backend.sourceUris.length = 0;+ backend.sourceWorkspaceIds.length = 0;+ await ingestFiles(join(alpha, "alpha.ts"), { ...quiet, force: true });+ expect(sent()).toEqual([{ uri: "alpha/alpha.ts", workspaceId: alphaId }]);+ expect(registered().map(w => w.root)).toEqual([repo]);+ });});diff --git a/ix-cli/src/cli/__tests__/map-root.test.ts b/ix-cli/src/cli/__tests__/map-root.test.tsindex 1a036c41..3e1b7196 100644--- a/ix-cli/src/cli/__tests__/map-root.test.ts+++ b/ix-cli/src/cli/__tests__/map-root.test.ts@@ -7,7 +7,8 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { Command } from "commander";import { registerMapCommand } from "../commands/map.js";-import { canonicalMapRoot, resolveMapRoot } from "../map-root.js";+import { canonicalMapRoot, resolveIngestRoot, resolveMapRoot } from "../map-root.js";+import { loadConfig } from "../config.js";import { lockPathForTest } from "../single-flight.js";const fixtures: string[] = [];@@ -171,3 +172,80 @@ describe("map root resolution", () => {expect(() => canonicalMapRoot(file)).toThrow(`Map path is not a directory: ${file}`);});});++describe("ingest root resolution", () => {+ const writeWorkspaces = (...roots: string[]): void => {+ writeFileSync(join(home, ".ix", "config.yaml"), [+ "endpoint: http://localhost:8090",+ "workspaces:",+ ...roots.flatMap((root, i) => [+ ` - workspace_id: id-${i}`,+ ` workspace_name: ws-${i}`,+ ` root_path: ${root}`,+ ` default: ${i === 0}`,+ ]),+ "",+ ].join("\n"));+ };++ it("puts a file or subdirectory of a registered workspace in that workspace", () => {+ const repo = realpathSync.native(fixture());+ mkdirSync(join(repo, "src", "util"), { recursive: true });+ writeFileSync(join(repo, "src", "a.ts"), "export {};\n");+ writeWorkspaces(repo);++ expect(resolveIngestRoot(join(repo, "src", "a.ts"), false)).toBe(repo);+ expect(resolveIngestRoot(join(repo, "src", "util"), true)).toBe(repo);+ expect(resolveIngestRoot(repo, true)).toBe(repo);+ });++ it("prefers the nearest registered workspace over an enclosing one and over the git root", () => {+ const repo = realpathSync.native(fixture());+ const member = join(repo, "member");+ mkdirSync(join(member, "src"), { recursive: true });+ execFileSync("git", ["init", "-q"], { cwd: repo });+ writeWorkspaces(repo, member);++ expect(resolveIngestRoot(join(member, "src"), true)).toBe(member);+ });++ it("uses the git root of a path in an unregistered repository", () => {+ const repo = realpathSync.native(fixture());+ mkdirSync(join(repo, "src"), { recursive: true });+ writeFileSync(join(repo, "src", "a.ts"), "export {};\n");+ execFileSync("git", ["init", "-q"], { cwd: repo });++ expect(resolveIngestRoot(join(repo, "src"), true)).toBe(repo);+ expect(resolveIngestRoot(join(repo, "src", "a.ts"), false)).toBe(repo);+ });++ it("falls back to the directory itself, or a file's directory, outside every workspace and repo", () => {+ const loose = realpathSync.native(fixture());+ mkdirSync(join(loose, "dir"));+ writeFileSync(join(loose, "x.ts"), "export {};\n");+ // A registered default elsewhere does not claim it: the user named a path.+ writeWorkspaces(realpathSync.native(fixture()));++ expect(resolveIngestRoot(join(loose, "dir"), true)).toBe(join(loose, "dir"));+ expect(resolveIngestRoot(join(loose, "x.ts"), false)).toBe(loose);+ });++ it("takes --root first, and refuses a path outside it", () => {+ const repo = realpathSync.native(fixture());+ const other = realpathSync.native(fixture());+ mkdirSync(join(repo, "src"), { recursive: true });+ execFileSync("git", ["init", "-q"], { cwd: repo });++ expect(resolveIngestRoot(join(repo, "src"), true, join(repo, "src"))).toBe(join(repo, "src"));+ expect(() => resolveIngestRoot(join(repo, "src"), true, other)).toThrow(/is outside --root/);+ });++ it("does not register anything itself", () => {+ const repo = realpathSync.native(fixture());+ mkdirSync(join(repo, "src"), { recursive: true });+ execFileSync("git", ["init", "-q"], { cwd: repo });++ resolveIngestRoot(join(repo, "src"), true);+ expect(loadConfig().workspaces ?? []).toEqual([]);+ });+});diff --git a/ix-cli/src/cli/bootstrap.ts b/ix-cli/src/cli/bootstrap.tsindex 69508055..076706fb 100644--- a/ix-cli/src/cli/bootstrap.ts+++ b/ix-cli/src/cli/bootstrap.ts@@ -127,9 +127,9 @@ export function ensureWorkspaceRegistered(cwd = process.cwd()): { registered: bo* 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 };+export function ensureWorkspaceIdState(cwd = process.cwd()): { workspaceId: string; migrated: boolean; previousWorkspaceId?: string; created: boolean; name: string } {+ const { ws, migrated, previousWorkspaceId, created } = getOrCreateWorkspace(cwd);+ return { workspaceId: ws.workspace_id, migrated, previousWorkspaceId, created, name: ws.workspace_name };}/**diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.tsindex 9ed5b02b..47f9ff07 100644--- a/ix-cli/src/cli/commands/ingest.ts+++ b/ix-cli/src/cli/commands/ingest.ts@@ -12,7 +12,8 @@ import { ParsePool } from './parse-pool.js';import chalk from 'chalk';import { IxClient } from '../../client/api.js';import type { GraphPatchPayload } from '../../client/types.js';-import { canonicalWorkspacePath, getEndpoint, resolveWorkspaceRoot, clearMapResultCache, clearStitchScopeCache } from '../config.js';+import { canonicalWorkspacePath, getEndpoint, isPathInside, resolveWorkspaceRoot, clearMapResultCache, clearStitchScopeCache } from '../config.js';+import { resolveIngestRoot } from '../map-root.js';import {clearRebuildProgress, extractorChanged, isRev, loadIngestBaseline, loadRebuildProgress,saveIngestBaseline, saveRebuildProgress,@@ -1006,7 +1007,7 @@ export function registerIngestCommand(program: Command): void {(value: string, previous: string[] = []) => [...previous, value],[] as string[],)- .addHelpText('after', '\nExamples:\n ix ingest ./src\n ix ingest --path ./src --force\n ix ingest --path ./rocksdb --lang cpp,c\n ix ingest --github owner/repo\n ix ingest --github owner/repo --since 2026-01-01 --limit 20 --format json\n ix ingest --github owner/repo --token ghp_xxxx')+ .addHelpText('after', '\nExamples:\n ix ingest ./src\n ix ingest --path ./src --force\n ix ingest --path ./rocksdb --lang cpp,c\n ix ingest --github owner/repo\n ix ingest --github owner/repo --since 2026-01-01 --limit 20 --format json\n ix ingest --github owner/repo --token ghp_xxxx\n\nA path inside a mapped workspace (or a git repo) refreshes just that part of it, under that\nworkspace; a path outside every workspace and repo is ingested as a workspace of its own.').action(async (positionalPath: string | undefined, opts: {path?: string; recursive?: boolean; force?: boolean; github?: string; token?: string;since?: string; limit: string; format: string; root?: string; debug?: boolean; lang?: string;@@ -1541,10 +1542,29 @@ export async function ingestFiles(// (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, migrated: workspaceMigrated, previousWorkspaceId } = ensureWorkspaceIdState(workspaceRoot);+ //+ // The workspace is the one the path BELONGS to, not the path itself: see+ // `resolveIngestRoot`. A path strictly inside that root is a scoped run --+ // discovery, deletion and the stitch are limited to it, and the rest of the+ // workspace's baseline is carried forward untouched.+ const workspaceRoot = resolveIngestRoot(resolvedPath, fs.statSync(resolvedPath).isDirectory(), opts.root);+ const {+ workspaceId,+ migrated: workspaceMigrated,+ previousWorkspaceId,+ created: workspaceCreated,+ name: workspaceName,+ } = ensureWorkspaceIdState(workspaceRoot);+ if (workspaceCreated && !opts.suppressOutput && opts.format === 'text') {+ process.stderr.write(chalk.dim(`Registered workspace "${workspaceName}" (${workspaceRoot}).\n`));+ }+ // What this run discovers. A migrated workspace is widened to its root: the+ // re-key below re-ingests everything under the new id and then deletes the+ // old id's graph, which after a scoped run would leave the rest of the+ // workspace with no nodes and a baseline vouching for them.+ const scopePath = workspaceMigrated ? workspaceRoot : resolvedPath;+ const scopedRun = scopePath !== workspaceRoot;+ const inScope = (absPath: string): boolean => !scopedRun || isPathInside(scopePath, absPath);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@@ -1984,18 +2004,20 @@ export async function ingestFiles(// Phase: discover filesconst langFilter = opts.lang ? parseLangs(opts.lang) : null;- const stat = fs.statSync(resolvedPath);- const excludePatterns = collectExcludePatterns(resolvedPath, opts.exclude ?? []);+ const stat = fs.statSync(scopePath);+ // `.ixignore` and `--exclude` are the WORKSPACE's, matched root-relative,+ // so a scoped run leaves out exactly what a map of the whole root would.+ const excludePatterns = collectExcludePatterns(workspaceRoot, opts.exclude ?? []);const excludeMatcher = createIgnoreMatcher(excludePatterns);const exclude = excludeMatcher.size > 0- ? { matcher: excludeMatcher, root: resolvedPath, onSkip: () => { filesExcluded += 1; } }+ ? { matcher: excludeMatcher, root: workspaceRoot, onSkip: () => { filesExcluded += 1; } }: undefined;const discovery = discoverIngestFilePaths(stat.isFile()- ? (isSupportedSourceFile(resolvedPath) ? [resolvedPath] : [])- : (tryGitLsFiles(resolvedPath, opts.recursive ?? true, exclude)- ?? Array.from(walkFiles(resolvedPath, opts.recursive ?? true, exclude))),- stat.isFile() ? undefined : resolvedPath,+ ? (isSupportedSourceFile(scopePath) ? [scopePath] : [])+ : (tryGitLsFiles(scopePath, opts.recursive ?? true, exclude)+ ?? Array.from(walkFiles(scopePath, opts.recursive ?? true, exclude))),+ stat.isFile() ? undefined : scopePath,);// `--lang` narrows discovery to the named languages. The files it leaves// out keep their baseline entries (`langExcluded`, below): this run says@@ -2007,10 +2029,22 @@ export async function ingestFiles(const filePaths: string[] = langFilter ? discovery.files.filter(inLangFilter) : discovery.files;const langExcluded: string[] = langFilter ? discovery.files.filter(fp => !inLangFilter(fp)) : [];outsideRoot = discovery.outsideRoot;+ // The files edges may resolve TO. A scoped run parses only its own files,+ // but an import from `src/a.ts` to `lib/b.ts` still names a file the+ // workspace holds: resolving against the scope alone would drop that edge+ // from every file the run re-sends. Paths only -- nothing outside the+ // scope is read or parsed.+ const resolutionPaths = scopedRun+ ? discoverIngestFilePaths(+ tryGitLsFiles(workspaceRoot, true, exclude && { ...exclude, onSkip: undefined })+ ?? Array.from(walkFiles(workspaceRoot, true, exclude && { ...exclude, onSkip: undefined })),+ workspaceRoot,+ ).files+ : filePaths;const resolveOpts = {...crossRepoResolveOpts,- resolveModuleSpecifier: createTypeScriptModuleResolver(workspaceRoot, filePaths),- packageDirOf: declaredPackageDirs(workspaceRoot, filePaths),+ resolveModuleSpecifier: createTypeScriptModuleResolver(workspaceRoot, resolutionPaths),+ packageDirOf: declaredPackageDirs(workspaceRoot, resolutionPaths),};filesDiscovered = filePaths.length;@@ -2024,15 +2058,20 @@ 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);+ // The WORKSPACE's baseline, scoped run or not: it is the one record of what+ // the graph holds for this workspace, and a scoped run updates its own+ // files in it and carries every other entry forward.+ const projectRoot = workspaceRoot;// 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 previousBaseline = loadIngestBaseline(projectRoot);const currentExtractor = extractorName();- // A --lang or single-file run re-extracts only its own files, so it must- // not record the new extractor for the rest; keep the old one and the next- // full run still re-ingests them.- const partialRun = Boolean(opts.lang) || stat.isFile();+ // A --lang run, or one scoped to a file or directory below the root,+ // re-extracts only its own files, so it must not record the new extractor+ // for the rest; keep the old one and the next full run still re-ingests+ // them. The same goes for every other whole-workspace claim -- see the+ // baseline write and the stitch below.+ const partialRun = Boolean(opts.lang) || scopedRun;const baselineExtractor = partialRun ? previousBaseline?.extractor : currentExtractor;// Files a full re-ingest for this extractor has committed, recorded as they// land so a run cut short resumes instead of starting over; null when no@@ -2049,7 +2088,9 @@ export async function ingestFiles(`\n [extractor changed] ${previousBaseline?.extractor ?? 'unrecorded'} -> ${currentExtractor}. ` +(resumedRebuild? `Resuming the re-ingest: ${resumedRebuild.size} of ${filePaths.length} files already done.\n`- : `Re-ingesting every file once.\n`),+ : partialRun+ ? `Re-ingesting the ${filePaths.length} file(s) in this run; the next full map re-ingests the rest.\n`+ : `Re-ingesting every file once.\n`),);// A resumed re-ingest is not forced: the files it already committed are// skipped by mtime below, and every other file is forced one by one.@@ -2146,10 +2187,12 @@ export async function ingestFiles(}}+ // Only inside the scope: a scoped run says nothing about the rest of the+ // workspace, so a file missing there is the next full map's to delete.const deletedPaths = workspaceMigrated? []: [...previousMtimes.keys()].filter(filePath =>- !currentMtimes.has(filePath) && !fs.existsSync(filePath)+ inScope(filePath) && !currentMtimes.has(filePath) && !fs.existsSync(filePath));if (deletedPaths.length > 0) deletionsFound = true;@@ -3180,7 +3223,7 @@ export async function ingestFiles(// parseFile.const relSources = new Map<string, string>();for (const [abs, text] of sources) relSources.set(toWorkspaceRelative(abs), text);- const relFilePaths = filePaths.map(toWorkspaceRelative);+ const relFilePaths = resolutionPaths.map(toWorkspaceRelative);const preParsed = await preParsePrescanSources(relSources);globalIndex = (ingestion.buildGlobalResolutionIndex as Function)(relFilePaths, relSources, preParsed);sources.clear();@@ -3249,7 +3292,7 @@ export async function ingestFiles(if (texts[j] != null) sources.set(toWorkspaceRelative(batch[j]), texts[j]!);}}- const relFilePaths = filePaths.map(toWorkspaceRelative);+ const relFilePaths = resolutionPaths.map(toWorkspaceRelative);const preParsed = await preParsePrescanSources(sources);globalIndex = ingestion.buildGlobalResolutionIndex(relFilePaths, sources, preParsed);sources.clear();@@ -3472,9 +3515,16 @@ export async function ingestFiles(// three guards would start caching mtimes for files whose patches never// landed. The next run would skip them as unchanged and they would stay// missing from the graph until a --force.- const baselinePersisted = persistIngestBaselineIfClean(+ // A scoped run carries every entry outside its scope forward, and keeps+ // the workspace's last full-ingest time: `lastIngestAt` is what a file+ // missing from the baseline is judged stale against, and only a run over+ // the whole root has looked at those. With no baseline to update it+ // writes none -- one written from a part of the workspace would mark the+ // whole graph complete.+ const outOfScope = scopedRun ? [...previousMtimes.keys()].filter(fp => !inScope(fp)) : [];+ const baselinePersisted = (scopedRun && !previousBaseline) ? false : persistIngestBaselineIfClean(projectRoot,- carryForwardMtimes(currentMtimes, previousMtimes, [...deferredDeletions, ...langExcluded]),+ carryForwardMtimes(currentMtimes, previousMtimes, [...deferredDeletions, ...langExcluded, ...outOfScope]),latestRev,// Lost parses count as parse errors HERE, whatever they are called// elsewhere. A run whose worker pool died resolves every later file as@@ -3486,7 +3536,7 @@ export async function ingestFiles(// respawns without a cap and loses one file per crash.parseErrors + crashedParses(),commitErrors,- undefined,+ scopedRun && previousBaseline ? new Date(previousBaseline.lastIngestAt) : undefined,nextDeletedFiles,baselineExtractor,);@@ -3542,7 +3592,10 @@ export async function ingestFiles(// that file's exports. A file `parseFile` simply returned null for is not --// that is deterministic, usually an unavailable optional grammar, and// gating on it blocked stitching forever for any repo containing one.- const registrationIsComplete = filesSkippedAsUnchanged === 0 && crashedParses() === 0;+ // And never on a partial run (`--lang`, or a path below the root): it+ // parsed a part of the repo by construction, so even with nothing skipped+ // its provides/consumes would replace the full registration with a slice.+ const registrationIsComplete = !partialRun && filesSkippedAsUnchanged === 0 && crashedParses() === 0;// Every way the stitch does not happen is REPORTED, not just the guard's.// `stitch_skipped: null` means "the cross-repo edges are current", so every// path that leaves it unset while skipping the stitch says something false@@ -3577,9 +3630,11 @@ export async function ingestFiles(// current" for the commonest map there is, while a cooldown was refusing// stitches the whole time. The staleness is identical either way.stitchSkippedRule = "incomplete";- stitchSkipped =- "this map did not re-parse every file, so it has no complete cross-workspace " +- "registration to send";+ stitchSkipped = partialRun+ ? "this run ingested only part of the workspace, so it has no complete " ++ "cross-workspace registration to send"+ : "this map did not re-parse every file, so it has no complete cross-workspace " ++ "registration to send";}if (stitchEnabled && registrationIsComplete && stitchFiles.length > 0 && ingestCompletedCleanly(parseErrors, commitErrors)) {try {diff --git a/ix-cli/src/cli/map-root.ts b/ix-cli/src/cli/map-root.tsindex 1f468cbe..6db993e8 100644--- a/ix-cli/src/cli/map-root.ts+++ b/ix-cli/src/cli/map-root.ts@@ -1,8 +1,8 @@// Copyright 2026 Ix Infrastructure Inc.import { realpathSync, statSync } from "node:fs";-import { resolve } from "node:path";-import { findWorkspaceForCwd, gitRootFor, resolveWorkspaceRoot } from "./config.js";+import { dirname, resolve } from "node:path";+import { canonicalWorkspacePath, findWorkspaceForCwd, gitRootFor, isPathInside, resolveWorkspaceRoot } from "./config.js";export function canonicalMapRoot(candidate: string): string {const resolved = resolve(candidate);@@ -38,11 +38,56 @@ export function canonicalMapRoot(candidate: string): string {export function resolveMapRoot(pathArg?: string, cwd = process.cwd()): string {if (pathArg) return canonicalMapRoot(resolve(cwd, pathArg));- const nearest = findWorkspaceForCwd(cwd);- if (nearest) return canonicalMapRoot(nearest.root_path);-- const gitRoot = gitRootFor(cwd);- if (gitRoot) return canonicalMapRoot(gitRoot);+ const local = localRootFor(cwd);+ if (local) return canonicalMapRoot(local);return canonicalMapRoot(resolveWorkspaceRoot(undefined, cwd));}++/**+ * Steps 2 and 3 of both cascades in this file: the registered workspace+ * containing `dir`, else the git root of `dir`. Undefined when `dir` has+ * neither. The nearest registration wins, so a repo registered inside another+ * (a member of a multi-repo system mapped on its own) keeps its own root.+ */+export function localRootFor(dir: string): string | undefined {+ return findWorkspaceForCwd(dir)?.root_path ?? gitRootFor(dir);+}++/**+ * Which workspace does `ix ingest <path>` write to?+ *+ * Not simply the path. Treating it as its own root made `ix ingest src/a.ts`+ * inside a mapped repo register `repo/src` as a second workspace, emit+ * `a.ts` instead of `src/a.ts` under that workspace's id, and from then on+ * route every read under `src/` to it. A path is a part of a workspace far+ * more often than it is one, so:+ *+ * 1. an explicit `--root` (the path must be inside it)+ * 2. the registered workspace containing the path+ * 3. the path's git root+ * 4. the path itself for a directory, its directory for a file -- a path+ * in no workspace and no repository is ingested as its own workspace.+ *+ * The same local-first order as `resolveMapRoot`, minus its named/default+ * workspace step: that one answers "which repo is cwd in", and a path the+ * user named outside every workspace and repository belongs to none of them.+ *+ * A path below the returned root is a partial ingest of that workspace; see+ * `ingestFiles`. Returned canonical (realpath'd), like the path ingest hands in.+ */+export function resolveIngestRoot(target: string, isDirectory: boolean, explicitRoot?: string): string {+ const canonicalTarget = canonicalWorkspacePath(target);+ if (explicitRoot) {+ const root = canonicalWorkspacePath(explicitRoot);+ let rootIsDirectory = false;+ try { rootIsDirectory = statSync(root).isDirectory(); } catch { /* reported below */ }+ if (!rootIsDirectory) throw new Error(`--root is not a directory: ${root}`);+ if (!isPathInside(root, canonicalTarget)) {+ throw new Error(`${canonicalTarget} is outside --root ${root}. Pass a path inside the root, or drop --root.`);+ }+ return root;+ }+ const probe = isDirectory ? canonicalTarget : dirname(canonicalTarget);+ return canonicalWorkspacePath(localRootFor(probe) ?? probe);+}diff --git a/ix-cli/src/mcp/server.ts b/ix-cli/src/mcp/server.tsindex cb92baf9..2bc68745 100644--- a/ix-cli/src/mcp/server.ts+++ b/ix-cli/src/mcp/server.ts@@ -646,7 +646,7 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServerregisterTool(ctx,"ix_ingest",- "Add a path or a GitHub repo to the graph. Slow; ix_map is the usual way in",+ "Add a path or a GitHub repo to the graph. A path inside a mapped workspace refreshes just that part of it. Slow; ix_map is the usual way in",{path: z.string().min(1).optional(),github: z.string().min(1).optional().describe("owner/repo"),diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.mdindex 33cae524..fe532b39 100644--- a/skills/ix/references/flags.md+++ b/skills/ix/references/flags.md@@ -84,8 +84,13 @@ surfaces (#575).d+1, so the first level is complete before the second begins. (The walkused to be depth-first, and could spend the whole cap down its firstbranch.) A walk the cap does not cut is the same tree it always was.-- **`ix ingest` honours `--exclude <glob>` and a `.ixignore` at the ingest- root.** A deliberate subset of `.gitignore`: `#` comments, `*`, `?`, `**`, a+- **`ix ingest <path>` writes to the workspace the path belongs to** -- the+ registered workspace containing it, else its git repository -- and a file or+ directory inside it refreshes just that part, leaving the rest of the+ workspace alone. Only a path in no workspace and no repository becomes a+ workspace of its own.+- **`ix ingest` honours `--exclude <glob>` and a `.ixignore` at the workspace+ root**, matched relative to that root. A deliberate subset of `.gitignore`: `#` comments, `*`, `?`, `**`, aleading `/` to anchor at the root, a trailing `/` for directories only, and abare name matching at any depth. **No** `!` negation and no characterclasses — a pattern that starts with `!` is dropped rather than half-honoured.