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(cli): hardening sweep for subprocess arguments, paths, ids and error bodies
KageBinary65f31536af33
diff --git a/ix-cli/src/cli/__tests__/diff-mode-conflict.test.ts b/ix-cli/src/cli/__tests__/diff-mode-conflict.test.tsindex 8b5fd8ea..1b2eef1b 100644--- a/ix-cli/src/cli/__tests__/diff-mode-conflict.test.ts+++ b/ix-cli/src/cli/__tests__/diff-mode-conflict.test.ts@@ -338,6 +338,8 @@ describe("mergeDiffOptions", () => {// ══════════════════════════════════════════════════════════════════════describe("loadFileFromDisk", () => {+ // tmpDir is passed as the root: reads are confined to readable roots, and a+ // temp dir is in no workspace.let tmpDir: string;beforeEach(() => {@@ -351,17 +353,17 @@ describe("loadFileFromDisk", () => {it("returns file content when file exists", () => {const filePath = join(tmpDir, "exists.txt");writeFileSync(filePath, "hello world", "utf-8");- expect(loadFileFromDisk(filePath)).toBe("hello world");+ expect(loadFileFromDisk(filePath, tmpDir)).toBe("hello world");});it("returns null when file does not exist", () => {- expect(loadFileFromDisk(join(tmpDir, "nope.txt"))).toBeNull();+ expect(loadFileFromDisk(join(tmpDir, "nope.txt"), tmpDir)).toBeNull();});it("returns empty string for an empty file (not null)", () => {const filePath = join(tmpDir, "empty.txt");writeFileSync(filePath, "", "utf-8");- const result = loadFileFromDisk(filePath);+ const result = loadFileFromDisk(filePath, tmpDir);// Empty string is falsy but NOT null — this is a meaningful distinction.// MUTATION: changing the return to undefined or null must fail.expect(result).toBe("");@@ -371,34 +373,34 @@ describe("loadFileFromDisk", () => {it("returns null when path is a directory (not a file)", () => {// readFileSync on a directory throws; catch block returns null.mkdirSync(join(tmpDir, "subdir"));- expect(loadFileFromDisk(join(tmpDir, "subdir"))).toBeNull();+ expect(loadFileFromDisk(join(tmpDir, "subdir"), tmpDir)).toBeNull();});it("returns content with multi-line content", () => {const filePath = join(tmpDir, "multi.txt");writeFileSync(filePath, "line1\nline2\nline3", "utf-8");- expect(loadFileFromDisk(filePath)).toBe("line1\nline2\nline3");+ expect(loadFileFromDisk(filePath, tmpDir)).toBe("line1\nline2\nline3");});it("returns content with special characters", () => {const filePath = join(tmpDir, "special.txt");writeFileSync(filePath, "hello\tworld\n\"quotes\" and 'apostrophes'", "utf-8");- expect(loadFileFromDisk(filePath)).toBe("hello\tworld\n\"quotes\" and 'apostrophes'");+ expect(loadFileFromDisk(filePath, tmpDir)).toBe("hello\tworld\n\"quotes\" and 'apostrophes'");});it("returns content with Unicode (emoji + CJK)", () => {const filePath = join(tmpDir, "unicode.txt");writeFileSync(filePath, "hello 😀 你好世界", "utf-8");- expect(loadFileFromDisk(filePath)).toBe("hello 😀 你好世界");+ expect(loadFileFromDisk(filePath, tmpDir)).toBe("hello 😀 你好世界");});it("returns null for path with null bytes (catch block)", () => {// A path containing null bytes will cause readFileSync to throw.- expect(loadFileFromDisk(join(tmpDir, "file\0.txt") as any)).toBeNull();+ expect(loadFileFromDisk(join(tmpDir, "file\0.txt") as any, tmpDir)).toBeNull();});it("returns null for non-existent parent directory", () => {- expect(loadFileFromDisk(join(tmpDir, "no", "such", "dir", "file.txt"))).toBeNull();+ expect(loadFileFromDisk(join(tmpDir, "no", "such", "dir", "file.txt"), tmpDir)).toBeNull();});});diff --git a/ix-cli/src/cli/__tests__/mcp-no-docker-autostart.test.ts b/ix-cli/src/cli/__tests__/mcp-no-docker-autostart.test.tsnew file mode 100644index 00000000..250a009b--- /dev/null+++ b/ix-cli/src/cli/__tests__/mcp-no-docker-autostart.test.ts@@ -0,0 +1,33 @@+// Copyright 2026 Ix Infrastructure Inc.++import { afterEach, describe, expect, it, vi } from "vitest";++// The backend is down, and this is the default local endpoint, where a CLI+// run would start Docker. Inside `ix mcp` it must not.+vi.mock("../commands/upgrade.js", () => ({+ readBackendHealth: vi.fn(async () => { throw new Error("connect ECONNREFUSED"); }),+}));+const execFileSync = vi.fn();+vi.mock("node:child_process", async (importOriginal) => ({+ ...(await importOriginal<typeof import("node:child_process")>()),+ execFileSync: (...args: unknown[]) => execFileSync(...args),+}));++const saved = { IX_CALLER: process.env.IX_CALLER, IX_ENDPOINT: process.env.IX_ENDPOINT };+afterEach(() => {+ for (const [k, v] of Object.entries(saved)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+ execFileSync.mockReset();+});++describe("ensureBackendAvailable under ix mcp", () => {+ it("reports backend_unreachable instead of starting Docker", async () => {+ process.env.IX_CALLER = "mcp";+ process.env.IX_ENDPOINT = "http://localhost:8090";+ const { ensureBackendAvailable } = await import("../bootstrap.js");+ await expect(ensureBackendAvailable()).rejects.toThrow(/backend_unreachable/);+ expect(execFileSync).not.toHaveBeenCalled();+ });+});diff --git a/ix-cli/src/cli/__tests__/sec06-hardening.test.ts b/ix-cli/src/cli/__tests__/sec06-hardening.test.tsnew file mode 100644index 00000000..bfa5b6e4--- /dev/null+++ b/ix-cli/src/cli/__tests__/sec06-hardening.test.ts@@ -0,0 +1,85 @@+// Copyright 2026 Ix Infrastructure Inc.++import { afterEach, describe, expect, it } from "vitest";+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";++import { IxClient, errorBodyForMessage } from "../../client/api.js";+import { loadFileFromDisk } from "../commands/diff.js";+import { isVisualizerOnPort } from "../commands/view.js";+import { parseGitHubRepo } from "../github/fetch.js";+import { isRawId } from "../resolve.js";+import { capErrorDetail } from "../../mcp/server.js";++const servers: Server[] = [];+afterEach(async () => {+ await Promise.all(servers.splice(0).map((s) => new Promise<void>((r) => { s.closeAllConnections(); s.close(() => r()); })));+});++async function server(handler: (url: string) => { status: number; body: string }): Promise<{ port: number; seen: string[] }> {+ const seen: string[] = [];+ const s = createServer((req, res) => {+ seen.push(req.url ?? "");+ const { status, body } = handler(req.url ?? "");+ res.writeHead(status, { "content-type": "application/json" }).end(body);+ });+ servers.push(s);+ await new Promise<void>((r) => s.listen(0, "127.0.0.1", r));+ return { port: (s.address() as AddressInfo).port, seen };+}++describe("ix diff reads only readable roots", () => {+ it("returns nothing for an absolute source_uri outside every workspace", () => {+ expect(loadFileFromDisk("/etc/passwd")).toBeNull();+ });+});++describe("ids in URL paths", () => {+ it("anchors isRawId: a UUID followed by a path is a name, not an id", () => {+ expect(isRawId("0b6f0c3e-1d2a-4c55-9a6e-3f1b2c4d5e6f")).toBe(true);+ expect(isRawId("0b6f0c3e-1d2a-4c55-9a6e-3f1b2c4d5e6f/../health")).toBe(false);+ });++ it("path-encodes entity ids", async () => {+ const b = await server(() => ({ status: 200, body: JSON.stringify({ node: {}, claims: [], edges: [] }) }));+ await new IxClient(`http://127.0.0.1:${b.port}`).entity("../health");+ expect(b.seen).toEqual(["/v1/entity/..%2Fhealth"]);+ });+});++describe("GitHub repo slugs", () => {+ it("accepts owner/repo and rejects anything that would change the API path", () => {+ expect(parseGitHubRepo("ix-infrastructure/Ix")).toEqual({ owner: "ix-infrastructure", repo: "Ix" });+ for (const bad of ["../x", "a/..", "./b", "a b/c", "a/b?x=1", "a/b/c", "a/"]) {+ expect(() => parseGitHubRepo(bad)).toThrow(/Invalid repo format/);+ }+ });+});++describe("error bodies in messages", () => {+ it("keeps a JSON body whole and cuts anything else to 300 characters", () => {+ const json = JSON.stringify({ error: "workspace_not_mapped", message: "x".repeat(1000) });+ expect(errorBodyForMessage(json)).toBe(json);+ const html = `<html>${"y".repeat(5000)}</html>`;+ const cut = errorBodyForMessage(html);+ expect(cut.length).toBeLessThan(400);+ expect(cut).toContain("more characters");+ });++ it("caps an MCP error result's detail", () => {+ expect(capErrorDetail("short")).toBe("short");+ expect(capErrorDetail("z".repeat(10_000)).length).toBeLessThan(4100);+ });+});++describe("ix view stop only signals the visualizer", () => {+ it("does not take another server on the recorded port for the visualizer", async () => {+ const other = await server(() => ({ status: 200, body: "{}" }));+ expect(await isVisualizerOnPort(other.port)).toBe(false);+ });++ it("recognises the visualizer's own 404 for an unknown /__ix route", async () => {+ const viz = await server((url) => ({ status: 404, body: JSON.stringify({ ok: false, error: `not found: ${url}` }) }));+ expect(await isVisualizerOnPort(viz.port)).toBe(true);+ });+});diff --git a/ix-cli/src/cli/__tests__/view-running-port.test.ts b/ix-cli/src/cli/__tests__/view-running-port.test.tsindex ef2da157..3f6f119f 100644--- a/ix-cli/src/cli/__tests__/view-running-port.test.ts+++ b/ix-cli/src/cli/__tests__/view-running-port.test.ts@@ -209,8 +209,14 @@ describe("view running port state", () => {expect(output).not.toContain("It is scoped to");});+ /** What the recorded port answers to stop's check (an unknown /__ix route). */+ function portAnswers(status: number, body: unknown): void {+ vi.spyOn(globalThis, "fetch").mockImplementation(async () => new Response(JSON.stringify(body), { status }));+ }+it("removes persisted state when the visualizer stops", async () => {seedRunningState(19123);+ portAnswers(404, { ok: false, error: "not found: /__ix/ping" });const kill = vi.spyOn(process, "kill").mockReturnValue(true);const output = await runView(["stop"]);@@ -222,6 +228,20 @@ describe("view running port state", () => {expect(existsSync(portFile())).toBe(false);});+ it("does not signal a PID whose recorded port is now something else", async () => {+ // The PID file outlived the visualizer and its number now belongs to an+ // unrelated process; the port answers, but not as the visualizer.+ seedRunningState(19123);+ portAnswers(200, { hello: "world" });+ const kill = vi.spyOn(process, "kill").mockReturnValue(true);++ const output = await runView(["stop"]);++ expect(output).toContain("now belongs to another process");+ expect(kill).not.toHaveBeenCalledWith(4242, "SIGTERM");+ expect(existsSync(pidFile())).toBe(false);+ });+it("says the requested port was not honoured", async () => {seedRunningState(19123);vi.spyOn(process, "kill").mockReturnValue(true);diff --git a/ix-cli/src/cli/bootstrap.ts b/ix-cli/src/cli/bootstrap.tsindex 076706fb..80f7d813 100644--- a/ix-cli/src/cli/bootstrap.ts+++ b/ix-cli/src/cli/bootstrap.ts@@ -12,6 +12,7 @@ import { WorkspaceNotMappedError, workspaceNotMappedHint } from "./errors.js";import { ixHome } from "./ix-home.js";import { stderr } from "./stderr.js";import { workspaceIdForPath } from "./system.js";+import { IX_CALLER_ENV } from "./next-step.js";import { readBackendHealth } from "./commands/upgrade.js";import { isLocalEndpoint } from "./backend-version.js";@@ -210,6 +211,12 @@ export async function ensureBackendAvailable(): Promise<void> {if (!canAutoStartBackend(endpoint)) {throw new Error(`Ix backend at ${endpoint} is not reachable.`);}+ // Never from inside `ix mcp`: a tool call would start Docker containers+ // on the user's machine without anyone asking, with the child's output+ // inherited onto the server's stdio. Say what to run instead.+ if (process.env[IX_CALLER_ENV] === "mcp") {+ throw new Error(`Ix backend at ${endpoint} is not reachable (backend_unreachable). Start it with: ix docker start`);+ }try {// This CLI's own entry point under this node, not `ix` off PATH: on// Windows `ix` is `ix.cmd`, which execFile cannot launch without a shell,diff --git a/ix-cli/src/cli/commands/callers.ts b/ix-cli/src/cli/commands/callers.tsindex f077f927..7db46db2 100644--- a/ix-cli/src/cli/commands/callers.ts+++ b/ix-cli/src/cli/commands/callers.ts@@ -66,9 +66,13 @@ export function registerCallersCommand(program: Command): void {// Fallback to text searchtry {const root = resolveWorkspaceRoot();+ // -F and -e: the name is a literal pattern, never a regex or a flag+ // (a symbol named `--pre=x` would otherwise run an rg preprocessor).+ // `--` ends the options before the root; the timeout bounds a search+ // that rg could otherwise run for ever.const { stdout } = await execFileAsync("rg", [- "--json", "--max-count", "10", target.name, root,- ], { maxBuffer: 5 * 1024 * 1024 });+ "--json", "--max-count", "10", "-F", "-e", target.name, "--", root,+ ], { maxBuffer: 5 * 1024 * 1024, timeout: 10_000 });const allTextResults: any[] = [];for (const line of stdout.split("\n")) {@@ -90,6 +94,9 @@ export function registerCallersCommand(program: Command): void {} catch { /* skip malformed lines */ }}+ // rg searches files in parallel, so match order varies between runs;+ // sort first so the ranking, and the output, do not.+ allTextResults.sort((x, y) => (x.path < y.path ? -1 : x.path > y.path ? 1 : x.line - y.line));// Calls first and the definition out: an unranked fallback led with// import lines and the target's own signature.const ranked = rankTextUses(diff --git a/ix-cli/src/cli/commands/diff.ts b/ix-cli/src/cli/commands/diff.tsindex 41af339b..97f0b008 100644--- a/ix-cli/src/cli/commands/diff.ts+++ b/ix-cli/src/cli/commands/diff.ts@@ -9,7 +9,7 @@ import type { Command } from "commander";import chalk from "chalk";import { IxClient } from "../../client/api.js";-import { absoluteFromSourceUri, getEndpoint, resolveWorkspaceRoot } from "../config.js";+import { absoluteFromSourceUri, getEndpoint, isReadablePath, resolveWorkspaceRoot } from "../config.js";import { resolveFileOrReport, printResolved, type ResolvedEntity } from "../resolve.js";import { formatDiff, relativePath, printJson } from "../format.js";import { llmLine } from "../llm.js";@@ -163,6 +163,10 @@ function compactDiffResult(result: any): any {/** Load full file content from current disk. */export function loadFileFromDisk(uri: string, root?: string): string | null {const filePath = absoluteFromSourceUri(uri, root);+ // A source_uri comes from the graph, and an absolute one is used as-is: the+ // same confinement as `ix read`, so a crafted graph cannot make diff print+ // /etc/passwd.+ if (!isReadablePath(filePath, root)) return null;try {if (!fs.existsSync(filePath)) return null;return fs.readFileSync(filePath, "utf-8");@@ -343,6 +347,7 @@ function readSourceSpan(node: any): string | null {if (lineStart == null || lineEnd == null) return null;const filePath = absoluteFromSourceUri(uri);+ if (!isReadablePath(filePath)) return null;try {if (!fs.existsSync(filePath)) return null;const content = fs.readFileSync(filePath, "utf-8");diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.tsindex 47f9ff07..22740d0e 100644--- a/ix-cli/src/cli/commands/ingest.ts+++ b/ix-cli/src/cli/commands/ingest.ts@@ -324,7 +324,9 @@ export function tryGitLsFiles(try {const result = spawnSync('git',- ['ls-files', '--cached', '--others', '--exclude-standard'],+ // -c: a cloned repository's own .git/config can name a core.fsmonitor+ // command, which ls-files would run. Never let it.+ ['-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=/dev/null', 'ls-files', '--cached', '--others', '--exclude-standard'],{cwd: dir,encoding: 'utf-8',diff --git a/ix-cli/src/cli/commands/view.ts b/ix-cli/src/cli/commands/view.tsindex 6ada996f..f765cbf4 100644--- a/ix-cli/src/cli/commands/view.ts+++ b/ix-cli/src/cli/commands/view.ts@@ -185,6 +185,23 @@ function readAlivePid(): number | null {}}+/**+ * Does `port` answer like this visualizer? An unknown `/__ix/` route gets the+ * server's own JSON 404, which nothing else on a port is likely to send. Used+ * before acting on the PID file: a PID outlives its process and can be reused+ * by an unrelated one, which `stop` would otherwise SIGTERM.+ */+export async function isVisualizerOnPort(port: number, timeoutMs = 1500): Promise<boolean> {+ try {+ const res = await fetch(`http://127.0.0.1:${port}/__ix/ping`, { signal: AbortSignal.timeout(timeoutMs) });+ if (res.status !== 404) return false;+ const body = (await res.json()) as { ok?: unknown; error?: unknown };+ return body.ok === false && typeof body.error === "string" && body.error.startsWith("not found: /__ix/ping");+ } catch {+ return false;+ }+}+/** Check whether a port is already in use. */function isPortInUse(port: number): Promise<boolean> {return new Promise((resolve) => {@@ -803,12 +820,21 @@ export function registerViewCommand(program: Command): void {view.command("stop").description("Stop the visualizer")- .action(() => {+ .action(async () => {const pid = readAlivePid();if (!pid) {console.log("[ok] Visualizer is not running.");return;}+ // Only signal a PID that is still the visualizer. An instance started+ // before the port was recorded has nothing to check against and keeps+ // the old behaviour.+ const port = readRunningPort();+ if (port !== null && !(await isVisualizerOnPort(port))) {+ removeCompassState();+ console.log(`[ok] Visualizer is not running (PID ${pid} now belongs to another process; left alone).`);+ return;+ }try {process.kill(pid, "SIGTERM");diff --git a/ix-cli/src/cli/config.ts b/ix-cli/src/cli/config.tsindex f1c8047f..0df25ac8 100644--- a/ix-cli/src/cli/config.ts+++ b/ix-cli/src/cli/config.ts@@ -409,7 +409,8 @@ export function resolveWorkspaceRoot(explicitRoot?: string, cwd = process.cwd())*/export function gitRootFor(cwd: string): string | undefined {try {- const out = execFileSync("git", ["rev-parse", "--show-toplevel"], {+ // -c: never run a core.fsmonitor command the repository's config names.+ const out = execFileSync("git", ["-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", "rev-parse", "--show-toplevel"], {cwd,encoding: "utf-8",stdio: ["ignore", "pipe", "ignore"],diff --git a/ix-cli/src/cli/github/fetch.ts b/ix-cli/src/cli/github/fetch.tsindex 8c412e35..d5cfc9ca 100644--- a/ix-cli/src/cli/github/fetch.ts+++ b/ix-cli/src/cli/github/fetch.ts@@ -5,9 +5,14 @@ export interface GitHubRepo {repo: string;}+const GITHUB_NAME = /^[A-Za-z0-9_.-]+$/;+export function parseGitHubRepo(input: string): GitHubRepo {const parts = input.split("/");- if (parts.length !== 2 || !parts[0] || !parts[1]) {+ // Each part goes into an API URL path, so `..`, `.`, or anything outside+ // GitHub's own name alphabet would change which endpoint is requested.+ const valid = (p: string | undefined): p is string => !!p && GITHUB_NAME.test(p) && p !== "." && p !== "..";+ if (parts.length !== 2 || !valid(parts[0]) || !valid(parts[1])) {throw new Error(`Invalid repo format: "${input}". Expected "owner/repo".`);}return { owner: parts[0], repo: parts[1] };@@ -87,7 +92,7 @@ export async function fetchGitHubData(const { owner, repo: repoName } = repo;const base = `https://api.github.com/repos/${owner}/${repoName}`;const limit = opts.limit ?? 50;- const sinceParam = opts.since ? `&since=${opts.since}` : "";+ const sinceParam = opts.since ? `&since=${encodeURIComponent(opts.since)}` : "";const issues = await ghFetch<GitHubIssue[]>(`${base}/issues?state=all&per_page=${limit}&sort=updated&direction=desc${sinceParam}`,diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.tsindex f97977f4..465866de 100644--- a/ix-cli/src/cli/resolve.ts+++ b/ix-cli/src/cli/resolve.ts@@ -724,7 +724,9 @@ export function printResolved(target: ResolvedEntity): void {/** Check if a string looks like a raw UUID (not a human-readable name). */export function isRawId(s: string): boolean {- return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i.test(s)+ // Anchored at both ends: a UUID followed by anything else (`<uuid>/../health`)+ // is a name to search for, not an id to put into a URL path.+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s)|| /^[0-9a-f]{32,}$/i.test(s);}diff --git a/ix-cli/src/client/api.ts b/ix-cli/src/client/api.tsindex c1b54b14..6f8bfed0 100644--- a/ix-cli/src/client/api.ts+++ b/ix-cli/src/client/api.ts@@ -126,7 +126,7 @@ export class IxClient {});if (!resp.ok) {const text = await resp.text();- throw new Error(`${resp.status}: ${text}`);+ throw new Error(`${resp.status}: ${errorBodyForMessage(text)}`);}return resp.json() as Promise<IngestResult>;}@@ -214,7 +214,7 @@ export class IxClient {claims: unknown[];edges: unknown[];}> {- return this.get(`/v1/entity/${id}`);+ return this.get(`/v1/entity/${encodeURIComponent(id)}`);}async expandByName(@@ -273,7 +273,7 @@ export class IxClient {}async getPatch(id: string): Promise<unknown> {- return this.get(`/v1/patches/${id}`);+ return this.get(`/v1/patches/${encodeURIComponent(id)}`);}/**@@ -307,7 +307,7 @@ export class IxClient {}async provenance(entityId: string): Promise<unknown> {- return this.post(`/v1/provenance/${entityId}`, {});+ return this.post(`/v1/provenance/${encodeURIComponent(entityId)}`, {});}async commitPatch(patch: GraphPatchPayload): Promise<PatchCommitResult> {@@ -319,7 +319,7 @@ export class IxClient {});if (!resp.ok) {const text = await resp.text();- throw new Error(`${resp.status}: ${text}`);+ throw new Error(`${resp.status}: ${errorBodyForMessage(text)}`);}return resp.json() as Promise<PatchCommitResult>;}@@ -367,7 +367,7 @@ export class IxClient {// TTL, so turning an outage into `null` pinned every later read in a stitched// workspace to the single repo until the next map.async workspaceSystem(workspaceId: string): Promise<{ systemId: string | null }> {- try { return await this.get(`/v1/stitch/system/${workspaceId}`); }+ try { return await this.get(`/v1/stitch/system/${encodeURIComponent(workspaceId)}`); }catch (err) {if (err instanceof Error && err.message.startsWith("404:")) return { systemId: null };throw err;@@ -387,7 +387,7 @@ export class IxClient {});if (!resp.ok) {const text = await resp.text();- throw new Error(`${resp.status}: ${text}`);+ throw new Error(`${resp.status}: ${errorBodyForMessage(text)}`);}return resp.json();}@@ -401,7 +401,7 @@ export class IxClient {});if (!resp.ok) {const text = await resp.text();- throw new Error(`${resp.status}: ${text}`);+ throw new Error(`${resp.status}: ${errorBodyForMessage(text)}`);}return resp.json() as Promise<PatchCommitResult>;}@@ -550,7 +550,7 @@ export class IxClient {}if (!beginResp.ok) {const text = await beginResp.text();- throw new Error(`${beginResp.status}: ${text}`);+ throw new Error(`${beginResp.status}: ${errorBodyForMessage(text)}`);}if (beginResp.status !== 202) {@@ -659,7 +659,7 @@ export class IxClient {}if (!resp.ok) {const text = await resp.text();- throw new Error(`${resp.status}: ${text}`);+ throw new Error(`${resp.status}: ${errorBodyForMessage(text)}`);}return resp.json() as Promise<{ ok: boolean; message: string }>;}@@ -673,7 +673,7 @@ export class IxClient {const resp = await fetch(`${this.endpoint}/v1/savings`, { method: "DELETE" });if (!resp.ok) {const text = await resp.text();- throw new Error(`${resp.status}: ${text}`);+ throw new Error(`${resp.status}: ${errorBodyForMessage(text)}`);}return resp.json();}@@ -733,7 +733,7 @@ export class IxClient {const run = async (): Promise<SuccessBody> => {const resp = await send();const text = await resp.text();- if (!resp.ok) throw new Error(`${resp.status}: ${text}`);+ if (!resp.ok) throw new Error(`${resp.status}: ${errorBodyForMessage(text)}`);return { status: resp.status, text };};return this.limiter ? this.limiter.run(run) : run();@@ -745,6 +745,25 @@ export class IxClient {}}+/**+ * An error response body as it goes into an Error message. A JSON body is kept+ * whole: callers read its error code back out of the message. Anything else,+ * such as a proxy's HTML page, is cut to 300 characters, so a multi-megabyte+ * page never becomes a message, a log line or an MCP tool result.+ */+export function errorBodyForMessage(text: string, max = 300): string {+ const trimmed = text.trim();+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {+ try {+ JSON.parse(trimmed);+ return text;+ } catch {+ // not JSON after all: truncate below+ }+ }+ return text.length > max ? `${text.slice(0, max)}… (${text.length - max} more characters)` : text;+}+interface SuccessBody {status: number;text: string;diff --git a/ix-cli/src/mcp/server.ts b/ix-cli/src/mcp/server.tsindex 2bc68745..1d88a1a5 100644--- a/ix-cli/src/mcp/server.ts+++ b/ix-cli/src/mcp/server.ts@@ -812,6 +812,18 @@ function toArgv(argv: IxArgv, format: string): string[] {*/const MAX_TOOL_RESULT_BYTES = 24 * 1024;+/**+ * The failure text an error result carries. A command's stderr can be a whole+ * stack trace or a multi-megabyte proxy page, and an error result goes into+ * the model's context the same as a success does.+ */+const MAX_ERROR_DETAIL_CHARS = 4000;+export function capErrorDetail(detail: string): string {+ return detail.length > MAX_ERROR_DETAIL_CHARS+ ? `${detail.slice(0, MAX_ERROR_DETAIL_CHARS)}… (${detail.length - MAX_ERROR_DETAIL_CHARS} more characters)`+ : detail;+}+/*** Cap a record stream, on a line boundary, and say so in a record.*@@ -883,7 +895,7 @@ async function runJsonStructured(const result = await runIx(toArgv(argv, "json"), DEFAULT_TIMEOUT_MS);if (!result.ok) {const detail = result.stderr.trim() || result.stdout.trim() || `${argv.command} failed without output`;- return textResult(JSON.stringify({ error: detail, tool }), true);+ return textResult(JSON.stringify({ error: capErrorDetail(detail), tool }), true);}const text = result.stdout.trim() || "{}";const parsed = parseJsonOutput(text);@@ -915,7 +927,7 @@ async function runCommand(result.stderr.trim() ||result.stdout.trim() ||`${args.slice(0, 2).join(" ")} failed without output`;- return textResult(JSON.stringify({ error: detail, tool }), true);+ return textResult(JSON.stringify({ error: capErrorDetail(detail), tool }), true);}return textResult(result.stdout.trim() || "{}");@@ -943,7 +955,7 @@ async function runSmells(runIx: IxRunner, input: ToolInput): Promise<CallToolResconst result = await runIx(toArgv(ix("smells"), "json"), DEFAULT_TIMEOUT_MS);if (!result.ok) {const detail = result.stderr.trim() || result.stdout.trim() || "smells failed without output";- return textResult(JSON.stringify({ error: detail, tool: "ix_smells" }), true);+ return textResult(JSON.stringify({ error: capErrorDetail(detail), tool: "ix_smells" }), true);}const parsed = parseJsonOutput(result.stdout);