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