Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix(ingest): ix ingest of an outside path never widens what ix read can open (CL-05) (#840)

Ian Hock71847108c2cb
diff --git a/docs-site/src/content/docs/reference/commands.md b/docs-site/src/content/docs/reference/commands.md
index adfdacf6..c4c1e7fc 100644
--- a/docs-site/src/content/docs/reference/commands.md
+++ b/docs-site/src/content/docs/reference/commands.md
@@ -68,7 +68,8 @@ These commands combine several graph queries into one bounded answer. Reach for
`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.
+workspace is left alone. A directory outside every workspace and repository becomes a workspace of its own (never
+the default). A loose file there is ingested but registers nothing, so `ix read` cannot open its neighbours.
`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 `/` for
diff --git a/ix-cli/src/cli/__tests__/ingest-files.test.ts b/ix-cli/src/cli/__tests__/ingest-files.test.ts
index af6f4e09..5aedf344 100644
--- a/ix-cli/src/cli/__tests__/ingest-files.test.ts
+++ b/ix-cli/src/cli/__tests__/ingest-files.test.ts
@@ -10,6 +10,7 @@ import { ingestFiles, ingestPathSingleFlight } from "../commands/ingest.js";
import { acquireMapLock, takeMapRerun } from "../single-flight.js";
import { ingestMtimeCachePath, ingestRebuildPath, ingestSymbolsJournalPath, ingestSymbolsPath, loadConfig } from "../config.js";
import { workspaceIdForPath } from "../system.js";
+import { ensureWorkspaceRegistered } from "../bootstrap.js";
import { FakeBackend } from "./helpers/fake-backend.js";
import { runWithSignal } from "../../client/run-signal.js";
import { loadIngestBaseline } from "../ingest-baseline.js";
@@ -1472,23 +1473,100 @@ describe("ingestFiles against a fake backend", () => {
fixture(2);
await ingestFiles(join(repo, "src"), { ...quiet, force: true });
- expect(registered()).toEqual([{ root: repo, id: workspaceIdForPath(repo), isDefault: true }]);
+ expect(registered(), "registered, and the default since none existed").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 () => {
+ it("ingests a loose FILE under its directory's id but registers nothing", 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");
+ const configPath = join(home, ".ix", "config.yaml");
+ const before = existsSync(configPath) ? readFileSync(configPath, "utf8") : undefined;
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) }]);
+ expect(registered()).toEqual([]);
+ expect(existsSync(configPath) ? readFileSync(configPath, "utf8") : undefined).toBe(before);
+ });
+
+ it("a coalesced rerun for a loose FILE ingest does not register the file's directory either", async () => {
+ // The holder's rerun widens a loose file to its whole directory once that
+ // directory has a baseline; registering it would make the directory readable.
+ const outside = join(repo, "loose");
+ mkdirSync(outside, { recursive: true });
+ const first = join(outside, "x.ts");
+ const second = join(outside, "y.ts");
+ writeFileSync(first, "export const x = 1;\n", "utf8");
+ // The directory was ingested once and its registration since dropped from
+ // config.yaml by hand: unregistered, but it keeps its baseline.
+ await ingestFiles(outside, quiet);
+ register();
+ expect(registered()).toEqual([]);
+ expect(loadIngestBaseline(outside), "the loose directory has a baseline, so the rerun covers all of it").not.toBeNull();
+ writeFileSync(first, "export const x = 2;\n", "utf8");
+ writeFileSync(second, "export const y = 2;\n", "utf8");
+ const configPath = join(home, ".ix", "config.yaml");
+ const before = existsSync(configPath) ? readFileSync(configPath, "utf8") : undefined;
+ const stdout = vi.spyOn(console, "log").mockImplementation(() => undefined);
+ try {
+ // The lock is taken before the first await, so the waiter coalesces.
+ const holder = ingestPathSingleFlight(first, { format: "json" });
+ const waiter = ingestPathSingleFlight(second, { format: "json" });
+ await Promise.all([holder, waiter]);
+ } finally {
+ stdout.mockRestore();
+ }
+
+ expect(loadIngestBaseline(outside)!.files.get(second), "the rerun ran").toBe(statSync(second).mtimeMs);
+ expect(registered()).toEqual([]);
+ expect(existsSync(configPath) ? readFileSync(configPath, "utf8") : undefined).toBe(before);
+ });
+
+ it("registers a loose DIRECTORY after a successful ingest, but never as the default", async () => {
+ const outside = join(repo, "loose");
+ mkdirSync(outside, { recursive: true });
+ writeFileSync(join(outside, "x.ts"), "export const x = 1;\n", "utf8");
+
+ await ingestFiles(outside, { ...quiet, force: true });
+
+ expect(registered()).toEqual([{ root: outside, id: workspaceIdForPath(outside), isDefault: false }]);
+ expect(sent()).toEqual([{ uri: "x.ts", workspaceId: workspaceIdForPath(outside) }]);
+ });
+
+ it("a git-repo ingest that set the default stays the default through a later map's registration", async () => {
+ fixture(2);
+ await ingestFiles(join(repo, "src", "m000.ts"), { ...quiet, force: true });
+ // `ix map` registers through bootstrap -> ensureWorkspaceRegistered first.
+ ensureWorkspaceRegistered(repo);
+ expect(registered()).toEqual([{ root: repo, id: workspaceIdForPath(repo), isDefault: true }]);
+ });
+
+ it("an explicit --root ingest of a non-repository directory may become the default", async () => {
+ const outside = join(repo, "rooted");
+ mkdirSync(outside, { recursive: true });
+ writeFileSync(join(outside, "x.ts"), "export const x = 1;\n", "utf8");
+
+ await ingestFiles(outside, { ...quiet, force: true, root: outside });
+
+ expect(registered()).toEqual([{ root: realpathSync.native(outside), id: workspaceIdForPath(realpathSync.native(outside)), isDefault: true }]);
+ });
+
+ it("leaves an existing default workspace the only default", async () => {
+ fixture(2);
+ const other = join(repo, "..", `${repo.split(/[\\/]/).pop()}-default`);
+ mkdirSync(other, { recursive: true });
+ register({ root: realpathSync.native(other), isDefault: true });
+
+ await ingestFiles(join(repo, "src"), { ...quiet, force: true });
+
+ expect(registered().filter(w => w.isDefault).map(w => w.root)).toEqual([realpathSync.native(other)]);
+ expect(registered().map(w => w.root)).toContain(repo);
});
it("leaves everything outside a subdirectory run alone: deletions, baseline, extractor, stitch", async () => {
diff --git a/ix-cli/src/cli/__tests__/ingest-registration.test.ts b/ix-cli/src/cli/__tests__/ingest-registration.test.ts
index 6c25999f..71fbb438 100644
--- a/ix-cli/src/cli/__tests__/ingest-registration.test.ts
+++ b/ix-cli/src/cli/__tests__/ingest-registration.test.ts
@@ -4,12 +4,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
+import { execFileSync } from "node:child_process";
import { Command } from "commander";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
-import { workspaceStateFor } from "../bootstrap.js";
+import { ensureWorkspaceIdState, workspaceStateFor } from "../bootstrap.js";
import { registerIngestCommand } from "../commands/ingest.js";
import { registerReadCommand } from "../commands/read.js";
import { createIxMcpServer, type IxRunner } from "../../mcp/server.js";
@@ -164,4 +165,61 @@ describe("MCP ix_ingest is confined like ix_read", () => {
expect(calls[0]).toContain("a.ts");
await client.close();
});
+
+ it("refuses a loose path that is readable only through the cwd fallback", async () => {
+ const loose = path.join(t, "loose");
+ fs.mkdirSync(loose);
+ fs.writeFileSync(path.join(loose, "x.json"), "{}\n");
+ fs.writeFileSync(config, fs.readFileSync(config, "utf8").replace("default: true", "default: false"));
+ process.chdir(loose);
+ const calls: string[][] = [];
+ const client = await connect(async (args) => { calls.push(args); return { ok: true, stdout: "{}", stderr: "" }; });
+ const result = (await client.callTool({ name: "ix_ingest", arguments: { path: "x.json" } })) as CallToolResult;
+ expect(result.isError).toBe(true);
+ expect(JSON.stringify(result.content)).toContain("path_outside_workspace");
+ expect(calls).toEqual([]);
+ await client.close();
+ });
+
+ it("resolves a relative path against the workspace root, as the CLI does", async () => {
+ fs.mkdirSync(path.join(ws, "a"));
+ fs.mkdirSync(path.join(ws, "outside"));
+ fs.writeFileSync(path.join(ws, "outside", "x.json"), "{}\n");
+ // <ws>/a/../outside is inside <ws> for cwd, but the CLI resolves "../outside/x.json"
+ // against the workspace root, i.e. to <t>/outside/x.json.
+ process.chdir(path.join(ws, "a"));
+ const calls: string[][] = [];
+ const client = await connect(async (args) => { calls.push(args); return { ok: true, stdout: "{}", stderr: "" }; });
+ const result = (await client.callTool({ name: "ix_ingest", arguments: { path: "../outside/x.json" } })) as CallToolResult;
+ expect(result.isError).toBe(true);
+ expect(JSON.stringify(result.content)).toContain("path_outside_workspace");
+ expect(calls).toEqual([]);
+ await client.close();
+ });
+
+ it("still ingests a path in the unregistered git repository cwd is in", async () => {
+ const repo = path.join(t, "repo");
+ fs.mkdirSync(repo);
+ execFileSync("git", ["init", "-q"], { cwd: repo });
+ fs.writeFileSync(path.join(repo, "r.ts"), "export const r = 1;\n");
+ process.chdir(repo);
+ const calls: string[][] = [];
+ const client = await connect(async (args) => { calls.push(args); return { ok: true, stdout: "{}", stderr: "" }; });
+ const result = (await client.callTool({ name: "ix_ingest", arguments: { path: "r.ts" } })) as CallToolResult;
+ expect(result.isError).not.toBe(true);
+ expect(calls).toHaveLength(1);
+ await client.close();
+ });
+});
+
+describe("ensureWorkspaceIdState setDefault", () => {
+ it("writes default: false when asked, default: true otherwise", () => {
+ fs.writeFileSync(config, "endpoint: http://127.0.0.1:1\nformat: text\n");
+ ensureWorkspaceIdState(outside, { setDefault: false });
+ expect(fs.readFileSync(config, "utf8")).toMatch(/default: false/);
+ expect(fs.readFileSync(config, "utf8")).not.toMatch(/default: true/);
+ fs.writeFileSync(config, "endpoint: http://127.0.0.1:1\nformat: text\n");
+ ensureWorkspaceIdState(outside);
+ expect(fs.readFileSync(config, "utf8")).toMatch(/default: true/);
+ });
});
diff --git a/ix-cli/src/cli/__tests__/map-root.test.ts b/ix-cli/src/cli/__tests__/map-root.test.ts
index 52310535..c2b3ed83 100644
--- a/ix-cli/src/cli/__tests__/map-root.test.ts
+++ b/ix-cli/src/cli/__tests__/map-root.test.ts
@@ -7,7 +7,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { Command } from "commander";
import { registerMapCommand } from "../commands/map.js";
-import { canonicalMapRoot, resolveIngestRoot, resolveMapRoot } from "../map-root.js";
+import { canonicalMapRoot, resolveIngestRoot, resolveIngestRootWithSource, resolveMapRoot } from "../map-root.js";
import { findWorkspaceForCwd, loadConfig } from "../config.js";
import { lockPathForTest } from "../single-flight.js";
@@ -346,6 +346,30 @@ describe("ingest root resolution", () => {
expect(resolveIngestRoot(join(realHome, "notes", "dir"), true)).toBe(realHome);
});
+ it("says which step chose the root", () => {
+ const repo = realpathSync.native(fixture());
+ const gitRepo = realpathSync.native(fixture());
+ const loose = realpathSync.native(fixture());
+ mkdirSync(join(repo, "src"), { recursive: true });
+ mkdirSync(join(gitRepo, "src"), { recursive: true });
+ writeFileSync(join(loose, "x.ts"), "export {};\n");
+ execFileSync("git", ["init", "-q"], { cwd: gitRepo });
+ writeWorkspaces(repo);
+
+ expect(resolveIngestRootWithSource(join(repo, "src"), true, join(repo, "src"))).toEqual({ root: join(repo, "src"), source: "explicit" });
+ expect(resolveIngestRootWithSource(join(repo, "src"), true)).toEqual({ root: repo, source: "workspace" });
+ expect(resolveIngestRootWithSource(join(gitRepo, "src"), true)).toEqual({ root: gitRepo, source: "git" });
+ expect(resolveIngestRootWithSource(loose, true)).toEqual({ root: loose, source: "loose" });
+ expect(resolveIngestRootWithSource(join(loose, "x.ts"), false)).toEqual({ root: loose, source: "loose" });
+ });
+
+ it("calls a git root at $HOME loose", () => {
+ const realHome = realpathSync.native(home);
+ mkdirSync(join(realHome, "notes"), { recursive: true });
+ execFileSync("git", ["init", "-q"], { cwd: realHome });
+ expect(resolveIngestRootWithSource(join(realHome, "notes"), true).source).toBe("loose");
+ });
+
it("takes --root first, and refuses a path outside it", () => {
const repo = realpathSync.native(fixture());
const other = realpathSync.native(fixture());
diff --git a/ix-cli/src/cli/bootstrap.ts b/ix-cli/src/cli/bootstrap.ts
index 71f07a14..7b8b7409 100644
--- a/ix-cli/src/cli/bootstrap.ts
+++ b/ix-cli/src/cli/bootstrap.ts
@@ -76,13 +76,16 @@ function noteRelocatedConfig(configPath: string): void {
// root path. The old id is what ingest deletes to clean up the migration's orphans.
const migratedRootsThisRun = new Map<string, string>();
+/** `setDefault: false` keeps a new registration from becoming the default workspace (ingest). */
+export interface RegisterOptions { setDefault?: boolean }
+
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): WorkspaceState {
+function getOrCreateWorkspace(cwd: string, opts: RegisterOptions = {}): WorkspaceState {
const rootPath = canonicalWorkspacePath(resolve(cwd));
// The common case, already registered under its path id, needs no write and
// so no lock.
@@ -95,13 +98,13 @@ function getOrCreateWorkspace(cwd: string): WorkspaceState {
// each see the one before (see updateConfig).
return updateConfig((config) => {
let save: typeof config | undefined;
- const state = registerIn(config, rootPath, () => { save = config; });
+ const state = registerIn(config, rootPath, () => { save = config; }, opts.setDefault ?? true);
return { save, result: state };
});
}
/** The registration itself, on a config read under the lock; `changed` marks it for saving. */
-function registerIn(config: IxConfig, rootPath: string, changed: () => void): WorkspaceState {
+function registerIn(config: IxConfig, rootPath: string, changed: () => void, setDefault: boolean): WorkspaceState {
const pathId = workspaceIdForPath(rootPath);
const existing = (config.workspaces ?? []).find(w => canonicalWorkspacePath(w.root_path) === rootPath);
if (existing) {
@@ -132,7 +135,7 @@ function registerIn(config: IxConfig, rootPath: string, changed: () => void): Wo
workspace_id: pathId,
workspace_name: basename(rootPath),
root_path: rootPath,
- default: !hasDefault,
+ default: setDefault && !hasDefault,
};
config.workspaces = [...workspaces, ws];
changed();
@@ -150,8 +153,8 @@ 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; created: boolean; name: string } {
- const { ws, migrated, previousWorkspaceId, created } = getOrCreateWorkspace(cwd);
+export function ensureWorkspaceIdState(cwd = process.cwd(), opts: RegisterOptions = {}): { workspaceId: string; migrated: boolean; previousWorkspaceId?: string; created: boolean; name: string } {
+ const { ws, migrated, previousWorkspaceId, created } = getOrCreateWorkspace(cwd, opts);
return { workspaceId: ws.workspace_id, migrated, previousWorkspaceId, created, name: ws.workspace_name };
}
@@ -164,8 +167,9 @@ export function ensureWorkspaceIdState(cwd = process.cwd()): { workspaceId: stri
* was actually ingested into it. Every registered workspace is a root `ix read`
* may open files from, so registering first let a failed ingest of any path --
* the backend down, or a path nobody meant to ingest -- widen what reads can
- * open, permanently. The caller registers with ensureWorkspaceIdState once a
- * commit has landed.
+ * open, permanently. The caller registers with `ensureWorkspaceIdState(root,
+ * { setDefault })` once a commit has landed -- `setDefault: false` for a loose
+ * directory, so it never becomes the default -- and never for a loose file.
*/
export function workspaceStateFor(root: string): {
workspaceId: string; migrated: boolean; previousWorkspaceId?: string; created: boolean; name: string; pending: boolean;
diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.ts
index 665d4d79..4cf8a945 100644
--- a/ix-cli/src/cli/commands/ingest.ts
+++ b/ix-cli/src/cli/commands/ingest.ts
@@ -13,7 +13,7 @@ import { IxClient } from '../../client/api.js';
import { combineSignals, currentRunSignal } from '../../client/run-signal.js';
import type { GraphPatchPayload } from '../../client/types.js';
import { canonicalWorkspacePath, isPathInside, resolveWorkspaceRoot, clearMapResultCache, clearStitchScopeCache } from '../config.js';
-import { resolveIngestRoot } from '../map-root.js';
+import { resolveIngestRootWithSource } from '../map-root.js';
import { acquireMapLock, requestMapRerun, takeMapRerun } from '../single-flight.js';
import { applyRequestedMapCoalesceExitCode } from './map.js';
import {
@@ -1141,11 +1141,17 @@ function renderProgressLine(phase: string, current: number, total: number): stri
type PathIngestOpts = Parameters<typeof ingestFiles>[1];
-/** The workspace root `target` ingests into, or undefined when it cannot be resolved. */
-function ingestLockRoot(target: string, explicitRoot?: string): string | undefined {
+/**
+ * The workspace root `target` ingests into, or undefined when it cannot be
+ * resolved. `looseFile`: the target is a file in no workspace and no
+ * repository, which is never registered (see ingestFiles).
+ */
+function ingestLockRoot(target: string, explicitRoot?: string): { root: string; looseFile: boolean } | undefined {
try {
const resolved = nodePath.resolve(target);
- return resolveIngestRoot(resolved, fs.statSync(resolved).isDirectory(), explicitRoot);
+ const isDirectory = fs.statSync(resolved).isDirectory();
+ const { root, source } = resolveIngestRootWithSource(resolved, isDirectory, explicitRoot);
+ return { root, looseFile: source === 'loose' && !isDirectory };
} catch {
// `ingestFiles` reports a missing or unreadable path itself.
return undefined;
@@ -1168,11 +1174,12 @@ function ingestLockRoot(target: string, explicitRoot?: string): string | undefin
* workspace, so it re-ingests only its own path then.
*/
export async function ingestPathSingleFlight(target: string, opts: PathIngestOpts): Promise<void> {
- const root = ingestLockRoot(target, opts.root);
- if (root === undefined) {
+ const lockRoot = ingestLockRoot(target, opts.root);
+ if (lockRoot === undefined) {
await ingestFiles(target, opts);
return;
}
+ const { root, looseFile } = lockRoot;
const lock = acquireMapLock(root, `ix ingest ${root}`);
if (lock === null) {
requestMapRerun(root);
@@ -1195,8 +1202,11 @@ export async function ingestPathSingleFlight(target: string, opts: PathIngestOpt
// known here, so this is a plain incremental pass.
const rerunTarget = loadIngestBaseline(root) !== null ? root : target;
try {
+ // The rerun may widen a loose file to its whole directory; that must
+ // not register the directory the file's own ingest would not have.
await ingestFiles(rerunTarget, {
recursive: true, format: 'json', printSummary: false, suppressOutput: true, root: opts.root,
+ neverRegister: looseFile,
});
} catch (err: any) {
if (opts.format !== 'json') {
@@ -1230,7 +1240,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\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.')
+ .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 directory outside every workspace and repo becomes a workspace of its own (never the\ndefault). A loose file outside them is ingested but registers nothing, so ix read cannot open its neighbours.')
.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;
@@ -1756,7 +1766,7 @@ export function ingestCompletedCleanly(parseErrors: number, commitErrors: number
export async function ingestFiles(
path: string,
- opts: { recursive?: boolean; force?: boolean; format: string; root?: string; debug?: boolean; printSummary?: boolean; suppressOutput?: boolean; lang?: string; mapMode?: boolean; exclude?: string[]; deadlineSignal?: AbortSignal }
+ opts: { recursive?: boolean; force?: boolean; format: string; root?: string; debug?: boolean; printSummary?: boolean; suppressOutput?: boolean; lang?: string; mapMode?: boolean; exclude?: string[]; deadlineSignal?: AbortSignal; neverRegister?: boolean }
): Promise<IngestFilesSummary> {
// Under `ix mcp` the tool call's deadline is this run's deadline too. The
// client would see it anyway (createClient combines it), but the commit loop,
@@ -1815,7 +1825,12 @@ export async function ingestFiles(
// `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 targetIsDirectory = fs.statSync(resolvedPath).isDirectory();
+ const { root: workspaceRoot, source: rootSource } = resolveIngestRootWithSource(resolvedPath, targetIsDirectory, opts.root);
+ // A file in no workspace and no repository is ingested under its directory's
+ // id but never registered: that would make the whole directory readable.
+ // `neverRegister`: a coalesced rerun on behalf of such a file ingest.
+ const registerAfterCommit = opts.neverRegister !== true && !(rootSource === 'loose' && !targetIsDirectory);
// A new workspace is only registered once a commit lands (below, before the
// summary): see workspaceStateFor.
const {
@@ -4401,11 +4416,18 @@ export async function ingestFiles(
// A new workspace is registered only now, and only if the backend took
// something: see workspaceStateFor.
- if (registrationPending && patchesTheBackendTook > 0) {
- ensureWorkspaceIdState(workspaceRoot);
+ if (registrationPending && patchesTheBackendTook > 0 && registerAfterCommit) {
+ // A repository (or --root) ingest may become the default when none exists, as
+ // before CL-05; a loose directory never does: an ingest of a stray directory
+ // must not pick the workspace other commands fall back to.
+ ensureWorkspaceIdState(workspaceRoot, { setDefault: rootSource !== 'loose' });
if (!opts.suppressOutput && opts.format === 'text') {
process.stderr.write(chalk.dim(`Registered workspace "${workspaceName}" (${workspaceRoot}).\n`));
}
+ } else if (registrationPending && patchesTheBackendTook > 0) {
+ if (!opts.suppressOutput && opts.format === 'text') {
+ process.stderr.write(chalk.dim(`Not registered as a workspace: ${workspaceRoot} (a file outside every workspace and repository). Run ix map ${workspaceRoot} to query and read it.\n`));
+ }
}
// Reported before the suppressOutput return, and thrown when nothing landed.
diff --git a/ix-cli/src/cli/map-root.ts b/ix-cli/src/cli/map-root.ts
index 99b4fea2..6d98796c 100644
--- a/ix-cli/src/cli/map-root.ts
+++ b/ix-cli/src/cli/map-root.ts
@@ -68,7 +68,10 @@ export function localRootFor(dir: string): string | undefined {
* 2. the registered workspace containing the path
* 3. the path's git root, unless that is the home directory
* 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.
+ * in no workspace and no repository is ingested under its own path id.
+ * A directory is then registered after the commit (the user named it); a
+ * loose FILE is never registered, so ingesting one file cannot make its
+ * whole directory readable. Over MCP a loose path is refused outright.
*
* Step 3 skips a git root at `$HOME` (a dotfiles repo): registering the whole
* home directory as a workspace would route every later read under it there.
@@ -82,6 +85,16 @@ export function localRootFor(dir: string): string | undefined {
* `ingestFiles`. Returned canonical (realpath'd), like the path ingest hands in.
*/
export function resolveIngestRoot(target: string, isDirectory: boolean, explicitRoot?: string): string {
+ return resolveIngestRootWithSource(target, isDirectory, explicitRoot).root;
+}
+
+/** Which step of {@link resolveIngestRootWithSource} chose the root; 'loose' is step 4 (and a git root at $HOME). */
+export type IngestRootSource = 'explicit' | 'workspace' | 'git' | 'loose';
+
+/** {@link resolveIngestRoot}, also saying which step chose the root. */
+export function resolveIngestRootWithSource(
+ target: string, isDirectory: boolean, explicitRoot?: string,
+): { root: string; source: IngestRootSource } {
const canonicalTarget = canonicalWorkspacePath(target);
if (explicitRoot) {
const root = canonicalWorkspacePath(explicitRoot);
@@ -91,14 +104,14 @@ export function resolveIngestRoot(target: string, isDirectory: boolean, explicit
if (!isPathInside(root, canonicalTarget)) {
throw new Error(`${canonicalTarget} is outside --root ${root}. Pass a path inside the root, or drop --root.`);
}
- return root;
+ return { root, source: 'explicit' };
}
const probe = isDirectory ? canonicalTarget : dirname(canonicalTarget);
const registered = findWorkspaceForCwd(probe)?.root_path;
- if (registered) return canonicalWorkspacePath(registered);
+ if (registered) return { root: canonicalWorkspacePath(registered), source: 'workspace' };
const gitRoot = gitRootFor(probe);
if (gitRoot && canonicalWorkspacePath(gitRoot) !== canonicalWorkspacePath(homedir())) {
- return canonicalWorkspacePath(gitRoot);
+ return { root: canonicalWorkspacePath(gitRoot), source: 'git' };
}
- return probe;
+ return { root: probe, source: 'loose' };
}
diff --git a/ix-cli/src/mcp/server.ts b/ix-cli/src/mcp/server.ts
index 4ffc7920..63234f20 100644
--- a/ix-cli/src/mcp/server.ts
+++ b/ix-cli/src/mcp/server.ts
@@ -5,10 +5,12 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
import type { CallToolResult, ToolAnnotations } from "@modelcontextprotocol/sdk/types.js";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
-import { join, resolve as resolvePath } from "node:path";
+import { statSync } from "node:fs";
+import { isAbsolute, join, resolve as resolvePath } from "node:path";
import { z } from "zod";
-import { isReadablePath } from "../cli/config.js";
+import { isReadablePath, resolveWorkspaceRoot } from "../cli/config.js";
+import { resolveIngestRootWithSource } from "../cli/map-root.js";
import {
createProtocolStdout,
@@ -672,15 +674,35 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
// Confined like ix_read. An ingested path's workspace becomes a root
// ix_read may open files from, so an unconfined path let a caller turn
// any directory into a readable one (ix_ingest, then ix_read).
- if (typeof input.path === "string" && !isReadablePath(resolvePath(process.cwd(), input.path))) {
- return textResult(
- JSON.stringify({
- error: "path_outside_workspace",
- message: `Refusing to ingest a path outside the workspace: ${input.path}. Run ix map in that directory to make it a workspace.`,
- tool: "ix_ingest",
- }),
- true,
- );
+ // Resolved against the workspace root, as ingestFiles does, not cwd:
+ // from <ws>/a, "../outside/x" is <ws>/outside for cwd but outside for the CLI.
+ if (typeof input.path === "string") {
+ const abs = isAbsolute(input.path) ? input.path : resolvePath(resolveWorkspaceRoot(), input.path);
+ if (!isReadablePath(abs)) {
+ return textResult(
+ JSON.stringify({
+ error: "path_outside_workspace",
+ message: `Refusing to ingest a path outside the workspace: ${input.path}. Run ix map in that directory to make it a workspace.`,
+ tool: "ix_ingest",
+ }),
+ true,
+ );
+ }
+ // A path in no workspace and no repository would be ingested as a
+ // workspace of its own; over MCP that is refused. A path that does not
+ // exist falls through: the CLI reports it and registers nothing.
+ let isDir: boolean | undefined;
+ try { isDir = statSync(abs).isDirectory(); } catch { /* the CLI reports it */ }
+ if (isDir !== undefined && resolveIngestRootWithSource(abs, isDir).source === "loose") {
+ return textResult(
+ JSON.stringify({
+ error: "path_outside_workspace",
+ message: `Refusing to ingest ${input.path}: it is in no mapped workspace and no git repository. Run ix map in that directory to make it a workspace.`,
+ tool: "ix_ingest",
+ }),
+ true,
+ );
+ }
}
const options: string[] = [];
pushOption(options, "--github", input.github);
diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.md
index af0c4db8..a8a9343e 100644
--- a/skills/ix/references/flags.md
+++ b/skills/ix/references/flags.md
@@ -101,8 +101,9 @@ surfaces (#575).
- **`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.
+ workspace alone. Only a directory in no workspace and no repository becomes
+ a workspace of its own (never the default); a loose file there is ingested
+ but registers nothing, so `ix read` cannot open its neighbours.
- **`ix ingest <path>` coalesces with a running `ix map` or `ix ingest` of the
same workspace**, as `ix map` does: it does not run beside the holder, asks
it for one more pass, and exits 0 (or `IX_MAP_COALESCE_EXIT_CODE`). With