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/graph.ts?version=127&format=json
1,270 linesFirst import 84% · codex-capacity-chair 16%Last change codex-capacity-chair in version 127, 8 versions changed it

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

1// The graph: every atom ever accepted, plus labels. Sets of atoms (states of
2// the codebase) are separate values; the graph only answers questions about
3// atoms and keeps indexes so those questions are cheap.
4
5import {
6 atomId,
7 attrKey,
8 gapKey,
9 isAtomId,
10 isStartNode,
11 lineId,
12 lineKey,
13 parseKey,
14 posKey,
15 seqOf,
16 startNode,
17} from "./keys.ts";
18import {
19 type GraphStateStorage,
20 type StateMap,
21 storedArray,
22 storedLists,
23 storedMap,
24 storedNumbers,
25} from "./state-source.ts";
26import {
27 ATTR_NAMES,
28 type Atom,
29 type AtomId,
30 EngineError,
31 type InsertRun,
32 type Key,
33 type Label,
34 type LineId,
35 type NodeId,
36 REASON_KINDS,
37 type Reason,
38} from "./types.ts";
40/**
41 * Where a line was written and what it says. Its text never changes. A move
42 * can give it another parent in a set, even in another file: `view.parentOf`
43 * and `view.fileOf` say where it is in a set.
44 */
45export interface LineInfo {
46 readonly id: LineId;
47 readonly atom: AtomId;
48 readonly k: number;
49 /** The file it was written in. */
50 readonly file: string;
51 /** The node it was written after. */
52 readonly parent: NodeId;
53 readonly text: string;
56/** One relocation of a line, by the atom that made it; `k` is its place in that atom's moves. */
57export interface RelocationInfo {
58 readonly atom: AtomId;
59 readonly line: LineId;
60 readonly parent: NodeId;
61 readonly k: number;
64/** A `together` reason seen from one end: `other` is the atom at the far end. */
65export interface TogetherLink {
66 readonly other: AtomId;
67 readonly text: string;
68 /** The atom that carries the reason. */
69 readonly from: AtomId;
72export const GRAPH_FORMAT = "ai-first-vcs.graph";
74/** The saved form of a graph. Atoms are in seq order. */
75export interface GraphJSON {
76 readonly format: typeof GRAPH_FORMAT;
77 readonly version: 1;
78 readonly atoms: readonly Atom[];
79 readonly labels: readonly Label[];
82/**
83 * An index entry that holds a lone value as itself, and a list only once there
84 * are two (#46): most keys name one atom, and a list for each costs more than
85 * the value.
86 */
87function pushOne<K, V>(map: StateMap<K, V | V[]>, key: K, value: V): void {
88 const had = map.get(key);
89 if (had === undefined) map.set(key, value);
90 else if (Array.isArray(had)) {
91 had.push(value);
92 map.set(key, had);
93 } else map.set(key, [had, value]);
96function listOf<V>(had: V | V[] | undefined): readonly V[] {
97 return had === undefined ? EMPTY : Array.isArray(had) ? had : [had];
100function pushIndex<K, V>(map: StateMap<K, V[]>, key: K, value: V): void {
101 const list = map.get(key);
102 if (list) {
103 list.push(value);
104 map.set(key, list);
105 } else map.set(key, [value]);
108const EMPTY: readonly never[] = Object.freeze([]);
110/**
111 * A run whose lines are read when asked for (#46, text on disk): a few fields
112 * and a shared reader, where an object with its own accessor cost about 400
113 * bytes a run.
114 */
115class LazyRun implements InsertRun {
116 readonly file: string;
117 readonly parent: NodeId;
118 readonly #text: (start: number, length: number) => readonly string[];
119 readonly #start: number;
120 readonly #length: number;
121 constructor(
122 file: string,
123 parent: NodeId,
124 text: (start: number, length: number) => readonly string[],
125 start: number,
126 length: number,
127 ) {
128 this.file = file;
129 this.parent = parent;
130 this.#text = text;
131 this.#start = start;
132 this.#length = length;
133 }
134 get lines(): readonly string[] {
135 return this.#text(this.#start, this.#length);
136 }
137 toJSON(): InsertRun {
138 return { file: this.file, parent: this.parent, lines: this.lines };
139 }
142/** Characters of atoms' text a graph that keeps text elsewhere holds at most (#46): about 8 MB. */
143const TEXT_CACHE = 4_000_000;
144/** How many list items (deletes and keys) are kept read back (#46): publishes and syncs meet few atoms, but one reformat's atom can hold 100,000. */
145const LIST_CACHE = 50_000;
147/** An atom's deletes and claim keys: kept in the log rather than in memory when the graph has a `lists` reader (#46). */
148export interface AtomLists {
149 readonly deletes: readonly LineId[];
150 readonly writes: readonly Key[];
151 readonly reads: readonly Key[];
152 readonly holds: readonly Key[];
155function listItems(l: AtomLists): number {
156 return l.deletes.length + l.writes.length + l.reads.length + l.holds.length;
159function frozenList<T>(xs: readonly T[]): readonly T[] {
160 return xs.length === 0 ? (EMPTY as readonly T[]) : Object.freeze([...xs]);
163/**
164 * An atom whose deletes, writes, reads and holds are read back through `read` (#46). The getters live on the
165 * prototype, so each atom keeps one reader and a fixed shape, not four closures in a dictionary-mode object.
166 */
167class ListedAtom {
168 readonly #read: () => AtomLists;
169 constructor(fields: object, read: () => AtomLists) {
170 Object.assign(this, fields);
171 this.#read = read;
172 }
173 get deletes(): readonly LineId[] {
174 return this.#read().deletes;
175 }
176 get writes(): readonly Key[] {
177 return this.#read().writes;
178 }
179 get reads(): readonly Key[] {
180 return this.#read().reads;
181 }
182 get holds(): readonly Key[] {
183 return this.#read().holds;
184 }
185 toJSON(): object {
186 return { ...this, ...this.#read() };
187 }
190/** A growable array of 32-bit integers: a line's fields cost 4 bytes each, not an object and its strings (#46). */
191interface NumberIndex {
192 readonly length: number;
193 push(n: number): void;
194 at(i: number): number;
195 set(i: number, n: number): void;
198class Ints implements NumberIndex {
199 #buf: Int32Array | Uint8Array;
200 /** bytes: values 0-255 only, one byte each. */
201 constructor(bytes = false) {
202 this.#buf = bytes ? new Uint8Array(1024) : new Int32Array(1024);
203 }
204 length = 0;
205 push(n: number): void {
206 if (this.length === this.#buf.length) {
207 const bigger =
208 this.#buf instanceof Uint8Array ? new Uint8Array(this.#buf.length * 2) : new Int32Array(this.#buf.length * 2);
209 bigger.set(this.#buf);
210 this.#buf = bigger;
211 }
212 this.#buf[this.length++] = n;
213 }
214 at(i: number): number {
215 return this.#buf[i]!;
216 }
217 set(i: number, n: number): void {
218 this.#buf[i] = n;
219 }
222/**
223 * A line id's place in the graph's line arrays, or -1: "a<seq>.<k>" is line
224 * `base[seq] + k`. Hand-parsed, as seqOf is, with the same rules: no leading
225 * zeros, and k within the lines its atom wrote.
226 */
227function parseLineId(id: string): { seq: number; k: number } | undefined {
228 if (typeof id !== "string") return undefined;
229 const n = id.length;
230 if (n < 4 || id.charCodeAt(0) !== 97 /* a */) return undefined;
231 let i = 1;
232 let seq = 0;
233 const seqStart = i;
234 for (; i < n; i++) {
235 const c = id.charCodeAt(i);
236 if (c === 46 /* . */) break;
237 if (c < 48 || c > 57) return undefined;
238 seq = seq * 10 + (c - 48);
239 }
240 if (i === seqStart || i >= n - 1 || i - seqStart > 15 || (i - seqStart > 1 && id.charCodeAt(seqStart) === 48))
241 return undefined;
242 const kStart = ++i;
243 let k = 0;
244 for (; i < n; i++) {
245 const c = id.charCodeAt(i);
246 if (c < 48 || c > 57) return undefined;
247 k = k * 10 + (c - 48);
248 }
249 if (i - kStart > 15 || (i - kStart > 1 && id.charCodeAt(kStart) === 48)) return undefined;
250 return { seq, k };
253export class Graph {
254 readonly #storage?: GraphStateStorage;
255 #atoms: Atom[] = [];
256 #lamport: number[] = [];
257 // Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its
258 // atom's seq, the file it was written in (an index into #paths) and its parent (a line's n, or -1 - a
259 // path's index for a file's start). Its text stays in the atom. Ids and LineInfo objects are made only
260 // when asked for, so a line costs about 16 bytes here instead of a record, its id and its parent's id.
261 #lineBase: number[] = [];
262 #lineAtom: NumberIndex = new Ints();
263 #lineFile: NumberIndex = new Ints();
264 #lineParent: NumberIndex = new Ints();
265 /** Lines' text, when the graph keeps it; without it, it comes from `texts` (#46, text on disk). */
266 #lineText: string[] | undefined = [];
267 get #lineTotal(): number {
268 return this.#lineAtom.length;
269 }
270 /** Where an atom's lines' text is when the graph doesn't keep it: each run's lines, by the atom's seq. */
271 #texts: ((seq: number) => readonly (readonly string[])[]) | undefined;
272 /** Recently read atoms' text, flattened, most recent last, up to TEXT_CACHE characters. */
273 #textCache = new Map<number, readonly string[]>();
274 #textCached = 0;
276 /**
277 * `texts`, when given, says where each atom's lines' text can be read back
278 * (#46): the graph then keeps no text, only each line's place, and reads an
279 * atom's text when a line of it is asked for, keeping the most recent.
280 */
281 constructor(
282 options: {
283 texts?: (seq: number) => readonly (readonly string[])[];
284 lists?: (seq: number) => AtomLists;
285 storage?: GraphStateStorage;
286 } = {},
287 ) {
288 if (options.texts) {
289 this.#texts = options.texts;
290 this.#lineText = undefined;
291 }
292 if (options.lists) this.#lists = options.lists;
293 this.#storage = options.storage;
294 if (options.storage) {
295 const storage = options.storage;
296 const numbers = (name: string): NumberIndex => storedNumbers(storage, name);
297 this.#atoms = storedArray<Atom>(storage, "atoms", (atom) =>
298 freezeAtom(
299 atom,
300 (id) => id,
301 (author) => author,
302 ),
303 );
304 this.#lamport = storedArray(storage, "lamport");
305 this.#lineBase = storedArray(storage, "line-base");
306 this.#paths = storedArray(storage, "paths");
307 this.#movers = storedArray(storage, "movers");
308 this.#atomFiles = storedArray(storage, "atom-files");
309 this.#atomDeletes = storedArray(storage, "atom-deletes");
310 this.#lineAtom = numbers("line-atom");
311 this.#lineFile = numbers("line-file");
312 this.#lineParent = numbers("line-parent");
313 this.#deleter = numbers("deleter");
314 this.#replacing = numbers("replacing");
315 this.#lineText = storedArray(storage, "line-text");
316 this.#pathIndex = storedMap(storage, "path-index");
317 this.#moreDeleters = storedMap(storage, "more-deleters");
318 this.#writersPages = storedLists<AtomId>(storage, "writers", (key) => key);
319 this.#readersPages = storedLists<AtomId>(storage, "readers", (key) => key);
320 this.#holdersPages = storedLists<AtomId>(storage, "holders", (key) => key);
321 this.#dependentsPages = storedLists<AtomId>(storage, "dependents");
322 this.#resolversPages = storedLists<AtomId>(storage, "resolvers");
323 this.#together = storedMap(storage, "together");
324 this.#fileAtomPages = storedLists<AtomId>(storage, "file-atoms");
325 this.#runStarts = storedMap(storage, "run-starts");
326 this.#relocationPages = storedLists<RelocationInfo>(storage, "relocations");
327 this.#relocatedToPages = storedLists<RelocationInfo>(storage, "relocated-to");
328 this.#relocatedToCodePages = storedLists<RelocationInfo>(storage, "relocated-to-code", (key) =>
329 JSON.stringify(["number", Number(key)]),
330 );
331 this.#labels = storedMap(storage, "labels");
332 }
333 }
335 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */
336 #lists: ((seq: number) => AtomLists) | undefined;
337 /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */
338 #listCache = new Map<number, AtomLists>();
339 #listCached = 0;
341 /** An atom's deletes, writes, reads and holds, read back from where they are stored. */
342 #listsOf(seq: number): AtomLists {
343 const hit = this.#listCache.get(seq);
344 if (hit) {
345 this.#listCache.delete(seq);
346 this.#listCache.set(seq, hit);
347 return hit;
348 }
349 const got = this.#lists!(seq);
350 const lists: AtomLists = {
351 deletes: frozenList(got.deletes),
352 writes: frozenList(got.writes),
353 reads: frozenList(got.reads),
354 holds: frozenList(got.holds),
355 };
356 this.#listCache.set(seq, lists);
357 this.#listCached += listItems(lists);
358 for (const [old, kept] of this.#listCache) {
359 if (this.#listCached <= LIST_CACHE || old === seq) break;
360 this.#listCache.delete(old);
361 this.#listCached -= listItems(kept);
362 }
363 return lists;
364 }
366 /** The reader an atom's lists use; made apart from add() so it keeps no atom alive (see #reader). */
367 #listReader(seq: number): () => AtomLists {
368 return () => this.#listsOf(seq);
369 }
371 /**
372 * A claim key as the index keeps it (#46): a line's L:, P: and G: keys by its n (n * 4, + 1, + 2), so the
373 * index holds numbers rather than one string per line; start-node and attribute keys stay strings. A key
374 * naming a line the graph doesn't have stays a string, which nothing has claimed.
375 */
376 #code(key: Key): Key | number {
377 const t = key.charCodeAt(0);
378 if (key.charCodeAt(1) !== 58 || key.charCodeAt(2) === 94) return key; // not "X:", or a start node "^"
379 const k = t === 76 ? 0 : t === 80 ? 1 : t === 71 ? 2 : -1; // L, P, G
380 if (k < 0) return key;
381 const n = this.#lineN(key.slice(2));
382 return n < 0 ? key : n * 4 + k;
383 }
385 /** An atom's lines' text, in k order. */
386 #textOf(seq: number): readonly string[] {
387 const hit = this.#textCache.get(seq);
388 if (hit) {
389 this.#textCache.delete(seq);
390 this.#textCache.set(seq, hit);
391 return hit;
392 }
393 const flat = this.#texts!(seq).flat();
394 let chars = 0;
395 for (const t of flat) chars += t.length + 1;
396 this.#textCache.set(seq, flat);
397 this.#textCached += chars;
398 for (const [old, lines] of this.#textCache) {
399 if (this.#textCached <= TEXT_CACHE || old === seq) break;
400 this.#textCache.delete(old);
401 for (const t of lines) this.#textCached -= t.length + 1;
402 }
403 return flat;
404 }
406 /**
407 * The reader an atom's runs use. Made in a function of its own: a closure made inside add() would
408 * keep add()'s whole scope alive, the atom as given with all its text included.
409 */
410 #reader(seq: number): (start: number, length: number) => readonly string[] {
411 return (start, length) => this.#textOf(seq).slice(start, start + length);
412 }
414 /** Line n's text. */
415 #text(n: number): string {
416 if (this.#lineText) return this.#lineText[n]!;
417 const seq = this.#lineAtom.at(n);
418 return this.#textOf(seq)[n - this.#lineBase[seq]!]!;
419 }
420 #paths: string[] = [];
421 #pathIndex: StateMap<string, number> = new Map();
422 /** The first atom that deletes each line (its seq), or -1; a line deleted by more than one has the rest in #moreDeleters. */
423 #deleter: NumberIndex = new Ints();
424 #moreDeleters: StateMap<number, number[]> = new Map();
425 #writers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
426 #writersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
427 #readers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
428 #readersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
429 #holders: StateMap<Key | number, AtomId | AtomId[]> = new Map();
430 #holdersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
431 #dependents: StateMap<AtomId, AtomId | AtomId[]> = new Map();
432 #dependentsPages: ReturnType<typeof storedLists<AtomId>> | undefined;
433 #resolvers: StateMap<AtomId, AtomId | AtomId[]> = new Map();
434 #resolversPages: ReturnType<typeof storedLists<AtomId>> | undefined;
435 #together: StateMap<AtomId, TogetherLink[]> = new Map();
436 #fileAtoms: StateMap<string, AtomId[]> = new Map();
437 #fileAtomPages: ReturnType<typeof storedLists<AtomId>> | undefined;
438 /** First lines of runs (their n), by the node they were written after: a line's n, or -1 - a path's index. */
439 #runStarts: StateMap<number, number | number[]> = new Map();
440 /** 1 for the first line of a run whose atom deleted the line it hangs off: the run replaces it. */
441 #replacing: NumberIndex = new Ints(true);
442 #relocations: StateMap<LineId, RelocationInfo[]> = new Map();
443 #relocationPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
444 #relocatedTo: StateMap<NodeId, RelocationInfo[]> = new Map();
445 #relocatedToPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
446 /** The same relocations by node code (a line's n, or -1 - a path's index), for views laid out by number. */
447 #relocatedToCode: StateMap<number, RelocationInfo[]> = new Map();
448 #relocatedToCodePages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
449 #movers: AtomId[] = [];
450 #atomFiles: (readonly string[])[] = [];
451 /** Each atom's deleted lines by n, packed (#46), or undefined when it deletes none. */
452 #atomDeletes: (readonly number[] | Int32Array | undefined)[] = [];
453 #labels: StateMap<string, Label> = new Map();
454 /** Each author's name kept once (#46). */
455 #authors = new Map<string, string>();
457 /** Number of atoms (also the seq the next atom gets). */
458 get size(): number {
459 return this.#atoms.length;
460 }
462 /** The id the next accepted atom must have. */
463 nextId(): AtomId {
464 return atomId(this.#atoms.length);
465 }
467 has(id: AtomId): boolean {
468 const seq = this.#seq(id);
469 return seq >= 0 && seq < this.#atoms.length;
470 }
472 atom(id: AtomId): Atom {
473 const seq = this.#seq(id);
474 const atom = seq >= 0 ? this.#atoms[seq] : undefined;
475 if (!atom) throw new EngineError("unknown-atom", `no atom ${id}`);
476 return atom;
477 }
479 /** All atoms in seq order. */
480 atoms(): readonly Atom[] {
481 return this.#atoms;
482 }
484 /** lamport(a) = 1 + max lamport of its deps; 0 for an atom with no deps (such as a0). */
485 lamport(id: AtomId): number {
486 this.atom(id);
487 return this.#lamport[this.#seq(id)]!;
488 }
490 /** Compare by priority (lamport, then seq). Negative when a comes first (is lower). */
491 comparePriority(a: AtomId, b: AtomId): number {
492 return this.lamport(a) - this.lamport(b) || this.#seq(a) - this.#seq(b);
493 }
495 line(id: LineId): LineInfo | undefined {
496 const n = this.#lineN(id);
497 if (n < 0) return undefined;
498 const seq = this.#lineAtom.at(n);
499 return {
500 id,
501 atom: this.#atoms[seq]!.id,
502 k: n - this.#lineBase[seq]!,
503 file: this.#paths[this.#lineFile.at(n)]!,
504 parent: this.#nodeName(this.#lineParent.at(n)),
505 text: this.#text(n),
506 };
507 }
509 /** A line's text, or undefined for an unknown line: line(id).text without making the record. */
510 lineText(id: LineId): string | undefined {
511 const n = this.#lineN(id);
512 return n < 0 ? undefined : this.#text(n);
513 }
515 /** The atom that wrote a line, or undefined: line(id).atom without making the record. */
516 lineAtom(id: LineId): AtomId | undefined {
517 const n = this.#lineN(id);
518 return n < 0 ? undefined : this.#atoms[this.#lineAtom.at(n)]!.id;
519 }
521 /** The file a line was written in, or undefined: line(id).file without making the record. */
522 lineFile(id: LineId): string | undefined {
523 const n = this.#lineN(id);
524 return n < 0 ? undefined : this.#paths[this.#lineFile.at(n)];
525 }
527 /** The node a line was written after, or undefined: line(id).parent without making the record. */
528 lineParent(id: LineId): NodeId | undefined {
529 const n = this.#lineN(id);
530 return n < 0 ? undefined : this.#nodeName(this.#lineParent.at(n));
531 }
533 // By number, for views (#46) ------------------------------------------------------
534 // A line's n and a node's code (a line's n, or -1 - a path's index for a file's start) as the graph
535 // keeps them, so a view can lay files out as arrays of numbers. For the engine's own use.
537 /** A line id's n, or -1 for an unknown line. */
538 lineN(id: LineId): number {
539 return this.#lineN(id);
540 }
542 /** A line's id from its n. */
543 lineIdOf(n: number): LineId {
544 return this.#lineName(n);
545 }
547 /** The lines an atom deletes, from the graph's own packed copy (#46): never a read of the log. */
548 deletedLines(id: AtomId): readonly LineId[] {
549 const ns = this.#atomDeletes[this.#seq(id)];
550 if (!ns) return EMPTY;
551 const out: LineId[] = new Array(ns.length);
552 for (let i = 0; i < ns.length; i++) out[i] = this.#lineName(ns[i]!);
553 return out;
554 }
556 /** How many lines an atom deletes, without reading its lists. */
557 deleteCount(id: AtomId): number {
558 return this.#atomDeletes[this.#seq(id)]?.length ?? 0;
559 }
561 textOf(n: number): string {
562 return this.#text(n);
563 }
565 /** The seq of the atom that wrote line n. */
566 writerSeqOf(n: number): number {
567 return this.#lineAtom.at(n);
568 }
570 /** Line n's k: its place among its atom's lines. */
571 kOf(n: number): number {
572 return n - this.#lineBase[this.#lineAtom.at(n)]!;
573 }
575 /** The atom id with this seq, as the graph keeps it. */
576 idOfSeq(seq: number): AtomId {
577 return this.#atoms[seq]!.id;
578 }
580 lamportOfSeq(seq: number): number {
581 return this.#lamport[seq]!;
582 }
584 /** The file line n was written in. */
585 writtenIn(n: number): string {
586 return this.#paths[this.#lineFile.at(n)]!;
587 }
589 /** The code of the node line n was written after. */
590 parentCodeOf(n: number): number {
591 return this.#lineParent.at(n);
592 }
594 /** A node's code, or undefined for a node the graph doesn't know (a start node of a file nothing was written in). */
595 codeOf(node: NodeId): number | undefined {
596 return this.#nodeCode(node);
597 }
599 /** The node a code names. */
600 nodeOf(code: number): NodeId {
601 return this.#nodeName(code);
602 }
604 /** The start node's code for a path, or undefined when nothing was ever written in it. */
605 startCodeOf(path: string): number | undefined {
606 const p = this.#pathIndex.get(path);
607 return p === undefined ? undefined : -1 - p;
608 }
610 /** The lines (their n) written right after a node, as childrenOf, into `out`. */
611 childrenN(code: number, out: number[]): void {
612 if (
613 code >= 0 &&
614 code + 1 < this.#lineTotal &&
615 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
616 this.#lineParent.at(code + 1) === code
617 )
618 out.push(code + 1);
619 const starts = this.#runStarts.get(code);
620 if (starts === undefined) return;
621 if (Array.isArray(starts)) out.push(...starts);
622 else out.push(starts);
623 }
625 replacesN(n: number): boolean {
626 return this.#replacing.at(n) === 1;
627 }
629 /** The seqs of every atom that deletes line n (none: an empty list, shared). */
630 deleterSeqsOf(n: number): readonly number[] {
631 const first = this.#deleter.at(n);
632 if (first < 0) return EMPTY;
633 const more = this.#moreDeleters.get(n);
634 return more ? [first, ...more] : [first];
635 }
637 /** Every relocation that puts a line right after the node with this code. */
638 relocatedToCode(code: number): readonly RelocationInfo[] {
639 if (this.#relocatedToCodePages) return [...this.eachRelocatedToCode(code)];
640 return this.#relocatedToCode.get(code) ?? EMPTY;
641 }
642 *eachRelocatedToCode(code: number): IterableIterator<RelocationInfo> {
643 if (this.#relocatedToCodePages) yield* this.#relocatedToCodePages.values(String(code));
644 else yield* this.#relocatedToCode.get(code) ?? EMPTY;
645 }
647 /** How many lines every atom together has written. */
648 get lineCount(): number {
649 return this.#lineTotal;
650 }
652 /** A line id's n, or -1 when no accepted atom wrote it. */
653 #lineN(id: LineId): number {
654 const p = parseLineId(id);
655 if (!p || p.seq >= this.#atoms.length) return -1;
656 const base = this.#lineBase[p.seq]!;
657 const end = p.seq + 1 < this.#lineBase.length ? this.#lineBase[p.seq + 1]! : this.#lineTotal;
658 return p.k < end - base ? base + p.k : -1;
659 }
661 /** A line's id from its n. */
662 #lineName(n: number): LineId {
663 const seq = this.#lineAtom.at(n);
664 return `${this.#atoms[seq]!.id}.${n - this.#lineBase[seq]!}`;
665 }
667 /** A node's code: a line's n, or -1 - a path's index for a start node; undefined when unknown. */
668 #nodeCode(node: NodeId): number | undefined {
669 if (isStartNode(node)) {
670 const p = this.#pathIndex.get(node.slice(1));
671 return p === undefined ? undefined : -1 - p;
672 }
673 const n = this.#lineN(node);
674 return n < 0 ? undefined : n;
675 }
677 #nodeName(code: number): NodeId {
678 return code >= 0 ? this.#lineName(code) : startNode(this.#paths[-1 - code]!);
679 }
681 #pathOf(file: string): number {
682 let p = this.#pathIndex.get(file);
683 if (p === undefined) {
684 p = this.#paths.push(file) - 1;
685 this.#pathIndex.set(file, p);
686 }
687 return p;
688 }
690 /** The line ids an atom inserted, in k order. */
691 linesOf(id: AtomId): LineId[] {
692 const atom = this.atom(id);
693 const out: LineId[] = [];
694 const seq = atom.seq;
695 const count = (seq + 1 < this.#lineBase.length ? this.#lineBase[seq + 1]! : this.#lineTotal) - this.#lineBase[seq]!;
696 for (let k = 0; k < count; k++) out.push(lineId(id, k));
697 return out;
698 }
700 /** Every atom that deletes this line (across the whole graph). */
701 deletersOf(line: LineId): readonly AtomId[] {
702 const n = this.#lineN(line);
703 if (n < 0) return EMPTY;
704 const first = this.#deleter.at(n);
705 if (first < 0) return EMPTY;
706 const more = this.#moreDeleters.get(n);
707 const out = [this.#atoms[first]!.id];
708 if (more) for (const seq of more) out.push(this.#atoms[seq]!.id);
709 return out;
710 }
712 writersOf(key: Key): readonly AtomId[] {
713 return [...this.eachWriterOf(key)];
714 }
715 *eachWriterOf(key: Key): IterableIterator<AtomId> {
716 const code = this.#code(key);
717 if (this.#writersPages) yield* this.#writersPages.values(JSON.stringify([typeof code, code]));
718 else yield* listOf(this.#writers.get(code));
719 }
721 /** Atoms whose implicit reads include the key. */
722 readersOf(key: Key): readonly AtomId[] {
723 return [...this.eachReaderOf(key)];
724 }
725 *eachReaderOf(key: Key): IterableIterator<AtomId> {
726 const code = this.#code(key);
727 if (this.#readersPages) yield* this.#readersPages.values(JSON.stringify([typeof code, code]));
728 else yield* listOf(this.#readers.get(code));
729 }
731 /** Atoms whose explicit holds include the key. */
732 holdersOf(key: Key): readonly AtomId[] {
733 return [...this.eachHolderOf(key)];
734 }
735 *eachHolderOf(key: Key): IterableIterator<AtomId> {
736 const code = this.#code(key);
737 if (this.#holdersPages) yield* this.#holdersPages.values(JSON.stringify([typeof code, code]));
738 else yield* listOf(this.#holders.get(code));
739 }
741 /** Every atom that inserts or deletes a line of the file, in seq order. */
742 atomsIn(file: string): readonly AtomId[] {
743 if (this.#fileAtomPages) return [...this.#fileAtomPages.values(file)];
744 return this.#fileAtoms.get(file) ?? EMPTY;
745 }
746 *eachAtomIn(file: string): IterableIterator<AtomId> {
747 if (this.#fileAtomPages) yield* this.#fileAtomPages.values(file);
748 else yield* this.#fileAtoms.get(file) ?? EMPTY;
749 }
750 hasAtomsIn(file: string): boolean {
751 return this.#fileAtomPages ? this.#fileAtomPages.length(file) > 0 : this.#fileAtoms.has(file);
752 }
754 /** Unique historical file paths, streamed without collecting their names. */
755 *knownFiles(): IterableIterator<string> {
756 yield* this.#fileAtomPages ? this.#fileAtomPages.keys() : this.#fileAtoms.keys();
757 }
759 /**
760 * The files an atom inserts, deletes or moves lines in, or sets attributes
761 * of, sorted. For lines, the file each was written in (or, for a move to a
762 * start node, that file): a set's moves can have taken them elsewhere.
763 */
764 filesOf(id: AtomId): readonly string[] {
765 this.atom(id);
766 return this.#atomFiles[this.#seq(id)]!;
767 }
769 /** Lines written right after a node (not counting moves), in seq order. */
770 childrenOf(node: NodeId): LineId[] {
771 const out: LineId[] = [];
772 const code = this.#nodeCode(node);
773 if (code === undefined) return out;
774 // The next line of the same run hangs off this one.
775 if (
776 code >= 0 &&
777 code + 1 < this.#lineTotal &&
778 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
779 this.#lineParent.at(code + 1) === code
780 ) {
781 out.push(this.#lineName(code + 1));
782 }
783 for (const n of listOf(this.#runStarts.get(code))) out.push(this.#lineName(n));
784 return out;
785 }
787 /** Whether a line starts a run whose atom deleted the line it hangs off. */
788 replaces(line: LineId): boolean {
789 const n = this.#lineN(line);
790 return n >= 0 && this.#replacing.at(n) === 1;
791 }
793 /** Every relocation of a line, in seq order. */
794 relocationsOf(line: LineId): readonly RelocationInfo[] {
795 if (this.#relocationPages) return [...this.eachRelocationOf(line)];
796 return this.#relocations.get(line) ?? EMPTY;
797 }
798 *eachRelocationOf(line: LineId): IterableIterator<RelocationInfo> {
799 if (this.#relocationPages) yield* this.#relocationPages.values(line);
800 else yield* this.#relocations.get(line) ?? EMPTY;
801 }
803 /** Every relocation that puts a line right after this node, in seq order. */
804 relocatedTo(node: NodeId): readonly RelocationInfo[] {
805 if (this.#relocatedToPages) return [...this.#relocatedToPages.values(node)];
806 return this.#relocatedTo.get(node) ?? EMPTY;
807 }
809 /** Atoms that move lines, in seq order. */
810 movers(): readonly AtomId[] {
811 return this.#movers;
812 }
814 /** Atoms that list this one directly in their deps. */
815 dependentsOf(id: AtomId): readonly AtomId[] {
816 return [...this.eachDependentOf(id)];
817 }
818 *eachDependentOf(id: AtomId): IterableIterator<AtomId> {
819 if (this.#dependentsPages) yield* this.#dependentsPages.values(id);
820 else yield* listOf(this.#dependents.get(id));
821 }
823 /** Atoms whose `resolves` names this one. */
824 resolversOf(id: AtomId): readonly AtomId[] {
825 return [...this.eachResolverOf(id)];
826 }
827 *eachResolverOf(id: AtomId): IterableIterator<AtomId> {
828 if (this.#resolversPages) yield* this.#resolversPages.values(id);
829 else yield* listOf(this.#resolvers.get(id));
830 }
832 /** `together` reasons touching this atom, in either direction. */
833 togetherLinks(id: AtomId): readonly TogetherLink[] {
834 return this.#together.get(id) ?? EMPTY;
835 }
837 /**
838 * The atom plus everything it depends on, transitively. Computed on demand
839 * and not cached: a cached set per atom costs memory quadratic in the length
840 * of a dependency chain. Use `dependsOn` to ask about one pair.
841 */
842 closure(id: AtomId): Set<AtomId> {
843 return this.closureOf([id]);
844 }
846 /** The atoms plus everything they depend on, transitively. */
847 closureOf(ids: Iterable<AtomId>): Set<AtomId> {
848 const out = new Set<AtomId>();
849 const stack: AtomId[] = [];
850 for (const id of ids) {
851 this.atom(id);
852 if (!out.has(id)) {
853 out.add(id);
854 stack.push(id);
855 }
856 }
857 while (stack.length > 0) {
858 for (const d of this.atom(stack.pop()!).deps) {
859 if (!out.has(d)) {
860 out.add(d);
861 stack.push(d);
862 }
863 }
864 }
865 return out;
866 }
868 /** Whether `b` is in the closure of `a` (an atom is in its own closure). */
869 dependsOn(a: AtomId, b: AtomId): boolean {
870 const atom = this.atom(a);
871 this.atom(b);
872 return a === b || this.#reaches(atom.deps, b);
873 }
875 /**
876 * Whether `target` is reachable along deps from any of `from` (themselves
877 * included). A dependency always has a lower lamport than its dependent, so
878 * the search never descends below the target's lamport.
879 */
880 #reaches(from: Iterable<AtomId>, target: AtomId): boolean {
881 const floor = this.#lamport[this.#seq(target)]!;
882 const seen = new Set<AtomId>();
883 const stack = [...from];
884 while (stack.length > 0) {
885 const cur = stack.pop()!;
886 if (cur === target) return true;
887 if (seen.has(cur)) continue;
888 seen.add(cur);
889 if (this.#lamport[this.#seq(cur)]! <= floor) continue;
890 for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);
891 }
892 return false;
893 }
895 /**
896 * Accept an atom into the graph. It must carry the next id and seq, and
897 * everything it touches must come from atoms in its dependency closure.
898 * The atom is frozen. Adding to the graph does not add it to any set.
899 */
900 add(atom: Atom): void {
901 if (this.#storage) this.#storage.transaction(() => this.#add(atom));
902 else this.#add(atom);
903 }
905 #add(atom: Atom): void {
906 validateShape(atom);
907 const seq = this.#atoms.length;
908 const bad = (why: string): never => {
909 throw new EngineError("bad-atom", `atom ${atom.id}: ${why}`);
910 };
911 if (atom.seq !== seq || atom.id !== atomId(seq)) bad(`expected id ${atomId(seq)} with seq ${seq}`);
913 const deps = new Set<AtomId>();
914 for (const d of atom.deps) {
915 if (!this.has(d)) bad(`dependency ${d} is not in the graph`);
916 if (deps.has(d)) bad(`dependency ${d} listed twice`);
917 deps.add(d);
918 }
919 for (const d of [...atom.needs, ...atom.resolves]) {
920 if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);
921 }
922 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);
924 // Everything it touches must come from its closure. Derived deps name the
925 // writers directly, so this is usually one lookup per writer.
926 const below = new Map<AtomId, boolean>();
927 const inClosure = (writer: AtomId): boolean => {
928 let hit = below.get(writer);
929 if (hit === undefined) {
930 hit = deps.has(writer) || this.#reaches(deps, writer);
931 below.set(writer, hit);
932 }
933 return hit;
934 };
935 const checkLine = (line: LineId, what: string): void => {
936 const writer = this.lineAtom(line);
937 if (writer === undefined) return bad(`${what} names unknown line ${line}`);
938 if (!inClosure(writer)) bad(`${what} names line ${line} but ${writer} is not in its closure`);
939 };
941 for (const run of atom.inserts) {
942 if (isStartNode(run.parent)) {
943 if (run.parent !== startNode(run.file)) bad(`run in ${run.file} starts at ${run.parent}`);
944 } else {
945 // The parent may have been moved into run.file, so its own file can differ.
946 checkLine(run.parent, "an insert");
947 }
948 }
949 const moved = new Set<LineId>();
950 for (const m of atom.moves ?? []) {
951 checkLine(m.line, "a move");
952 if (!isStartNode(m.parent)) checkLine(m.parent, "a move");
953 if (m.line === m.parent) bad(`moves ${m.line} after itself`);
954 if (moved.has(m.line)) bad(`moves ${m.line} twice`);
955 moved.add(m.line);
956 if (!atom.writes.includes(posKey(m.line)) || !atom.writes.includes(gapKey(m.parent))) {
957 bad(`moves ${m.line} without writing ${posKey(m.line)} and ${gapKey(m.parent)}`);
958 }
959 }
960 const deleted = new Set<LineId>();
961 for (const line of atom.deletes) {
962 checkLine(line, "a delete");
963 if (deleted.has(line)) bad(`deletes ${line} twice`);
964 deleted.add(line);
965 }
966 const writes = new Set(atom.writes);
967 for (const line of deleted) if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);
968 for (const key of [...atom.writes, ...atom.reads, ...atom.holds]) {
969 const parsed = parseKey(key);
970 if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`);
971 else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))
972 checkLine(parsed.node, `key ${key}`);
973 }
975 // Accept.
976 const frozen = freezeAtom(
977 atom,
978 (id) => this.#atoms[seqOf(id)]!.id,
979 (author) => {
980 if (this.#storage) return author;
981 let a = this.#authors.get(author);
982 if (a === undefined) this.#authors.set(author, (a = author));
983 return a;
984 },
985 this.#texts ? this.#reader(seq) : undefined,
986 this.#lists ? this.#listReader(seq) : undefined,
987 );
988 this.#atoms.push(this.#storage ? atom : frozen);
989 let lam = 0;
990 for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1);
991 this.#lamport.push(lam);
993 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist.
994 // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log.
995 const deletes = atom.deletes.length > 0 ? new Set(atom.deletes) : undefined;
996 const deletedN = atom.deletes.map((line) => this.#lineN(line));
997 this.#atomDeletes.push(deletedN.length > 0 ? (this.#storage ? deletedN : Int32Array.from(deletedN)) : undefined);
998 this.#lineBase.push(this.#lineTotal);
999 for (const run of atom.inserts) {
1000 const file = this.#pathOf(run.file);
1001 let parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent);
1002 const first = this.#lineTotal;
1003 pushOne(this.#runStarts, parent, first);
1004 for (let i = 0; i < run.lines.length; i++) {
1005 const n = this.#lineTotal;
1006 this.#lineAtom.push(seq);
1007 this.#lineFile.push(file);
1008 this.#lineParent.push(parent);
1009 this.#lineText?.push(run.lines[i]!);
1010 this.#deleter.push(-1);
1011 this.#replacing.push(i === 0 && deletes?.has(run.parent) ? 1 : 0);
1012 parent = n;
1015 (frozen.moves ?? []).forEach((m, i) => {
1016 const info: RelocationInfo = Object.freeze({ atom: frozen.id, line: m.line, parent: m.parent, k: i });
1017 if (this.#relocationPages) this.#relocationPages.append(m.line, info);
1018 else pushIndex(this.#relocations, m.line, info);
1019 if (this.#relocatedToPages) this.#relocatedToPages.append(m.parent, info);
1020 else pushIndex(this.#relocatedTo, m.parent, info);
1021 const parentCode = isStartNode(m.parent) ? -1 - this.#pathOf(m.parent.slice(1)) : this.#lineN(m.parent);
1022 if (this.#relocatedToCodePages) this.#relocatedToCodePages.append(String(parentCode), info);
1023 else pushIndex(this.#relocatedToCode, parentCode, info);
1024 });
1025 if (frozen.moves) this.#movers.push(frozen.id);
1026 for (const n of deletedN) {
1027 if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);
1028 else pushIndex(this.#moreDeleters, n, seq);
1030 for (const key of new Set(atom.writes)) {
1031 const code = this.#code(key);
1032 if (this.#writersPages) this.#writersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1033 else pushOne(this.#writers, code, frozen.id);
1035 for (const key of new Set(atom.reads)) {
1036 const code = this.#code(key);
1037 if (this.#readersPages) this.#readersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1038 else pushOne(this.#readers, code, frozen.id);
1040 for (const key of new Set(atom.holds)) {
1041 const code = this.#code(key);
1042 if (this.#holdersPages) this.#holdersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1043 else pushOne(this.#holders, code, frozen.id);
1045 for (const d of deps) {
1046 if (this.#dependentsPages) this.#dependentsPages.append(d, frozen.id);
1047 else pushOne(this.#dependents, d, frozen.id);
1049 for (const r of new Set(frozen.resolves)) {
1050 if (this.#resolversPages) this.#resolversPages.append(r, frozen.id);
1051 else pushOne(this.#resolvers, r, frozen.id);
1053 const files = new Set<string>();
1054 for (const run of atom.inserts) files.add(run.file);
1055 for (const n of deletedN) files.add(this.#paths[this.#lineFile.at(n)]!);
1056 for (const a of frozen.attrs ?? []) files.add(a.file);
1057 for (const m of frozen.moves ?? []) {
1058 files.add(this.lineFile(m.line)!);
1059 files.add(isStartNode(m.parent) ? m.parent.slice(1) : this.lineFile(m.parent)!);
1061 this.#atomFiles.push(Object.freeze([...files].sort()));
1062 for (const file of files) {
1063 if (this.#fileAtomPages) this.#fileAtomPages.append(file, frozen.id);
1064 else pushIndex(this.#fileAtoms, file, frozen.id);
1066 for (const r of frozen.reasons) {
1067 if (r.kind !== "together" || r.to === frozen.id) continue;
1068 pushIndex(this.#together, frozen.id, { other: r.to, text: r.text, from: frozen.id });
1069 pushIndex(this.#together, r.to, { other: frozen.id, text: r.text, from: frozen.id });
1073 // Labels -----------------------------------------------------------------
1075 /**
1076 * Add or replace a label. Label names may not look like atom ids. A base is
1077 * resolved to its head only when it is used, never followed further, so
1078 * bases may name each other in any shape.
1079 */
1080 setLabel(label: Label): void {
1081 this.#putLabel(label, (name) => this.#labels.has(name));
1084 #putLabel(label: Label, isLabel: (name: string) => boolean): void {
1085 const bad = (why: string): never => {
1086 throw new EngineError("bad-label", `label ${JSON.stringify(label?.name)}: ${why}`);
1087 };
1088 if (typeof label !== "object" || label === null) bad("not an object");
1089 if (typeof label.name !== "string" || label.name === "") bad("needs a name");
1090 if (isAtomId(label.name)) bad("a label name may not look like an atom id");
1091 if (!this.has(label.head)) bad(`head ${label.head} is not in the graph`);
1092 if (
1093 label.base !== undefined &&
1094 !(typeof label.base === "string" && (isLabel(label.base) || this.has(label.base)))
1095 ) {
1096 bad(`base ${label.base} is neither a label nor an atom`);
1098 if (label.base === label.name) bad("a label cannot be its own base");
1099 if (typeof label.title !== "string" || typeof label.message !== "string") bad("needs a title and message");
1100 if (label.follows !== undefined && !Array.isArray(label.follows)) bad("follows must be a list of label names");
1101 const copy: Label = {
1102 name: label.name,
1103 head: label.head,
1104 ...(label.base !== undefined ? { base: label.base } : {}),
1105 title: label.title,
1106 message: label.message,
1107 ...(label.follows !== undefined ? { follows: Object.freeze([...label.follows]) } : {}),
1108 };
1109 this.#labels.set(label.name, Object.freeze(copy));
1112 label(name: string): Label | undefined {
1113 return this.#labels.get(name);
1116 /** Labels sorted by name. */
1117 labels(): Label[] {
1118 return [...this.#labels.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1121 /**
1122 * Remove a label. Labels that used it as their base get its head atom as
1123 * their base instead, so their contents don't change.
1124 */
1125 removeLabel(name: string): boolean {
1126 return this.#storage ? this.#storage.transaction(() => this.#removeLabel(name)) : this.#removeLabel(name);
1129 #removeLabel(name: string): boolean {
1130 const gone = this.#labels.get(name);
1131 if (!gone) return false;
1132 this.#labels.delete(name);
1133 for (const label of [...this.#labels.values()]) {
1134 if (label.base === name) this.#labels.set(label.name, Object.freeze({ ...label, base: gone.head }));
1136 return true;
1139 // JSON -------------------------------------------------------------------
1141 toJSON(): GraphJSON {
1142 return { format: GRAPH_FORMAT, version: 1, atoms: this.#atoms, labels: this.labels() };
1145 /** Load a saved graph. Every atom is re-validated as it is added. */
1146 static fromJSON(data: unknown): Graph {
1147 const bad = (why: string): never => {
1148 throw new EngineError("bad-json", why);
1149 };
1150 if (typeof data !== "object" || data === null) bad("graph JSON must be an object");
1151 const obj = data as Partial<GraphJSON>;
1152 if (obj.format !== GRAPH_FORMAT) bad(`format must be ${GRAPH_FORMAT}`);
1153 if (obj.version !== 1) bad(`unsupported version ${String(obj.version)}`);
1154 if (!Array.isArray(obj.atoms) || !Array.isArray(obj.labels)) bad("atoms and labels must be arrays");
1155 const graph = new Graph();
1156 for (const atom of obj.atoms!) graph.add(atom);
1157 // Labels may name each other as bases, in any order and any shape.
1158 const names = new Set<string>();
1159 for (const label of obj.labels!) {
1160 const name: unknown = (label as Partial<Label> | null)?.name;
1161 if (typeof name !== "string") return bad("every label needs a name");
1162 if (names.has(name)) bad(`label ${name} appears twice`);
1163 names.add(name);
1165 for (const label of obj.labels!) {
1166 try {
1167 graph.#putLabel(label, (name) => names.has(name));
1168 } catch (err) {
1169 if (err instanceof EngineError) bad(err.message);
1170 throw err;
1173 return graph;
1176 #seq(id: AtomId): number {
1177 return typeof id === "string" ? seqOf(id) : -1;
1181function validateShape(atom: Atom): void {
1182 const bad = (why: string): never => {
1183 throw new EngineError("bad-atom", `atom ${String((atom as { id?: unknown }).id)}: ${why}`);
1184 };
1185 if (typeof atom !== "object" || atom === null) bad("not an object");
1186 if (typeof atom.id !== "string" || !Number.isInteger(atom.seq)) bad("needs id and seq");
1187 if (typeof atom.author !== "string" || typeof atom.message !== "string") bad("needs author and message");
1188 if (typeof atom.time !== "number" || !Number.isFinite(atom.time)) bad("time must be a finite number");
1189 const lists = ["inserts", "deletes", "writes", "reads", "holds", "needs", "resolves", "reasons", "deps"] as const;
1190 for (const name of lists) if (!Array.isArray(atom[name])) bad(`${name} must be an array`);
1191 for (const run of atom.inserts as readonly InsertRun[]) {
1192 if (typeof run.file !== "string" || run.file === "" || run.file.includes("\n")) bad("a run needs a file path");
1193 if (typeof run.parent !== "string") bad("a run needs a parent");
1194 if (!Array.isArray(run.lines) || run.lines.length === 0) bad("a run needs at least one line");
1195 for (const text of run.lines) {
1196 if (typeof text !== "string" || text.includes("\n") || text.includes("\r"))
1197 bad("run lines must be strings without line breaks");
1200 if (atom.attrs !== undefined) {
1201 if (!Array.isArray(atom.attrs)) bad("attrs must be an array");
1202 for (const a of atom.attrs) {
1203 if (typeof a?.file !== "string" || a.file === "" || a.file.includes("\n") || !ATTR_NAMES.includes(a.name))
1204 bad("an attr needs a file and a name");
1205 if (a.value !== null && typeof a.value !== "string") bad("an attr value is a string or null");
1206 if (!atom.writes.includes(attrKey(a.file, a.name))) bad(`sets ${a.name} of ${a.file} without writing its key`);
1209 if (atom.moves !== undefined) {
1210 if (!Array.isArray(atom.moves) || atom.moves.length === 0) bad("moves must be a non-empty array");
1211 for (const m of atom.moves) {
1212 if (typeof m?.line !== "string" || typeof m.parent !== "string") bad("a move needs a line and a parent");
1215 for (const name of ["deletes", "writes", "reads", "holds", "needs", "resolves", "deps"] as const) {
1216 for (const x of atom[name]) if (typeof x !== "string") bad(`${name} must hold strings`);
1218 for (const r of atom.reasons as readonly Reason[]) {
1219 if (typeof r.to !== "string" || typeof r.text !== "string" || !REASON_KINDS.includes(r.kind)) {
1220 bad("a reason needs to, kind (together, because-of or supersedes) and text");
1225/**
1226 * A frozen copy of an atom. An empty list is one shared frozen list, and atom
1227 * ids and authors are the graph's own strings (`canon`, `author`), so each is
1228 * kept once however often it's named (#46).
1229 */
1230function freezeAtom(
1231 atom: Atom,
1232 canon: (id: AtomId) => AtomId,
1233 author: (name: string) => string,
1234 text?: (start: number, length: number) => readonly string[],
1235 lists?: () => AtomLists,
1236): Atom {
1237 const list = <T>(xs: readonly T[], f?: (x: T) => T): readonly T[] =>
1238 xs.length === 0 ? EMPTY : Object.freeze(f ? xs.map(f) : [...xs]);
1239 // With text kept elsewhere (#46), a run's lines are read when asked for.
1240 let k = 0;
1241 const run = (r: InsertRun): InsertRun => {
1242 if (!text) return Object.freeze({ file: r.file, parent: r.parent, lines: Object.freeze([...r.lines]) });
1243 const start = k;
1244 const length = r.lines.length;
1245 k += length;
1246 return Object.freeze(new LazyRun(r.file, r.parent, text, start, length));
1247 };
1248 const copy: Atom = {
1249 id: atom.id,
1250 seq: atom.seq,
1251 author: author(atom.author),
1252 message: atom.message,
1253 time: atom.time,
1254 inserts: Object.freeze(atom.inserts.map(run)),
1255 ...(lists
1256 ? {}
1257 : { deletes: list(atom.deletes), writes: list(atom.writes), reads: list(atom.reads), holds: list(atom.holds) }),
1258 needs: list(atom.needs, canon),
1259 resolves: list(atom.resolves, canon),
1260 reasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })),
1261 deps: list(atom.deps, canon),
1262 ...(atom.attrs && atom.attrs.length > 0
1263 ? { attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))) }
1264 : {}),
1265 ...(atom.moves
1266 ? { moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))) }
1267 : {}),
1268 } as Atom;
1269 return Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);