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=243&format=json
1,167 linescapacity 44% · First import 32% · codex-capacity-chair 21% · codex-capacity-policy 3%Last change capacity in version 241, 35 versions changed it

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