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?version=295&format=json
450 linesFirst import 56% · capacity 25% · codex-capacity-chair 19% · pinch 1%Last change capacity in version 266, 10 versions changed it

You're reading version 295. The newest is 318, and 1 version since then changed this file. Go to the newestCompare with 318

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(g, 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(g: Graph, 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 const advance = (stream: number) => {
156 const next = streams[stream]!.next();
157 if (!next.done) push({ id: next.value, seq: g.atom(next.value).seq, stream });
158 };
159 for (let stream = 0; stream < streams.length; stream++) advance(stream);
160 let previous = -1;
161 while (heap.length) {
162 const head = heap[0]!;
163 const tail = heap.pop()!;
164 if (heap.length) {
165 let at = 0;
166 while (at * 2 + 1 < heap.length) {
167 let child = at * 2 + 1;
168 if (child + 1 < heap.length && less(heap[child + 1]!, heap[child]!)) child++;
169 if (!less(heap[child]!, tail)) break;
170 heap[at] = heap[child]!;
171 at = child;
172 }
173 heap[at] = tail;
174 }
175 advance(head.stream);
176 if (head.seq === previous) continue;
177 previous = head.seq;
178 yield head.id;
179 }
180 } finally {
181 for (const stream of streams) stream.return?.();
182 }
185/** Resolver indexes share the same append order, so intersection needs two cursors. */
186function hasCommonResolver(g: Graph, lo: AtomId, hi: AtomId, settled: ReadonlySet<AtomId>): boolean {
187 const left = g.eachResolverOf(lo);
188 const right = g.eachResolverOf(hi);
189 try {
190 let a = left.next();
191 let b = right.next();
192 while (!a.done && !b.done) {
193 const x = g.atom(a.value).seq;
194 const y = g.atom(b.value).seq;
195 if (x === y && settled.has(a.value)) return true;
196 if (x <= y) a = left.next();
197 if (y <= x) b = right.next();
198 }
199 return false;
200 } finally {
201 left.return?.();
202 right.return?.();
203 }
206/**
207 * Two pure insertions at the same point, and nothing else between them
208 * (#37, the game trial): both only write the gap after one line. Neither
209 * loses anything (both are kept, one after the other), so that alone is
210 * not a collision. It still is when they share a line with real content (the
211 * same import added twice would be doubled), or when the gap is the top of
212 * a file (two agents creating the same file).
213 */
214function sideBySide(g: Graph, a: AtomId, b: AtomId, keys: readonly ConflictKey[]): boolean {
215 const gaps = new Set<string>();
216 for (const k of keys) {
217 if (k.relation !== "write" || !k.key.startsWith("G:") || k.key.startsWith("G:^")) return false;
218 gaps.add(k.key.slice(2));
219 }
220 const linesAt = (id: AtomId): Set<string> => {
221 const out = new Set<string>();
222 for (const run of g.atom(id).inserts) {
223 if (!gaps.has(run.parent)) continue;
224 for (const l of run.lines) if (!PLAIN_LINE.test(l)) out.add(l.trim());
225 }
226 return out;
227 };
228 const ours = linesAt(a);
229 for (const l of linesAt(b)) if (ours.has(l)) return false;
230 return true;
233/** Describe a pair for the agent: its side in `yoursView`, theirs in `theirsView`, with who published theirs. */
234export function describePair(
235 g: Graph,
236 origin: (atom: AtomId, spaceName: string) => Origin,
237 pair: Pair,
238 yoursView: ReadView,
239 theirsView: ReadView,
240 spaceName: string,
241): Collision {
242 const file = fileOfKey(pair.keys[0]!.key, yoursView);
243 const fileKeys = pair.keys.filter((k) => fileOfKey(k.key, yoursView) === file).map((k) => k.key);
244 const attrsOnly = fileKeys.map((k) => parseKey(k)).filter((k) => k.kind === "attr");
245 if (attrsOnly.length === fileKeys.length) {
246 // Both set the same attribute of the file: show each side's value.
247 const name = attrsOnly[0]!.attr!;
248 const valueIn = (view: ReadView, atom: AtomId): string => {
249 const set = (g.atom(atom).attrs ?? []).find((a) => a.file === file && a.name === name);
250 return set?.value ?? (name === "exec" ? "" : String(view.attrs(file)[name] ?? ""));
251 };
252 return {
253 kind: "attribute",
254 name,
255 file,
256 yours: { lines: [1, 0], text: valueIn(yoursView, pair.yours) },
257 theirs: { lines: [1, 0], text: valueIn(theirsView, pair.theirs), ...origin(pair.theirs, spaceName) },
258 };
259 }
260 return {
261 kind: "lines",
262 file,
263 yours: describeSide(yoursView, pair.yours, file, fileKeys),
264 theirs: { ...describeSide(theirsView, pair.theirs, file, fileKeys), ...origin(pair.theirs, spaceName) },
265 };
268export function fileOfKey(key: string, view: ReadView): string {
269 const { kind, node } = parseKey(key);
270 if (kind === "attr") return node;
271 return node.startsWith("^") ? node.slice(1) : view.fileOf(node);
274/**
275 * The files some atoms change: the graph's files of each, and, in views
276 * with moves (#28), wherever the lines they touch are in those views.
277 */
278export function touchedFiles(g: Graph, ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string> {
279 const out = new Set<string>();
280 const moved = views.filter((v) => v.hasMoves());
281 for (const id of ids) {
282 for (const file of g.filesOf(id)) out.add(file);
283 if (moved.length === 0) continue;
284 const atom = g.atom(id);
285 const lines: string[] = [];
286 for (const run of atom.inserts) if (!run.parent.startsWith("^")) lines.push(run.parent);
287 for (const m of atom.moves ?? []) {
288 lines.push(m.line);
289 if (!m.parent.startsWith("^")) lines.push(m.parent);
290 }
291 for (const v of moved) {
292 for (const line of lines) out.add(v.fileOf(line));
293 // Deleted lines by number where the view can (abso Capacity): a draft deleting a big file has thousands, and
294 // making each one's id only to look its number up again was most of collisions on website.
295 const byNumber = (v as { fileOfNumber?: (n: number) => string }).fileOfNumber;
296 if (byNumber) for (const n of g.deletedNumbers(id)) out.add(byNumber.call(v, n));
297 else for (const line of g.deletedLines(id)) out.add(v.fileOf(line));
298 }
299 }
300 return out;
303/**
304 * The files a view over `below` plus `mine` can lay out differently from `below` (abso Capacity, View.shareFiles), or
305 * 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
306 * `mine` depends on that `below` lacks; each of those can change a file, so all of them count. Counting `mine` alone
307 * missed the files of work the draft depends on (Testing's typescript-rs diff for cloud-ts-01, core 235).
308 */
309export function touchedBeyond(
310 g: Graph,
311 below: ReadonlySet<AtomId>,
312 mine: Iterable<AtomId>,
313 views: readonly ReadView[],
314 placedDifferently?: () => ReadonlySet<string> | undefined,
315): Set<string> | undefined {
316 const beyond = new Set<AtomId>();
317 const stack = [...mine];
318 while (stack.length) {
319 const id = stack.pop()!;
320 if (beyond.has(id) || below.has(id)) continue;
321 beyond.add(id);
322 for (const dep of g.atom(id).deps) if (!beyond.has(dep) && !below.has(dep)) stack.push(dep);
323 }
324 const files = touchedFiles(g, beyond, views);
325 // Moves change more than the files their atoms name only where a moved line lands differently (View.placedDifferently,
326 // abso Capacity); without that comparison, a draft that moves lines shares nothing.
327 if ([...beyond].some((id) => (g.atom(id).moves?.length ?? 0) > 0)) {
328 const placed = placedDifferently?.();
329 if (!placed) return undefined;
330 for (const file of placed) files.add(file);
331 }
332 return files;
335/** The atom's visible lines in a file of a view, or where it acted when none are left. */
336export function describeSide(view: ReadView, atom: AtomId, file: string, keys: readonly string[]): CollisionSide {
337 const visible = view.lines(file);
338 let first = -1;
339 let lastLine = -1;
340 visible.forEach((line, i) => {
341 if (line.atom === atom) {
342 if (first < 0) first = i;
343 lastLine = i;
344 }
345 });
346 if (first >= 0) {
347 return { lines: [first + 1, lastLine + 1], text: joinLines(visible.slice(first, lastLine + 1).map((l) => l.text)) };
348 }
349 // No lines of its own here (a deletion): point at where the first key sits.
350 let at = 1;
351 const { node } = parseKey(keys[0]!);
352 if (!node.startsWith("^")) {
353 const sequence = view.sequence(file);
354 const index = view.sequenceIndex(file, node);
355 at = 1 + sequence.slice(0, Math.max(index, 0)).filter((l) => l.visible).length;
356 }
357 return { lines: [at, at - 1], text: "" };
360/** What origin, open pairs and duplicate-name collisions need from a project. */
361export interface CollisionHost {
362 readonly graph: Graph;
363 readonly spaces: ReadonlyMap<string, Space>;
364 version(): number;
365 spaceOf(agent: AgentState): Space;
366 agentSet(agent: AgentState): ReadonlySet<AtomId>;
367 draft(agent: AgentState): AtomId[];
368 agentView(agent: AgentState): ReadView;
369 at(space: Space, version: number): ReadonlySet<AtomId>;
370 shared(): Space;
373/** Who published an atom, looking in the given space first and then in shared. */
374export function originOf(host: CollisionHost, atom: AtomId, spaceName: string): Origin {
375 for (const name of [spaceName, SHARED]) {
376 const space = host.spaces.get(name)!;
377 const version = space.publishedIn.get(atom);
378 if (version === undefined) continue;
379 const p = space.versions[version]!;
380 return { agent: p.agent, message: p.message, version, ...(name !== SHARED ? { draft: name } : {}) };
381 }
382 return { agent: host.graph.atom(atom).author, message: "", version: host.version() };
385/**
386 * Draft changes that build on atoms a set doesn't have (a drop took them
387 * out): the files they touch. Those changes can't move onto that set.
388 */
389export function strandedFiles(g: Graph, draft: readonly AtomId[], set: ReadonlySet<AtomId>): string[] {
390 const mine = new Set(draft);
391 const files = new Set<string>();
392 for (const id of draft) {
393 if (g.atom(id).deps.some((d) => !set.has(d) && !mine.has(d))) for (const f of g.filesOf(id)) files.add(f);
394 }
395 return [...files].toSorted();
398/**
399 * Names the agent's draft defines at the top level of a file where other
400 * work defines them too, so they are defined twice there (#25, Fuzzer).
401 */
402export function duplicateCollisions(host: CollisionHost, agent: AgentState): Collision[] {
403 const draft = host.draft(agent);
404 if (draft.length === 0) return [];
405 const mine = new Set(draft);
406 const view = host.agentView(agent);
407 const space = host.spaceOf(agent);
408 const out: Collision[] = [];
409 for (const file of [...touchedFiles(host.graph, draft, [view])].toSorted()) {
410 if (!view.hasFile(file)) continue;
411 for (const [name, defs] of definedTwice(view, file)) {
412 const yours = defs.find((d) => d.lines.some((l) => mine.has(host.graph.line(l)!.atom)));
413 const theirs = defs.find((d) => d.lines.every((l) => !mine.has(host.graph.line(l)!.atom)));
414 if (!yours || !theirs) continue;
415 const by = host.graph.line(theirs.lines[0]!)!.atom;
416 out.push({
417 kind: "duplicate",
418 name,
419 file,
420 yours: { lines: [yours.start + 1, yours.end], text: `${yours.text}\n` },
421 theirs: { lines: [theirs.start + 1, theirs.end], text: `${theirs.text}\n`, ...originOf(host, by, space.name) },
422 });
423 }
424 }
425 return out;
428/**
429 * Collisions the agent has synced into and not settled: its draft against
430 * its space at its base. In a named draft, also the draft's own changes
431 * against shared work the draft was moved onto.
432 */
433export function openPairs(host: CollisionHost, agent: AgentState): Pair[] {
434 const space = host.spaceOf(agent);
435 const set = host.agentSet(agent);
436 const mine = new StableOverlaySet(agent.mine);
437 const out: Pair[] = [];
438 const draft = host.draft(agent);
439 if (draft.length > 0) {
440 const seen = differenceSet(host.at(space, agent.base), mine);
441 out.push(...pairsIn(host.graph, draft, seen, set));
442 }
443 if (space.name !== SHARED) {
444 const shared = host.shared();
445 const pending = [...space.own].filter((id) => set.has(id) && !shared.own.has(id));
446 const sharedSeen = new Set([...set].filter((id) => shared.own.has(id)));
447 out.push(...pairsIn(host.graph, pending, sharedSeen, set));
448 }
449 return out;