- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/worker/project/markers.ts?format=json
373 linesFirst import 94% · speed 3% · codex-capacity-chair 1% · engine 1% · infra-split 1%Last change codex-capacity-chair in version 175, 9 versions changed it
1// Collision markers (#11, round 1, ruled 2026-10-05): when a sync finds both
2// sides changed the same lines differently, it writes the file diff3 style,
3// so the collision can't pass for finished code. Helpers write, find and settle
4// blocks, and read the blocks still in an agent's files (status, sync, publish).
5//
6// <<<<<<< yours (unpublished)
7// ...the agent's lines...
8// ||||||| before (version 276)
9// ...the lines both started from...
10// =======
11// ...their lines...
12// >>>>>>> theirs: writer1, version 277 "Boiler gauge says what it multiplies"
13//
14// Settled means the block is gone. These helpers also say what an agent kept
15// once it settled one.
17import { type Atom, type AtomId, diffLines, type Graph, type Hunk, type ReadView } from "../../src/engine/index.ts";
18import type { AgentState, AgentStatus, Collision } from "./project-types.ts";
20export const YOURS = "<<<<<<< yours (unpublished)";
21const BEFORE = "||||||| before (version ";
22export const SPLIT = "=======";
23const THEIRS = ">>>>>>> theirs: ";
24const THEIRS_LABEL = /^>>>>>>> theirs: (.+), version (\d+) "(.*)"$/;
26/** One side of a block: who published theirs. */
27export interface TheirSide {
28 readonly agent: string;
29 readonly version: number;
30 readonly message: string;
31}
33/** A block in a file: 0-based indexes of its first and last marker lines, and each part. */
34export interface Block extends TheirSide {
35 readonly start: number;
36 readonly end: number;
37 readonly yours: readonly string[];
38 readonly base: readonly string[];
39 readonly theirs: readonly string[];
40}
42/** A collision a sync wrote markers for, kept until the agent publishes: what it says the agent kept. */
43export interface MarkedRegion extends TheirSide {
44 readonly file: string;
45 readonly yours: readonly string[];
46 readonly base: readonly string[];
47 readonly theirs: readonly string[];
48 /** The changes that collided (the draft's, then theirs): the edit that takes the markers out settles them. */
49 readonly settles?: readonly string[];
50}
52export type Kept = "yours" | "theirs" | "both" | "rewrote";
54/** A publish message as a marker label: its first line, at most 100 characters, with no double quotes. */
55function label(message: string): string {
56 const first = message.split("\n")[0]!.trim().replace(/"/g, "'");
57 return first.length > 100 ? `${first.slice(0, 99)}…` : first;
58}
60export function markerBlock(
61 yours: readonly string[],
62 base: readonly string[],
63 baseVersion: number,
64 theirs: readonly string[],
65 who: TheirSide,
66): string[] {
67 return [
68 YOURS,
69 ...yours,
70 `${BEFORE}${baseVersion})`,
71 ...base,
72 SPLIT,
73 ...theirs,
74 `${THEIRS}${who.agent}, version ${who.version} "${label(who.message)}"`,
75 ];
76}
78/** A line the engine writes as a marker (the split line alone is not one: `=======` is ordinary Markdown). */
79export function isMarkerLine(line: string): boolean {
80 return line === YOURS || (line.startsWith(BEFORE) && line.endsWith(")")) || THEIRS_LABEL.test(line);
81}
83/** The well-formed blocks in a file's lines, in order. */
84export function blocksIn(lines: readonly string[]): Block[] {
85 const out: Block[] = [];
86 for (let i = 0; i < lines.length; i++) {
87 if (lines[i] !== YOURS) continue;
88 let b = -1;
89 let s = -1;
90 let e = -1;
91 for (let j = i + 1; j < lines.length; j++) {
92 const l = lines[j]!;
93 if (l === YOURS) break;
94 if (b < 0 && l.startsWith(BEFORE)) b = j;
95 else if (b >= 0 && s < 0 && l === SPLIT) s = j;
96 else if (s >= 0 && THEIRS_LABEL.test(l)) {
97 e = j;
98 break;
99 }
100 }
101 if (e < 0) continue;
102 const m = THEIRS_LABEL.exec(lines[e]!)!;
103 out.push({
104 start: i,
105 end: e,
106 yours: lines.slice(i + 1, b),
107 base: lines.slice(b + 1, s),
108 theirs: lines.slice(s + 1, e),
109 agent: m[1]!,
110 version: Number(m[2]),
111 message: m[3]!,
112 });
113 i = e;
114 }
115 return out;
116}
118/** The lines with every block replaced by the side (or sides) kept. */
119export function settleLines(
120 lines: readonly string[],
121 keep: "yours" | "theirs" | "both",
122): { lines: string[]; blocks: number } {
123 const blocks = blocksIn(lines);
124 const out: string[] = [];
125 let pos = 0;
126 for (const b of blocks) {
127 out.push(...lines.slice(pos, b.start));
128 if (keep !== "theirs") out.push(...b.yours);
129 if (keep !== "yours") out.push(...b.theirs);
130 pos = b.end + 1;
131 }
132 out.push(...lines.slice(pos));
133 return { lines: out, blocks: blocks.length };
134}
136/**
137 * The edit from their text to the merged text that keeps their lines inside
138 * each block as their lines: a plain diff would pair a `}` of theirs with a
139 * `}` of yours, so their definition would read as partly the agent's, and the
140 * duplicate check would miss it. Between blocks it is a plain diff. `blocks`
141 * gives each block's place in the merged lines (at, length) and in theirs
142 * (theirsAt, theirs: how many of their lines it holds).
143 */
144export function markedHunks(
145 theirs: readonly string[],
146 merged: readonly string[],
147 blocks: readonly { at: number; length: number; theirsAt: number; theirs: number }[],
148): Hunk[] {
149 const out: Hunk[] = [];
150 const push = (h: Hunk): void => {
151 const last = out[out.length - 1];
152 // Hunks that meet are one hunk, so no two edits touch the same gap.
153 if (last && last.end === h.start)
154 out[out.length - 1] = { start: last.start, end: h.end, lines: [...last.lines, ...h.lines] };
155 else out.push(h);
156 };
157 let t = 0;
158 let m = 0;
159 for (const b of blocks) {
160 for (const h of diffLines(theirs.slice(t, b.theirsAt), merged.slice(m, b.at)))
161 push({ start: h.start + t, end: h.end + t, lines: h.lines });
162 // The block is: its opening lines, their lines as they are, the closing marker.
163 const head = b.length - b.theirs - 1;
164 push({ start: b.theirsAt, end: b.theirsAt, lines: merged.slice(b.at, b.at + head) });
165 push({ start: b.theirsAt + b.theirs, end: b.theirsAt + b.theirs, lines: [merged[b.at + b.length - 1]!] });
166 t = b.theirsAt + b.theirs;
167 m = b.at + b.length;
168 }
169 for (const h of diffLines(theirs.slice(t), merged.slice(m)))
170 push({ start: h.start + t, end: h.end + t, lines: h.lines });
171 return out;
172}
174/** A line's words, lowercased, without a checklist box: what "the same line, reworded" compares. */
175function words(line: string): Set<string> {
176 return new Set(
177 line
178 .replace(/^\s*[-*]\s*\[[ xX]\]\s*/, "")
179 .toLowerCase()
180 .match(/[a-z0-9]+/g) ?? [],
181 );
182}
184/**
185 * Whether `b` reads as `a` reworded: at least half of `a`'s words are still
186 * in it. Counted against `a` alone, so a rewording that keeps the line and
187 * adds to it (a reason, the other side's number) still reads as the line.
188 */
189function alike(a: string, b: string): boolean {
190 if (a === b) return true;
191 const x = words(a);
192 const y = words(b);
193 if (x.size === 0 || y.size === 0) return false;
194 let both = 0;
195 for (const w of x) if (y.has(w)) both++;
196 return both / x.size >= 0.5;
197}
199/**
200 * Lines both sides still had that the settled file has lost (#37): neither side deleted them, yet neither side's version, nor the base's,
201 * nor anything reading like a rewording of one, is left. When both sides
202 * changed line for line, each position is one line in three versions;
203 * otherwise only lines both sides kept word for word count. Answers each
204 * lost line as one side gave it.
205 */
206export function lostLines(lines: readonly string[], region: MarkedRegion): string[] {
207 const solid = (l: string | undefined): l is string => l !== undefined && /[A-Za-z0-9]/.test(l);
208 const groups: string[][] =
209 region.yours.length === region.theirs.length
210 ? region.yours.map((y, i) => [
211 y,
212 region.theirs[i]!,
213 ...(region.base.length === region.yours.length ? [region.base[i]!] : []),
214 ])
215 : region.yours.filter((l) => region.theirs.includes(l)).map((l) => [l]);
216 const now = lines.filter((l) => solid(l));
217 const out: string[] = [];
218 for (const g of groups) {
219 const versions = g.filter(solid);
220 if (versions.length === 0) continue;
221 if (versions.some((v) => now.some((l) => alike(v, l)))) continue;
222 out.push(versions[0]!);
223 }
224 return out;
225}
227/**
228 * What a settled region kept, judged from the file as it is now, by each
229 * side's own changes (#37): the lines it added, and
230 * the base lines only it removed. A side's block also holds lines it left as
231 * they were, and an edit to one of those must not hide that its change was
232 * kept. Lines both sides added alike, and lines with no letters or digits
233 * (`}`, blank), say nothing about whose change survived.
234 */
235export function keptOf(lines: readonly string[], region: MarkedRegion): Kept {
236 const now = new Set(lines);
237 const base = new Set(region.base);
238 const solid = (l: string) => /[A-Za-z0-9]/.test(l);
239 const yours = new Set(region.yours);
240 const theirs = new Set(region.theirs);
241 // Whether each of a side's changes is in the file: all of them, none, some, or it made none of its own.
242 const score = (
243 mine: Set<string>,
244 other: Set<string>,
245 side: readonly string[],
246 ): "all" | "none" | "some" | "nothing" => {
247 const checks = [
248 ...side.filter((l) => solid(l) && !base.has(l) && !other.has(l)).map((l) => now.has(l)),
249 ...region.base.filter((l) => solid(l) && !mine.has(l) && other.has(l)).map((l) => !now.has(l)),
250 ];
251 if (checks.length === 0) return "nothing";
252 if (checks.every(Boolean)) return "all";
253 return checks.some(Boolean) ? "some" : "none";
254 };
255 const y = score(yours, theirs, region.yours);
256 const t = score(theirs, yours, region.theirs);
257 if (y === "some" || t === "some") return "rewrote";
258 if (y === "all" && t === "all") return "both";
259 if (y === "all") return "yours";
260 if (t === "all") return "theirs";
261 // One side made no change of its own and the other's is gone: what's left is the first side's.
262 if (y === "none" && t === "nothing") return "theirs";
263 if (t === "none" && y === "nothing") return "yours";
264 return y === "nothing" && t === "nothing" ? "both" : "rewrote";
265}
267/** The message of the agent's newest held push that named `file`: its side's reason, for the settle to tell. */
268export function heldMessage(agent: AgentState, file: string): string | undefined {
269 return agent.held?.findLast((h) => h.message && h.files.includes(file))?.message;
270}
272/** What the marker reads need from a project. */
273export interface MarkerHost {
274 readonly graph: Graph;
275 agentView(agent: AgentState): ReadView;
276 draft(agent: AgentState): AtomId[];
277 draftFiles(agent: AgentState): Set<string>;
278}
280/** Files where a sync wrote the agent collision markers in its current space (#11). */
281export function markedFiles(agent: AgentState): string[] {
282 return [...new Set(agent.marked.filter((r) => r.space === agent.space).map((r) => r.file))].toSorted();
283}
285export function blockCollision(file: string, b: Block): Collision {
286 const lines: [number, number] = [b.start + 1, b.end + 1];
287 const text = (ls: readonly string[]) => (ls.length > 0 ? `${ls.join("\n")}\n` : "");
288 return {
289 kind: "lines",
290 marked: true,
291 file,
292 yours: { lines, text: text(b.yours) },
293 theirs: { lines: [...lines], text: text(b.theirs), agent: b.agent, message: b.message, version: b.version },
294 };
295}
297/** The blocks of markers still in the agent's files, as collisions (#11): listed by sync and status. */
298export function markedCollisions(host: MarkerHost, agent: AgentState): Collision[] {
299 const files = markedFiles(agent);
300 // No marked files, no view to build: most agents have none.
301 if (files.length === 0) return [];
302 const view = host.agentView(agent);
303 const out: Collision[] = [];
304 for (const file of files) {
305 if (!view.hasFile(file)) continue;
306 for (const b of blocksIn(view.lines(file).map((l) => l.text))) out.push(blockCollision(file, b));
307 }
308 return out;
309}
311export function openCollisions(host: MarkerHost, agent: AgentState): { collisions?: AgentStatus["collisions"] } {
312 const open = markedCollisions(host, agent).map((c) => ({
313 file: c.file,
314 lines: c.yours.lines,
315 theirs: { agent: c.theirs.agent, version: c.theirs.version, message: c.theirs.message },
316 }));
317 return open.length > 0 ? { collisions: open } : {};
318}
320/** The collided changes behind each block whose marker lines `atom` deletes (#11). */
321export function markersSettled(host: MarkerHost, agent: AgentState, view: ReadView, atom: Atom): AtomId[] {
322 if (agent.marked.length === 0) return [];
323 const out = new Set<AtomId>();
324 const blocksBy = new Map<string, Block[]>();
325 for (const id of atom.deletes) {
326 const info = host.graph.line(id);
327 if (!info || !isMarkerLine(info.text)) continue;
328 const file = view.fileOf(id);
329 const lines = view.lines(file);
330 if (!blocksBy.has(file)) blocksBy.set(file, blocksIn(lines.map((l) => l.text)));
331 const at = lines.findIndex((l) => l.id === id);
332 const b = blocksBy.get(file)!.find((x) => at >= x.start && at <= x.end);
333 if (!b) continue;
334 const r = agent.marked.find(
335 (m) => m.space === agent.space && m.file === file && m.agent === b.agent && m.version === b.version,
336 );
337 for (const s of r?.settles ?? []) out.add(s);
338 }
339 // Only changes still in the view can be named: the draft's own side was replaced when the sync wrote the markers.
340 return [...out].filter((id) => view.set.has(id));
341}
343/**
344 * Marker lines the agent's draft adds (#11), as collisions: each
345 * well-formed block, and any marker line left outside one. Only the labeled
346 * lines the engine writes count, so a document that shows markers can be
347 * published.
348 */
349export function markerCollisions(host: MarkerHost, agent: AgentState): Collision[] {
350 const mine = new Set(host.draft(agent));
351 const view = host.agentView(agent);
352 const out: Collision[] = [];
353 for (const file of [...host.draftFiles(agent)].toSorted()) {
354 if (!view.hasFile(file)) continue;
355 const lines = view.buildLines(file);
356 const added = lines.map((l, i) => (mine.has(l.atom) && isMarkerLine(l.text) ? i : -1)).filter((i) => i >= 0);
357 if (added.length === 0) continue;
358 const blocks = blocksIn(lines.map((l) => l.text));
359 for (const b of blocks) out.push(blockCollision(file, b));
360 for (const i of added) {
361 if (blocks.some((b) => i >= b.start && i <= b.end)) continue;
362 const at: [number, number] = [i + 1, i + 1];
363 out.push({
364 kind: "lines",
365 marked: true,
366 file,
367 yours: { lines: at, text: `${lines[i]!.text}\n` },
368 theirs: { lines: [...at], text: "", agent: "", message: "a marker line left from a collision", version: 0 },
369 });
370 }
371 }
372 return out;
373}