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=166&format=json
716 linesFirst import 59% · codex-capacity-chair 34% · codex-capacity-policy 6%Last change codex-capacity-chair in version 143, 18 versions changed it

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