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