Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
blame on this site's /mcp
CLI
abso blame src/engine/test/text.test.ts --json
JSON
/christopher/abso-core/blame/src/engine/test/text.test.ts?format=json
237 linesFirst import 98% · pinch 2%Last change pinch in version 78,

237 lines from 2 changes in 2 versions.

init0Start the project1import assert from "node:assert/strict";
2import { describe, it } from "node:test";
3import {
4 canonicalText,
5 diffLines,
6 type Hunk,
7 joinLines,
8 mergeLines,
9 mergeWords,
10 normalizeText,
11 splitLines,
12} from "../index.ts";
13import { Rng } from "./helpers.ts";
15describe("line text", () => {
16 it("normalizes line endings", () => {
17 assert.equal(normalizeText("a\r\nb\rc\n"), "a\nb\nc\n");
18 });
20 it("splits and joins with a trailing newline", () => {
21 assert.deepEqual(splitLines(""), []);
22 assert.deepEqual(splitLines("\n"), [""]);
23 assert.deepEqual(splitLines("a"), ["a"]);
24 assert.deepEqual(splitLines("a\n"), ["a"]);
25 assert.deepEqual(splitLines("a\n\nb\n"), ["a", "", "b"]);
26 assert.equal(joinLines([]), "");
27 assert.equal(joinLines([""]), "\n");
28 assert.equal(joinLines(["a", "b"]), "a\nb\n");
29 assert.equal(canonicalText("a\r\nb"), "a\nb\n");
30 });
31});
33/** Apply hunks to the old lines. */
34function apply(a: readonly string[], hunks: readonly Hunk[]): string[] {
35 const out: string[] = [];
36 let pos = 0;
37 for (const h of hunks) {
38 out.push(...a.slice(pos, h.start), ...h.lines);
39 pos = h.end;
40 }
41 return [...out, ...a.slice(pos)];
44/** LCS length by plain recursion with memo (independent of the engine's table). */
45function lcs(a: readonly string[], b: readonly string[]): number {
46 const memo = new Map<string, number>();
47 const go = (i: number, j: number): number => {
48 if (i === a.length || j === b.length) return 0;
49 const key = `${i},${j}`;
50 const hit = memo.get(key);
51 if (hit !== undefined) return hit;
52 const v = a[i] === b[j] ? 1 + go(i + 1, j + 1) : Math.max(go(i + 1, j), go(i, j + 1));
53 memo.set(key, v);
54 return v;
55 };
56 return go(0, 0);
59describe("diffLines", () => {
60 it("finds a single replaced line", () => {
61 assert.deepEqual(diffLines(["a", "b", "c"], ["a", "X", "c"]), [{ start: 1, end: 2, lines: ["X"] }]);
62 });
64 it("keeps an unchanged line between two changes as two hunks", () => {
65 assert.deepEqual(diffLines(["a", "b", "c"], ["X", "b", "Y"]), [
66 { start: 0, end: 1, lines: ["X"] },
67 { start: 2, end: 3, lines: ["Y"] },
68 ]);
69 });
71 it("reports pure insertions and pure deletions", () => {
72 assert.deepEqual(diffLines(["a", "c"], ["a", "b", "c"]), [{ start: 1, end: 1, lines: ["b"] }]);
73 assert.deepEqual(diffLines(["a", "b", "c"], ["a", "c"]), [{ start: 1, end: 2, lines: [] }]);
74 assert.deepEqual(diffLines([], ["x"]), [{ start: 0, end: 0, lines: ["x"] }]);
75 assert.deepEqual(diffLines(["x"], []), [{ start: 0, end: 1, lines: [] }]);
76 assert.deepEqual(diffLines(["x"], ["x"]), []);
77 });
79 it("random inputs: hunks are ordered, disjoint, rebuild the new lines, and keep a longest common subsequence", () => {
80 for (let seed = 1; seed <= 3000; seed++) {
81 const rng = new Rng(seed);
82 const alphabet = ["a", "b", "c", "d", "", "e", "f", "g"].slice(0, rng.range(1, 8));
83 const size = seed <= 1500 ? 9 : 40;
84 const a = Array.from({ length: rng.int(size) }, () => rng.pick(alphabet));
85 const b = Array.from({ length: rng.int(size) }, () => rng.pick(alphabet));
86 const hunks = diffLines(a, b);
87 const where = `seed ${seed}: ${JSON.stringify(a)} -> ${JSON.stringify(b)}`;
88 assert.deepEqual(apply(a, hunks), b, where);
89 let pos = 0;
90 let kept = a.length;
91 for (const h of hunks) {
92 assert.ok(h.start >= pos && h.end >= h.start, where);
93 assert.ok(h.end > h.start || h.lines.length > 0, `empty hunk at ${where}`);
94 pos = h.end;
95 kept -= h.end - h.start;
96 }
97 assert.equal(kept, lcs(a, b), `not minimal at ${where}`);
98 }
99 });
101 it("stays minimal at any size: four small changes to 2100 lines are four hunks", () => {
102 const a = Array.from({ length: 2100 }, (_, i) => `line ${i}`);
103 const b = [...a];
104 b[0] = "FIRST";
105 b[1500] = "MIDDLE";
106 b[2099] = "LAST";
107 b.splice(700, 0, "inserted");
108 assert.deepEqual(diffLines(a, b), [
109 { start: 0, end: 1, lines: ["FIRST"] },
110 { start: 700, end: 700, lines: ["inserted"] },
111 { start: 1500, end: 1501, lines: ["MIDDLE"] },
112 { start: 2099, end: 2100, lines: ["LAST"] },
113 ]);
114 // Wholly different texts are one hunk, found at once.
115 assert.deepEqual(
116 diffLines(
117 a,
pinch78Biome is silent: about 90 hints cleared. String joins as templates, dotted keys, unused imports, variables and a private method removed, optional chains (one kept boolean with === true), the preset field instead of the deprecated recommended. Two rules off where they don't fit: noExplicitAny in the hook modules, whose engine types come from the host, and noTemplateCurlyInString in tests, which hold source text as data.Compare118 a.map((s) => `${s}!`),
init0Start the project119 ),
pinch78Biome is silent: about 90 hints cleared. String joins as templates, dotted keys, unused imports, variables and a private method removed, optional chains (one kept boolean with === true), the preset field instead of the deprecated recommended. Two rules off where they don't fit: noExplicitAny in the hook modules, whose engine types come from the host, and noTemplateCurlyInString in tests, which hold source text as data.Compare120 [{ start: 0, end: 2100, lines: a.map((s) => `${s}!`) }],
init0Start the project121 );
122 });
124 it("stays minimal past the cost cap: 2,091 scattered changes and 622 inserts in 23,000 lines", () => {
125 const a = Array.from({ length: 23000 }, (_, i) => `line ${i}`);
126 const b = [...a];
127 let changed = 0;
128 for (let i = 0; i < b.length; i += 11, changed++) b[i] = `changed ${i}`;
129 for (let i = b.length; i > 0; i -= 37) b.splice(i, 0, `new ${i}`);
130 const hunks = diffLines(a, b);
131 assert.deepEqual(apply(a, hunks), b);
132 assert.equal(a.length - hunks.reduce((n, h) => n + h.end - h.start, 0), a.length - changed);
133 });
135 it("a file reordered through is close to minimal and quick, not its length squared (abso issue 158)", () => {
136 const a = Array.from({ length: 23000 }, (_, i) => `line ${i}`);
137 const b = [...a].reverse();
138 const t0 = performance.now();
139 const hunks = diffLines(a, b);
140 assert.ok(performance.now() - t0 < 2000, "under 2 s (minimal Myers took about 10 s)");
141 assert.deepEqual(apply(a, hunks), b);
142 });
143});
145describe("mergeLines", () => {
146 const m = (b: string, o: string, t: string) => mergeLines(b.split(" "), o.split(" "), t.split(" "));
147 it("takes one-sided changes from either side", () => {
148 assert.deepEqual(m("a b c d", "a B c d", "a b c D"), {
149 lines: ["a", "B", "c", "D"],
150 conflicts: 0,
151 resolved: [],
152 conflictsAt: [],
153 });
154 });
155 it("takes identical changes on both sides once", () => {
156 assert.deepEqual(m("a b c d e", "a X c d E", "a X c d e"), {
157 lines: ["a", "X", "c", "d", "E"],
158 conflicts: 0,
159 resolved: [],
160 conflictsAt: [],
161 });
162 assert.deepEqual(m("a b", "a n b", "a n b"), {
163 lines: ["a", "n", "b"],
164 conflicts: 0,
165 resolved: [],
166 conflictsAt: [],
167 });
168 });
169 it("counts differing or touching changes as conflicts", () => {
170 assert.equal(m("a b c", "a X c", "a Y c").conflicts, 1);
171 assert.equal(m("a b c d", "a X c d", "a b Y d").conflicts, 1);
172 assert.equal(m("a b", "a x b", "a y b").conflicts, 1);
173 });
174 it("hands a conflict to the caller with where each side starts, and writes what it returns (#11)", () => {
175 const seen: unknown[] = [];
176 const got = mergeLines("a b c d".split(" "), "a n b X d".split(" "), "a b Y d".split(" "), undefined, (c) => {
177 seen.push(c);
178 return ["<", ...c.ours, "|", ...c.base, "=", ...c.theirs, ">"];
179 });
180 assert.deepEqual(seen, [{ base: ["c"], ours: ["X"], theirs: ["Y"], baseAt: 2, oursAt: 3, theirsAt: 2 }]);
181 assert.deepEqual(got, {
182 lines: ["a", "n", "b", "<", "X", "|", "c", "=", "Y", ">", "d"],
183 conflicts: 1,
184 resolved: [],
185 conflictsAt: [{ at: 3, length: 7 }],
186 });
187 });
188 it("agrees with taking every change when nothing overlaps (random)", () => {
189 for (let seed = 0; seed < 300; seed++) {
190 let s = seed * 7919 + 1;
191 const rnd = (n: number) => (s = (s * 1103515245 + 12345) % 2147483648) % n;
192 const base = Array.from({ length: 6 + rnd(10) }, (_, k) => `l${k}`);
193 // ours edits the first half, theirs the second, with a gap between.
194 const cut = Math.floor(base.length / 2);
pinch78Biome is silent: about 90 hints cleared. String joins as templates, dotted keys, unused imports, variables and a private method removed, optional chains (one kept boolean with === true), the preset field instead of the deprecated recommended. Two rules off where they don't fit: noExplicitAny in the hook modules, whose engine types come from the host, and noTemplateCurlyInString in tests, which hold source text as data.Compare195 const ours = base.map((l, k) => (k < cut - 1 && rnd(3) === 0 ? `${l}o` : l));
196 const theirs = base.map((l, k) => (k > cut && rnd(3) === 0 ? `${l}t` : l));
init0Start the project197 const expected = base.map((l, k) => (ours[k] !== l ? ours[k] : theirs[k]));
198 const got = mergeLines(base, ours, theirs);
199 if (got.conflicts === 0) assert.deepEqual(got.lines, expected, `seed ${seed}`);
200 // Adjacent edits from both sides may touch and conflict; nothing else may.
201 else
202 assert.ok(
203 ours.some((l, k) => l !== base[k] && (theirs[k + 1] !== base[k + 1] || theirs[k - 1] !== base[k - 1])),
204 `seed ${seed}`,
205 );
206 }
207 });
208});
210describe("mergeWords", () => {
211 it("keeps items both sides added to the same list on one line, theirs first", () => {
212 assert.equal(
213 mergeWords("const S = [a, b, c];", "const S = [a, b, c, d];", "const S = [a, b, c, e];"),
214 "const S = [a, b, c, e, d];",
215 );
216 assert.equal(
217 mergeWords('import { a } from "x";', 'import { a, b } from "x";', 'import { a, c } from "x";'),
218 'import { a, c, b } from "x";',
219 );
220 assert.equal(
221 mergeWords("const o = { a: 1 };", "const o = { a: 1, b: 2 };", "const o = { a: 1, c: [3] };"),
222 "const o = { a: 1, c: [3], b: 2 };",
223 );
224 });
225 it("takes one-sided and identical word changes", () => {
226 assert.equal(
227 mergeWords("x = [a, b]; y = 1;", "x = [a, b, c]; y = 1;", "x = [a, b]; y = 2;"),
228 "x = [a, b, c]; y = 2;",
229 );
230 assert.equal(mergeWords("[a]", "[a, b]", "[a, b]"), "[a, b]");
231 });
232 it("is no merge for call arguments, method chains, or overlapping changes", () => {
233 assert.equal(mergeWords("f(a);", "f(a, x);", "f(a, y);"), undefined);
234 assert.equal(mergeWords("return h2;", "return h2.toLowerCase();", "return h2.trim();"), undefined);
235 assert.equal(mergeWords("[a, b]", "[a, X]", "[a, Y]"), undefined);
236 });
237});