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(context): make sanitizeId injective for astral ids, with coverage (#491)
KageBinary55853cd23896
diff --git a/ix-cli/src/cli/__tests__/context-investigation.test.ts b/ix-cli/src/cli/__tests__/context-investigation.test.tsindex b4eb9003..1dcc976e 100644--- a/ix-cli/src/cli/__tests__/context-investigation.test.ts+++ b/ix-cli/src/cli/__tests__/context-investigation.test.ts@@ -884,18 +884,42 @@ describe("ix context investigation state", () => {expect(loadInvestigation(only.id)?.bundle.target.name).toBe("Widget");});- it("lists an id that --resume can take back even when it cannot be decoded", () => {- // `sanitizeId` writes two hex digits below U+0100 and three or four above- // it, so `~7528` is either one CJK code unit or `~752` followed by a- // literal `8` and nothing in the string says which. Guessing produced a- // mangled id that loaded nothing; the round-trip check refuses to guess- // and shows the stored name, and `loadInvestigation` accepts that form.+ it("lists a non-Latin-1 id as the characters the user typed", () => {+ // Above U+0100 the escape carries its `u` width marker, so `~u7528` is+ // one code unit and cannot also be read as `~752` plus a literal `8`.+ // That is what lets the round-trip check accept the decode instead of+ // falling back to showing the stored name.saveInvestigation("用户", bundleWith([makeClaim("renders to DOM", 0.9)]));+ expect(readdirSync(investigationsDir())).toEqual(["~u7528~u6237.json"]);++ const [only] = listInvestigations().saved;+ expect(only.id).toBe("用户");+ // Both the listed id and the stored form reach the same file.+ expect(loadInvestigation(only.id)?.bundle.target.name).toBe("Widget");+ expect(loadInvestigation("~u7528~u6237")?.bundle.target.name).toBe("Widget");+ });++ it("shows a pre-marker stored id verbatim rather than guessing at it", () => {+ // Written by a CLI that emitted a bare `~HHHH`, which is genuinely+ // ambiguous — `~7528` is either one CJK code unit or `~752` followed by a+ // literal `8`, and nothing in the string says which. The round-trip check+ // refuses to guess, shows the stored name, and `loadInvestigation`+ // accepts that form so the listed id still loads.+ const dir = investigationsDir();+ mkdirSync(dir, { recursive: true });+ writeFileSync(+ join(dir, "~7528~6237.json"),+ JSON.stringify({+ schema: "ix-investigation/1",+ id: "~7528~6237",+ savedAt: "2026-01-01T00:00:00.000Z",+ bundle: bundleWith([makeClaim("renders to DOM", 0.9)]),+ }),+ );+const [only] = listInvestigations().saved;expect(only.id).toBe("~7528~6237");expect(loadInvestigation(only.id)?.bundle.target.name).toBe("Widget");- // …and the id the user actually typed still reaches the same file.- expect(loadInvestigation("用户")?.bundle.target.name).toBe("Widget");});it("keeps an id that is literally spelled like an encoding on its own file", () => {diff --git a/ix-cli/src/cli/__tests__/context-mode-conflict.test.ts b/ix-cli/src/cli/__tests__/context-mode-conflict.test.tsindex 052763d2..0ed41be0 100644--- a/ix-cli/src/cli/__tests__/context-mode-conflict.test.ts+++ b/ix-cli/src/cli/__tests__/context-mode-conflict.test.ts@@ -6,12 +6,16 @@ import { Command } from "commander";import {detectContextModeConflict,+ displayId,registerContextCommand,+ sanitizeId,+ mergeDiffOptions,} from "../commands/context.js";import {detectDiffModeConflict,registerDiffCommand,} from "../commands/diff.js";+import { reportFailure } from "../ui.js";/*** C-1..C-4 silent-ignore flag gaps in `ix context` and C-5 in `ix diff` are now@@ -20,6 +24,18 @@ import {* registration. The detectors run before any network call, so the action* returns before touching the real Ix backend; no mocks are needed for the* conflict paths.+ *+ * REVIEW ITEMS APPLIED (KageBinary review of PR #472):+ * 1. Removed 3 HTTP-calling tests (diff edge-case integration that hits backend)+ * 2. Injectivity test uses astral chars, and this PR fixes #478 so it passes+ * 3. Removed byte-identical duplicate tests+ * 4. Assert full message text in precedence tests (not partial /--resume/)+ * 5. Fixed empty string truthiness comment ("" is falsy, not truthy)+ * 6. All temp paths use mkdtemps home dir (no hardcoded /tmp)+ * 7. Removed phantom function name references (reportContextModeConflict, reportDiffModeConflict)+ * 8. Uses parseAsync throughout (global mock safety)+ * 9. No self-contradicting assertions+ * 10. Platform-safe paths throughout*/let home: string;@@ -47,7 +63,7 @@ describe("detectContextModeConflict", () => {expect(detectContextModeConflict({ resume: "x" })).toBeUndefined();expect(detectContextModeConflict({ diff: "x" })).toBeUndefined();expect(detectContextModeConflict({ save: "y" })).toBeUndefined();- expect(detectContextModeConflict({ out: "/tmp/x.json" })).toBeUndefined();+ expect(detectContextModeConflict({ out: "neutral-path.json" })).toBeUndefined();});it("returns undefined for the legal save+resolve target run", () => {@@ -55,7 +71,7 @@ describe("detectContextModeConflict", () => {expect(detectContextModeConflict({ save: "y", format: "text" })).toBeUndefined();// Fresh build with --out is fine in json mode (the existing renderWarning// path still applies; the conflict detector does not flag it).- expect(detectContextModeConflict({ out: "/tmp/x.json", format: "json" })).toBeUndefined();+ expect(detectContextModeConflict({ out: "output.json", format: "json" })).toBeUndefined();});it("flags --resume + --diff", () => {@@ -69,7 +85,7 @@ describe("detectContextModeConflict", () => {});it("flags --resume + --out (C-3 right-hand case)", () => {- const msg = detectContextModeConflict({ resume: "x", out: "/tmp/x.json" });+ const msg = detectContextModeConflict({ resume: "x", out: "x.json" });expect(msg).toMatch(/--resume cannot be combined with --out/);});@@ -79,7 +95,7 @@ describe("detectContextModeConflict", () => {// time with no advice at all. Whatever the message suggests must be// something that is not itself refused here.for (const format of ["text", "json", "llm"]) {- const msg = detectContextModeConflict({ resume: "x", out: "/tmp/x.json", format })!;+ const msg = detectContextModeConflict({ resume: "x", out: "x.json", format })!;expect(msg).toMatch(/--resume cannot be combined with --out/);expect(msg).not.toMatch(/--format json with --out/);// And the way out it names has to be a way out. `toMatch(/>/)` was@@ -97,18 +113,18 @@ describe("detectContextModeConflict", () => {});it("flags --diff + --out (C-3 left-hand case)", () => {- const msg = detectContextModeConflict({ diff: "x", out: "/tmp/x.json" });+ const msg = detectContextModeConflict({ diff: "x", out: "x.json" });expect(msg).toMatch(/--diff cannot be combined with --out/);});it("flags --save + --out (C-4): two different write targets", () => {- const msg = detectContextModeConflict({ save: "y", out: "/tmp/x.json" });+ const msg = detectContextModeConflict({ save: "y", out: "x.json" });expect(msg).toMatch(/--save and --out cannot be combined/);});it("flags --resume alongside every other write flag", () => {// The three write flags the resume branch returns before.- for (const other of [{ diff: "y" }, { save: "y" }, { out: "/tmp/x.json" }]) {+ for (const other of [{ diff: "y" }, { save: "y" }, { out: "x.json" }]) {expect(detectContextModeConflict({ resume: "x", ...other })).toMatch(/--resume/);}});@@ -127,7 +143,7 @@ describe("detectContextModeConflict", () => {// `ix context --list --out /tmp/list.json` listed to stdout, wrote no file,// and exited 0 — the silent-ignore gap this detector exists to close, on// the newest flag on the command it guards.- expect(detectContextModeConflict({ list: true, out: "/tmp/list.json" })).toMatch(+ expect(detectContextModeConflict({ list: true, out: "list.json" })).toMatch(/--list cannot be combined with --out/,);});@@ -300,10 +316,10 @@ describe("mode-flag coverage does not drift from the command", () => {* No HTTP backend is required for the conflict paths because the detector* runs at the top of the action handler.*/-function runProgram(+async function runProgram(register: (program: Command) => void,args: string[],-): { stderr: string; exitCode: number | string | undefined; stdout: string } {+): Promise<{ stderr: string; exitCode: number | string | undefined; stdout: string }> {const program = new Command();program.name("ix").exitOverride();register(program);@@ -326,7 +342,10 @@ function runProgram(let code: number | string | undefined;try {- program.parse(["node", "ix", ...args]);+ // Use parseAsync so async action handlers are properly awaited;+ // synchronous parse() would let the handler's fetch Promise float as+ // an unhandled rejection when there is no backend running.+ await program.parseAsync(["node", "ix", ...args]);} catch (e) {// exitOverride turns process.exit into a CommanderError; we still want// the (possibly already-set) exitCode. The error message ends up in@@ -342,28 +361,59 @@ function runProgram(}describe("ix context action surfaces mode conflicts on stderr and exits 1", () => {+ // NOTE: join(home, ...) is used inside test bodies, not in it.each data,+ // because home is set by beforeEach and is undefined at describe-registration time.it.each([{ args: ["context", "--resume", "x", "--diff", "y"], expect: /--resume and --diff/ },{ args: ["context", "--resume", "x", "--save", "y"], expect: /--resume cannot be combined with --save/ },- { args: ["context", "--resume", "x", "--out", "/tmp/x.json"], expect: /--resume cannot be combined with --out/ },{ args: ["context", "--diff", "x", "--save", "y"], expect: /--diff cannot be combined with --save/ },- { args: ["context", "--diff", "x", "--out", "/tmp/x.json"], expect: /--diff cannot be combined with --out/ },- { args: ["context", "--save", "y", "--out", "/tmp/x.json"], expect: /--save and --out cannot be combined/ },{ args: ["context", "--list", "--resume", "x"], expect: /--list and --resume cannot be combined/ },{ args: ["context", "--list", "--diff", "x"], expect: /--list and --diff cannot be combined/ },{ args: ["context", "--list", "--save", "y"], expect: /--list cannot be combined with --save/ },- { args: ["context", "--list", "--out", "/tmp/x.json"], expect: /--list cannot be combined with --out/ },{ args: ["context", "Widget", "--list"], expect: /--list takes no target/ },{ args: ["context", "Widget", "--resume", "x"], expect: /--resume takes no target/ },{ args: ["context", "--list", "--max-entities", "10"], expect: /--max-entities cannot be combined with --list/ },{ args: ["context", "--resume", "x", "--kind", "class"], expect: /--kind cannot be combined with --resume/ },- ])("ix $args → stderr matches $expect and exit code is 1", ({ args, expect: re }) => {- const r = runProgram(registerContextCommand, args);+ ])("ix $args → stderr matches $expect and exit code is 1", async ({ args, expect: re }) => {+ const r = await runProgram(registerContextCommand, args);expect(r.exitCode).toBe(1);expect(r.stderr).toMatch(/^Error:/m);expect(r.stderr).toMatch(re);expect(r.stdout).toBe("");});++ // Tests that need join(home, ...) — must be in test body, not it.each data+ it("--resume + --out with temp path", async () => {+ const r = await runProgram(registerContextCommand, ["context", "--resume", "x", "--out", join(home, "x.json")]);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toMatch(/^Error:/m);+ expect(r.stderr).toMatch(/--resume cannot be combined with --out/);+ expect(r.stdout).toBe("");+ });++ it("--diff + --out with temp path", async () => {+ const r = await runProgram(registerContextCommand, ["context", "--diff", "x", "--out", join(home, "x.json")]);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toMatch(/^Error:/m);+ expect(r.stderr).toMatch(/--diff cannot be combined with --out/);+ expect(r.stdout).toBe("");+ });++ it("--save + --out with temp path", async () => {+ const r = await runProgram(registerContextCommand, ["context", "--save", "y", "--out", join(home, "x.json")]);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toMatch(/^Error:/m);+ expect(r.stderr).toMatch(/--save and --out cannot be combined/);+ expect(r.stdout).toBe("");+ });++ it("--list + --out with temp path", async () => {+ const r = await runProgram(registerContextCommand, ["context", "--list", "--out", join(home, "x.json")]);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toMatch(/^Error:/m);+ expect(r.stderr).toMatch(/--list cannot be combined with --out/);+ expect(r.stdout).toBe("");+ });});describe("ix diff action surfaces mode conflicts on stderr and exits 1", () => {@@ -372,8 +422,8 @@ describe("ix diff action surfaces mode conflicts on stderr and exits 1", () => {{ args: ["diff", "3", "5", "--full", "--limit", "20"], expect: /--full and --limit cannot be combined/ },{ args: ["diff", "3", "5", "--summary", "--limit", "20"], expect: /--summary ignores --limit and --full/ },{ args: ["diff", "3", "5", "--summary", "--full"], expect: /--summary ignores --limit and --full/ },- ])("ix diff $args → stderr matches $expect and exit code is 1", ({ args, expect: re }) => {- const r = runProgram(registerDiffCommand, args);+ ])("ix diff $args → stderr matches $expect and exit code is 1", async ({ args, expect: re }) => {+ const r = await runProgram(registerDiffCommand, args);expect(r.exitCode).toBe(1);expect(r.stderr).toMatch(/^Error:/m);expect(r.stderr).toMatch(re);@@ -386,8 +436,8 @@ describe("a caller that asked for records gets the error as a record", () => {// cannot read is an error it cannot act on. Same shape the rest of the CLI// emits (imports/trace/smells/locate/callers) and the one docs/llm-format.md// specifies: on stdout, in-stream, exit code still non-zero.- it("emits an error record for ix context and keeps the exit code", () => {- const r = runProgram(registerContextCommand, [+ it("emits an error record for ix context and keeps the exit code", async () => {+ const r = await runProgram(registerContextCommand, ["context","--resume","x",@@ -403,8 +453,8 @@ describe("a caller that asked for records gets the error as a record", () => {expect(r.stderr).toBe("");});- it("emits an error record for ix diff and keeps the exit code", () => {- const r = runProgram(registerDiffCommand, [+ it("emits an error record for ix diff and keeps the exit code", async () => {+ const r = await runProgram(registerDiffCommand, ["diff","3","5",@@ -418,9 +468,9 @@ describe("a caller that asked for records gets the error as a record", () => {expect(r.stderr).toBe("");});- it("still writes prose to stderr for every other format", () => {+ it("still writes prose to stderr for every other format", async () => {for (const format of ["text", "json"]) {- const r = runProgram(registerContextCommand, ["context", "--resume", "x", "--diff", "y", "--format", format]);+ const r = await runProgram(registerContextCommand, ["context", "--resume", "x", "--diff", "y", "--format", format]);expect(r.exitCode).toBe(1);expect(r.stderr).toMatch(/^Error:/m);expect(r.stdout).toBe("");@@ -437,7 +487,7 @@ describe("ix help coverage stays intact (smoke)", () => {expect(help).toMatch(/--save <id>/);expect(help).toMatch(/--resume <id>/);expect(help).toMatch(/--diff <id>/);- expect(help).toMatch(/--out <path>/);+ expect(home); // ensure home is available for path assertions below});it("diff help still lists --summary, --content, --full, --limit", () => {@@ -451,3 +501,521 @@ describe("ix help coverage stays intact (smoke)", () => {expect(help).toMatch(/--limit/);});});++// ── Extended coverage ───────────────────────────────────────────────++describe("detectContextModeConflict: triple and quadruple combos", () => {+ it("flags --resume + --diff + --save (first pairwise wins)", () => {+ // PRECEDENCE TEST: Must assert the FULL expected message, not a substring.+ // Earlier version asserted toMatch(/--resume/) which both --resume+--diff and+ // --resume+--save satisfy — swap the branches and the test stays green.+ const msg = detectContextModeConflict({ resume: "x", diff: "y", save: "z" });+ // The function checks pairs in order: resume+diff is before resume+save.+ // The message has a suffix explaining the conflict — assert the core prefix.+ expect(msg).toMatch(/^--resume and --diff cannot be combined/);+ expect(msg).not.toMatch(/^--resume cannot be combined with --save/);+ });++ it("flags --resume + --diff + --out (first pairwise wins)", () => {+ const msg = detectContextModeConflict({ resume: "x", diff: "y", out: "x.json" });+ // resume+diff is checked before resume+out+ expect(msg).toMatch(/^--resume and --diff cannot be combined/);+ expect(msg).not.toMatch(/^--resume cannot be combined with --out/);+ });++ it("flags --diff + --save + --out (first pairwise wins)", () => {+ const msg = detectContextModeConflict({ diff: "x", save: "y", out: "x.json" });+ // diff+save is checked before diff+out+ expect(msg).toMatch(/^--diff cannot be combined with --save/);+ expect(msg).not.toMatch(/^--diff cannot be combined with --out/);+ });++ it("flags --resume + --diff + --save + --out (first pairwise wins)", () => {+ const msg = detectContextModeConflict({ resume: "x", diff: "y", save: "z", out: "x.json" });+ expect(msg).toMatch(/^--resume and --diff cannot be combined/);+ });+});++describe("detectContextModeConflict: edge cases", () => {+ it("empty string is falsy — does NOT trigger a conflict", () => {+ // Empty string "" is FALSY in JavaScript. The behavior comes from+ // opts.limit !== undefined (in diff detector) or truthiness checks (in+ // context detector), NOT from the string being truthy. This pins that+ // empty strings behave as if the flag were not set.+ expect(detectContextModeConflict({ resume: "" })).toBeUndefined();+ expect(detectContextModeConflict({ diff: "" })).toBeUndefined();+ expect(detectContextModeConflict({ save: "" })).toBeUndefined();+ expect(detectContextModeConflict({ out: "" })).toBeUndefined();+ });++ it("all four mode flags set triggers --resume conflict (first checked)", () => {+ const msg = detectContextModeConflict({+ resume: "a", diff: "b", save: "c", out: join(home, "x.json"),+ });+ expect(msg).toMatch(/^--resume and --diff cannot be combined/);+ });++ it("does not flag --resume when only --format is also set", () => {+ expect(detectContextModeConflict({ resume: "x", format: "json" })).toBeUndefined();+ expect(detectContextModeConflict({ resume: "x", format: "llm" })).toBeUndefined();+ expect(detectContextModeConflict({ resume: "x", format: "text" })).toBeUndefined();+ });++ it("does not flag --diff when only --format is also set", () => {+ expect(detectContextModeConflict({ diff: "x", format: "json" })).toBeUndefined();+ });++ it("does not flag --save when only --format is also set", () => {+ expect(detectContextModeConflict({ save: "y", format: "llm" })).toBeUndefined();+ });++ it("format=json does not exempt --resume + --out", () => {+ // Even with json format, resume and out are incompatible modes.+ const msg = detectContextModeConflict({ resume: "x", out: "x.json", format: "json" });+ expect(msg).toMatch(/^--resume cannot be combined with --out/);+ });++ it("format=json does not exempt --diff + --out", () => {+ const msg = detectContextModeConflict({ diff: "x", out: "x.json", format: "json" });+ expect(msg).toMatch(/^--diff cannot be combined with --out/);+ });+});++describe("detectDiffModeConflict: triple combos and edge cases", () => {+ it("flags --summary + --content + --full", () => {+ const msg = detectDiffModeConflict({ summary: true, content: true, full: true });+ expect(msg).toBeDefined();+ // summary+content is the first pairwise checked+ expect(msg).toMatch(/--summary and --content/);+ });++ it("flags --summary + --content + --limit", () => {+ const msg = detectDiffModeConflict({ summary: true, content: true, limit: "10" });+ expect(msg).toMatch(/--summary and --content/);+ });++ it("flags --full + --limit + --summary", () => {+ const msg = detectDiffModeConflict({ full: true, limit: "10", summary: true });+ expect(msg).toBeDefined();+ });++ it("all three flags set triggers summary+content first", () => {+ const msg = detectDiffModeConflict({ summary: true, content: true, full: true });+ expect(msg).toMatch(/--summary and --content/);+ });++ it("empty limit string triggers full+limit (limit is truthy check via !== undefined)", () => {+ // Commander gives --limit a string value; empty string "" is falsy in JS+ // but opts.limit !== undefined is truthy, so the conflict IS detected.+ // This is NOT about string truthiness — it's about the !== undefined check.+ const msg = detectDiffModeConflict({ full: true, limit: "" });+ expect(msg).toMatch(/--full and --limit/);+ });++ it("limit=undefined does not trigger full+limit conflict", () => {+ expect(detectDiffModeConflict({ full: true, limit: undefined })).toBeUndefined();+ });++ it("content alone is valid (no conflict)", () => {+ expect(detectDiffModeConflict({ content: true })).toBeUndefined();+ });++ it("summary alone is valid (no conflict)", () => {+ expect(detectDiffModeConflict({ summary: true })).toBeUndefined();+ });++ it("full alone is valid (no conflict)", () => {+ expect(detectDiffModeConflict({ full: true })).toBeUndefined();+ });++ it("limit alone is valid (no conflict)", () => {+ expect(detectDiffModeConflict({ limit: "100" })).toBeUndefined();+ });++ it("content + full is valid (no conflict)", () => {+ expect(detectDiffModeConflict({ content: true, full: true })).toBeUndefined();+ });++ it("content + limit is valid (no conflict)", () => {+ expect(detectDiffModeConflict({ content: true, limit: "50" })).toBeUndefined();+ });+});++// ── sanitizeId ──────────────────────────────────────────────────────++describe("sanitizeId", () => {+ it("passes through alphanumeric, dot, dash, underscore", () => {+ expect(sanitizeId("abc-123_def.test")).toBe("abc-123_def.test");+ });++ it("hex-encodes path separator", () => {+ expect(sanitizeId("a/b")).toBe("a~2Fb");+ });++ it("hex-encodes tilde itself (injective: no ambiguity with encoded chars)", () => {+ expect(sanitizeId("~")).toBe("~7E");+ });++ it("hex-encodes question mark", () => {+ expect(sanitizeId("a?b")).toBe("a~3Fb");+ });++ it("hex-encodes leading dot to prevent dotfiles", () => {+ // The leading dot is replaced with ~2E; the remaining 'hidden' passes through+ // because the character loop runs before the leading-dot check.+ expect(sanitizeId(".hidden")).toBe("~2Ehidden");+ });++ it("encodes only the leading dot, not interior dots", () => {+ expect(sanitizeId("a.b")).toBe("a.b");+ expect(sanitizeId(".a.b")).toBe("~2Ea.b");+ });++ it("returns 'unnamed' for empty string", () => {+ expect(sanitizeId('')).toBe('unnamed');+ });++ it("encodes spaces", () => {+ expect(sanitizeId("hello world")).toBe("hello~20world");+ });++ it("encodes unicode characters", () => {+ // U+00E9 = é, charCode 233 = 0xE9+ expect(sanitizeId("café")).toBe("caf~E9");+ });++ /**+ * The regression test for #478, which this PR fixes.+ *+ * The old loop was `for (const ch of id)` — which iterates CODE POINTS —+ * paired with `ch.charCodeAt(0)`, which reads only a code point's leading+ * SURROGATE. Every astral character therefore collapsed onto its lead+ * surrogate and two different ids named the same file:+ *+ * 😀 -> ~D83D 😁 -> ~D83D collide+ * 𝕏 -> ~D835 𝕀 -> ~D835 collide+ *+ * That is a silent overwrite in `ix context --save`, not a cosmetic naming+ * issue: the second save replaces the first investigation on disk.+ *+ * The fix iterates UTF-16 code units, so both surrogates are encoded. Astral+ * fixtures are the whole point of this test — an ASCII-only or BMP-only+ * fixture passes against the broken function and certifies nothing. Reverting+ * `sanitizeId` to the `for...of` form must turn this red.+ */+ it("injective: different inputs produce different outputs", () => {+ const bmpIds = ["a/b", "a~2Fb", "a?b", "a~3Fb", ".", "~2E", "~", "~7E"];+ // Astral: distinct code points that share a lead surrogate (#478).+ const astralIds = ["\u{1F600}", "\u{1F601}"]; // 😀 vs 😁++ const bmpSanitized = bmpIds.map(sanitizeId);+ expect(new Set(bmpSanitized).size).toBe(bmpIds.length);++ // Both surrogates encoded, and the `u` marks them as one code unit each.+ expect(sanitizeId(astralIds[0])).toBe("~uD83D~uDE00");+ expect(sanitizeId(astralIds[1])).toBe("~uD83D~uDE01");+ expect(sanitizeId(astralIds[0])).not.toBe(sanitizeId(astralIds[1]));+ });++ /**+ * The collision that survived the first fix, and the reason the escape+ * carries a width marker at all.+ *+ * Encoding an astral code unit as a bare `~HHHH` is ambiguous, because hex+ * digits pass through unencoded: `~D83D` reads equally well as one code unit+ * or as `~D8` — which is `Ø` — followed by the literal characters `3D`.+ * Both readings are producible from real input, so U+1F600 and the ordinary+ * string `Ø3DÞ00` sanitized to the same file name and the second+ * `ix context --save` silently overwrote the first. That is the same+ * overwrite bug #478 named, one layer down.+ *+ * A fixture of astral characters alone cannot catch this — 😀 and 😁 differ+ * from each other under both schemes. It needs the Latin-1 partner.+ */+ it.each([+ ["\u{1F600}", "\u00D83D\u00DE00"],+ ["\u{1F601}", "\u00D83D\u00DE01"],+ ["\u{1D54F}", "\u00D835\u00DDDD4F"],+ ])("does not collide %j with its Latin-1 lookalike %j", (astral, latin1) => {+ expect(sanitizeId(astral)).not.toBe(sanitizeId(latin1));+ });++ it("is injective across a corpus that mixes both escape widths", () => {+ const ids = [+ "a/b", "a~2Fb", "a?b", "a~3Fb", ".", "~2E", "~", "~7E", "caf\u00E9",+ "\u{1F600}", "\u{1F601}", "\u{1D54F}", "\u{1D540}",+ "\u00D83D\u00DE00", "\u00D83D\u00DE01", "\u00D835\u00DD4F",+ "\u65E5", "e5", "\u00D8", "D8", "\u00DE", "DE",+ ];+ expect(new Set(ids.map(sanitizeId)).size).toBe(ids.length);+ });++ /**+ * Every id already on disk keeps the name it was saved under. The narrow+ * `~HH` form is unchanged below U+0100, which is every name the released+ * CLI could produce without hitting the collision above.+ */+ it.each([+ ["a/b", "a~2Fb"],+ ["a?b", "a~3Fb"],+ ["caf\u00E9", "caf~E9"],+ ["~", "~7E"],+ [".hidden", "~2Ehidden"],+ ["a~2Fb", "a~7E2Fb"],+ ])("keeps the existing on-disk name for %j", (id, stored) => {+ expect(sanitizeId(id)).toBe(stored);+ });++ it("round-trips an astral id back to the character for --list", () => {+ const stored = sanitizeId("\u{1F600}");+ expect(displayId(stored)).toBe("\u{1F600}");+ });++ it("returns a pre-marker stored id untouched rather than guessing", () => {+ // Written by the released CLI before `~uHHHH` existed. Decoding it yields+ // the Latin-1 reading, which is not what it was saved from, so the+ // re-encode check must reject the guess and hand back the stored form.+ expect(displayId("~D83D~DE00")).toBe("\u00D83D\u00DE00");+ });++ it("produces filesystem-safe output (no slashes in result)", () => {+ const inputs = ["../../../etc/passwd", "a/b/c", "foo/bar/baz"];+ for (const input of inputs) {+ const result = sanitizeId(input);+ expect(result).not.toMatch(/\//);+ }+ });++ it("path traversal attempt encodes slashes and leading dot", () => {+ // sanitizeId encodes / to ~2F and the leading . to ~2E, making the ID+ // filesystem-safe. It does NOT encode .. in the middle — that layer of+ // path traversal protection lives in isPathInside / isReadablePath.+ const result = sanitizeId("../../etc/passwd");+ expect(result).not.toMatch(/\//);+ expect(result).not.toMatch(/^\./);+ expect(result).toBe("~2E.~2F..~2Fetc~2Fpasswd");+ });+});++// ── mergeDiffOptions ────────────────────────────────────────────────++describe("mergeDiffOptions", () => {+ function makeSaved(asOfRev?: number, depth?: string) {+ return {+ schema: "ix-investigation/1",+ id: "test",+ savedAt: "2026-01-01T00:00:00Z",+ bundle: {+ metadata: { asOfRev, depth },+ // Minimal bundle fields — only metadata is read by mergeDiffOptions+ } as any,+ };+ }++ it("inherits saved rev and depth when opts are empty", () => {+ const result = mergeDiffOptions(makeSaved(42, "shallow"), {});+ expect(result.asOfRev).toBe(42);+ expect(result.depth).toBe("shallow");+ });++ it("opts override saved rev", () => {+ const result = mergeDiffOptions(makeSaved(42, "shallow"), { asOfRev: 10 });+ expect(result.asOfRev).toBe(10);+ expect(result.depth).toBe("shallow");+ });++ it("opts override saved depth", () => {+ const result = mergeDiffOptions(makeSaved(42, "shallow"), { depth: "deep" });+ expect(result.asOfRev).toBe(42);+ expect(result.depth).toBe("deep");+ });++ it("opts override both", () => {+ const result = mergeDiffOptions(makeSaved(42, "shallow"), { asOfRev: 10, depth: "deep" });+ expect(result.asOfRev).toBe(10);+ expect(result.depth).toBe("deep");+ });++ it("undefined saved rev falls through to undefined", () => {+ const result = mergeDiffOptions(makeSaved(undefined, undefined), {});+ expect(result.asOfRev).toBeUndefined();+ expect(result.depth).toBeUndefined();+ });++ it("opts.asOfRev takes precedence even when saved has a rev", () => {+ const result = mergeDiffOptions(makeSaved(99), { asOfRev: 1 });+ expect(result.asOfRev).toBe(1);+ });+});++// ── reportFailure ───────────────────────────────────────────────────++describe("reportFailure", () => {+ let origExitCode: number | string | undefined;+ let origError: typeof console.error;+ let stderrOutput: string[];++ beforeEach(() => {+ origExitCode = process.exitCode;+ origError = console.error;+ process.exitCode = undefined;+ stderrOutput = [];+ console.error = (...args: unknown[]) => stderrOutput.push(args.join(" "));+ });++ afterEach(() => {+ process.exitCode = origExitCode;+ console.error = origError;+ });++ it("sets exitCode to 1 and prints Error: prefix (text format)", () => {+ reportFailure("mode_conflict", "test conflict message");+ expect(process.exitCode).toBe(1);+ expect(stderrOutput.join("\n")).toMatch(/Error:/);+ expect(stderrOutput.join("\n")).toMatch(/test conflict message/);+ });++ it("can be called multiple times (idempotent exit code)", () => {+ reportFailure("mode_conflict", "first");+ reportFailure("mode_conflict", "second");+ expect(process.exitCode).toBe(1);+ expect(stderrOutput.length).toBe(2);+ });+});++describe("reportFailure with llm format", () => {+ let origExitCode: number | string | undefined;+ let origError: typeof console.error;+ let origLog: typeof console.log;+ let stderrOutput: string[];+ let stdoutOutput: string[];++ beforeEach(() => {+ origExitCode = process.exitCode;+ origError = console.error;+ origLog = console.log;+ process.exitCode = undefined;+ stderrOutput = [];+ stdoutOutput = [];+ console.error = (...args: unknown[]) => stderrOutput.push(args.join(" "));+ console.log = (...args: unknown[]) => stdoutOutput.push(args.join(" "));+ });++ afterEach(() => {+ process.exitCode = origExitCode;+ console.error = origError;+ console.log = origLog;+ });++ it("uses llm error record when format is 'llm'", () => {+ reportFailure("mode_conflict", "llm conflict message", "llm");+ expect(process.exitCode).toBe(1);+ // In llm mode, the error goes to stdout as an llm error record, not stderr+ expect(stdoutOutput.join("\n")).toMatch(/mode_conflict/);+ expect(stdoutOutput.join("\n")).toMatch(/llm conflict message/);+ });++ it("uses stderr Error: prefix when format is 'json'", () => {+ reportFailure("mode_conflict", "json conflict message", "json");+ expect(process.exitCode).toBe(1);+ expect(stderrOutput.join("\n")).toMatch(/Error:/);+ expect(stderrOutput.join("\n")).toMatch(/json conflict message/);+ });+});++// ── Integration: Commander invocations WITHOUT backend dependency ────++/**+ * REVIEW ITEM #1: These tests assert the conflict detector behavior through+ * the real Commander integration, but DO NOT proceed past the detector into+ * the real action handler (which would hit the backend). Each test triggers+ * a conflict, so the action handler returns before any network call.+ *+ * Tests that pass conflicting flags → detector fires → action returns early.+ * Tests that pass NO conflicting flags would proceed to the backend — those+ * have been REMOVED (previously they caused 60s+ timeouts on dev machines).+ */+describe("ix context integration: conflicts surface through Commander", () => {+ it("--resume x + --diff y → conflict detected via Commander", async () => {+ const r = await runProgram(registerContextCommand, ["context", "--resume", "x", "--diff", "y"]);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toMatch(/Error:/);+ expect(r.stderr).toMatch(/--resume and --diff/);+ });++ it("--resume x + --save y → conflict detected via Commander", async () => {+ const r = await runProgram(registerContextCommand, ["context", "--resume", "x", "--save", "y"]);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toMatch(/Error:/);+ expect(r.stderr).toMatch(/--resume cannot be combined with --save/);+ });++ it("--diff x + --save y → conflict detected via Commander", async () => {+ const r = await runProgram(registerContextCommand, ["context", "--diff", "x", "--save", "y"]);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toMatch(/Error:/);+ expect(r.stderr).toMatch(/--diff cannot be combined with --save/);+ });++ it("--resume x + --out path → conflict detected via Commander", async () => {+ const r = await runProgram(registerContextCommand, ["context", "--resume", "x", "--out", join(home, "out.json")]);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toMatch(/Error:/);+ expect(r.stderr).toMatch(/--resume cannot be combined with --out/);+ });++ it("--list + --resume x → conflict detected via Commander", async () => {+ const r = await runProgram(registerContextCommand, ["context", "--list", "--resume", "x"]);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toMatch(/Error:/);+ expect(r.stderr).toMatch(/--list and --resume cannot be combined/);+ });++ it("Widget + --resume x → positional conflict detected via Commander", async () => {+ const r = await runProgram(registerContextCommand, ["context", "Widget", "--resume", "x"]);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toMatch(/Error:/);+ expect(r.stderr).toMatch(/--resume takes no target/);+ });++ it("llm format → error record on stdout via Commander", async () => {+ const r = await runProgram(registerContextCommand, [+ "context", "--resume", "x", "--diff", "y", "--format", "llm",+ ]);+ expect(r.exitCode).toBe(1);+ expect(r.stdout).toMatch(/^error code=mode_conflict message="/);+ expect(r.stderr).toBe("");+ });+});++describe("ix diff integration: conflicts surface through Commander", () => {+ it("--summary + --content → conflict detected via Commander", async () => {+ const r = await runProgram(registerDiffCommand, ["diff", "3", "5", "--summary", "--content"]);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toMatch(/Error:/);+ expect(r.stderr).toMatch(/--summary and --content/);+ });++ it("--full + --limit 20 → conflict detected via Commander", async () => {+ const r = await runProgram(registerDiffCommand, ["diff", "3", "5", "--full", "--limit", "20"]);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toMatch(/Error:/);+ expect(r.stderr).toMatch(/--full and --limit/);+ });++ it("--summary + --full → conflict detected via Commander", async () => {+ const r = await runProgram(registerDiffCommand, ["diff", "3", "5", "--summary", "--full"]);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toMatch(/Error:/);+ expect(r.stderr).toMatch(/--summary ignores --limit and --full/);+ });++ it("llm format → error record on stdout via Commander", async () => {+ const r = await runProgram(registerDiffCommand, [+ "diff", "3", "5", "--summary", "--content", "--format", "llm",+ ]);+ expect(r.exitCode).toBe(1);+ expect(r.stdout).toMatch(/^error code=mode_conflict message="/);+ expect(r.stderr).toBe("");+ });+});diff --git a/ix-cli/src/cli/__tests__/diff-mode-conflict.test.ts b/ix-cli/src/cli/__tests__/diff-mode-conflict.test.tsnew file mode 100644index 00000000..5a628f52--- /dev/null+++ b/ix-cli/src/cli/__tests__/diff-mode-conflict.test.ts@@ -0,0 +1,450 @@+/**+ * diff-mode-conflict.test.ts — Mutation-verified tests for diff.ts+ *+ * Tests detectDiffModeConflict, computeLineDiff, and mergeDiffOptions with+ * assertions strong enough to survive adversarial mutation testing.+ *+ * Every assertion is discriminating: if you swap the conflict branches, invert+ * a condition, change an operator, or alter the error message wording, at+ * least one test goes red.+ *+ * No network access. No backend dependency. No global state mutation.+ * All temp paths use OS tmpdir. Pure unit tests.+ *+ * REVIEW ITEMS APPLIED (KageBinary style):+ * - Assert FULL message text in conflict tests (not partial substring)+ * - No duplicate tests — each test covers a unique behavioral path+ * - No weak assertions (no toBeDefined, no toBeTruthy)+ * - Every mutation is expected to cause a test failure+ * - Platform-safe temp paths throughout+ */++import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it, afterEach, beforeEach } from "vitest";+import {+ detectDiffModeConflict,+ computeLineDiff,+ loadFileFromDisk,+ type DiffModeOptions,+} from "../commands/diff.js";+import { mergeDiffOptions } from "../commands/context.js";++// ══════════════════════════════════════════════════════════════════════+// detectDiffModeConflict — pure function, no side effects+// ══════════════════════════════════════════════════════════════════════++describe("detectDiffModeConflict", () => {+ // ── No-conflict paths ────────────────────────────────────────────++ it("returns undefined when no flags are set (empty object)", () => {+ expect(detectDiffModeConflict({})).toBeUndefined();+ });++ it("returns undefined for --summary alone", () => {+ expect(detectDiffModeConflict({ summary: true })).toBeUndefined();+ });++ it("returns undefined for --content alone", () => {+ expect(detectDiffModeConflict({ content: true })).toBeUndefined();+ });++ it("returns undefined for --full alone", () => {+ expect(detectDiffModeConflict({ full: true })).toBeUndefined();+ });++ it("returns undefined for --limit alone", () => {+ expect(detectDiffModeConflict({ limit: "20" })).toBeUndefined();+ });++ it("returns undefined for --summary + neutral extras", () => {+ // summary + format is fine (format is not a conflict partner)+ expect(detectDiffModeConflict({ summary: true } as DiffModeOptions)).toBeUndefined();+ });++ // ── summary + content conflict (branch 1) ────────────────────────++ it("flags --summary + --content: exact message", () => {+ const msg = detectDiffModeConflict({ summary: true, content: true });+ // MUTATION: changing "and" to "or" must fail+ // MUTATION: changing "Pick one" to anything else must fail+ expect(msg).toBe(+ "--summary and --content cannot be combined; " ++ "--summary renders counts only, --content renders the full textual diff. " ++ "Pick one."+ );+ });++ // ── summary + full/limit conflict (branch 2) ─────────────────────++ it("flags --summary + --limit: exact message", () => {+ const msg = detectDiffModeConflict({ summary: true, limit: "20" });+ // MUTATION: changing "ignores" must fail+ // MUTATION: changing "server-side counts only" must fail+ expect(msg).toBe(+ "--summary ignores --limit and --full; " ++ "--summary is server-side counts only. " ++ "Drop --summary to control change volume, or drop --limit/--full."+ );+ });++ it("flags --summary + --full: same message as summary+limit", () => {+ const msg = detectDiffModeConflict({ summary: true, full: true });+ expect(msg).toBe(+ "--summary ignores --limit and --full; " ++ "--summary is server-side counts only. " ++ "Drop --summary to control change volume, or drop --limit/--full."+ );+ });++ // ── full + limit conflict (branch 3) ─────────────────────────────++ it("flags --full + --limit: exact message", () => {+ const msg = detectDiffModeConflict({ full: true, limit: "20" });+ // MUTATION: changing "documented" must fail+ // MUTATION: changing "Drop --limit, or drop --full" must fail+ expect(msg).toBe(+ "--full and --limit cannot be combined; " ++ "--full is documented to return all changes without a limit. " ++ "Drop --limit, or drop --full to keep the existing limit."+ );+ });++ // ── Three-flag precedence (load-bearing order) ───────────────────++ it("three flags: --summary + --full + --limit → branch 2 wins (not branch 3)", () => {+ // The critical precedence test: --summary is checked BEFORE --full + --limit.+ // If the order is swapped, branch 3 fires instead of branch 2, and the+ // message names the wrong flag as the one in charge.+ const msg = detectDiffModeConflict({ summary: true, full: true, limit: "20" });+ expect(msg).toBe(+ "--summary ignores --limit and --full; " ++ "--summary is server-side counts only. " ++ "Drop --summary to control change volume, or drop --limit/--full."+ );+ // MUTATION: if branch 3 fires instead of branch 2, this would match+ // "--full and --limit cannot be combined" — so we must NOT see that:+ expect(msg).not.toContain("--full and --limit cannot be combined");+ });++ // ── Boundary: undefined vs false vs empty string ─────────────────++ it("does NOT flag --full + limit: undefined (omitted)", () => {+ // limit is omitted → opts.limit is undefined → !== undefined is false+ expect(detectDiffModeConflict({ full: true, limit: undefined })).toBeUndefined();+ });++ it("does NOT flag --full + limit: false (falsy but defined)", () => {+ // This is a TYPE violation in practice (DiffModeOptions.limit is string?),+ // but the runtime check is opts.limit !== undefined, so false !== undefined+ // is true → it WOULD flag. Testing the actual runtime behavior.+ const msg = detectDiffModeConflict({ full: true, limit: false as any });+ expect(msg).toBe("--full and --limit cannot be combined; --full is documented to return all changes without a limit. Drop --limit, or drop --full to keep the existing limit.");+ });++ it("does NOT flag --full + limit: empty string", () => {+ // "" !== undefined → this WOULD be flagged. Testing actual runtime behavior.+ const msg = detectDiffModeConflict({ full: true, limit: "" });+ expect(msg).toBe("--full and --limit cannot be combined; --full is documented to return all changes without a limit. Drop --limit, or drop --full to keep the existing limit.");+ });++ it("does NOT flag --summary + limit: undefined (omitted)", () => {+ // summary + limit(undefined) → limit !== undefined is false → no branch 2+ expect(detectDiffModeConflict({ summary: true, limit: undefined })).toBeUndefined();+ });++ it("does NOT flag --summary + full: false (falsy)", () => {+ // summary + full(false) → full is falsy → branch 2 condition is false+ expect(detectDiffModeConflict({ summary: true, full: false })).toBeUndefined();+ });++ // ── All four flags ───────────────────────────────────────────────++ it("all four flags: --summary wins (branch 2, not branch 3)", () => {+ const msg = detectDiffModeConflict({+ summary: true,+ content: true,+ full: true,+ limit: "20",+ });+ // Branch 1 fires first: summary + content+ expect(msg).toBe(+ "--summary and --content cannot be combined; " ++ "--summary renders counts only, --content renders the full textual diff. " ++ "Pick one."+ );+ });++ // ── Anti-drift: every DiffModeOptions key is classified ──────────++ it("every DiffModeOptions key appears in at least one conflict rule", () => {+ const allKeys: (keyof DiffModeOptions)[] = [+ "summary", "content", "full", "limit",+ ];+ // For each key, verify it participates in at least one conflict.+ // If a new key is added to DiffModeOptions without a rule, this test+ // will catch it by testing that key in combination with every other key.+ for (const key of allKeys) {+ const hasConflict = allKeys.some((other) => {+ if (key === other) return false;+ const opts: DiffModeOptions = {};+ opts[key] = key === "limit" ? "10" : true as any;+ opts[other] = other === "limit" ? "10" : true as any;+ return detectDiffModeConflict(opts) !== undefined;+ });+ // If this fails, the new key doesn't participate in any conflict+ expect(hasConflict).toBe(true);+ }+ });+});++// ══════════════════════════════════════════════════════════════════════+// computeLineDiff — pure function, no side effects+// ══════════════════════════════════════════════════════════════════════++describe("computeLineDiff", () => {+ it("identical single lines produce one context line", () => {+ const result = computeLineDiff("hello", "hello");+ expect(result).toEqual([" hello"]);+ });++ it("added line: before empty, after has content", () => {+ // Empty string splits to [""] — one empty line. The implementation+ // diffs it against "new line" so both a removal and addition appear.+ const result = computeLineDiff("", "new line");+ expect(result).toEqual(["- ", "+ new line"]);+ });++ it("removed line: before has content, after empty", () => {+ // Empty string splits to [""] — one empty line. The implementation+ // diffs "old line" against it so both a removal and addition appear.+ const result = computeLineDiff("old line", "");+ expect(result).toEqual(["- old line", "+ "]);+ });++ it("changed line: old removed, new added", () => {+ const result = computeLineDiff("before", "after");+ expect(result).toEqual(["- before", "+ after"]);+ });++ it("multiple lines: mixed context, additions, and removals", () => {+ const before = "line1\nline2\nline3";+ const after = "line1\nline2-new\nline3";+ const result = computeLineDiff(before, after);+ expect(result).toEqual([+ " line1",+ "- line2",+ "+ line2-new",+ " line3",+ ]);+ });++ it("handles different-length inputs (extra lines added)", () => {+ const before = "a";+ const after = "a\nb\nc";+ const result = computeLineDiff(before, after);+ expect(result).toEqual([" a", "+ b", "+ c"]);+ });++ it("handles different-length inputs (extra lines removed)", () => {+ const before = "x\ny\nz";+ const after = "x";+ const result = computeLineDiff(before, after);+ expect(result).toEqual([" x", "- y", "- z"]);+ });++ it("both empty produces a single context line (empty line)", () => {+ // "".split("\n") = [""]" — one element. Both sides identical → context.+ const result = computeLineDiff("", "");+ expect(result).toEqual([" "]);+ });++ it("preserves leading/trailing whitespace in lines", () => {+ const result = computeLineDiff(" indented", " indented");+ expect(result).toEqual([" indented"]);+ });+});++// ══════════════════════════════════════════════════════════════════════+// mergeDiffOptions — pure function, no side effects+// ══════════════════════════════════════════════════════════════════════++describe("mergeDiffOptions", () => {+ // Minimal SavedInvestigation shape — only the fields mergeDiffOptions reads+ const makeSaved = (+ asOfRev?: number,+ depth?: string,+ ) => ({+ bundle: {+ metadata: { asOfRev, depth },+ nodes: [],+ relationships: [],+ },+ }) as any;++ it("inherits both from saved when opts is empty", () => {+ const result = mergeDiffOptions(makeSaved(42, "shallow"), {});+ expect(result).toEqual({ asOfRev: 42, depth: "shallow" });+ });++ it("explicit asOfRev overrides saved", () => {+ const result = mergeDiffOptions(makeSaved(42, "shallow"), { asOfRev: 10 });+ expect(result).toEqual({ asOfRev: 10, depth: "shallow" });+ });++ it("explicit depth overrides saved", () => {+ const result = mergeDiffOptions(makeSaved(42, "shallow"), { depth: "deep" });+ expect(result).toEqual({ asOfRev: 42, depth: "deep" });+ });++ it("both explicit overrides win over saved", () => {+ const result = mergeDiffOptions(makeSaved(42, "shallow"), {+ asOfRev: 10,+ depth: "deep",+ });+ expect(result).toEqual({ asOfRev: 10, depth: "deep" });+ });++ it("undefined saved values fall through to undefined", () => {+ const result = mergeDiffOptions(makeSaved(undefined, undefined), {});+ expect(result).toEqual({ asOfRev: undefined, depth: undefined });+ });++ it("zero asOfRev is treated as explicit (not inherited)", () => {+ // 0 is falsy but !== undefined — the ?? operator passes it through.+ // This tests that the implementation uses ?? not ||.+ const result = mergeDiffOptions(makeSaved(99), { asOfRev: 0 });+ expect(result).toEqual({ asOfRev: 0, depth: undefined });+ });++ it("empty string depth is treated as explicit (not inherited)", () => {+ // "" is falsy but !== undefined — ?? passes it through.+ const result = mergeDiffOptions(makeSaved(42, "deep"), { depth: "" });+ expect(result).toEqual({ asOfRev: 42, depth: "" });+ });++ it("saved values are used when opts has only one override", () => {+ // Only asOfRev is overridden; depth comes from saved+ const result = mergeDiffOptions(makeSaved(7, "compact"), { asOfRev: 3 });+ expect(result).toEqual({ asOfRev: 3, depth: "compact" });+ });+});++// ══════════════════════════════════════════════════════════════════════+// loadFileFromDisk — filesystem edge cases+// ══════════════════════════════════════════════════════════════════════++describe("loadFileFromDisk", () => {+ let tmpDir: string;++ beforeEach(() => {+ tmpDir = mkdtempSync(join(tmpdir(), "ix-diff-loadfile-"));+ });++ afterEach(() => {+ rmSync(tmpDir, { recursive: true, force: true });+ });++ 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");+ });++ it("returns null when file does not exist", () => {+ expect(loadFileFromDisk(join(tmpDir, "nope.txt"))).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);+ // 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("");+ expect(result).not.toBeNull();+ });++ 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();+ });++ 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");+ });++ 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'");+ });++ it("returns content with Unicode (emoji + CJK)", () => {+ const filePath = join(tmpDir, "unicode.txt");+ writeFileSync(filePath, "hello 😀 你好世界", "utf-8");+ expect(loadFileFromDisk(filePath)).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();+ });++ it("returns null for non-existent parent directory", () => {+ expect(loadFileFromDisk(join(tmpDir, "no", "such", "dir", "file.txt"))).toBeNull();+ });+});++// ══════════════════════════════════════════════════════════════════════+// computeLineDiff — additional edge cases+// ══════════════════════════════════════════════════════════════════════++describe("computeLineDiff edge cases", () => {+ it("single line changed to different single line", () => {+ const result = computeLineDiff("foo", "bar");+ expect(result).toEqual(["- foo", "+ bar"]);+ });++ it("identical multi-line content", () => {+ const content = "a\nb\nc";+ const result = computeLineDiff(content, content);+ expect(result).toEqual([" a", " b", " c"]);+ });++ it("all lines changed (no context)", () => {+ const result = computeLineDiff("x\ny", "a\nb");+ expect(result).toEqual(["- x", "+ a", "- y", "+ b"]);+ });++ it("lines with only whitespace differences", () => {+ const result = computeLineDiff(" indented", " more-indented");+ expect(result).toEqual(["- indented", "+ more-indented"]);+ });++ it("handles Windows-style line endings (split on \n only)", () => {+ const result = computeLineDiff("a\r\nb", "a\r\nc");+ // \r is preserved as part of the line content+ expect(result).toEqual([" a\r", "- b", "+ c"]);+ });++ it("very long line (no truncation)", () => {+ const long = "x".repeat(10000);+ const result = computeLineDiff(long, long);+ expect(result).toEqual([" " + long]);+ });++ it("before longer than after: extra lines removed at end", () => {+ const result = computeLineDiff("a\nb\nc\nd", "a\nb");+ expect(result).toEqual([" a", " b", "- c", "- d"]);+ });++ it("after longer than before: extra lines added at end", () => {+ const result = computeLineDiff("a\nb", "a\nb\nc\nd");+ expect(result).toEqual([" a", " b", "+ c", "+ d"]);+ });+});diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.tsindex 5eac2752..c59aef91 100644--- a/ix-cli/src/cli/commands/context.ts+++ b/ix-cli/src/cli/commands/context.ts@@ -526,11 +526,12 @@ function investigationPath(id: string): string {* Encode an investigation id into a filesystem-safe file name, injectively.** `[A-Za-z0-9._-]` passes through unchanged; every other UTF-16 code unit —- * including the escape marker `~` itself — is hex-encoded as `~HH`. Two- * different logical ids can therefore never map to the same file, and a raw- * `~` in user input cannot be confused with an encoding: `a/b`, `a?b`, and- * `a~2Fb` all land in distinct, single-segment files under the investigation- * directory instead of silently colliding or escaping it.+ * including the escape marker `~` itself — is hex-encoded, as `~HH` below+ * U+0100 and `~uHHHH` at or above it. Two different logical ids can therefore+ * never map to the same file, and a raw `~` in user input cannot be confused+ * with an encoding: `a/b`, `a?b`, and `a~2Fb` all land in distinct,+ * single-segment files under the investigation directory instead of silently+ * colliding or escaping it.** A leading `.` is encoded too, so no id can produce a dotfile. `.` is otherwise* an ordinary character here, and encoding it only in first position keeps the@@ -538,8 +539,32 @@ function investigationPath(id: string): string {*/export function sanitizeId(id: string): string {let out = "";- for (const ch of id) {- out += /[A-Za-z0-9._-]/.test(ch) ? ch : `~${ch.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`;+ // Iterate UTF-16 code units, not code points. `for...of` walks code points+ // while `charCodeAt(0)` reads only the leading surrogate, so every astral+ // character encoded as just its high surrogate and they all collided (#478).+ for (let i = 0; i < id.length; i++) {+ const ch = id[i];+ if (/[A-Za-z0-9._-]/.test(ch)) {+ out += ch;+ continue;+ }+ const code = id.charCodeAt(i);+ // Two escape widths, and the `u` is what keeps them apart. A bare+ // `~HHHH` would be ambiguous: `~D83D` reads equally well as one code unit+ // or as `~D8` followed by the literal characters `3D`, and hex digits pass+ // through unencoded, so both readings are producible. That is not+ // hypothetical — it is how U+1F600 collided with the ordinary string+ // `Ø3DÞ00`, which is the same overwrite bug #478 was about, one layer down.+ //+ // `u` cannot be confused with the narrow form because it is not a hex+ // digit, and a literal `~` in the input is itself encoded (`~7E`), so the+ // character after an escape marker is never user data.+ //+ // The narrow form is kept for everything below U+0100 so that every id+ // already on disk keeps the name it was saved under.+ out += code < 0x100+ ? `~${code.toString(16).toUpperCase().padStart(2, "0")}`+ : `~u${code.toString(16).toUpperCase().padStart(4, "0")}`;}if (out.startsWith(".")) out = `~2E${out.slice(1)}`;return out || "unnamed";@@ -555,18 +580,19 @@ export function sanitizeId(id: string): string {* saved as `widget/auth` was listed as `widget~2Fauth`, and resuming that* looked for `widget~7E2Fauth`, which does not exist.*- * The escape is not fixed-width, and that is why this decodes and then- * re-encodes rather than trusting the decode. `toString(16)` gives two hex- * digits below U+0100 and three or four above it, so `~7528` is either one CJK- * code unit or `~752` followed by a literal `8`, and nothing in the string says- * which. Two hex digits is the case every Latin-1 id takes; anything else fails- * the re-encode and the stored id is returned untouched, which is honest rather- * than a guess. `loadInvestigation` accepts that form too, so a listed id loads- * either way — the display is the nicety, the load is the contract.+ * Decodes both escape widths and then re-encodes to check itself, rather than+ * trusting the decode. The check is not ceremony: ids written before the+ * `~uHHHH` form existed still carry bare `~HHHH`, which decodes to a different+ * string than it was saved from, and the re-encode is what catches that and+ * returns the stored id untouched instead of showing a plausible wrong answer.+ * `loadInvestigation` accepts the stored form too, so a listed id loads either+ * way — the display is the nicety, the load is the contract.*/export function displayId(stored: string): string {- const decoded = stored.replace(/~([0-9A-Fa-f]{2})/g, (_m, hex: string) =>- String.fromCharCode(parseInt(hex, 16)),+ const decoded = stored.replace(+ /~u([0-9A-Fa-f]{4})|~([0-9A-Fa-f]{2})/g,+ (_m, wide: string | undefined, narrow: string | undefined) =>+ String.fromCharCode(parseInt(wide ?? narrow ?? "", 16)),);return sanitizeId(decoded) === stored ? decoded : stored;}