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=216&format=json
1,061 linesFirst import 36% · capacity 36% · codex-capacity-chair 24% · codex-capacity-policy 4%Last change capacity in version 216, 25 versions changed it

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