- 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=104&format=json
523 linesFirst import 91% · codex-capacity-policy 9%Last change codex-capacity-policy in version 103, 2 versions changed it
You're reading version 104. The newest is 318, and 43 versions since then changed this file.
1// Projection: the files a closed set of atoms produces. A pure function of the
2// set. Each file is a tree of lines hanging off its start node; linearizing it
3// depth-first, children in descending priority, gives the file's sequence. A
4// line hangs off the node it was written after, unless a move in the set gave
5// it another parent (#28): then the newest such move decides.
6//
7// A laid-out file is kept as arrays of line numbers (the graph's n), not as a
8// record per line (#46): a record, its id and two index entries cost about
9// 370 bytes a line, and the view cache holds up to 200,000 lines. Records are
10// made when a caller asks for them, and the latest asked for is kept.
12import type { Graph, RelocationInfo } from "./graph.ts";
13import { isStartNode } from "./keys.ts";
14import { joinLines } from "./text.ts";
15import { type AtomId, type AtomSet, EngineError, type LineId, type NodeId } from "./types.ts";
17/** A line in a file's full sequence, tombstones included. */
18export interface SeqLine {
19 readonly id: LineId;
20 readonly text: string;
21 /** The atom that wrote it. */
22 readonly atom: AtomId;
23 /** Atoms in the set that delete it, by seq. Empty when it is visible. */
24 readonly deletedBy: readonly AtomId[];
25 readonly visible: boolean;
26}
28/** A visible line of a projected file. */
29export interface VisibleLine {
30 readonly id: LineId;
31 readonly text: string;
32 readonly atom: AtomId;
33}
35/** A file's attributes in a view. */
36export interface FileAttrs {
37 /** Kept with no lines (an empty file). */
38 readonly exists: boolean;
39 readonly exec: boolean;
40 /** The target, when the file is a symbolic link. */
41 readonly link: string | null;
42 /** The SHA-256 of its bytes, when the file is binary. */
43 readonly blob: string | null;
44}
46const NO_ATTRS: FileAttrs = { exists: false, exec: false, link: null, blob: null };
47const NONE: readonly never[] = Object.freeze([]);
49interface FileState {
50 readonly attrs: FileAttrs;
51 /** The file's sequence, tombstones included: each line's n. */
52 readonly seq: Int32Array;
53 /** Its visible lines' n, in order. */
54 readonly vis: Int32Array;
55 /** For each deleted position in seq: the seqs of the atoms in the set that delete it, by priority. */
56 readonly deletedBy: ReadonlyMap<number, readonly number[]>;
57 /** Positions by n, built the first time they're asked for. */
58 seqIndex?: Map<number, number>;
59 visIndex?: Map<number, number>;
60}
62interface Child {
63 readonly n: number;
64 /** 1 when the child's atom deleted the parent (the child replaces it), else 0. A moved line is 0. */
65 readonly replaces: number;
66 readonly lamport: number;
67 readonly seq: number;
68 readonly k: number;
69}
71const EMPTY_INTS = new Int32Array(0);
72const NO_FILE: FileState = { attrs: NO_ATTRS, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() };
74// Approximate retained-container costs for View.weight(): reference slots,
75// object headers, and map/set entries. These are cache-budget units, not V8
76// heap measurements. Referenced Graph strings and records are not charged.
77const ARRAY_HEADER_BYTES = 24;
78const OBJECT_BYTES = 32;
79const MAP_HEADER_BYTES = 32;
80const MAP_ENTRY_BYTES = 40;
81const SET_ENTRY_BYTES = 32;
82const REFERENCE_BYTES = 8;
84/**
85 * The projection of a closed set. Construct once, then ask for files, lines
86 * and sequences. Throws `not-closed` if some atom's dependency is missing.
87 * Each file is laid out the first time it is asked for, so a view of a large
88 * set costs little until files are read.
89 */
90export class View {
91 readonly graph: Graph;
92 /** 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). */
93 #set: Set<AtomId> | undefined;
94 #files = new Map<string, FileState>();
95 /** Every file the set wrote in, sorted; worked out the first time it's asked for. */
96 #knownList: string[] | undefined;
97 /** 1 for each atom (by seq) in the set. */
98 #in: Uint8Array;
99 /** Atoms in the set that move lines. */
100 #movers: AtomId[];
101 /** Each moved line's relocation that counts in this set; built on first use. */
102 #relocs: Map<LineId, RelocationInfo> | undefined;
103 /** The same, by n, with the new parent's code. */
104 #relocsN: Map<number, { readonly r: RelocationInfo; readonly parent: number }> | undefined;
105 #fileOf = new Map<number, string>();
106 /** The latest records asked for: one file's lines, one file's sequence, one file's text. */
107 #linesCache: { path: string; lines: readonly VisibleLine[] } | undefined;
108 #seqCache: { path: string; seq: readonly SeqLine[] } | undefined;
109 #textCache: { path: string; text: string } | undefined;
111 constructor(graph: Graph, set: Iterable<AtomId>) {
112 const inSet = new Uint8Array(graph.size);
113 const atoms: { readonly id: AtomId; readonly deps: readonly AtomId[] }[] = [];
114 for (const id of set) {
115 const atom = graph.atom(id);
116 inSet[atom.seq] = 1;
117 atoms.push(atom);
118 }
119 for (const atom of atoms) {
120 for (const d of atom.deps) {
121 if (inSet[graph.atom(d).seq] !== 1)
122 throw new EngineError("not-closed", `set is not closed: ${atom.id} depends on ${d}`);
123 }
124 }
125 this.graph = graph;
126 this.#in = inSet;
127 this.#movers = graph.movers().filter((id) => inSet[graph.atom(id).seq] === 1);
128 this.#relocs = this.#movers.length === 0 ? new Map() : undefined;
129 this.#relocsN = this.#movers.length === 0 ? new Map() : undefined;
130 }
132 /** The set of atoms this view projects. */
133 get set(): AtomSet {
134 if (!this.#set) {
135 const out = new Set<AtomId>();
136 for (let seq = 0; seq < this.#in.length; seq++) if (this.#in[seq] === 1) out.add(this.graph.idOfSeq(seq));
137 this.#set = out;
138 }
139 return this.#set;
140 }
142 /** Whether the atom with this seq is in the set. */
143 #has(seq: number): boolean {
144 return seq < this.#in.length && this.#in[seq] === 1;
145 }
147 /**
148 * The relocation that counts for each moved line: the newest (by priority)
149 * in the set. Two moves made apart can loop lines into each other, so no
150 * start node reaches them; then the oldest relocation on the loop is
151 * ignored, and the next newest of that line counts, until none loop.
152 */
153 #relocations(): Map<LineId, RelocationInfo> {
154 if (this.#relocs) return this.#relocs;
155 const graph = this.graph;
156 const stronger = (a: RelocationInfo, b: RelocationInfo): boolean => graph.comparePriority(a.atom, b.atom) > 0;
157 const ignored = new Set<RelocationInfo>();
158 const pick = (line: LineId): RelocationInfo | undefined => {
159 let best: RelocationInfo | undefined;
160 for (const r of graph.relocationsOf(line)) {
161 if (this.#has(graph.atom(r.atom).seq) && !ignored.has(r) && (!best || stronger(r, best))) best = r;
162 }
163 return best;
164 };
165 const relocs = new Map<LineId, RelocationInfo>();
166 for (const id of this.#movers) {
167 for (const m of graph.atom(id).moves!) {
168 if (!relocs.has(m.line)) relocs.set(m.line, pick(m.line)!);
169 }
170 }
171 const parentOf = (line: LineId): NodeId => relocs.get(line)?.parent ?? graph.lineParent(line)!;
172 const reaches = new Set<LineId>();
173 for (const line of [...relocs.keys()]) {
174 for (;;) {
175 const path: LineId[] = [];
176 const onPath = new Map<LineId, number>();
177 let cur: NodeId = line;
178 let loopAt = -1;
179 while (!isStartNode(cur) && !reaches.has(cur)) {
180 const at = onPath.get(cur);
181 if (at !== undefined) {
182 loopAt = at;
183 break;
184 }
185 onPath.set(cur, path.length);
186 path.push(cur);
187 cur = parentOf(cur);
188 }
189 if (loopAt < 0) {
190 for (const l of path) reaches.add(l);
191 break;
192 }
193 let weakest: RelocationInfo | undefined;
194 for (const l of path.slice(loopAt)) {
195 const r = relocs.get(l);
196 if (r && (!weakest || stronger(weakest, r))) weakest = r;
197 }
198 ignored.add(weakest!);
199 const next = pick(weakest!.line);
200 if (next) relocs.set(weakest!.line, next);
201 else relocs.delete(weakest!.line);
202 }
203 }
204 this.#relocs = relocs;
205 return relocs;
206 }
208 /** The relocations by n, with each new parent's code. */
209 #relocationsN(): Map<number, { readonly r: RelocationInfo; readonly parent: number }> {
210 if (this.#relocsN) return this.#relocsN;
211 const out = new Map<number, { readonly r: RelocationInfo; readonly parent: number }>();
212 for (const [line, r] of this.#relocations())
213 out.set(this.graph.lineN(line), { r, parent: this.graph.codeOf(r.parent)! });
214 this.#relocsN = out;
215 return out;
216 }
218 /** The node a line hangs off in this set: where it was written, or where a move put it. */
219 parentOf(line: LineId): NodeId {
220 const r = this.#movers.length === 0 ? undefined : this.#relocations().get(line);
221 if (r) return r.parent;
222 const parent = this.graph.lineParent(line);
223 if (parent === undefined) throw new EngineError("unknown-line", `no line ${line}`);
224 return parent;
225 }
227 /** Whether any atom in the set moves lines. */
228 hasMoves(): boolean {
229 return this.#movers.length > 0;
230 }
232 /** The file a line is in, in this set: the one its chain of parents reaches. */
233 fileOf(line: LineId): string {
234 const n = this.graph.lineN(line);
235 if (n < 0) throw new EngineError("unknown-line", `no line ${line}`);
236 return this.#fileOfN(n);
237 }
239 #fileOfN(n: number): string {
240 const graph = this.graph;
241 if (this.#movers.length === 0) return graph.writtenIn(n);
242 const relocs = this.#relocationsN();
243 const path: number[] = [];
244 let cur = n;
245 let file: string | undefined;
246 while (file === undefined) {
247 if (cur < 0) file = graph.nodeOf(cur).slice(1);
248 else {
249 file = this.#fileOf.get(cur);
250 if (file === undefined) {
251 path.push(cur);
252 cur = relocs.get(cur)?.parent ?? graph.parentCodeOf(cur);
253 }
254 }
255 }
256 for (const l of path) this.#fileOf.set(l, file);
257 return file;
258 }
260 /** The lines hanging off a node in this set, in layout order. */
261 #children(code: number): Child[] {
262 const graph = this.graph;
263 const relocs = this.#movers.length === 0 ? undefined : this.#relocationsN();
264 const ns: number[] = [];
265 graph.childrenN(code, ns);
266 const out: Child[] = [];
267 for (const n of ns) {
268 const seq = graph.writerSeqOf(n);
269 if (!this.#has(seq) || relocs?.has(n)) continue;
270 out.push({ n, replaces: graph.replacesN(n) ? 1 : 0, lamport: graph.lamportOfSeq(seq), seq, k: graph.kOf(n) });
271 }
272 if (relocs) {
273 for (const r of graph.relocatedToCode(code)) {
274 const n = graph.lineN(r.line);
275 if (relocs.get(n)?.r !== r) continue;
276 const seq = graph.atom(r.atom).seq;
277 out.push({ n, replaces: 0, lamport: graph.lamportOfSeq(seq), seq, k: r.k });
278 }
279 }
280 // A line's replacements (runs of atoms that deleted it) first, then the
281 // rest; each group in descending priority (lamport, then seq); lines of
282 // one atom keep k order. A replacement already outranks every insertion
283 // after the line that reads it (it depends on them, or conflicts with
284 // them); the grouping also puts it above a `before` insertion, which
285 // doesn't read the line above, so the new text lands in the replaced
286 // line's place. A moved line ranks like an insertion by the moving atom.
287 if (out.length > 1)
288 out.sort((a, b) => b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k);
289 return out;
290 }
292 /** Lay out one file: its line tree from the set's atoms, linearized. */
293 #layout(path: string): FileState {
294 const graph = this.graph;
295 // For each attribute, the highest-priority setter in the set wins.
296 const setters = new Map<string, { id: AtomId; value: string | null }>();
297 for (const id of graph.atomsIn(path)) {
298 if (!this.#has(graph.atom(id).seq)) continue;
299 for (const a of graph.atom(id).attrs ?? []) {
300 if (a.file !== path) continue;
301 const best = setters.get(a.name);
302 if (!best || graph.comparePriority(best.id, id) < 0) setters.set(a.name, { id, value: a.value });
303 }
304 }
306 const seq: number[] = [];
307 const vis: number[] = [];
308 const deletedBy = new Map<number, readonly number[]>();
309 // Depth-first, iteratively (a file of n lines can be a chain n deep).
310 const stack: number[] = [];
311 const pushChildren = (code: number): void => {
312 const list = this.#children(code);
313 for (let i = list.length - 1; i >= 0; i--) stack.push(list[i]!.n);
314 };
315 const start = graph.startCodeOf(path);
316 if (start !== undefined) pushChildren(start);
317 const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b;
318 while (stack.length > 0) {
319 const n = stack.pop()!;
320 const deleters = graph.deleterSeqsOf(n);
321 const by = deleters.length === 0 ? NONE : deleters.filter((d) => this.#has(d));
322 if (by.length > 0) deletedBy.set(seq.length, by.length > 1 ? [...by].sort(priority) : by);
323 else vis.push(n);
324 seq.push(n);
325 pushChildren(n);
326 }
327 const attrs: FileAttrs = {
328 exists: setters.get("exists")?.value === "1",
329 exec: setters.get("exec")?.value === "1",
330 link: setters.get("link")?.value ?? null,
331 blob: setters.get("blob")?.value ?? null,
332 };
333 return { attrs, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy };
334 }
336 get #known(): string[] {
337 if (!this.#knownList) {
338 const known = new Set<string>();
339 for (let seq = 0; seq < this.#in.length; seq++)
340 if (this.#in[seq] === 1) for (const file of this.graph.filesOf(this.graph.idOfSeq(seq))) known.add(file);
341 this.#knownList = [...known].sort();
342 }
343 return this.#knownList;
344 }
346 /** Files with at least one visible line, sorted. */
347 paths(): string[] {
348 return this.#known.filter((p) => this.hasFile(p));
349 }
351 /** Every file the set has ever written a line in, including fully deleted ones. */
352 knownPaths(): string[] {
353 return [...this.#known];
354 }
356 /** Whether the file exists in this projection (has a visible line). */
357 hasFile(path: string): boolean {
358 const f = this.#file(path);
359 return f.vis.length > 0 || f.attrs.exists || f.attrs.link !== null || f.attrs.blob !== null;
360 }
362 /** A file's attributes: kept while empty, executable, a link's target. */
363 attrs(path: string): FileAttrs {
364 return this.#file(path).attrs;
365 }
367 /** The projected text of a file ("" if it has no visible lines). */
368 text(path: string): string {
369 if (this.#textCache?.path === path) return this.#textCache.text;
370 const vis = this.#file(path).vis;
371 const lines: string[] = new Array(vis.length);
372 for (let i = 0; i < vis.length; i++) lines[i] = this.graph.textOf(vis[i]!);
373 const text = joinLines(lines);
374 this.#textCache = { path, text };
375 return text;
376 }
378 /** Whether a file reads the same here and in `other` (of the same graph), compared line by line without joining either (#46). */
379 sameText(path: string, other: View): boolean {
380 const a = this.#file(path).vis;
381 const b = other.#file(path).vis;
382 if (a.length !== b.length) return false;
383 for (let i = 0; i < a.length; i++)
384 if (a[i] !== b[i] && this.graph.textOf(a[i]!) !== this.graph.textOf(b[i]!)) return false;
385 return true;
386 }
388 /** Visible lines with their ids. */
389 lines(path: string): readonly VisibleLine[] {
390 if (this.#linesCache?.path === path) return this.#linesCache.lines;
391 const graph = this.graph;
392 const vis = this.#file(path).vis;
393 const lines: VisibleLine[] = new Array(vis.length);
394 for (let i = 0; i < vis.length; i++) {
395 const n = vis[i]!;
396 lines[i] = { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) };
397 }
398 this.#linesCache = { path, lines };
399 return lines;
400 }
402 /** The full linearized sequence of a file, tombstones included. */
403 sequence(path: string): readonly SeqLine[] {
404 if (this.#seqCache?.path === path) return this.#seqCache.seq;
405 const graph = this.graph;
406 const f = this.#file(path);
407 const out: SeqLine[] = new Array(f.seq.length);
408 for (let i = 0; i < f.seq.length; i++) {
409 const n = f.seq[i]!;
410 const by = f.deletedBy.get(i);
411 out[i] = {
412 id: graph.lineIdOf(n),
413 text: graph.textOf(n),
414 atom: graph.idOfSeq(graph.writerSeqOf(n)),
415 deletedBy: by ? by.map((s) => graph.idOfSeq(s)) : NONE,
416 visible: by === undefined,
417 };
418 }
419 this.#seqCache = { path, seq: out };
420 return out;
421 }
423 /** Index of a line in `sequence(path)`, or -1. */
424 sequenceIndex(path: string, line: LineId): number {
425 const f = this.#file(path);
426 if (!f.seqIndex) {
427 f.seqIndex = new Map();
428 for (let i = 0; i < f.seq.length; i++) f.seqIndex.set(f.seq[i]!, i);
429 }
430 return f.seqIndex.get(this.graph.lineN(line)) ?? -1;
431 }
433 /** Index of a line in `lines(path)` (0-based visible line number), or -1 if not visible. */
434 lineNumber(path: string, line: LineId): number {
435 const f = this.#file(path);
436 if (!f.visIndex) {
437 f.visIndex = new Map();
438 for (let i = 0; i < f.vis.length; i++) f.visIndex.set(f.vis[i]!, i);
439 }
440 return f.visIndex.get(this.graph.lineN(line)) ?? -1;
441 }
443 /** All projected text files, path -> text, in path order. Binary files are in `blobs()`. */
444 files(): Record<string, string> {
445 const out: Record<string, string> = {};
446 for (const path of this.paths()) if (this.#file(path).attrs.blob === null) out[path] = this.text(path);
447 return out;
448 }
450 /** Binary files, path -> the SHA-256 of their bytes, in path order. */
451 blobs(): Record<string, string> {
452 const out: Record<string, string> = {};
453 for (const path of this.paths()) {
454 const blob = this.#file(path).attrs.blob;
455 if (blob !== null) out[path] = blob;
456 }
457 return out;
458 }
460 /**
461 * About how many bytes of retained state this view costs (#46). This uses
462 * approximate ownership costs for containers and wrappers, not V8 heap
463 * measurements. Graph-owned strings and records count only as references.
464 * This method only inspects already-created state: it does not lay out files,
465 * populate lazy caches, enumerate the graph, or count temporary traversal
466 * containers and shared empty singleton payloads as retained view state.
467 */
468 weight(): number {
469 let n = this.#in.byteLength;
470 n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#movers.length;
471 n += MAP_HEADER_BYTES; // #files exists from construction.
472 n += MAP_HEADER_BYTES; // #fileOf exists from construction.
473 if (this.#set) n += OBJECT_BYTES + SET_ENTRY_BYTES * this.#set.size;
474 if (this.#knownList) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#knownList.length;
475 if (this.#relocs) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * this.#relocs.size;
476 if (this.#relocsN) n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + OBJECT_BYTES) * this.#relocsN.size;
477 n += MAP_ENTRY_BYTES * this.#fileOf.size;
478 for (const f of this.#files.values()) {
479 n += MAP_ENTRY_BYTES;
480 if (f !== NO_FILE) {
481 // FileState and FileAttrs are per laid-out file; typed-array
482 // headers are separate from their payload byte lengths below.
483 n += OBJECT_BYTES + OBJECT_BYTES + 2 * ARRAY_HEADER_BYTES;
484 n += f.seq.byteLength + f.vis.byteLength;
485 n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + ARRAY_HEADER_BYTES) * f.deletedBy.size;
486 for (const deleters of f.deletedBy.values()) n += REFERENCE_BYTES * deleters.length;
487 if (f.seqIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.seqIndex.size;
488 if (f.visIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.visIndex.size;
489 }
490 }
491 if (this.#linesCache)
492 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 100 * this.#linesCache.lines.length;
493 if (this.#seqCache) {
494 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 120 * this.#seqCache.seq.length;
495 for (const line of this.#seqCache.seq)
496 if (line.deletedBy !== NONE) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * line.deletedBy.length;
497 }
498 if (this.#textCache) n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 2 * this.#textCache.text.length;
499 return n;
500 }
502 #file(path: string): FileState {
503 let state = this.#files.get(path);
504 if (!state) {
505 state = this.graph.atomsIn(path).length === 0 ? NO_FILE : this.#layout(path);
506 this.#files.set(path, state);
507 }
508 return state;
509 }
510}
512/** The files of a closed set, path -> text. */
513export function project(graph: Graph, set: Iterable<AtomId>): Record<string, string> {
514 return new View(graph, set).files();
515}
517/** Where a node sits in a file's sequence: the index just after it (0 for a start node). */
518export function indexAfter(view: View, path: string, node: NodeId): number {
519 if (isStartNode(node)) return 0;
520 const i = view.sequenceIndex(path, node);
521 if (i < 0) throw new EngineError("not-in-view", `line ${node} is not in ${path} in this view`);
522 return i + 1;
523}