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