- 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=140&format=json
706 linesFirst import 60% · codex-capacity-chair 33% · codex-capacity-policy 6%Last change codex-capacity-chair in version 140, 17 versions changed it
You're reading version 140. The newest is 318, and 28 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 } from "./keys.ts";
14import { resolveScratchMoves, scratchLayoutNodes } from "./relocation-scratch.ts";
15import { 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 id: LineId;
33 readonly text: string;
34 readonly atom: AtomId;
35}
37/** A file's attributes in a view. */
38export interface FileAttrs {
39 /** Kept with no lines (an empty file). */
40 readonly exists: boolean;
41 readonly exec: boolean;
42 /** The target, when the file is a symbolic link. */
43 readonly link: string | null;
44 /** The SHA-256 of its bytes, when the file is binary. */
45 readonly blob: string | null;
46}
48const NO_ATTRS: FileAttrs = { exists: false, exec: false, link: null, blob: null };
49const NONE: readonly never[] = Object.freeze([]);
51interface FileState {
52 readonly attrs: FileAttrs;
53 /** Full history is retained only when a sequence caller explicitly requests it. */
54 readonly complete: boolean;
55 /** The file's sequence, tombstones included: each line's n. */
56 readonly seq: Int32Array;
57 /** Its visible lines' n, in order. */
58 readonly vis: Int32Array;
59 /** For each deleted position in seq: the seqs of the atoms in the set that delete it, by priority. */
60 readonly deletedBy: ReadonlyMap<number, readonly number[]>;
61 /** Positions by n, built the first time they're asked for. */
62 seqIndex?: Map<number, number>;
63 visIndex?: Map<number, number>;
64}
66interface Child {
67 readonly n: number;
68 /** 1 when the child's atom deleted the parent (the child replaces it), else 0. A moved line is 0. */
69 readonly replaces: number;
70 readonly lamport: number;
71 readonly seq: number;
72 readonly k: number;
73}
75const EMPTY_INTS = new Int32Array(0);
76const NO_FILE: FileState = { attrs: NO_ATTRS, complete: true, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() };
78// Approximate retained-container costs for View.weight(): reference slots,
79// object headers, and map/set entries. These are cache-budget units, not V8
80// heap measurements. Referenced Graph strings and records are not charged.
81const ARRAY_HEADER_BYTES = 24;
82const OBJECT_BYTES = 32;
83const MAP_HEADER_BYTES = 32;
84const MAP_ENTRY_BYTES = 40;
85const SET_ENTRY_BYTES = 32;
86const REFERENCE_BYTES = 8;
87const FILE_LOCATION_MEMO_ENTRIES = 256;
89/**
90 * The projection of a closed set. Construct once, then ask for files, lines
91 * and sequences. Throws `not-closed` if some atom's dependency is missing.
92 * Each file is laid out the first time it is asked for, so a view of a large
93 * set costs little until files are read.
94 */
95export class View {
96 readonly graph: Graph;
97 /** 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). */
98 #set: AtomSet | undefined;
99 readonly #stable: StableSet<AtomId> | undefined;
100 /** Fixed-size memo for immutable indexed membership, independent of history size. */
101 #membershipSeq = new Float64Array(256).fill(-1);
102 #membershipValue = new Uint8Array(256);
103 #files = new Map<string, FileState>();
104 /** Every file the set wrote in, sorted; worked out the first time it's asked for. */
105 #knownList: string[] | undefined;
106 /** 1 for each atom (by seq) in the set. */
107 #in: Uint8Array;
108 /** Atoms in the set that move lines. */
109 #movers: AtomId[] | undefined;
110 #hasMoves = false;
111 /** Each moved line's relocation that counts in this set; built on first use. */
112 #relocs: Map<LineId, RelocationInfo> | undefined;
113 /** The same, by n, with the new parent's code. */
114 #relocsN: Map<number, { readonly r: RelocationInfo; readonly parent: number }> | undefined;
115 /** Bounded memo: ancestry can span the entire history even for one visible line. */
116 #fileOf = new Map<number, string>();
117 /** The latest records asked for: one file's lines, one file's sequence, one file's text. */
118 #linesCache: { path: string; lines: readonly VisibleLine[] } | undefined;
119 #seqCache: { path: string; seq: readonly SeqLine[] } | undefined;
120 #textCache: { path: string; text: string } | undefined;
122 constructor(graph: Graph, set: Iterable<AtomId>) {
123 this.graph = graph;
124 if (set instanceof StableSet) {
125 this.#stable = set;
126 this.#set = set;
127 this.#in = new Uint8Array(0);
128 for (const id of set) {
129 const atom = graph.atom(id);
130 for (const dependency of atom.deps) {
131 graph.atom(dependency);
132 if (!set.has(dependency))
133 throw new EngineError("not-closed", `set is not closed: ${id} depends on ${dependency}`);
134 }
135 }
136 for (const id of graph.movers()) {
137 if (set.has(id)) {
138 this.#hasMoves = true;
139 break;
140 }
141 }
142 this.#relocs = this.#hasMoves ? undefined : new Map();
143 this.#relocsN = this.#hasMoves ? undefined : new Map();
144 return;
145 }
146 const inSet = new Uint8Array(graph.size);
147 for (const id of set) {
148 const atom = graph.atom(id);
149 inSet[atom.seq] = 1;
150 }
151 // Validate one atom at a time. Keeping all decoded atoms here defeats
152 // storage-backed Graph reads even though the view only needs membership.
153 for (let seq = 0; seq < inSet.length; seq++) {
154 if (inSet[seq] !== 1) continue;
155 const atom = graph.atom(graph.idOfSeq(seq));
156 for (const d of atom.deps) {
157 if (inSet[graph.atom(d).seq] !== 1)
158 throw new EngineError("not-closed", `set is not closed: ${atom.id} depends on ${d}`);
159 }
160 }
161 this.graph = graph;
162 this.#in = inSet;
163 this.#movers = graph.movers().filter((id) => inSet[graph.atom(id).seq] === 1);
164 this.#hasMoves = this.#movers.length > 0;
165 this.#relocs = this.#movers.length === 0 ? new Map() : undefined;
166 this.#relocsN = this.#movers.length === 0 ? new Map() : undefined;
167 }
169 /** The set of atoms this view projects. */
170 get set(): AtomSet {
171 if (!this.#set) {
172 const out = new Set<AtomId>();
173 for (let seq = 0; seq < this.#in.length; seq++) if (this.#in[seq] === 1) out.add(this.graph.idOfSeq(seq));
174 this.#set = out;
175 }
176 return this.#set;
177 }
179 /** Whether the atom with this seq is in the set. */
180 #has(seq: number): boolean {
181 if (this.#stable) {
182 const slot = seq % this.#membershipSeq.length;
183 if (this.#membershipSeq[slot] === seq) return this.#membershipValue[slot] === 1;
184 const present = this.#stable.has(this.graph.idOfSeq(seq));
185 this.#membershipSeq[slot] = seq;
186 this.#membershipValue[slot] = present ? 1 : 0;
187 return present;
188 }
189 return seq < this.#in.length && this.#in[seq] === 1;
190 }
192 /**
193 * The relocation that counts for each moved line: the newest (by priority)
194 * in the set. Two moves made apart can loop lines into each other, so no
195 * start node reaches them; then the oldest relocation on the loop is
196 * ignored, and the next newest of that line counts, until none loop.
197 */
198 #relocations(): Map<LineId, RelocationInfo> {
199 if (this.#relocs) return this.#relocs;
200 const graph = this.graph;
201 const stronger = (a: RelocationInfo, b: RelocationInfo): boolean => graph.comparePriority(a.atom, b.atom) > 0;
202 // Persistent reads decode new objects. Cycle suppression must identify the
203 // logical move, not one particular decoded JavaScript object.
204 const identity = (r: RelocationInfo): string => JSON.stringify([r.atom, r.k]);
205 const ignored = new Set<string>();
206 const pick = (line: LineId): RelocationInfo | undefined => {
207 let best: RelocationInfo | undefined;
208 for (const r of graph.eachRelocationOf(line)) {
209 if (this.#has(graph.atom(r.atom).seq) && !ignored.has(identity(r)) && (!best || stronger(r, best))) best = r;
210 }
211 return best;
212 };
213 const relocs = new Map<LineId, RelocationInfo>();
214 for (const id of this.#eachMover()) {
215 for (const m of graph.atom(id).moves!) {
216 if (!relocs.has(m.line)) relocs.set(m.line, pick(m.line)!);
217 }
218 }
219 const parentOf = (line: LineId): NodeId => relocs.get(line)?.parent ?? graph.lineParent(line)!;
220 const reaches = new Set<LineId>();
221 for (const line of [...relocs.keys()]) {
222 for (;;) {
223 const path: LineId[] = [];
224 const onPath = new Map<LineId, number>();
225 let cur: NodeId = line;
226 let loopAt = -1;
227 while (!isStartNode(cur) && !reaches.has(cur)) {
228 const at = onPath.get(cur);
229 if (at !== undefined) {
230 loopAt = at;
231 break;
232 }
233 onPath.set(cur, path.length);
234 path.push(cur);
235 cur = parentOf(cur);
236 }
237 if (loopAt < 0) {
238 for (const l of path) reaches.add(l);
239 break;
240 }
241 let weakest: RelocationInfo | undefined;
242 for (const l of path.slice(loopAt)) {
243 const r = relocs.get(l);
244 if (r && (!weakest || stronger(weakest, r))) weakest = r;
245 }
246 ignored.add(identity(weakest!));
247 const next = pick(weakest!.line);
248 if (next) relocs.set(weakest!.line, next);
249 else relocs.delete(weakest!.line);
250 }
251 }
252 this.#relocs = relocs;
253 return relocs;
254 }
256 /** The relocations by n, with each new parent's code. */
257 #relocationsN(): Map<number, { readonly r: RelocationInfo; readonly parent: number }> {
258 if (this.#relocsN) return this.#relocsN;
259 const out = new Map<number, { readonly r: RelocationInfo; readonly parent: number }>();
260 for (const [line, r] of this.#relocations())
261 out.set(this.graph.lineN(line), { r, parent: this.graph.codeOf(r.parent)! });
262 this.#relocsN = out;
263 return out;
264 }
266 /** The node a line hangs off in this set: where it was written, or where a move put it. */
267 parentOf(line: LineId): NodeId {
268 if (this.graph.lineParent(line) === undefined) throw new EngineError("unknown-line", `no line ${line}`);
269 if (this.#hasMoves && this.graph.hasOrderedChildren)
270 return this.graph.withProjectionScratch((scratch) =>
271 resolveScratchMoves(this.graph, (id) => this.#has(this.graph.atom(id).seq), scratch).parent(line),
272 );
273 const r = this.#hasMoves ? this.#relocations().get(line) : undefined;
274 if (r) return r.parent;
275 const parent = this.graph.lineParent(line);
276 if (parent === undefined) throw new EngineError("unknown-line", `no line ${line}`);
277 return parent;
278 }
280 /** Whether any atom in the set moves lines. */
281 hasMoves(): boolean {
282 return this.#hasMoves;
283 }
284 *#eachMover(): IterableIterator<AtomId> {
285 if (this.#movers) yield* this.#movers;
286 else for (const id of this.graph.movers()) if (this.#stable!.has(id)) yield id;
287 }
289 /** The file a line is in, in this set: the one its chain of parents reaches. */
290 fileOf(line: LineId): string {
291 const n = this.graph.lineN(line);
292 if (n < 0) throw new EngineError("unknown-line", `no line ${line}`);
293 return this.#fileOfN(n);
294 }
296 #fileOfN(n: number): string {
297 const graph = this.graph;
298 if (!this.#hasMoves) return graph.writtenIn(n);
299 if (graph.hasOrderedChildren)
300 return graph.withProjectionScratch((scratch) => {
301 const moves = resolveScratchMoves(graph, (id) => this.#has(graph.atom(id).seq), scratch);
302 let current = graph.nodeOf(n);
303 while (!isStartNode(current)) current = moves.parent(current);
304 return current.slice(1);
305 });
306 const relocs = this.#relocationsN();
307 // Keep only a fixed tail of the walk for path compression. The selected
308 // relocation graph is acyclic, so traversal needs no history-sized stack.
309 const path: number[] = [];
310 let visited = 0;
311 let cur = n;
312 let file: string | undefined;
313 while (file === undefined) {
314 if (cur < 0) file = graph.nodeOf(cur).slice(1);
315 else {
316 file = this.#fileOf.get(cur);
317 if (file === undefined) {
318 path[visited++ % FILE_LOCATION_MEMO_ENTRIES] = cur;
319 cur = relocs.get(cur)?.parent ?? graph.parentCodeOf(cur);
320 }
321 }
322 }
323 for (const l of path) {
324 if (!this.#fileOf.has(l) && this.#fileOf.size >= FILE_LOCATION_MEMO_ENTRIES)
325 this.#fileOf.delete(this.#fileOf.keys().next().value!);
326 this.#fileOf.set(l, file);
327 }
328 return file;
329 }
331 /** The lines hanging off a node in this set, in layout order. */
332 #children(code: number): Child[] {
333 const graph = this.graph;
334 const relocs = this.#hasMoves ? this.#relocationsN() : undefined;
335 const out: Child[] = [];
336 for (const n of graph.eachChildN(code)) {
337 const seq = graph.writerSeqOf(n);
338 if (!this.#has(seq) || relocs?.has(n)) continue;
339 out.push({ n, replaces: graph.replacesN(n) ? 1 : 0, lamport: graph.lamportOfSeq(seq), seq, k: graph.kOf(n) });
340 }
341 if (relocs) {
342 for (const r of graph.eachRelocatedToCode(code)) {
343 const n = graph.lineN(r.line);
344 const selected = relocs.get(n)?.r;
345 if (!selected || selected.atom !== r.atom || selected.k !== r.k) continue;
346 const seq = graph.atom(r.atom).seq;
347 out.push({ n, replaces: 0, lamport: graph.lamportOfSeq(seq), seq, k: r.k });
348 }
349 }
350 // A line's replacements (runs of atoms that deleted it) first, then the
351 // rest; each group in descending priority (lamport, then seq); lines of
352 // one atom keep k order. A replacement already outranks every insertion
353 // after the line that reads it (it depends on them, or conflicts with
354 // them); the grouping also puts it above a `before` insertion, which
355 // doesn't read the line above, so the new text lands in the replaced
356 // line's place. A moved line ranks like an insertion by the moving atom.
357 if (out.length > 1)
358 out.sort((a, b) => b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k);
359 return out;
360 }
362 /** Parent/successor traversal keeps no history-sized ancestry or sibling frontier. */
363 *#layoutNodes(start: number): IterableIterator<number> {
364 const graph = this.graph;
365 if (graph.hasOrderedChildren && !this.#hasMoves) {
366 const first = (parent: number, after?: number): number | undefined => {
367 for (const n of graph.orderedChildrenN(parent, after)) if (this.#has(graph.writerSeqOf(n))) return n;
368 return undefined;
369 };
370 let n = first(start);
371 while (n !== undefined) {
372 yield n;
373 const child = first(n);
374 if (child !== undefined) {
375 n = child;
376 continue;
377 }
378 let previous = n;
379 for (;;) {
380 const parent = graph.parentCodeOf(previous);
381 const sibling = first(parent, previous);
382 if (sibling !== undefined) {
383 n = sibling;
384 break;
385 }
386 if (parent === start) {
387 n = undefined;
388 break;
389 }
390 if (parent < 0 || parent >= previous) throw new Error("invalid persistent layout ancestry");
391 previous = parent;
392 }
393 }
394 return;
395 }
396 const stack: number[] = [];
397 const push = (parent: number): void => {
398 const children = this.#children(parent);
399 for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]!.n);
400 };
401 push(start);
402 while (stack.length) {
403 const n = stack.pop()!;
404 yield n;
405 push(n);
406 }
407 }
409 /** Lay out one file: its line tree from the set's atoms, linearized. */
410 #layout(path: string, complete: boolean): FileState {
411 const graph = this.graph;
412 if (this.#hasMoves && graph.hasOrderedChildren)
413 return graph.withProjectionScratch((scratch) =>
414 this.#layoutResolved(
415 path,
416 complete,
417 scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, `^${path}`),
418 ),
419 );
420 return this.#layoutResolved(path, complete);
421 }
423 #attributes(path: string): FileAttrs {
424 const graph = this.graph;
425 // For each attribute, the highest-priority setter in the set wins.
426 const setters = new Map<string, { id: AtomId; value: string | null }>();
427 for (const id of graph.eachAtomIn(path)) {
428 if (!this.#has(graph.atom(id).seq)) continue;
429 for (const a of graph.atom(id).attrs ?? []) {
430 if (a.file !== path) continue;
431 const best = setters.get(a.name);
432 if (!best || graph.comparePriority(best.id, id) < 0) setters.set(a.name, { id, value: a.value });
433 }
434 }
436 return {
437 exists: setters.get("exists")?.value === "1",
438 exec: setters.get("exec")?.value === "1",
439 link: setters.get("link")?.value ?? null,
440 blob: setters.get("blob")?.value ?? null,
441 };
442 }
444 #layoutResolved(path: string, complete: boolean, nodes?: Iterable<number>): FileState {
445 const graph = this.graph;
446 const attrs = this.#attributes(path);
447 const seq: number[] = [];
448 const vis: number[] = [];
449 const deletedBy = new Map<number, readonly number[]>();
451 const start = graph.startCodeOf(path);
452 const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b;
453 for (const n of nodes ?? (start === undefined ? [] : this.#layoutNodes(start))) {
454 let deleted = false;
455 const by: number[] = [];
456 for (const deleter of graph.eachDeleterSeqOf(n)) {
457 if (!this.#has(deleter)) continue;
458 deleted = true;
459 if (!complete) break;
460 by.push(deleter);
461 }
462 if (deleted) {
463 if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by);
464 } else vis.push(n);
465 if (complete) seq.push(n);
466 }
468 return { attrs, complete, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy };
469 }
471 get #known(): string[] {
472 if (!this.#knownList) {
473 const known = new Set<string>();
474 if (this.#stable) {
475 for (const id of this.#stable) for (const file of this.graph.filesOf(id)) known.add(file);
476 } else {
477 for (let seq = 0; seq < this.#in.length; seq++)
478 if (this.#in[seq] === 1) for (const file of this.graph.filesOf(this.graph.idOfSeq(seq))) known.add(file);
479 }
480 this.#knownList = [...known].sort();
481 }
482 return this.#knownList;
483 }
485 /** Files with at least one visible line, sorted. */
486 paths(): string[] {
487 if (this.#stable) {
488 const paths: string[] = [];
489 for (const path of this.graph.knownFiles()) {
490 if (this.hasFile(path)) paths.push(path);
491 else this.#files.delete(path);
492 }
493 return paths.sort();
494 }
495 return this.#known.filter((p) => this.hasFile(p));
496 }
498 /** Every file the set has ever written a line in, including fully deleted ones. */
499 knownPaths(): string[] {
500 return [...this.#known];
501 }
503 /** Whether the file exists in this projection (has a visible line). */
504 hasFile(path: string): boolean {
505 const attrs = this.attrs(path);
506 return attrs.exists || attrs.link !== null || attrs.blob !== null || this.#file(path).vis.length > 0;
507 }
509 /** A file's attributes: kept while empty, executable, a link's target. */
510 attrs(path: string): FileAttrs {
511 return this.#files.get(path)?.attrs ?? this.#attributes(path);
512 }
514 /** The projected text of a file ("" if it has no visible lines). */
515 text(path: string): string {
516 if (this.#textCache?.path === path) return this.#textCache.text;
517 const vis = this.#file(path).vis;
518 const lines: string[] = new Array(vis.length);
519 for (let i = 0; i < vis.length; i++) lines[i] = this.graph.textOf(vis[i]!);
520 const text = joinLines(lines);
521 this.#textCache = { path, text };
522 return text;
523 }
525 /** Whether a file reads the same here and in `other` (of the same graph), compared line by line without joining either (#46). */
526 sameText(path: string, other: View): boolean {
527 const a = this.#file(path).vis;
528 const b = other.#file(path).vis;
529 if (a.length !== b.length) return false;
530 for (let i = 0; i < a.length; i++)
531 if (a[i] !== b[i] && this.graph.textOf(a[i]!) !== this.graph.textOf(b[i]!)) return false;
532 return true;
533 }
535 /** Visible lines with their ids. */
536 lines(path: string): readonly VisibleLine[] {
537 if (this.#linesCache?.path === path) return this.#linesCache.lines;
538 const graph = this.graph;
539 const vis = this.#file(path).vis;
540 const lines: VisibleLine[] = new Array(vis.length);
541 for (let i = 0; i < vis.length; i++) {
542 const n = vis[i]!;
543 lines[i] = { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) };
544 }
545 this.#linesCache = { path, lines };
546 return lines;
547 }
549 /** The full linearized sequence of a file, tombstones included. */
550 sequence(path: string): readonly SeqLine[] {
551 if (this.#seqCache?.path === path) return this.#seqCache.seq;
552 const graph = this.graph;
553 const f = this.#file(path, true);
554 const out: SeqLine[] = new Array(f.seq.length);
555 for (let i = 0; i < f.seq.length; i++) {
556 const n = f.seq[i]!;
557 const by = f.deletedBy.get(i);
558 out[i] = {
559 id: graph.lineIdOf(n),
560 text: graph.textOf(n),
561 atom: graph.idOfSeq(graph.writerSeqOf(n)),
562 deletedBy: by ? by.map((s) => graph.idOfSeq(s)) : NONE,
563 visible: by === undefined,
564 };
565 }
566 this.#seqCache = { path, seq: out };
567 return out;
568 }
570 /** Two visible neighbours without retaining the file's historical sequence. */
571 visibleNeighbours(path: string, line: LineId): LineId[] {
572 const graph = this.graph;
573 const target = graph.lineN(line);
574 const start = graph.startCodeOf(path);
575 if (target < 0 || start === undefined) return [];
576 const scan = (nodes: Iterable<number>): LineId[] => {
577 let previous: LineId | undefined;
578 let found = false;
579 for (const n of nodes) {
580 if (n === target) {
581 found = true;
582 continue;
583 }
584 let deleted = false;
585 for (const seq of graph.eachDeleterSeqOf(n))
586 if (this.#has(seq)) {
587 deleted = true;
588 break;
589 }
590 if (deleted) continue;
591 const id = graph.lineIdOf(n);
592 if (found) return previous === undefined ? [id] : [previous, id];
593 previous = id;
594 }
595 return found && previous !== undefined ? [previous] : [];
596 };
597 if (this.#hasMoves && graph.hasOrderedChildren)
598 return graph.withProjectionScratch((scratch) =>
599 scan(scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, graph.nodeOf(start))),
600 );
601 return scan(this.#layoutNodes(start));
602 }
604 /** Index of a line in `sequence(path)`, or -1. */
605 sequenceIndex(path: string, line: LineId): number {
606 const f = this.#file(path, true);
607 if (!f.seqIndex) {
608 f.seqIndex = new Map();
609 for (let i = 0; i < f.seq.length; i++) f.seqIndex.set(f.seq[i]!, i);
610 }
611 return f.seqIndex.get(this.graph.lineN(line)) ?? -1;
612 }
614 /** Index of a line in `lines(path)` (0-based visible line number), or -1 if not visible. */
615 lineNumber(path: string, line: LineId): number {
616 const f = this.#file(path);
617 if (!f.visIndex) {
618 f.visIndex = new Map();
619 for (let i = 0; i < f.vis.length; i++) f.visIndex.set(f.vis[i]!, i);
620 }
621 return f.visIndex.get(this.graph.lineN(line)) ?? -1;
622 }
624 /** All projected text files, path -> text, in path order. Binary files are in `blobs()`. */
625 files(): Record<string, string> {
626 const out: Record<string, string> = {};
627 for (const path of this.paths()) if (this.#file(path).attrs.blob === null) out[path] = this.text(path);
628 return out;
629 }
631 /** Binary files, path -> the SHA-256 of their bytes, in path order. */
632 blobs(): Record<string, string> {
633 const out: Record<string, string> = {};
634 for (const path of this.paths()) {
635 const blob = this.#file(path).attrs.blob;
636 if (blob !== null) out[path] = blob;
637 }
638 return out;
639 }
641 /**
642 * About how many bytes of retained state this view costs (#46). This uses
643 * approximate ownership costs for containers and wrappers, not V8 heap
644 * measurements. Graph-owned strings and records count only as references.
645 * This method only inspects already-created state: it does not lay out files,
646 * populate lazy caches, enumerate the graph, or count temporary traversal
647 * containers and shared empty singleton payloads as retained view state.
648 */
649 weight(): number {
650 let n = this.#in.byteLength;
651 n += 2 * ARRAY_HEADER_BYTES + this.#membershipSeq.byteLength + this.#membershipValue.byteLength;
652 if (this.#movers) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#movers.length;
653 n += MAP_HEADER_BYTES; // #files exists from construction.
654 n += MAP_HEADER_BYTES; // #fileOf exists from construction.
655 if (this.#stable) n += this.#stable.retainedBytes;
656 else if (this.#set) n += OBJECT_BYTES + SET_ENTRY_BYTES * this.#set.size;
657 if (this.#knownList) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#knownList.length;
658 if (this.#relocs) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * this.#relocs.size;
659 if (this.#relocsN) n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + OBJECT_BYTES) * this.#relocsN.size;
660 n += MAP_ENTRY_BYTES * this.#fileOf.size;
661 for (const f of this.#files.values()) {
662 n += MAP_ENTRY_BYTES;
663 if (f !== NO_FILE) {
664 // FileState and FileAttrs are per laid-out file; typed-array
665 // headers are separate from their payload byte lengths below.
666 n += OBJECT_BYTES + OBJECT_BYTES + 2 * ARRAY_HEADER_BYTES;
667 n += f.seq.byteLength + f.vis.byteLength;
668 n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + ARRAY_HEADER_BYTES) * f.deletedBy.size;
669 for (const deleters of f.deletedBy.values()) n += REFERENCE_BYTES * deleters.length;
670 if (f.seqIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.seqIndex.size;
671 if (f.visIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.visIndex.size;
672 }
673 }
674 if (this.#linesCache)
675 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 100 * this.#linesCache.lines.length;
676 if (this.#seqCache) {
677 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 120 * this.#seqCache.seq.length;
678 for (const line of this.#seqCache.seq)
679 if (line.deletedBy !== NONE) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * line.deletedBy.length;
680 }
681 if (this.#textCache) n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 2 * this.#textCache.text.length;
682 return n;
683 }
685 #file(path: string, complete = false): FileState {
686 let state = this.#files.get(path);
687 if (!state || (complete && !state.complete)) {
688 state = this.graph.hasAtomsIn(path) ? this.#layout(path, complete) : NO_FILE;
689 this.#files.set(path, state);
690 }
691 return state;
692 }
693}
695/** The files of a closed set, path -> text. */
696export function project(graph: Graph, set: Iterable<AtomId>): Record<string, string> {
697 return new View(graph, set).files();
698}
700/** Where a node sits in a file's sequence: the index just after it (0 for a start node). */
701export function indexAfter(view: View, path: string, node: NodeId): number {
702 if (isStartNode(node)) return 0;
703 const i = view.sequenceIndex(path, node);
704 if (i < 0) throw new EngineError("not-in-view", `line ${node} is not in ${path} in this view`);
705 return i + 1;
706}