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 90 to 318

Compare

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