- 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=239&format=json
331 linesFirst import 95% · codex-capacity-chair 5%Last change codex-capacity-chair in version 138, 6 versions changed it
You're reading version 239. The newest is 318, and no version 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 return view.visibleNeighbours(info.file, line);
211}
213/**
214 * When atom N changes A's lines (deletes one, or inserts between two lines of
215 * one run of A), A has a `together` reason with B (either direction), B is in
216 * the set, and N doesn't touch B's side, warn. N touches B's side when it
217 * writes, reads or holds a line B wrote, or a line right next to one B
218 * deleted (a deletion leaves no lines of its own). No warning when N itself
219 * carries a reason to B (it has said why B is fine).
220 */
221export function reasonWarnings(graph: Graph, set: AtomSet, atom: Atom): ReasonWarning[] {
222 const claimed = new Set<LineId>();
223 for (const key of claimsOf(atom)) {
224 const line = lineOfKey(key);
225 if (line !== undefined) claimed.add(line);
226 }
227 const touched = new Set<AtomId>([...claimed].map(writerOf));
228 const changed = new Set<AtomId>();
229 for (const key of atom.writes) {
230 const { kind, node } = parseKey(key);
231 if (kind === "line") changed.add(writerOf(node));
232 else if (kind === "gap" && !isStartNode(node) && insideRun(graph, node)) changed.add(writerOf(node));
233 }
234 let view: View | undefined;
235 const touchesSide = (b: AtomId): boolean => {
236 if (touched.has(b)) return true;
237 const deleted = graph.atom(b).deletes;
238 if (deleted.length === 0) return false;
239 view ??= new View(graph, set);
240 const v = view;
241 return deleted.some((line) => visibleNeighbours(v, graph, line).some((n) => claimed.has(n)));
242 };
243 const acknowledged = new Set(atom.reasons.map((r) => r.to));
244 const out: ReasonWarning[] = [];
245 const seen = new Set<string>();
246 for (const a of [...changed].sort(bySeq(graph))) {
247 if (a === atom.id) continue;
248 for (const link of graph.eachTogetherLink(a)) {
249 const b = link.other;
250 if (b === atom.id || !set.has(b) || acknowledged.has(b)) continue;
251 const tag = `${a} ${b}`;
252 if (seen.has(tag)) continue;
253 seen.add(tag);
254 if (touchesSide(b)) continue;
255 out.push({
256 atom: a,
257 partner: b,
258 text: link.text,
259 message: `${a} was changed together with ${b} because: ${link.text}; you changed ${a}'s lines but not ${b}'s.`,
260 });
261 }
262 }
263 return out;
264}
266// Draft check ----------------------------------------------------------------------
268/** Whose lines a draft touches, and how. */
269export interface Touch {
270 readonly atom: AtomId;
271 readonly author: string;
272 readonly message: string;
273 readonly writes: readonly LineId[];
274 readonly reads: readonly LineId[];
275 readonly holds: readonly LineId[];
276}
278export interface DraftReport {
279 readonly touches: readonly Touch[];
280 /** Conflicts the draft would have with atoms in the set (none are resolved yet). */
281 readonly conflicts: readonly Conflict[];
282 readonly warnings: readonly ReasonWarning[];
283}
285/**
286 * What accepting `draft` into `set` would mean, before it is accepted: whose
287 * lines it touches (with author and message), the conflicts it would bring
288 * (exactly those `conflicts` reports once it is in the set), and reason
289 * warnings. The draft must not be in the graph yet; its deps must be.
290 */
291export function checkDraft(graph: Graph, set: AtomSet, draft: Atom): DraftReport {
292 const below = graph.closureOf(draft.deps);
293 const candidates = new Set<AtomId>();
294 for (const key of draft.writes) for (const id of claimersIn(graph, set, key)) candidates.add(id);
295 for (const key of claimsOf(draft)) for (const id of graph.eachWriterOf(key)) if (set.has(id)) candidates.add(id);
296 const found: Conflict[] = [];
297 for (const id of [...candidates].sort(bySeq(graph))) {
298 const other = graph.atom(id);
299 const keys = conflictKeys(other, draft, below.has(id));
300 if (keys.length > 0) found.push(makeConflict(graph, undefined, other, draft, keys));
301 }
302 return { touches: touchesOf(graph, draft), conflicts: found, warnings: reasonWarnings(graph, set, draft) };
303}
305/** Group the lines an atom writes, reads and holds by the atom that wrote them. */
306export function touchesOf(graph: Graph, atom: Atom): Touch[] {
307 const by = new Map<AtomId, { writes: LineId[]; reads: LineId[]; holds: LineId[] }>();
308 const add = (keys: readonly Key[], field: "writes" | "reads" | "holds"): void => {
309 for (const key of keys) {
310 const line = lineOfKey(key);
311 if (line === undefined) continue;
312 const writer = writerOf(line);
313 if (writer === atom.id) continue;
314 let entry = by.get(writer);
315 if (!entry) {
316 entry = { writes: [], reads: [], holds: [] };
317 by.set(writer, entry);
318 }
319 entry[field].push(line);
320 }
321 };
322 add(atom.writes, "writes");
323 add(atom.reads, "reads");
324 add(atom.holds, "holds");
325 return [...by.entries()]
326 .sort(([p], [q]) => graph.atom(p).seq - graph.atom(q).seq)
327 .map(([id, lines]) => {
328 const a = graph.atom(id);
329 return { atom: id, author: a.author, message: a.message, ...lines };
330 });
331}