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=206&format=json
910 linesFirst import 46% · codex-capacity-chair 30% · capacity 19% · codex-capacity-policy 5%Last change capacity in version 206, 21 versions changed it

You're reading version 206. The newest is 318, and 24 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 /** Its visible lines' text, when laid out from the file's packed history: null for a line too long to pack. */
68 readonly visText?: readonly (string | null)[];
69 /** Positions by n, built the first time they're asked for. */
70 seqIndex?: Map<number, number>;
71 visIndex?: Map<number, number>;
74interface Child {
75 readonly n: number;
76 /** 1 when the child's atom deleted the parent (the child replaces it), else 0. A moved line is 0. */
77 readonly replaces: number;
78 readonly lamport: number;
79 readonly seq: number;
80 readonly k: number;
83const EMPTY_INTS = new Int32Array(0);
84const NO_FILE: FileState = { attrs: NO_ATTRS, complete: true, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() };
86// Approximate retained-container costs for View.weight(): reference slots,
87// object headers, and map/set entries. These are cache-budget units, not V8
88// heap measurements. Referenced Graph strings and records are not charged.
89const ARRAY_HEADER_BYTES = 24;
90const OBJECT_BYTES = 32;
91const MAP_HEADER_BYTES = 32;
92const MAP_ENTRY_BYTES = 40;
93const SET_ENTRY_BYTES = 32;
94const REFERENCE_BYTES = 8;
95const FILE_LOCATION_MEMO_ENTRIES = 256;
96/**
97 * Moved lines a view resolves once and keeps (abso Capacity): a stored graph otherwise resolved every move again on
98 * disk for each file it laid out. Game's whole history has 290; past this many, the view goes back to that.
99 */
100export const MOVED_LINES_KEPT = 20_000;
101class TooManyMoves extends Error {}
102const NO_LINES: readonly number[] = Object.freeze([]);
104/**
105 * The projection of a closed set. Construct once, then ask for files, lines
106 * and sequences. Throws `not-closed` if some atom's dependency is missing.
107 * Each file is laid out the first time it is asked for, so a view of a large
108 * set costs little until files are read.
109 */
110export class View {
111 readonly graph: Graph;
112 /** 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). */
113 #set: AtomSet | undefined;
114 readonly #stable: StableSet<AtomId> | undefined;
115 /** Fixed-size memo for immutable indexed membership, independent of history size. */
116 #membershipSeq = new Float64Array(256).fill(-1);
117 #membershipValue = new Uint8Array(256);
118 #files = new Map<string, FileState>();
119 /** Every file the set wrote in, sorted; worked out the first time it's asked for. */
120 #knownList: string[] | undefined;
121 /** 1 for each atom (by seq) in the set. */
122 #in: Uint8Array;
123 /** Atoms in the set that move lines. */
124 #movers: AtomId[] | undefined;
125 #hasMoves = false;
126 /** Each moved line's relocation that counts in this set; built on first use. */
127 #relocs: Map<LineId, RelocationInfo> | undefined;
128 /** The same, by n, with the new parent's code. */
129 #relocsN: Map<number, { readonly r: RelocationInfo; readonly parent: number }> | undefined;
130 /** The moved lines under each node, by its code, made from the relocations on first use. */
131 #movedInto: Map<number, number[]> | undefined;
132 /** Whether this view's moves are too many to keep, so they're resolved on disk per layout; undefined until asked. */
133 #movesOnDisk: boolean | undefined;
134 /** Bounded memo: ancestry can span the entire history even for one visible line. */
135 #fileOf = new Map<number, string>();
136 /** The latest records asked for: one file's lines, one file's sequence, one file's text. */
137 #linesCache: { path: string; lines: readonly VisibleLine[] } | undefined;
138 #seqCache: { path: string; seq: readonly SeqLine[] } | undefined;
139 #textCache: { path: string; text: string } | undefined;
141 constructor(graph: Graph, set: Iterable<AtomId>) {
142 this.graph = graph;
143 if (set instanceof StableSet) {
144 this.#stable = set;
145 this.#set = set;
146 this.#in = new Uint8Array(0);
147 // A set kept closed when it was written needs no proof here (abso Capacity).
148 for (const id of isClosedSet(set) ? [] : set) {
149 const atom = graph.atom(id);
150 for (const dependency of atom.deps) {
151 graph.atom(dependency);
152 if (!set.has(dependency))
153 throw new EngineError("not-closed", `set is not closed: ${id} depends on ${dependency}`);
154 }
155 }
156 for (const id of graph.movers()) {
157 if (set.has(id)) {
158 this.#hasMoves = true;
159 break;
160 }
161 }
162 this.#relocs = this.#hasMoves ? undefined : new Map();
163 this.#relocsN = this.#hasMoves ? undefined : new Map();
164 return;
165 }
166 const inSet = new Uint8Array(graph.size);
167 for (const id of set) {
168 const atom = graph.atom(id);
169 inSet[atom.seq] = 1;
170 }
171 // Validate one atom at a time. Keeping all decoded atoms here defeats
172 // storage-backed Graph reads even though the view only needs membership.
173 for (let seq = 0; seq < inSet.length; seq++) {
174 if (inSet[seq] !== 1) continue;
175 const atom = graph.atom(graph.idOfSeq(seq));
176 for (const d of atom.deps) {
177 if (inSet[graph.atom(d).seq] !== 1)
178 throw new EngineError("not-closed", `set is not closed: ${atom.id} depends on ${d}`);
179 }
180 }
181 this.graph = graph;
182 this.#in = inSet;
183 this.#movers = graph.movers().filter((id) => inSet[graph.atom(id).seq] === 1);
184 this.#hasMoves = this.#movers.length > 0;
185 this.#relocs = this.#movers.length === 0 ? new Map() : undefined;
186 this.#relocsN = this.#movers.length === 0 ? new Map() : undefined;
187 }
189 /** The set of atoms this view projects. */
190 get set(): AtomSet {
191 if (!this.#set) {
192 const out = new Set<AtomId>();
193 for (let seq = 0; seq < this.#in.length; seq++) if (this.#in[seq] === 1) out.add(this.graph.idOfSeq(seq));
194 this.#set = out;
195 }
196 return this.#set;
197 }
199 /** Whether the atom with this seq is in the set. */
200 #has(seq: number): boolean {
201 if (this.#stable) {
202 const slot = seq % this.#membershipSeq.length;
203 if (this.#membershipSeq[slot] === seq) return this.#membershipValue[slot] === 1;
204 const present = this.#stable.has(this.graph.idOfSeq(seq));
205 this.#membershipSeq[slot] = seq;
206 this.#membershipValue[slot] = present ? 1 : 0;
207 return present;
208 }
209 return seq < this.#in.length && this.#in[seq] === 1;
210 }
212 /**
213 * The relocation that counts for each moved line: the newest (by priority)
214 * in the set. Two moves made apart can loop lines into each other, so no
215 * start node reaches them; then the oldest relocation on the loop is
216 * ignored, and the next newest of that line counts, until none loop.
217 */
218 #relocations(): Map<LineId, RelocationInfo> {
219 if (this.#relocs) return this.#relocs;
220 const graph = this.graph;
221 const stronger = (a: RelocationInfo, b: RelocationInfo): boolean => graph.comparePriority(a.atom, b.atom) > 0;
222 // Persistent reads decode new objects. Cycle suppression must identify the
223 // logical move, not one particular decoded JavaScript object.
224 const identity = (r: RelocationInfo): string => JSON.stringify([r.atom, r.k]);
225 const ignored = new Set<string>();
226 const pick = (line: LineId): RelocationInfo | undefined => {
227 let best: RelocationInfo | undefined;
228 for (const r of graph.eachRelocationOf(line)) {
229 if (this.#has(graph.atom(r.atom).seq) && !ignored.has(identity(r)) && (!best || stronger(r, best))) best = r;
230 }
231 return best;
232 };
233 const relocs = new Map<LineId, RelocationInfo>();
234 for (const id of this.#eachMover()) {
235 for (const m of graph.atom(id).moves!) {
236 if (!relocs.has(m.line)) relocs.set(m.line, pick(m.line)!);
237 if (graph.hasOrderedChildren && relocs.size > MOVED_LINES_KEPT) throw new TooManyMoves();
238 }
239 }
240 const parentOf = (line: LineId): NodeId => relocs.get(line)?.parent ?? graph.lineParent(line)!;
241 const reaches = new Set<LineId>();
242 for (const line of [...relocs.keys()]) {
243 for (;;) {
244 const path: LineId[] = [];
245 const onPath = new Map<LineId, number>();
246 let cur: NodeId = line;
247 let loopAt = -1;
248 while (!isStartNode(cur) && !reaches.has(cur)) {
249 const at = onPath.get(cur);
250 if (at !== undefined) {
251 loopAt = at;
252 break;
253 }
254 onPath.set(cur, path.length);
255 path.push(cur);
256 cur = parentOf(cur);
257 }
258 if (loopAt < 0) {
259 for (const l of path) reaches.add(l);
260 break;
261 }
262 let weakest: RelocationInfo | undefined;
263 for (const l of path.slice(loopAt)) {
264 const r = relocs.get(l);
265 if (r && (!weakest || stronger(weakest, r))) weakest = r;
266 }
267 ignored.add(identity(weakest!));
268 const next = pick(weakest!.line);
269 if (next) relocs.set(weakest!.line, next);
270 else relocs.delete(weakest!.line);
271 }
272 }
273 this.#relocs = relocs;
274 return relocs;
275 }
277 /** Whether moves are resolved on disk for each layout: only a stored graph's view with more than MOVED_LINES_KEPT. */
278 #scratchMoves(): boolean {
279 if (!this.#hasMoves || !this.graph.hasOrderedChildren) return false;
280 if (this.#movesOnDisk === undefined) {
281 try {
282 this.#relocations();
283 this.#movesOnDisk = false;
284 } catch (error) {
285 if (!(error instanceof TooManyMoves)) throw error;
286 this.#movesOnDisk = true;
287 }
288 }
289 return this.#movesOnDisk;
290 }
292 /** The relocations by n, with each new parent's code. */
293 #relocationsN(): Map<number, { readonly r: RelocationInfo; readonly parent: number }> {
294 if (this.#relocsN) return this.#relocsN;
295 const out = new Map<number, { readonly r: RelocationInfo; readonly parent: number }>();
296 for (const [line, r] of this.#relocations())
297 out.set(this.graph.lineN(line), { r, parent: this.graph.codeOf(r.parent)! });
298 this.#relocsN = out;
299 return out;
300 }
302 /** The node a line hangs off in this set: where it was written, or where a move put it. */
303 parentOf(line: LineId): NodeId {
304 if (this.graph.lineParent(line) === undefined) throw new EngineError("unknown-line", `no line ${line}`);
305 if (this.#scratchMoves())
306 return this.graph.withProjectionScratch((scratch) =>
307 resolveScratchMoves(this.graph, (id) => this.#has(this.graph.atom(id).seq), scratch).parent(line),
308 );
309 const r = this.#hasMoves ? this.#relocations().get(line) : undefined;
310 if (r) return r.parent;
311 const parent = this.graph.lineParent(line);
312 if (parent === undefined) throw new EngineError("unknown-line", `no line ${line}`);
313 return parent;
314 }
316 /** Whether any atom in the set moves lines. */
317 hasMoves(): boolean {
318 return this.#hasMoves;
319 }
320 *#eachMover(): IterableIterator<AtomId> {
321 if (this.#movers) yield* this.#movers;
322 else for (const id of this.graph.movers()) if (this.#stable!.has(id)) yield id;
323 }
325 /** The file a line is in, in this set: the one its chain of parents reaches. */
326 fileOf(line: LineId): string {
327 const n = this.graph.lineN(line);
328 if (n < 0) throw new EngineError("unknown-line", `no line ${line}`);
329 return this.#fileOfN(n);
330 }
332 #fileOfN(n: number): string {
333 const graph = this.graph;
334 if (!this.#hasMoves) return graph.writtenIn(n);
335 if (this.#scratchMoves())
336 return graph.withProjectionScratch((scratch) => {
337 const moves = resolveScratchMoves(graph, (id) => this.#has(graph.atom(id).seq), scratch);
338 let current = graph.nodeOf(n);
339 while (!isStartNode(current)) current = moves.parent(current);
340 return current.slice(1);
341 });
342 const relocs = this.#relocationsN();
343 // Keep only a fixed tail of the walk for path compression. The selected
344 // relocation graph is acyclic, so traversal needs no history-sized stack.
345 const path: number[] = [];
346 let visited = 0;
347 let cur = n;
348 let file: string | undefined;
349 while (file === undefined) {
350 if (cur < 0) file = graph.nodeOf(cur).slice(1);
351 else {
352 file = this.#fileOf.get(cur);
353 if (file === undefined) {
354 path[visited++ % FILE_LOCATION_MEMO_ENTRIES] = cur;
355 cur = relocs.get(cur)?.parent ?? graph.parentCodeOf(cur);
356 }
357 }
358 }
359 for (const l of path) {
360 if (!this.#fileOf.has(l) && this.#fileOf.size >= FILE_LOCATION_MEMO_ENTRIES)
361 this.#fileOf.delete(this.#fileOf.keys().next().value!);
362 this.#fileOf.set(l, file);
363 }
364 return file;
365 }
367 /** The lines hanging off a node in this set, in layout order. */
368 #children(code: number): Child[] {
369 const graph = this.graph;
370 const relocs = this.#hasMoves ? this.#relocationsN() : undefined;
371 const out: Child[] = [];
372 for (const n of graph.eachChildN(code)) {
373 const seq = graph.writerSeqOf(n);
374 if (!this.#has(seq) || relocs?.has(n)) continue;
375 out.push({ n, replaces: graph.replacesN(n) ? 1 : 0, lamport: graph.lamportOfSeq(seq), seq, k: graph.kOf(n) });
376 }
377 if (relocs) {
378 // The lines this set's moves put under each node, from the moves it already resolved: no row read per node
379 // (abso Capacity).
380 if (!this.#movedInto) {
381 this.#movedInto = new Map();
382 for (const [n, { parent }] of relocs) {
383 const into = this.#movedInto.get(parent);
384 if (into) into.push(n);
385 else this.#movedInto.set(parent, [n]);
386 }
387 }
388 for (const n of this.#movedInto.get(code) ?? NO_LINES) {
389 const r = relocs.get(n)!.r;
390 const seq = graph.atom(r.atom).seq;
391 out.push({ n, replaces: 0, lamport: graph.lamportOfSeq(seq), seq, k: r.k });
392 }
393 }
394 // A line's replacements (runs of atoms that deleted it) first, then the
395 // rest; each group in descending priority (lamport, then seq); lines of
396 // one atom keep k order. A replacement already outranks every insertion
397 // after the line that reads it (it depends on them, or conflicts with
398 // them); the grouping also puts it above a `before` insertion, which
399 // doesn't read the line above, so the new text lands in the replaced
400 // line's place. A moved line ranks like an insertion by the moving atom.
401 if (out.length > 1)
402 out.sort((a, b) => b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k);
403 return out;
404 }
406 /** Parent/successor traversal keeps no history-sized ancestry or sibling frontier. */
407 *#layoutNodes(start: number): IterableIterator<number> {
408 const graph = this.graph;
409 if (graph.hasOrderedChildren && !this.#hasMoves) {
410 const first = (parent: number, after?: number): number | undefined => {
411 for (const n of graph.orderedChildrenN(parent, after)) if (this.#has(graph.writerSeqOf(n))) return n;
412 return undefined;
413 };
414 let n = first(start);
415 while (n !== undefined) {
416 yield n;
417 const child = first(n);
418 if (child !== undefined) {
419 n = child;
420 continue;
421 }
422 let previous = n;
423 for (;;) {
424 const parent = graph.parentCodeOf(previous);
425 const sibling = first(parent, previous);
426 if (sibling !== undefined) {
427 n = sibling;
428 break;
429 }
430 if (parent === start) {
431 n = undefined;
432 break;
433 }
434 if (parent < 0 || parent >= previous) throw new Error("invalid persistent layout ancestry");
435 previous = parent;
436 }
437 }
438 return;
439 }
440 const stack: number[] = [];
441 const push = (parent: number): void => {
442 const children = this.#children(parent);
443 for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]!.n);
444 };
445 push(start);
446 while (stack.length) {
447 const n = stack.pop()!;
448 yield n;
449 push(n);
450 }
451 }
453 /** Lay out one file: its line tree from the set's atoms, linearized. */
454 #layout(path: string, complete: boolean): FileState {
455 const graph = this.graph;
456 if (graph.packedFiles && !this.#scratchMoves()) return this.#layoutPacked(path, complete);
457 if (this.#scratchMoves())
458 return graph.withProjectionScratch((scratch) =>
459 this.#layoutResolved(
460 path,
461 complete,
462 scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, `^${path}`),
463 ),
464 );
465 return this.#layoutResolved(path, complete);
466 }
468 /** For each path, the files that lines moved into it were written in: worked out once per view. */
469 #movedFrom: Map<string, Set<number>> | undefined;
470 #movedInFrom(): Map<string, Set<number>> {
471 if (this.#movedFrom) return this.#movedFrom;
472 const graph = this.graph;
473 const out = new Map<string, Set<number>>();
474 if (this.#hasMoves) {
475 const relocs = this.#relocationsN();
476 // Where each node sits, walked once for the whole view: through the moves, up to a file's start.
477 const memo = new Map<number, string>();
478 const fileOf = (code: number): string => {
479 const walked: number[] = [];
480 let cur = code;
481 let file: string | undefined;
482 while (file === undefined) {
483 if (cur < 0) file = graph.nodeOf(cur).slice(1);
484 else {
485 file = memo.get(cur);
486 if (file === undefined) {
487 walked.push(cur);
488 cur = relocs.get(cur)?.parent ?? graph.parentCodeOf(cur);
489 }
490 }
491 }
492 for (const n of walked) memo.set(n, file);
493 return file;
494 };
495 for (const [n, { parent }] of relocs) {
496 const into = fileOf(parent);
497 let from = out.get(into);
498 if (!from) out.set(into, (from = new Set()));
499 from.add(graph.writtenInIndex(n));
500 }
501 }
502 this.#movedFrom = out;
503 return out;
504 }
506 /**
507 * Lay one file out from its packed history (abso Capacity, Graph.packedLines): the lines written in it, and in the
508 * files its moved-in lines came from, read a page at a time; the same tree and order as #layoutResolved, built in
509 * memory with no read per line.
510 */
511 #layoutPacked(path: string, complete: boolean): FileState {
512 const graph = this.graph;
513 const attrs = this.#attributes(path);
514 const start = graph.startCodeOf(path);
515 if (start === undefined) return { attrs, complete, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() };
516 const relocs = this.#hasMoves ? this.#relocationsN() : undefined;
517 const files = new Set<number>([-1 - start, ...(this.#movedInFrom().get(path) ?? [])]);
518 const children = new Map<number, Child[]>();
519 const texts = new Map<number, string | null>();
520 const deleters = new Map<number, number[]>();
521 for (const file of files) {
522 const lineTexts = graph.packedTexts(file);
523 for (const [n, parent, seq, k, replaces] of graph.packedLines(file)) {
524 const text = lineTexts.next().value as string | null;
525 if (!this.#has(seq)) continue;
526 const moved = relocs?.get(n);
527 let at = parent;
528 let child: Child = { n, replaces, lamport: graph.lamportOfSeq(seq), seq, k };
529 if (moved) {
530 const mover = graph.atom(moved.r.atom).seq;
531 child = { n, replaces: 0, lamport: graph.lamportOfSeq(mover), seq: mover, k: moved.r.k };
532 at = moved.parent;
533 }
534 const list = children.get(at);
535 if (list) list.push(child);
536 else children.set(at, [child]);
537 texts.set(n, text);
538 }
539 for (const [n, deleter] of graph.packedDeletes(file)) {
540 if (!this.#has(deleter)) continue;
541 const by = deleters.get(n);
542 if (by) by.push(deleter);
543 else deleters.set(n, [deleter]);
544 }
545 }
546 const order = (a: Child, b: Child) =>
547 b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k;
548 const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b;
549 const seq: number[] = [];
550 const vis: number[] = [];
551 const visText: (string | null)[] = [];
552 const deletedBy = new Map<number, readonly number[]>();
553 const stack: number[] = [];
554 const push = (code: number) => {
555 const list = children.get(code);
556 if (!list) return;
557 if (list.length > 1) list.sort(order);
558 for (let i = list.length - 1; i >= 0; i--) stack.push(list[i]!.n);
559 };
560 push(start);
561 while (stack.length) {
562 const n = stack.pop()!;
563 const by = deleters.get(n);
564 if (by) {
565 if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by);
566 } else {
567 vis.push(n);
568 visText.push(texts.get(n) ?? null);
569 }
570 if (complete) seq.push(n);
571 push(n);
572 }
573 return { attrs, complete, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy, visText };
574 }
576 #attributes(path: string): FileAttrs {
577 const graph = this.graph;
578 // For each attribute, the highest-priority setter in the set wins.
579 const setters = new Map<string, { id: AtomId; value: string | null }>();
580 const file = graph.packedFiles ? graph.pathIndexOf(path) : undefined;
581 if (graph.packedFiles) {
582 for (const [seq, name, value] of file === undefined ? [] : graph.packedAttrs(file)) {
583 if (!this.#has(seq)) continue;
584 const id = graph.idOfSeq(seq);
585 const best = setters.get(name);
586 if (!best || graph.comparePriority(best.id, id) < 0) setters.set(name, { id, value });
587 }
588 return {
589 exists: setters.get("exists")?.value === "1",
590 exec: setters.get("exec")?.value === "1",
591 link: setters.get("link")?.value ?? null,
592 blob: setters.get("blob")?.value ?? null,
593 };
594 }
595 for (const id of graph.eachAtomIn(path)) {
596 if (!this.#has(graph.atom(id).seq)) continue;
597 for (const a of graph.atom(id).attrs ?? []) {
598 if (a.file !== path) continue;
599 const best = setters.get(a.name);
600 if (!best || graph.comparePriority(best.id, id) < 0) setters.set(a.name, { id, value: a.value });
601 }
602 }
604 return {
605 exists: setters.get("exists")?.value === "1",
606 exec: setters.get("exec")?.value === "1",
607 link: setters.get("link")?.value ?? null,
608 blob: setters.get("blob")?.value ?? null,
609 };
610 }
612 #layoutResolved(path: string, complete: boolean, nodes?: Iterable<number>): FileState {
613 const graph = this.graph;
614 const attrs = this.#attributes(path);
615 const seq: number[] = [];
616 const vis: number[] = [];
617 const deletedBy = new Map<number, readonly number[]>();
619 const start = graph.startCodeOf(path);
620 const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b;
621 for (const n of nodes ?? (start === undefined ? [] : this.#layoutNodes(start))) {
622 let deleted = false;
623 const by: number[] = [];
624 for (const deleter of graph.eachDeleterSeqOf(n)) {
625 if (!this.#has(deleter)) continue;
626 deleted = true;
627 if (!complete) break;
628 by.push(deleter);
629 }
630 if (deleted) {
631 if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by);
632 } else vis.push(n);
633 if (complete) seq.push(n);
634 }
636 return { attrs, complete, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy };
637 }
639 get #known(): string[] {
640 if (!this.#knownList) {
641 const known = new Set<string>();
642 if (this.#stable) {
643 for (const id of this.#stable) for (const file of this.graph.filesOf(id)) known.add(file);
644 } else {
645 for (let seq = 0; seq < this.#in.length; seq++)
646 if (this.#in[seq] === 1) for (const file of this.graph.filesOf(this.graph.idOfSeq(seq))) known.add(file);
647 }
648 this.#knownList = [...known].sort();
649 }
650 return this.#knownList;
651 }
653 /** Files with at least one visible line, sorted. */
654 paths(): string[] {
655 if (this.#stable) {
656 const paths: string[] = [];
657 for (const path of this.graph.knownFiles()) {
658 if (this.hasFile(path)) paths.push(path);
659 else this.#files.delete(path);
660 }
661 return paths.sort();
662 }
663 return this.#known.filter((p) => this.hasFile(p));
664 }
666 /** Every file the set has ever written a line in, including fully deleted ones. */
667 knownPaths(): string[] {
668 return [...this.#known];
669 }
671 /** Whether the file exists in this projection (has a visible line). */
672 hasFile(path: string): boolean {
673 const attrs = this.attrs(path);
674 return attrs.exists || attrs.link !== null || attrs.blob !== null || this.#file(path).vis.length > 0;
675 }
677 /** A file's attributes: kept while empty, executable, a link's target. */
678 attrs(path: string): FileAttrs {
679 return this.#files.get(path)?.attrs ?? this.#attributes(path);
680 }
682 /** The projected text of a file ("" if it has no visible lines). */
683 text(path: string): string {
684 if (this.#textCache?.path === path) return this.#textCache.text;
685 const { vis, visText } = this.#file(path);
686 const lines: string[] = new Array(vis.length);
687 for (let i = 0; i < vis.length; i++) lines[i] = visText?.[i] ?? this.graph.textOf(vis[i]!);
688 const text = joinLines(lines);
689 this.#textCache = { path, text };
690 return text;
691 }
693 /** Whether a file reads the same here and in `other` (of the same graph), compared line by line without joining either (#46). */
694 sameText(path: string, other: ReadView): boolean {
695 if (!(other instanceof View)) {
696 const a = this.lines(path),
697 b = other.lines(path);
698 return a.length === b.length && a.every((line, i) => line.text === b[i]!.text);
699 }
700 const a = this.#file(path).vis;
701 const b = other.#file(path).vis;
702 if (a.length !== b.length) return false;
703 for (let i = 0; i < a.length; i++)
704 if (a[i] !== b[i] && this.graph.textOf(a[i]!) !== this.graph.textOf(b[i]!)) return false;
705 return true;
706 }
708 *lineChunks(path: string): IterableIterator<() => Iterable<string>> {
709 for (const n of this.#file(path).vis) yield () => this.graph.textChunks(n);
710 }
712 /** Visible lines without retaining their text in the view cache. */
713 *visibleLines(path: string): IterableIterator<VisibleLine> {
714 const graph = this.graph;
715 for (const n of this.#file(path).vis)
716 yield { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) };
717 }
719 /** Atom-building line handles; text is loaded only when requested. */
720 buildLines(path: string): readonly VisibleLine[] {
721 const graph = this.graph;
722 const vis = this.#file(path).vis;
723 const lines: VisibleLine[] = new Array(vis.length);
724 for (let i = 0; i < vis.length; i++) {
725 const n = vis[i]!;
726 lines[i] = {
727 id: graph.lineIdOf(n),
728 textChunks: () => graph.textChunks(n),
729 get text() {
730 return graph.textOf(n);
731 },
732 atom: graph.idOfSeq(graph.writerSeqOf(n)),
733 };
734 }
735 return lines;
736 }
738 /** Visible lines with their ids. */
739 lines(path: string): readonly VisibleLine[] {
740 if (this.#linesCache?.path === path) return this.#linesCache.lines;
741 const graph = this.graph;
742 const vis = this.#file(path).vis;
743 const lines: VisibleLine[] = new Array(vis.length);
744 for (let i = 0; i < vis.length; i++) {
745 const n = vis[i]!;
746 lines[i] = { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) };
747 }
748 this.#linesCache = { path, lines };
749 return lines;
750 }
752 /** The full linearized sequence of a file, tombstones included. */
753 sequence(path: string): readonly SeqLine[] {
754 if (this.#seqCache?.path === path) return this.#seqCache.seq;
755 const graph = this.graph;
756 const f = this.#file(path, true);
757 const out: SeqLine[] = new Array(f.seq.length);
758 for (let i = 0; i < f.seq.length; i++) {
759 const n = f.seq[i]!;
760 const by = f.deletedBy.get(i);
761 out[i] = {
762 id: graph.lineIdOf(n),
763 text: graph.textOf(n),
764 atom: graph.idOfSeq(graph.writerSeqOf(n)),
765 deletedBy: by ? by.map((s) => graph.idOfSeq(s)) : NONE,
766 visible: by === undefined,
767 };
768 }
769 this.#seqCache = { path, seq: out };
770 return out;
771 }
773 /** Two visible neighbours without retaining the file's historical sequence. */
774 visibleNeighbours(path: string, line: LineId): LineId[] {
775 const graph = this.graph;
776 const target = graph.lineN(line);
777 const start = graph.startCodeOf(path);
778 if (target < 0 || start === undefined) return [];
779 const scan = (nodes: Iterable<number>): LineId[] => {
780 let previous: LineId | undefined;
781 let found = false;
782 for (const n of nodes) {
783 if (n === target) {
784 found = true;
785 continue;
786 }
787 let deleted = false;
788 for (const seq of graph.eachDeleterSeqOf(n))
789 if (this.#has(seq)) {
790 deleted = true;
791 break;
792 }
793 if (deleted) continue;
794 const id = graph.lineIdOf(n);
795 if (found) return previous === undefined ? [id] : [previous, id];
796 previous = id;
797 }
798 return found && previous !== undefined ? [previous] : [];
799 };
800 if (this.#scratchMoves())
801 return graph.withProjectionScratch((scratch) =>
802 scan(scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, graph.nodeOf(start))),
803 );
804 return scan(this.#layoutNodes(start));
805 }
807 /** Index of a line in `sequence(path)`, or -1. */
808 sequenceIndex(path: string, line: LineId): number {
809 const f = this.#file(path, true);
810 if (!f.seqIndex) {
811 f.seqIndex = new Map();
812 for (let i = 0; i < f.seq.length; i++) f.seqIndex.set(f.seq[i]!, i);
813 }
814 return f.seqIndex.get(this.graph.lineN(line)) ?? -1;
815 }
817 /** Index of a line in `lines(path)` (0-based visible line number), or -1 if not visible. */
818 lineNumber(path: string, line: LineId): number {
819 const f = this.#file(path);
820 if (!f.visIndex) {
821 f.visIndex = new Map();
822 for (let i = 0; i < f.vis.length; i++) f.visIndex.set(f.vis[i]!, i);
823 }
824 return f.visIndex.get(this.graph.lineN(line)) ?? -1;
825 }
827 /** All projected text files, path -> text, in path order. Binary files are in `blobs()`. */
828 files(): Record<string, string> {
829 const out: Record<string, string> = {};
830 for (const path of this.paths()) if (this.#file(path).attrs.blob === null) out[path] = this.text(path);
831 return out;
832 }
834 /** Binary files, path -> the SHA-256 of their bytes, in path order. */
835 blobs(): Record<string, string> {
836 const out: Record<string, string> = {};
837 for (const path of this.paths()) {
838 const blob = this.#file(path).attrs.blob;
839 if (blob !== null) out[path] = blob;
840 }
841 return out;
842 }
844 /**
845 * About how many bytes of retained state this view costs (#46). This uses
846 * approximate ownership costs for containers and wrappers, not V8 heap
847 * measurements. Graph-owned strings and records count only as references.
848 * This method only inspects already-created state: it does not lay out files,
849 * populate lazy caches, enumerate the graph, or count temporary traversal
850 * containers and shared empty singleton payloads as retained view state.
851 */
852 weight(): number {
853 let n = this.#in.byteLength;
854 n += 2 * ARRAY_HEADER_BYTES + this.#membershipSeq.byteLength + this.#membershipValue.byteLength;
855 if (this.#movers) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#movers.length;
856 n += MAP_HEADER_BYTES; // #files exists from construction.
857 n += MAP_HEADER_BYTES; // #fileOf exists from construction.
858 if (this.#stable) n += this.#stable.retainedBytes;
859 else if (this.#set) n += OBJECT_BYTES + SET_ENTRY_BYTES * this.#set.size;
860 if (this.#knownList) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#knownList.length;
861 if (this.#relocs) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * this.#relocs.size;
862 if (this.#relocsN) n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + OBJECT_BYTES) * this.#relocsN.size;
863 n += MAP_ENTRY_BYTES * this.#fileOf.size;
864 for (const f of this.#files.values()) {
865 n += MAP_ENTRY_BYTES;
866 if (f !== NO_FILE) {
867 // FileState and FileAttrs are per laid-out file; typed-array
868 // headers are separate from their payload byte lengths below.
869 n += OBJECT_BYTES + OBJECT_BYTES + 2 * ARRAY_HEADER_BYTES;
870 n += f.seq.byteLength + f.vis.byteLength;
871 if (f.visText) for (const text of f.visText) n += REFERENCE_BYTES + 2 * (text?.length ?? 0);
872 n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + ARRAY_HEADER_BYTES) * f.deletedBy.size;
873 for (const deleters of f.deletedBy.values()) n += REFERENCE_BYTES * deleters.length;
874 if (f.seqIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.seqIndex.size;
875 if (f.visIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.visIndex.size;
876 }
877 }
878 if (this.#linesCache)
879 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 100 * this.#linesCache.lines.length;
880 if (this.#seqCache) {
881 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 120 * this.#seqCache.seq.length;
882 for (const line of this.#seqCache.seq)
883 if (line.deletedBy !== NONE) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * line.deletedBy.length;
884 }
885 if (this.#textCache) n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 2 * this.#textCache.text.length;
886 return n;
887 }
889 #file(path: string, complete = false): FileState {
890 let state = this.#files.get(path);
891 if (!state || (complete && !state.complete)) {
892 state = this.graph.hasAtomsIn(path) ? this.#layout(path, complete) : NO_FILE;
893 this.#files.set(path, state);
894 }
895 return state;
896 }
899/** The files of a closed set, path -> text. */
900export function project(graph: Graph, set: Iterable<AtomId>): Record<string, string> {
901 return new View(graph, set).files();
904/** Where a node sits in a file's sequence: the index just after it (0 for a start node). */
905export function indexAfter(view: Pick<ReadView, "sequenceIndex">, path: string, node: NodeId): number {
906 if (isStartNode(node)) return 0;
907 const i = view.sequenceIndex(path, node);
908 if (i < 0) throw new EngineError("not-in-view", `line ${node} is not in ${path} in this view`);
909 return i + 1;