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?draft=login-timeout&format=json
273 linesFirst import 100%0 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 parseKey,
13 type View,
14} from "../../src/engine/index.ts";
15import { definedTwice } from "./definitions.ts";
16import type { AgentState, Collision, CollisionSide } from "./project-types.ts";
17import { SHARED, type Space } from "./spaces.ts";
19export interface Pair {
20 readonly yours: AtomId;
21 readonly theirs: AtomId;
22 readonly keys: readonly ConflictKey[];
25/** Where a published atom came from. */
26export interface Origin {
27 readonly agent: string;
28 readonly message: string;
29 readonly version: number;
30 readonly draft?: string;
33/** A line too plain to identify on its own: blank, or only brackets and punctuation. */
34export const PLAIN_LINE = /^[\s{}()[\];,.]*$/;
36/**
37 * Pairs of a draft change and an atom of `against` that collide by the
38 * engine's rule, and that no atom of `settled` resolves.
39 */
40export function pairsIn(
41 g: Graph,
42 draft: readonly AtomId[],
43 against: ReadonlySet<AtomId>,
44 settled: ReadonlySet<AtomId>,
45): Pair[] {
46 const out: Pair[] = [];
47 for (const yours of draft) {
48 const atom = g.atom(yours);
49 const candidates = new Set<AtomId>();
50 for (const key of atom.writes) {
51 for (const list of [g.writersOf(key), g.readersOf(key), g.holdersOf(key)]) {
52 for (const id of list) if (against.has(id)) candidates.add(id);
53 }
54 }
55 for (const key of claimsOf(atom)) for (const id of g.writersOf(key)) if (against.has(id)) candidates.add(id);
56 for (const theirs of [...candidates].sort((p, q) => g.atom(p).seq - g.atom(q).seq)) {
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 const fromHi = new Set(g.resolversOf(hi));
61 if (g.resolversOf(lo).some((r) => fromHi.has(r) && settled.has(r))) continue;
62 out.push({ yours, theirs, keys });
63 }
64 }
65 return out;
68/**
69 * Two pure insertions at the same point, and nothing else between them
70 * (#37, the game trial): both only write the gap after one line. Neither
71 * loses anything (both are kept, one after the other), so that alone is
72 * not a collision. It still is when they share a line with real content (the
73 * same import added twice would be doubled), or when the gap is the top of
74 * a file (two agents creating the same file).
75 */
76function sideBySide(g: Graph, a: AtomId, b: AtomId, keys: readonly ConflictKey[]): boolean {
77 const gaps = new Set<string>();
78 for (const k of keys) {
79 if (k.relation !== "write" || !k.key.startsWith("G:") || k.key.startsWith("G:^")) return false;
80 gaps.add(k.key.slice(2));
81 }
82 const linesAt = (id: AtomId): Set<string> => {
83 const out = new Set<string>();
84 for (const run of g.atom(id).inserts) {
85 if (!gaps.has(run.parent)) continue;
86 for (const l of run.lines) if (!PLAIN_LINE.test(l)) out.add(l.trim());
87 }
88 return out;
89 };
90 const ours = linesAt(a);
91 for (const l of linesAt(b)) if (ours.has(l)) return false;
92 return true;
95/** Describe a pair for the agent: its side in `yoursView`, theirs in `theirsView`, with who published theirs. */
96export function describePair(
97 g: Graph,
98 origin: (atom: AtomId, spaceName: string) => Origin,
99 pair: Pair,
100 yoursView: View,
101 theirsView: View,
102 spaceName: string,
103): Collision {
104 const file = fileOfKey(pair.keys[0]!.key, yoursView);
105 const fileKeys = pair.keys.filter((k) => fileOfKey(k.key, yoursView) === file).map((k) => k.key);
106 const attrsOnly = fileKeys.map((k) => parseKey(k)).filter((k) => k.kind === "attr");
107 if (attrsOnly.length === fileKeys.length) {
108 // Both set the same attribute of the file: show each side's value.
109 const name = attrsOnly[0]!.attr!;
110 const valueIn = (view: View, atom: AtomId): string => {
111 const set = (g.atom(atom).attrs ?? []).find((a) => a.file === file && a.name === name);
112 return set?.value ?? (name === "exec" ? "" : String(view.attrs(file)[name] ?? ""));
113 };
114 return {
115 kind: "attribute",
116 name,
117 file,
118 yours: { lines: [1, 0], text: valueIn(yoursView, pair.yours) },
119 theirs: { lines: [1, 0], text: valueIn(theirsView, pair.theirs), ...origin(pair.theirs, spaceName) },
120 };
121 }
122 return {
123 kind: "lines",
124 file,
125 yours: describeSide(yoursView, pair.yours, file, fileKeys),
126 theirs: { ...describeSide(theirsView, pair.theirs, file, fileKeys), ...origin(pair.theirs, spaceName) },
127 };
130export function fileOfKey(key: string, view: View): string {
131 const { kind, node } = parseKey(key);
132 if (kind === "attr") return node;
133 return node.startsWith("^") ? node.slice(1) : view.fileOf(node);
136/**
137 * The files some atoms change: the graph's files of each, and, in views
138 * with moves (#28), wherever the lines they touch are in those views.
139 */
140export function touchedFiles(g: Graph, ids: Iterable<AtomId>, views: readonly View[]): Set<string> {
141 const out = new Set<string>();
142 const moved = views.filter((v) => v.hasMoves());
143 for (const id of ids) {
144 for (const file of g.filesOf(id)) out.add(file);
145 if (moved.length === 0) continue;
146 const atom = g.atom(id);
147 const lines: string[] = [...g.deletedLines(id)];
148 for (const run of atom.inserts) if (!run.parent.startsWith("^")) lines.push(run.parent);
149 for (const m of atom.moves ?? []) {
150 lines.push(m.line);
151 if (!m.parent.startsWith("^")) lines.push(m.parent);
152 }
153 for (const v of moved) for (const line of lines) out.add(v.fileOf(line));
154 }
155 return out;
158/** The atom's visible lines in a file of a view, or where it acted when none are left. */
159export function describeSide(view: View, atom: AtomId, file: string, keys: readonly string[]): CollisionSide {
160 const visible = view.lines(file);
161 let first = -1;
162 let lastLine = -1;
163 visible.forEach((line, i) => {
164 if (line.atom === atom) {
165 if (first < 0) first = i;
166 lastLine = i;
167 }
168 });
169 if (first >= 0) {
170 return { lines: [first + 1, lastLine + 1], text: joinLines(visible.slice(first, lastLine + 1).map((l) => l.text)) };
171 }
172 // No lines of its own here (a deletion): point at where the first key sits.
173 let at = 1;
174 const { node } = parseKey(keys[0]!);
175 if (!node.startsWith("^")) {
176 const sequence = view.sequence(file);
177 const index = view.sequenceIndex(file, node);
178 at = 1 + sequence.slice(0, Math.max(index, 0)).filter((l) => l.visible).length;
179 }
180 return { lines: [at, at - 1], text: "" };
183/** What origin, open pairs and duplicate-name collisions need from a project. */
184export interface CollisionHost {
185 readonly graph: Graph;
186 readonly spaces: ReadonlyMap<string, Space>;
187 version(): number;
188 spaceOf(agent: AgentState): Space;
189 agentSet(agent: AgentState): Set<AtomId>;
190 draft(agent: AgentState): AtomId[];
191 agentView(agent: AgentState): View;
192 at(space: Space, version: number): ReadonlySet<AtomId>;
193 shared(): Space;
196/** Who published an atom, looking in the given space first and then in shared. */
197export function originOf(host: CollisionHost, atom: AtomId, spaceName: string): Origin {
198 for (const name of [spaceName, SHARED]) {
199 const space = host.spaces.get(name)!;
200 const version = space.publishedIn.get(atom);
201 if (version === undefined) continue;
202 const p = space.versions[version]!;
203 return { agent: p.agent, message: p.message, version, ...(name !== SHARED ? { draft: name } : {}) };
204 }
205 return { agent: host.graph.atom(atom).author, message: "", version: host.version() };
208/**
209 * Draft changes that build on atoms a set doesn't have (a drop took them
210 * out): the files they touch. Those changes can't move onto that set.
211 */
212export function strandedFiles(g: Graph, draft: readonly AtomId[], set: ReadonlySet<AtomId>): string[] {
213 const mine = new Set(draft);
214 const files = new Set<string>();
215 for (const id of draft) {
216 if (g.atom(id).deps.some((d) => !set.has(d) && !mine.has(d))) for (const f of g.filesOf(id)) files.add(f);
217 }
218 return [...files].toSorted();
221/**
222 * Names the agent's draft defines at the top level of a file where other
223 * work defines them too, so they are defined twice there (#25, Fuzzer).
224 */
225export function duplicateCollisions(host: CollisionHost, agent: AgentState): Collision[] {
226 const draft = host.draft(agent);
227 if (draft.length === 0) return [];
228 const mine = new Set(draft);
229 const view = host.agentView(agent);
230 const space = host.spaceOf(agent);
231 const out: Collision[] = [];
232 for (const file of [...touchedFiles(host.graph, draft, [view])].toSorted()) {
233 if (!view.hasFile(file)) continue;
234 for (const [name, defs] of definedTwice(view, file)) {
235 const yours = defs.find((d) => d.lines.some((l) => mine.has(host.graph.line(l)!.atom)));
236 const theirs = defs.find((d) => d.lines.every((l) => !mine.has(host.graph.line(l)!.atom)));
237 if (!yours || !theirs) continue;
238 const by = host.graph.line(theirs.lines[0]!)!.atom;
239 out.push({
240 kind: "duplicate",
241 name,
242 file,
243 yours: { lines: [yours.start + 1, yours.end], text: yours.text + "\n" },
244 theirs: { lines: [theirs.start + 1, theirs.end], text: theirs.text + "\n", ...originOf(host, by, space.name) },
245 });
246 }
247 }
248 return out;
251/**
252 * Collisions the agent has synced into and not settled: its draft against
253 * its space at its base. In a named draft, also the draft's own changes
254 * against shared work the draft was moved onto.
255 */
256export function openPairs(host: CollisionHost, agent: AgentState): Pair[] {
257 const space = host.spaceOf(agent);
258 const set = host.agentSet(agent);
259 const mine = new Set(agent.mine);
260 const out: Pair[] = [];
261 const draft = host.draft(agent);
262 if (draft.length > 0) {
263 const seen = new Set([...host.at(space, agent.base)].filter((id) => !mine.has(id)));
264 out.push(...pairsIn(host.graph, draft, seen, set));
265 }
266 if (space.name !== SHARED) {
267 const shared = host.shared();
268 const pending = [...space.own].filter((id) => set.has(id) && !shared.own.has(id));
269 const sharedSeen = new Set([...set].filter((id) => shared.own.has(id)));
270 out.push(...pairsIn(host.graph, pending, sharedSeen, set));
271 }
272 return out;