- MCP
- blame on this site's /mcp
- CLI
- abso blame src/engine/test/gen.ts --json
- JSON
- /christopher/abso-core/blame/src/engine/test/gen.ts?format=json
318 linesFirst import 99% · pinch 1%Last change pinch in version 78,
318 lines from 2 changes in 2 versions.
init0Start the project1// Random edit generation for property tests. Everything is driven by a seeded
2// Rng; a failing case is reproduced by its seed alone.
4import { canonicalText, type EditInput, type LineRange, type Mode, splitLines, type View } from "../index.ts";
5import type { Rng } from "./helpers.ts";
7/** path -> visible lines. The plain-text model the engine is checked against. */
8export type Files = Map<string, string[]>;
10export function filesFromView(view: View): Files {
11 const out: Files = new Map();
12 for (const path of view.paths())
13 out.set(
14 path,
15 view.lines(path).map((l) => l.text),
16 );
17 return out;
18}
20export function filesToRecord(files: Files): Record<string, string> {
21 const out: Record<string, string> = {};
22 for (const path of [...files.keys()].sort()) {
23 const lines = files.get(path)!;
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.Compare24 if (lines.length > 0) out[path] = `${lines.join("\n")}\n`;
26 return out;
27}
29function textOf(lines: readonly string[]): string {
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.Compare30 return lines.length === 0 ? "" : `${lines.join("\n")}\n`;
33function occurrences(text: string, needle: string): number {
34 let count = 0;
35 for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + 1)) count++;
36 return count;
37}
39/** One generated atom's worth of edits, plus what it does to plain text. */
40export interface GenEdit {
41 readonly edits: EditInput[];
42 readonly describe: string;
43 /** Apply to plain text (returns a new map). */
44 readonly apply: (files: Files) => Files;
45}
47export interface GenOptions {
48 /** Use a small alphabet so lines repeat (exercises unique matching and LCS). */
49 readonly duplicates: boolean;
50 /** Allow wide mode. */
51 readonly wide: boolean;
52}
54/** Splice regions on one file, applied simultaneously in (start, end, order) order. */
55export interface SpliceRegion {
56 readonly start: number;
57 readonly end: number;
58 readonly lines: readonly string[];
59}
61export function applySplices(lines: readonly string[], regions: readonly SpliceRegion[]): string[] {
62 const sorted = regions
63 .map((r, order) => ({ ...r, order }))
64 .sort((a, b) => a.start - b.start || a.end - b.end || a.order - b.order);
65 const out: string[] = [];
66 let pos = 0;
67 for (const r of sorted) {
68 if (r.start < pos) throw new Error("overlapping splice regions in generator");
69 out.push(...lines.slice(pos, r.start), ...r.lines);
70 pos = r.end;
71 }
72 out.push(...lines.slice(pos));
73 return out;
74}
76export class EditGen {
77 readonly rng: Rng;
78 readonly opts: GenOptions;
79 #token = 0;
80 #deletedPaths: string[] = [];
81 #fileCounter = 0;
83 constructor(rng: Rng, opts: GenOptions) {
84 this.rng = rng;
85 this.opts = opts;
86 }
88 fresh(): string {
89 return `t${this.#token++}`;
90 }
92 line(): string {
93 if (this.opts.duplicates && this.rng.chance(0.6)) {
94 return this.rng.pick(["a", "b", "c", "", "{", "}", " x", "y y", "a b"]);
95 }
96 return this.fresh();
97 }
99 newLines(min: number, max: number): string[] {
100 const n = this.rng.range(min, max);
101 return Array.from({ length: n }, () => this.line());
102 }
104 mode(): Mode {
105 const modes: Mode[] = this.opts.wide ? ["both", "after", "before", "wide"] : ["both", "after", "before"];
106 return this.rng.pick(modes);
107 }
109 initialFiles(): Files {
110 const files: Files = new Map();
111 const count = this.rng.range(1, 3);
112 for (let i = 0; i < count; i++) {
113 const path = this.rng.chance(0.3) ? `dir/f${i}.txt` : `f${i}.txt`;
114 const lines = this.newLines(0, 8);
115 if (lines.length > 0) files.set(path, lines);
116 }
117 if (files.size === 0) files.set("f0.txt", this.newLines(1, 4));
118 return files;
119 }
121 /** Gaps p (0..n) that have tombstones between visible line p-1 and p. */
122 static tombstoneGaps(view: View | undefined, path: string): number[] {
123 if (!view) return [];
124 const gaps = new Set<number>();
125 let seen = 0;
126 for (const line of view.sequence(path)) {
127 if (line.visible) seen++;
128 else gaps.add(seen);
129 }
130 return [...gaps];
131 }
133 /** A gap position, biased toward gaps with tombstones. */
134 gap(n: number, tombs: readonly number[]): number {
135 if (tombs.length > 0 && this.rng.chance(0.5)) return Math.min(this.rng.pick(tombs), n);
136 return this.rng.int(n + 1);
137 }
139 /** A non-empty range [i, j), biased to start or end next to a tombstone. */
140 range(n: number, tombs: readonly number[]): [number, number] {
141 let i: number;
142 if (tombs.length > 0 && this.rng.chance(0.5)) {
143 const g = Math.min(this.rng.pick(tombs), n);
144 i = this.rng.chance(0.5) && g > 0 ? g - 1 : Math.min(g, n - 1);
145 } else {
146 i = this.rng.int(n);
147 }
148 const j = this.rng.range(i + 1, Math.min(n, i + 4));
149 return [i, j];
150 }
152 /**
153 * A text edit replacing lines [start, end) with `lines`, with enough context
154 * that `old` matches exactly once.
155 */
156 textEdit(
157 path: string,
158 all: readonly string[],
159 start: number,
160 end: number,
161 lines: readonly string[],
162 mode: Mode,
163 ): EditInput {
164 let a = start;
165 let b = end;
166 if (a === b) {
167 if (a > 0 && (b === all.length || this.rng.chance(0.5))) a--;
168 else b++;
169 }
170 const text = textOf(all);
171 while (occurrences(text, textOf(all.slice(a, b))) !== 1) {
172 if (a > 0 && (b === all.length || this.rng.chance(0.5))) a--;
173 else b++;
174 }
175 return {
176 file: path,
177 old: textOf(all.slice(a, b)),
178 new: textOf([...all.slice(a, start), ...lines, ...all.slice(end, b)]),
179 mode,
180 };
181 }
183 /** One random atom's edits against `files` (the plain model of `view`). */
184 next(files: Files, view?: View): GenEdit | undefined {
185 const paths = [...files.keys()].filter((p) => files.get(p)!.length > 0).sort();
186 const roll = this.rng.int(100);
187 if (paths.length === 0 || roll < 8) return this.create(files);
188 const path = this.rng.pick(paths);
189 const lines = files.get(path)!;
190 const n = lines.length;
191 const tombs = EditGen.tombstoneGaps(view, path);
192 const mode = this.mode();
193 const useText = this.rng.chance(0.5);
194 const spliceTo = (start: number, end: number, add: readonly string[], what: string): GenEdit => ({
195 edits: [
196 useText ? this.textEdit(path, lines, start, end, add, mode) : { file: path, start, end, lines: add, mode },
197 ],
198 describe: `${what} ${path}[${start},${end}) -> ${JSON.stringify(add)} mode=${mode}${useText ? " (text)" : " (splice)"}`,
199 apply: (fs) => replaceFile(fs, path, applySplices(fs.get(path) ?? [], [{ start, end, lines: add }])),
200 });
202 if (roll < 30) {
203 const p = this.gap(n, tombs);
204 return spliceTo(p, p, this.newLines(1, 4), "insert");
205 }
206 if (roll < 50) {
207 const [i, j] = this.range(n, tombs);
208 return spliceTo(i, j, this.newLines(1, 4), "replace");
209 }
210 if (roll < 62) {
211 const [i, j] = this.range(n, tombs);
212 return spliceTo(i, j, [], "delete");
213 }
214 if (roll < 77) return this.partial(path, lines, mode);
215 if (roll < 82) {
216 const all = textOf(lines);
217 return {
218 edits: [{ file: path, old: all, new: "", mode }],
219 describe: `delete-file ${path}`,
220 apply: (fs) => {
221 this.#deletedPaths.push(path);
222 return replaceFile(fs, path, []);
223 },
224 };
225 }
226 return this.multi(files, paths);
227 }
229 create(files: Files): GenEdit {
230 const reuse = this.#deletedPaths.filter((p) => (files.get(p) ?? []).length === 0);
231 const path = reuse.length > 0 && this.rng.chance(0.6) ? this.rng.pick(reuse) : `new${this.#fileCounter++}.txt`;
232 const lines = this.newLines(1, 5);
233 return {
234 edits: [{ file: path, old: "", new: textOf(lines) }],
235 describe: `create ${path} ${JSON.stringify(lines)}`,
236 apply: (fs) => replaceFile(fs, path, lines),
237 };
238 }
240 /** Replace part of a line (maybe running into the next line) with text that may add or remove line breaks. */
241 partial(path: string, lines: readonly string[], mode: Mode): GenEdit | undefined {
242 const candidates = lines.map((t, i) => (t.length > 0 ? i : -1)).filter((i) => i >= 0);
243 if (candidates.length === 0) return undefined;
244 const i = this.rng.pick(candidates);
245 const t = lines[i]!;
246 const c1 = this.rng.int(t.length);
247 let old = t.slice(c1, this.rng.range(c1 + 1, t.length));
248 if (this.rng.chance(0.3) && i + 1 < lines.length) {
249 const next = lines[i + 1]!;
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.Compare250 old = `${t.slice(c1)}\n${next.slice(0, this.rng.int(next.length + 1))}`;
252 const replacement = this.rng.pick(["", "Z", "q\nr", "\n", "w\n", "yy", "Z\nZ", this.fresh()]);
253 const text = textOf(lines);
254 if (occurrences(text, old) !== 1 || old === replacement) return undefined;
255 const at = text.indexOf(old);
256 return {
257 edits: [{ file: path, old, new: replacement, mode }],
258 describe: `partial ${path} ${JSON.stringify(old)} -> ${JSON.stringify(replacement)} mode=${mode}`,
259 apply: (fs) => {
260 const cur = textOf(fs.get(path) ?? []);
261 const next = canonicalText(cur.slice(0, at) + replacement + cur.slice(at + old.length));
262 return replaceFile(fs, path, splitLines(next));
263 },
264 };
265 }
267 /** Two or three splices in one atom, across one or two files. */
268 multi(files: Files, paths: readonly string[]): GenEdit {
269 const chosen =
270 this.rng.chance(0.5) && paths.length > 1 ? this.rng.shuffle(paths).slice(0, 2) : [this.rng.pick(paths)];
271 const edits: EditInput[] = [];
272 const perFile = new Map<string, SpliceRegion[]>();
273 for (const path of chosen) {
274 const n = files.get(path)!.length;
275 const count = chosen.length === 1 ? this.rng.range(2, 3) : this.rng.range(1, 2);
276 const cuts = Array.from({ length: count * 2 }, () => this.rng.int(n + 1)).sort((a, b) => a - b);
277 const regions: SpliceRegion[] = [];
278 for (let r = 0; r < count; r++) {
279 const start = cuts[2 * r]!;
280 const end = cuts[2 * r + 1]!;
281 const add = this.newLines(start === end ? 1 : 0, 3);
282 regions.push({ start, end, lines: add });
283 edits.push({ file: path, start, end, lines: add, mode: this.mode() });
284 }
285 perFile.set(path, regions);
286 }
287 return {
288 edits,
289 describe: `multi ${[...perFile].map(([p, rs]) => `${p}:${rs.map((r) => `[${r.start},${r.end})->${JSON.stringify(r.lines)}`).join(",")}`).join(" ")}`,
290 apply: (fs) => {
291 let out = fs;
292 for (const [path, regions] of perFile) out = replaceFile(out, path, applySplices(out.get(path) ?? [], regions));
293 return out;
294 },
295 };
296 }
298 /** A random non-empty range of some file, for reliesOn. */
299 reliance(files: Files): LineRange | undefined {
300 const paths = [...files.keys()].filter((p) => files.get(p)!.length > 0);
301 if (paths.length === 0) return undefined;
302 const path = this.rng.pick(paths);
303 const n = files.get(path)!.length;
304 const start = this.rng.int(n);
305 return { file: path, start, end: this.rng.range(start + 1, Math.min(n, start + 3)) };
306 }
307}
309function replaceFile(files: Files, path: string, lines: string[]): Files {
310 const out: Files = new Map(files);
311 if (lines.length === 0) out.delete(path);
312 else out.set(path, lines);
313 return out;
314}
316export function sameFiles(a: Files, b: Files): boolean {
317 return JSON.stringify(filesToRecord(a)) === JSON.stringify(filesToRecord(b));
318}