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/view.ts?version=231&format=json
1,094 linescapacity 39% · First import 34% · codex-capacity-chair 22% · codex-capacity-policy 4%Last change capacity in version 231, 30 versions changed it

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

1// Projection: the files a closed set of atoms produces. A pure function of the
2// set. Each file is a tree of lines hanging off its start node; linearizing it
3// depth-first, children in descending priority, gives the file's sequence. A
4// line hangs off the node it was written after, unless a move in the set gave
5// it another parent (#28): then the newest such move decides.
6//
7// A laid-out file is kept as arrays of line numbers (the graph's n), not as a
8// record per line (#46): a record, its id and two index entries cost about
9// 370 bytes a line, and the view cache holds up to 200,000 lines. Records are
10// made when a caller asks for them, and the latest asked for is kept.
12import type { Graph, RelocationInfo } from "./graph.ts";
13import { isStartNode, seqOf } from "./keys.ts";
14import { resolveScratchMoves, scratchLayoutNodes } from "./relocation-scratch.ts";
15import { isClosedSet, StableSet } from "./state-source.ts";
16import { joinLines } from "./text.ts";
17import { type AtomId, type AtomSet, EngineError, type LineId, type NodeId } from "./types.ts";
19/** A line in a file's full sequence, tombstones included. */
20export interface SeqLine {
21 readonly id: LineId;
22 readonly text: string;
23 /** The atom that wrote it. */
24 readonly atom: AtomId;
25 /** Atoms in the set that delete it, by seq. Empty when it is visible. */
26 readonly deletedBy: readonly AtomId[];
27 readonly visible: boolean;
30/** A visible line of a projected file. */
31export interface VisibleLine {
32 readonly textChunks?: () => Iterable<string>;
33 readonly id: LineId;
34 readonly text: string;
35 readonly atom: AtomId;
38/** A file's attributes in a view. */
39export interface FileAttrs {
40 /** Kept with no lines (an empty file). */
41 readonly exists: boolean;
42 readonly exec: boolean;
43 /** The target, when the file is a symbolic link. */
44 readonly link: string | null;
45 /** The SHA-256 of its bytes, when the file is binary. */
46 readonly blob: string | null;
49/** Structural read boundary shared by historical and transaction-bound projections. */
50export type ReadView = Omit<
51 Pick<View, keyof View>,
52 "sameText" | "visibleCount" | "shareMoves" | "fileOfNumber" | "lineNumberOf" | "visibleWriters"
53> & {
54 sameText(path: string, other: ReadView): boolean;
55};
57const NO_ATTRS: FileAttrs = { exists: false, exec: false, link: null, blob: null };
58const NONE: readonly never[] = Object.freeze([]);
60interface FileState {
61 readonly attrs: FileAttrs;
62 /** Full history is retained only when a sequence caller explicitly requests it. */
63 readonly complete: boolean;
64 /** The file's sequence, tombstones included: each line's n. */
65 readonly seq: Int32Array;
66 /** Its visible lines' n, in order. */
67 readonly vis: Int32Array;
68 /** For each deleted position in seq: the seqs of the atoms in the set that delete it, by priority. */
69 readonly deletedBy: ReadonlyMap<number, readonly number[]>;
70 /** Its visible lines' text, when laid out from the file's packed history: null for a line too long to pack. */
71 readonly visText?: readonly (string | null)[];
72 /** Its visible lines' writers' seqs, when laid out from the file's packed history. */
73 readonly visWriter?: Int32Array;
74 /** Positions by n, built the first time they're asked for. */
75 seqIndex?: Map<number, number>;
76 visIndex?: Map<number, number>;
79interface Child {
80 readonly n: number;
81 /** 1 when the child's atom deleted the parent (the child replaces it), else 0. A moved line is 0. */
82 readonly replaces: number;
83 readonly lamport: number;
84 readonly seq: number;
85 readonly k: number;
88const EMPTY_INTS = new Int32Array(0);
89const NO_FILE: FileState = { attrs: NO_ATTRS, complete: true, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() };
91// Approximate retained-container costs for View.weight(): reference slots,
92// object headers, and map/set entries. These are cache-budget units, not V8
93// heap measurements. Referenced Graph strings and records are not charged.
94const ARRAY_HEADER_BYTES = 24;
95const OBJECT_BYTES = 32;
96const MAP_HEADER_BYTES = 32;
97const MAP_ENTRY_BYTES = 40;
98const SET_ENTRY_BYTES = 32;
99const REFERENCE_BYTES = 8;
100/**
101 * Moved lines a view resolves once and keeps (abso Capacity): a stored graph otherwise resolved every move again on
102 * disk for each file it laid out. Game's whole history has 290; past this many, the view goes back to that.
103 */
104export const MOVED_LINES_KEPT = 20_000;
105class TooManyMoves extends Error {}
106const NO_LINES: readonly number[] = Object.freeze([]);
107/** Nodes whose nearest moved line above a graph remembers, at most: about 40 bytes each. */
108const CLIMB_MEMO = 200_000;
110/** One relocation of a moved line, with its line's number and its new parent's code. */
111interface MoveEntry {
112 readonly n: number;
113 readonly r: RelocationInfo;
114 readonly parent: number;
117/**
118 * A graph's moves, whatever the set (abso Capacity): each mover's moved lines, each moved line's relocations in seq
119 * order, and for any node the nearest node at or above it, by where lines were written, that a move ever relocated,
120 * or its file's start. Worked out once per graph and extended as it grows. A view's moves then resolve over the moved
121 * lines alone: before, every view walked each moved line's file up to its start, a read per line.
122 */
123class MoveSkeleton {
124 readonly #graph: Graph;
125 #seen = 0;
126 /** Movers in seq order, with the numbers of the lines each moves, in its moves' order. */
127 readonly movers: { readonly seq: number; readonly lines: readonly number[] }[] = [];
128 /** Every relocation of each moved line, by the line's number, in seq order. */
129 readonly byLine = new Map<number, MoveEntry[]>();
130 readonly #climbed = new Map<number, number>();
132 constructor(graph: Graph) {
133 this.#graph = graph;
134 }
136 /** Take in movers the graph gained since. */
137 update(): this {
138 const graph = this.#graph;
139 const all = graph.movers();
140 if (this.#seen === all.length) return this;
141 for (; this.#seen < all.length; this.#seen++) {
142 const id = all[this.#seen]!;
143 const lines: number[] = [];
144 graph.atom(id).moves!.forEach((m, k) => {
145 const n = graph.lineN(m.line);
146 const r: RelocationInfo = Object.freeze({ atom: id, line: m.line, parent: m.parent, k });
147 const entry: MoveEntry = { n, r, parent: graph.codeOf(m.parent)! };
148 const list = this.byLine.get(n);
149 if (list) list.push(entry);
150 else this.byLine.set(n, [entry]);
151 lines.push(n);
152 });
153 this.movers.push({ seq: seqOf(id), lines });
154 }
155 // A new moved line can sit between a node and the one it climbed to.
156 this.#climbed.clear();
157 return this;
158 }
160 /** The nearest node at or above this one, by where lines were written, that a move ever relocated; or its file's start. */
161 climb(code: number): number {
162 const walked: number[] = [];
163 let c = code;
164 while (c >= 0 && !this.byLine.has(c)) {
165 const known = this.#climbed.get(c);
166 if (known !== undefined) {
167 c = known;
168 break;
169 }
170 walked.push(c);
171 c = this.#graph.parentCodeOf(c);
172 }
173 if (this.#climbed.size + walked.length > CLIMB_MEMO) this.#climbed.clear();
174 for (const w of walked) this.#climbed.set(w, c);
175 return c;
176 }
179const skeletons = new WeakMap<Graph, MoveSkeleton>();
180function skeletonOf(graph: Graph): MoveSkeleton {
181 let skeleton = skeletons.get(graph);
182 if (!skeleton) skeletons.set(graph, (skeleton = new MoveSkeleton(graph)));
183 return skeleton.update();
186/**
187 * The projection of a closed set. Construct once, then ask for files, lines
188 * and sequences. Throws `not-closed` if some atom's dependency is missing.
189 * Each file is laid out the first time it is asked for, so a view of a large
190 * set costs little until files are read.
191 */
192export class View {
193 readonly graph: Graph;
194 /** The set, made from #in the first time it's asked for: a view keeps a byte per atom, not a copy of the set (#46). */
195 #set: AtomSet | undefined;
196 readonly #stable: StableSet<AtomId> | undefined;
197 /** Fixed-size memo for immutable indexed membership, independent of history size. */
198 #membershipSeq = new Float64Array(256).fill(-1);
199 #membershipValue = new Uint8Array(256);
200 #files = new Map<string, FileState>();
201 /** Every file the set wrote in, sorted; worked out the first time it's asked for. */
202 #knownList: string[] | undefined;
203 /** 1 for each atom (by seq) in the set. */
204 #in: Uint8Array;
205 /** Atoms in the set that move lines. */
206 #movers: AtomId[] | undefined;
207 #hasMoves = false;
208 /** Each moved line's relocation that counts in this set; built on first use. */
209 #relocs: Map<LineId, RelocationInfo> | undefined;
210 /** The same, by n, with the new parent's code. */
211 #relocsN: Map<number, { readonly r: RelocationInfo; readonly parent: number }> | undefined;
212 /** The moved lines under each node, by its code, made from the relocations on first use. */
213 #movedInto: Map<number, number[]> | undefined;
214 /** Whether this view's moves are too many to keep, so they're resolved on disk per layout; undefined until asked. */
215 #movesOnDisk: boolean | undefined;
216 /** The latest records asked for: one file's lines, one file's sequence, one file's text. */
217 #linesCache: { path: string; lines: readonly VisibleLine[] } | undefined;
218 #seqCache: { path: string; seq: readonly SeqLine[] } | undefined;
219 #textCache: { path: string; text: string } | undefined;
221 constructor(graph: Graph, set: Iterable<AtomId>) {
222 this.graph = graph;
223 if (set instanceof StableSet) {
224 this.#stable = set;
225 this.#set = set;
226 this.#in = new Uint8Array(0);
227 // A set kept closed when it was written needs no proof here (abso Capacity).
228 for (const id of isClosedSet(set) ? [] : set) {
229 const atom = graph.atom(id);
230 for (const dependency of atom.deps) {
231 graph.atom(dependency);
232 if (!set.has(dependency))
233 throw new EngineError("not-closed", `set is not closed: ${id} depends on ${dependency}`);
234 }
235 }
236 for (const id of graph.movers()) {
237 if (set.has(id)) {
238 this.#hasMoves = true;
239 break;
240 }
241 }
242 this.#relocs = this.#hasMoves ? undefined : new Map();
243 this.#relocsN = this.#hasMoves ? undefined : new Map();
244 return;
245 }
246 const inSet = new Uint8Array(graph.size);
247 // An atom's number is in its id (abso Capacity): reading the atom for it read the whole history on a stored graph.
248 const seqIn = (id: AtomId): number => {
249 const seq = seqOf(id);
250 return seq >= 0 && seq < inSet.length && graph.idOfSeq(seq) === id ? seq : graph.atom(id).seq;
251 };
252 for (const id of set) inSet[seqIn(id)] = 1;
253 // Validate one atom at a time. Keeping all decoded atoms here defeats
254 // storage-backed Graph reads even though the view only needs membership.
255 for (let seq = 0; seq < inSet.length; seq++) {
256 if (inSet[seq] !== 1) continue;
257 const atom = graph.atom(graph.idOfSeq(seq));
258 for (const d of atom.deps) {
259 if (inSet[seqIn(d)] !== 1) throw new EngineError("not-closed", `set is not closed: ${atom.id} depends on ${d}`);
260 }
261 }
262 this.graph = graph;
263 this.#in = inSet;
264 this.#movers = graph.movers().filter((id) => inSet[seqOf(id)] === 1);
265 this.#hasMoves = this.#movers.length > 0;
266 this.#relocs = this.#movers.length === 0 ? new Map() : undefined;
267 this.#relocsN = this.#movers.length === 0 ? new Map() : undefined;
268 }
270 /** The set of atoms this view projects. */
271 get set(): AtomSet {
272 if (!this.#set) {
273 const out = new Set<AtomId>();
274 for (let seq = 0; seq < this.#in.length; seq++) if (this.#in[seq] === 1) out.add(this.graph.idOfSeq(seq));
275 this.#set = out;
276 }
277 return this.#set;
278 }
280 /** Whether the atom with this seq is in the set. */
281 #has(seq: number): boolean {
282 if (this.#stable) {
283 const slot = seq % this.#membershipSeq.length;
284 if (this.#membershipSeq[slot] === seq) return this.#membershipValue[slot] === 1;
285 const present = this.#stable.has(this.graph.idOfSeq(seq));
286 this.#membershipSeq[slot] = seq;
287 this.#membershipValue[slot] = present ? 1 : 0;
288 return present;
289 }
290 return seq < this.#in.length && this.#in[seq] === 1;
291 }
293 /**
294 * The relocation that counts for each moved line: the newest (by priority)
295 * in the set. Two moves made apart can loop lines into each other, so no
296 * start node reaches them; then the oldest relocation on the loop is
297 * ignored, and the next newest of that line counts, until none loop.
298 */
299 #relocations(): Map<LineId, RelocationInfo> {
300 if (this.#relocs) return this.#relocs;
301 this.#takeShared();
302 if (this.#relocs) return this.#relocs;
303 const graph = this.graph;
304 const skeleton = skeletonOf(graph);
305 const stronger = (a: RelocationInfo, b: RelocationInfo): boolean => graph.comparePriority(a.atom, b.atom) > 0;
306 const identity = (r: RelocationInfo): string => JSON.stringify([r.atom, r.k]);
307 const ignored = new Set<string>();
308 const pick = (n: number): MoveEntry | undefined => {
309 let best: MoveEntry | undefined;
310 for (const e of skeleton.byLine.get(n) ?? []) {
311 if (this.#has(seqOf(e.r.atom)) && !ignored.has(identity(e.r)) && (!best || stronger(e.r, best.r))) best = e;
312 }
313 return best;
314 };
315 // By the moved line's number, in the order its movers come (seq order, then each mover's moves).
316 const relocs = new Map<number, MoveEntry>();
317 for (const mover of skeleton.movers) {
318 if (!this.#has(mover.seq)) continue;
319 for (const n of mover.lines) {
320 if (!relocs.has(n)) relocs.set(n, pick(n)!);
321 if (graph.hasOrderedChildren && relocs.size > MOVED_LINES_KEPT) throw new TooManyMoves();
322 }
323 }
324 // From a node, the next node that matters for loops: a line moved in this set, or a file's start.
325 const hop = (code: number): number => {
326 let c = skeleton.climb(code);
327 while (c >= 0 && !relocs.has(c)) c = skeleton.climb(graph.parentCodeOf(c));
328 return c;
329 };
330 const step = (n: number): number => {
331 const e = relocs.get(n);
332 return hop(e ? e.parent : graph.parentCodeOf(n));
333 };
334 // Two moves made apart can loop lines into each other, so no start node reaches them; then the oldest
335 // relocation on the loop is ignored, and the next newest of that line counts, until none loop.
336 const reaches = new Set<number>();
337 for (const line of [...relocs.keys()]) {
338 for (;;) {
339 const path: number[] = [];
340 const onPath = new Map<number, number>();
341 let cur = line;
342 let loopAt = -1;
343 while (cur >= 0 && !reaches.has(cur)) {
344 const at = onPath.get(cur);
345 if (at !== undefined) {
346 loopAt = at;
347 break;
348 }
349 onPath.set(cur, path.length);
350 path.push(cur);
351 cur = step(cur);
352 }
353 if (loopAt < 0) {
354 for (const l of path) reaches.add(l);
355 break;
356 }
357 let weakest: MoveEntry | undefined;
358 for (const l of path.slice(loopAt)) {
359 const e = relocs.get(l);
360 if (e && (!weakest || stronger(weakest.r, e.r))) weakest = e;
361 }
362 ignored.add(identity(weakest!.r));
363 const next = pick(weakest!.n);
364 if (next) relocs.set(weakest!.n, next);
365 else relocs.delete(weakest!.n);
366 }
367 }
368 this.#relocsN = new Map([...relocs].map(([n, e]) => [n, { r: e.r, parent: e.parent }]));
369 this.#relocs = new Map([...relocs.values()].map((e) => [e.r.line, e.r]));
370 return this.#relocs;
371 }
373 /** The view whose moves this one may take, until it needs them all; then the view it took them from. */
374 #movesFrom: View | undefined;
375 #movesTaken: View | undefined;
377 /**
378 * Take another view's resolved moves (abso Capacity), when both sets hold the very same atoms that move lines: the
379 * moves then resolve the same, and every line sits where it sits there. Checked when this view first needs all its
380 * moves, so any caller may ask, and a view that only finds a few lines' files never resolves them.
381 */
382 shareMoves(from: View): void {
383 if (from.graph !== this.graph || from.#hasMoves !== this.#hasMoves || !this.#hasMoves || this.#relocs) return;
384 this.#movesFrom = from;
385 }
387 #takeShared(): void {
388 const from = this.#movesFrom;
389 if (!from) return;
390 this.#movesFrom = undefined;
391 if (from.#scratchMoves()) return;
392 for (const id of this.graph.movers()) {
393 const seq = seqOf(id);
394 if (this.#has(seq) !== from.#has(seq)) return;
395 }
396 this.#relocs = from.#relocations();
397 this.#relocsN = from.#relocationsN();
398 this.#movesOnDisk = false;
399 this.#movesTaken = from;
400 }
402 /** Moved lines' relocations picked one at a time, before the view resolves them all (null: not moved here). */
403 readonly #picked = new Map<number, MoveEntry | null>();
405 /**
406 * The relocation of moved line n that counts here, as #relocations picks it before any loop: right whenever the
407 * walk that reached n goes on to a file's start, since only lines on a loop have their relocation set aside.
408 */
409 #pickOne(n: number): MoveEntry | undefined {
410 let picked = this.#picked.get(n);
411 if (picked === undefined) {
412 const graph = this.graph;
413 let best: MoveEntry | undefined;
414 for (const e of skeletonOf(graph).byLine.get(n) ?? []) {
415 if (this.#has(seqOf(e.r.atom)) && (!best || graph.comparePriority(e.r.atom, best.r.atom) > 0)) best = e;
416 }
417 this.#picked.set(n, (picked = best ?? null));
418 }
419 return picked ?? undefined;
420 }
422 /** Whether moves are resolved on disk for each layout: only a stored graph's view with more than MOVED_LINES_KEPT. */
423 #scratchMoves(): boolean {
424 if (!this.#hasMoves || !this.graph.hasOrderedChildren) return false;
425 if (this.#movesOnDisk === undefined) {
426 try {
427 this.#relocations();
428 this.#movesOnDisk = false;
429 } catch (error) {
430 if (!(error instanceof TooManyMoves)) throw error;
431 this.#movesOnDisk = true;
432 }
433 }
434 return this.#movesOnDisk;
435 }
437 /** The relocations by n, with each new parent's code. */
438 #relocationsN(): Map<number, { readonly r: RelocationInfo; readonly parent: number }> {
439 if (this.#relocsN) return this.#relocsN;
440 const out = new Map<number, { readonly r: RelocationInfo; readonly parent: number }>();
441 for (const [line, r] of this.#relocations())
442 out.set(this.graph.lineN(line), { r, parent: this.graph.codeOf(r.parent)! });
443 this.#relocsN = out;
444 return out;
445 }
447 /** The node a line hangs off in this set: where it was written, or where a move put it. */
448 parentOf(line: LineId): NodeId {
449 if (this.graph.lineParent(line) === undefined) throw new EngineError("unknown-line", `no line ${line}`);
450 if (this.#scratchMoves())
451 return this.graph.withProjectionScratch((scratch) =>
452 resolveScratchMoves(this.graph, (id) => this.#has(this.graph.atom(id).seq), scratch).parent(line),
453 );
454 const r = this.#hasMoves ? this.#relocations().get(line) : undefined;
455 if (r) return r.parent;
456 const parent = this.graph.lineParent(line);
457 if (parent === undefined) throw new EngineError("unknown-line", `no line ${line}`);
458 return parent;
459 }
461 /** Whether any atom in the set moves lines. */
462 hasMoves(): boolean {
463 return this.#hasMoves;
464 }
466 /** The file a line is in, in this set: the one its chain of parents reaches. */
467 fileOf(line: LineId): string {
468 const n = this.graph.lineN(line);
469 if (n < 0) throw new EngineError("unknown-line", `no line ${line}`);
470 return this.#fileOfN(n);
471 }
473 #fileOfN(n: number): string {
474 const graph = this.graph;
475 if (!this.#hasMoves) return graph.writtenIn(n);
476 if (this.#scratchMoves())
477 return graph.withProjectionScratch((scratch) => {
478 const moves = resolveScratchMoves(graph, (id) => this.#has(graph.atom(id).seq), scratch);
479 let current = graph.nodeOf(n);
480 while (!isStartNode(current)) current = moves.parent(current);
481 return current.slice(1);
482 });
483 return this.#fileOfCode(n);
484 }
486 /** The file a node sits in, in this set: up by where lines were written, through the moves that count here. */
487 #fileOfCode(code: number): string {
488 const graph = this.graph;
489 const skeleton = skeletonOf(graph);
490 if (!this.#relocsN) {
491 // One moved line at a time, until a walk comes back to a line it passed: then moves loop, and are resolved whole.
492 const passed = new Set<number>();
493 let c = code;
494 for (;;) {
495 c = skeleton.climb(c);
496 if (c < 0) return graph.nodeOf(c).slice(1);
497 if (passed.has(c)) break;
498 passed.add(c);
499 const e = this.#pickOne(c);
500 c = e ? e.parent : graph.parentCodeOf(c);
501 }
502 }
503 const relocs = this.#relocationsN();
504 let c = code;
505 for (;;) {
506 c = skeleton.climb(c);
507 if (c < 0) return graph.nodeOf(c).slice(1);
508 const e = relocs.get(c);
509 c = e ? e.parent : graph.parentCodeOf(c);
510 }
511 }
513 /** The lines hanging off a node in this set, in layout order. */
514 #children(code: number): Child[] {
515 const graph = this.graph;
516 const relocs = this.#hasMoves ? this.#relocationsN() : undefined;
517 const out: Child[] = [];
518 for (const n of graph.eachChildN(code)) {
519 const seq = graph.writerSeqOf(n);
520 if (!this.#has(seq) || relocs?.has(n)) continue;
521 out.push({ n, replaces: graph.replacesN(n) ? 1 : 0, lamport: graph.lamportOfSeq(seq), seq, k: graph.kOf(n) });
522 }
523 if (relocs) {
524 // The lines this set's moves put under each node, from the moves it already resolved: no row read per node
525 // (abso Capacity).
526 if (!this.#movedInto) {
527 this.#movedInto = new Map();
528 for (const [n, { parent }] of relocs) {
529 const into = this.#movedInto.get(parent);
530 if (into) into.push(n);
531 else this.#movedInto.set(parent, [n]);
532 }
533 }
534 for (const n of this.#movedInto.get(code) ?? NO_LINES) {
535 const r = relocs.get(n)!.r;
536 const seq = graph.atom(r.atom).seq;
537 out.push({ n, replaces: 0, lamport: graph.lamportOfSeq(seq), seq, k: r.k });
538 }
539 }
540 // A line's replacements (runs of atoms that deleted it) first, then the
541 // rest; each group in descending priority (lamport, then seq); lines of
542 // one atom keep k order. A replacement already outranks every insertion
543 // after the line that reads it (it depends on them, or conflicts with
544 // them); the grouping also puts it above a `before` insertion, which
545 // doesn't read the line above, so the new text lands in the replaced
546 // line's place. A moved line ranks like an insertion by the moving atom.
547 if (out.length > 1)
548 out.sort((a, b) => b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k);
549 return out;
550 }
552 /** Parent/successor traversal keeps no history-sized ancestry or sibling frontier. */
553 *#layoutNodes(start: number): IterableIterator<number> {
554 const graph = this.graph;
555 if (graph.hasOrderedChildren && !this.#hasMoves) {
556 const first = (parent: number, after?: number): number | undefined => {
557 for (const n of graph.orderedChildrenN(parent, after)) if (this.#has(graph.writerSeqOf(n))) return n;
558 return undefined;
559 };
560 let n = first(start);
561 while (n !== undefined) {
562 yield n;
563 const child = first(n);
564 if (child !== undefined) {
565 n = child;
566 continue;
567 }
568 let previous = n;
569 for (;;) {
570 const parent = graph.parentCodeOf(previous);
571 const sibling = first(parent, previous);
572 if (sibling !== undefined) {
573 n = sibling;
574 break;
575 }
576 if (parent === start) {
577 n = undefined;
578 break;
579 }
580 if (parent < 0 || parent >= previous) throw new Error("invalid persistent layout ancestry");
581 previous = parent;
582 }
583 }
584 return;
585 }
586 const stack: number[] = [];
587 const push = (parent: number): void => {
588 const children = this.#children(parent);
589 for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]!.n);
590 };
591 push(start);
592 while (stack.length) {
593 const n = stack.pop()!;
594 yield n;
595 push(n);
596 }
597 }
599 /** Lay out one file: its line tree from the set's atoms, linearized. */
600 #layout(path: string, complete: boolean): FileState {
601 const graph = this.graph;
602 if (graph.packedLayout && !this.#scratchMoves()) return this.#layoutPacked(path, complete);
603 if (this.#scratchMoves())
604 return graph.withProjectionScratch((scratch) =>
605 this.#layoutResolved(
606 path,
607 complete,
608 scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, `^${path}`),
609 ),
610 );
611 return this.#layoutResolved(path, complete);
612 }
614 /** For each path, the files that lines moved into it were written in: worked out once per view. */
615 #movedFrom: Map<string, Set<number>> | undefined;
616 #movedInFrom(): Map<string, Set<number>> {
617 if (this.#movedFrom) return this.#movedFrom;
618 this.#relocations();
619 if (this.#movesTaken) return (this.#movedFrom = this.#movesTaken.#movedInFrom());
620 const graph = this.graph;
621 const out = new Map<string, Set<number>>();
622 if (this.#hasMoves) {
623 const relocs = this.#relocationsN();
624 const fileOf = (code: number): string => this.#fileOfCode(code);
625 for (const [n, { parent }] of relocs) {
626 const into = fileOf(parent);
627 let from = out.get(into);
628 if (!from) out.set(into, (from = new Set()));
629 from.add(graph.writtenInIndex(n));
630 }
631 }
632 this.#movedFrom = out;
633 return out;
634 }
636 /**
637 * Lay one file out from its packed history (abso Capacity, Graph.packedLines): the lines written in it, in the files
638 * its moved-in lines came from, and in the files runs under any of those lines were written in, read a page at a
639 * time; the same tree and order as #layoutResolved, built in memory with no read per line.
640 */
641 #layoutPacked(path: string, complete: boolean): FileState {
642 const graph = this.graph;
643 const attrs = this.#attributes(path);
644 const start = graph.startCodeOf(path);
645 if (start === undefined) return { attrs, complete, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() };
646 const relocs = this.#hasMoves ? this.#relocationsN() : undefined;
647 const files = new Set<number>([-1 - start, ...(this.#movedInFrom().get(path) ?? [])]);
648 const children = new Map<number, Child[]>();
649 const texts = new Map<number, string | null>();
650 const writers = new Map<number, number>();
651 const deleters = new Map<number, number[]>();
652 // Each atom's lamport once per layout: most lines share a few atoms, and a stored graph reads it from a page.
653 const lamports = new Map<number, number>();
654 const lamportOf = (seq: number): number => {
655 let lamport = lamports.get(seq);
656 if (lamport === undefined) {
657 lamport = graph.lamportOfSeq(seq);
658 lamports.set(seq, lamport);
659 }
660 return lamport;
661 };
662 for (const file of files) {
663 const lineTexts = graph.packedTexts(file);
664 for (const [n, parent, seq, k, replaces] of graph.packedLines(file)) {
665 const text = lineTexts.next().value as string | null;
666 if (!this.#has(seq)) continue;
667 const moved = relocs?.get(n);
668 let at = parent;
669 let child: Child = { n, replaces, lamport: lamportOf(seq), seq, k };
670 if (moved) {
671 const mover = graph.atom(moved.r.atom).seq;
672 child = { n, replaces: 0, lamport: lamportOf(mover), seq: mover, k: moved.r.k };
673 at = moved.parent;
674 }
675 const list = children.get(at);
676 if (list) list.push(child);
677 else children.set(at, [child]);
678 texts.set(n, text);
679 writers.set(n, seq);
680 }
681 for (const [n, deleter] of graph.packedDeletes(file)) {
682 if (!this.#has(deleter)) continue;
683 const by = deleters.get(n);
684 if (by) by.push(deleter);
685 else deleters.set(n, [deleter]);
686 }
687 // Runs written elsewhere under this file's lines follow them; the loop reads their files too.
688 for (const [parent, into] of graph.packedCrossings(file)) if (texts.has(parent)) files.add(into);
689 }
690 const order = (a: Child, b: Child) =>
691 b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k;
692 const priority = (a: number, b: number) => lamportOf(a) - lamportOf(b) || a - b;
693 const seq: number[] = [];
694 const vis: number[] = [];
695 const visText: (string | null)[] = [];
696 const visWriter: number[] = [];
697 const deletedBy = new Map<number, readonly number[]>();
698 const stack: number[] = [];
699 const push = (code: number) => {
700 const list = children.get(code);
701 if (!list) return;
702 if (list.length > 1) list.sort(order);
703 for (let i = list.length - 1; i >= 0; i--) stack.push(list[i]!.n);
704 };
705 push(start);
706 while (stack.length) {
707 const n = stack.pop()!;
708 const by = deleters.get(n);
709 if (by) {
710 if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by);
711 } else {
712 vis.push(n);
713 visText.push(texts.get(n) ?? null);
714 visWriter.push(writers.get(n)!);
715 }
716 if (complete) seq.push(n);
717 push(n);
718 }
719 return {
720 attrs,
721 complete,
722 seq: Int32Array.from(seq),
723 vis: Int32Array.from(vis),
724 deletedBy,
725 visText,
726 visWriter: Int32Array.from(visWriter),
727 };
728 }
730 #attributes(path: string): FileAttrs {
731 const graph = this.graph;
732 // For each attribute, the highest-priority setter in the set wins.
733 const setters = new Map<string, { id: AtomId; value: string | null }>();
734 const file = graph.packedFiles ? graph.pathIndexOf(path) : undefined;
735 if (graph.packedFiles) {
736 for (const [seq, name, value] of file === undefined ? [] : graph.packedAttrs(file)) {
737 if (!this.#has(seq)) continue;
738 const id = graph.idOfSeq(seq);
739 const best = setters.get(name);
740 if (!best || graph.comparePriority(best.id, id) < 0) setters.set(name, { id, value });
741 }
742 return {
743 exists: setters.get("exists")?.value === "1",
744 exec: setters.get("exec")?.value === "1",
745 link: setters.get("link")?.value ?? null,
746 blob: setters.get("blob")?.value ?? null,
747 };
748 }
749 for (const id of graph.eachAtomIn(path)) {
750 if (!this.#has(graph.atom(id).seq)) continue;
751 for (const a of graph.atom(id).attrs ?? []) {
752 if (a.file !== path) continue;
753 const best = setters.get(a.name);
754 if (!best || graph.comparePriority(best.id, id) < 0) setters.set(a.name, { id, value: a.value });
755 }
756 }
758 return {
759 exists: setters.get("exists")?.value === "1",
760 exec: setters.get("exec")?.value === "1",
761 link: setters.get("link")?.value ?? null,
762 blob: setters.get("blob")?.value ?? null,
763 };
764 }
766 #layoutResolved(path: string, complete: boolean, nodes?: Iterable<number>): FileState {
767 const graph = this.graph;
768 const attrs = this.#attributes(path);
769 const seq: number[] = [];
770 const vis: number[] = [];
771 const deletedBy = new Map<number, readonly number[]>();
773 const start = graph.startCodeOf(path);
774 const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b;
775 for (const n of nodes ?? (start === undefined ? [] : this.#layoutNodes(start))) {
776 let deleted = false;
777 const by: number[] = [];
778 for (const deleter of graph.eachDeleterSeqOf(n)) {
779 if (!this.#has(deleter)) continue;
780 deleted = true;
781 if (!complete) break;
782 by.push(deleter);
783 }
784 if (deleted) {
785 if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by);
786 } else vis.push(n);
787 if (complete) seq.push(n);
788 }
790 return { attrs, complete, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy };
791 }
793 get #known(): string[] {
794 if (!this.#knownList) {
795 const known = new Set<string>();
796 if (this.#stable) {
797 for (const id of this.#stable) for (const file of this.graph.filesOf(id)) known.add(file);
798 } else {
799 for (let seq = 0; seq < this.#in.length; seq++)
800 if (this.#in[seq] === 1) for (const file of this.graph.filesOf(this.graph.idOfSeq(seq))) known.add(file);
801 }
802 this.#knownList = [...known].sort();
803 }
804 return this.#knownList;
805 }
807 /** Files with at least one visible line, sorted. */
808 paths(): string[] {
809 if (this.#stable) {
810 const paths: string[] = [];
811 for (const path of this.graph.knownFiles()) {
812 if (this.hasFile(path)) paths.push(path);
813 else this.#files.delete(path);
814 }
815 return paths.sort();
816 }
817 return this.#known.filter((p) => this.hasFile(p));
818 }
820 /** Every file the set has ever written a line in, including fully deleted ones. */
821 knownPaths(): string[] {
822 return [...this.#known];
823 }
825 /** The file line n sits in, in this set: fileOf by the line's number, with no lookup of its id. */
826 fileOfNumber(n: number): string {
827 return this.#fileOfN(n);
828 }
830 /** How many visible lines a file has. */
831 visibleCount(path: string): number {
832 return this.#file(path).vis.length;
833 }
835 /** Whether the file exists in this projection (has a visible line). */
836 hasFile(path: string): boolean {
837 const attrs = this.attrs(path);
838 return attrs.exists || attrs.link !== null || attrs.blob !== null || this.#file(path).vis.length > 0;
839 }
841 /** A file's attributes: kept while empty, executable, a link's target. */
842 attrs(path: string): FileAttrs {
843 return this.#files.get(path)?.attrs ?? this.#attributes(path);
844 }
846 /** The projected text of a file ("" if it has no visible lines). */
847 text(path: string): string {
848 if (this.#textCache?.path === path) return this.#textCache.text;
849 const { vis, visText } = this.#file(path);
850 const lines: string[] = new Array(vis.length);
851 for (let i = 0; i < vis.length; i++) lines[i] = visText?.[i] ?? this.graph.textOf(vis[i]!);
852 const text = joinLines(lines);
853 this.#textCache = { path, text };
854 return text;
855 }
857 /** Whether a file reads the same here and in `other` (of the same graph), compared line by line without joining either (#46). */
858 sameText(path: string, other: ReadView): boolean {
859 if (!(other instanceof View)) {
860 const a = this.lines(path),
861 b = other.lines(path);
862 return a.length === b.length && a.every((line, i) => line.text === b[i]!.text);
863 }
864 const a = this.#file(path).vis;
865 const b = other.#file(path).vis;
866 if (a.length !== b.length) return false;
867 for (let i = 0; i < a.length; i++)
868 if (a[i] !== b[i] && this.graph.textOf(a[i]!) !== this.graph.textOf(b[i]!)) return false;
869 return true;
870 }
872 *lineChunks(path: string): IterableIterator<() => Iterable<string>> {
873 for (const n of this.#file(path).vis) yield () => this.graph.textChunks(n);
874 }
876 /** Visible lines without retaining their text in the view cache. */
877 *visibleLines(path: string): IterableIterator<VisibleLine> {
878 const graph = this.graph;
879 for (const n of this.#file(path).vis)
880 yield { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) };
881 }
883 /** Atom-building line handles; text is loaded only when requested. */
884 buildLines(path: string): readonly VisibleLine[] {
885 const graph = this.graph;
886 // Texts and writers the packed layout already holds are not read again (abso Capacity).
887 const { vis, visText, visWriter } = this.#file(path);
888 const lines: VisibleLine[] = new Array(vis.length);
889 for (let i = 0; i < vis.length; i++) {
890 const n = vis[i]!;
891 const packed = visText?.[i];
892 lines[i] = {
893 id: graph.lineIdOf(n),
894 textChunks: () => graph.textChunks(n),
895 get text() {
896 return packed ?? graph.textOf(n);
897 },
898 atom: graph.idOfSeq(visWriter ? visWriter[i]! : graph.writerSeqOf(n)),
899 };
900 }
901 return lines;
902 }
904 /** Visible lines with their ids. */
905 lines(path: string): readonly VisibleLine[] {
906 if (this.#linesCache?.path === path) return this.#linesCache.lines;
907 const graph = this.graph;
908 const { vis, visText, visWriter } = this.#file(path);
909 const lines: VisibleLine[] = new Array(vis.length);
910 for (let i = 0; i < vis.length; i++) {
911 const n = vis[i]!;
912 lines[i] = {
913 id: graph.lineIdOf(n),
914 text: visText?.[i] ?? graph.textOf(n),
915 atom: graph.idOfSeq(visWriter ? visWriter[i]! : graph.writerSeqOf(n)),
916 };
917 }
918 this.#linesCache = { path, lines };
919 return lines;
920 }
922 /** The full linearized sequence of a file, tombstones included. */
923 sequence(path: string): readonly SeqLine[] {
924 if (this.#seqCache?.path === path) return this.#seqCache.seq;
925 const graph = this.graph;
926 const f = this.#file(path, true);
927 const out: SeqLine[] = new Array(f.seq.length);
928 for (let i = 0; i < f.seq.length; i++) {
929 const n = f.seq[i]!;
930 const by = f.deletedBy.get(i);
931 out[i] = {
932 id: graph.lineIdOf(n),
933 text: graph.textOf(n),
934 atom: graph.idOfSeq(graph.writerSeqOf(n)),
935 deletedBy: by ? by.map((s) => graph.idOfSeq(s)) : NONE,
936 visible: by === undefined,
937 };
938 }
939 this.#seqCache = { path, seq: out };
940 return out;
941 }
943 /** Two visible neighbours without retaining the file's historical sequence. */
944 visibleNeighbours(path: string, line: LineId): LineId[] {
945 const graph = this.graph;
946 const target = graph.lineN(line);
947 const start = graph.startCodeOf(path);
948 if (target < 0 || start === undefined) return [];
949 const scan = (nodes: Iterable<number>): LineId[] => {
950 let previous: LineId | undefined;
951 let found = false;
952 for (const n of nodes) {
953 if (n === target) {
954 found = true;
955 continue;
956 }
957 let deleted = false;
958 for (const seq of graph.eachDeleterSeqOf(n))
959 if (this.#has(seq)) {
960 deleted = true;
961 break;
962 }
963 if (deleted) continue;
964 const id = graph.lineIdOf(n);
965 if (found) return previous === undefined ? [id] : [previous, id];
966 previous = id;
967 }
968 return found && previous !== undefined ? [previous] : [];
969 };
970 if (this.#scratchMoves())
971 return graph.withProjectionScratch((scratch) =>
972 scan(scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, graph.nodeOf(start))),
973 );
974 return scan(this.#layoutNodes(start));
975 }
977 /** Index of a line in `sequence(path)`, or -1. */
978 sequenceIndex(path: string, line: LineId): number {
979 const f = this.#file(path, true);
980 if (!f.seqIndex) {
981 f.seqIndex = new Map();
982 for (let i = 0; i < f.seq.length; i++) f.seqIndex.set(f.seq[i]!, i);
983 }
984 return f.seqIndex.get(this.graph.lineN(line)) ?? -1;
985 }
987 /** Index of a line in `lines(path)` (0-based visible line number), or -1 if not visible. */
988 lineNumber(path: string, line: LineId): number {
989 return this.lineNumberOf(path, this.graph.lineN(line));
990 }
992 /** lineNumber by the line's number, with no lookup of its id. */
993 lineNumberOf(path: string, n: number): number {
994 const f = this.#file(path);
995 if (!f.visIndex) {
996 f.visIndex = new Map();
997 for (let i = 0; i < f.vis.length; i++) f.visIndex.set(f.vis[i]!, i);
998 }
999 return f.visIndex.get(n) ?? -1;
1002 /** The seq of the atom that wrote each visible line, in order: lines() without ids or text. */
1003 visibleWriters(path: string): number[] {
1004 const graph = this.graph;
1005 const { vis, visWriter } = this.#file(path);
1006 // The packed layout keeps them (abso Capacity): looking each up again read a page per few lines on a stored graph.
1007 if (visWriter) return Array.from(visWriter);
1008 return Array.from(vis, (n) => graph.writerSeqOf(n));
1011 /** All projected text files, path -> text, in path order. Binary files are in `blobs()`. */
1012 files(): Record<string, string> {
1013 const out: Record<string, string> = {};
1014 for (const path of this.paths()) if (this.#file(path).attrs.blob === null) out[path] = this.text(path);
1015 return out;
1018 /** Binary files, path -> the SHA-256 of their bytes, in path order. */
1019 blobs(): Record<string, string> {
1020 const out: Record<string, string> = {};
1021 for (const path of this.paths()) {
1022 const blob = this.#file(path).attrs.blob;
1023 if (blob !== null) out[path] = blob;
1025 return out;
1028 /**
1029 * About how many bytes of retained state this view costs (#46). This uses
1030 * approximate ownership costs for containers and wrappers, not V8 heap
1031 * measurements. Graph-owned strings and records count only as references.
1032 * This method only inspects already-created state: it does not lay out files,
1033 * populate lazy caches, enumerate the graph, or count temporary traversal
1034 * containers and shared empty singleton payloads as retained view state.
1035 */
1036 weight(): number {
1037 let n = this.#in.byteLength;
1038 n += 2 * ARRAY_HEADER_BYTES + this.#membershipSeq.byteLength + this.#membershipValue.byteLength;
1039 if (this.#movers) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#movers.length;
1040 n += MAP_HEADER_BYTES; // #files exists from construction.
1041 if (this.#stable) n += this.#stable.retainedBytes;
1042 else if (this.#set) n += OBJECT_BYTES + SET_ENTRY_BYTES * this.#set.size;
1043 if (this.#knownList) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#knownList.length;
1044 if (this.#relocs) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * this.#relocs.size;
1045 if (this.#relocsN) n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + OBJECT_BYTES) * this.#relocsN.size;
1046 n += MAP_ENTRY_BYTES * this.#picked.size;
1047 for (const f of this.#files.values()) {
1048 n += MAP_ENTRY_BYTES;
1049 if (f !== NO_FILE) {
1050 // FileState and FileAttrs are per laid-out file; typed-array
1051 // headers are separate from their payload byte lengths below.
1052 n += OBJECT_BYTES + OBJECT_BYTES + 2 * ARRAY_HEADER_BYTES;
1053 n += f.seq.byteLength + f.vis.byteLength;
1054 if (f.visText) for (const text of f.visText) n += REFERENCE_BYTES + 2 * (text?.length ?? 0);
1055 if (f.visWriter) n += 4 * f.visWriter.length;
1056 n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + ARRAY_HEADER_BYTES) * f.deletedBy.size;
1057 for (const deleters of f.deletedBy.values()) n += REFERENCE_BYTES * deleters.length;
1058 if (f.seqIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.seqIndex.size;
1059 if (f.visIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.visIndex.size;
1062 if (this.#linesCache)
1063 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 100 * this.#linesCache.lines.length;
1064 if (this.#seqCache) {
1065 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 120 * this.#seqCache.seq.length;
1066 for (const line of this.#seqCache.seq)
1067 if (line.deletedBy !== NONE) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * line.deletedBy.length;
1069 if (this.#textCache) n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 2 * this.#textCache.text.length;
1070 return n;
1073 #file(path: string, complete = false): FileState {
1074 let state = this.#files.get(path);
1075 if (!state || (complete && !state.complete)) {
1076 state = this.graph.hasAtomsIn(path) ? this.#layout(path, complete) : NO_FILE;
1077 this.#files.set(path, state);
1079 return state;
1083/** The files of a closed set, path -> text. */
1084export function project(graph: Graph, set: Iterable<AtomId>): Record<string, string> {
1085 return new View(graph, set).files();
1088/** Where a node sits in a file's sequence: the index just after it (0 for a start node). */
1089export function indexAfter(view: Pick<ReadView, "sequenceIndex">, path: string, node: NodeId): number {
1090 if (isStartNode(node)) return 0;
1091 const i = view.sequenceIndex(path, node);
1092 if (i < 0) throw new EngineError("not-in-view", `line ${node} is not in ${path} in this view`);
1093 return i + 1;