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/src/engine/build.ts?version=5&format=json
520 linesFirst import 100%Last change First import in version 0, 1 version changed it

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

1// Building an atom from an edit against a view. Agents say "replace this exact
2// text with that text" (or "replace these visible lines with these lines");
3// the engine turns it into deletes, inserts, claim keys and derived deps.
4
5import { Graph } from "./graph.ts";
6import { attrKey, gapKey, isStartNode, lineKey, parseKey, posKey, startNode, writerOf } from "./keys.ts";
7import { diffLines, joinLines, normalizeText, splitLines } from "./text.ts";
8import {
9 ATTR_NAMES,
10 type Atom,
11 type AtomId,
12 type AttrSet,
13 EngineError,
14 type InsertRun,
15 type Key,
16 type LineId,
17 MODES,
18 type Mode,
19 type NodeId,
20 REASON_KINDS,
21 type Reason,
22 type Relocation,
23} from "./types.ts";
24import { View } from "./view.ts";
26/** Replace the one exact occurrence of `old` in `file` with `new`. */
27export interface TextEdit {
28 readonly file: string;
29 readonly old: string;
30 readonly new: string;
31 readonly mode?: Mode;
34/**
35 * Replace visible lines [start, end) of `file` (0-based) with `lines`. With
36 * start === end it is a pure insertion before line `start`. This is the form
37 * a git hunk maps onto.
38 */
39export interface SpliceEdit {
40 readonly file: string;
41 readonly start: number;
42 readonly end: number;
43 readonly lines: readonly string[];
44 readonly mode?: Mode;
47export type EditInput = TextEdit | SpliceEdit;
49/** Visible lines [start, end) of a file, 0-based, end exclusive, non-empty. */
50export interface LineRange {
51 readonly file: string;
52 readonly start: number;
53 readonly end: number;
56/**
57 * Move visible lines [start, end) of `file` (0-based, non-empty) so they sit
58 * just before visible line `at` of `to` (at === its line count: the end).
59 * `to` may be the same file, with `at` outside [start, end]. The lines keep
60 * their ids, so edits to them, made before or after, follow them (#28).
61 */
62export interface MoveInput {
63 readonly file: string;
64 readonly start: number;
65 readonly end: number;
66 readonly to: string;
67 readonly at: number;
70export interface AtomInput {
71 readonly author: string;
72 /** The why. */
73 readonly message: string;
74 /** Milliseconds since the epoch. Defaults to 0; the engine never reads a clock. */
75 readonly time?: number;
76 /** Edits, all matched against the same view; their line spans may not overlap. */
77 readonly edits?: readonly EditInput[];
78 /**
79 * "My change relies on these lines staying as they are": holds each line and
80 * the gaps between them, so an edit landing anywhere in the range trips it.
81 */
82 readonly reliesOn?: readonly LineRange[];
83 /** Claim spans: hold these lines and the gaps between them (what a claim-only atom is made of). */
84 readonly spans?: readonly LineRange[];
85 /** Explicit dependencies. */
86 readonly needs?: readonly AtomId[];
87 /** Atoms whose conflict this atom settles. Implies needs. */
88 readonly resolves?: readonly AtomId[];
89 readonly reasons?: readonly Reason[];
90 /** File attributes to set: an empty file's existence, the executable bit, a link target. */
91 readonly attrs?: readonly AttrSet[];
92 /** One block of lines to move. Not together with edits. */
93 readonly move?: MoveInput;
96/** An edit after matching: visible lines [start, end) of `file` become `lines`. */
97interface Region {
98 readonly file: string;
99 readonly start: number;
100 readonly end: number;
101 readonly lines: readonly string[];
102 readonly mode: Mode;
103 readonly order: number;
106/**
107 * Build (but do not accept) an atom from edits against a view. The atom gets
108 * the graph's next id; accept it with `graph.add(atom)` and put it in a set.
109 * Its dependencies are derived from what it touched in the view (see deriveDeps).
110 */
111export function buildAtom(view: View, input: AtomInput): Atom {
112 return build(view, input, false);
115/** The starting snapshot: a0, inserting every line of every file. Empty files are skipped. */
116export function buildBase(
117 files: Readonly<Record<string, string>>,
118 meta: { author: string; message: string; time?: number },
119 attrs: readonly AttrSet[] = [],
120): Atom {
121 const view = new View(new Graph(), []);
122 const edits: TextEdit[] = Object.keys(files)
123 .sort()
124 .filter((file) => files[file] !== "")
125 .map((file) => ({ file, old: "", new: files[file]! }));
126 return build(view, { ...meta, edits, attrs }, true);
129function build(view: View, input: AtomInput, allowEmpty: boolean): Atom {
130 const graph = view.graph;
131 const id = graph.nextId();
132 if (typeof input.author !== "string" || typeof input.message !== "string") {
133 throw new EngineError("bad-edit", "an atom needs an author and a message");
134 }
135 const time = input.time ?? 0;
136 if (!Number.isFinite(time)) throw new EngineError("bad-edit", "time must be a finite number");
138 const regions = resolveRegions(view, input.edits ?? []);
139 if (input.move !== undefined && regions.length > 0)
140 throw new EngineError("bad-edit", "a move goes in an atom of its own, without edits");
142 const inserts: InsertRun[] = [];
143 const deletes: LineId[] = [];
144 const writes = new Set<Key>();
145 const reads = new Set<Key>();
146 const holds = new Set<Key>();
147 const emptiedBy = new Set<AtomId>();
149 for (const region of regions) {
150 const visible = view.lines(region.file);
151 const oldLines = visible.slice(region.start, region.end).map((l) => l.text);
152 for (const hunk of diffLines(oldLines, region.lines)) {
153 const start = region.start + hunk.start;
154 const end = region.start + hunk.end;
155 let parent: NodeId;
156 if (end > start) {
157 // Replacement: delete the old lines; new lines hang off the last deleted one.
158 for (let i = start; i < end; i++) {
159 const line = visible[i]!.id;
160 deletes.push(line);
161 writes.add(lineKey(line));
162 }
163 parent = visible[end - 1]!.id;
164 } else {
165 // Pure insertion between X (above, or the start node) and Y (below, or end of file).
166 const above = start > 0 ? visible[start - 1]!.id : undefined;
167 const below = start < visible.length ? visible[start]!.id : undefined;
168 parent = above ?? startNode(region.file);
169 writes.add(gapKey(parent));
170 // after reads only X and before only Y; at the edge of a file each
171 // reads the neighbour there is, so an insertion into a non-empty file
172 // always claims a line of it.
173 if (above !== undefined && (region.mode !== "before" || below === undefined)) reads.add(lineKey(above));
174 if (below !== undefined && (region.mode !== "after" || above === undefined)) reads.add(lineKey(below));
175 // Creating a file over a deleted one relies on it being empty.
176 if (visible.length === 0) {
177 for (const line of view.sequence(region.file)) for (const d of line.deletedBy) emptiedBy.add(d);
178 }
179 }
180 if (hunk.lines.length > 0) inserts.push({ file: region.file, parent, lines: [...hunk.lines] });
181 }
182 if (region.mode === "wide")
183 holdSpan(
184 visible.slice(region.start, region.end).map((l) => l.id),
185 holds,
186 );
187 }
189 const moves = input.move !== undefined ? planMove(view, input.move, writes, reads) : [];
191 const attrs: AttrSet[] = [];
192 for (const a of input.attrs ?? []) {
193 if (typeof a?.file !== "string" || a.file === "" || /[\n\r]/.test(a.file) || !ATTR_NAMES.includes(a.name)) {
194 throw new EngineError("bad-edit", `an attribute needs a file and one of ${ATTR_NAMES.join(", ")}`);
195 }
196 if (a.value !== null && typeof a.value !== "string")
197 throw new EngineError("bad-edit", "an attribute value is a string or null");
198 if (attrs.some((x) => x.file === a.file && x.name === a.name))
199 throw new EngineError("bad-edit", `${a.name} of ${a.file} set twice`);
200 attrs.push({ file: a.file, name: a.name, value: a.value });
201 writes.add(attrKey(a.file, a.name));
202 }
204 for (const range of input.reliesOn ?? []) holdSpan(rangeLines(view, range), holds);
205 for (const range of input.spans ?? []) holdSpan(rangeLines(view, range), holds);
207 const needs = uniqueAtoms(view, input.needs ?? [], "needs");
208 const resolves = uniqueAtoms(view, input.resolves ?? [], "resolves");
209 const reasons = (input.reasons ?? []).map((r) => {
210 if (!REASON_KINDS.includes(r.kind)) {
211 throw new EngineError("bad-edit", `reason kind must be one of ${REASON_KINDS.join(", ")}, not ${String(r.kind)}`);
212 }
213 if (!graph.has(r.to)) throw new EngineError("unknown-atom", `reason points at unknown atom ${r.to}`);
214 if (typeof r.text !== "string") throw new EngineError("bad-edit", "a reason needs text");
215 return { to: r.to, kind: r.kind, text: r.text };
216 });
218 const nothing =
219 inserts.length === 0 &&
220 deletes.length === 0 &&
221 holds.size === 0 &&
222 needs.length === 0 &&
223 resolves.length === 0 &&
224 reasons.length === 0 &&
225 attrs.length === 0 &&
226 moves.length === 0;
227 if (nothing && !allowEmpty) {
228 throw new EngineError("empty-atom", "the edit changes nothing and claims nothing");
229 }
231 const sortedWrites = [...writes].sort();
232 const sortedReads = [...reads].sort();
233 const sortedHolds = [...holds].sort();
234 const deps = deriveDeps(view, {
235 writes: sortedWrites,
236 reads: sortedReads,
237 holds: sortedHolds,
238 emptiedBy,
239 needs,
240 resolves,
241 });
243 return {
244 id,
245 seq: graph.size,
246 author: input.author,
247 message: input.message,
248 time,
249 inserts,
250 deletes,
251 writes: sortedWrites,
252 reads: sortedReads,
253 holds: sortedHolds,
254 needs,
255 resolves,
256 reasons,
257 deps,
258 ...(attrs.length > 0 ? { attrs } : {}),
259 ...(moves.length > 0 ? { moves } : {}),
260 };
263/**
264 * The relocations that move a block. In the file's full sequence (tombstones
265 * included), the block runs from its first line to its last. Afterwards the
266 * block must sit right after D (the visible line before `at`, or the start
267 * node), and everything else must keep its order. So:
268 * - the block's first line moves to D;
269 * - a later block line whose parent is outside the block moves to the block
270 * line before it (which has no children, the walk being depth-first);
271 * - a line after the block whose parent is inside it moves to the line before
272 * it once the block is gone (the line before the block, for the first).
273 * It writes P: of every block line and of every line it relocates, and G: of
274 * every new parent. It reads P:D, so two moves made apart that would loop
275 * lines into each other collide in all but the rarest cases (the view breaks
276 * any loop that is left).
277 */
278function planMove(view: View, move: MoveInput, writes: Set<Key>, reads: Set<Key>): Relocation[] {
279 for (const path of [move.file, move.to]) {
280 if (typeof path !== "string" || path === "" || /[\n\r]/.test(path))
281 throw new EngineError("bad-edit", `bad file path ${JSON.stringify(path)}`);
282 }
283 const visible = view.lines(move.file);
284 const { start, end, at } = move;
285 if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end > visible.length || start >= end) {
286 throw new EngineError(
287 "bad-range",
288 `${move.file} lines [${start}, ${end}) are not a non-empty range of its ${visible.length} visible lines`,
289 );
290 }
291 const dest = view.lines(move.to);
292 if (!Number.isInteger(at) || at < 0 || at > dest.length) {
293 throw new EngineError("bad-range", `${move.to} has no place ${at} (it has ${dest.length} visible lines)`);
294 }
295 if (move.to === move.file && at >= start && at <= end)
296 throw new EngineError("bad-range", "the lines are already there");
297 const sequence = view.sequence(move.file);
298 const i = view.sequenceIndex(move.file, visible[start]!.id);
299 const j = view.sequenceIndex(move.file, visible[end - 1]!.id);
300 const block = sequence.slice(i, j + 1).map((l) => l.id);
301 const inBlock = new Set(block);
302 const target: NodeId = at > 0 ? dest[at - 1]!.id : startNode(move.to);
304 const out: Relocation[] = [{ line: block[0]!, parent: target }];
305 for (let k = 1; k < block.length; k++) {
306 if (!inBlock.has(view.parentOf(block[k]!))) out.push({ line: block[k]!, parent: block[k - 1]! });
307 }
308 for (let m = j + 1; m < sequence.length; m++) {
309 const line = sequence[m]!.id;
310 if (!inBlock.has(view.parentOf(line))) continue;
311 const parent = m === j + 1 ? (i > 0 ? sequence[i - 1]!.id : startNode(move.file)) : sequence[m - 1]!.id;
312 out.push({ line, parent });
313 }
314 for (const line of block) writes.add(posKey(line));
315 for (const r of out) {
316 writes.add(posKey(r.line));
317 writes.add(gapKey(r.parent));
318 }
319 if (!isStartNode(target)) reads.add(posKey(target));
320 return out;
323/**
324 * Derived dependencies of a new atom against its view (docs/prototype.md,
325 * "Dependencies"):
326 * - blame: the writers of every line its keys name (a G: key names the line
327 * the gap follows);
328 * - gap rule: atoms in the view that wrote a gap it inserts into or holds.
329 * Their lines hang off the same line, so the new run outranks all of them
330 * and lands directly after its parent;
331 * - implicit-read rule: atoms in the view whose implicit reads include a key
332 * it writes (it saw that insert and changed its neighbour);
333 * - creating a file over a deleted one: the atoms that deleted its lines;
334 * - needs and resolves.
335 * Nothing else from the view: not the line below an insertion, not the
336 * tombstones around it.
337 */
338function deriveDeps(
339 view: View,
340 parts: {
341 writes: readonly Key[];
342 reads: readonly Key[];
343 holds: readonly Key[];
344 emptiedBy: ReadonlySet<AtomId>;
345 needs: readonly AtomId[];
346 resolves: readonly AtomId[];
347 },
348): AtomId[] {
349 const graph = view.graph;
350 const deps = new Set<AtomId>(parts.emptiedBy);
351 for (const key of [...parts.writes, ...parts.reads, ...parts.holds]) {
352 const { kind, node } = parseKey(key);
353 // An attribute builds on whoever set it last in the view, the way an insertion builds on a gap's writers;
354 // a move builds on the earlier moves of its lines.
355 if (kind !== "attr" && !isStartNode(node)) deps.add(writerOf(node));
356 if (kind !== "line") for (const writer of graph.writersOf(key)) if (view.set.has(writer)) deps.add(writer);
357 }
358 for (const key of parts.writes) {
359 for (const reader of graph.readersOf(key)) if (view.set.has(reader)) deps.add(reader);
360 }
361 for (const id of parts.needs) deps.add(id);
362 for (const id of parts.resolves) deps.add(id);
363 return [...deps].sort((a, b) => graph.atom(a).seq - graph.atom(b).seq);
366/** Hold every line of a span and every gap between consecutive lines of it. */
367function holdSpan(lines: readonly LineId[], holds: Set<Key>): void {
368 lines.forEach((line, i) => {
369 holds.add(lineKey(line));
370 if (i + 1 < lines.length) holds.add(gapKey(line));
371 });
374function rangeLines(view: View, range: LineRange): LineId[] {
375 const visible = view.lines(range.file);
376 if (
377 !Number.isInteger(range.start) ||
378 !Number.isInteger(range.end) ||
379 range.start < 0 ||
380 range.end > visible.length ||
381 range.start >= range.end
382 ) {
383 throw new EngineError(
384 "bad-range",
385 `${range.file} lines [${range.start}, ${range.end}) are not a non-empty range of its ${visible.length} visible lines`,
386 );
387 }
388 return visible.slice(range.start, range.end).map((l) => l.id);
391function uniqueAtoms(view: View, ids: readonly AtomId[], what: string): AtomId[] {
392 const out: AtomId[] = [];
393 for (const id of ids) {
394 if (!view.graph.has(id)) throw new EngineError("unknown-atom", `${what} names unknown atom ${id}`);
395 if (!view.set.has(id)) throw new EngineError("not-in-view", `${what} names ${id}, which is not in the view`);
396 if (!out.includes(id)) out.push(id);
397 }
398 return out.sort((a, b) => view.graph.atom(a).seq - view.graph.atom(b).seq);
401// Matching edits ---------------------------------------------------------------
403function resolveRegions(view: View, edits: readonly EditInput[]): Region[] {
404 const regions = edits.map((edit, order) => {
405 const mode = edit.mode ?? "both";
406 if (!MODES.includes(mode)) throw new EngineError("bad-edit", `mode must be one of ${MODES.join(", ")}`);
407 // A path may start with '^' (a start node is '^' + path, so '^^x' stays unambiguous).
408 if (typeof edit.file !== "string" || edit.file === "" || /[\n\r]/.test(edit.file)) {
409 throw new EngineError("bad-edit", `bad file path ${JSON.stringify(edit.file)}`);
410 }
411 return "old" in edit ? matchText(view, edit, mode, order) : matchSplice(view, edit, mode, order);
412 });
414 // Files in order of first appearance; within a file, regions in position order.
415 const fileOrder = new Map<string, number>();
416 for (const r of regions) if (!fileOrder.has(r.file)) fileOrder.set(r.file, fileOrder.size);
417 regions.sort(
418 (a, b) =>
419 fileOrder.get(a.file)! - fileOrder.get(b.file)! || a.start - b.start || a.end - b.end || a.order - b.order,
420 );
421 for (let i = 1; i < regions.length; i++) {
422 const prev = regions[i - 1]!;
423 const cur = regions[i]!;
424 if (prev.file === cur.file && prev.end > cur.start) {
425 throw new EngineError(
426 "overlapping-edits",
427 `two edits to ${cur.file} overlap (lines ${prev.start + 1}-${prev.end} and ${cur.start + 1}-${cur.end})`,
428 );
429 }
430 }
431 return regions;
434/**
435 * Find `old` (exactly once) in the file's visible text and widen the match to
436 * whole lines. If the replacement would leave a line without its newline, the
437 * next line joins the region (that is what the plain-text edit does).
438 */
439function matchText(view: View, edit: TextEdit, mode: Mode, order: number): Region {
440 if (typeof edit.old !== "string" || typeof edit.new !== "string") {
441 throw new EngineError("bad-edit", "a text edit needs old and new strings");
442 }
443 const file = edit.file;
444 const visible = view.lines(file);
445 const oldText = normalizeText(edit.old);
446 const newText = normalizeText(edit.new);
447 if (oldText === "") {
448 if (visible.length > 0) {
449 throw new EngineError(
450 "ambiguous-match",
451 `empty old text matches everywhere in ${file}; an empty old text only creates a file`,
452 );
453 }
454 return { file, start: 0, end: 0, lines: splitLines(newText), mode, order };
455 }
456 const text = joinLines(visible.map((l) => l.text));
457 const at = text.indexOf(oldText);
458 if (at < 0) throw new EngineError("no-match", `old text not found in ${file}`);
459 if (text.indexOf(oldText, at + 1) >= 0) {
460 throw new EngineError(
461 "ambiguous-match",
462 `old text matches more than once in ${file}; add context to make it unique`,
463 );
464 }
465 const starts: number[] = [];
466 let pos = 0;
467 for (const line of visible) {
468 starts.push(pos);
469 pos += line.text.length + 1;
470 }
471 const lineAt = (offset: number): number => {
472 let lo = 0;
473 let hi = starts.length - 1;
474 while (lo < hi) {
475 const mid = (lo + hi + 1) >> 1;
476 if (starts[mid]! <= offset) lo = mid;
477 else hi = mid - 1;
478 }
479 return lo;
480 };
481 const end = at + oldText.length;
482 const startLine = lineAt(at);
483 let endLine = lineAt(end - 1);
484 const lineStart = starts[startLine]!;
485 const lineEnd = starts[endLine]! + visible[endLine]!.text.length + 1;
486 let replacement = text.slice(lineStart, at) + newText + text.slice(end, lineEnd);
487 if (replacement !== "" && !replacement.endsWith("\n")) {
488 if (endLine + 1 < visible.length) {
489 endLine++;
490 replacement += visible[endLine]!.text + "\n";
491 } else {
492 replacement += "\n";
493 }
494 }
495 return { file, start: startLine, end: endLine + 1, lines: splitLines(replacement), mode, order };
498function matchSplice(view: View, edit: SpliceEdit, mode: Mode, order: number): Region {
499 const count = view.lines(edit.file).length;
500 if (
501 !Number.isInteger(edit.start) ||
502 !Number.isInteger(edit.end) ||
503 edit.start < 0 ||
504 edit.start > edit.end ||
505 edit.end > count
506 ) {
507 throw new EngineError(
508 "bad-range",
509 `${edit.file} lines [${edit.start}, ${edit.end}) are outside its ${count} visible lines`,
510 );
511 }
512 if (!Array.isArray(edit.lines)) throw new EngineError("bad-edit", "a splice edit needs lines");
513 const lines = edit.lines.map((line) => {
514 if (typeof line !== "string" || /[\n\r]/.test(line)) {
515 throw new EngineError("bad-edit", "splice lines must be strings without line breaks");
516 }
517 return line;
518 });
519 return { file: edit.file, start: edit.start, end: edit.end, lines, mode, order };