- 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=136&format=json
539 linesFirst import 95% · codex-capacity-chair 4% · pinch 1%Last change codex-capacity-chair in version 124, 4 versions changed it
You're reading version 136. The newest is 318, and 2 versions 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/** 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;
32}
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;
45}
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;
54}
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;
68}
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;
94}
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;
104}
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);
113}
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);
127}
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 };
261}
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;
321}
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. New atoms encode implicit dependencies as maximal
337 * tips: ancestors reachable through another tip are omitted from direct deps.
338 * Explicit needs/resolves always remain direct. Existing atoms are not rewritten.
339 * Direct-edge diagnostics (including why/Deps trailers and missingDeps) therefore
340 * show fewer redundant edges; transitive closure and dependency ordering remain
341 * the semantic contract. A missing tip still implies its required ancestors.
342 */
343function deriveDeps(
344 view: View,
345 parts: {
346 writes: readonly Key[];
347 reads: readonly Key[];
348 holds: readonly Key[];
349 emptiedBy: ReadonlySet<AtomId>;
350 needs: readonly AtomId[];
351 resolves: readonly AtomId[];
352 },
353): AtomId[] {
354 const graph = view.graph;
355 // New atoms retain maximal implicit dependencies. Their transitive closure is
356 // unchanged; explicit needs/resolves remain direct edges below.
357 const deps = new Set<AtomId>();
358 const addImplicit = (candidate: AtomId): void => {
359 if (deps.has(candidate)) return;
360 const candidateClock = graph.lamport(candidate);
361 for (const previous of deps) {
362 const previousClock = graph.lamport(previous);
363 // Equal Lamport clocks cannot reach each other; check only the possible direction.
364 if (previousClock > candidateClock && graph.dependsOn(previous, candidate)) return;
365 if (candidateClock > previousClock && graph.dependsOn(candidate, previous)) deps.delete(previous);
366 }
367 deps.add(candidate);
368 };
369 for (const id of parts.emptiedBy) addImplicit(id);
370 for (const key of [...parts.writes, ...parts.reads, ...parts.holds]) {
371 const { kind, node } = parseKey(key);
372 // An attribute builds on whoever set it last in the view, the way an insertion builds on a gap's writers;
373 // a move builds on the earlier moves of its lines.
374 if (kind !== "attr" && !isStartNode(node)) addImplicit(writerOf(node));
375 if (kind !== "line") for (const writer of graph.eachWriterOf(key)) if (view.set.has(writer)) addImplicit(writer);
376 }
377 for (const key of parts.writes) {
378 for (const reader of graph.eachReaderOf(key)) if (view.set.has(reader)) addImplicit(reader);
379 }
380 for (const id of parts.needs) deps.add(id);
381 for (const id of parts.resolves) deps.add(id);
382 return [...deps].sort((a, b) => graph.atom(a).seq - graph.atom(b).seq);
383}
385/** Hold every line of a span and every gap between consecutive lines of it. */
386function holdSpan(lines: readonly LineId[], holds: Set<Key>): void {
387 lines.forEach((line, i) => {
388 holds.add(lineKey(line));
389 if (i + 1 < lines.length) holds.add(gapKey(line));
390 });
391}
393function rangeLines(view: View, range: LineRange): LineId[] {
394 const visible = view.lines(range.file);
395 if (
396 !Number.isInteger(range.start) ||
397 !Number.isInteger(range.end) ||
398 range.start < 0 ||
399 range.end > visible.length ||
400 range.start >= range.end
401 ) {
402 throw new EngineError(
403 "bad-range",
404 `${range.file} lines [${range.start}, ${range.end}) are not a non-empty range of its ${visible.length} visible lines`,
405 );
406 }
407 return visible.slice(range.start, range.end).map((l) => l.id);
408}
410function uniqueAtoms(view: View, ids: readonly AtomId[], what: string): AtomId[] {
411 const out: AtomId[] = [];
412 for (const id of ids) {
413 if (!view.graph.has(id)) throw new EngineError("unknown-atom", `${what} names unknown atom ${id}`);
414 if (!view.set.has(id)) throw new EngineError("not-in-view", `${what} names ${id}, which is not in the view`);
415 if (!out.includes(id)) out.push(id);
416 }
417 return out.sort((a, b) => view.graph.atom(a).seq - view.graph.atom(b).seq);
418}
420// Matching edits ---------------------------------------------------------------
422function resolveRegions(view: View, edits: readonly EditInput[]): Region[] {
423 const regions = edits.map((edit, order) => {
424 const mode = edit.mode ?? "both";
425 if (!MODES.includes(mode)) throw new EngineError("bad-edit", `mode must be one of ${MODES.join(", ")}`);
426 // A path may start with '^' (a start node is '^' + path, so '^^x' stays unambiguous).
427 if (typeof edit.file !== "string" || edit.file === "" || /[\n\r]/.test(edit.file)) {
428 throw new EngineError("bad-edit", `bad file path ${JSON.stringify(edit.file)}`);
429 }
430 return "old" in edit ? matchText(view, edit, mode, order) : matchSplice(view, edit, mode, order);
431 });
433 // Files in order of first appearance; within a file, regions in position order.
434 const fileOrder = new Map<string, number>();
435 for (const r of regions) if (!fileOrder.has(r.file)) fileOrder.set(r.file, fileOrder.size);
436 regions.sort(
437 (a, b) =>
438 fileOrder.get(a.file)! - fileOrder.get(b.file)! || a.start - b.start || a.end - b.end || a.order - b.order,
439 );
440 for (let i = 1; i < regions.length; i++) {
441 const prev = regions[i - 1]!;
442 const cur = regions[i]!;
443 if (prev.file === cur.file && prev.end > cur.start) {
444 throw new EngineError(
445 "overlapping-edits",
446 `two edits to ${cur.file} overlap (lines ${prev.start + 1}-${prev.end} and ${cur.start + 1}-${cur.end})`,
447 );
448 }
449 }
450 return regions;
451}
453/**
454 * Find `old` (exactly once) in the file's visible text and widen the match to
455 * whole lines. If the replacement would leave a line without its newline, the
456 * next line joins the region (that is what the plain-text edit does).
457 */
458function matchText(view: View, edit: TextEdit, mode: Mode, order: number): Region {
459 if (typeof edit.old !== "string" || typeof edit.new !== "string") {
460 throw new EngineError("bad-edit", "a text edit needs old and new strings");
461 }
462 const file = edit.file;
463 const visible = view.lines(file);
464 const oldText = normalizeText(edit.old);
465 const newText = normalizeText(edit.new);
466 if (oldText === "") {
467 if (visible.length > 0) {
468 throw new EngineError(
469 "ambiguous-match",
470 `empty old text matches everywhere in ${file}; an empty old text only creates a file`,
471 );
472 }
473 return { file, start: 0, end: 0, lines: splitLines(newText), mode, order };
474 }
475 const text = joinLines(visible.map((l) => l.text));
476 const at = text.indexOf(oldText);
477 if (at < 0) throw new EngineError("no-match", `old text not found in ${file}`);
478 if (text.indexOf(oldText, at + 1) >= 0) {
479 throw new EngineError(
480 "ambiguous-match",
481 `old text matches more than once in ${file}; add context to make it unique`,
482 );
483 }
484 const starts: number[] = [];
485 let pos = 0;
486 for (const line of visible) {
487 starts.push(pos);
488 pos += line.text.length + 1;
489 }
490 const lineAt = (offset: number): number => {
491 let lo = 0;
492 let hi = starts.length - 1;
493 while (lo < hi) {
494 const mid = (lo + hi + 1) >> 1;
495 if (starts[mid]! <= offset) lo = mid;
496 else hi = mid - 1;
497 }
498 return lo;
499 };
500 const end = at + oldText.length;
501 const startLine = lineAt(at);
502 let endLine = lineAt(end - 1);
503 const lineStart = starts[startLine]!;
504 const lineEnd = starts[endLine]! + visible[endLine]!.text.length + 1;
505 let replacement = text.slice(lineStart, at) + newText + text.slice(end, lineEnd);
506 if (replacement !== "" && !replacement.endsWith("\n")) {
507 if (endLine + 1 < visible.length) {
508 endLine++;
509 replacement += `${visible[endLine]!.text}\n`;
510 } else {
511 replacement += "\n";
512 }
513 }
514 return { file, start: startLine, end: endLine + 1, lines: splitLines(replacement), mode, order };
515}
517function matchSplice(view: View, edit: SpliceEdit, mode: Mode, order: number): Region {
518 const count = view.lines(edit.file).length;
519 if (
520 !Number.isInteger(edit.start) ||
521 !Number.isInteger(edit.end) ||
522 edit.start < 0 ||
523 edit.start > edit.end ||
524 edit.end > count
525 ) {
526 throw new EngineError(
527 "bad-range",
528 `${edit.file} lines [${edit.start}, ${edit.end}) are outside its ${count} visible lines`,
529 );
530 }
531 if (!Array.isArray(edit.lines)) throw new EngineError("bad-edit", "a splice edit needs lines");
532 const lines = edit.lines.map((line) => {
533 if (typeof line !== "string" || /[\n\r]/.test(line)) {
534 throw new EngineError("bad-edit", "splice lines must be strings without line breaks");
535 }
536 return line;
537 });
538 return { file: edit.file, start: edit.start, end: edit.end, lines, mode, order };
539}