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
show on this site's /mcp
CLI
abso show 199 --json
JSON
/christopher/abso-core/versions/199?format=json

Auto-settle (#19): replay.ts rebuilds a past hold's three files with the engine from a project's raw log (the held agent's base plus its draft at the refused push, its base, theirs' version) and cuts them with git merge-file --diff3, as a pull would. On project abso's log it recovers 33 of 35 settled blocks.

of shared·autosettle··Not checked

Version 198 · Files at version 199

1 file, 146 lines added, 142 removed.

--- a/scripts/autosettle/replay.ts
+++ b/scripts/autosettle/replay.ts
@@ -1,40 +1,33 @@
11// Recover each past hold's lines from a project's raw log (#19): the held agent's own lines survive in its draft
22// entries even after it kept theirs or edited by hand, which no version shows.
33//
4−// node scripts/autosettle/replay.ts <log.ndjson> <cases.json> <seat folder> <out.json>
4+// node --max-old-space-size=8192 scripts/autosettle/replay.ts <log.ndjson> <cases.json> <out.json>
55//
66// <log.ndjson> is GET /p/<project>/export (one raw log entry per line; owner-only). <cases.json> comes from
7−// extract.ts, which says which settles to look for and what was kept. The seat folder reads theirs' file text
8−// for positions and context. For each settle: the held agent's draft edits between its last push and the
9−// refused push, the edits of theirs' push, and the groups of them that wrote the same lines (abso's own test
10−// for a collision), in file order, paired with the settle's blocks in order.
7+// extract.ts, which says which settles to look for and what was kept. For each settle, the engine rebuilds three
8+// files from the log: the held agent's at its refused push (its base plus its draft), its base, and theirs' version.
9+// git merge-file --diff3 cuts them into blocks as a pull would, and the blocks pair with the settle's in order.
1110
1211import { execFileSync } from "node:child_process";
13−import { readFileSync, writeFileSync } from "node:fs";
12+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
13+import { tmpdir } from "node:os";
14+import { join } from "node:path";
15+import { Graph } from "../../src/engine/graph.ts";
16+import type { Atom } from "../../src/engine/types.ts";
17+import { View } from "../../src/engine/view.ts";
1418
15−interface InsertRun {
16− file: string;
17− parent: string;
18− lines: string[];
19−}
20−interface Atom {
21− id: string;
22− seq: number;
23− author: string;
24− time: number;
25− inserts: InsertRun[];
26− deletes: string[];
27− writes: string[];
28−}
2919type Entry = {
3020 type: string;
3121 agent?: string;
22+ space?: string | null;
23+ version?: number;
3224 time?: number;
3325 atom?: Atom;
3426 tie?: Atom;
35− version?: number;
36− space?: string;
37−} & Record<string, unknown>;
27+ atoms?: string[];
28+ changes?: string[];
29+ collisions?: { file: string }[];
30+};
3831interface Case {
3932 id: string;
4033 file: string;
@@ -44,9 +37,11 @@
4437 [k: string]: unknown;
4538}
4639
47−const [logPath, casesPath, seat, out] = process.argv.slice(2);
48−if (!logPath || !casesPath || !seat || !out) {
49− console.error("usage: node scripts/autosettle/replay.ts <log.ndjson> <cases.json> <seat folder> <out.json>");
40+const [logPath, casesPath, out] = process.argv.slice(2);
41+if (!logPath || !casesPath || !out) {
42+ console.error(
43+ "usage: node --max-old-space-size=8192 scripts/autosettle/replay.ts <log.ndjson> <cases.json> <out.json>",
44+ );
5045 process.exit(2);
5146}
5247const entries: Entry[] = readFileSync(logPath, "utf8")
@@ -54,90 +49,107 @@
5449 .filter((l) => l.trim() !== "")
5550 .map((l) => JSON.parse(l) as Entry);
5651const cases = JSON.parse(readFileSync(casesPath, "utf8")) as Case[];
57−const abso = (...args: string[]) =>
58− execFileSync("abso", args, { cwd: seat, encoding: "utf8", maxBuffer: 1 << 28, shell: process.platform === "win32" });
5952
60−// Every line any atom inserted: its text and file.
61−const lineText = new Map<string, { text: string; file: string }>();
62−const atoms = new Map<string, Atom>();
63−for (const e of entries)
64− for (const a of [e.atom, e.tie]) {
65− if (!a?.inserts) continue;
66− atoms.set(a.id, a);
67− let k = 0;
68− for (const run of a.inserts) for (const text of run.lines) lineText.set(`${a.id}.${k++}`, { text, file: run.file });
69− }
70−const insertedIds = (a: Atom, file: string) => {
71− const ids: string[] = [];
72− let k = 0;
73− for (const run of a.inserts)
74− for (const _ of run.lines) {
75− if (run.file === file) ids.push(`${a.id}.${k}`);
76− k++;
77− }
78− return ids;
53+// Every atom into one graph, and shared's set after each version.
54+const graph = new Graph();
55+const added = (a: Atom | undefined) => {
56+ if (a && !graph.has(a.id)) graph.add(a);
7957};
80−const MARKER = /^(<<<<<<< yours|\|\|\|\|\|\|\| before|=======$|>>>>>>> theirs:)/;
81−
82−/** The published shared version's index in the log, and the agent's draft atoms before an index since its last push. */
83−const publishAt = new Map<number, number>();
58+const sharedAt = new Map<number, Set<string>>();
59+const versionAt = new Map<number, number>();
60+let shared = new Set<string>();
8461entries.forEach((e, i) => {
85− if ((e.type === "publish" || e.type === "land") && e.space === undefined && typeof e.version === "number")
86− publishAt.set(e.version, i);
62+ added(e.atom);
63+ added(e.tie);
64+ if (e.type === "init" && e.atom) {
65+ shared.add(e.atom.id);
66+ sharedAt.set(0, new Set(shared));
67+ }
68+ const intoShared = (e.type === "publish" && !e.space) || e.type === "land";
69+ if (intoShared && typeof e.version === "number") {
70+ shared = new Set(shared);
71+ for (const id of e.changes ?? []) shared.add(id);
72+ if (e.tie) shared.add(e.tie.id);
73+ sharedAt.set(e.version, shared);
74+ versionAt.set(e.version, i);
75+ }
8776});
88−function draftBefore(agent: string, end: number): Atom[] {
77+const textOf = (set: Set<string>, file: string): string[] => {
78+ const view = new View(graph, set);
79+ return view.hasFile(file) ? view.lines(file).map((l) => l.text) : [];
80+};
82+/** The agent's base version and its unpublished draft atoms just before log index `end`. */
83+function draftBefore(agent: string, end: number): { base: number; draft: string[] } {
84+ let base = 0;
8985 let start = 0;
9086 for (let i = end - 1; i >= 0; i--) {
9187 const e = entries[i]!;
92− if (e.agent === agent && (e.type === "publish" || e.type === "land")) {
88+ if (e.agent !== agent) continue;
89+ if (base === 0 && (e.type === "sync" || e.type === "join") && typeof e.version === "number") base = e.version;
90+ if ((e.type === "publish" && !e.space) || e.type === "land") {
91+ if (base === 0 && typeof e.version === "number") base = e.version;
9392 start = i + 1;
9493 break;
9594 }
9695 }
97− return entries
98− .slice(start, end)
99− .filter((e) => e.type === "draft" && e.agent === agent && e.atom)
100− .map((e) => e.atom!);
96+ const draft: string[] = [];
97+ for (const e of entries.slice(start, end)) {
98+ if (e.agent !== agent) continue;
99+ if (e.type === "draft" && e.atom) draft.push(e.atom.id);
100+ if (e.type === "discard")
101+ for (const id of e.atoms ?? []) draft.splice(draft.indexOf(id), draft.includes(id) ? 1 : 0);
102+ }
103+ return { base, draft };
101104}
102105
103−/** Atoms touching `file`, grouped into collisions: groups linked by a written key or by one editing another's lines. */
104−function collisions(mine: Atom[], theirs: Atom[], file: string) {
105− const touches = (a: Atom) =>
106− a.inserts.some((r) => r.file === file) || a.deletes.some((d) => lineText.get(d)?.file === file);
107− const all = [
108− ...mine.filter(touches).map((a) => ({ a, side: "yours" as const })),
109− ...theirs.filter(touches).map((a) => ({ a, side: "theirs" as const })),
110− ];
111− const parent = all.map((_, i) => i);
112− const find = (i: number): number => (parent[i] === i ? i : (parent[i] = find(parent[i]!)));
113− const keyOwner = new Map<string, number>();
114− all.forEach(({ a }, i) => {
115− const keys = [...a.writes, ...a.deletes.map((d) => `L:${d}`)];
116− for (const own of insertedIds(a, file)) keys.push(`own:${own}`);
117− for (const k of keys) {
118− const key = k.startsWith("own:") ? `L:${k.slice(4)}` : k;
119− const j = keyOwner.get(key);
120− if (j === undefined) keyOwner.set(key, i);
121− else parent[find(i)] = find(j);
106+interface Block {
107+ yours: string[];
108+ base: string[];
109+ theirs: string[];
110+ /** Where the block starts in theirs. */
111+ at: number;
112+}
113+/** git's three-way merge of the files, as marker blocks with each side's lines. */
114+function blocks(yours: string[], base: string[], theirs: string[]): Block[] {
115+ const dir = mkdtempSync(join(tmpdir(), "autosettle-"));
116+ const path = (n: string) => join(dir, n);
117+ writeFileSync(path("yours"), `${yours.join("\n")}\n`);
118+ writeFileSync(path("base"), `${base.join("\n")}\n`);
119+ writeFileSync(path("theirs"), `${theirs.join("\n")}\n`);
120+ let merged = "";
121+ try {
122+ merged = execFileSync("git", ["merge-file", "-p", "--diff3", path("yours"), path("base"), path("theirs")], {
123+ encoding: "utf8",
124+ maxBuffer: 1 << 28,
125+ });
126+ } catch (e) {
127+ // git merge-file exits with the number of conflicts.
128+ merged = (e as { stdout?: string }).stdout ?? "";
129+ }
130+ rmSync(dir, { recursive: true, force: true });
131+ const found: Block[] = [];
132+ let side: "out" | "yours" | "base" | "theirs" = "out";
133+ let cur: Block = { yours: [], base: [], theirs: [], at: 0 };
134+ let theirsLine = 0;
135+ for (const line of merged.split("\n")) {
136+ if (line.startsWith("<<<<<<< ")) {
137+ side = "yours";
138+ cur = { yours: [], base: [], theirs: [], at: theirsLine };
139+ } else if (side === "yours" && line.startsWith("||||||| ")) side = "base";
140+ else if (side === "base" && line === "=======") side = "theirs";
141+ else if (side === "theirs" && line.startsWith(">>>>>>> ")) {
142+ found.push(cur);
143+ side = "out";
144+ } else if (side === "out") theirsLine++;
145+ else {
146+ cur[side].push(line);
147+ if (side === "theirs") theirsLine++;
122148 }
123− });
124− const groups = new Map<number, typeof all>();
125− all.forEach((x, i) => groups.set(find(i), [...(groups.get(find(i)) ?? []), x]));
126− return [...groups.values()].filter((g) => g.some((x) => x.side === "yours") && g.some((x) => x.side === "theirs"));
149+ }
150+ return found;
127151}
128152
129−/** The lines a side's atoms in a group leave standing, in order, without marker lines. */
130−function standing(group: { a: Atom; side: string }[], side: string, file: string): string[] {
131− const atomsOf = group.filter((x) => x.side === side).map((x) => x.a);
132− const gone = new Set(atomsOf.flatMap((a) => a.deletes));
133− return atomsOf
134− .sort((x, y) => x.seq - y.seq)
135− .flatMap((a) => insertedIds(a, file))
136− .filter((id) => !gone.has(id))
137− .map((id) => lineText.get(id)!.text)
138− .filter((t) => !MARKER.test(t));
139−}
140−
141153const results: unknown[] = [];
142154const byGroup = new Map<string, Case[]>();
143155for (const c of cases) {
@@ -146,68 +158,60 @@
146158}
147159for (const group of byGroup.values()) {
148160 const c0 = group[0]!;
149− const settleAt = publishAt.get(c0.settler.settleVersion);
150− const theirsAt = publishAt.get(c0.theirs.version);
151− const notes: string[] = [];
152− if (settleAt === undefined || theirsAt === undefined) {
161+ const settleAt = versionAt.get(c0.settler.settleVersion);
162+ const theirSet = sharedAt.get(c0.theirs.version);
163+ if (settleAt === undefined || !theirSet) {
153164 for (const c of group) results.push({ ...c, yours: null, notes: "the settle or theirs isn't in this log" });
154165 continue;
155166 }
156− // The held push: the settler's newest refusal naming the file before its settle.
167+ const notes: string[] = [];
157168 let refusedAt = -1;
158169 for (let i = settleAt - 1; i >= 0; i--) {
159170 const e = entries[i]!;
160− if (e.type === "refused" && e.agent === c0.settler.agent) {
161− const files = ((e.collisions as { file: string }[] | undefined) ?? []).map((x) => x.file);
162− if (files.includes(c0.file)) {
163− refusedAt = i;
171+ if (e.type === "refused" && e.agent === c0.settler.agent && (e.collisions ?? []).some((x) => x.file === c0.file)) {
172+ refusedAt = i;
173+ break;
174+ }
175+ }
176+ // No refusal on record (older holds): the draft just before the agent's first pull past theirs.
177+ let end = refusedAt;
178+ if (end < 0) {
179+ notes.push("no refused push on record; used the draft before the agent pulled theirs");
180+ const theirsAt = versionAt.get(c0.theirs.version)!;
181+ end = settleAt;
182+ for (let i = theirsAt + 1; i < settleAt; i++) {
183+ const e = entries[i]!;
184+ if (e.agent === c0.settler.agent && e.type === "sync" && (e.version ?? 0) >= c0.theirs.version) {
185+ end = i;
164186 break;
165187 }
166188 }
167189 }
168− if (refusedAt < 0) notes.push("no refused push found; used the draft just before the settle");
169− const mine = draftBefore(c0.settler.agent, refusedAt >= 0 ? refusedAt : settleAt);
170− const theirPublish = entries[theirsAt]!;
171− const theirIds = (theirPublish.changes as string[] | undefined) ?? [];
172− const theirs = theirIds.map((id) => atoms.get(id)).filter((a): a is Atom => a !== undefined);
173− const found = collisions(mine, theirs, c0.file);
174− // File order, by where theirs' first standing line sits in theirs' version.
175− let theirFile: string[] = [];
176− try {
177− theirFile = abso("show", `${c0.theirs.version}:${c0.file}`).split(/\r?\n/);
178− } catch {
179− notes.push("couldn't read theirs' file");
190+ const { base, draft } = draftBefore(c0.settler.agent, end);
191+ const baseSet = sharedAt.get(base);
192+ if (!baseSet) {
193+ for (const c of group) results.push({ ...c, yours: null, notes: `no shared version ${base} in this log` });
194+ continue;
180195 }
181− const placed = found
182− .map((g) => {
183− const t = standing(g, "theirs", c0.file);
184− const at = t.length > 0 ? theirFile.indexOf(t[0]!) : -1;
185− return { g, at, yours: standing(g, "yours", c0.file), theirs: t };
186− })
187− .sort((x, y) => x.at - y.at);
188− if (placed.length !== group.length)
189− notes.push(`found ${placed.length} collisions for ${group.length} settled blocks`);
196+ const yoursText = textOf(new Set([...baseSet, ...draft]), c0.file);
197+ const baseText = textOf(baseSet, c0.file);
198+ const theirText = textOf(theirSet, c0.file);
199+ const found = blocks(yoursText, baseText, theirText);
200+ if (found.length !== group.length) notes.push(`git found ${found.length} blocks for ${group.length} settled`);
190201 group.forEach((c, i) => {
191− const p = placed[i];
192− const base = p
193− ? [...new Set(p.g.flatMap((x) => x.a.deletes))]
194− .filter((d) => !p.g.some((x) => insertedIds(x.a, c.file).includes(d)))
195− .map((d) => lineText.get(d)?.text)
196− .filter((t): t is string => t !== undefined && !MARKER.test(t))
197− : null;
202+ const b = found.length === group.length ? found[i] : undefined;
198203 results.push({
199204 ...c,
200− base,
201− yours: p ? p.yours : null,
202− theirsLines: p ? p.theirs : null,
203− context:
204− p && p.at >= 0
205− ? {
206− before: theirFile.slice(Math.max(0, p.at - 15), p.at),
207− after: theirFile.slice(p.at + p.theirs.length, p.at + p.theirs.length + 15),
208− }
209− : { before: [], after: [] },
210− notes: [...notes, ...(p ? [] : ["no collision paired with this block"])].join("; "),
205+ base: b?.base ?? null,
206+ yours: b?.yours ?? null,
207+ theirsLines: b?.theirs ?? null,
208+ context: b
209+ ? {
210+ before: theirText.slice(Math.max(0, b.at - 15), b.at),
211+ after: theirText.slice(b.at + b.theirs.length, b.at + b.theirs.length + 15),
212+ }
213+ : { before: [], after: [] },
214+ notes: [...notes, ...(b ? [] : ["blocks don't pair one to one, so none is used"])].join("; "),
211215 recoveredBy: "replay",
212216 });
213217 });