- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/src/engine/experimental/projection-atom-adoption.ts?format=json
334 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 149, 2 versions changed it
1import { createHash } from "node:crypto";
2import type { Atom } from "../types.ts";
3import { ProjectionAtomDescriptor } from "./projection-atom-index.ts";
4import type { ExperimentalMarkerProjection, MarkerState } from "./projection-marker.ts";
5import { adoptMovesStep } from "./projection-move-adoption.ts";
7const phases = [
8 "dependencies",
9 "files",
10 "lines",
11 "deletes",
12 "counts",
13 "attributes",
14 "contributions",
15 "membership",
16 "moves",
17 "cleanup",
18 "done",
19] as const;
20type Phase = (typeof phases)[number];
21interface Cursor {
22 identity: string;
23 phase: Phase;
24 index: number;
25 run: number;
26 line: number;
27 k: number;
28 state: MarkerState;
29}
30const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
31function shape(value: unknown, names: string): asserts value is Record<string, unknown> {
32 const keys = names.split(" ");
33 if (
34 !value ||
35 typeof value !== "object" ||
36 Array.isArray(value) ||
37 Object.keys(value).length !== keys.length ||
38 keys.some((key) => !Object.hasOwn(value, key))
39 )
40 throw Error("invalid atom adoption record");
41}
42function readCursor(value: unknown): Cursor | undefined {
43 if (value === undefined) return undefined;
44 shape(value, "format checksum cursor");
45 if (value.format !== 1 || typeof value.checksum !== "string" || value.checksum !== digest(value.cursor))
46 throw Error("damaged atom adoption cursor");
47 shape(value.cursor, "identity phase index run line k state");
48 const cursor = value.cursor;
49 shape(cursor.state, "context sequence locator membership children attributeFiles");
50 for (const key of ["locator", "membership", "children", "attributeFiles"])
51 if (cursor.state[key] !== null && (!Number.isSafeInteger(cursor.state[key]) || Number(cursor.state[key]) < 0))
52 throw Error("invalid atom adoption page reference");
53 shape(cursor.state.sequence, "map root next");
54 const sequence = cursor.state.sequence;
55 if (
56 !Number.isSafeInteger(sequence.next) ||
57 Number(sequence.next) < 0 ||
58 Number(sequence.next) > 2 ** 32 ||
59 (sequence.map !== null && (!Number.isSafeInteger(sequence.map) || Number(sequence.map) < 0)) ||
60 (sequence.root !== null &&
61 (!Number.isSafeInteger(sequence.root) ||
62 Number(sequence.root) < 0 ||
63 Number(sequence.root) >= Number(sequence.next))) ||
64 (sequence.root === null) !== (sequence.next === 0) ||
65 (sequence.map === null) !== (sequence.root === null)
66 )
67 throw Error("invalid atom adoption sequence");
68 return cursor as unknown as Cursor;
69}
71/** Private adoption experiment. Partial state must never be published as a read root.
72 * The host must pin source identity and atomically retain this cursor with each page.
73 * Move reconciliation advances through private persisted pages.
74 */
75export class ProjectionAtomAdoption {
76 readonly adapter: ExperimentalMarkerProjection;
77 readonly task: string;
78 constructor(adapter: ExperimentalMarkerProjection, task: string) {
79 if (!task || task.length > 128) throw Error("invalid atom adoption task");
80 this.adapter = adapter;
81 this.task = task;
82 }
83 page(input: {
84 previous: MarkerState;
85 atom: Atom | ProjectionAtomDescriptor;
86 remove: boolean;
87 source: string;
88 maxSteps: number;
89 validateSource(): void;
90 }): {
91 done: boolean;
92 state: MarkerState;
93 steps: number;
94 atomicMoveWork: boolean;
95 } {
96 const { adapter: p } = this;
97 if (
98 !/^[a-f0-9]{64}$/.test(input.source) ||
99 !Number.isSafeInteger(input.maxSteps) ||
100 input.maxSteps < 1 ||
101 input.maxSteps > 256
102 )
103 throw Error("invalid atom adoption page bounds");
104 const atom = input.atom;
105 const indexed = atom instanceof ProjectionAtomDescriptor ? atom : undefined;
106 const full = indexed ? undefined : (atom as Atom);
107 const identity = digest([
108 input.source,
109 input.previous,
110 indexed ? [indexed.id, indexed.seq, indexed.digest] : atom,
111 input.remove,
112 ]);
113 if (indexed) {
114 if (p.graph.idOfSeq(indexed.seq) !== indexed.id) throw Error("canonical adoption atom mismatch");
115 } else if (digest(p.graph.atom(atom.id)) !== digest(full)) throw Error("canonical adoption atom mismatch");
116 const inserts = indexed?.count("inserts") ?? full!.inserts.length;
117 const run = (i: number) =>
118 indexed
119 ? indexed.item("inserts", i)
120 : { file: full!.inserts[i]!.file, parent: full!.inserts[i]!.parent, lines: full!.inserts[i]!.lines.length };
121 const deps = indexed?.count("deps") ?? full!.deps.length;
122 const dependency = (i: number) => (indexed ? indexed.item("deps", i) : full!.deps[i]!);
123 const deletes = indexed?.count("deletes") ?? full!.deletes.length;
124 const deletion = (i: number) => (indexed ? indexed.item("deletes", i) : full!.deletes[i]!);
125 const attrs = indexed?.count("attrs") ?? full!.attrs?.length ?? 0;
126 const attribute = (i: number) => (indexed ? indexed.item("attrs", i) : full!.attrs![i]!);
127 const moves = indexed?.count("moves") ?? full!.moves?.length ?? 0;
128 const fullFiles = indexed ? undefined : p.graph.filesOf(atom.id);
129 const files = indexed?.count("files") ?? fullFiles!.length;
130 const file = (i: number) => (indexed ? indexed.item("files", i) : fullFiles![i]!);
131 const seqOf = (id: string) => {
132 if (!p.graph.has(id)) throw Error("missing dependency");
133 return Number(id.slice(1));
134 };
135 const collection = `atom-adoption:${this.task}`;
136 const validate = () => {
137 const result: unknown = input.validateSource();
138 if (result && typeof result === "object" && "then" in result)
139 throw Error("atom adoption source validation must be synchronous");
140 };
141 return p.storage.transaction(() => {
142 validate();
143 let cursor = readCursor(p.storage.read(collection, "cursor"));
144 if (cursor !== undefined) {
145 if (
146 !cursor ||
147 cursor.identity !== identity ||
148 !phases.includes(cursor.phase) ||
149 ![cursor.index, cursor.run, cursor.line, cursor.k].every((n) => Number.isSafeInteger(n) && n >= 0)
150 )
151 throw Error("invalid or changed atom adoption cursor");
152 p.assertContext(cursor.state);
153 if (cursor.run > inserts || cursor.line > (cursor.run < inserts ? run(cursor.run).lines : 0))
154 throw Error("invalid atom adoption line position");
155 const limits: Record<Phase, number> = {
156 dependencies: deps,
157 files: inserts + 1,
158 lines: 0,
159 deletes: deletes,
160 counts: deps,
161 attributes: attrs,
162 contributions: files,
163 membership: 0,
164 moves: 0,
165 cleanup: attrs,
166 done: 0,
167 };
168 if (cursor.index > limits[cursor.phase]) throw Error("invalid atom adoption phase position");
169 } else {
170 p.assertContext(input.previous);
171 const member = p.members.get(input.previous.membership, atom.seq);
172 if (input.remove && member?.dependents) throw Error("included dependent prevents removal");
173 cursor = {
174 identity,
175 phase: (member?.present ?? false) === !input.remove ? "done" : "dependencies",
176 index: 0,
177 run: 0,
178 line: 0,
179 k: 0,
180 state: structuredClone(input.previous),
181 };
182 }
183 let steps = 0;
184 const atomicMoveWork = false;
185 const next = () => {
186 cursor!.phase = phases[phases.indexOf(cursor!.phase) + 1]!;
187 cursor!.index = 0;
188 };
189 const state = cursor.state;
191 while (cursor.phase !== "done" && steps < input.maxSteps) {
192 steps++;
193 switch (cursor.phase) {
194 case "dependencies": {
195 if (input.remove || cursor.index === deps) {
196 next();
197 break;
198 }
199 const id = dependency(cursor.index++);
200 if (!p.members.get(state.membership, seqOf(id))?.present) throw Error("missing dependency");
201 break;
202 }
203 case "files": {
204 if (input.remove || cursor.index > inserts) {
205 next();
206 break;
207 }
208 p.ensureFile(state, cursor.index === 0 ? p.path : run(cursor.index - 1).file);
209 cursor.index++;
210 break;
211 }
212 case "lines": {
213 if (cursor.run === inserts) {
214 next();
215 break;
216 }
217 const currentRun = run(cursor.run);
218 if (cursor.line === currentRun.lines) {
219 cursor.run++;
220 cursor.line = 0;
221 break;
222 }
223 const line = `${atom.id}.${cursor.k++}`;
224 cursor.line++;
225 if (!input.remove) p.insertLine(state, line);
226 else {
227 const marker = p.markers.get(state.locator, p.graph.lineN(line) + 1);
228 if (!marker) throw Error("missing inserted marker");
229 state.sequence = p.sequence.update(state.sequence, { kind: "visibility", id: marker.enter, delta: 1 });
230 }
231 break;
232 }
233 case "deletes": {
234 if (cursor.index === deletes) {
235 next();
236 break;
237 }
238 const marker = p.markers.get(state.locator, p.graph.lineN(deletion(cursor.index++)) + 1);
239 if (!marker) throw Error("missing deleted marker");
240 state.sequence = p.sequence.update(state.sequence, {
241 kind: "visibility",
242 id: marker.enter,
243 delta: input.remove ? -1 : 1,
244 });
245 break;
246 }
247 case "counts": {
248 if (cursor.index === deps) {
249 next();
250 break;
251 }
252 const seq = seqOf(dependency(cursor.index++));
253 const member = p.members.get(state.membership, seq);
254 if (!member?.present || (input.remove && member.dependents < 1)) throw Error("invalid dependency count");
255 state.membership = p.members.set(state.membership, seq, {
256 ...member,
257 dependents: member.dependents + (input.remove ? -1 : 1),
258 });
259 break;
260 }
261 case "attributes": {
262 if (cursor.index === attrs) {
263 next();
264 break;
265 }
266 const attr = attribute(cursor.index++);
267 const key = JSON.stringify([attr.file, attr.name]);
268 if (!p.storage.read(`${collection}:attributes`, key)) {
269 p.updateAttributes(state, { seq: atom.seq, attrs: [attr] }, !input.remove);
270 p.storage.write(`${collection}:attributes`, key, true);
271 }
272 break;
273 }
274 case "contributions": {
275 if (cursor.index === files) {
276 next();
277 break;
278 }
279 const path = file(cursor.index++);
280 p.ensureFile(state, path);
281 const key = p.fileKey(path)!;
282 const marker = p.markers.get(state.locator, key);
283 const delta = input.remove ? -1 : 1;
284 if (marker?.kind !== "file" || marker.contributions + delta < 0)
285 throw Error("invalid file contribution count");
286 state.locator = p.markers.set(state.locator, key, {
287 ...marker,
288 contributions: marker.contributions + delta,
289 });
290 break;
291 }
292 case "membership":
293 state.membership = p.members.set(state.membership, atom.seq, { present: !input.remove, dependents: 0 });
294 next();
295 break;
296 case "moves":
297 if (moves) {
298 const result = adoptMovesStep(
299 p,
300 state,
301 this.task,
302 identity,
303 indexed
304 ? {
305 count: (id) => indexed.related(id).count("moves"),
306 at: (id, k) => {
307 const atom = indexed.related(id);
308 return k < atom.count("moves") ? atom.item("moves", k) : undefined;
309 },
310 }
311 : undefined,
312 );
313 Object.assign(state, result.state);
314 if (!result.done) break;
315 }
316 next();
317 break;
318 case "cleanup": {
319 if (cursor.index === attrs) {
320 next();
321 break;
322 }
323 const attr = attribute(cursor.index++);
324 p.storage.remove(`${collection}:attributes`, JSON.stringify([attr.file, attr.name]));
325 break;
326 }
327 }
328 }
329 validate();
330 p.storage.write(collection, "cursor", { format: 1, checksum: digest(cursor), cursor });
331 return { done: cursor.phase === "done", state: structuredClone(state), steps, atomicMoveWork };
332 });
333 }
334}