Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/src/engine/view.ts?version=110&format=json
555 linesFirst import 83% · codex-capacity-chair 9% · codex-capacity-policy 8%Last change codex-capacity-chair in version 110, 4 versions changed it

You're reading version 110. The newest is 318, and 41 versions since then changed this file. Go to the newestCompare with 318

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