Lines 10–18 at 318 (were 10–16 at 39)
1010// made when a caller asks for them, and the latest asked for is kept. 1212import type { Graph, RelocationInfo } from "./graph.ts"; 13−import { isStartNode } from "./keys.ts";
13+import { atomId, isStartNode, lineId, seqOf } from "./keys.ts"; 14+import { resolveScratchMoves, scratchLayoutNodes } from "./relocation-scratch.ts"; 15+import { isClosedSet, StableSet } from "./state-source.ts"; 1416import { joinLines } from "./text.ts"; 1517import { type AtomId, type AtomSet, EngineError, type LineId, type NodeId } from "./types.ts"; Lines 29–35 at 318 (were 27–32 at 39)
2830/** A visible line of a projected file. */ 2931export interface VisibleLine { 32+ readonly textChunks?: () => Iterable<string>; 3033 readonly id: LineId; 3134 readonly text: string; 3235 readonly atom: AtomId; Lines 46–118 at 318 (were 43–59 at 39)
4346 readonly blob: string | null; 46−const NO_ATTRS: FileAttrs = { exists: false, exec: false, link: null, blob: null };
49+/** Structural read boundary shared by historical and transaction-bound projections. */ 50+export type ReadView = Omit< 51+ Pick<View, keyof View>, 59+ | "placedDifferently" 64+ sameText(path: string, other: ReadView): boolean; 67+const NO_ATTRS: FileAttrs = { 75+ * A file layout's bytes, less its lookup indexes, worked out once per layout (abso Capacity): a layout never changes 76+ * once made, and the view cache weighs every view it holds on every lookup, which summed every line's text again. 78+const layoutSizes = new WeakMap<FileState, number>(); 79+function layoutBytes(f: FileState): number { 80+ let n = layoutSizes.get(f); 81+ if (n !== undefined) return n; 82+ // FileState and FileAttrs are per laid-out file; typed-array headers are separate from their payload byte lengths. 83+ n = OBJECT_BYTES + OBJECT_BYTES + 2 * ARRAY_HEADER_BYTES; 84+ n += f.seq.byteLength + f.vis.byteLength; 85+ if (f.visText) for (const text of f.visText) n += REFERENCE_BYTES + (text === null ? 0 : stringBytes(text)); 86+ if (f.visWriter) n += 4 * f.visWriter.length; 87+ if (f.visK) n += 4 * f.visK.length; 88+ if (f.seqWriter) n += 4 * f.seqWriter.length; 89+ if (f.seqK) n += 4 * f.seqK.length; 90+ n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + ARRAY_HEADER_BYTES) * f.deletedBy.size; 91+ for (const deleters of f.deletedBy.values()) n += REFERENCE_BYTES * deleters.length; 92+ layoutSizes.set(f, n); 4795const NONE: readonly never[] = Object.freeze([]); 4997interface FileState { 5098 readonly attrs: FileAttrs; 99+ /** Full history is retained only when a sequence caller explicitly requests it. */ 100+ readonly complete: boolean; 51101 /** The file's sequence, tombstones included: each line's n. */ 52102 readonly seq: Int32Array; 53103 /** Its visible lines' n, in order. */ 54104 readonly vis: Int32Array; 55105 /** For each deleted position in seq: the seqs of the atoms in the set that delete it, by priority. */ 56106 readonly deletedBy: ReadonlyMap<number, readonly number[]>; 107+ /** Its visible lines' text, when laid out from the file's packed history: null for a line too long to pack. */ 108+ readonly visText?: readonly (string | null)[]; 109+ /** Its visible lines' writers' seqs, when laid out from the file's packed history. */ 110+ readonly visWriter?: Int32Array; 111+ /** Its visible lines' places in their writers (a line id's k), when laid out from packed history. */ 112+ readonly visK?: Int32Array; 113+ /** The same for every line of seq, when complete and laid out from packed history. */ 114+ readonly seqWriter?: Int32Array; 115+ readonly seqK?: Int32Array; 57116 /** Positions by n, built the first time they're asked for. */ 58117 seqIndex?: Map<number, number>; 59118 visIndex?: Map<number, number>; Lines 128–262 at 318 (were 69–77 at 39)
71130const EMPTY_INTS = new Int32Array(0); 72−const NO_FILE: FileState = { attrs: NO_ATTRS, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() };
131+const NO_FILE: FileState = { 136+ deletedBy: new Map(), 139+/** A count of file uses shared by every view, so a cache can tell which layout across its views was used longest ago. */ 142+// Approximate retained-container costs for View.weight(): reference slots, 143+// object headers, and map/set entries. These are cache-budget units, not V8 144+// heap measurements. Referenced Graph strings and records are not charged. 145+const ARRAY_HEADER_BYTES = 24; 146+const OBJECT_BYTES = 32; 147+const MAP_HEADER_BYTES = 32; 148+const MAP_ENTRY_BYTES = 40; 149+const SET_ENTRY_BYTES = 32; 150+const REFERENCE_BYTES = 8; 151+const STRING_HEADER_BYTES = 16; 153+ * What V8 holds for a string of its own (abso Capacity, measured on abso's layouts): a header, then one byte a 154+ * character when every character fits in Latin-1 and two otherwise, rounded up to 8. 156+export function stringBytes(text: string): number { 157+ const chars = /[^\u0000-\u00ff]/.test(text) ? 2 * text.length : text.length; 158+ return (STRING_HEADER_BYTES + chars + 7) & ~7; 161+ * Moved lines a view resolves once and keeps (abso Capacity): a stored graph otherwise resolved every move again on 162+ * disk for each file it laid out. Game's whole history has 290; past this many, the view goes back to that. 164+export const MOVED_LINES_KEPT = 20_000; 165+class TooManyMoves extends Error {} 166+const NO_LINES: readonly number[] = Object.freeze([]); 167+/** Nodes whose nearest moved line above a graph remembers, at most: about 40 bytes each. */ 168+const CLIMB_MEMO = 200_000; 170+/** One relocation of a moved line, with its line's number and its new parent's code. */ 171+interface MoveEntry { 173+ readonly r: RelocationInfo; 174+ readonly parent: number; 178+ * A graph's moves, whatever the set (abso Capacity): each mover's moved lines, each moved line's relocations in seq 179+ * order, and for any node the nearest node at or above it, by where lines were written, that a move ever relocated, 180+ * or its file's start. Worked out once per graph and extended as it grows. A view's moves then resolve over the moved 181+ * lines alone: before, every view walked each moved line's file up to its start, a read per line. 184+ readonly #graph: Graph; 186+ /** Movers in seq order, with the numbers of the lines each moves, in its moves' order. */ 188+ readonly seq: number; 189+ readonly lines: readonly number[]; 191+ /** Every relocation of each moved line, by the line's number, in seq order. */ 192+ readonly byLine = new Map<number, MoveEntry[]>(); 193+ readonly #climbed = new Map<number, number>(); 195+ constructor(graph: Graph) { 196+ this.#graph = graph; 199+ /** The graph's accepted count when movers were last taken in: nothing to read while it's the same. */ 202+ /** Take in movers the graph gained since. */ 204+ const graph = this.#graph; 205+ if (this.#stamp === graph.accepted) return this; 206+ this.#stamp = graph.accepted; 207+ const all = graph.movers(); 208+ if (this.#seen === all.length) return this; 209+ for (; this.#seen < all.length; this.#seen++) { 210+ const id = all[this.#seen]!; 211+ const lines: number[] = []; 212+ graph.atom(id).moves!.forEach((m, k) => { 213+ const n = graph.lineN(m.line); 214+ const r: RelocationInfo = Object.freeze({ 220+ const entry: MoveEntry = { n, r, parent: graph.codeOf(m.parent)! }; 221+ const list = this.byLine.get(n); 222+ if (list) list.push(entry); 223+ else this.byLine.set(n, [entry]); 226+ this.movers.push({ seq: seqOf(id), lines }); 228+ // A new moved line can sit between a node and the one it climbed to. 229+ this.#climbed.clear(); 233+ /** The nearest node at or above this one, by where lines were written, that a move ever relocated; or its file's start. */ 234+ climb(code: number): number { 235+ const walked: number[] = []; 237+ while (c >= 0 && !this.byLine.has(c)) { 238+ const known = this.#climbed.get(c); 239+ if (known !== undefined) { 244+ c = this.#graph.parentCodeOf(c); 246+ if (this.#climbed.size + walked.length > CLIMB_MEMO) this.#climbed.clear(); 247+ for (const w of walked) this.#climbed.set(w, c); 252+const skeletons = new WeakMap<Graph, MoveSkeleton>(); 253+function skeletonOf(graph: Graph): MoveSkeleton { 254+ let skeleton = skeletons.get(graph); 255+ if (!skeleton) skeletons.set(graph, (skeleton = new MoveSkeleton(graph))); 256+ return skeleton.update(); 75260 * The projection of a closed set. Construct once, then ask for files, lines 76261 * and sequences. Throws `not-closed` if some atom's dependency is missing. 77262 * Each file is laid out the first time it is asked for, so a view of a large Lines 265–341 at 318 (were 80–120 at 39)
81266 readonly graph: Graph; 82267 /** 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). */ 83− #set: Set<AtomId> | undefined;
268+ #set: AtomSet | undefined; 269+ readonly #stable: StableSet<AtomId> | undefined; 270+ /** Fixed-size memo for immutable indexed membership, independent of history size. */ 271+ #membershipSeq = new Float64Array(256).fill(-1); 272+ #membershipValue = new Uint8Array(256); 84273 #files = new Map<string, FileState>(); 85274 /** Every file the set wrote in, sorted; worked out the first time it's asked for. */ 86275 #knownList: string[] | undefined; 87276 /** 1 for each atom (by seq) in the set. */ 89278 /** Atoms in the set that move lines. */ 90− #movers: AtomId[];
279+ #movers: AtomId[] | undefined; 91281 /** Each moved line's relocation that counts in this set; built on first use. */ 92282 #relocs: Map<LineId, RelocationInfo> | undefined; 93283 /** The same, by n, with the new parent's code. */ 94284 #relocsN: Map<number, { readonly r: RelocationInfo; readonly parent: number }> | undefined; 95− #fileOf = new Map<number, string>();
285+ /** The moved lines under each node, by its code, made from the relocations on first use. */ 286+ #movedInto: Map<number, number[]> | undefined; 287+ /** Whether this view's moves are too many to keep, so they're resolved on disk per layout; undefined until asked. */ 288+ #movesOnDisk: boolean | undefined; 96289 /** The latest records asked for: one file's lines, one file's sequence, one file's text. */ 97290 #linesCache: { path: string; lines: readonly VisibleLine[] } | undefined; 98291 #seqCache: { path: string; seq: readonly SeqLine[] } | undefined; 99292 #textCache: { path: string; text: string } | undefined; 101294 constructor(graph: Graph, set: Iterable<AtomId>) { 102− const inSet = new Uint8Array(graph.size);
103− const atoms: { readonly id: AtomId; readonly deps: readonly AtomId[] }[] = [];
104− for (const id of set) {
105− const atom = graph.atom(id);
106− inSet[atom.seq] = 1;
107− atoms.push(atom);
296+ if (set instanceof StableSet) { 299+ this.#in = new Uint8Array(0); 300+ // A set kept closed when it was written needs no proof here (abso Capacity). 301+ for (const id of isClosedSet(set) ? [] : set) { 302+ const atom = graph.atom(id); 303+ for (const dependency of atom.deps) { 304+ graph.atom(dependency); 305+ if (!set.has(dependency)) 306+ throw new EngineError("not-closed", `set is not closed: ${id} depends on ${dependency}`); 309+ for (const id of graph.movers()) { 311+ this.#hasMoves = true; 315+ this.#relocs = this.#hasMoves ? undefined : new Map(); 316+ this.#relocsN = this.#hasMoves ? undefined : new Map(); 109− for (const atom of atoms) {
319+ const inSet = new Uint8Array(graph.size); 320+ // An atom's number is in its id (abso Capacity): reading the atom for it read the whole history on a stored graph. 321+ const seqIn = (id: AtomId): number => { 322+ const seq = seqOf(id); 323+ return seq >= 0 && seq < inSet.length && graph.idOfSeq(seq) === id ? seq : graph.atom(id).seq; 325+ for (const id of set) inSet[seqIn(id)] = 1; 326+ // Validate one atom at a time. Keeping all decoded atoms here defeats 327+ // storage-backed Graph reads even though the view only needs membership. 328+ for (let seq = 0; seq < inSet.length; seq++) { 329+ if (inSet[seq] !== 1) continue; 330+ const atom = graph.atom(graph.idOfSeq(seq)); 110331 for (const d of atom.deps) { 111− if (inSet[graph.atom(d).seq] !== 1)
112− throw new EngineError("not-closed", `set is not closed: ${atom.id} depends on ${d}`);
332+ if (inSet[seqIn(d)] !== 1) throw new EngineError("not-closed", `set is not closed: ${atom.id} depends on ${d}`); 115335 this.graph = graph; 117− this.#movers = graph.movers().filter((id) => inSet[graph.atom(id).seq] === 1);
337+ this.#movers = graph.movers().filter((id) => inSet[seqOf(id)] === 1); 338+ this.#hasMoves = this.#movers.length > 0; 118339 this.#relocs = this.#movers.length === 0 ? new Map() : undefined; 119340 this.#relocsN = this.#movers.length === 0 ? new Map() : undefined; Lines 352–365 at 318 (were 131–136 at 39)
132353 /** Whether the atom with this seq is in the set. */ 133354 #has(seq: number): boolean { 356+ const slot = seq % this.#membershipSeq.length; 357+ if (this.#membershipSeq[slot] === seq) return this.#membershipValue[slot] === 1; 358+ const present = this.#stable.has(this.graph.idOfSeq(seq)); 359+ this.#membershipSeq[slot] = seq; 360+ this.#membershipValue[slot] = present ? 1 : 0; 134363 return seq < this.#in.length && this.#in[seq] === 1; Lines 371–419 at 318 (were 142–172 at 39)
143372 #relocations(): Map<LineId, RelocationInfo> { 144373 if (this.#relocs) return this.#relocs; 375+ if (this.#relocs) return this.#relocs; 145376 const graph = this.graph; 377+ const skeleton = skeletonOf(graph); 146378 const stronger = (a: RelocationInfo, b: RelocationInfo): boolean => graph.comparePriority(a.atom, b.atom) > 0; 147− const ignored = new Set<RelocationInfo>();
148− const pick = (line: LineId): RelocationInfo | undefined => {
149− let best: RelocationInfo | undefined;
150− for (const r of graph.relocationsOf(line)) {
151− if (this.#has(graph.atom(r.atom).seq) && !ignored.has(r) && (!best || stronger(r, best))) best = r;
379+ const identity = (r: RelocationInfo): string => JSON.stringify([r.atom, r.k]); 380+ const ignored = new Set<string>(); 381+ const pick = (n: number): MoveEntry | undefined => { 382+ let best: MoveEntry | undefined; 383+ for (const e of skeleton.byLine.get(n) ?? []) { 384+ if (this.#has(seqOf(e.r.atom)) && !ignored.has(identity(e.r)) && (!best || stronger(e.r, best.r))) best = e; 155− const relocs = new Map<LineId, RelocationInfo>();
156− for (const id of this.#movers) {
157− for (const m of graph.atom(id).moves!) {
158− if (!relocs.has(m.line)) relocs.set(m.line, pick(m.line)!);
388+ // By the moved line's number, in the order its movers come (seq order, then each mover's moves). 389+ const relocs = new Map<number, MoveEntry>(); 390+ for (const mover of skeleton.movers) { 391+ if (!this.#has(mover.seq)) continue; 392+ for (const n of mover.lines) { 393+ if (!relocs.has(n)) relocs.set(n, pick(n)!); 394+ if (graph.hasOrderedChildren && relocs.size > MOVED_LINES_KEPT) throw new TooManyMoves(); 161− const parentOf = (line: LineId): NodeId => relocs.get(line)?.parent ?? graph.lineParent(line)!;
162− const reaches = new Set<LineId>();
397+ // From a node, the next node that matters for loops: a line moved in this set, or a file's start. 398+ const hop = (code: number): number => { 399+ let c = skeleton.climb(code); 400+ while (c >= 0 && !relocs.has(c)) c = skeleton.climb(graph.parentCodeOf(c)); 403+ const step = (n: number): number => { 404+ const e = relocs.get(n); 405+ return hop(e ? e.parent : graph.parentCodeOf(n)); 407+ // Two moves made apart can loop lines into each other, so no start node reaches them; then the oldest 408+ // relocation on the loop is ignored, and the next newest of that line counts, until none loop. 409+ const reaches = new Set<number>(); 163410 for (const line of [...relocs.keys()]) { 165− const path: LineId[] = [];
166− const onPath = new Map<LineId, number>();
167− let cur: NodeId = line;
412+ const path: number[] = []; 413+ const onPath = new Map<number, number>(); 169− while (!isStartNode(cur) && !reaches.has(cur)) {
416+ while (cur >= 0 && !reaches.has(cur)) { 170417 const at = onPath.get(cur); 171418 if (at !== undefined) { Lines 421–597 at 318 (were 174–222 at 39)
175422 onPath.set(cur, path.length); 177− cur = parentOf(cur);
180427 for (const l of path) reaches.add(l); 183− let weakest: RelocationInfo | undefined;
430+ let weakest: MoveEntry | undefined; 184431 for (const l of path.slice(loopAt)) { 185− const r = relocs.get(l);
186− if (r && (!weakest || stronger(weakest, r))) weakest = r;
432+ const e = relocs.get(l); 433+ if (e && (!weakest || stronger(weakest.r, e.r))) weakest = e; 188− ignored.add(weakest!);
189− const next = pick(weakest!.line);
190− if (next) relocs.set(weakest!.line, next);
191− else relocs.delete(weakest!.line);
435+ ignored.add(identity(weakest!.r)); 436+ const next = pick(weakest!.n); 437+ if (next) relocs.set(weakest!.n, next); 438+ else relocs.delete(weakest!.n); 194− this.#relocs = relocs;
195− return relocs;
441+ this.#relocsN = new Map([...relocs].map(([n, e]) => [n, { r: e.r, parent: e.parent }])); 442+ this.#relocs = new Map([...relocs.values()].map((e) => [e.r.line, e.r])); 443+ return this.#relocs; 446+ /** The view whose moves this one may take, until it needs them all; then the view it took them from. */ 447+ #movesFrom: View | undefined; 448+ #movesTaken: View | undefined; 451+ * Take another view's resolved moves (abso Capacity), when both sets hold the very same atoms that move lines: the 452+ * moves then resolve the same, and every line sits where it sits there. Checked when this view first needs all its 453+ * moves, so any caller may ask, and a view that only finds a few lines' files never resolves them. 455+ shareMoves(from: View): void { 456+ if (from.graph !== this.graph || from.#hasMoves !== this.#hasMoves || !this.#hasMoves || this.#relocs) return; 457+ this.#movesFrom = from; 461+ * Files laid out as another view lays them out (abso Capacity): a draft's view over its base's, for every file the 462+ * draft doesn't touch. The caller knows what the draft is; `except` is asked once, when a file is first needed, for 463+ * the files the draft touches, or undefined when nothing can be shared (a draft that moves lines). Without it, an 464+ * agent's tree, files and blame laid out every file of the project again for each agent. 466+ shareFiles(from: View, except: () => ReadonlySet<string> | undefined): void { 467+ if (from.graph !== this.graph || from === this || this.#filesFrom !== undefined) return; 468+ this.#filesFrom = { from, except }; 470+ #filesFrom: { from: View; except: () => ReadonlySet<string> | undefined } | null | undefined; 473+ * The files this view's set has, from what the project keeps for a published version (abso Capacity): hasFile 474+ * answers from it, not a layout of the file. Collisions resolving an import tried up to seven names, and each one 475+ * laid its file out. `paths` is asked once, when first needed; undefined lays files out as before. 477+ knowPaths(paths: () => ReadonlySet<string> | undefined): void { 478+ if (this.#pathsFrom === undefined) this.#pathsFrom = paths; 480+ #pathsFrom: (() => ReadonlySet<string> | undefined) | undefined; 481+ #knownPaths: ReadonlySet<string> | null | undefined; 482+ #filesShared: { from: View; except: ReadonlySet<string> } | null | undefined; 483+ #sharedFiles(): { from: View; except: ReadonlySet<string> } | null { 484+ if (this.#filesShared === undefined) { 485+ const share = this.#filesFrom; 486+ const except = share ? share.except() : undefined; 487+ this.#filesShared = share && except ? { from: share.from, except } : null; 489+ return this.#filesShared; 492+ #takeShared(): void { 493+ const from = this.#movesFrom; 495+ this.#movesFrom = undefined; 496+ if (from.#scratchMoves()) return; 497+ for (const id of this.graph.movers()) { 498+ const seq = seqOf(id); 499+ if (this.#has(seq) !== from.#has(seq)) return; 501+ this.#relocs = from.#relocations(); 502+ this.#relocsN = from.#relocationsN(); 503+ this.#movesOnDisk = false; 504+ this.#movesTaken = from; 507+ /** Moved lines' relocations picked one at a time, before the view resolves them all (null: not moved here). */ 508+ readonly #picked = new Map<number, MoveEntry | null>(); 511+ * The relocation of moved line n that counts here, as #relocations picks it before any loop: right whenever the 512+ * walk that reached n goes on to a file's start, since only lines on a loop have their relocation set aside. 514+ #pickOne(n: number): MoveEntry | undefined { 515+ let picked = this.#picked.get(n); 516+ if (picked === undefined) { 517+ const graph = this.graph; 518+ let best: MoveEntry | undefined; 519+ for (const e of skeletonOf(graph).byLine.get(n) ?? []) { 520+ if (this.#has(seqOf(e.r.atom)) && (!best || graph.comparePriority(e.r.atom, best.r.atom) > 0)) best = e; 522+ this.#picked.set(n, (picked = best ?? null)); 524+ return picked ?? undefined; 527+ /** Whether moves are resolved on disk for each layout: only a stored graph's view with more than MOVED_LINES_KEPT. */ 528+ #scratchMoves(): boolean { 529+ if (!this.#hasMoves || !this.graph.hasOrderedChildren) return false; 530+ if (this.#movesOnDisk === undefined) { 532+ this.#relocations(); 533+ this.#movesOnDisk = false; 535+ if (!(error instanceof TooManyMoves)) throw error; 536+ this.#movesOnDisk = true; 539+ return this.#movesOnDisk; 198542 /** The relocations by n, with each new parent's code. */ 199543 #relocationsN(): Map<number, { readonly r: RelocationInfo; readonly parent: number }> { 200544 if (this.#relocsN) return this.#relocsN; 201545 const out = new Map<number, { readonly r: RelocationInfo; readonly parent: number }>(); 202546 for (const [line, r] of this.#relocations()) 203− out.set(this.graph.lineN(line), { r, parent: this.graph.codeOf(r.parent)! });
547+ out.set(this.graph.lineN(line), { 549+ parent: this.graph.codeOf(r.parent)!, 204551 this.#relocsN = out; 208555 /** The node a line hangs off in this set: where it was written, or where a move put it. */ 209556 parentOf(line: LineId): NodeId { 210− const r = this.#movers.length === 0 ? undefined : this.#relocations().get(line);
557+ if (this.graph.lineParent(line) === undefined) throw new EngineError("unknown-line", `no line ${line}`); 558+ if (this.#scratchMoves()) 559+ return this.graph.withProjectionScratch((scratch) => 560+ resolveScratchMoves(this.graph, (id) => this.#has(this.graph.atom(id).seq), scratch).parent(line), 562+ const r = this.#hasMoves ? this.#relocations().get(line) : undefined; 211563 if (r) return r.parent; 212564 const parent = this.graph.lineParent(line); 213565 if (parent === undefined) throw new EngineError("unknown-line", `no line ${line}`); 570+ * The files where a moved line sits, in this view or in `other`, when the two place it differently: a different 571+ * relocation wins, or a different parent (abso Capacity). Besides the files a draft's atoms name, these are the only 572+ * ones a draft's moves can lay out differently from its base, since a line's descendants follow it. Undefined when 573+ * either view resolves its moves in scratch, which keeps no map of them to compare. 575+ placedDifferently(other: View): Set<string> | undefined { 576+ if (this.#scratchMoves() || other.#scratchMoves()) return undefined; 577+ const here = this.#hasMoves ? this.#relocationsN() : undefined; 578+ const there = other.#hasMoves ? other.#relocationsN() : undefined; 579+ const files = new Set<string>(); 580+ const add = (n: number) => { 581+ files.add(this.#fileOfN(n)); 582+ files.add(other.#fileOfN(n)); 584+ for (const [n, x] of here ?? []) { 585+ const y = there?.get(n); 586+ if (!y || y.parent !== x.parent || y.r.atom !== x.r.atom) add(n); 588+ for (const n of there?.keys() ?? []) if (!here?.has(n)) add(n); 217592 /** Whether any atom in the set moves lines. */ 218593 hasMoves(): boolean { 219− return this.#movers.length > 0;
594+ return this.#hasMoves; 222597 /** The file a line is in, in this set: the one its chain of parents reaches. */ Lines 603–683 at 318 (were 228–270 at 39)
229604 #fileOfN(n: number): string { 230605 const graph = this.graph; 231− if (this.#movers.length === 0) return graph.writtenIn(n);
232− const relocs = this.#relocationsN();
233− const path: number[] = [];
234− let cur = n;
235− let file: string | undefined;
236− while (file === undefined) {
237− if (cur < 0) file = graph.nodeOf(cur).slice(1);
238− else {
239− file = this.#fileOf.get(cur);
240− if (file === undefined) {
241− path.push(cur);
242− cur = relocs.get(cur)?.parent ?? graph.parentCodeOf(cur);
243− }
606+ if (!this.#hasMoves) return graph.writtenIn(n); 607+ if (this.#scratchMoves()) 608+ return graph.withProjectionScratch((scratch) => { 609+ const moves = resolveScratchMoves(graph, (id) => this.#has(graph.atom(id).seq), scratch); 610+ let current = graph.nodeOf(n); 611+ while (!isStartNode(current)) current = moves.parent(current); 612+ return current.slice(1); 614+ return this.#fileOfCode(n); 617+ /** The file a node sits in, in this set: up by where lines were written, through the moves that count here. */ 618+ #fileOfCode(code: number): string { 619+ const graph = this.graph; 620+ const skeleton = skeletonOf(graph); 621+ if (!this.#relocsN) { 622+ // One moved line at a time, until a walk comes back to a line it passed: then moves loop, and are resolved whole. 623+ const passed = new Set<number>(); 626+ c = skeleton.climb(c); 627+ if (c < 0) return graph.nodeOf(c).slice(1); 628+ if (passed.has(c)) break; 630+ const e = this.#pickOne(c); 631+ c = e ? e.parent : graph.parentCodeOf(c); 246− for (const l of path) this.#fileOf.set(l, file);
247− return file;
634+ const relocs = this.#relocationsN(); 637+ c = skeleton.climb(c); 638+ if (c < 0) return graph.nodeOf(c).slice(1); 639+ const e = relocs.get(c); 640+ c = e ? e.parent : graph.parentCodeOf(c); 250644 /** The lines hanging off a node in this set, in layout order. */ 251645 #children(code: number): Child[] { 252646 const graph = this.graph; 253− const relocs = this.#movers.length === 0 ? undefined : this.#relocationsN();
254− const ns: number[] = [];
255− graph.childrenN(code, ns);
647+ const relocs = this.#hasMoves ? this.#relocationsN() : undefined; 256648 const out: Child[] = []; 257− for (const n of ns) {
649+ for (const n of graph.eachChildN(code)) { 258650 const seq = graph.writerSeqOf(n); 259651 if (!this.#has(seq) || relocs?.has(n)) continue; 260− out.push({ n, replaces: graph.replacesN(n) ? 1 : 0, lamport: graph.lamportOfSeq(seq), seq, k: graph.kOf(n) });
654+ replaces: graph.replacesN(n) ? 1 : 0, 655+ lamport: graph.lamportOfSeq(seq), 263− for (const r of graph.relocatedToCode(code)) {
264− const n = graph.lineN(r.line);
265− if (relocs.get(n)?.r !== r) continue;
661+ // The lines this set's moves put under each node, from the moves it already resolved: no row read per node 663+ if (!this.#movedInto) { 664+ this.#movedInto = new Map(); 665+ for (const [n, { parent }] of relocs) { 666+ const into = this.#movedInto.get(parent); 667+ if (into) into.push(n); 668+ else this.#movedInto.set(parent, [n]); 671+ for (const n of this.#movedInto.get(code) ?? NO_LINES) { 672+ const r = relocs.get(n)!.r; 266673 const seq = graph.atom(r.atom).seq; 267− out.push({ n, replaces: 0, lamport: graph.lamportOfSeq(seq), seq, k: r.k });
677+ lamport: graph.lamportOfSeq(seq), 270683 // A line's replacements (runs of atoms that deleted it) first, then the Lines 692–947 at 318 (were 279–290 at 39)
695+ /** Parent/successor traversal keeps no history-sized ancestry or sibling frontier. */ 696+ *#layoutNodes(start: number): IterableIterator<number> { 697+ const graph = this.graph; 698+ if (graph.hasOrderedChildren && !this.#hasMoves) { 699+ const first = (parent: number, after?: number): number | undefined => { 700+ for (const n of graph.orderedChildrenN(parent, after)) if (this.#has(graph.writerSeqOf(n))) return n; 703+ let n = first(start); 704+ while (n !== undefined) { 706+ const child = first(n); 707+ if (child !== undefined) { 713+ const parent = graph.parentCodeOf(previous); 714+ const sibling = first(parent, previous); 715+ if (sibling !== undefined) { 719+ if (parent === start) { 723+ if (parent < 0 || parent >= previous) throw new Error("invalid persistent layout ancestry"); 729+ const stack: number[] = []; 730+ const push = (parent: number): void => { 731+ const children = this.#children(parent); 732+ for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]!.n); 735+ while (stack.length) { 736+ const n = stack.pop()!; 282742 /** Lay out one file: its line tree from the set's atoms, linearized. */ 283− #layout(path: string): FileState {
743+ #layout(path: string, complete: boolean): FileState { 284744 const graph = this.graph; 745+ if (graph.packedLayout && !this.#scratchMoves()) return this.#layoutPacked(path, complete); 746+ if (this.#scratchMoves()) 747+ return graph.withProjectionScratch((scratch) => 748+ this.#layoutResolved( 751+ scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, `^${path}`), 754+ return this.#layoutResolved(path, complete); 757+ /** For each path, the files that lines moved into it were written in: worked out once per view. */ 758+ #movedFrom: Map<string, Set<number>> | undefined; 759+ #movedInFrom(): Map<string, Set<number>> { 760+ if (this.#movedFrom) return this.#movedFrom; 761+ this.#relocations(); 762+ if (this.#movesTaken) return (this.#movedFrom = this.#movesTaken.#movedInFrom()); 763+ const graph = this.graph; 764+ const out = new Map<string, Set<number>>(); 765+ if (this.#hasMoves) { 766+ const relocs = this.#relocationsN(); 767+ const fileOf = (code: number): string => this.#fileOfCode(code); 768+ for (const [n, { parent }] of relocs) { 769+ const into = fileOf(parent); 770+ let from = out.get(into); 771+ if (!from) out.set(into, (from = new Set())); 772+ from.add(graph.writtenInIndex(n)); 775+ this.#movedFrom = out; 780+ * Lay one file out from its packed history (abso Capacity, Graph.packedLines): the lines written in it, in the files 781+ * its moved-in lines came from, and in the files runs under any of those lines were written in, read a page at a 782+ * time; the same tree and order as #layoutResolved, built in memory with no read per line. 784+ #layoutPacked(path: string, complete: boolean): FileState { 785+ const graph = this.graph; 786+ const attrs = this.#attributes(path); 787+ const start = graph.startCodeOf(path); 788+ if (start === undefined) 794+ deletedBy: new Map(), 796+ const relocs = this.#hasMoves ? this.#relocationsN() : undefined; 797+ const files = new Set<number>([-1 - start, ...(this.#movedInFrom().get(path) ?? [])]); 798+ const children = new Map<number, Child[]>(); 799+ // Where each line's text is: its file and its place in that file's packed history. Texts are read after the walk, 800+ // only for the lines it shows (abso Capacity): every text a file and its moved-in sources ever had was read for 801+ // every layout, and abso's worker files, split out of index.ts, read all of index.ts's history each. 802+ const textFile = new Map<number, number>(); 803+ const textPlace = new Map<number, number>(); 804+ const writers = new Map<number, number>(); 805+ const places = new Map<number, number>(); 806+ const deleters = new Map<number, number[]>(); 807+ // Each atom's lamport once per layout: most lines share a few atoms, and a stored graph reads it from a page. 808+ const lamports = new Map<number, number>(); 809+ const lamportOf = (seq: number): number => { 810+ let lamport = lamports.get(seq); 811+ if (lamport === undefined) { 812+ lamport = graph.lamportOfSeq(seq); 813+ lamports.set(seq, lamport); 817+ for (const file of files) { 818+ // The file's history decoded once and kept by the graph (abso Capacity): each view of it read every page again. 819+ const history = graph.packedHistory(file); 820+ const lines = history.lines; 821+ for (let i = 0, place = 0; i < lines.length; i += 5, place++) { 822+ const n = lines[i]!; 823+ const parent = lines[i + 1]!; 824+ const seq = lines[i + 2]!; 825+ const k = lines[i + 3]!; 826+ const replaces = lines[i + 4]!; 827+ if (!this.#has(seq)) continue; 828+ const moved = relocs?.get(n); 830+ let child: Child = { n, replaces, lamport: lamportOf(seq), seq, k }; 832+ const mover = graph.atom(moved.r.atom).seq; 836+ lamport: lamportOf(mover), 842+ const list = children.get(at); 843+ if (list) list.push(child); 844+ else children.set(at, [child]); 845+ textFile.set(n, file); 846+ textPlace.set(n, place); 847+ writers.set(n, seq); 850+ const dels = history.deletes; 851+ for (let at = 0; at < dels.length; at += 2) { 852+ const n = dels[at]!; 853+ const deleter = dels[at + 1]!; 854+ if (!this.#has(deleter)) continue; 855+ const by = deleters.get(n); 856+ if (by) by.push(deleter); 857+ else deleters.set(n, [deleter]); 859+ // Runs written elsewhere under this file's lines follow them; the loop reads their files too. 860+ const crossings = history.crossings; 861+ for (let at = 0; at < crossings.length; at += 2) if (writers.has(crossings[at]!)) files.add(crossings[at + 1]!); 863+ const order = (a: Child, b: Child) => 864+ b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k; 865+ const priority = (a: number, b: number) => lamportOf(a) - lamportOf(b) || a - b; 866+ const seq: number[] = []; 867+ const vis: number[] = []; 868+ const visText: (string | null)[] = []; 869+ const visWriter: number[] = []; 870+ const visK: number[] = []; 871+ const seqWriter: number[] = []; 872+ const seqK: number[] = []; 873+ const deletedBy = new Map<number, readonly number[]>(); 874+ // The text pages read for this layout, by file and page: each at most once. 875+ const pages = new Map<number, Map<number, readonly (string | null)[]>>(); 876+ const textOf = (n: number): string | null => { 877+ const file = textFile.get(n)!; 878+ const place = textPlace.get(n)!; 879+ const page = Math.floor(place / 256); 880+ let byPage = pages.get(file); 881+ if (!byPage) pages.set(file, (byPage = new Map())); 882+ let texts = byPage.get(page); 883+ if (!texts) byPage.set(page, (texts = graph.packedTextPage(file, page))); 884+ return texts[place % 256] ?? null; 886+ const stack: number[] = []; 887+ const push = (code: number) => { 888+ const list = children.get(code); 890+ if (list.length > 1) list.sort(order); 891+ for (let i = list.length - 1; i >= 0; i--) stack.push(list[i]!.n); 894+ while (stack.length) { 895+ const n = stack.pop()!; 896+ const by = deleters.get(n); 898+ if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by); 901+ visText.push(textOf(n)); 902+ visWriter.push(writers.get(n)!); 903+ visK.push(places.get(n)!); 907+ seqWriter.push(writers.get(n)!); 908+ seqK.push(places.get(n)!); 915+ seq: Int32Array.from(seq), 916+ vis: Int32Array.from(vis), 919+ visWriter: Int32Array.from(visWriter), 920+ visK: Int32Array.from(visK), 921+ ...(complete ? { seqWriter: Int32Array.from(seqWriter), seqK: Int32Array.from(seqK) } : {}), 925+ #attributes(path: string): FileAttrs { 926+ const graph = this.graph; 285927 // For each attribute, the highest-priority setter in the set wins. 286928 const setters = new Map<string, { id: AtomId; value: string | null }>(); 287− for (const id of graph.atomsIn(path)) {
929+ const file = graph.packedFiles ? graph.pathIndexOf(path) : undefined; 930+ if (graph.packedFiles) { 931+ for (const [seq, name, value] of file === undefined ? [] : graph.packedAttrs(file)) { 932+ if (!this.#has(seq)) continue; 933+ const id = graph.idOfSeq(seq); 934+ const best = setters.get(name); 935+ if (!best || graph.comparePriority(best.id, id) < 0) setters.set(name, { id, value }); 938+ exists: setters.get("exists")?.value === "1", 939+ exec: setters.get("exec")?.value === "1", 940+ link: setters.get("link")?.value ?? null, 941+ blob: setters.get("blob")?.value ?? null, 944+ for (const id of graph.eachAtomIn(path)) { 288945 if (!this.#has(graph.atom(id).seq)) continue; 289946 for (const a of graph.atom(id).attrs ?? []) { 290947 if (a.file !== path) continue; Lines 950–1005 at 318 (were 293–333 at 39)
954+ exists: setters.get("exists")?.value === "1", 955+ exec: setters.get("exec")?.value === "1", 956+ link: setters.get("link")?.value ?? null, 957+ blob: setters.get("blob")?.value ?? null, 961+ #layoutResolved(path: string, complete: boolean, nodes?: Iterable<number>): FileState { 962+ const graph = this.graph; 963+ const attrs = this.#attributes(path); 296964 const seq: number[] = []; 297965 const vis: number[] = []; 298966 const deletedBy = new Map<number, readonly number[]>(); 299− // Depth-first, iteratively (a file of n lines can be a chain n deep).
300− const stack: number[] = [];
301− const pushChildren = (code: number): void => {
302− const list = this.#children(code);
303− for (let i = list.length - 1; i >= 0; i--) stack.push(list[i]!.n);
304− };
305968 const start = graph.startCodeOf(path); 306− if (start !== undefined) pushChildren(start);
307969 const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b; 308− while (stack.length > 0) {
309− const n = stack.pop()!;
310− const deleters = graph.deleterSeqsOf(n);
311− const by = deleters.length === 0 ? NONE : deleters.filter((d) => this.#has(d));
312− if (by.length > 0) deletedBy.set(seq.length, by.length > 1 ? [...by].sort(priority) : by);
313− else vis.push(n);
314− seq.push(n);
315− pushChildren(n);
970+ for (const n of nodes ?? (start === undefined ? [] : this.#layoutNodes(start))) { 971+ let deleted = false; 972+ const by: number[] = []; 973+ for (const deleter of graph.eachDeleterSeqOf(n)) { 974+ if (!this.#has(deleter)) continue; 976+ if (!complete) break; 980+ if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by); 982+ if (complete) seq.push(n); 317− const attrs: FileAttrs = {
318− exists: setters.get("exists")?.value === "1",
319− exec: setters.get("exec")?.value === "1",
320− link: setters.get("link")?.value ?? null,
321− blob: setters.get("blob")?.value ?? null,
988+ seq: Int32Array.from(seq), 989+ vis: Int32Array.from(vis), 323− return { attrs, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy };
326994 get #known(): string[] { 327995 if (!this.#knownList) { 328996 const known = new Set<string>(); 329− for (let seq = 0; seq < this.#in.length; seq++)
330− if (this.#in[seq] === 1) for (const file of this.graph.filesOf(this.graph.idOfSeq(seq))) known.add(file);
998+ for (const id of this.#stable) for (const file of this.graph.filesOf(id)) known.add(file); 1000+ for (let seq = 0; seq < this.#in.length; seq++) 1001+ if (this.#in[seq] === 1) for (const file of this.graph.filesOf(this.graph.idOfSeq(seq))) known.add(file); 3311003 this.#knownList = [...known].sort(); 3331005 return this.#knownList; Lines 1007–1035 at 318 (were 335–340 at 39)
3361008 /** Files with at least one visible line, sorted. */ 3371009 paths(): string[] { 1010+ // Without walking every file the graph has ever had (abso Capacity): a draft's view over its base's has the base's 1011+ // files, with the ones its draft touches checked here; a published version's are kept (knowPaths). 1012+ const shared = this.#filesFrom === undefined ? null : this.#sharedFiles(); 1014+ const out = shared.from.paths().filter((p) => !shared.except.has(p)); 1015+ for (const p of shared.except) if (this.hasFile(p)) out.push(p); 1018+ if (this.#pathsFrom !== undefined) { 1019+ if (this.#knownPaths === undefined) this.#knownPaths = this.#pathsFrom() ?? null; 1020+ if (this.#knownPaths) return [...this.#knownPaths].sort(); 1022+ if (this.#stable) { 1023+ const paths: string[] = []; 1024+ for (const path of this.graph.knownFiles()) { 1025+ if (this.hasFile(path)) paths.push(path); 1027+ this.#files.delete(path); 1028+ this.#used.delete(path); 1031+ return paths.sort(); 3381033 return this.#known.filter((p) => this.hasFile(p)); Lines 1038–1091 at 318 (were 343–372 at 39)
3431038 return [...this.#known]; 1041+ /** The file line n sits in, in this set: fileOf by the line's number, with no lookup of its id. */ 1042+ fileOfNumber(n: number): string { 1043+ return this.#fileOfN(n); 1046+ /** How many visible lines a file has. */ 1047+ visibleCount(path: string): number { 1048+ return this.#file(path).vis.length; 3461051 /** Whether the file exists in this projection (has a visible line). */ 3471052 hasFile(path: string): boolean { 348− const f = this.#file(path);
349− return f.vis.length > 0 || f.attrs.exists || f.attrs.link !== null || f.attrs.blob !== null;
1053+ if (!this.#files.has(path)) { 1054+ // A file the draft doesn't touch exists as it does in the base; a published version's files are kept. 1055+ const shared = this.#filesFrom === undefined ? null : this.#sharedFiles(); 1056+ if (shared && !shared.except.has(path)) return shared.from.hasFile(path); 1057+ if (this.#pathsFrom !== undefined) { 1058+ if (this.#knownPaths === undefined) this.#knownPaths = this.#pathsFrom() ?? null; 1059+ if (this.#knownPaths) return this.#knownPaths.has(path); 1062+ const attrs = this.attrs(path); 1063+ return attrs.exists || attrs.link !== null || attrs.blob !== null || this.#file(path).vis.length > 0; 3521066 /** A file's attributes: kept while empty, executable, a link's target. */ 3531067 attrs(path: string): FileAttrs { 354− return this.#file(path).attrs;
1068+ return this.#files.get(path)?.attrs ?? this.#attributes(path); 3571071 /** The projected text of a file ("" if it has no visible lines). */ 3581072 text(path: string): string { 3591073 if (this.#textCache?.path === path) return this.#textCache.text; 360− const vis = this.#file(path).vis;
1074+ const { vis, visText } = this.#file(path); 3611075 const lines: string[] = new Array(vis.length); 362− for (let i = 0; i < vis.length; i++) lines[i] = this.graph.textOf(vis[i]!);
1076+ for (let i = 0; i < vis.length; i++) lines[i] = visText?.[i] ?? this.graph.textOf(vis[i]!); 3631077 const text = joinLines(lines); 3641078 this.#textCache = { path, text }; 3681082 /** Whether a file reads the same here and in `other` (of the same graph), compared line by line without joining either (#46). */ 369− sameText(path: string, other: View): boolean {
1083+ sameText(path: string, other: ReadView): boolean { 1084+ if (!(other instanceof View)) { 1085+ const a = this.lines(path), 1086+ b = other.lines(path); 1087+ return a.length === b.length && a.every((line, i) => line.text === b[i]!.text); 3701089 const a = this.#file(path).vis; 3711090 const b = other.#file(path).vis; 3721091 if (a.length !== b.length) return false; Lines 1094–1157 at 318 (were 375–389 at 39)
1097+ *lineChunks(path: string): IterableIterator<() => Iterable<string>> { 1098+ // The texts the packed layout already holds, read a page at a time (abso Capacity, 714): a record's diff read each 1099+ // line's own row, 11,873 statements for abso's index.ts. Only a line too long to pack is read in chunks. 1100+ const { vis, visText } = this.#file(path); 1101+ for (let i = 0; i < vis.length; i++) { 1102+ const packed = visText?.[i]; 1103+ if (packed != null) yield () => [packed]; 1104+ else yield () => this.graph.textChunks(vis[i]!); 1108+ /** Visible lines without retaining their text in the view cache. */ 1109+ *visibleLines(path: string): IterableIterator<VisibleLine> { 1110+ const graph = this.graph; 1111+ for (const n of this.#file(path).vis) 1113+ id: graph.lineIdOf(n), 1114+ text: graph.textOf(n), 1115+ atom: atomId(graph.writerSeqOf(n)), 1119+ /** Atom-building line handles; text is loaded only when requested. */ 1120+ buildLines(path: string): readonly VisibleLine[] { 1121+ const graph = this.graph; 1122+ // Texts and writers the packed layout already holds are not read again (abso Capacity). 1123+ const { vis, visText, visWriter, visK } = this.#file(path); 1124+ const lines: VisibleLine[] = new Array(vis.length); 1125+ for (let i = 0; i < vis.length; i++) { 1127+ const packed = visText?.[i]; 1129+ id: visWriter && visK ? lineId(atomId(visWriter[i]!), visK[i]!) : graph.lineIdOf(n), 1130+ textChunks: () => graph.textChunks(n), 1132+ return packed ?? graph.textOf(n); 1134+ atom: atomId(visWriter ? visWriter[i]! : graph.writerSeqOf(n)), 3781140 /** Visible lines with their ids. */ 3791141 lines(path: string): readonly VisibleLine[] { 3801142 if (this.#linesCache?.path === path) return this.#linesCache.lines; 3811143 const graph = this.graph; 382− const vis = this.#file(path).vis;
1144+ const { vis, visText, visWriter, visK } = this.#file(path); 3831145 const lines: VisibleLine[] = new Array(vis.length); 1146+ // Writer seqs come from the graph's own layout, so they're named with atomId, not checked by idOfSeq (abso 738): 1147+ // on a stored graph its check read the atom count once a line, about 0.9 s of a warm draft-state on abso. 3841148 for (let i = 0; i < vis.length; i++) { 3851149 const n = vis[i]!; 386− lines[i] = { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) };
1151+ id: visWriter && visK ? lineId(atomId(visWriter[i]!), visK[i]!) : graph.lineIdOf(n), 1152+ text: visText?.[i] ?? graph.textOf(n), 1153+ atom: atomId(visWriter ? visWriter[i]! : graph.writerSeqOf(n)), 3881156 this.#linesCache = { path, lines }; Lines 1161–1184 at 318 (were 393–408 at 39)
3931161 sequence(path: string): readonly SeqLine[] { 3941162 if (this.#seqCache?.path === path) return this.#seqCache.seq; 3951163 const graph = this.graph; 396− const f = this.#file(path);
1164+ const f = this.#file(path, true); 3971165 const out: SeqLine[] = new Array(f.seq.length); 1166+ // Ids and writers from the packed layout, and each text read only when asked (abso Capacity): callers walk a few 1167+ // lines of a file's history, and reading every line's text was a row each on a stored graph. 1168+ const { seqWriter, seqK } = f; 3981169 for (let i = 0; i < f.seq.length; i++) { 3991170 const n = f.seq[i]!; 4001171 const by = f.deletedBy.get(i); 1172+ const writer = seqWriter ? seqWriter[i]! : graph.writerSeqOf(n); 1173+ let text: string | undefined; 402− id: graph.lineIdOf(n),
403− text: graph.textOf(n),
404− atom: graph.idOfSeq(graph.writerSeqOf(n)),
405− deletedBy: by ? by.map((s) => graph.idOfSeq(s)) : NONE,
1175+ id: seqWriter && seqK ? lineId(atomId(writer), seqK[i]!) : graph.lineIdOf(n), 1177+ text ??= graph.textOf(n); 1180+ atom: atomId(writer), 1181+ deletedBy: by ? by.map((s) => atomId(s)) : NONE, 4061182 visible: by === undefined, Lines 1186–1228 at 318 (were 410–418 at 39)
1189+ /** Two visible neighbours without retaining the file's historical sequence. */ 1190+ visibleNeighbours(path: string, line: LineId): LineId[] { 1191+ const graph = this.graph; 1192+ const target = graph.lineN(line); 1193+ const start = graph.startCodeOf(path); 1194+ if (target < 0 || start === undefined) return []; 1195+ const scan = (nodes: Iterable<number>): LineId[] => { 1196+ let previous: LineId | undefined; 1198+ for (const n of nodes) { 1199+ if (n === target) { 1203+ let deleted = false; 1204+ for (const seq of graph.eachDeleterSeqOf(n)) 1205+ if (this.#has(seq)) { 1209+ if (deleted) continue; 1210+ const id = graph.lineIdOf(n); 1211+ if (found) return previous === undefined ? [id] : [previous, id]; 1214+ return found && previous !== undefined ? [previous] : []; 1216+ if (this.#scratchMoves()) 1217+ return graph.withProjectionScratch((scratch) => 1218+ scan(scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, graph.nodeOf(start))), 1220+ return scan(this.#layoutNodes(start)); 4131223 /** Index of a line in `sequence(path)`, or -1. */ 4141224 sequenceIndex(path: string, line: LineId): number { 415− const f = this.#file(path);
1225+ const f = this.#file(path, true); 4161226 if (!f.seqIndex) { 4171227 f.seqIndex = new Map(); 4181228 for (let i = 0; i < f.seq.length; i++) f.seqIndex.set(f.seq[i]!, i); Lines 1232–1259 at 318 (were 422–435 at 39)
4231233 /** Index of a line in `lines(path)` (0-based visible line number), or -1 if not visible. */ 4241234 lineNumber(path: string, line: LineId): number { 1235+ return this.lineNumberOf(path, this.graph.lineN(line)); 1238+ /** lineNumber by the line's number, with no lookup of its id. */ 1239+ lineNumberOf(path: string, n: number): number { 4251240 const f = this.#file(path); 4261241 if (!f.visIndex) { 4271242 f.visIndex = new Map(); 4281243 for (let i = 0; i < f.vis.length; i++) f.visIndex.set(f.vis[i]!, i); 430− return f.visIndex.get(this.graph.lineN(line)) ?? -1;
1245+ return f.visIndex.get(n) ?? -1; 1248+ /** The seq of the atom that wrote each visible line, in order: lines() without ids or text. */ 1249+ visibleWriters(path: string): number[] { 1250+ const graph = this.graph; 1251+ const { vis, visWriter } = this.#file(path); 1252+ // The packed layout keeps them (abso Capacity): looking each up again read a page per few lines on a stored graph. 1253+ if (visWriter) return Array.from(visWriter); 1254+ return Array.from(vis, (n) => graph.writerSeqOf(n)); 4331257 /** All projected text files, path -> text, in path order. Binary files are in `blobs()`. */ 4341258 files(): Record<string, string> { 4351259 const out: Record<string, string> = {}; Lines 1263–1362 at 318 (were 439–479 at 39)
4401264 /** Binary files, path -> the SHA-256 of their bytes, in path order. */ 4411265 blobs(): Record<string, string> { 1266+ // From attributes alone (abso Capacity): a file with a blob exists, so no file is laid out to find them. Going 1267+ // through paths() laid out every file in the set, and shared() asks for blobs on every call. 4421268 const out: Record<string, string> = {}; 443− for (const path of this.paths()) {
444− const blob = this.#file(path).attrs.blob;
1269+ const candidates = this.#stable ? [...this.graph.knownFiles()].sort() : this.#known; 1270+ for (const path of candidates) { 1271+ const blob = this.attrs(path).blob; 4451272 if (blob !== null) out[path] = blob; 451− * About how many bytes keeping this view costs (#46): its laid-out files
452− * (4 bytes a line, and more for a deleted line and for positions once asked
453− * for), and the records it keeps for the file it was last asked about.
1278+ * About how many bytes of retained state this view costs (#46). This uses 1279+ * approximate ownership costs for containers and wrappers, not V8 heap 1280+ * measurements. Graph-owned strings and records count only as references. 1281+ * This method only inspects already-created state: it does not lay out files, 1282+ * populate lazy caches, enumerate the graph, or count temporary traversal 1283+ * containers and shared empty singleton payloads as retained view state. 455− weight(): number {
456− let n = 0;
457− for (const f of this.#files.values())
458− n +=
459− 4 * (f.seq.length + f.vis.length) +
460− 40 * f.deletedBy.size +
461− 24 * ((f.seqIndex?.size ?? 0) + (f.visIndex?.size ?? 0));
462− n +=
463− 100 * (this.#linesCache?.lines.length ?? 0) +
464− 120 * (this.#seqCache?.seq.length ?? 0) +
465− 2 * (this.#textCache?.text.length ?? 0);
1285+ weight(seen?: Set<object>): number { 1286+ let n = this.#in.byteLength; 1287+ n += 2 * ARRAY_HEADER_BYTES + this.#membershipSeq.byteLength + this.#membershipValue.byteLength; 1288+ if (this.#movers) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#movers.length; 1289+ n += MAP_HEADER_BYTES; // #files exists from construction. 1290+ if (this.#stable) n += this.#stable.retainedBytes; 1291+ else if (this.#set) n += OBJECT_BYTES + SET_ENTRY_BYTES * this.#set.size; 1292+ if (this.#knownList) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#knownList.length; 1293+ if (this.#relocs) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * this.#relocs.size; 1294+ if (this.#relocsN) n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + OBJECT_BYTES) * this.#relocsN.size; 1295+ n += MAP_ENTRY_BYTES * this.#picked.size; 1296+ n += MAP_ENTRY_BYTES * this.#used.size; 1297+ for (const f of this.#files.values()) { 1298+ n += MAP_ENTRY_BYTES; 1299+ if (f !== NO_FILE) { 1300+ // A layout another view counted already (`seen`, across a cache's views) isn't counted again. 1301+ if (!seen?.has(f)) n += layoutBytes(f); 1303+ if (f.seqIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.seqIndex.size; 1304+ if (f.visIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.visIndex.size; 1307+ if (this.#linesCache) 1308+ n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 100 * this.#linesCache.lines.length; 1309+ if (this.#seqCache) { 1310+ n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 120 * this.#seqCache.seq.length; 1311+ for (const line of this.#seqCache.seq) 1312+ if (line.deletedBy !== NONE) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * line.deletedBy.length; 1314+ if (this.#textCache) n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 2 * this.#textCache.text.length; 469− #file(path: string): FileState {
1318+ #file(path: string, complete = false): FileState { 4701319 let state = this.#files.get(path); 471− if (!state) {
472− state = this.graph.atomsIn(path).length === 0 ? NO_FILE : this.#layout(path);
1320+ if (!state || (complete && !state.complete)) { 1321+ const shared = this.#filesFrom === undefined ? null : this.#sharedFiles(); 1322+ if (shared && !shared.except.has(path)) state = shared.from.#file(path, complete); 1323+ else state = this.graph.hasAtomsIn(path) ? this.#layout(path, complete) : NO_FILE; 4731324 this.#files.set(path, state); 1326+ if (state !== NO_FILE) this.#used.set(path, ++fileUses); 1330+ /** When each laid-out file was last used (fileUses). */ 1331+ readonly #used = new Map<string, number>(); 1334+ * Each laid-out file: its layout, when it was last used (a count shared by every view) and what it holds, for a 1335+ * cache that trims the least recently used layouts across its views before whole views (views.ts, abso Capacity). 1337+ *laidOut(): IterableIterator<{ 1343+ for (const [path, f] of this.#files) { 1344+ if (f === NO_FILE) continue; 1345+ let bytes = 2 * MAP_ENTRY_BYTES + layoutBytes(f); 1346+ if (f.seqIndex) bytes += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.seqIndex.size; 1347+ if (f.visIndex) bytes += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.visIndex.size; 1348+ yield { path, layout: f, used: this.#used.get(path) ?? 0, bytes }; 1352+ /** Let go of a file's layout: the next ask lays it out again, the same. */ 1353+ forget(path: string): void { 1354+ this.#files.delete(path); 1355+ this.#used.delete(path); 1356+ if (this.#linesCache?.path === path) this.#linesCache = undefined; 1357+ if (this.#seqCache?.path === path) this.#seqCache = undefined; 1358+ if (this.#textCache?.path === path) this.#textCache = undefined; 4791362/** The files of a closed set, path -> text. */ Lines 1365–1371 at 318 (were 482–488 at 39)
4841367/** Where a node sits in a file's sequence: the index just after it (0 for a start node). */ 485−export function indexAfter(view: View, path: string, node: NodeId): number {
1368+export function indexAfter(view: Pick<ReadView, "sequenceIndex">, path: string, node: NodeId): number { 4861369 if (isStartNode(node)) return 0; 4871370 const i = view.sequenceIndex(path, node); 4881371 if (i < 0) throw new EngineError("not-in-view", `line ${node} is not in ${path} in this view`);