Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix(cli): cap long lines in `ix text` snippets (HR-01)

KageBinaryc365105025fb
diff --git a/ix-cli/src/cli/__tests__/text-snippet-cap.test.ts b/ix-cli/src/cli/__tests__/text-snippet-cap.test.ts
new file mode 100644
index 00000000..2ecd8d55
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/text-snippet-cap.test.ts
@@ -0,0 +1,92 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Command } from "commander";
+import { clipSnippet, registerTextCommand, SNIPPET_MAX_CHARS as CAP } from "../commands/text.js";
+
+function sub(text: string, needle: string) {
+ const start = Buffer.byteLength(text.slice(0, text.indexOf(needle)));
+ return [{ start, end: start + Buffer.byteLength(needle) }];
+}
+function clip(text: string, needle = "needle") {
+ return clipSnippet(text, sub(text, needle));
+}
+const lone = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
+
+describe("clipSnippet", () => {
+ it("clips a 50 KB line around the match", () => {
+ const t = "x".repeat(25000) + "needle" + "y".repeat(25000) + "\n";
+ const r = clip(t);
+ expect(r.length).toBeLessThanOrEqual(CAP + 2);
+ expect(r.startsWith("…")).toBe(true);
+ expect(r.endsWith("…")).toBe(true);
+ expect(r).toContain("needle");
+ });
+ it("leaves short lines and lines at the cap unchanged", () => {
+ expect(clip("const needle = 1;\n")).toBe("const needle = 1;\n");
+ const exact = "a".repeat(CAP - 6) + "needle";
+ expect(clip(exact + "\n")).toBe(exact + "\n");
+ expect(clip(exact + "z\n")).not.toBe(exact + "z\n");
+ });
+ it("marks only the cut side", () => {
+ const head = clip("needle" + "y".repeat(5000) + "\n");
+ expect(head.startsWith("needle")).toBe(true);
+ expect(head.endsWith("…")).toBe(true);
+ const tail = clip("x".repeat(5000) + "needle end\n");
+ expect(tail.startsWith("…")).toBe(true);
+ expect(tail.endsWith("needle end\n")).toBe(true);
+ expect(tail.length).toBeLessThanOrEqual(CAP + 2);
+ });
+ it("maps byte offsets and keeps surrogate pairs whole", () => {
+ for (const filler of ["é", "😀", "日"]) {
+ const t = filler.repeat(5000) + "needle" + filler.repeat(5000) + "\n";
+ const r = clip(t);
+ expect(r).toContain("needle");
+ expect(r).not.toMatch(lone);
+ expect(r.length).toBeLessThanOrEqual(CAP + 2);
+ }
+ const odd = "a" + "😀".repeat(3000) + "needle" + "😀".repeat(3000);
+ expect(clip(odd)).not.toMatch(lone);
+ });
+ it("keeps the head when submatches are missing or out of range", () => {
+ const t = "x".repeat(5000) + "\n";
+ for (const subs of [undefined, [], [{ start: 99999, end: 100000 }], [{}]]) {
+ const r = clipSnippet(t, subs);
+ expect(r.startsWith("x")).toBe(true);
+ expect(r.endsWith("…")).toBe(true);
+ expect(r.length).toBeLessThanOrEqual(CAP + 1);
+ }
+ });
+ it("caps a match longer than the cap", () => {
+ const t = "z".repeat(50000) + "\n";
+ const r = clipSnippet(t, [{ start: 0, end: 50000 }]);
+ expect(r).toBe("z".repeat(CAP) + "…");
+ });
+});
+
+describe("ix text snippet cap end to end", () => {
+ let log: ReturnType<typeof vi.spyOn>;
+ beforeEach(() => { log = vi.spyOn(console, "log").mockImplementation(() => {}); });
+ afterEach(() => vi.restoreAllMocks());
+ async function run(format: string) {
+ const text = "é".repeat(25000) + "needle" + "y".repeat(25000) + "\n";
+ const line = JSON.stringify({ type: "match", data: {
+ path: { text: "a.ts" }, line_number: 3, lines: { text }, submatches: [{ match: { text: "needle" }, ...sub(text, "needle")[0] }],
+ } });
+ const program = new Command();
+ registerTextCommand(program, async () => ({ stdout: line + "\n" }));
+ await program.parseAsync(["text", "needle", "--format", format], { from: "user" });
+ return log.mock.calls.map((c: unknown[]) => String(c[0])).join("\n");
+ }
+ it("json keeps its shape", async () => {
+ const out = JSON.parse(await run("json"));
+ expect(Object.keys(out[0])).toEqual(["path", "line_start", "line_end", "snippet", "engine", "score", "language"]);
+ expect(out[0].snippet.length).toBeLessThanOrEqual(CAP + 2);
+ expect(out[0].snippet).toContain("needle");
+ });
+ it.each(["text", "llm"])("%s output is bounded", async format => {
+ const out = await run(format);
+ expect(out).toContain("needle");
+ expect(Math.max(...out.split("\n").map((l: string) => l.length))).toBeLessThan(CAP + 200);
+ });
+});
diff --git a/ix-cli/src/cli/commands/text.ts b/ix-cli/src/cli/commands/text.ts
index 7dfd4d9a..c31991ad 100644
--- a/ix-cli/src/cli/commands/text.ts
+++ b/ix-cli/src/cli/commands/text.ts
@@ -12,6 +12,66 @@ import { currentRunSignal } from "../../client/run-signal.js";
type RunRipgrep = (args: string[], limit: number) => Promise<{ stdout: string }>;
+/**
+ * Max characters of context kept in one `ix text` snippet. A single minified
+ * bundle or lockfile line can be tens of KB; one row must never flood the
+ * agent's context. The match itself stays whole (up to this same cap).
+ */
+export const SNIPPET_MAX_CHARS = 200;
+
+/**
+ * Trim a ripgrep line to a window of about `cap` characters around the first
+ * submatch, with `…` on each cut side. Lines at or under the cap are returned
+ * unchanged. `submatches` carry UTF-8 byte offsets (rg JSON), not string indices.
+ * A match longer than the cap keeps its first `cap` characters plus `…`.
+ */
+export function clipSnippet(
+ text: string,
+ submatches?: Array<{ start?: number; end?: number }>,
+ cap = SNIPPET_MAX_CHARS,
+): string {
+ const eol = /\r?\n$/.exec(text)?.[0] ?? "";
+ const body = eol ? text.slice(0, text.length - eol.length) : text;
+ if (body.length <= cap) return text;
+
+ const bytes = Buffer.from(text, "utf8");
+ const toIndex = (n: number) => Math.min(bytes.subarray(0, n).toString("utf8").length, body.length);
+ let start = 0;
+ let end = 0;
+ const m = submatches?.[0];
+ if (
+ m && Number.isInteger(m.start) && Number.isInteger(m.end) &&
+ m.start! >= 0 && m.start! <= m.end! && m.end! <= bytes.length
+ ) {
+ start = toIndex(m.start!);
+ end = Math.max(start, toIndex(m.end!));
+ }
+
+ let left: number;
+ let right: number;
+ if (end - start >= cap) {
+ left = start;
+ right = start + cap;
+ } else {
+ const budget = cap - (end - start);
+ const leftAvail = start;
+ const rightAvail = body.length - end;
+ const half = Math.floor(budget / 2);
+ const l = Math.min(leftAvail, half);
+ const r = Math.min(rightAvail, budget - l);
+ const l2 = Math.min(leftAvail, budget - r);
+ left = start - l2;
+ right = end + r;
+ }
+ // Do not split surrogate pairs.
+ const isLow = (i: number) => { const c = body.charCodeAt(i); return c >= 0xdc00 && c <= 0xdfff; };
+ const isHigh = (i: number) => { const c = body.charCodeAt(i); return c >= 0xd800 && c <= 0xdbff; };
+ if (left > 0 && left < body.length && isLow(left)) left++;
+ if (right < body.length && right > left && isHigh(right - 1)) right--;
+
+ return (left > 0 ? "…" : "") + body.slice(left, right) + (right < body.length ? "…" : eol);
+}
+
async function runRipgrep(args: string[], limit: number): Promise<{ stdout: string }> {
return new Promise((resolve, reject) => {
// Killed when an `ix mcp` tool call that runs it times out (run-signal.ts).
@@ -165,7 +225,7 @@ export function registerTextCommand(program: Command, executeRipgrep: RunRipgrep
path: path.relative(root, absoluteFilePath).split(path.sep).join("/"),
line_start: lineNum,
line_end: lineNum,
- snippet: data.lines?.text ?? "",
+ snippet: clipSnippet(data.lines?.text ?? "", data.submatches),
engine: "ripgrep",
score: 1.0,
language: inferLanguage(filePath),