- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/src/engine/experimental/projection-sequence.ts?format=json
375 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 163, 4 versions changed it
1import type { GraphStateStorage } from "../state-source.ts";
2import { ProjectionLocator } from "./projection-locator.ts";
4type Page = number | null;
5interface SequenceNode {
6 id: number;
7 parent: Page;
8 left: Page;
9 right: Page;
10 text: string;
11 deletions: number;
12 height: number;
13 count: number;
14 visible: number;
15 fileStarts: number;
16}
17export interface SequenceState {
18 readonly map: Page;
19 readonly root: Page;
20 readonly next: number;
21}
22export type SequenceOperation =
23 | { kind: "insert"; rank: number; text: string; hidden?: boolean }
24 | { kind: "visibility"; id: number; delta: number }
25 | { kind: "move"; from: number; length: number; to: number };
26const safe = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;
27function decode(value: unknown): SequenceNode {
28 if (!value || typeof value !== "object" || Array.isArray(value)) throw Error("invalid sequence node");
29 const row = value as Record<string, unknown>;
30 if (Object.keys(row).length !== 10 || !safe(row.id) || row.id >= 2 ** 32 || typeof row.text !== "string")
31 throw Error("invalid sequence node fields");
32 for (const name of ["parent", "left", "right"])
33 if (row[name] !== null && (!safe(row[name]) || Number(row[name]) >= 2 ** 32 || row[name] === row.id))
34 throw Error("invalid sequence edge");
35 for (const name of ["deletions", "height", "count", "visible", "fileStarts"])
36 if (!safe(row[name])) throw Error("invalid sequence aggregate");
37 if (
38 Number(row.height) < 1 ||
39 Number(row.height) > 64 ||
40 Number(row.count) < 1 ||
41 Number(row.visible) > Number(row.count) ||
42 Number(row.fileStarts) > Number(row.count)
43 )
44 throw Error("invalid sequence aggregate bounds");
45 return row as unknown as SequenceNode;
46}
47export class ProjectionSequence {
48 readonly storage: GraphStateStorage;
49 readonly #locator: ProjectionLocator<SequenceNode>;
50 constructor(storage: GraphStateStorage, namespace: string) {
51 this.storage = storage;
52 this.#locator = new ProjectionLocator(storage, namespace, decode);
53 }
54 empty(): SequenceState {
55 return { map: null, root: null, next: 0 };
56 }
57 get(map: Page, id: number): SequenceNode {
58 const node = this.#locator.get(map, id);
59 if (!node || node.id !== id) throw Error("missing sequence node");
60 const child = (key: Page): SequenceNode | undefined => {
61 if (key === null) return undefined;
62 const value = this.#locator.get(map, key);
63 if (!value || value.id !== key || value.parent !== id) throw Error("invalid sequence child identity");
64 return value;
65 };
66 const left = child(node.left),
67 right = child(node.right);
68 if (
69 node.height !== 1 + Math.max(left?.height ?? 0, right?.height ?? 0) ||
70 Math.abs((left?.height ?? 0) - (right?.height ?? 0)) > 1 ||
71 node.count !== 1 + (left?.count ?? 0) + (right?.count ?? 0) ||
72 node.visible !== (node.deletions === 0 ? 1 : 0) + (left?.visible ?? 0) + (right?.visible ?? 0) ||
73 node.fileStarts !== (node.text.startsWith("root:") ? 1 : 0) + (left?.fileStarts ?? 0) + (right?.fileStarts ?? 0)
74 )
75 throw Error("inconsistent sequence aggregate");
76 return node;
77 }
78 #state(state: SequenceState): void {
79 if (
80 !state ||
81 !safe(state.next) ||
82 state.next > 2 ** 32 ||
83 (state.map !== null && !safe(state.map)) ||
84 (state.root !== null && (!safe(state.root) || state.root >= state.next)) ||
85 (state.root === null) !== (state.next === 0) ||
86 (state.map === null) !== (state.root === null)
87 )
88 throw Error("invalid sequence state");
89 if (state.root !== null && this.get(state.map, state.root).parent !== null)
90 throw Error("invalid sequence root parent");
91 }
92 set(map: Page, id: number, node: SequenceNode): number {
93 if (node.id !== id) throw Error("sequence node identity mismatch");
94 return this.#locator.set(map, id, node);
95 }
96 rank(state: SequenceState, id: number): number {
97 this.#state(state);
98 let node = this.get(state.map, id);
99 if (!node) throw Error("unknown marker");
100 const count = (id: Page): number => (id === null ? 0 : this.get(state.map, id).count);
101 let rank = count(node.left),
102 steps = 0;
103 while (node.parent !== null) {
104 if (++steps > 64) throw Error("invalid parent chain");
105 const parent = this.get(state.map, node.parent);
106 if (parent.right === node.id) rank += count(parent.left) + 1;
107 else if (parent.left !== node.id) throw Error("broken parent edge");
108 node = parent;
109 }
110 if (node.id !== state.root) throw Error("wrong root");
111 return rank;
112 }
113 /** Nearest file start before a marker, using subtree counts instead of line ancestry. */
114 fileAt(state: SequenceState, id: number): string {
115 const target = this.rank(state, id);
116 const seek = (id: Page, offset: number, depth: number): string | undefined => {
117 if (id === null || offset > target) return undefined;
118 if (depth > 64) throw Error("invalid file lookup depth");
119 const node = this.get(state.map, id);
120 if (!node.fileStarts) return undefined;
121 const leftCount = node.left === null ? 0 : this.get(state.map, node.left).count;
122 const at = offset + leftCount;
123 if (at <= target) {
124 const right = seek(node.right, at + 1, depth + 1);
125 if (right !== undefined) return right;
126 if (node.text.startsWith("root:")) return node.text.slice(5);
127 }
128 return seek(node.left, offset, depth + 1);
129 };
130 const file = seek(state.root, 0, 0);
131 if (file === undefined) throw Error("missing projected file start");
132 return file;
133 }
134 update(state: SequenceState, operation: SequenceOperation): SequenceState {
135 return this.updateMany(state, [operation]);
136 }
137 /** A small bounded group shares changed AVL nodes and one locator flush. */
138 updateMany(state: SequenceState, operations: readonly SequenceOperation[]): SequenceState {
139 if (operations.length < 1 || operations.length > 16) throw Error("invalid sequence operation batch");
140 this.#state(state);
141 return this.storage.transaction(() => {
142 let map = state.map;
143 // One operation changes an AVL path plus rotation neighbors, not history.
144 // Keep only those decoded records and persist each final record once.
145 const changed = new Map<number, SequenceNode>();
146 // The immutable input map is fixed for this batch. Cache only its bounded reads;
147 // changed nodes always take precedence and the cache never survives a transaction.
148 const original = new Map<number, SequenceNode>();
149 let originalBytes = 0;
150 const get = (id: number): SequenceNode => {
151 const found = changed.get(id) ?? original.get(id);
152 if (found) return found;
153 const node = this.get(map, id);
154 const bytes = 192 + node.text.length * 2;
155 if (original.size < 256 && originalBytes + bytes <= 65536) {
156 original.set(id, node);
157 originalBytes += bytes;
158 }
159 return node;
160 };
161 const put = (node: SequenceNode): number => {
162 changed.set(node.id, node);
163 return node.id;
164 };
165 const height = (id: Page): number => (id === null ? 0 : get(id).height);
166 const count = (id: Page): number => (id === null ? 0 : get(id).count);
167 const visible = (id: Page): number => (id === null ? 0 : get(id).visible);
168 const fileStarts = (id: Page): number => (id === null ? 0 : get(id).fileStarts);
169 const parent = (id: Page, p: Page): void => {
170 if (id !== null) {
171 const node = get(id);
172 if (node.parent !== p) put({ ...node, parent: p });
173 }
174 };
175 const save = (node: SequenceNode): number => {
176 parent(node.left, node.id);
177 parent(node.right, node.id);
178 return put({
179 ...node,
180 height: 1 + Math.max(height(node.left), height(node.right)),
181 count: 1 + count(node.left) + count(node.right),
182 visible: (node.deletions === 0 ? 1 : 0) + visible(node.left) + visible(node.right),
183 fileStarts: (node.text.startsWith("root:") ? 1 : 0) + fileStarts(node.left) + fileStarts(node.right),
184 });
185 };
186 const rotateLeft = (id: number): number => {
187 const a = get(id),
188 b = get(a.right!);
189 save({ ...a, right: b.left, parent: b.id });
190 return save({ ...b, left: a.id, parent: a.parent });
191 };
192 const rotateRight = (id: number): number => {
193 const a = get(id),
194 b = get(a.left!);
195 save({ ...a, left: b.right, parent: b.id });
196 return save({ ...b, right: a.id, parent: a.parent });
197 };
198 const balance = (id: number): number => {
199 const node = get(id);
200 if (height(node.left) - height(node.right) > 1) {
201 const left = get(node.left!);
202 if (height(left.left) < height(left.right)) save({ ...node, left: rotateLeft(left.id) });
203 return rotateRight(id);
204 }
205 if (height(node.right) - height(node.left) > 1) {
206 const right = get(node.right!);
207 if (height(right.right) < height(right.left)) save({ ...node, right: rotateRight(right.id) });
208 return rotateLeft(id);
209 }
210 return id;
211 };
212 let root = state.root,
213 next = state.next;
214 for (const operation of operations) {
215 if (operation.kind === "insert") {
216 const { rank, text } = operation;
217 if (!Number.isInteger(rank) || rank < 0 || rank > count(root) || next >= 2 ** 32)
218 throw Error("invalid insert");
219 const added = next++;
220 const insert = (id: Page, at: number, p: Page): number => {
221 if (id === null)
222 return put({
223 id: added,
224 parent: p,
225 left: null,
226 right: null,
227 text,
228 deletions: operation.hidden ? 1 : 0,
229 height: 1,
230 count: 1,
231 visible: operation.hidden ? 0 : 1,
232 fileStarts: text.startsWith("root:") ? 1 : 0,
233 });
234 const node = get(id),
235 leftCount = count(node.left);
236 if (at <= leftCount) save({ ...node, left: insert(node.left, at, id) });
237 else save({ ...node, right: insert(node.right, at - leftCount - 1, id) });
238 return balance(id);
239 };
240 root = insert(root, rank, null);
241 parent(root, null);
242 } else if (operation.kind === "move") {
243 const { from, length, to } = operation;
244 const total = count(root);
245 if (
246 ![from, length, to].every(Number.isSafeInteger) ||
247 from < 0 ||
248 length < 0 ||
249 from + length > total ||
250 to < 0 ||
251 to > total - length
252 )
253 throw Error("invalid move range");
254 // Join two AVL trees around one existing stable marker.
255 const join = (left: Page, pivot: number, right: Page): number => {
256 if (height(left) > height(right) + 1) {
257 const node = get(left!);
258 save({ ...node, right: join(node.right, pivot, right) });
259 const result = balance(left!);
260 parent(result, null);
261 return result;
262 }
263 if (height(right) > height(left) + 1) {
264 const node = get(right!);
265 save({ ...node, left: join(left, pivot, node.left) });
266 const result = balance(right!);
267 parent(result, null);
268 return result;
269 }
270 return save({ ...get(pivot), left, right, parent: null });
271 };
272 const split = (id: Page, at: number): [Page, Page] => {
273 if (id === null) return [null, null];
274 const node = get(id),
275 size = count(node.left);
276 if (at <= size) {
277 const [left, middle] = split(node.left, at);
278 const right = join(middle, id, node.right);
279 parent(left, null);
280 parent(right, null);
281 return [left, right];
282 }
283 const [middle, right] = split(node.right, at - size - 1);
284 const left = join(node.left, id, middle);
285 parent(left, null);
286 parent(right, null);
287 return [left, right];
288 };
289 const merge = (left: Page, right: Page): Page => {
290 if (left === null) {
291 parent(right, null);
292 return right;
293 }
294 if (right === null) {
295 parent(left, null);
296 return left;
297 }
298 const [pivot, rest] = split(right, 1);
299 return join(left, pivot!, rest);
300 };
301 if (length && from !== to) {
302 const [left, tail] = split(root, from);
303 const [moved, right] = split(tail, length);
304 const remaining = merge(left, right);
305 const [before, after] = split(remaining, to);
306 root = merge(merge(before, moved), after);
307 parent(root, null);
308 }
309 } else if (operation.kind === "visibility") {
310 let node = get(operation.id);
311 if (
312 !node ||
313 !Number.isInteger(operation.delta) ||
314 Math.abs(operation.delta) !== 1 ||
315 node.deletions + operation.delta < 0
316 )
317 throw Error("invalid visibility");
318 save({ ...node, deletions: node.deletions + operation.delta });
319 while (node.parent !== null) {
320 node = get(node.parent);
321 save(node);
322 }
323 } else throw Error("unknown operation");
324 }
325 // Keep locator staging bounded even if a valid split/merge changes more
326 // than one batch. The enclosing transaction commits all batches together.
327 let batch: Array<readonly [number, SequenceNode]> = [];
328 for (const entry of changed) {
329 batch.push(entry);
330 if (batch.length === 256) {
331 map = this.#locator.setMany(map, batch);
332 batch = [];
333 }
334 }
335 map = this.#locator.setMany(map, batch);
336 return { map, root, next };
337 });
338 }
339 *range(
340 state: SequenceState,
341 from: number,
342 to: number,
343 visibleOnly = true,
344 ): IterableIterator<{ id: number; text: string }> {
345 this.#state(state);
346 if (!safe(from) || !safe(to) || from > to) throw Error("invalid sequence range");
347 const visit = function* (
348 seq: ProjectionSequence,
349 id: Page,
350 offset: number,
351 ): IterableIterator<{ id: number; text: string }> {
352 if (id === null) return;
353 const node = seq.get(state.map, id);
354 if ((visibleOnly && !node.visible) || offset >= to || offset + node.count <= from) return;
355 const leftCount = node.left === null ? 0 : seq.get(state.map, node.left).count;
356 yield* visit(seq, node.left, offset);
357 const at = offset + leftCount;
358 if (at >= from && at < to && (!visibleOnly || node.deletions === 0)) yield { id: node.id, text: node.text };
359 yield* visit(seq, node.right, at + 1);
360 };
361 yield* visit(this, state.root, 0);
362 }
363 *values(state: SequenceState, visibleOnly = true): IterableIterator<{ id: number; text: string }> {
364 this.#state(state);
365 const visit = function* (seq: ProjectionSequence, id: Page): IterableIterator<{ id: number; text: string }> {
366 if (id === null) return;
367 const node = seq.get(state.map, id);
368 if (visibleOnly && node.visible === 0) return;
369 yield* visit(seq, node.left);
370 if (!visibleOnly || node.deletions === 0) yield { id: node.id, text: node.text };
371 yield* visit(seq, node.right);
372 };
373 yield* visit(this, state.root);
374 }
375}