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=235&format=json
1,148 linescapacity 43% · First import 32% · codex-capacity-chair 21% · codex-capacity-policy 4%Last change capacity in version 235, 33 versions changed it

You're reading version 235. The newest is 318, and 12 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, lineId, 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;
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<
51 Pick<View, keyof View>,
52 "sameText" | "visibleCount" | "shareMoves" | "shareFiles" | "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 /** Its visible lines' writers' seqs, when laid out from the file's packed history. */
73 readonly visWriter?: Int32Array;
74 /** Its visible lines' places in their writers (a line id's k), when laid out from packed history. */
75 readonly visK?: Int32Array;
76 /** The same for every line of seq, when complete and laid out from packed history. */
77 readonly seqWriter?: Int32Array;
78 readonly seqK?: Int32Array;
79 /** Positions by n, built the first time they're asked for. */
80 seqIndex?: Map<number, number>;
81 visIndex?: Map<number, number>;
84interface Child {
85 readonly n: number;
86 /** 1 when the child's atom deleted the parent (the child replaces it), else 0. A moved line is 0. */
87 readonly replaces: number;
88 readonly lamport: number;
89 readonly seq: number;
90 readonly k: number;
93const EMPTY_INTS = new Int32Array(0);
94const NO_FILE: FileState = { attrs: NO_ATTRS, complete: true, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() };
96// Approximate retained-container costs for View.weight(): reference slots,
97// object headers, and map/set entries. These are cache-budget units, not V8
98// heap measurements. Referenced Graph strings and records are not charged.
99const ARRAY_HEADER_BYTES = 24;
100const OBJECT_BYTES = 32;
101const MAP_HEADER_BYTES = 32;
102const MAP_ENTRY_BYTES = 40;
103const SET_ENTRY_BYTES = 32;
104const REFERENCE_BYTES = 8;
105/**
106 * Moved lines a view resolves once and keeps (abso Capacity): a stored graph otherwise resolved every move again on
107 * disk for each file it laid out. Game's whole history has 290; past this many, the view goes back to that.
108 */
109export const MOVED_LINES_KEPT = 20_000;
110class TooManyMoves extends Error {}
111const NO_LINES: readonly number[] = Object.freeze([]);
112/** Nodes whose nearest moved line above a graph remembers, at most: about 40 bytes each. */
113const CLIMB_MEMO = 200_000;
115/** One relocation of a moved line, with its line's number and its new parent's code. */
116interface MoveEntry {
117 readonly n: number;
118 readonly r: RelocationInfo;
119 readonly parent: number;
122/**
123 * A graph's moves, whatever the set (abso Capacity): each mover's moved lines, each moved line's relocations in seq
124 * order, and for any node the nearest node at or above it, by where lines were written, that a move ever relocated,
125 * or its file's start. Worked out once per graph and extended as it grows. A view's moves then resolve over the moved
126 * lines alone: before, every view walked each moved line's file up to its start, a read per line.
127 */
128class MoveSkeleton {
129 readonly #graph: Graph;
130 #seen = 0;
131 /** Movers in seq order, with the numbers of the lines each moves, in its moves' order. */
132 readonly movers: { readonly seq: number; readonly lines: readonly number[] }[] = [];
133 /** Every relocation of each moved line, by the line's number, in seq order. */
134 readonly byLine = new Map<number, MoveEntry[]>();
135 readonly #climbed = new Map<number, number>();
137 constructor(graph: Graph) {
138 this.#graph = graph;
139 }
141 /** Take in movers the graph gained since. */
142 update(): this {
143 const graph = this.#graph;
144 const all = graph.movers();
145 if (this.#seen === all.length) return this;
146 for (; this.#seen < all.length; this.#seen++) {
147 const id = all[this.#seen]!;
148 const lines: number[] = [];
149 graph.atom(id).moves!.forEach((m, k) => {
150 const n = graph.lineN(m.line);
151 const r: RelocationInfo = Object.freeze({ atom: id, line: m.line, parent: m.parent, k });
152 const entry: MoveEntry = { n, r, parent: graph.codeOf(m.parent)! };
153 const list = this.byLine.get(n);
154 if (list) list.push(entry);
155 else this.byLine.set(n, [entry]);
156 lines.push(n);
157 });
158 this.movers.push({ seq: seqOf(id), lines });
159 }
160 // A new moved line can sit between a node and the one it climbed to.
161 this.#climbed.clear();
162 return this;
163 }
165 /** The nearest node at or above this one, by where lines were written, that a move ever relocated; or its file's start. */
166 climb(code: number): number {
167 const walked: number[] = [];
168 let c = code;
169 while (c >= 0 && !this.byLine.has(c)) {
170 const known = this.#climbed.get(c);
171 if (known !== undefined) {
172 c = known;
173 break;
174 }
175 walked.push(c);
176 c = this.#graph.parentCodeOf(c);
177 }
178 if (this.#climbed.size + walked.length > CLIMB_MEMO) this.#climbed.clear();
179 for (const w of walked) this.#climbed.set(w, c);
180 return c;
181 }
184const skeletons = new WeakMap<Graph, MoveSkeleton>();
185function skeletonOf(graph: Graph): MoveSkeleton {
186 let skeleton = skeletons.get(graph);
187 if (!skeleton) skeletons.set(graph, (skeleton = new MoveSkeleton(graph)));
188 return skeleton.update();
191/**
192 * The projection of a closed set. Construct once, then ask for files, lines
193 * and sequences. Throws `not-closed` if some atom's dependency is missing.
194 * Each file is laid out the first time it is asked for, so a view of a large
195 * set costs little until files are read.
196 */
197export class View {
198 readonly graph: Graph;
199 /** 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). */
200 #set: AtomSet | undefined;
201 readonly #stable: StableSet<AtomId> | undefined;
202 /** Fixed-size memo for immutable indexed membership, independent of history size. */
203 #membershipSeq = new Float64Array(256).fill(-1);
204 #membershipValue = new Uint8Array(256);
205 #files = new Map<string, FileState>();
206 /** Every file the set wrote in, sorted; worked out the first time it's asked for. */
207 #knownList: string[] | undefined;
208 /** 1 for each atom (by seq) in the set. */
209 #in: Uint8Array;
210 /** Atoms in the set that move lines. */
211 #movers: AtomId[] | undefined;
212 #hasMoves = false;
213 /** Each moved line's relocation that counts in this set; built on first use. */
214 #relocs: Map<LineId, RelocationInfo> | undefined;
215 /** The same, by n, with the new parent's code. */
216 #relocsN: Map<number, { readonly r: RelocationInfo; readonly parent: number }> | undefined;
217 /** The moved lines under each node, by its code, made from the relocations on first use. */
218 #movedInto: Map<number, number[]> | undefined;
219 /** Whether this view's moves are too many to keep, so they're resolved on disk per layout; undefined until asked. */
220 #movesOnDisk: boolean | undefined;
221 /** The latest records asked for: one file's lines, one file's sequence, one file's text. */
222 #linesCache: { path: string; lines: readonly VisibleLine[] } | undefined;
223 #seqCache: { path: string; seq: readonly SeqLine[] } | undefined;
224 #textCache: { path: string; text: string } | undefined;
226 constructor(graph: Graph, set: Iterable<AtomId>) {
227 this.graph = graph;
228 if (set instanceof StableSet) {
229 this.#stable = set;
230 this.#set = set;
231 this.#in = new Uint8Array(0);
232 // A set kept closed when it was written needs no proof here (abso Capacity).
233 for (const id of isClosedSet(set) ? [] : set) {
234 const atom = graph.atom(id);
235 for (const dependency of atom.deps) {
236 graph.atom(dependency);
237 if (!set.has(dependency))
238 throw new EngineError("not-closed", `set is not closed: ${id} depends on ${dependency}`);
239 }
240 }
241 for (const id of graph.movers()) {
242 if (set.has(id)) {
243 this.#hasMoves = true;
244 break;
245 }
246 }
247 this.#relocs = this.#hasMoves ? undefined : new Map();
248 this.#relocsN = this.#hasMoves ? undefined : new Map();
249 return;
250 }
251 const inSet = new Uint8Array(graph.size);
252 // An atom's number is in its id (abso Capacity): reading the atom for it read the whole history on a stored graph.
253 const seqIn = (id: AtomId): number => {
254 const seq = seqOf(id);
255 return seq >= 0 && seq < inSet.length && graph.idOfSeq(seq) === id ? seq : graph.atom(id).seq;
256 };
257 for (const id of set) inSet[seqIn(id)] = 1;
258 // Validate one atom at a time. Keeping all decoded atoms here defeats
259 // storage-backed Graph reads even though the view only needs membership.
260 for (let seq = 0; seq < inSet.length; seq++) {
261 if (inSet[seq] !== 1) continue;
262 const atom = graph.atom(graph.idOfSeq(seq));
263 for (const d of atom.deps) {
264 if (inSet[seqIn(d)] !== 1) throw new EngineError("not-closed", `set is not closed: ${atom.id} depends on ${d}`);
265 }
266 }
267 this.graph = graph;
268 this.#in = inSet;
269 this.#movers = graph.movers().filter((id) => inSet[seqOf(id)] === 1);
270 this.#hasMoves = this.#movers.length > 0;
271 this.#relocs = this.#movers.length === 0 ? new Map() : undefined;
272 this.#relocsN = this.#movers.length === 0 ? new Map() : undefined;
273 }
275 /** The set of atoms this view projects. */
276 get set(): AtomSet {
277 if (!this.#set) {
278 const out = new Set<AtomId>();
279 for (let seq = 0; seq < this.#in.length; seq++) if (this.#in[seq] === 1) out.add(this.graph.idOfSeq(seq));
280 this.#set = out;
281 }
282 return this.#set;
283 }
285 /** Whether the atom with this seq is in the set. */
286 #has(seq: number): boolean {
287 if (this.#stable) {
288 const slot = seq % this.#membershipSeq.length;
289 if (this.#membershipSeq[slot] === seq) return this.#membershipValue[slot] === 1;
290 const present = this.#stable.has(this.graph.idOfSeq(seq));
291 this.#membershipSeq[slot] = seq;
292 this.#membershipValue[slot] = present ? 1 : 0;
293 return present;
294 }
295 return seq < this.#in.length && this.#in[seq] === 1;
296 }
298 /**
299 * The relocation that counts for each moved line: the newest (by priority)
300 * in the set. Two moves made apart can loop lines into each other, so no
301 * start node reaches them; then the oldest relocation on the loop is
302 * ignored, and the next newest of that line counts, until none loop.
303 */
304 #relocations(): Map<LineId, RelocationInfo> {
305 if (this.#relocs) return this.#relocs;
306 this.#takeShared();
307 if (this.#relocs) return this.#relocs;
308 const graph = this.graph;
309 const skeleton = skeletonOf(graph);
310 const stronger = (a: RelocationInfo, b: RelocationInfo): boolean => graph.comparePriority(a.atom, b.atom) > 0;
311 const identity = (r: RelocationInfo): string => JSON.stringify([r.atom, r.k]);
312 const ignored = new Set<string>();
313 const pick = (n: number): MoveEntry | undefined => {
314 let best: MoveEntry | undefined;
315 for (const e of skeleton.byLine.get(n) ?? []) {
316 if (this.#has(seqOf(e.r.atom)) && !ignored.has(identity(e.r)) && (!best || stronger(e.r, best.r))) best = e;
317 }
318 return best;
319 };
320 // By the moved line's number, in the order its movers come (seq order, then each mover's moves).
321 const relocs = new Map<number, MoveEntry>();
322 for (const mover of skeleton.movers) {
323 if (!this.#has(mover.seq)) continue;
324 for (const n of mover.lines) {
325 if (!relocs.has(n)) relocs.set(n, pick(n)!);
326 if (graph.hasOrderedChildren && relocs.size > MOVED_LINES_KEPT) throw new TooManyMoves();
327 }
328 }
329 // From a node, the next node that matters for loops: a line moved in this set, or a file's start.
330 const hop = (code: number): number => {
331 let c = skeleton.climb(code);
332 while (c >= 0 && !relocs.has(c)) c = skeleton.climb(graph.parentCodeOf(c));
333 return c;
334 };
335 const step = (n: number): number => {
336 const e = relocs.get(n);
337 return hop(e ? e.parent : graph.parentCodeOf(n));
338 };
339 // Two moves made apart can loop lines into each other, so no start node reaches them; then the oldest
340 // relocation on the loop is ignored, and the next newest of that line counts, until none loop.
341 const reaches = new Set<number>();
342 for (const line of [...relocs.keys()]) {
343 for (;;) {
344 const path: number[] = [];
345 const onPath = new Map<number, number>();
346 let cur = line;
347 let loopAt = -1;
348 while (cur >= 0 && !reaches.has(cur)) {
349 const at = onPath.get(cur);
350 if (at !== undefined) {
351 loopAt = at;
352 break;
353 }
354 onPath.set(cur, path.length);
355 path.push(cur);
356 cur = step(cur);
357 }
358 if (loopAt < 0) {
359 for (const l of path) reaches.add(l);
360 break;
361 }
362 let weakest: MoveEntry | undefined;
363 for (const l of path.slice(loopAt)) {
364 const e = relocs.get(l);
365 if (e && (!weakest || stronger(weakest.r, e.r))) weakest = e;
366 }
367 ignored.add(identity(weakest!.r));
368 const next = pick(weakest!.n);
369 if (next) relocs.set(weakest!.n, next);
370 else relocs.delete(weakest!.n);
371 }
372 }
373 this.#relocsN = new Map([...relocs].map(([n, e]) => [n, { r: e.r, parent: e.parent }]));
374 this.#relocs = new Map([...relocs.values()].map((e) => [e.r.line, e.r]));
375 return this.#relocs;
376 }
378 /** The view whose moves this one may take, until it needs them all; then the view it took them from. */
379 #movesFrom: View | undefined;
380 #movesTaken: View | undefined;
382 /**
383 * Take another view's resolved moves (abso Capacity), when both sets hold the very same atoms that move lines: the
384 * moves then resolve the same, and every line sits where it sits there. Checked when this view first needs all its
385 * moves, so any caller may ask, and a view that only finds a few lines' files never resolves them.
386 */
387 shareMoves(from: View): void {
388 if (from.graph !== this.graph || from.#hasMoves !== this.#hasMoves || !this.#hasMoves || this.#relocs) return;
389 this.#movesFrom = from;
390 }
392 /**
393 * Files laid out as another view lays them out (abso Capacity): a draft's view over its base's, for every file the
394 * draft doesn't touch. The caller knows what the draft is; `except` is asked once, when a file is first needed, for
395 * the files the draft touches, or undefined when nothing can be shared (a draft that moves lines). Without it, an
396 * agent's tree, files and blame laid out every file of the project again for each agent.
397 */
398 shareFiles(from: View, except: () => ReadonlySet<string> | undefined): void {
399 if (from.graph !== this.graph || from === this || this.#filesFrom !== undefined) return;
400 this.#filesFrom = { from, except };
401 }
402 #filesFrom: { from: View; except: () => ReadonlySet<string> | undefined } | null | undefined;
403 #filesShared: { from: View; except: ReadonlySet<string> } | null | undefined;
404 #sharedFiles(): { from: View; except: ReadonlySet<string> } | null {
405 if (this.#filesShared === undefined) {
406 const share = this.#filesFrom;
407 const except = share ? share.except() : undefined;
408 this.#filesShared = share && except ? { from: share.from, except } : null;
409 }
410 return this.#filesShared;
411 }
413 #takeShared(): void {
414 const from = this.#movesFrom;
415 if (!from) return;
416 this.#movesFrom = undefined;
417 if (from.#scratchMoves()) return;
418 for (const id of this.graph.movers()) {
419 const seq = seqOf(id);
420 if (this.#has(seq) !== from.#has(seq)) return;
421 }
422 this.#relocs = from.#relocations();
423 this.#relocsN = from.#relocationsN();
424 this.#movesOnDisk = false;
425 this.#movesTaken = from;
426 }
428 /** Moved lines' relocations picked one at a time, before the view resolves them all (null: not moved here). */
429 readonly #picked = new Map<number, MoveEntry | null>();
431 /**
432 * The relocation of moved line n that counts here, as #relocations picks it before any loop: right whenever the
433 * walk that reached n goes on to a file's start, since only lines on a loop have their relocation set aside.
434 */
435 #pickOne(n: number): MoveEntry | undefined {
436 let picked = this.#picked.get(n);
437 if (picked === undefined) {
438 const graph = this.graph;
439 let best: MoveEntry | undefined;
440 for (const e of skeletonOf(graph).byLine.get(n) ?? []) {
441 if (this.#has(seqOf(e.r.atom)) && (!best || graph.comparePriority(e.r.atom, best.r.atom) > 0)) best = e;
442 }
443 this.#picked.set(n, (picked = best ?? null));
444 }
445 return picked ?? undefined;
446 }
448 /** Whether moves are resolved on disk for each layout: only a stored graph's view with more than MOVED_LINES_KEPT. */
449 #scratchMoves(): boolean {
450 if (!this.#hasMoves || !this.graph.hasOrderedChildren) return false;
451 if (this.#movesOnDisk === undefined) {
452 try {
453 this.#relocations();
454 this.#movesOnDisk = false;
455 } catch (error) {
456 if (!(error instanceof TooManyMoves)) throw error;
457 this.#movesOnDisk = true;
458 }
459 }
460 return this.#movesOnDisk;
461 }
463 /** The relocations by n, with each new parent's code. */
464 #relocationsN(): Map<number, { readonly r: RelocationInfo; readonly parent: number }> {
465 if (this.#relocsN) return this.#relocsN;
466 const out = new Map<number, { readonly r: RelocationInfo; readonly parent: number }>();
467 for (const [line, r] of this.#relocations())
468 out.set(this.graph.lineN(line), { r, parent: this.graph.codeOf(r.parent)! });
469 this.#relocsN = out;
470 return out;
471 }
473 /** The node a line hangs off in this set: where it was written, or where a move put it. */
474 parentOf(line: LineId): NodeId {
475 if (this.graph.lineParent(line) === undefined) throw new EngineError("unknown-line", `no line ${line}`);
476 if (this.#scratchMoves())
477 return this.graph.withProjectionScratch((scratch) =>
478 resolveScratchMoves(this.graph, (id) => this.#has(this.graph.atom(id).seq), scratch).parent(line),
479 );
480 const r = this.#hasMoves ? this.#relocations().get(line) : undefined;
481 if (r) return r.parent;
482 const parent = this.graph.lineParent(line);
483 if (parent === undefined) throw new EngineError("unknown-line", `no line ${line}`);
484 return parent;
485 }
487 /** Whether any atom in the set moves lines. */
488 hasMoves(): boolean {
489 return this.#hasMoves;
490 }
492 /** The file a line is in, in this set: the one its chain of parents reaches. */
493 fileOf(line: LineId): string {
494 const n = this.graph.lineN(line);
495 if (n < 0) throw new EngineError("unknown-line", `no line ${line}`);
496 return this.#fileOfN(n);
497 }
499 #fileOfN(n: number): string {
500 const graph = this.graph;
501 if (!this.#hasMoves) return graph.writtenIn(n);
502 if (this.#scratchMoves())
503 return graph.withProjectionScratch((scratch) => {
504 const moves = resolveScratchMoves(graph, (id) => this.#has(graph.atom(id).seq), scratch);
505 let current = graph.nodeOf(n);
506 while (!isStartNode(current)) current = moves.parent(current);
507 return current.slice(1);
508 });
509 return this.#fileOfCode(n);
510 }
512 /** The file a node sits in, in this set: up by where lines were written, through the moves that count here. */
513 #fileOfCode(code: number): string {
514 const graph = this.graph;
515 const skeleton = skeletonOf(graph);
516 if (!this.#relocsN) {
517 // One moved line at a time, until a walk comes back to a line it passed: then moves loop, and are resolved whole.
518 const passed = new Set<number>();
519 let c = code;
520 for (;;) {
521 c = skeleton.climb(c);
522 if (c < 0) return graph.nodeOf(c).slice(1);
523 if (passed.has(c)) break;
524 passed.add(c);
525 const e = this.#pickOne(c);
526 c = e ? e.parent : graph.parentCodeOf(c);
527 }
528 }
529 const relocs = this.#relocationsN();
530 let c = code;
531 for (;;) {
532 c = skeleton.climb(c);
533 if (c < 0) return graph.nodeOf(c).slice(1);
534 const e = relocs.get(c);
535 c = e ? e.parent : graph.parentCodeOf(c);
536 }
537 }
539 /** The lines hanging off a node in this set, in layout order. */
540 #children(code: number): Child[] {
541 const graph = this.graph;
542 const relocs = this.#hasMoves ? this.#relocationsN() : undefined;
543 const out: Child[] = [];
544 for (const n of graph.eachChildN(code)) {
545 const seq = graph.writerSeqOf(n);
546 if (!this.#has(seq) || relocs?.has(n)) continue;
547 out.push({ n, replaces: graph.replacesN(n) ? 1 : 0, lamport: graph.lamportOfSeq(seq), seq, k: graph.kOf(n) });
548 }
549 if (relocs) {
550 // The lines this set's moves put under each node, from the moves it already resolved: no row read per node
551 // (abso Capacity).
552 if (!this.#movedInto) {
553 this.#movedInto = new Map();
554 for (const [n, { parent }] of relocs) {
555 const into = this.#movedInto.get(parent);
556 if (into) into.push(n);
557 else this.#movedInto.set(parent, [n]);
558 }
559 }
560 for (const n of this.#movedInto.get(code) ?? NO_LINES) {
561 const r = relocs.get(n)!.r;
562 const seq = graph.atom(r.atom).seq;
563 out.push({ n, replaces: 0, lamport: graph.lamportOfSeq(seq), seq, k: r.k });
564 }
565 }
566 // A line's replacements (runs of atoms that deleted it) first, then the
567 // rest; each group in descending priority (lamport, then seq); lines of
568 // one atom keep k order. A replacement already outranks every insertion
569 // after the line that reads it (it depends on them, or conflicts with
570 // them); the grouping also puts it above a `before` insertion, which
571 // doesn't read the line above, so the new text lands in the replaced
572 // line's place. A moved line ranks like an insertion by the moving atom.
573 if (out.length > 1)
574 out.sort((a, b) => b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k);
575 return out;
576 }
578 /** Parent/successor traversal keeps no history-sized ancestry or sibling frontier. */
579 *#layoutNodes(start: number): IterableIterator<number> {
580 const graph = this.graph;
581 if (graph.hasOrderedChildren && !this.#hasMoves) {
582 const first = (parent: number, after?: number): number | undefined => {
583 for (const n of graph.orderedChildrenN(parent, after)) if (this.#has(graph.writerSeqOf(n))) return n;
584 return undefined;
585 };
586 let n = first(start);
587 while (n !== undefined) {
588 yield n;
589 const child = first(n);
590 if (child !== undefined) {
591 n = child;
592 continue;
593 }
594 let previous = n;
595 for (;;) {
596 const parent = graph.parentCodeOf(previous);
597 const sibling = first(parent, previous);
598 if (sibling !== undefined) {
599 n = sibling;
600 break;
601 }
602 if (parent === start) {
603 n = undefined;
604 break;
605 }
606 if (parent < 0 || parent >= previous) throw new Error("invalid persistent layout ancestry");
607 previous = parent;
608 }
609 }
610 return;
611 }
612 const stack: number[] = [];
613 const push = (parent: number): void => {
614 const children = this.#children(parent);
615 for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]!.n);
616 };
617 push(start);
618 while (stack.length) {
619 const n = stack.pop()!;
620 yield n;
621 push(n);
622 }
623 }
625 /** Lay out one file: its line tree from the set's atoms, linearized. */
626 #layout(path: string, complete: boolean): FileState {
627 const graph = this.graph;
628 if (graph.packedLayout && !this.#scratchMoves()) return this.#layoutPacked(path, complete);
629 if (this.#scratchMoves())
630 return graph.withProjectionScratch((scratch) =>
631 this.#layoutResolved(
632 path,
633 complete,
634 scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, `^${path}`),
635 ),
636 );
637 return this.#layoutResolved(path, complete);
638 }
640 /** For each path, the files that lines moved into it were written in: worked out once per view. */
641 #movedFrom: Map<string, Set<number>> | undefined;
642 #movedInFrom(): Map<string, Set<number>> {
643 if (this.#movedFrom) return this.#movedFrom;
644 this.#relocations();
645 if (this.#movesTaken) return (this.#movedFrom = this.#movesTaken.#movedInFrom());
646 const graph = this.graph;
647 const out = new Map<string, Set<number>>();
648 if (this.#hasMoves) {
649 const relocs = this.#relocationsN();
650 const fileOf = (code: number): string => this.#fileOfCode(code);
651 for (const [n, { parent }] of relocs) {
652 const into = fileOf(parent);
653 let from = out.get(into);
654 if (!from) out.set(into, (from = new Set()));
655 from.add(graph.writtenInIndex(n));
656 }
657 }
658 this.#movedFrom = out;
659 return out;
660 }
662 /**
663 * Lay one file out from its packed history (abso Capacity, Graph.packedLines): the lines written in it, in the files
664 * its moved-in lines came from, and in the files runs under any of those lines were written in, read a page at a
665 * time; the same tree and order as #layoutResolved, built in memory with no read per line.
666 */
667 #layoutPacked(path: string, complete: boolean): FileState {
668 const graph = this.graph;
669 const attrs = this.#attributes(path);
670 const start = graph.startCodeOf(path);
671 if (start === undefined) return { attrs, complete, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() };
672 const relocs = this.#hasMoves ? this.#relocationsN() : undefined;
673 const files = new Set<number>([-1 - start, ...(this.#movedInFrom().get(path) ?? [])]);
674 const children = new Map<number, Child[]>();
675 const texts = new Map<number, string | null>();
676 const writers = new Map<number, number>();
677 const places = new Map<number, number>();
678 const deleters = new Map<number, number[]>();
679 // Each atom's lamport once per layout: most lines share a few atoms, and a stored graph reads it from a page.
680 const lamports = new Map<number, number>();
681 const lamportOf = (seq: number): number => {
682 let lamport = lamports.get(seq);
683 if (lamport === undefined) {
684 lamport = graph.lamportOfSeq(seq);
685 lamports.set(seq, lamport);
686 }
687 return lamport;
688 };
689 for (const file of files) {
690 const lineTexts = graph.packedTexts(file);
691 for (const [n, parent, seq, k, replaces] of graph.packedLines(file)) {
692 const text = lineTexts.next().value as string | null;
693 if (!this.#has(seq)) continue;
694 const moved = relocs?.get(n);
695 let at = parent;
696 let child: Child = { n, replaces, lamport: lamportOf(seq), seq, k };
697 if (moved) {
698 const mover = graph.atom(moved.r.atom).seq;
699 child = { n, replaces: 0, lamport: lamportOf(mover), seq: mover, k: moved.r.k };
700 at = moved.parent;
701 }
702 const list = children.get(at);
703 if (list) list.push(child);
704 else children.set(at, [child]);
705 texts.set(n, text);
706 writers.set(n, seq);
707 places.set(n, k);
708 }
709 for (const [n, deleter] of graph.packedDeletes(file)) {
710 if (!this.#has(deleter)) continue;
711 const by = deleters.get(n);
712 if (by) by.push(deleter);
713 else deleters.set(n, [deleter]);
714 }
715 // Runs written elsewhere under this file's lines follow them; the loop reads their files too.
716 for (const [parent, into] of graph.packedCrossings(file)) if (texts.has(parent)) files.add(into);
717 }
718 const order = (a: Child, b: Child) =>
719 b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k;
720 const priority = (a: number, b: number) => lamportOf(a) - lamportOf(b) || a - b;
721 const seq: number[] = [];
722 const vis: number[] = [];
723 const visText: (string | null)[] = [];
724 const visWriter: number[] = [];
725 const visK: number[] = [];
726 const seqWriter: number[] = [];
727 const seqK: number[] = [];
728 const deletedBy = new Map<number, readonly number[]>();
729 const stack: number[] = [];
730 const push = (code: number) => {
731 const list = children.get(code);
732 if (!list) return;
733 if (list.length > 1) list.sort(order);
734 for (let i = list.length - 1; i >= 0; i--) stack.push(list[i]!.n);
735 };
736 push(start);
737 while (stack.length) {
738 const n = stack.pop()!;
739 const by = deleters.get(n);
740 if (by) {
741 if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by);
742 } else {
743 vis.push(n);
744 visText.push(texts.get(n) ?? null);
745 visWriter.push(writers.get(n)!);
746 visK.push(places.get(n)!);
747 }
748 if (complete) {
749 seq.push(n);
750 seqWriter.push(writers.get(n)!);
751 seqK.push(places.get(n)!);
752 }
753 push(n);
754 }
755 return {
756 attrs,
757 complete,
758 seq: Int32Array.from(seq),
759 vis: Int32Array.from(vis),
760 deletedBy,
761 visText,
762 visWriter: Int32Array.from(visWriter),
763 visK: Int32Array.from(visK),
764 ...(complete ? { seqWriter: Int32Array.from(seqWriter), seqK: Int32Array.from(seqK) } : {}),
765 };
766 }
768 #attributes(path: string): FileAttrs {
769 const graph = this.graph;
770 // For each attribute, the highest-priority setter in the set wins.
771 const setters = new Map<string, { id: AtomId; value: string | null }>();
772 const file = graph.packedFiles ? graph.pathIndexOf(path) : undefined;
773 if (graph.packedFiles) {
774 for (const [seq, name, value] of file === undefined ? [] : graph.packedAttrs(file)) {
775 if (!this.#has(seq)) continue;
776 const id = graph.idOfSeq(seq);
777 const best = setters.get(name);
778 if (!best || graph.comparePriority(best.id, id) < 0) setters.set(name, { id, value });
779 }
780 return {
781 exists: setters.get("exists")?.value === "1",
782 exec: setters.get("exec")?.value === "1",
783 link: setters.get("link")?.value ?? null,
784 blob: setters.get("blob")?.value ?? null,
785 };
786 }
787 for (const id of graph.eachAtomIn(path)) {
788 if (!this.#has(graph.atom(id).seq)) continue;
789 for (const a of graph.atom(id).attrs ?? []) {
790 if (a.file !== path) continue;
791 const best = setters.get(a.name);
792 if (!best || graph.comparePriority(best.id, id) < 0) setters.set(a.name, { id, value: a.value });
793 }
794 }
796 return {
797 exists: setters.get("exists")?.value === "1",
798 exec: setters.get("exec")?.value === "1",
799 link: setters.get("link")?.value ?? null,
800 blob: setters.get("blob")?.value ?? null,
801 };
802 }
804 #layoutResolved(path: string, complete: boolean, nodes?: Iterable<number>): FileState {
805 const graph = this.graph;
806 const attrs = this.#attributes(path);
807 const seq: number[] = [];
808 const vis: number[] = [];
809 const deletedBy = new Map<number, readonly number[]>();
811 const start = graph.startCodeOf(path);
812 const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b;
813 for (const n of nodes ?? (start === undefined ? [] : this.#layoutNodes(start))) {
814 let deleted = false;
815 const by: number[] = [];
816 for (const deleter of graph.eachDeleterSeqOf(n)) {
817 if (!this.#has(deleter)) continue;
818 deleted = true;
819 if (!complete) break;
820 by.push(deleter);
821 }
822 if (deleted) {
823 if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by);
824 } else vis.push(n);
825 if (complete) seq.push(n);
826 }
828 return { attrs, complete, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy };
829 }
831 get #known(): string[] {
832 if (!this.#knownList) {
833 const known = new Set<string>();
834 if (this.#stable) {
835 for (const id of this.#stable) for (const file of this.graph.filesOf(id)) known.add(file);
836 } else {
837 for (let seq = 0; seq < this.#in.length; seq++)
838 if (this.#in[seq] === 1) for (const file of this.graph.filesOf(this.graph.idOfSeq(seq))) known.add(file);
839 }
840 this.#knownList = [...known].sort();
841 }
842 return this.#knownList;
843 }
845 /** Files with at least one visible line, sorted. */
846 paths(): string[] {
847 if (this.#stable) {
848 const paths: string[] = [];
849 for (const path of this.graph.knownFiles()) {
850 if (this.hasFile(path)) paths.push(path);
851 else this.#files.delete(path);
852 }
853 return paths.sort();
854 }
855 return this.#known.filter((p) => this.hasFile(p));
856 }
858 /** Every file the set has ever written a line in, including fully deleted ones. */
859 knownPaths(): string[] {
860 return [...this.#known];
861 }
863 /** The file line n sits in, in this set: fileOf by the line's number, with no lookup of its id. */
864 fileOfNumber(n: number): string {
865 return this.#fileOfN(n);
866 }
868 /** How many visible lines a file has. */
869 visibleCount(path: string): number {
870 return this.#file(path).vis.length;
871 }
873 /** Whether the file exists in this projection (has a visible line). */
874 hasFile(path: string): boolean {
875 const attrs = this.attrs(path);
876 return attrs.exists || attrs.link !== null || attrs.blob !== null || this.#file(path).vis.length > 0;
877 }
879 /** A file's attributes: kept while empty, executable, a link's target. */
880 attrs(path: string): FileAttrs {
881 return this.#files.get(path)?.attrs ?? this.#attributes(path);
882 }
884 /** The projected text of a file ("" if it has no visible lines). */
885 text(path: string): string {
886 if (this.#textCache?.path === path) return this.#textCache.text;
887 const { vis, visText } = this.#file(path);
888 const lines: string[] = new Array(vis.length);
889 for (let i = 0; i < vis.length; i++) lines[i] = visText?.[i] ?? this.graph.textOf(vis[i]!);
890 const text = joinLines(lines);
891 this.#textCache = { path, text };
892 return text;
893 }
895 /** Whether a file reads the same here and in `other` (of the same graph), compared line by line without joining either (#46). */
896 sameText(path: string, other: ReadView): boolean {
897 if (!(other instanceof View)) {
898 const a = this.lines(path),
899 b = other.lines(path);
900 return a.length === b.length && a.every((line, i) => line.text === b[i]!.text);
901 }
902 const a = this.#file(path).vis;
903 const b = other.#file(path).vis;
904 if (a.length !== b.length) return false;
905 for (let i = 0; i < a.length; i++)
906 if (a[i] !== b[i] && this.graph.textOf(a[i]!) !== this.graph.textOf(b[i]!)) return false;
907 return true;
908 }
910 *lineChunks(path: string): IterableIterator<() => Iterable<string>> {
911 for (const n of this.#file(path).vis) yield () => this.graph.textChunks(n);
912 }
914 /** Visible lines without retaining their text in the view cache. */
915 *visibleLines(path: string): IterableIterator<VisibleLine> {
916 const graph = this.graph;
917 for (const n of this.#file(path).vis)
918 yield { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) };
919 }
921 /** Atom-building line handles; text is loaded only when requested. */
922 buildLines(path: string): readonly VisibleLine[] {
923 const graph = this.graph;
924 // Texts and writers the packed layout already holds are not read again (abso Capacity).
925 const { vis, visText, visWriter, visK } = this.#file(path);
926 const lines: VisibleLine[] = new Array(vis.length);
927 for (let i = 0; i < vis.length; i++) {
928 const n = vis[i]!;
929 const packed = visText?.[i];
930 lines[i] = {
931 id: visWriter && visK ? lineId(graph.idOfSeq(visWriter[i]!), visK[i]!) : graph.lineIdOf(n),
932 textChunks: () => graph.textChunks(n),
933 get text() {
934 return packed ?? graph.textOf(n);
935 },
936 atom: graph.idOfSeq(visWriter ? visWriter[i]! : graph.writerSeqOf(n)),
937 };
938 }
939 return lines;
940 }
942 /** Visible lines with their ids. */
943 lines(path: string): readonly VisibleLine[] {
944 if (this.#linesCache?.path === path) return this.#linesCache.lines;
945 const graph = this.graph;
946 const { vis, visText, visWriter, visK } = this.#file(path);
947 const lines: VisibleLine[] = new Array(vis.length);
948 for (let i = 0; i < vis.length; i++) {
949 const n = vis[i]!;
950 lines[i] = {
951 id: visWriter && visK ? lineId(graph.idOfSeq(visWriter[i]!), visK[i]!) : graph.lineIdOf(n),
952 text: visText?.[i] ?? graph.textOf(n),
953 atom: graph.idOfSeq(visWriter ? visWriter[i]! : graph.writerSeqOf(n)),
954 };
955 }
956 this.#linesCache = { path, lines };
957 return lines;
958 }
960 /** The full linearized sequence of a file, tombstones included. */
961 sequence(path: string): readonly SeqLine[] {
962 if (this.#seqCache?.path === path) return this.#seqCache.seq;
963 const graph = this.graph;
964 const f = this.#file(path, true);
965 const out: SeqLine[] = new Array(f.seq.length);
966 // Ids and writers from the packed layout, and each text read only when asked (abso Capacity): callers walk a few
967 // lines of a file's history, and reading every line's text was a row each on a stored graph.
968 const { seqWriter, seqK } = f;
969 for (let i = 0; i < f.seq.length; i++) {
970 const n = f.seq[i]!;
971 const by = f.deletedBy.get(i);
972 const writer = seqWriter ? seqWriter[i]! : graph.writerSeqOf(n);
973 let text: string | undefined;
974 out[i] = {
975 id: seqWriter && seqK ? lineId(graph.idOfSeq(writer), seqK[i]!) : graph.lineIdOf(n),
976 get text() {
977 text ??= graph.textOf(n);
978 return text;
979 },
980 atom: graph.idOfSeq(writer),
981 deletedBy: by ? by.map((s) => graph.idOfSeq(s)) : NONE,
982 visible: by === undefined,
983 };
984 }
985 this.#seqCache = { path, seq: out };
986 return out;
987 }
989 /** Two visible neighbours without retaining the file's historical sequence. */
990 visibleNeighbours(path: string, line: LineId): LineId[] {
991 const graph = this.graph;
992 const target = graph.lineN(line);
993 const start = graph.startCodeOf(path);
994 if (target < 0 || start === undefined) return [];
995 const scan = (nodes: Iterable<number>): LineId[] => {
996 let previous: LineId | undefined;
997 let found = false;
998 for (const n of nodes) {
999 if (n === target) {
1000 found = true;
1001 continue;
1003 let deleted = false;
1004 for (const seq of graph.eachDeleterSeqOf(n))
1005 if (this.#has(seq)) {
1006 deleted = true;
1007 break;
1009 if (deleted) continue;
1010 const id = graph.lineIdOf(n);
1011 if (found) return previous === undefined ? [id] : [previous, id];
1012 previous = id;
1014 return found && previous !== undefined ? [previous] : [];
1015 };
1016 if (this.#scratchMoves())
1017 return graph.withProjectionScratch((scratch) =>
1018 scan(scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, graph.nodeOf(start))),
1019 );
1020 return scan(this.#layoutNodes(start));
1023 /** Index of a line in `sequence(path)`, or -1. */
1024 sequenceIndex(path: string, line: LineId): number {
1025 const f = this.#file(path, true);
1026 if (!f.seqIndex) {
1027 f.seqIndex = new Map();
1028 for (let i = 0; i < f.seq.length; i++) f.seqIndex.set(f.seq[i]!, i);
1030 return f.seqIndex.get(this.graph.lineN(line)) ?? -1;
1033 /** Index of a line in `lines(path)` (0-based visible line number), or -1 if not visible. */
1034 lineNumber(path: string, line: LineId): number {
1035 return this.lineNumberOf(path, this.graph.lineN(line));
1038 /** lineNumber by the line's number, with no lookup of its id. */
1039 lineNumberOf(path: string, n: number): number {
1040 const f = this.#file(path);
1041 if (!f.visIndex) {
1042 f.visIndex = new Map();
1043 for (let i = 0; i < f.vis.length; i++) f.visIndex.set(f.vis[i]!, i);
1045 return f.visIndex.get(n) ?? -1;
1048 /** The seq of the atom that wrote each visible line, in order: lines() without ids or text. */
1049 visibleWriters(path: string): number[] {
1050 const graph = this.graph;
1051 const { vis, visWriter } = this.#file(path);
1052 // The packed layout keeps them (abso Capacity): looking each up again read a page per few lines on a stored graph.
1053 if (visWriter) return Array.from(visWriter);
1054 return Array.from(vis, (n) => graph.writerSeqOf(n));
1057 /** All projected text files, path -> text, in path order. Binary files are in `blobs()`. */
1058 files(): Record<string, string> {
1059 const out: Record<string, string> = {};
1060 for (const path of this.paths()) if (this.#file(path).attrs.blob === null) out[path] = this.text(path);
1061 return out;
1064 /** Binary files, path -> the SHA-256 of their bytes, in path order. */
1065 blobs(): Record<string, string> {
1066 // From attributes alone (abso Capacity): a file with a blob exists, so no file is laid out to find them. Going
1067 // through paths() laid out every file in the set, and shared() asks for blobs on every call.
1068 const out: Record<string, string> = {};
1069 const candidates = this.#stable ? [...this.graph.knownFiles()].sort() : this.#known;
1070 for (const path of candidates) {
1071 const blob = this.attrs(path).blob;
1072 if (blob !== null) out[path] = blob;
1074 return out;
1077 /**
1078 * About how many bytes of retained state this view costs (#46). This uses
1079 * approximate ownership costs for containers and wrappers, not V8 heap
1080 * measurements. Graph-owned strings and records count only as references.
1081 * This method only inspects already-created state: it does not lay out files,
1082 * populate lazy caches, enumerate the graph, or count temporary traversal
1083 * containers and shared empty singleton payloads as retained view state.
1084 */
1085 weight(): number {
1086 let n = this.#in.byteLength;
1087 n += 2 * ARRAY_HEADER_BYTES + this.#membershipSeq.byteLength + this.#membershipValue.byteLength;
1088 if (this.#movers) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#movers.length;
1089 n += MAP_HEADER_BYTES; // #files exists from construction.
1090 if (this.#stable) n += this.#stable.retainedBytes;
1091 else if (this.#set) n += OBJECT_BYTES + SET_ENTRY_BYTES * this.#set.size;
1092 if (this.#knownList) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#knownList.length;
1093 if (this.#relocs) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * this.#relocs.size;
1094 if (this.#relocsN) n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + OBJECT_BYTES) * this.#relocsN.size;
1095 n += MAP_ENTRY_BYTES * this.#picked.size;
1096 for (const f of this.#files.values()) {
1097 n += MAP_ENTRY_BYTES;
1098 if (f !== NO_FILE) {
1099 // FileState and FileAttrs are per laid-out file; typed-array
1100 // headers are separate from their payload byte lengths below.
1101 n += OBJECT_BYTES + OBJECT_BYTES + 2 * ARRAY_HEADER_BYTES;
1102 n += f.seq.byteLength + f.vis.byteLength;
1103 if (f.visText) for (const text of f.visText) n += REFERENCE_BYTES + 2 * (text?.length ?? 0);
1104 if (f.visWriter) n += 4 * f.visWriter.length;
1105 if (f.visK) n += 4 * f.visK.length;
1106 if (f.seqWriter) n += 4 * f.seqWriter.length;
1107 if (f.seqK) n += 4 * f.seqK.length;
1108 n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + ARRAY_HEADER_BYTES) * f.deletedBy.size;
1109 for (const deleters of f.deletedBy.values()) n += REFERENCE_BYTES * deleters.length;
1110 if (f.seqIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.seqIndex.size;
1111 if (f.visIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.visIndex.size;
1114 if (this.#linesCache)
1115 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 100 * this.#linesCache.lines.length;
1116 if (this.#seqCache) {
1117 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 120 * this.#seqCache.seq.length;
1118 for (const line of this.#seqCache.seq)
1119 if (line.deletedBy !== NONE) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * line.deletedBy.length;
1121 if (this.#textCache) n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 2 * this.#textCache.text.length;
1122 return n;
1125 #file(path: string, complete = false): FileState {
1126 let state = this.#files.get(path);
1127 if (!state || (complete && !state.complete)) {
1128 const shared = this.#filesFrom === undefined ? null : this.#sharedFiles();
1129 if (shared && !shared.except.has(path)) state = shared.from.#file(path, complete);
1130 else state = this.graph.hasAtomsIn(path) ? this.#layout(path, complete) : NO_FILE;
1131 this.#files.set(path, state);
1133 return state;
1137/** The files of a closed set, path -> text. */
1138export function project(graph: Graph, set: Iterable<AtomId>): Record<string, string> {
1139 return new View(graph, set).files();
1142/** Where a node sits in a file's sequence: the index just after it (0 for a start node). */
1143export function indexAfter(view: Pick<ReadView, "sequenceIndex">, path: string, node: NodeId): number {
1144 if (isStartNode(node)) return 0;
1145 const i = view.sequenceIndex(path, node);
1146 if (i < 0) throw new EngineError("not-in-view", `line ${node} is not in ${path} in this view`);
1147 return i + 1;