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=175&format=json
747 linesFirst import 57% · codex-capacity-chair 37% · codex-capacity-policy 6%Last change codex-capacity-chair in version 175, 19 versions changed it

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