- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/src/engine/conflicts.ts?version=122&format=json
347 linesFirst import 95% · codex-capacity-chair 5%Last change codex-capacity-chair in version 122, 4 versions changed it
You're reading version 122. The newest is 318, and 2 versions since then changed this file.
1// Conflicts, reason warnings, and the check a draft atom gets before it is
2// accepted into a set.
4import type { Graph } from "./graph.ts";
5import { isStartNode, lineId, lineOfKey, parseKey, writerOf } from "./keys.ts";
6import type { Atom, AtomId, AtomSet, Key, LineId } from "./types.ts";
7import { View } from "./view.ts";
9/** How the non-writing side relates to a key the other side writes. */
10export type Relation = "write" | "read" | "hold";
12/** One overlapping key: `writer` writes it; `other` writes, reads or holds it. */
13export interface ConflictKey {
14 readonly key: Key;
15 readonly writer: AtomId;
16 readonly other: AtomId;
17 readonly relation: Relation;
18}
20export interface Side {
21 readonly atom: AtomId;
22 readonly author: string;
23 readonly message: string;
24}
26/**
27 * Two atoms whose claims overlap where at least one side writes: either they
28 * are independent, or the later one writes into a hold of the earlier one
29 * without naming it in needs or resolves. kind is 'semantic' when every
30 * overlap is an edit against a hold (reliesOn, wide, claim span), otherwise
31 * 'edit-edit'.
32 */
33export interface Conflict {
34 /** The two atoms, lower seq first. */
35 readonly atoms: readonly [AtomId, AtomId];
36 readonly kind: "edit-edit" | "semantic";
37 readonly keys: readonly ConflictKey[];
38 readonly sides: readonly [Side, Side];
39 /** Atoms in the set whose `resolves` names both sides. Empty means unresolved. */
40 readonly resolvedBy: readonly AtomId[];
41}
43interface KeySets {
44 readonly writes: ReadonlySet<Key>;
45 readonly reads: ReadonlySet<Key>;
46 readonly holds: ReadonlySet<Key>;
47}
49const keySetCache = new WeakMap<Atom, KeySets>();
51function keySets(atom: Atom): KeySets {
52 let sets = keySetCache.get(atom);
53 if (!sets) {
54 sets = { writes: new Set(atom.writes), reads: new Set(atom.reads), holds: new Set(atom.holds) };
55 keySetCache.set(atom, sets);
56 }
57 return sets;
58}
60function relationTo(sets: KeySets, key: Key): Relation | undefined {
61 if (sets.writes.has(key)) return "write";
62 if (sets.reads.has(key)) return "read";
63 if (sets.holds.has(key)) return "hold";
64 return undefined;
65}
67/** All keys of an atom it claims: reads ∪ holds ∪ writes. */
68export function claimsOf(atom: Atom): Key[] {
69 return [...new Set([...atom.writes, ...atom.reads, ...atom.holds])].sort();
70}
72/**
73 * The overlap between two atoms' claims that would make them conflict if they
74 * were independent: writes(a) ∩ claims(b) and writes(b) ∩ claims(a).
75 * Read-read and hold-hold overlap never count. A key both write is listed
76 * once, with `a` as the writer.
77 */
78export function keyOverlap(a: Atom, b: Atom): ConflictKey[] {
79 const ka = keySets(a);
80 const kb = keySets(b);
81 const out: ConflictKey[] = [];
82 for (const key of ka.writes) {
83 const relation = relationTo(kb, key);
84 if (relation) out.push({ key, writer: a.id, other: b.id, relation });
85 }
86 for (const key of kb.writes) {
87 if (ka.writes.has(key)) continue; // already listed as write-write
88 const relation = relationTo(ka, key);
89 if (relation) out.push({ key, writer: b.id, other: a.id, relation });
90 }
91 return out.sort((x, y) => (x.key < y.key ? -1 : x.key > y.key ? 1 : x.writer < y.writer ? -1 : 1));
92}
94/** Neither atom is in the other's dependency closure. */
95export function independent(graph: Graph, a: AtomId, b: AtomId): boolean {
96 return a !== b && !graph.dependsOn(a, b) && !graph.dependsOn(b, a);
97}
99/** Whether `atom` names `holder` in its needs or resolves: the one way to release a hold. */
100export function releases(atom: Atom, holder: AtomId): boolean {
101 return atom.needs.includes(holder) || atom.resolves.includes(holder);
102}
104/**
105 * The keys two atoms conflict over (empty when they don't). `a` has the lower
106 * seq, so `b` is never in `a`'s closure; `aBelowB` says whether `a` is in
107 * `b`'s. Independent atoms conflict over their keyOverlap. When `b` built on
108 * `a`, only the holds of `a` that `b` writes count, and only while `b` doesn't
109 * name `a` in needs or resolves: a hold is released on purpose, never by a
110 * dependency derived from neighbouring lines.
111 */
112export function conflictKeys(a: Atom, b: Atom, aBelowB: boolean): ConflictKey[] {
113 if (!aBelowB) return keyOverlap(a, b);
114 if (releases(b, a.id)) return [];
115 const held = keySets(a).holds;
116 return [...keySets(b).writes]
117 .filter((key) => held.has(key))
118 .sort()
119 .map((key) => ({ key, writer: b.id, other: a.id, relation: "hold" }));
120}
122function side(atom: Atom): Side {
123 return { atom: atom.id, author: atom.author, message: atom.message };
124}
126/** `a` has the lower seq. */
127function makeConflict(graph: Graph, set: AtomSet | undefined, a: Atom, b: Atom, keys: ConflictKey[]): Conflict {
128 const kind = keys.every((k) => k.relation === "hold") ? "semantic" : "edit-edit";
129 const resolvedBy: AtomId[] = [];
130 if (set) {
131 // Resolver indexes append in sequence order: intersect without copying either history.
132 const left = graph.eachResolverOf(a.id);
133 const right = graph.eachResolverOf(b.id);
134 let p = left.next();
135 let q = right.next();
136 while (!p.done && !q.done) {
137 const order = graph.atom(p.value).seq - graph.atom(q.value).seq;
138 if (order === 0 && set.has(p.value)) resolvedBy.push(p.value);
139 if (order <= 0) p = left.next();
140 if (order >= 0) q = right.next();
141 }
142 }
143 return { atoms: [a.id, b.id], kind, keys, sides: [side(a), side(b)], resolvedBy };
144}
146/** Atoms in the set that claim (write, read or hold) a key. */
147function* claimersIn(graph: Graph, set: AtomSet, key: Key): IterableIterator<AtomId> {
148 for (const list of [graph.eachWriterOf(key), graph.eachReaderOf(key), graph.eachHolderOf(key)]) {
149 for (const id of list) if (set.has(id)) yield id;
150 }
151}
153const bySeq =
154 (graph: Graph) =>
155 (p: AtomId, q: AtomId): number =>
156 graph.atom(p).seq - graph.atom(q).seq;
158/**
159 * Every conflict in a set, resolved ones included (see `resolvedBy`), ordered
160 * by the two atoms' seqs. A conflict between A and B is resolved when the set
161 * holds an atom whose `resolves` names both.
162 */
163export function conflicts(graph: Graph, set: AtomSet): Conflict[] {
164 const pairs = new Map<string, [AtomId, AtomId]>();
165 for (const id of set) {
166 for (const key of graph.atom(id).writes) {
167 for (const other of claimersIn(graph, set, key)) {
168 if (other === id) continue;
169 const [a, b] = graph.atom(id).seq < graph.atom(other).seq ? [id, other] : [other, id];
170 pairs.set(`${a} ${b}`, [a, b]);
171 }
172 }
173 }
174 const out: Conflict[] = [];
175 for (const [a, b] of pairs.values()) {
176 const x = graph.atom(a);
177 const y = graph.atom(b);
178 const keys = conflictKeys(x, y, graph.dependsOn(b, a));
179 if (keys.length > 0) out.push(makeConflict(graph, set, x, y, keys));
180 }
181 return out.sort((p, q) => bySeq(graph)(p.atoms[0], q.atoms[0]) || bySeq(graph)(p.atoms[1], q.atoms[1]));
182}
184/** Conflicts in the set that no atom in the set resolves. */
185export function unresolvedConflicts(graph: Graph, set: AtomSet): Conflict[] {
186 return conflicts(graph, set).filter((c) => c.resolvedBy.length === 0);
187}
189// Reason warnings ----------------------------------------------------------------
191export interface ReasonWarning {
192 /** The atom whose lines the new atom changed. */
193 readonly atom: AtomId;
194 /** The atom it was changed together with. */
195 readonly partner: AtomId;
196 readonly text: string;
197 readonly message: string;
198}
200/** Whether a line has the next line of its own run hanging off it (an insert after it lands inside the run). */
201function insideRun(graph: Graph, line: LineId): boolean {
202 const info = graph.line(line);
203 return info !== undefined && graph.line(lineId(info.atom, info.k + 1))?.parent === line;
204}
206/** The nearest visible lines above and below a line in the view's sequence of its file. */
207function visibleNeighbours(view: View, graph: Graph, line: LineId): LineId[] {
208 const info = graph.line(line);
209 if (!info) return [];
210 const sequence = view.sequence(info.file);
211 const at = view.sequenceIndex(info.file, line);
212 if (at < 0) return [];
213 const out: LineId[] = [];
214 for (let i = at - 1; i >= 0; i--) {
215 if (sequence[i]!.visible) {
216 out.push(sequence[i]!.id);
217 break;
218 }
219 }
220 for (let i = at + 1; i < sequence.length; i++) {
221 if (sequence[i]!.visible) {
222 out.push(sequence[i]!.id);
223 break;
224 }
225 }
226 return out;
227}
229/**
230 * When atom N changes A's lines (deletes one, or inserts between two lines of
231 * one run of A), A has a `together` reason with B (either direction), B is in
232 * the set, and N doesn't touch B's side, warn. N touches B's side when it
233 * writes, reads or holds a line B wrote, or a line right next to one B
234 * deleted (a deletion leaves no lines of its own). No warning when N itself
235 * carries a reason to B (it has said why B is fine).
236 */
237export function reasonWarnings(graph: Graph, set: AtomSet, atom: Atom): ReasonWarning[] {
238 const claimed = new Set<LineId>();
239 for (const key of claimsOf(atom)) {
240 const line = lineOfKey(key);
241 if (line !== undefined) claimed.add(line);
242 }
243 const touched = new Set<AtomId>([...claimed].map(writerOf));
244 const changed = new Set<AtomId>();
245 for (const key of atom.writes) {
246 const { kind, node } = parseKey(key);
247 if (kind === "line") changed.add(writerOf(node));
248 else if (kind === "gap" && !isStartNode(node) && insideRun(graph, node)) changed.add(writerOf(node));
249 }
250 let view: View | undefined;
251 const touchesSide = (b: AtomId): boolean => {
252 if (touched.has(b)) return true;
253 const deleted = graph.atom(b).deletes;
254 if (deleted.length === 0) return false;
255 view ??= new View(graph, set);
256 const v = view;
257 return deleted.some((line) => visibleNeighbours(v, graph, line).some((n) => claimed.has(n)));
258 };
259 const acknowledged = new Set(atom.reasons.map((r) => r.to));
260 const out: ReasonWarning[] = [];
261 const seen = new Set<string>();
262 for (const a of [...changed].sort(bySeq(graph))) {
263 if (a === atom.id) continue;
264 for (const link of graph.togetherLinks(a)) {
265 const b = link.other;
266 if (b === atom.id || !set.has(b) || acknowledged.has(b)) continue;
267 const tag = `${a} ${b}`;
268 if (seen.has(tag)) continue;
269 seen.add(tag);
270 if (touchesSide(b)) continue;
271 out.push({
272 atom: a,
273 partner: b,
274 text: link.text,
275 message: `${a} was changed together with ${b} because: ${link.text}; you changed ${a}'s lines but not ${b}'s.`,
276 });
277 }
278 }
279 return out;
280}
282// Draft check ----------------------------------------------------------------------
284/** Whose lines a draft touches, and how. */
285export interface Touch {
286 readonly atom: AtomId;
287 readonly author: string;
288 readonly message: string;
289 readonly writes: readonly LineId[];
290 readonly reads: readonly LineId[];
291 readonly holds: readonly LineId[];
292}
294export interface DraftReport {
295 readonly touches: readonly Touch[];
296 /** Conflicts the draft would have with atoms in the set (none are resolved yet). */
297 readonly conflicts: readonly Conflict[];
298 readonly warnings: readonly ReasonWarning[];
299}
301/**
302 * What accepting `draft` into `set` would mean, before it is accepted: whose
303 * lines it touches (with author and message), the conflicts it would bring
304 * (exactly those `conflicts` reports once it is in the set), and reason
305 * warnings. The draft must not be in the graph yet; its deps must be.
306 */
307export function checkDraft(graph: Graph, set: AtomSet, draft: Atom): DraftReport {
308 const below = graph.closureOf(draft.deps);
309 const candidates = new Set<AtomId>();
310 for (const key of draft.writes) for (const id of claimersIn(graph, set, key)) candidates.add(id);
311 for (const key of claimsOf(draft)) for (const id of graph.eachWriterOf(key)) if (set.has(id)) candidates.add(id);
312 const found: Conflict[] = [];
313 for (const id of [...candidates].sort(bySeq(graph))) {
314 const other = graph.atom(id);
315 const keys = conflictKeys(other, draft, below.has(id));
316 if (keys.length > 0) found.push(makeConflict(graph, undefined, other, draft, keys));
317 }
318 return { touches: touchesOf(graph, draft), conflicts: found, warnings: reasonWarnings(graph, set, draft) };
319}
321/** Group the lines an atom writes, reads and holds by the atom that wrote them. */
322export function touchesOf(graph: Graph, atom: Atom): Touch[] {
323 const by = new Map<AtomId, { writes: LineId[]; reads: LineId[]; holds: LineId[] }>();
324 const add = (keys: readonly Key[], field: "writes" | "reads" | "holds"): void => {
325 for (const key of keys) {
326 const line = lineOfKey(key);
327 if (line === undefined) continue;
328 const writer = writerOf(line);
329 if (writer === atom.id) continue;
330 let entry = by.get(writer);
331 if (!entry) {
332 entry = { writes: [], reads: [], holds: [] };
333 by.set(writer, entry);
334 }
335 entry[field].push(line);
336 }
337 };
338 add(atom.writes, "writes");
339 add(atom.reads, "reads");
340 add(atom.holds, "holds");
341 return [...by.entries()]
342 .sort(([p], [q]) => graph.atom(p).seq - graph.atom(q).seq)
343 .map(([id, lines]) => {
344 const a = graph.atom(id);
345 return { atom: id, author: a.author, message: a.message, ...lines };
346 });
347}