Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/src/engine/view.ts?version=205&format=json
783 linesFirst import 54% · codex-capacity-chair 34% · capacity 6% · codex-capacity-policy 6%Last change capacity in version 205, 20 versions changed it

You're reading version 205. The newest is 318, and 25 versions since then changed this file. Go to the newestCompare with 318

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