- 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=190&format=json
341 linesFirst import 74% · codex-capacity-chair 26% · pinch 1%Last change codex-capacity-chair in version 162, 6 versions changed it
You're reading version 190. The newest is 318, and 5 versions since then changed this file.
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.
5import {
6 type AtomId,
7 type ConflictKey,
8 claimsOf,
9 conflictKeys,
10 type Graph,
11 joinLines,
12 parseKey,
13 type ReadView,
14} from "../../src/engine/index.ts";
15import { differenceSet, StableOverlaySet } from "../../src/engine/state-source.ts";
16import { definedTwice } from "./definitions.ts";
17import type { AgentState, Collision, CollisionSide } from "./project-types.ts";
18import { SHARED, type Space } from "./spaces.ts";
20export interface Pair {
21 readonly yours: AtomId;
22 readonly theirs: AtomId;
23 readonly keys: readonly ConflictKey[];
24}
26/** Where a published atom came from. */
27export interface Origin {
28 readonly agent: string;
29 readonly message: string;
30 readonly version: number;
31 readonly draft?: string;
32}
34/** A line too plain to identify on its own: blank, or only brackets and punctuation. */
35export const PLAIN_LINE = /^[\s{}()[\];,.]*$/;
37/**
38 * Pairs of a draft change and an atom of `against` that collide by the
39 * engine's rule, and that no atom of `settled` resolves.
40 */
41export function pairsIn(
42 g: Graph,
43 draft: readonly AtomId[],
44 against: ReadonlySet<AtomId>,
45 settled: ReadonlySet<AtomId>,
46): Pair[] {
47 const out: Pair[] = [];
48 for (const yours of draft) {
49 const atom = g.atom(yours);
50 const streams: IterableIterator<AtomId>[] = [];
51 for (const key of atom.writes) {
52 streams.push(g.eachWriterOf(key), g.eachReaderOf(key), g.eachHolderOf(key));
53 }
54 for (const key of claimsOf(atom)) streams.push(g.eachWriterOf(key));
55 for (const theirs of orderedClaimants(g, streams)) {
56 if (!against.has(theirs)) continue;
57 const [lo, hi] = g.atom(yours).seq < g.atom(theirs).seq ? [yours, theirs] : [theirs, yours];
58 const keys = conflictKeys(g.atom(lo), g.atom(hi), g.dependsOn(hi, lo));
59 if (keys.length === 0 || sideBySide(g, lo, hi, keys)) continue;
60 if (hasCommonResolver(g, lo, hi, settled)) continue;
61 out.push({ yours, theirs, keys });
62 }
63 }
64 return out;
65}
67/** Claim indexes append in canonical seq order. Merge one cursor per current
68 * atom key, retaining no candidate set proportional to historical claims. */
69function* orderedClaimants(g: Graph, streams: IterableIterator<AtomId>[]): IterableIterator<AtomId> {
70 try {
71 type Head = { id: AtomId; seq: number; stream: number };
72 const heap: Head[] = [];
73 const less = (a: Head, b: Head) => a.seq < b.seq || (a.seq === b.seq && a.stream < b.stream);
74 const push = (head: Head) => {
75 let at = heap.length;
76 heap.push(head);
77 while (at > 0) {
78 const parent = (at - 1) >>> 1;
79 if (!less(head, heap[parent]!)) break;
80 heap[at] = heap[parent]!;
81 at = parent;
82 }
83 heap[at] = head;
84 };
85 const advance = (stream: number) => {
86 const next = streams[stream]!.next();
87 if (!next.done) push({ id: next.value, seq: g.atom(next.value).seq, stream });
88 };
89 for (let stream = 0; stream < streams.length; stream++) advance(stream);
90 let previous = -1;
91 while (heap.length) {
92 const head = heap[0]!;
93 const tail = heap.pop()!;
94 if (heap.length) {
95 let at = 0;
96 while (at * 2 + 1 < heap.length) {
97 let child = at * 2 + 1;
98 if (child + 1 < heap.length && less(heap[child + 1]!, heap[child]!)) child++;
99 if (!less(heap[child]!, tail)) break;
100 heap[at] = heap[child]!;
101 at = child;
102 }
103 heap[at] = tail;
104 }
105 advance(head.stream);
106 if (head.seq === previous) continue;
107 previous = head.seq;
108 yield head.id;
109 }
110 } finally {
111 for (const stream of streams) stream.return?.();
112 }
113}
115/** Resolver indexes share the same append order, so intersection needs two cursors. */
116function hasCommonResolver(g: Graph, lo: AtomId, hi: AtomId, settled: ReadonlySet<AtomId>): boolean {
117 const left = g.eachResolverOf(lo);
118 const right = g.eachResolverOf(hi);
119 try {
120 let a = left.next();
121 let b = right.next();
122 while (!a.done && !b.done) {
123 const x = g.atom(a.value).seq;
124 const y = g.atom(b.value).seq;
125 if (x === y && settled.has(a.value)) return true;
126 if (x <= y) a = left.next();
127 if (y <= x) b = right.next();
128 }
129 return false;
130 } finally {
131 left.return?.();
132 right.return?.();
133 }
134}
136/**
137 * Two pure insertions at the same point, and nothing else between them
138 * (#37, the game trial): both only write the gap after one line. Neither
139 * loses anything (both are kept, one after the other), so that alone is
140 * not a collision. It still is when they share a line with real content (the
141 * same import added twice would be doubled), or when the gap is the top of
142 * a file (two agents creating the same file).
143 */
144function sideBySide(g: Graph, a: AtomId, b: AtomId, keys: readonly ConflictKey[]): boolean {
145 const gaps = new Set<string>();
146 for (const k of keys) {
147 if (k.relation !== "write" || !k.key.startsWith("G:") || k.key.startsWith("G:^")) return false;
148 gaps.add(k.key.slice(2));
149 }
150 const linesAt = (id: AtomId): Set<string> => {
151 const out = new Set<string>();
152 for (const run of g.atom(id).inserts) {
153 if (!gaps.has(run.parent)) continue;
154 for (const l of run.lines) if (!PLAIN_LINE.test(l)) out.add(l.trim());
155 }
156 return out;
157 };
158 const ours = linesAt(a);
159 for (const l of linesAt(b)) if (ours.has(l)) return false;
160 return true;
161}
163/** Describe a pair for the agent: its side in `yoursView`, theirs in `theirsView`, with who published theirs. */
164export function describePair(
165 g: Graph,
166 origin: (atom: AtomId, spaceName: string) => Origin,
167 pair: Pair,
168 yoursView: ReadView,
169 theirsView: ReadView,
170 spaceName: string,
171): Collision {
172 const file = fileOfKey(pair.keys[0]!.key, yoursView);
173 const fileKeys = pair.keys.filter((k) => fileOfKey(k.key, yoursView) === file).map((k) => k.key);
174 const attrsOnly = fileKeys.map((k) => parseKey(k)).filter((k) => k.kind === "attr");
175 if (attrsOnly.length === fileKeys.length) {
176 // Both set the same attribute of the file: show each side's value.
177 const name = attrsOnly[0]!.attr!;
178 const valueIn = (view: ReadView, atom: AtomId): string => {
179 const set = (g.atom(atom).attrs ?? []).find((a) => a.file === file && a.name === name);
180 return set?.value ?? (name === "exec" ? "" : String(view.attrs(file)[name] ?? ""));
181 };
182 return {
183 kind: "attribute",
184 name,
185 file,
186 yours: { lines: [1, 0], text: valueIn(yoursView, pair.yours) },
187 theirs: { lines: [1, 0], text: valueIn(theirsView, pair.theirs), ...origin(pair.theirs, spaceName) },
188 };
189 }
190 return {
191 kind: "lines",
192 file,
193 yours: describeSide(yoursView, pair.yours, file, fileKeys),
194 theirs: { ...describeSide(theirsView, pair.theirs, file, fileKeys), ...origin(pair.theirs, spaceName) },
195 };
196}
198export function fileOfKey(key: string, view: ReadView): string {
199 const { kind, node } = parseKey(key);
200 if (kind === "attr") return node;
201 return node.startsWith("^") ? node.slice(1) : view.fileOf(node);
202}
204/**
205 * The files some atoms change: the graph's files of each, and, in views
206 * with moves (#28), wherever the lines they touch are in those views.
207 */
208export function touchedFiles(g: Graph, ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string> {
209 const out = new Set<string>();
210 const moved = views.filter((v) => v.hasMoves());
211 for (const id of ids) {
212 for (const file of g.filesOf(id)) out.add(file);
213 if (moved.length === 0) continue;
214 const atom = g.atom(id);
215 const lines: string[] = [...g.deletedLines(id)];
216 for (const run of atom.inserts) if (!run.parent.startsWith("^")) lines.push(run.parent);
217 for (const m of atom.moves ?? []) {
218 lines.push(m.line);
219 if (!m.parent.startsWith("^")) lines.push(m.parent);
220 }
221 for (const v of moved) for (const line of lines) out.add(v.fileOf(line));
222 }
223 return out;
224}
226/** The atom's visible lines in a file of a view, or where it acted when none are left. */
227export function describeSide(view: ReadView, atom: AtomId, file: string, keys: readonly string[]): CollisionSide {
228 const visible = view.lines(file);
229 let first = -1;
230 let lastLine = -1;
231 visible.forEach((line, i) => {
232 if (line.atom === atom) {
233 if (first < 0) first = i;
234 lastLine = i;
235 }
236 });
237 if (first >= 0) {
238 return { lines: [first + 1, lastLine + 1], text: joinLines(visible.slice(first, lastLine + 1).map((l) => l.text)) };
239 }
240 // No lines of its own here (a deletion): point at where the first key sits.
241 let at = 1;
242 const { node } = parseKey(keys[0]!);
243 if (!node.startsWith("^")) {
244 const sequence = view.sequence(file);
245 const index = view.sequenceIndex(file, node);
246 at = 1 + sequence.slice(0, Math.max(index, 0)).filter((l) => l.visible).length;
247 }
248 return { lines: [at, at - 1], text: "" };
249}
251/** What origin, open pairs and duplicate-name collisions need from a project. */
252export interface CollisionHost {
253 readonly graph: Graph;
254 readonly spaces: ReadonlyMap<string, Space>;
255 version(): number;
256 spaceOf(agent: AgentState): Space;
257 agentSet(agent: AgentState): ReadonlySet<AtomId>;
258 draft(agent: AgentState): AtomId[];
259 agentView(agent: AgentState): ReadView;
260 at(space: Space, version: number): ReadonlySet<AtomId>;
261 shared(): Space;
262}
264/** Who published an atom, looking in the given space first and then in shared. */
265export function originOf(host: CollisionHost, atom: AtomId, spaceName: string): Origin {
266 for (const name of [spaceName, SHARED]) {
267 const space = host.spaces.get(name)!;
268 const version = space.publishedIn.get(atom);
269 if (version === undefined) continue;
270 const p = space.versions[version]!;
271 return { agent: p.agent, message: p.message, version, ...(name !== SHARED ? { draft: name } : {}) };
272 }
273 return { agent: host.graph.atom(atom).author, message: "", version: host.version() };
274}
276/**
277 * Draft changes that build on atoms a set doesn't have (a drop took them
278 * out): the files they touch. Those changes can't move onto that set.
279 */
280export function strandedFiles(g: Graph, draft: readonly AtomId[], set: ReadonlySet<AtomId>): string[] {
281 const mine = new Set(draft);
282 const files = new Set<string>();
283 for (const id of draft) {
284 if (g.atom(id).deps.some((d) => !set.has(d) && !mine.has(d))) for (const f of g.filesOf(id)) files.add(f);
285 }
286 return [...files].toSorted();
287}
289/**
290 * Names the agent's draft defines at the top level of a file where other
291 * work defines them too, so they are defined twice there (#25, Fuzzer).
292 */
293export function duplicateCollisions(host: CollisionHost, agent: AgentState): Collision[] {
294 const draft = host.draft(agent);
295 if (draft.length === 0) return [];
296 const mine = new Set(draft);
297 const view = host.agentView(agent);
298 const space = host.spaceOf(agent);
299 const out: Collision[] = [];
300 for (const file of [...touchedFiles(host.graph, draft, [view])].toSorted()) {
301 if (!view.hasFile(file)) continue;
302 for (const [name, defs] of definedTwice(view, file)) {
303 const yours = defs.find((d) => d.lines.some((l) => mine.has(host.graph.line(l)!.atom)));
304 const theirs = defs.find((d) => d.lines.every((l) => !mine.has(host.graph.line(l)!.atom)));
305 if (!yours || !theirs) continue;
306 const by = host.graph.line(theirs.lines[0]!)!.atom;
307 out.push({
308 kind: "duplicate",
309 name,
310 file,
311 yours: { lines: [yours.start + 1, yours.end], text: `${yours.text}\n` },
312 theirs: { lines: [theirs.start + 1, theirs.end], text: `${theirs.text}\n`, ...originOf(host, by, space.name) },
313 });
314 }
315 }
316 return out;
317}
319/**
320 * Collisions the agent has synced into and not settled: its draft against
321 * its space at its base. In a named draft, also the draft's own changes
322 * against shared work the draft was moved onto.
323 */
324export function openPairs(host: CollisionHost, agent: AgentState): Pair[] {
325 const space = host.spaceOf(agent);
326 const set = host.agentSet(agent);
327 const mine = new StableOverlaySet(agent.mine);
328 const out: Pair[] = [];
329 const draft = host.draft(agent);
330 if (draft.length > 0) {
331 const seen = differenceSet(host.at(space, agent.base), mine);
332 out.push(...pairsIn(host.graph, draft, seen, set));
333 }
334 if (space.name !== SHARED) {
335 const shared = host.shared();
336 const pending = [...space.own].filter((id) => set.has(id) && !shared.own.has(id));
337 const sharedSeen = new Set([...set].filter((id) => shared.own.has(id)));
338 out.push(...pairsIn(host.graph, pending, sharedSeen, set));
339 }
340 return out;
341}