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