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
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/worker/project/trail.ts?version=295&format=json
353 lineswhytrail 91% · capacity 9%Last change capacity in version 242, 3 versions changed it

You're reading version 295. The newest is 318, and no version since then changed this file. Go to the newestCompare with 318

1// A line's earlier changes, for why (abso-core issue 20). A line's id names
2// the change that wrote it, so a line that was rewritten (reformatted,
3// renamed, edited) is a new line, and the one it replaced is a deleted line
4// in the same file. The file's full sequence keeps deleted lines where they
5// were, so the lines a change deleted and the lines it wrote sit together:
6// that's one hunk, and the line it replaced is the one it pairs with there.
7// Following those pairs back gives the line's changes, newest first. A
8// change that only touched formatting (whitespace, line wrapping, quotes,
9// trailing commas and semicolons, parentheses around one arrow parameter)
10// is marked, so why can skip past it to the change that said what the line
11// does. So is a move: code a push took out of one place and wrote, the same,
12// in another (a file split in two), which the trail follows into the file it
13// came from.
15import {
16 type Atom,
17 type AtomId,
18 type Graph,
19 type LineId,
20 type ReadView,
21 type SeqLine,
22 seqOf,
23} from "../../src/engine/index.ts";
25/** One change in a line's past, newest first. */
26export interface TrailStep {
27 /** The change that wrote the line. */
28 readonly atom: AtomId;
29 /** The line it wrote, and its text then. */
30 readonly line: LineId;
31 readonly text: string;
32 /** It only changed formatting from the line it replaced. */
33 readonly formatting: boolean;
34 /** The line it replaced, when it replaced one. */
35 readonly replaced?: LineId;
36 /**
37 * The change may have moved the line: the line it replaced was found
38 * elsewhere, or was written in another file. Which file it was in then
39 * takes the versions before and after (blame.ts).
40 */
41 readonly maybeMoved?: true;
44/** At most this many steps back. */
45export const TRAIL_MAX = 50;
47/**
48 * Text with formatting taken out, for comparing two versions of the same
49 * code: no whitespace, one kind of quote, no trailing commas before a
50 * closing bracket, no semicolons at line ends (or before a comment there), and no parentheses around a
51 * lone arrow parameter. Lines are normalized then joined, so a statement
52 * wrapped onto three lines matches it on one.
53 */
54export function normalize(lines: readonly string[]): string {
55 return lines
56 .map((l) => l.replace(/;\s*(\/\/.*)?$/, "$1"))
57 .join("")
58 .replace(/\s+/g, "")
59 .replace(/['`]/g, '"')
60 .replace(/,(?=[)\]}]|$)/g, "")
61 .replace(/\(([A-Za-z_$][\w$]*)\)=>/g, "$1=>");
64/** Whether two runs of lines are the same code, formatted differently (or not at all). */
65export function sameCode(before: readonly string[], after: readonly string[]): boolean {
66 return normalize(before) === normalize(after);
69/** Similarity of two strings, 0 to 1: shared character pairs (Dice). */
70function similarity(a: string, b: string): number {
71 if (a === b) return 1;
72 if (a.length < 2 || b.length < 2) return 0;
73 const pairs = new Map<string, number>();
74 for (let i = 0; i < a.length - 1; i++) {
75 const p = a.slice(i, i + 2);
76 pairs.set(p, (pairs.get(p) ?? 0) + 1);
77 }
78 let shared = 0;
79 for (let i = 0; i < b.length - 1; i++) {
80 const p = b.slice(i, i + 2);
81 const n = pairs.get(p) ?? 0;
82 if (n > 0) {
83 shared++;
84 pairs.set(p, n - 1);
85 }
86 }
87 return (2 * shared) / (a.length + b.length - 2);
90/** Below this, a rewritten line isn't taken for the one it replaced: it was new. */
91const SIMILAR = 0.4;
93/**
94 * For a run that's the same code reformatted: which old line each new line
95 * came from, by where its characters fall in the joined, normalized text
96 * (the old line it overlaps most).
97 */
98function byCharacters(before: readonly string[], after: readonly string[], at: number): number | undefined {
99 const spans = (lines: readonly string[]) => {
100 let from = 0;
101 return lines.map((l) => {
102 const n = normalize([l]).length;
103 const span = [from, from + n] as const;
104 from += n;
105 return span;
106 });
107 };
108 const [from, to] = spans(after)[at]!;
109 let best: number | undefined;
110 let most = 0;
111 for (const [i, [a, b]] of spans(before).entries()) {
112 const overlap = Math.min(to, b) - Math.max(from, a);
113 if (overlap > most) [best, most] = [i, overlap];
114 }
115 return best;
118/** Longest common subsequence of two lists of keys: matched index pairs, in order. */
119function common(a: readonly string[], b: readonly string[]): [number, number][] {
120 const n = a.length;
121 const m = b.length;
122 // Hunks are small; a full table is fine, but cap it so a whole-file rewrite stays cheap.
123 if (n * m > 4_000_000) return [];
124 const t: Uint32Array[] = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
125 for (let i = n - 1; i >= 0; i--)
126 for (let j = m - 1; j >= 0; j--)
127 t[i]![j] = a[i] === b[j] ? t[i + 1]![j + 1]! + 1 : Math.max(t[i + 1]![j]!, t[i]![j + 1]!);
128 const out: [number, number][] = [];
129 let i = 0;
130 let j = 0;
131 while (i < n && j < m) {
132 if (a[i] === b[j]) {
133 out.push([i, j]);
134 i++;
135 j++;
136 } else if (t[i + 1]![j]! >= t[i]![j + 1]!) i++;
137 else j++;
138 }
139 return out;
142/**
143 * In one hunk, the old line a new one replaced, and whether that was only
144 * formatting. Lines whose normalized text matches pair first; between those,
145 * a run that's the same code rewrapped pairs by its characters; anything
146 * else pairs with the most similar old line, if one is similar enough.
147 */
148export function pairIn(
149 before: readonly string[],
150 after: readonly string[],
151 at: number,
152): { index: number; formatting: boolean } | undefined {
153 if (before.length === 0) return undefined;
154 if (sameCode(before, after)) {
155 const index = byCharacters(before, after, at);
156 return index === undefined ? undefined : { index, formatting: true };
157 }
158 const keys = (lines: readonly string[]) => lines.map((l) => normalize([l]));
159 const a = keys(before);
160 const b = keys(after);
161 const anchors = common(a, b);
162 const hit = anchors.find(([, j]) => j === at);
163 if (hit && a[hit[0]] !== "") return { index: hit[0], formatting: true };
164 // The gap between anchors that holds the new line.
165 let [i0, j0] = [0, 0];
166 let [i1, j1] = [before.length, after.length];
167 for (const [i, j] of anchors) {
168 if (j < at) [i0, j0] = [i + 1, j + 1];
169 else if (j > at) {
170 [i1, j1] = [i, j];
171 break;
172 }
173 }
174 const gapBefore = before.slice(i0, i1);
175 const gapAfter = after.slice(j0, j1);
176 if (gapBefore.length === 0) return undefined;
177 if (sameCode(gapBefore, gapAfter)) {
178 const index = byCharacters(gapBefore, gapAfter, at - j0);
179 return index === undefined ? undefined : { index: i0 + index, formatting: true };
180 }
181 let best: number | undefined;
182 let most = SIMILAR;
183 for (let i = i0; i < i1; i++) {
184 const s = similarity(a[i]!, b[at]!);
185 if (s >= most) [best, most] = [i, s];
186 }
187 return best === undefined ? undefined : { index: best, formatting: false };
190/**
191 * The line's changes, newest first: the change that wrote it, then the one
192 * that wrote the line it replaced, and so on back to a change that wrote it
193 * new. A line written new where the same push deleted the same code
194 * elsewhere (code moved to another file, or within one) follows that line
195 * on; `samePush` says which changes were pushed together. At most `max`
196 * steps; `more` says the trail went on.
197 */
198export function trail(
199 graph: Graph,
200 view: ReadView,
201 file: string,
202 line: LineId,
203 max = TRAIL_MAX,
204 samePush: (a: Atom, b: Atom) => boolean = (a, b) => a.id === b.id,
205 pushmates?: (atom: Atom) => Iterable<AtomId> | undefined,
206): { steps: TrailStep[]; more: boolean } {
207 const files = new Map<string, { seq: readonly SeqLine[]; index: Map<LineId, number> }>();
208 const sequenceOf = (path: string) => {
209 let f = files.get(path);
210 if (!f) {
211 const seq = view.sequence(path);
212 f = { seq, index: new Map(seq.map((s, i) => [s.id, i])) };
213 files.set(path, f);
214 }
215 return f;
216 };
217 const steps: TrailStep[] = [];
218 let current: LineId | undefined = line;
219 let hint = file;
220 while (current !== undefined && steps.length < max) {
221 // The file to read its hunk in: where the view has it, or where it was written, whichever pairs it.
222 const id: LineId = current;
223 let found: { seq: readonly SeqLine[]; at: number; hunk: { before: number[]; after: number[] } } | undefined;
224 let pair: ReturnType<typeof pairIn>;
225 for (const path of new Set([hint, fileIn(view, id), graph.lineFile(id)])) {
226 if (path === undefined) continue;
227 const { seq, index } = sequenceOf(path);
228 const at = index.get(id);
229 if (at === undefined) continue;
230 const hunk = hunkOf(seq, at, graph.atom(seq[at]!.atom));
231 const p = pairIn(
232 hunk.before.map((i) => seq[i]!.text),
233 hunk.after.map((i) => seq[i]!.text),
234 hunk.after.indexOf(at),
235 );
236 if (!found || p) [found, pair] = [{ seq, at, hunk }, p];
237 if (p) break;
238 }
239 if (!found) break;
240 const { seq, at, hunk } = found;
241 const atom = graph.atom(seq[at]!.atom);
242 let replaced = pair ? seq[hunk.before[pair.index]!]!.id : undefined;
243 let formatting = pair?.formatting ?? false;
244 let searched = false;
245 if (replaced === undefined) {
246 const moved = movedFrom(
247 graph,
248 view,
249 atom,
250 seq[at]!.text,
251 new Set(hunk.before.map((i) => seq[i]!.id)),
252 samePush,
253 pushmates,
254 );
255 if (moved) [replaced, formatting, searched] = [moved, true, true];
256 }
257 const maybeMoved = searched || (replaced !== undefined && graph.lineFile(replaced) !== graph.lineFile(id));
258 steps.push({
259 atom: atom.id,
260 line: id,
261 text: seq[at]!.text,
262 formatting,
263 ...(replaced !== undefined ? { replaced } : {}),
264 ...(maybeMoved ? { maybeMoved: true as const } : {}),
265 });
266 hint = replaced === undefined ? hint : (fileIn(view, replaced) ?? hint);
267 current = replaced;
268 }
269 return { steps, more: current !== undefined };
272/** The file a line is in, in a view, or undefined when the view can't place it. */
273function fileIn(view: ReadView, line: LineId): string | undefined {
274 try {
275 return view.fileOf(line);
276 } catch {
277 return undefined;
278 }
281/** How far either side of a change to look for the others pushed with it. */
282const NEAR = 5000;
284/**
285 * Where a line written new came from, when it was moved: a line with the same
286 * code (exactly, else formatted differently) that a change pushed with this
287 * one deleted, if exactly one such line has the best match. Short lines
288 * (a brace, a blank) match too much to follow.
289 */
290function movedFrom(
291 graph: Graph,
292 view: ReadView,
293 atom: Atom,
294 text: string,
295 skip: ReadonlySet<LineId>,
296 samePush: (a: Atom, b: Atom) => boolean,
297 pushmates?: (atom: Atom) => Iterable<AtomId> | undefined,
298): LineId | undefined {
299 const want = normalize([text]);
300 if (want.length < 12) return undefined;
301 const all = graph.atoms();
302 const exact: LineId[] = [];
303 const same: LineId[] = [];
304 // Only atoms pushed with this one can count (samePush), so where the caller can list them, those are the candidates
305 // (abso Capacity): reading every atom within NEAR of it was 10,000 atom reads a step on abso. Otherwise, every atom
306 // near by, as before.
307 const mates = pushmates?.(atom);
308 const near = (s: number) => s >= atom.seq - NEAR && s <= atom.seq + NEAR;
309 const candidates: Iterable<Atom> = mates
310 ? [...mates].filter((id) => near(seqOf(id))).map((id) => graph.atom(id))
311 : (function* () {
312 for (let s = Math.max(0, atom.seq - NEAR); s <= Math.min(all.length - 1, atom.seq + NEAR); s++) yield all[s]!;
313 })();
314 for (const other of candidates) {
315 if (other.author !== atom.author || !view.set.has(other.id) || !samePush(other, atom)) continue;
316 for (const d of other.deletes) {
317 if (skip.has(d)) continue;
318 const t = graph.lineText(d);
319 if (t === undefined) continue;
320 if (t === text) exact.push(d);
321 else if (normalize([t]) === want) same.push(d);
322 }
323 }
324 const found = exact.length > 0 ? exact : same;
325 return found.length === 1 ? found[0] : undefined;
328/**
329 * The hunk a change made around one of its lines, as indexes into the
330 * sequence in file order: the lines it deleted there and the lines it wrote.
331 * Lines nobody could see when it was made (written later, or already
332 * deleted) are passed over; a line it left alone ends the hunk.
333 */
334function hunkOf(seq: readonly SeqLine[], at: number, atom: Atom): { before: number[]; after: number[] } {
335 const role = (s: SeqLine): "wrote" | "deleted" | "unseen" | "kept" => {
336 if (s.atom === atom.id) return "wrote";
337 if (seqOf(s.atom) > atom.seq) return "unseen";
338 if (s.deletedBy.some((d) => d !== atom.id && seqOf(d) < atom.seq)) return "unseen";
339 return s.deletedBy.includes(atom.id) ? "deleted" : "kept";
340 };
341 let first = at;
342 while (first > 0 && role(seq[first - 1]!) !== "kept") first--;
343 let last = at;
344 while (last < seq.length - 1 && role(seq[last + 1]!) !== "kept") last++;
345 const before: number[] = [];
346 const after: number[] = [];
347 for (let i = first; i <= last; i++) {
348 const r = role(seq[i]!);
349 if (r === "deleted") before.push(i);
350 else if (r === "wrote") after.push(i);
351 }
352 return { before, after };