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