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): register a workspace only after something was ingested into it

KageBinary3d0efe7e3756
diff --git a/ix-cli/src/cli/__tests__/ingest-registration.test.ts b/ix-cli/src/cli/__tests__/ingest-registration.test.ts
new file mode 100644
index 00000000..5d8b99aa
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/ingest-registration.test.ts
@@ -0,0 +1,161 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+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 { 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 { registerIngestCommand } from "../commands/ingest.js";
+import { registerReadCommand } from "../commands/read.js";
+import { createIxMcpServer, type IxRunner } from "../../mcp/server.js";
+
+/**
+ * Every registered workspace is a root `ix read` may open files from. `ix
+ * ingest <path>` registered the path's workspace before it ingested anything,
+ * so one failed ingest of a directory outside the workspace (backend down, or
+ * a path nobody meant) made that directory readable for good:
+ *
+ * ix read <outside>/secret.txt -> path_outside_workspace
+ * ix ingest <outside>/x.json -> commit fails, config.yaml gains <outside>
+ * ix read <outside>/secret.txt -> the secret
+ */
+
+let t: string;
+let ws: string;
+let outside: string;
+let config: string;
+let savedCwd: string;
+const savedEnv = { IX_HOME: process.env.IX_HOME, IX_ENDPOINT: process.env.IX_ENDPOINT };
+
+beforeEach(() => {
+ t = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), "ix-ingest-reg-")));
+ ws = path.join(t, "ws");
+ outside = path.join(t, "outside");
+ fs.mkdirSync(ws);
+ fs.mkdirSync(outside);
+ fs.mkdirSync(path.join(t, "home"));
+ fs.writeFileSync(path.join(ws, "a.ts"), "export const a = 1;\n");
+ fs.writeFileSync(path.join(outside, "secret.txt"), "TOP-SECRET-VALUE\n");
+ fs.writeFileSync(path.join(outside, "x.json"), '{"k": 1}\n');
+ config = path.join(t, "home", "config.yaml");
+ fs.writeFileSync(config, [
+ "endpoint: http://127.0.0.1:1",
+ "format: text",
+ "workspaces:",
+ " - workspace_id: ws1",
+ " workspace_name: ws",
+ ` root_path: ${ws}`,
+ " default: true",
+ "",
+ ].join("\n"));
+ process.env.IX_HOME = path.join(t, "home");
+ process.env.IX_ENDPOINT = "http://127.0.0.1:1"; // nothing listens: every commit fails
+ savedCwd = process.cwd();
+ process.chdir(ws);
+});
+
+afterEach(() => {
+ process.chdir(savedCwd);
+ for (const [k, v] of Object.entries(savedEnv)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ process.exitCode = undefined;
+ vi.restoreAllMocks();
+ fs.rmSync(t, { recursive: true, force: true });
+});
+
+async function run(register: (p: Command) => void, args: string[]): Promise<{ out: string; exitCode: number }> {
+ const out: string[] = [];
+ vi.spyOn(console, "log").mockImplementation((...a: unknown[]) => { out.push(a.join(" ")); });
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ vi.spyOn(process.stderr, "write").mockImplementation(() => true);
+ vi.spyOn(process.stdout, "write").mockImplementation((chunk: unknown) => { out.push(String(chunk)); return true; });
+ vi.spyOn(process, "exit").mockImplementation(((code?: number) => { throw new Error(`exit ${code ?? 0}`); }) as never);
+ process.exitCode = undefined;
+ const program = new Command().exitOverride();
+ register(program);
+ let exitCode: number;
+ try {
+ await program.parseAsync(args, { from: "user" });
+ exitCode = Number(process.exitCode ?? 0);
+ } catch (err) {
+ const m = /^exit (\d+)$/.exec((err as Error).message);
+ exitCode = m ? Number(m[1]) : 1;
+ }
+ process.exitCode = undefined;
+ vi.restoreAllMocks();
+ return { out: out.join("\n"), exitCode };
+}
+
+describe("ix ingest registers a workspace only once something was ingested", () => {
+ it("leaves config.yaml unchanged after a failed ingest, so reads stay confined", async () => {
+ const before = fs.readFileSync(config, "utf8");
+ const secret = path.join(outside, "secret.txt");
+
+ const first = await run(registerReadCommand, ["read", secret, "--root", ws, "--format", "json"]);
+ expect(first.out).toContain("path_outside_workspace");
+
+ await run(registerIngestCommand, ["ingest", path.join(outside, "x.json")]);
+ expect(fs.readFileSync(config, "utf8")).toBe(before);
+
+ const second = await run(registerReadCommand, ["read", secret, "--root", ws, "--format", "json"]);
+ expect(second.out).toContain("path_outside_workspace");
+ expect(second.out).not.toContain("TOP-SECRET-VALUE");
+ expect(second.exitCode).toBe(1);
+ }, 60_000);
+
+ it("workspaceStateFor gives a new root's id without writing anything", () => {
+ const before = fs.readFileSync(config, "utf8");
+ const state = workspaceStateFor(outside);
+ expect(state.pending).toBe(true);
+ expect(state.name).toBe("outside");
+ expect(fs.readFileSync(config, "utf8")).toBe(before);
+ // A registered root is the existing workspace (its legacy id migrated, as before).
+ expect(workspaceStateFor(ws)).toEqual(expect.objectContaining({ name: "ws", pending: false }));
+ });
+});
+
+describe("ix read refuses an outside path before looking at it", () => {
+ it("answers path_outside_workspace for a path that does not exist, too", async () => {
+ const missing = await run(registerReadCommand, ["read", path.join(outside, "nope.txt"), "--root", ws, "--format", "json"]);
+ const present = await run(registerReadCommand, ["read", path.join(outside, "secret.txt"), "--root", ws, "--format", "json"]);
+ expect(missing.out).toContain("path_outside_workspace");
+ expect(present.out).toContain("path_outside_workspace");
+ });
+});
+
+describe("MCP ix_ingest is confined like ix_read", () => {
+ async function connect(runIx: IxRunner): Promise<Client> {
+ const server = createIxMcpServer({ version: "test", runIx, proAvailable: false, tools: "all" });
+ const client = new Client({ name: "ix-ingest-reg-test", version: "1.0.0" });
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ await server.connect(serverTransport);
+ await client.connect(clientTransport);
+ return client;
+ }
+
+ it("refuses a path outside the workspace without running the CLI", async () => {
+ 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: path.join(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 inside the workspace", async () => {
+ const calls: string[][] = [];
+ const client = await connect(async (args) => { calls.push(args); return { ok: true, stdout: "{}", stderr: "" }; });
+ await client.callTool({ name: "ix_ingest", arguments: { path: "a.ts" } });
+ expect(calls).toHaveLength(1);
+ expect(calls[0]).toContain("a.ts");
+ await client.close();
+ });
+});
diff --git a/ix-cli/src/cli/bootstrap.ts b/ix-cli/src/cli/bootstrap.ts
index 076706fb..67a4d1f0 100644
--- a/ix-cli/src/cli/bootstrap.ts
+++ b/ix-cli/src/cli/bootstrap.ts
@@ -132,6 +132,27 @@ export function ensureWorkspaceIdState(cwd = process.cwd()): { workspaceId: stri
return { workspaceId: ws.workspace_id, migrated, previousWorkspaceId, created, name: ws.workspace_name };
}
+/**
+ * The workspace state for `root` WITHOUT registering a new one: an existing
+ * workspace exactly as ensureWorkspaceIdState returns it, or, for a root not
+ * registered yet, the id it would get with `pending: true` and nothing written.
+ *
+ * For `ix ingest <path>`, which must not register a workspace until something
+ * 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.
+ */
+export function workspaceStateFor(root: string): {
+ workspaceId: string; migrated: boolean; previousWorkspaceId?: string; created: boolean; name: string; pending: boolean;
+} {
+ const rootPath = canonicalWorkspacePath(resolve(root));
+ const registered = (loadConfig().workspaces ?? []).some(w => canonicalWorkspacePath(w.root_path) === rootPath);
+ if (registered) return { ...ensureWorkspaceIdState(rootPath), pending: false };
+ return { workspaceId: workspaceIdForPath(rootPath), migrated: false, created: true, name: basename(rootPath), pending: true };
+}
+
/**
* 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 47f9ff07..488d5859 100644
--- a/ix-cli/src/cli/commands/ingest.ts
+++ b/ix-cli/src/cli/commands/ingest.ts
@@ -22,7 +22,7 @@ import { resolveGitHubToken } from '../github/auth.js';
import { parseGitHubRepo, fetchGitHubData } from '../github/fetch.js';
import { loadIngestionModules } from './ingestion-loader.js';
import { declaredPackageDirs } from '../package-dirs.js';
-import { ensureWorkspaceIdState } from '../bootstrap.js';
+import { ensureWorkspaceIdState, workspaceStateFor } from '../bootstrap.js';
import { detectSystem, repoWorkspaceIdFor, lookupPackage, readPackageNames, readPackageDeps } from '../system.js';
import { CLIENT_EXPECTED_SCHEMA_VERSION } from '../backend-status.js';
import { admitStitchWaiting, connectionNeverEstablished, type StitchRefusal } from '../stitch-guard.js';
@@ -1548,16 +1548,15 @@ export async function ingestFiles(
// 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);
+ // A new workspace is only registered once a commit lands (below, before the
+ // summary): see workspaceStateFor.
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`));
- }
+ pending: registrationPending,
+ } = workspaceStateFor(workspaceRoot);
// 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
@@ -3772,6 +3771,12 @@ export async function ingestFiles(
// left the agent believing the graph was current while `ix search` and
// `ix impact` answered from a stale one. A wrong answer nobody can see is
// worse than a failed command.
+ if (registrationPending && patchesTheBackendTook > 0) {
+ ensureWorkspaceIdState(workspaceRoot);
+ if (!opts.suppressOutput && opts.format === 'text') {
+ process.stderr.write(chalk.dim(`Registered workspace "${workspaceName}" (${workspaceRoot}).\n`));
+ }
+ }
const commitReport = describeCommitOutcome(
commitErrors,
patchesApplied,
diff --git a/ix-cli/src/cli/commands/read.ts b/ix-cli/src/cli/commands/read.ts
index 46a3f745..38dde77d 100644
--- a/ix-cli/src/cli/commands/read.ts
+++ b/ix-cli/src/cli/commands/read.ts
@@ -348,6 +348,10 @@ Examples:
// --- Step 2: Try exact file path ---
const resolvedPath = path.isAbsolute(rawTarget) ? rawTarget : path.resolve(root, rawTarget);
+ // A path-shaped target is checked before it is stat'ed: refusing only
+ // the paths that exist told a caller which files exist outside the
+ // workspace. A bare name resolves inside the root and passes.
+ if (/[\\/]/.test(rawTarget) && !guardReadable(resolvedPath, opts.root, "file", opts.format)) return;
if (fs.existsSync(resolvedPath) && fs.statSync(resolvedPath).isFile()) {
if (!guardReadable(resolvedPath, opts.root, "file", opts.format)) return;
const stale = checkStale(resolvedPath);
diff --git a/ix-cli/src/mcp/server.ts b/ix-cli/src/mcp/server.ts
index 2bc68745..30851e4d 100644
--- a/ix-cli/src/mcp/server.ts
+++ b/ix-cli/src/mcp/server.ts
@@ -5,9 +5,10 @@ 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 } from "node:path";
+import { join, resolve as resolvePath } from "node:path";
import { z } from "zod";
+import { isReadablePath } from "../cli/config.js";
import {
createProtocolStdout,
@@ -660,6 +661,19 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
true,
);
}
+ // 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,
+ );
+ }
const options: string[] = [];
pushOption(options, "--github", input.github);
pushOption(options, "--since", input.since);