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

Versions 142 to 143

Compare

+428 −0 in 1 place
new file, 428 lines
1+import type { Graph } from "../graph.ts";
2+import { orderedChildKey } from "../ordered-index.ts";
3+import { resolveScratchMoves } from "../relocation-scratch.ts";
4+import type { GraphStateStorage } from "../state-source.ts";
5+import type { Atom, AtomId } from "../types.ts";
6+import { ProjectionLocator } from "./projection-locator.ts";
7+import { ProjectionPriority } from "./projection-priority.ts";
8+import {
9+ type ProjectionAttributeName,
10+ type ProjectionAttributes,
11+ type ProjectionAttributeValue,
12+ type ProjectionChildRoot,
13+ type ProjectionMarker,
14+ type ProjectionMembership,
15+ projectionAttributes,
16+ projectionAttributeValue,
17+ projectionChildRoot,
18+ projectionMarker,
19+ projectionMembership,
20+} from "./projection-records.ts";
21+import { ProjectionSequence, type SequenceState } from "./projection-sequence.ts";
23+type Page = number | null;
24+export interface MarkerState {
25+ readonly context: string;
26+ sequence: SequenceState;
27+ locator: Page;
28+ membership: Page;
29+ children: Page;
30+ attributeFiles: Page;
31+}
32+interface Plan {
33+ n: number;
34+ parentKey: number;
35+ key: string;
36+}
37+function relocationPlan(value: unknown): Plan {
38+ if (!value || typeof value !== "object" || Array.isArray(value)) throw Error("invalid relocation plan");
39+ const row = value as Record<string, unknown>;
40+ if (
41+ Object.keys(row).length !== 3 ||
42+ !Number.isSafeInteger(row.n) ||
43+ Number(row.n) < 0 ||
44+ Number(row.n) >= 0x7fffffff ||
45+ !Number.isSafeInteger(row.parentKey) ||
46+ Number(row.parentKey) < 0 ||
47+ Number(row.parentKey) >= 2 ** 32 ||
48+ typeof row.key !== "string" ||
49+ !/^[0-9a-f]{57}$/.test(row.key)
50+ )
51+ throw Error("invalid relocation plan");
52+ return { n: row.n as number, parentKey: row.parentKey as number, key: row.key };
53+}
54+const numeric = (value: unknown): number => {
55+ if (!Number.isSafeInteger(value) || Number(value) < 0) throw Error("invalid projection number");
56+ return value as number;
57+};
58+function required<T>(value: T | undefined): T {
59+ if (value === undefined) throw Error("missing projection record");
60+ return value;
61+}
62+/** Internal typed experiment; root binding wrapper is still required before integration. */
63+export class ExperimentalMarkerProjection {
64+ readonly context: string;
65+ readonly storage: GraphStateStorage;
66+ readonly graph: Graph;
67+ readonly path: string;
68+ readonly sequence: ProjectionSequence;
69+ readonly markers: ProjectionLocator<ProjectionMarker>;
70+ readonly members: ProjectionLocator<ProjectionMembership>;
71+ readonly childRoots: ProjectionLocator<ProjectionChildRoot>;
72+ readonly attributeRoots: ProjectionLocator<ProjectionAttributes>;
73+ readonly priorities: ProjectionPriority<number>;
74+ readonly attributePriorities: ProjectionPriority<ProjectionAttributeValue>;
75+ constructor(storage: GraphStateStorage, graph: Graph, path: string, namespace: string) {
76+ if (!namespace || namespace.length > 4096) throw Error("invalid projection namespace");
77+ this.context = JSON.stringify([namespace, path]);
78+ const prefix = `experimental-marker:${JSON.stringify(namespace)}:`;
79+ this.storage = {
80+ read: (collection, key) => storage.read(prefix + collection, key),
81+ write: (collection, key, value) => storage.write(prefix + collection, key, value),
82+ remove: (collection, key) => storage.remove(prefix + collection, key),
83+ entries: (collection) => storage.entries(prefix + collection),
84+ transaction: (body) => storage.transaction(body),
85+ };
86+ this.graph = graph;
87+ this.path = path;
88+ this.sequence = new ProjectionSequence(storage, namespace + ":sequence");
89+ this.markers = new ProjectionLocator(storage, namespace + ":markers", projectionMarker);
90+ this.members = new ProjectionLocator(storage, namespace + ":membership", projectionMembership);
91+ this.childRoots = new ProjectionLocator(storage, namespace + ":children", projectionChildRoot);
92+ this.attributeRoots = new ProjectionLocator(storage, namespace + ":attributes", projectionAttributes);
93+ this.priorities = new ProjectionPriority(storage, namespace + ":priorities", numeric);
94+ this.attributePriorities = new ProjectionPriority(
95+ storage,
96+ namespace + ":attribute-priorities",
97+ projectionAttributeValue,
98+ );
99+ }
100+ assertContext(state: MarkerState): void {
101+ if (!state || state.context !== this.context) throw Error("projection constructor context mismatch");
102+ }
103+ empty(): MarkerState {
104+ return {
105+ context: this.context,
106+ sequence: this.sequence.empty(),
107+ locator: null,
108+ membership: null,
109+ children: null,
110+ attributeFiles: null,
111+ };
112+ }
113+ apply(previous: MarkerState, atom: Atom): MarkerState {
114+ this.assertContext(previous);
115+ if (JSON.stringify(this.graph.atom(atom.id)) !== JSON.stringify(atom)) throw Error("canonical atom mismatch");
116+ if (this.members.get(previous.membership, atom.seq)?.present) return previous;
117+ for (const id of atom.deps)
118+ if (!this.members.get(previous.membership, this.graph.atom(id).seq)?.present) throw Error("missing dependency");
119+ return this.storage.transaction(() => {
120+ const state = { ...previous };
121+ const sequence = this.sequence;
122+ const insert = (rank: number, text: string, hidden = false): number => {
123+ const id = state.sequence.next;
124+ state.sequence = sequence.update(state.sequence, { kind: "insert", rank, text });
125+ if (hidden) state.sequence = sequence.update(state.sequence, { kind: "visibility", id, delta: 1 });
126+ return id;
127+ };
128+ this.ensureFile(state, this.path);
129+ for (const run of atom.inserts) this.ensureFile(state, run.file);
130+ let k = 0;
131+ for (const run of atom.inserts)
132+ for (const text of run.lines) {
133+ const line = `${atom.id}.${k++}`,
134+ n = this.graph.lineN(line),
135+ parent = this.graph.parentCodeOf(n);
136+ if (n + 1 >= 0x80000000) throw Error("prototype line identity limit");
137+ const existing = this.markers.get(state.locator, n + 1);
138+ if (existing) {
139+ state.sequence = sequence.update(state.sequence, { kind: "visibility", id: existing.enter, delta: -1 });
140+ continue;
141+ }
142+ const parentMarker = this.markers.get(state.locator, this.parentKey(parent));
143+ if (!parentMarker) throw Error("missing parent marker");
144+ const parentKey = this.parentKey(parent);
145+ const index = this.priorities;
146+ const root = this.childRoots.get(state.children, parentKey)?.root ?? null;
147+ const seq = this.graph.writerSeqOf(n);
148+ const key = orderedChildKey({
149+ n,
150+ replaces: this.graph.replacesN(n) ? 1 : 0,
151+ lamport: this.graph.lamportOfSeq(seq),
152+ seq,
153+ k: this.graph.kOf(n),
154+ });
155+ const preceding = index.before(root, key);
156+ const anchor =
157+ preceding === undefined
158+ ? parentMarker.enter
159+ : required(this.markers.get(state.locator, preceding + 1)).exit;
160+ state.children = this.childRoots.set(state.children, parentKey, { root: index.insert(root, key, n) });
161+ const at = sequence.rank(state.sequence, anchor) + 1;
162+ const enter = insert(at, line),
163+ exit = insert(at + 1, `${line}:end`, true);
164+ state.locator = this.markers.set(state.locator, n + 1, { kind: "line", enter, exit, parentKey, key });
165+ }
166+ for (const line of atom.deletes) {
167+ const marker = this.markers.get(state.locator, this.graph.lineN(line) + 1);
168+ if (!marker) throw Error("missing deleted marker");
169+ state.sequence = sequence.update(state.sequence, { kind: "visibility", id: marker.enter, delta: 1 });
170+ }
171+ for (const id of atom.deps) {
172+ const seq = this.graph.atom(id).seq,
173+ member = required(this.members.get(state.membership, seq));
174+ state.membership = this.members.set(state.membership, seq, { ...member, dependents: member.dependents + 1 });
175+ }
176+ this.updateAttributes(state, atom, true);
177+ this.updateFiles(state, atom, 1);
178+ state.membership = this.members.set(state.membership, atom.seq, { present: true, dependents: 0 });
179+ return atom.moves?.length ? this.reconcileMoves(state) : state;
180+ });
181+ }
182+ removeDeleter(previous: MarkerState, atom: Atom): MarkerState {
183+ return this.removeAtom(previous, atom);
184+ }
185+ removeAtom(previous: MarkerState, atom: Atom): MarkerState {
186+ this.assertContext(previous);
187+ if (JSON.stringify(this.graph.atom(atom.id)) !== JSON.stringify(atom)) throw Error("canonical atom mismatch");
188+ if (!this.members.get(previous.membership, atom.seq)?.present) return previous;
189+ if (required(this.members.get(previous.membership, atom.seq)).dependents)
190+ throw Error("included dependent prevents removal");
191+ return this.storage.transaction(() => {
192+ const state = { ...previous };
193+ let k = 0;
194+ for (const run of atom.inserts)
195+ for (const text of run.lines) {
196+ const marker = this.markers.get(state.locator, this.graph.lineN(`${atom.id}.${k++}`) + 1);
197+ if (!marker) throw Error("missing inserted marker");
198+ state.sequence = this.sequence.update(state.sequence, { kind: "visibility", id: marker.enter, delta: 1 });
199+ }
200+ for (const line of atom.deletes) {
201+ const marker = this.markers.get(state.locator, this.graph.lineN(line) + 1);
202+ if (!marker) throw Error("missing deleted marker");
203+ state.sequence = this.sequence.update(state.sequence, { kind: "visibility", id: marker.enter, delta: -1 });
204+ }
205+ for (const id of atom.deps) {
206+ const seq = this.graph.atom(id).seq,
207+ member = required(this.members.get(state.membership, seq));
208+ if (!member?.present || member.dependents < 1) throw Error("invalid dependency count");
209+ state.membership = this.members.set(state.membership, seq, { ...member, dependents: member.dependents - 1 });
210+ }
211+ this.updateAttributes(state, atom, false);
212+ this.updateFiles(state, atom, -1);
213+ state.membership = this.members.set(state.membership, atom.seq, { present: false, dependents: 0 });
214+ return atom.moves?.length ? this.reconcileMoves(state) : state;
215+ });
216+ }
217+ reconcileMoves(previous: MarkerState): MarkerState {
218+ this.assertContext(previous);
219+ return this.storage.transaction(() => {
220+ const scope = numeric(this.storage.read("sequence-meta", "work-scope") ?? 0);
221+ this.storage.write("sequence-meta", "work-scope", scope + 1);
222+ const prefix = `sequence-resolver:${scope}:`,
223+ collections = new Set<string>();
224+ const scratch: GraphStateStorage = {
225+ read: (c, k) => this.storage.read(prefix + c, k),
226+ write: (c, k, v) => {
227+ collections.add(c);
228+ this.storage.write(prefix + c, k, v);
229+ },
230+ remove: (c, k) => this.storage.remove(prefix + c, k),
231+ entries: (c) => this.storage.entries(prefix + c),
232+ transaction: (body) => this.storage.transaction(body),
233+ };
234+ const has = (id: AtomId) => this.members.get(previous.membership, this.graph.atom(id).seq)?.present ?? false;
235+ previous = { ...previous };
236+ for (const id of this.graph.movers())
237+ for (const move of this.graph.atom(id).moves ?? [])
238+ if (move.parent.startsWith("^")) this.ensureFile(previous, move.parent.slice(1));
239+ const resolved = resolveScratchMoves(this.graph, has, scratch),
240+ self = this;
241+ function* plans(): IterableIterator<Plan> {
242+ for (const id of self.graph.movers())
243+ for (const move of self.graph.atom(id).moves ?? []) {
244+ if (scratch.read("planned", move.line)) continue;
245+ scratch.write("planned", move.line, true);
246+ const n = self.graph.lineN(move.line);
247+ if (!has(self.graph.idOfSeq(self.graph.writerSeqOf(n)))) continue;
248+ const marker = self.markers.get(previous.locator, n + 1);
249+ if (!marker || marker.kind !== "line") throw Error("missing selected relocation marker");
250+ const selected = resolved.selected(move.line),
251+ parent = resolved.parent(move.line);
252+ const parentKey = parent.startsWith("^")
253+ ? required(self.fileKey(parent.slice(1)))
254+ : self.graph.lineN(parent) + 1;
255+ const seq = selected ? self.graph.atom(selected.atom).seq : self.graph.writerSeqOf(n);
256+ const key = orderedChildKey({
257+ n,
258+ replaces: selected ? 0 : Number(self.graph.replacesN(n)),
259+ lamport: self.graph.lamportOfSeq(seq),
260+ seq,
261+ k: selected ? selected.k : self.graph.kOf(n),
262+ });
263+ if (parentKey !== marker.parentKey || key !== marker.key) yield { n, parentKey, key };
264+ }
265+ }
266+ const state = this.relocateBatch(previous, plans());
267+ for (const collection of collections)
268+ for (const [key] of this.storage.entries(prefix + collection)) this.storage.remove(prefix + collection, key);
269+ return state;
270+ });
271+ }
272+ relocateBatch(previous: MarkerState, plans: Iterable<Plan>): MarkerState {
273+ this.assertContext(previous);
274+ return this.storage.transaction(() => {
275+ const scope = numeric(this.storage.read("sequence-meta", "work-scope") ?? 0);
276+ this.storage.write("sequence-meta", "work-scope", scope + 1);
277+ const name = `sequence-relocation-work:${scope}`;
278+ let count = 0,
279+ state = previous;
280+ for (const candidate of plans) {
281+ const plan = relocationPlan(candidate);
282+ if (this.storage.read(name, `seen:${plan.n}`)) throw Error("duplicate relocation plan");
283+ this.storage.write(name, `seen:${plan.n}`, true);
284+ this.storage.write(name, String(count++), plan);
285+ }
286+ // A file root is the temporary parking parent. All phases are invisible
287+ // outside this transaction; no history-sized plan array is retained.
288+ for (let i = 0; i < count; i++) {
289+ const plan = relocationPlan(this.storage.read(name, String(i)));
290+ const marker = this.markers.get(state.locator, plan.n + 1);
291+ if (!marker || marker.kind !== "line") throw Error("missing relocation marker");
292+ state = this.relocate(state, plan.n, 0, marker.key);
293+ }
294+ for (let i = 0; i < count; i++) {
295+ const plan = relocationPlan(this.storage.read(name, String(i)));
296+ state = this.relocate(state, plan.n, plan.parentKey, plan.key);
297+ }
298+ for (let i = 0; i < count; i++) {
299+ const plan = relocationPlan(this.storage.read(name, String(i)));
300+ this.storage.remove(name, `seen:${plan.n}`);
301+ this.storage.remove(name, String(i));
302+ }
303+ return state;
304+ });
305+ }
306+ relocate(previous: MarkerState, n: number, parentKey: number, key: string): MarkerState {
307+ this.assertContext(previous);
308+ return this.storage.transaction(() => {
309+ const state = { ...previous },
310+ seq = this.sequence,
311+ index = this.priorities;
312+ const marker = this.markers.get(state.locator, n + 1),
313+ target = this.markers.get(state.locator, parentKey);
314+ if (!marker || marker.kind !== "line" || !target) throw Error("missing relocation marker");
315+ const oldRoot = this.childRoots.get(state.children, marker.parentKey)?.root ?? null;
316+ state.children = this.childRoots.set(state.children, marker.parentKey, {
317+ root: index.remove(oldRoot, marker.key),
318+ });
319+ const newRoot = this.childRoots.get(state.children, parentKey)?.root ?? null;
320+ const sibling = index.before(newRoot, key);
321+ const anchor = sibling === undefined ? target.enter : required(this.markers.get(state.locator, sibling + 1)).exit;
322+ const from = seq.rank(state.sequence, marker.enter),
323+ end = seq.rank(state.sequence, marker.exit);
324+ const anchorRank = seq.rank(state.sequence, anchor),
325+ length = end - from + 1;
326+ if (anchorRank >= from && anchorRank <= end) throw Error("relocation would cycle");
327+ const to = anchorRank + 1 - (anchorRank > end ? length : 0);
328+ state.sequence = seq.update(state.sequence, { kind: "move", from, length, to });
329+ state.children = this.childRoots.set(state.children, parentKey, { root: index.insert(newRoot, key, n) });
330+ state.locator = this.markers.set(state.locator, n + 1, { ...marker, parentKey, key });
331+ return state;
332+ });
333+ }
334+ fileKey(path: string): number | undefined {
335+ if (path === this.path) return 0;
336+ const id = this.storage.read("sequence-file-identities", path);
337+ return id === undefined ? undefined : numeric(id);
338+ }
339+ parentKey(code: number): number {
340+ return code < 0 ? this.fileKey(this.graph.nodeOf(code).slice(1))! : code + 1;
341+ }
342+ ensureFile(state: MarkerState, path: string): void {
343+ this.assertContext(state);
344+ let key = this.fileKey(path);
345+ if (key === undefined) {
346+ key = numeric(this.storage.read("sequence-meta", "next-file") ?? 0x80000000);
347+ if (key >= 2 ** 32) throw Error("file identity limit");
348+ this.storage.write("sequence-file-identities", path, key);
349+ this.storage.write("sequence-meta", "next-file", key + 1);
350+ }
351+ if (this.markers.get(state.locator, key)) return;
352+ const seq = this.sequence;
353+ const insert = (text: string): number => {
354+ const id = state.sequence.next,
355+ rank = state.sequence.root === null ? 0 : seq.get(state.sequence.map, state.sequence.root).count;
356+ state.sequence = seq.update(state.sequence, { kind: "insert", rank, text });
357+ state.sequence = seq.update(state.sequence, { kind: "visibility", id, delta: 1 });
358+ return id;
359+ };
360+ const enter = insert(`root:${path}`),
361+ exit = insert(`end:${path}`);
362+ state.locator = this.markers.set(state.locator, key, { kind: "file", enter, exit, contributions: 0 });
363+ }
364+ updateFiles(state: MarkerState, atom: Atom, delta: 1 | -1): void {
365+ for (const path of this.graph.filesOf(atom.id)) {
366+ this.ensureFile(state, path);
367+ const key = required(this.fileKey(path));
368+ const marker = this.markers.get(state.locator, key);
369+ if (marker?.kind !== "file" || marker.contributions + delta < 0) throw Error("invalid file contribution count");
370+ state.locator = this.markers.set(state.locator, key, { ...marker, contributions: marker.contributions + delta });
371+ }
372+ }
373+ knownPaths(state: MarkerState): string[] {
374+ this.assertContext(state);
375+ const paths: string[] = [];
376+ for (const path of this.graph.knownFiles()) {
377+ const key = this.fileKey(path),
378+ marker = key === undefined ? undefined : this.markers.get(state.locator, key);
379+ if (marker?.kind === "file" && marker.contributions > 0) paths.push(path);
380+ }
381+ return paths.sort();
382+ }
383+ updateAttributes(state: MarkerState, atom: Atom, adding: boolean): void {
384+ this.assertContext(state);
385+ const index = this.attributePriorities,
386+ hex = (n: number) => n.toString(16).padStart(14, "0");
387+ const key = `0${hex(this.graph.lamportOfSeq(atom.seq))}${hex(atom.seq)}${hex(0)}${hex(0)}`;
388+ const names = new Set<string>();
389+ for (const attr of atom.attrs ?? []) {
390+ if (!["exists", "exec", "link", "blob"].includes(attr.name)) throw Error("unsupported attribute");
391+ const identity = JSON.stringify([attr.file, attr.name]);
392+ if (names.has(identity)) continue;
393+ names.add(identity);
394+ this.ensureFile(state, attr.file);
395+ const file = required(this.fileKey(attr.file)),
396+ roots = this.attributeRoots.get(state.attributeFiles, file) ?? {};
397+ const root = roots[attr.name] ?? null;
398+ state.attributeFiles = this.attributeRoots.set(state.attributeFiles, file, {
399+ ...roots,
400+ [attr.name]: adding ? index.insert(root, key, { value: attr.value }) : index.remove(root, key),
401+ });
402+ }
403+ }
404+ attrs(state: MarkerState, path = this.path) {
405+ this.assertContext(state);
406+ const index = this.attributePriorities,
407+ file = this.fileKey(path);
408+ const roots = file === undefined ? {} : (this.attributeRoots.get(state.attributeFiles, file) ?? {});
409+ const value = (name: ProjectionAttributeName) => index.before(roots[name] ?? null, "f".repeat(57))?.value ?? null;
410+ return { exists: value("exists") === "1", exec: value("exec") === "1", link: value("link"), blob: value("blob") };
411+ }
412+ lines(state: MarkerState, path = this.path): string[] {
413+ return [...this.lineIds(state, path)];
414+ }
415+ *lineIds(state: MarkerState, path = this.path): IterableIterator<string> {
416+ this.assertContext(state);
417+ const key = this.fileKey(path);
418+ if (key === undefined) return;
419+ const marker = this.markers.get(state.locator, key);
420+ if (!marker) return;
421+ for (const line of this.sequence.range(
422+ state.sequence,
423+ this.sequence.rank(state.sequence, marker.enter) + 1,
424+ this.sequence.rank(state.sequence, marker.exit),
425+ ))
426+ yield line.text;
427+ }
428+}
MCP
compare on this site's /mcp
CLI
abso diff 142 143 src/engine/experimental/projection-marker.ts --json
JSON
/christopher/abso-core/compare/142..143?file=src%2Fengine%2Fexperimental%2Fprojection-marker.ts&format=json