- 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=44&format=json
490 linesFirst import 100%Last change First import in version 0, 1 version changed it
You're reading version 44. The newest is 318, and 44 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/**
75 * The projection of a closed set. Construct once, then ask for files, lines
76 * and sequences. Throws `not-closed` if some atom's dependency is missing.
77 * Each file is laid out the first time it is asked for, so a view of a large
78 * set costs little until files are read.
79 */
80export class View {
81 readonly graph: Graph;
82 /** 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;
84 #files = new Map<string, FileState>();
85 /** Every file the set wrote in, sorted; worked out the first time it's asked for. */
86 #knownList: string[] | undefined;
87 /** 1 for each atom (by seq) in the set. */
88 #in: Uint8Array;
89 /** Atoms in the set that move lines. */
90 #movers: AtomId[];
91 /** Each moved line's relocation that counts in this set; built on first use. */
92 #relocs: Map<LineId, RelocationInfo> | undefined;
93 /** The same, by n, with the new parent's code. */
94 #relocsN: Map<number, { readonly r: RelocationInfo; readonly parent: number }> | undefined;
95 #fileOf = new Map<number, string>();
96 /** The latest records asked for: one file's lines, one file's sequence, one file's text. */
97 #linesCache: { path: string; lines: readonly VisibleLine[] } | undefined;
98 #seqCache: { path: string; seq: readonly SeqLine[] } | undefined;
99 #textCache: { path: string; text: string } | undefined;
101 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);
108 }
109 for (const atom of atoms) {
110 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}`);
113 }
114 }
115 this.graph = graph;
116 this.#in = inSet;
117 this.#movers = graph.movers().filter((id) => inSet[graph.atom(id).seq] === 1);
118 this.#relocs = this.#movers.length === 0 ? new Map() : undefined;
119 this.#relocsN = this.#movers.length === 0 ? new Map() : undefined;
120 }
122 /** The set of atoms this view projects. */
123 get set(): AtomSet {
124 if (!this.#set) {
125 const out = new Set<AtomId>();
126 for (let seq = 0; seq < this.#in.length; seq++) if (this.#in[seq] === 1) out.add(this.graph.idOfSeq(seq));
127 this.#set = out;
128 }
129 return this.#set;
130 }
132 /** Whether the atom with this seq is in the set. */
133 #has(seq: number): boolean {
134 return seq < this.#in.length && this.#in[seq] === 1;
135 }
137 /**
138 * The relocation that counts for each moved line: the newest (by priority)
139 * in the set. Two moves made apart can loop lines into each other, so no
140 * start node reaches them; then the oldest relocation on the loop is
141 * ignored, and the next newest of that line counts, until none loop.
142 */
143 #relocations(): Map<LineId, RelocationInfo> {
144 if (this.#relocs) return this.#relocs;
145 const graph = this.graph;
146 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;
152 }
153 return best;
154 };
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)!);
159 }
160 }
161 const parentOf = (line: LineId): NodeId => relocs.get(line)?.parent ?? graph.lineParent(line)!;
162 const reaches = new Set<LineId>();
163 for (const line of [...relocs.keys()]) {
164 for (;;) {
165 const path: LineId[] = [];
166 const onPath = new Map<LineId, number>();
167 let cur: NodeId = line;
168 let loopAt = -1;
169 while (!isStartNode(cur) && !reaches.has(cur)) {
170 const at = onPath.get(cur);
171 if (at !== undefined) {
172 loopAt = at;
173 break;
174 }
175 onPath.set(cur, path.length);
176 path.push(cur);
177 cur = parentOf(cur);
178 }
179 if (loopAt < 0) {
180 for (const l of path) reaches.add(l);
181 break;
182 }
183 let weakest: RelocationInfo | undefined;
184 for (const l of path.slice(loopAt)) {
185 const r = relocs.get(l);
186 if (r && (!weakest || stronger(weakest, r))) weakest = r;
187 }
188 ignored.add(weakest!);
189 const next = pick(weakest!.line);
190 if (next) relocs.set(weakest!.line, next);
191 else relocs.delete(weakest!.line);
192 }
193 }
194 this.#relocs = relocs;
195 return relocs;
196 }
198 /** The relocations by n, with each new parent's code. */
199 #relocationsN(): Map<number, { readonly r: RelocationInfo; readonly parent: number }> {
200 if (this.#relocsN) return this.#relocsN;
201 const out = new Map<number, { readonly r: RelocationInfo; readonly parent: number }>();
202 for (const [line, r] of this.#relocations())
203 out.set(this.graph.lineN(line), { r, parent: this.graph.codeOf(r.parent)! });
204 this.#relocsN = out;
205 return out;
206 }
208 /** The node a line hangs off in this set: where it was written, or where a move put it. */
209 parentOf(line: LineId): NodeId {
210 const r = this.#movers.length === 0 ? undefined : this.#relocations().get(line);
211 if (r) return r.parent;
212 const parent = this.graph.lineParent(line);
213 if (parent === undefined) throw new EngineError("unknown-line", `no line ${line}`);
214 return parent;
215 }
217 /** Whether any atom in the set moves lines. */
218 hasMoves(): boolean {
219 return this.#movers.length > 0;
220 }
222 /** The file a line is in, in this set: the one its chain of parents reaches. */
223 fileOf(line: LineId): string {
224 const n = this.graph.lineN(line);
225 if (n < 0) throw new EngineError("unknown-line", `no line ${line}`);
226 return this.#fileOfN(n);
227 }
229 #fileOfN(n: number): string {
230 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 }
244 }
245 }
246 for (const l of path) this.#fileOf.set(l, file);
247 return file;
248 }
250 /** The lines hanging off a node in this set, in layout order. */
251 #children(code: number): Child[] {
252 const graph = this.graph;
253 const relocs = this.#movers.length === 0 ? undefined : this.#relocationsN();
254 const ns: number[] = [];
255 graph.childrenN(code, ns);
256 const out: Child[] = [];
257 for (const n of ns) {
258 const seq = graph.writerSeqOf(n);
259 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) });
261 }
262 if (relocs) {
263 for (const r of graph.relocatedToCode(code)) {
264 const n = graph.lineN(r.line);
265 if (relocs.get(n)?.r !== r) continue;
266 const seq = graph.atom(r.atom).seq;
267 out.push({ n, replaces: 0, lamport: graph.lamportOfSeq(seq), seq, k: r.k });
268 }
269 }
270 // A line's replacements (runs of atoms that deleted it) first, then the
271 // rest; each group in descending priority (lamport, then seq); lines of
272 // one atom keep k order. A replacement already outranks every insertion
273 // after the line that reads it (it depends on them, or conflicts with
274 // them); the grouping also puts it above a `before` insertion, which
275 // doesn't read the line above, so the new text lands in the replaced
276 // line's place. A moved line ranks like an insertion by the moving atom.
277 if (out.length > 1)
278 out.sort((a, b) => b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k);
279 return out;
280 }
282 /** Lay out one file: its line tree from the set's atoms, linearized. */
283 #layout(path: string): FileState {
284 const graph = this.graph;
285 // For each attribute, the highest-priority setter in the set wins.
286 const setters = new Map<string, { id: AtomId; value: string | null }>();
287 for (const id of graph.atomsIn(path)) {
288 if (!this.#has(graph.atom(id).seq)) continue;
289 for (const a of graph.atom(id).attrs ?? []) {
290 if (a.file !== path) continue;
291 const best = setters.get(a.name);
292 if (!best || graph.comparePriority(best.id, id) < 0) setters.set(a.name, { id, value: a.value });
293 }
294 }
296 const seq: number[] = [];
297 const vis: number[] = [];
298 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 };
305 const start = graph.startCodeOf(path);
306 if (start !== undefined) pushChildren(start);
307 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);
316 }
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,
322 };
323 return { attrs, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy };
324 }
326 get #known(): string[] {
327 if (!this.#knownList) {
328 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);
331 this.#knownList = [...known].sort();
332 }
333 return this.#knownList;
334 }
336 /** Files with at least one visible line, sorted. */
337 paths(): string[] {
338 return this.#known.filter((p) => this.hasFile(p));
339 }
341 /** Every file the set has ever written a line in, including fully deleted ones. */
342 knownPaths(): string[] {
343 return [...this.#known];
344 }
346 /** Whether the file exists in this projection (has a visible line). */
347 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;
350 }
352 /** A file's attributes: kept while empty, executable, a link's target. */
353 attrs(path: string): FileAttrs {
354 return this.#file(path).attrs;
355 }
357 /** The projected text of a file ("" if it has no visible lines). */
358 text(path: string): string {
359 if (this.#textCache?.path === path) return this.#textCache.text;
360 const vis = this.#file(path).vis;
361 const lines: string[] = new Array(vis.length);
362 for (let i = 0; i < vis.length; i++) lines[i] = this.graph.textOf(vis[i]!);
363 const text = joinLines(lines);
364 this.#textCache = { path, text };
365 return text;
366 }
368 /** 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 {
370 const a = this.#file(path).vis;
371 const b = other.#file(path).vis;
372 if (a.length !== b.length) return false;
373 for (let i = 0; i < a.length; i++)
374 if (a[i] !== b[i] && this.graph.textOf(a[i]!) !== this.graph.textOf(b[i]!)) return false;
375 return true;
376 }
378 /** Visible lines with their ids. */
379 lines(path: string): readonly VisibleLine[] {
380 if (this.#linesCache?.path === path) return this.#linesCache.lines;
381 const graph = this.graph;
382 const vis = this.#file(path).vis;
383 const lines: VisibleLine[] = new Array(vis.length);
384 for (let i = 0; i < vis.length; i++) {
385 const n = vis[i]!;
386 lines[i] = { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) };
387 }
388 this.#linesCache = { path, lines };
389 return lines;
390 }
392 /** The full linearized sequence of a file, tombstones included. */
393 sequence(path: string): readonly SeqLine[] {
394 if (this.#seqCache?.path === path) return this.#seqCache.seq;
395 const graph = this.graph;
396 const f = this.#file(path);
397 const out: SeqLine[] = new Array(f.seq.length);
398 for (let i = 0; i < f.seq.length; i++) {
399 const n = f.seq[i]!;
400 const by = f.deletedBy.get(i);
401 out[i] = {
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,
406 visible: by === undefined,
407 };
408 }
409 this.#seqCache = { path, seq: out };
410 return out;
411 }
413 /** Index of a line in `sequence(path)`, or -1. */
414 sequenceIndex(path: string, line: LineId): number {
415 const f = this.#file(path);
416 if (!f.seqIndex) {
417 f.seqIndex = new Map();
418 for (let i = 0; i < f.seq.length; i++) f.seqIndex.set(f.seq[i]!, i);
419 }
420 return f.seqIndex.get(this.graph.lineN(line)) ?? -1;
421 }
423 /** Index of a line in `lines(path)` (0-based visible line number), or -1 if not visible. */
424 lineNumber(path: string, line: LineId): number {
425 const f = this.#file(path);
426 if (!f.visIndex) {
427 f.visIndex = new Map();
428 for (let i = 0; i < f.vis.length; i++) f.visIndex.set(f.vis[i]!, i);
429 }
430 return f.visIndex.get(this.graph.lineN(line)) ?? -1;
431 }
433 /** All projected text files, path -> text, in path order. Binary files are in `blobs()`. */
434 files(): Record<string, string> {
435 const out: Record<string, string> = {};
436 for (const path of this.paths()) if (this.#file(path).attrs.blob === null) out[path] = this.text(path);
437 return out;
438 }
440 /** Binary files, path -> the SHA-256 of their bytes, in path order. */
441 blobs(): Record<string, string> {
442 const out: Record<string, string> = {};
443 for (const path of this.paths()) {
444 const blob = this.#file(path).attrs.blob;
445 if (blob !== null) out[path] = blob;
446 }
447 return out;
448 }
450 /**
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.
454 */
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);
466 return n;
467 }
469 #file(path: string): FileState {
470 let state = this.#files.get(path);
471 if (!state) {
472 state = this.graph.atomsIn(path).length === 0 ? NO_FILE : this.#layout(path);
473 this.#files.set(path, state);
474 }
475 return state;
476 }
477}
479/** The files of a closed set, path -> text. */
480export function project(graph: Graph, set: Iterable<AtomId>): Record<string, string> {
481 return new View(graph, set).files();
482}
484/** Where a node sits in a file's sequence: the index just after it (0 for a start node). */
485export function indexAfter(view: View, path: string, node: NodeId): number {
486 if (isStartNode(node)) return 0;
487 const i = view.sequenceIndex(path, node);
488 if (i < 0) throw new EngineError("not-in-view", `line ${node} is not in ${path} in this view`);
489 return i + 1;
490}