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/worker/project/collisions.ts?format=json
452 linesFirst import 55% · capacity 26% · codex-capacity-chair 18% · pinch 1%Last change capacity in version 317, 11 versions changed it
1// Collisions (#11, #37): which draft changes collide with other work by the
2// engine's rule, how a collision reads, who published the other side, and
3// duplicate top-level names. The project calls these and decides who hears what.
4
5import {
6 type AtomId,
7 type ConflictKey,
8 claimsOf,
9 conflictKeys,
10 type Graph,
11 joinLines,
12 type Key,
13 parseKey,
14 type ReadView,
15 seqOf,
16} from "../../src/engine/index.ts";
17import { differenceSet, StableOverlaySet } from "../../src/engine/state-source.ts";
18import { definedTwice } from "./definitions.ts";
19import type { AgentState, Collision, CollisionSide } from "./project-types.ts";
20import { SHARED, type Space } from "./spaces.ts";
22export interface Pair {
23 readonly yours: AtomId;
24 readonly theirs: AtomId;
25 readonly keys: readonly ConflictKey[];
28/** Where a published atom came from. */
29export interface Origin {
30 readonly agent: string;
31 readonly message: string;
32 readonly version: number;
33 readonly draft?: string;
36/** A line too plain to identify on its own: blank, or only brackets and punctuation. */
37export const PLAIN_LINE = /^[\s{}()[\];,.]*$/;
39/**
40 * Pairs of a draft change and an atom of `against` that collide by the
41 * engine's rule, and that no atom of `settled` resolves.
42 */
43export function pairsIn(
44 g: Graph,
45 draft: readonly AtomId[],
46 against: ReadonlySet<AtomId>,
47 settled: ReadonlySet<AtomId>,
48): Pair[] {
49 return pairsFrom(g, claimantsIn(g, draft, against), against, settled);
52/**
53 * Each draft change's claimants in `against`, in seq order: the atoms whose claims meet its keys, before the
54 * engine's rule is applied. A stored atom's keys are read from disk, so a caller checking one draft against many
55 * (draft-collisions.ts) gathers once against all of them and filters with pairsFrom.
56 */
57export function claimantsIn(
58 g: Graph,
59 draft: readonly AtomId[],
60 against: ReadonlySet<AtomId>,
61): ReadonlyMap<AtomId, readonly AtomId[]> {
62 const out = new Map<AtomId, AtomId[]>();
63 for (const yours of draft) {
64 const atom = g.atom(yours);
65 const streams: IterableIterator<AtomId>[] = [];
66 for (const key of atom.writes) {
67 streams.push(g.eachWriterOf(key), g.eachReaderOf(key), g.eachHolderOf(key));
68 }
69 for (const key of claimsOf(atom)) streams.push(g.eachWriterOf(key));
70 const theirs: AtomId[] = [];
71 for (const id of orderedClaimants(streams)) if (against.has(id)) theirs.push(id);
72 out.set(yours, theirs);
73 }
74 return out;
77/**
78 * claimantsIn for a few atoms against each other: each atom's claimants among `atoms`, in seq order, from their own
79 * keys held in memory. Walking each key's history of claimants read four lists from disk per key, and a draft deleting
80 * a big file has thousands of keys (abso Capacity).
81 */
82export function claimantsAmong(g: Graph, atoms: readonly AtomId[]): ReadonlyMap<AtomId, readonly AtomId[]> {
83 const claimers = new Map<Key, AtomId[]>();
84 const writers = new Map<Key, AtomId[]>();
85 const keys = new Map<AtomId, { writes: readonly Key[]; claims: readonly Key[] }>();
86 const add = (index: Map<Key, AtomId[]>, key: Key, id: AtomId) => {
87 const list = index.get(key);
88 if (list) list.push(id);
89 else index.set(key, [id]);
90 };
91 for (const id of atoms) {
92 const atom = g.atom(id);
93 const writes = [...atom.writes];
94 // claimsOf, with the writes already read.
95 const claims = [...new Set([...writes, ...atom.reads, ...atom.holds])].sort();
96 keys.set(id, { writes, claims });
97 for (const key of writes) add(writers, key, id);
98 for (const key of claims) add(claimers, key, id);
99 }
100 const out = new Map<AtomId, AtomId[]>();
101 for (const id of atoms) {
102 const own = keys.get(id)!;
103 const found = new Set<AtomId>();
104 // As claimantsIn's streams: what claims a key it writes, and what writes a key it claims.
105 for (const key of own.writes) for (const other of claimers.get(key) ?? []) found.add(other);
106 for (const key of own.claims) for (const other of writers.get(key) ?? []) found.add(other);
107 found.delete(id);
108 out.set(
109 id,
110 [...found].sort((a, b) => seqOf(a) - seqOf(b)),
111 );
112 }
113 return out;
116/** The claimants in `against` that collide by the engine's rule and that no atom of `settled` resolves. */
117export function pairsFrom(
118 g: Graph,
119 claimants: ReadonlyMap<AtomId, readonly AtomId[]>,
120 against: ReadonlySet<AtomId>,
121 settled: ReadonlySet<AtomId>,
122): Pair[] {
123 const out: Pair[] = [];
124 for (const [yours, theirsList] of claimants) {
125 for (const theirs of theirsList) {
126 if (!against.has(theirs)) continue;
127 const [lo, hi] = g.atom(yours).seq < g.atom(theirs).seq ? [yours, theirs] : [theirs, yours];
128 const keys = conflictKeys(g.atom(lo), g.atom(hi), g.dependsOn(hi, lo));
129 if (keys.length === 0 || sideBySide(g, lo, hi, keys)) continue;
130 if (hasCommonResolver(g, lo, hi, settled)) continue;
131 out.push({ yours, theirs, keys });
132 }
133 }
134 return out;
137/** Claim indexes append in canonical seq order. Merge one cursor per current
138 * atom key, retaining no candidate set proportional to historical claims. */
139function* orderedClaimants(streams: IterableIterator<AtomId>[]): IterableIterator<AtomId> {
140 try {
141 type Head = { id: AtomId; seq: number; stream: number };
142 const heap: Head[] = [];
143 const less = (a: Head, b: Head) => a.seq < b.seq || (a.seq === b.seq && a.stream < b.stream);
144 const push = (head: Head) => {
145 let at = heap.length;
146 heap.push(head);
147 while (at > 0) {
148 const parent = (at - 1) >>> 1;
149 if (!less(head, heap[parent]!)) break;
150 heap[at] = heap[parent]!;
151 at = parent;
152 }
153 heap[at] = head;
154 };
155 // Each claimant's seq from its id, as the graph reads it (abso 738): loading the stored atom for it read a row a
156 // claimant, most of a warm draft-state's pairing on abso.
157 const advance = (stream: number) => {
158 const next = streams[stream]!.next();
159 if (!next.done) push({ id: next.value, seq: seqOf(next.value), stream });
160 };
161 for (let stream = 0; stream < streams.length; stream++) advance(stream);
162 let previous = -1;
163 while (heap.length) {
164 const head = heap[0]!;
165 const tail = heap.pop()!;
166 if (heap.length) {
167 let at = 0;
168 while (at * 2 + 1 < heap.length) {
169 let child = at * 2 + 1;
170 if (child + 1 < heap.length && less(heap[child + 1]!, heap[child]!)) child++;
171 if (!less(heap[child]!, tail)) break;
172 heap[at] = heap[child]!;
173 at = child;
174 }
175 heap[at] = tail;
176 }
177 advance(head.stream);
178 if (head.seq === previous) continue;
179 previous = head.seq;
180 yield head.id;
181 }
182 } finally {
183 for (const stream of streams) stream.return?.();
184 }
187/** Resolver indexes share the same append order, so intersection needs two cursors. */
188function hasCommonResolver(g: Graph, lo: AtomId, hi: AtomId, settled: ReadonlySet<AtomId>): boolean {
189 const left = g.eachResolverOf(lo);
190 const right = g.eachResolverOf(hi);
191 try {
192 let a = left.next();
193 let b = right.next();
194 while (!a.done && !b.done) {
195 const x = seqOf(a.value);
196 const y = seqOf(b.value);
197 if (x === y && settled.has(a.value)) return true;
198 if (x <= y) a = left.next();
199 if (y <= x) b = right.next();
200 }
201 return false;
202 } finally {
203 left.return?.();
204 right.return?.();
205 }
208/**
209 * Two pure insertions at the same point, and nothing else between them
210 * (#37, the game trial): both only write the gap after one line. Neither
211 * loses anything (both are kept, one after the other), so that alone is
212 * not a collision. It still is when they share a line with real content (the
213 * same import added twice would be doubled), or when the gap is the top of
214 * a file (two agents creating the same file).
215 */
216function sideBySide(g: Graph, a: AtomId, b: AtomId, keys: readonly ConflictKey[]): boolean {
217 const gaps = new Set<string>();
218 for (const k of keys) {
219 if (k.relation !== "write" || !k.key.startsWith("G:") || k.key.startsWith("G:^")) return false;
220 gaps.add(k.key.slice(2));
221 }
222 const linesAt = (id: AtomId): Set<string> => {
223 const out = new Set<string>();
224 for (const run of g.atom(id).inserts) {
225 if (!gaps.has(run.parent)) continue;
226 for (const l of run.lines) if (!PLAIN_LINE.test(l)) out.add(l.trim());
227 }
228 return out;
229 };
230 const ours = linesAt(a);
231 for (const l of linesAt(b)) if (ours.has(l)) return false;
232 return true;
235/** Describe a pair for the agent: its side in `yoursView`, theirs in `theirsView`, with who published theirs. */
236export function describePair(
237 g: Graph,
238 origin: (atom: AtomId, spaceName: string) => Origin,
239 pair: Pair,
240 yoursView: ReadView,
241 theirsView: ReadView,
242 spaceName: string,
243): Collision {
244 const file = fileOfKey(pair.keys[0]!.key, yoursView);
245 const fileKeys = pair.keys.filter((k) => fileOfKey(k.key, yoursView) === file).map((k) => k.key);
246 const attrsOnly = fileKeys.map((k) => parseKey(k)).filter((k) => k.kind === "attr");
247 if (attrsOnly.length === fileKeys.length) {
248 // Both set the same attribute of the file: show each side's value.
249 const name = attrsOnly[0]!.attr!;
250 const valueIn = (view: ReadView, atom: AtomId): string => {
251 const set = (g.atom(atom).attrs ?? []).find((a) => a.file === file && a.name === name);
252 return set?.value ?? (name === "exec" ? "" : String(view.attrs(file)[name] ?? ""));
253 };
254 return {
255 kind: "attribute",
256 name,
257 file,
258 yours: { lines: [1, 0], text: valueIn(yoursView, pair.yours) },
259 theirs: { lines: [1, 0], text: valueIn(theirsView, pair.theirs), ...origin(pair.theirs, spaceName) },
260 };
261 }
262 return {
263 kind: "lines",
264 file,
265 yours: describeSide(yoursView, pair.yours, file, fileKeys),
266 theirs: { ...describeSide(theirsView, pair.theirs, file, fileKeys), ...origin(pair.theirs, spaceName) },
267 };
270export function fileOfKey(key: string, view: ReadView): string {
271 const { kind, node } = parseKey(key);
272 if (kind === "attr") return node;
273 return node.startsWith("^") ? node.slice(1) : view.fileOf(node);
276/**
277 * The files some atoms change: the graph's files of each, and, in views
278 * with moves (#28), wherever the lines they touch are in those views.
279 */
280export function touchedFiles(g: Graph, ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string> {
281 const out = new Set<string>();
282 const moved = views.filter((v) => v.hasMoves());
283 for (const id of ids) {
284 for (const file of g.filesOf(id)) out.add(file);
285 if (moved.length === 0) continue;
286 const atom = g.atom(id);
287 const lines: string[] = [];
288 for (const run of atom.inserts) if (!run.parent.startsWith("^")) lines.push(run.parent);
289 for (const m of atom.moves ?? []) {
290 lines.push(m.line);
291 if (!m.parent.startsWith("^")) lines.push(m.parent);
292 }
293 for (const v of moved) {
294 for (const line of lines) out.add(v.fileOf(line));
295 // Deleted lines by number where the view can (abso Capacity): a draft deleting a big file has thousands, and
296 // making each one's id only to look its number up again was most of collisions on website.
297 const byNumber = (v as { fileOfNumber?: (n: number) => string }).fileOfNumber;
298 if (byNumber) for (const n of g.deletedNumbers(id)) out.add(byNumber.call(v, n));
299 else for (const line of g.deletedLines(id)) out.add(v.fileOf(line));
300 }
301 }
302 return out;
305/**
306 * The files a view over `below` plus `mine` can lay out differently from `below` (abso Capacity, View.shareFiles), or
307 * undefined when any of it moves lines and `placedDifferently` can't say where those land differently. A view's set is closed under dependencies, so it holds `mine` and whatever
308 * `mine` depends on that `below` lacks; each of those can change a file, so all of them count. Counting `mine` alone
309 * missed the files of work the draft depends on (Testing's typescript-rs diff for cloud-ts-01, core 235).
310 */
311export function touchedBeyond(
312 g: Graph,
313 below: ReadonlySet<AtomId>,
314 mine: Iterable<AtomId>,
315 views: readonly ReadView[],
316 placedDifferently?: () => ReadonlySet<string> | undefined,
317): Set<string> | undefined {
318 const beyond = new Set<AtomId>();
319 const stack = [...mine];
320 while (stack.length) {
321 const id = stack.pop()!;
322 if (beyond.has(id) || below.has(id)) continue;
323 beyond.add(id);
324 for (const dep of g.atom(id).deps) if (!beyond.has(dep) && !below.has(dep)) stack.push(dep);
325 }
326 const files = touchedFiles(g, beyond, views);
327 // Moves change more than the files their atoms name only where a moved line lands differently (View.placedDifferently,
328 // abso Capacity); without that comparison, a draft that moves lines shares nothing.
329 if ([...beyond].some((id) => (g.atom(id).moves?.length ?? 0) > 0)) {
330 const placed = placedDifferently?.();
331 if (!placed) return undefined;
332 for (const file of placed) files.add(file);
333 }
334 return files;
337/** The atom's visible lines in a file of a view, or where it acted when none are left. */
338export function describeSide(view: ReadView, atom: AtomId, file: string, keys: readonly string[]): CollisionSide {
339 const visible = view.lines(file);
340 let first = -1;
341 let lastLine = -1;
342 visible.forEach((line, i) => {
343 if (line.atom === atom) {
344 if (first < 0) first = i;
345 lastLine = i;
346 }
347 });
348 if (first >= 0) {
349 return { lines: [first + 1, lastLine + 1], text: joinLines(visible.slice(first, lastLine + 1).map((l) => l.text)) };
350 }
351 // No lines of its own here (a deletion): point at where the first key sits.
352 let at = 1;
353 const { node } = parseKey(keys[0]!);
354 if (!node.startsWith("^")) {
355 const sequence = view.sequence(file);
356 const index = view.sequenceIndex(file, node);
357 at = 1 + sequence.slice(0, Math.max(index, 0)).filter((l) => l.visible).length;
358 }
359 return { lines: [at, at - 1], text: "" };
362/** What origin, open pairs and duplicate-name collisions need from a project. */
363export interface CollisionHost {
364 readonly graph: Graph;
365 readonly spaces: ReadonlyMap<string, Space>;
366 version(): number;
367 spaceOf(agent: AgentState): Space;
368 agentSet(agent: AgentState): ReadonlySet<AtomId>;
369 draft(agent: AgentState): AtomId[];
370 agentView(agent: AgentState): ReadView;
371 at(space: Space, version: number): ReadonlySet<AtomId>;
372 shared(): Space;
375/** Who published an atom, looking in the given space first and then in shared. */
376export function originOf(host: CollisionHost, atom: AtomId, spaceName: string): Origin {
377 for (const name of [spaceName, SHARED]) {
378 const space = host.spaces.get(name)!;
379 const version = space.publishedIn.get(atom);
380 if (version === undefined) continue;
381 const p = space.versions[version]!;
382 return { agent: p.agent, message: p.message, version, ...(name !== SHARED ? { draft: name } : {}) };
383 }
384 return { agent: host.graph.atom(atom).author, message: "", version: host.version() };
387/**
388 * Draft changes that build on atoms a set doesn't have (a drop took them
389 * out): the files they touch. Those changes can't move onto that set.
390 */
391export function strandedFiles(g: Graph, draft: readonly AtomId[], set: ReadonlySet<AtomId>): string[] {
392 const mine = new Set(draft);
393 const files = new Set<string>();
394 for (const id of draft) {
395 if (g.atom(id).deps.some((d) => !set.has(d) && !mine.has(d))) for (const f of g.filesOf(id)) files.add(f);
396 }
397 return [...files].toSorted();
400/**
401 * Names the agent's draft defines at the top level of a file where other
402 * work defines them too, so they are defined twice there (#25, Fuzzer).
403 */
404export function duplicateCollisions(host: CollisionHost, agent: AgentState): Collision[] {
405 const draft = host.draft(agent);
406 if (draft.length === 0) return [];
407 const mine = new Set(draft);
408 const view = host.agentView(agent);
409 const space = host.spaceOf(agent);
410 const out: Collision[] = [];
411 for (const file of [...touchedFiles(host.graph, draft, [view])].toSorted()) {
412 if (!view.hasFile(file)) continue;
413 for (const [name, defs] of definedTwice(view, file)) {
414 const yours = defs.find((d) => d.lines.some((l) => mine.has(host.graph.line(l)!.atom)));
415 const theirs = defs.find((d) => d.lines.every((l) => !mine.has(host.graph.line(l)!.atom)));
416 if (!yours || !theirs) continue;
417 const by = host.graph.line(theirs.lines[0]!)!.atom;
418 out.push({
419 kind: "duplicate",
420 name,
421 file,
422 yours: { lines: [yours.start + 1, yours.end], text: `${yours.text}\n` },
423 theirs: { lines: [theirs.start + 1, theirs.end], text: `${theirs.text}\n`, ...originOf(host, by, space.name) },
424 });
425 }
426 }
427 return out;
430/**
431 * Collisions the agent has synced into and not settled: its draft against
432 * its space at its base. In a named draft, also the draft's own changes
433 * against shared work the draft was moved onto.
434 */
435export function openPairs(host: CollisionHost, agent: AgentState): Pair[] {
436 const space = host.spaceOf(agent);
437 const set = host.agentSet(agent);
438 const mine = new StableOverlaySet(agent.mine);
439 const out: Pair[] = [];
440 const draft = host.draft(agent);
441 if (draft.length > 0) {
442 const seen = differenceSet(host.at(space, agent.base), mine);
443 out.push(...pairsIn(host.graph, draft, seen, set));
444 }
445 if (space.name !== SHARED) {
446 const shared = host.shared();
447 const pending = [...space.own].filter((id) => set.has(id) && !shared.own.has(id));
448 const sharedSeen = new Set([...set].filter((id) => shared.own.has(id)));
449 out.push(...pairsIn(host.graph, pending, sharedSeen, set));
450 }
451 return out;