{"version":199,"agent":"autosettle","message":"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.","time":1792024228013,"timeIso":"2026-10-15T00:30:28.013Z","changes":1,"change":3382,"files":["scripts/autosettle/replay.ts"],"draft":null,"diff":[{"path":"scripts/autosettle/replay.ts","added":146,"removed":142,"diff":"--- a/scripts/autosettle/replay.ts\n+++ b/scripts/autosettle/replay.ts\n@@ -1,40 +1,33 @@\n // Recover each past hold's lines from a project's raw log (#19): the held agent's own lines survive in its draft\n // entries even after it kept theirs or edited by hand, which no version shows.\n //\n-//   node scripts/autosettle/replay.ts <log.ndjson> <cases.json> <seat folder> <out.json>\n+//   node --max-old-space-size=8192 scripts/autosettle/replay.ts <log.ndjson> <cases.json> <out.json>\n //\n // <log.ndjson> is GET /p/<project>/export (one raw log entry per line; owner-only). <cases.json> comes from\n-// extract.ts, which says which settles to look for and what was kept. The seat folder reads theirs' file text\n-// for positions and context. For each settle: the held agent's draft edits between its last push and the\n-// refused push, the edits of theirs' push, and the groups of them that wrote the same lines (abso's own test\n-// for a collision), in file order, paired with the settle's blocks in order.\n+// extract.ts, which says which settles to look for and what was kept. For each settle, the engine rebuilds three\n+// files from the log: the held agent's at its refused push (its base plus its draft), its base, and theirs' version.\n+// git merge-file --diff3 cuts them into blocks as a pull would, and the blocks pair with the settle's in order.\n \n import { execFileSync } from \"node:child_process\";\n-import { readFileSync, writeFileSync } from \"node:fs\";\n+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\n+import { tmpdir } from \"node:os\";\n+import { join } from \"node:path\";\n+import { Graph } from \"../../src/engine/graph.ts\";\n+import type { Atom } from \"../../src/engine/types.ts\";\n+import { View } from \"../../src/engine/view.ts\";\n \n-interface InsertRun {\n-\tfile: string;\n-\tparent: string;\n-\tlines: string[];\n-}\n-interface Atom {\n-\tid: string;\n-\tseq: number;\n-\tauthor: string;\n-\ttime: number;\n-\tinserts: InsertRun[];\n-\tdeletes: string[];\n-\twrites: string[];\n-}\n type Entry = {\n \ttype: string;\n \tagent?: string;\n+\tspace?: string | null;\n+\tversion?: number;\n \ttime?: number;\n \tatom?: Atom;\n \ttie?: Atom;\n-\tversion?: number;\n-\tspace?: string;\n-} & Record<string, unknown>;\n+\tatoms?: string[];\n+\tchanges?: string[];\n+\tcollisions?: { file: string }[];\n+};\n interface Case {\n \tid: string;\n \tfile: string;\n@@ -44,9 +37,11 @@\n \t[k: string]: unknown;\n }\n \n-const [logPath, casesPath, seat, out] = process.argv.slice(2);\n-if (!logPath || !casesPath || !seat || !out) {\n-\tconsole.error(\"usage: node scripts/autosettle/replay.ts <log.ndjson> <cases.json> <seat folder> <out.json>\");\n+const [logPath, casesPath, out] = process.argv.slice(2);\n+if (!logPath || !casesPath || !out) {\n+\tconsole.error(\n+\t\t\"usage: node --max-old-space-size=8192 scripts/autosettle/replay.ts <log.ndjson> <cases.json> <out.json>\",\n+\t);\n \tprocess.exit(2);\n }\n const entries: Entry[] = readFileSync(logPath, \"utf8\")\n@@ -54,90 +49,107 @@\n \t.filter((l) => l.trim() !== \"\")\n \t.map((l) => JSON.parse(l) as Entry);\n const cases = JSON.parse(readFileSync(casesPath, \"utf8\")) as Case[];\n-const abso = (...args: string[]) =>\n-\texecFileSync(\"abso\", args, { cwd: seat, encoding: \"utf8\", maxBuffer: 1 << 28, shell: process.platform === \"win32\" });\n \n-// Every line any atom inserted: its text and file.\n-const lineText = new Map<string, { text: string; file: string }>();\n-const atoms = new Map<string, Atom>();\n-for (const e of entries)\n-\tfor (const a of [e.atom, e.tie]) {\n-\t\tif (!a?.inserts) continue;\n-\t\tatoms.set(a.id, a);\n-\t\tlet k = 0;\n-\t\tfor (const run of a.inserts) for (const text of run.lines) lineText.set(`${a.id}.${k++}`, { text, file: run.file });\n-\t}\n-const insertedIds = (a: Atom, file: string) => {\n-\tconst ids: string[] = [];\n-\tlet k = 0;\n-\tfor (const run of a.inserts)\n-\t\tfor (const _ of run.lines) {\n-\t\t\tif (run.file === file) ids.push(`${a.id}.${k}`);\n-\t\t\tk++;\n-\t\t}\n-\treturn ids;\n+// Every atom into one graph, and shared's set after each version.\n+const graph = new Graph();\n+const added = (a: Atom | undefined) => {\n+\tif (a && !graph.has(a.id)) graph.add(a);\n };\n-const MARKER = /^(<<<<<<< yours|\\|\\|\\|\\|\\|\\|\\| before|=======$|>>>>>>> theirs:)/;\n-\n-/** The published shared version's index in the log, and the agent's draft atoms before an index since its last push. */\n-const publishAt = new Map<number, number>();\n+const sharedAt = new Map<number, Set<string>>();\n+const versionAt = new Map<number, number>();\n+let shared = new Set<string>();\n entries.forEach((e, i) => {\n-\tif ((e.type === \"publish\" || e.type === \"land\") && e.space === undefined && typeof e.version === \"number\")\n-\t\tpublishAt.set(e.version, i);\n+\tadded(e.atom);\n+\tadded(e.tie);\n+\tif (e.type === \"init\" && e.atom) {\n+\t\tshared.add(e.atom.id);\n+\t\tsharedAt.set(0, new Set(shared));\n+\t}\n+\tconst intoShared = (e.type === \"publish\" && !e.space) || e.type === \"land\";\n+\tif (intoShared && typeof e.version === \"number\") {\n+\t\tshared = new Set(shared);\n+\t\tfor (const id of e.changes ?? []) shared.add(id);\n+\t\tif (e.tie) shared.add(e.tie.id);\n+\t\tsharedAt.set(e.version, shared);\n+\t\tversionAt.set(e.version, i);\n+\t}\n });\n-function draftBefore(agent: string, end: number): Atom[] {\n+const textOf = (set: Set<string>, file: string): string[] => {\n+\tconst view = new View(graph, set);\n+\treturn view.hasFile(file) ? view.lines(file).map((l) => l.text) : [];\n+};\n+\n+/** The agent's base version and its unpublished draft atoms just before log index `end`. */\n+function draftBefore(agent: string, end: number): { base: number; draft: string[] } {\n+\tlet base = 0;\n \tlet start = 0;\n \tfor (let i = end - 1; i >= 0; i--) {\n \t\tconst e = entries[i]!;\n-\t\tif (e.agent === agent && (e.type === \"publish\" || e.type === \"land\")) {\n+\t\tif (e.agent !== agent) continue;\n+\t\tif (base === 0 && (e.type === \"sync\" || e.type === \"join\") && typeof e.version === \"number\") base = e.version;\n+\t\tif ((e.type === \"publish\" && !e.space) || e.type === \"land\") {\n+\t\t\tif (base === 0 && typeof e.version === \"number\") base = e.version;\n \t\t\tstart = i + 1;\n \t\t\tbreak;\n \t\t}\n \t}\n-\treturn entries\n-\t\t.slice(start, end)\n-\t\t.filter((e) => e.type === \"draft\" && e.agent === agent && e.atom)\n-\t\t.map((e) => e.atom!);\n+\tconst draft: string[] = [];\n+\tfor (const e of entries.slice(start, end)) {\n+\t\tif (e.agent !== agent) continue;\n+\t\tif (e.type === \"draft\" && e.atom) draft.push(e.atom.id);\n+\t\tif (e.type === \"discard\")\n+\t\t\tfor (const id of e.atoms ?? []) draft.splice(draft.indexOf(id), draft.includes(id) ? 1 : 0);\n+\t}\n+\treturn { base, draft };\n }\n \n-/** Atoms touching `file`, grouped into collisions: groups linked by a written key or by one editing another's lines. */\n-function collisions(mine: Atom[], theirs: Atom[], file: string) {\n-\tconst touches = (a: Atom) =>\n-\t\ta.inserts.some((r) => r.file === file) || a.deletes.some((d) => lineText.get(d)?.file === file);\n-\tconst all = [\n-\t\t...mine.filter(touches).map((a) => ({ a, side: \"yours\" as const })),\n-\t\t...theirs.filter(touches).map((a) => ({ a, side: \"theirs\" as const })),\n-\t];\n-\tconst parent = all.map((_, i) => i);\n-\tconst find = (i: number): number => (parent[i] === i ? i : (parent[i] = find(parent[i]!)));\n-\tconst keyOwner = new Map<string, number>();\n-\tall.forEach(({ a }, i) => {\n-\t\tconst keys = [...a.writes, ...a.deletes.map((d) => `L:${d}`)];\n-\t\tfor (const own of insertedIds(a, file)) keys.push(`own:${own}`);\n-\t\tfor (const k of keys) {\n-\t\t\tconst key = k.startsWith(\"own:\") ? `L:${k.slice(4)}` : k;\n-\t\t\tconst j = keyOwner.get(key);\n-\t\t\tif (j === undefined) keyOwner.set(key, i);\n-\t\t\telse parent[find(i)] = find(j);\n+interface Block {\n+\tyours: string[];\n+\tbase: string[];\n+\ttheirs: string[];\n+\t/** Where the block starts in theirs. */\n+\tat: number;\n+}\n+/** git's three-way merge of the files, as marker blocks with each side's lines. */\n+function blocks(yours: string[], base: string[], theirs: string[]): Block[] {\n+\tconst dir = mkdtempSync(join(tmpdir(), \"autosettle-\"));\n+\tconst path = (n: string) => join(dir, n);\n+\twriteFileSync(path(\"yours\"), `${yours.join(\"\\n\")}\\n`);\n+\twriteFileSync(path(\"base\"), `${base.join(\"\\n\")}\\n`);\n+\twriteFileSync(path(\"theirs\"), `${theirs.join(\"\\n\")}\\n`);\n+\tlet merged = \"\";\n+\ttry {\n+\t\tmerged = execFileSync(\"git\", [\"merge-file\", \"-p\", \"--diff3\", path(\"yours\"), path(\"base\"), path(\"theirs\")], {\n+\t\t\tencoding: \"utf8\",\n+\t\t\tmaxBuffer: 1 << 28,\n+\t\t});\n+\t} catch (e) {\n+\t\t// git merge-file exits with the number of conflicts.\n+\t\tmerged = (e as { stdout?: string }).stdout ?? \"\";\n+\t}\n+\trmSync(dir, { recursive: true, force: true });\n+\tconst found: Block[] = [];\n+\tlet side: \"out\" | \"yours\" | \"base\" | \"theirs\" = \"out\";\n+\tlet cur: Block = { yours: [], base: [], theirs: [], at: 0 };\n+\tlet theirsLine = 0;\n+\tfor (const line of merged.split(\"\\n\")) {\n+\t\tif (line.startsWith(\"<<<<<<< \")) {\n+\t\t\tside = \"yours\";\n+\t\t\tcur = { yours: [], base: [], theirs: [], at: theirsLine };\n+\t\t} else if (side === \"yours\" && line.startsWith(\"||||||| \")) side = \"base\";\n+\t\telse if (side === \"base\" && line === \"=======\") side = \"theirs\";\n+\t\telse if (side === \"theirs\" && line.startsWith(\">>>>>>> \")) {\n+\t\t\tfound.push(cur);\n+\t\t\tside = \"out\";\n+\t\t} else if (side === \"out\") theirsLine++;\n+\t\telse {\n+\t\t\tcur[side].push(line);\n+\t\t\tif (side === \"theirs\") theirsLine++;\n \t\t}\n-\t});\n-\tconst groups = new Map<number, typeof all>();\n-\tall.forEach((x, i) => groups.set(find(i), [...(groups.get(find(i)) ?? []), x]));\n-\treturn [...groups.values()].filter((g) => g.some((x) => x.side === \"yours\") && g.some((x) => x.side === \"theirs\"));\n+\t}\n+\treturn found;\n }\n \n-/** The lines a side's atoms in a group leave standing, in order, without marker lines. */\n-function standing(group: { a: Atom; side: string }[], side: string, file: string): string[] {\n-\tconst atomsOf = group.filter((x) => x.side === side).map((x) => x.a);\n-\tconst gone = new Set(atomsOf.flatMap((a) => a.deletes));\n-\treturn atomsOf\n-\t\t.sort((x, y) => x.seq - y.seq)\n-\t\t.flatMap((a) => insertedIds(a, file))\n-\t\t.filter((id) => !gone.has(id))\n-\t\t.map((id) => lineText.get(id)!.text)\n-\t\t.filter((t) => !MARKER.test(t));\n-}\n-\n const results: unknown[] = [];\n const byGroup = new Map<string, Case[]>();\n for (const c of cases) {\n@@ -146,68 +158,60 @@\n }\n for (const group of byGroup.values()) {\n \tconst c0 = group[0]!;\n-\tconst settleAt = publishAt.get(c0.settler.settleVersion);\n-\tconst theirsAt = publishAt.get(c0.theirs.version);\n-\tconst notes: string[] = [];\n-\tif (settleAt === undefined || theirsAt === undefined) {\n+\tconst settleAt = versionAt.get(c0.settler.settleVersion);\n+\tconst theirSet = sharedAt.get(c0.theirs.version);\n+\tif (settleAt === undefined || !theirSet) {\n \t\tfor (const c of group) results.push({ ...c, yours: null, notes: \"the settle or theirs isn't in this log\" });\n \t\tcontinue;\n \t}\n-\t// The held push: the settler's newest refusal naming the file before its settle.\n+\tconst notes: string[] = [];\n \tlet refusedAt = -1;\n \tfor (let i = settleAt - 1; i >= 0; i--) {\n \t\tconst e = entries[i]!;\n-\t\tif (e.type === \"refused\" && e.agent === c0.settler.agent) {\n-\t\t\tconst files = ((e.collisions as { file: string }[] | undefined) ?? []).map((x) => x.file);\n-\t\t\tif (files.includes(c0.file)) {\n-\t\t\t\trefusedAt = i;\n+\t\tif (e.type === \"refused\" && e.agent === c0.settler.agent && (e.collisions ?? []).some((x) => x.file === c0.file)) {\n+\t\t\trefusedAt = i;\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\t// No refusal on record (older holds): the draft just before the agent's first pull past theirs.\n+\tlet end = refusedAt;\n+\tif (end < 0) {\n+\t\tnotes.push(\"no refused push on record; used the draft before the agent pulled theirs\");\n+\t\tconst theirsAt = versionAt.get(c0.theirs.version)!;\n+\t\tend = settleAt;\n+\t\tfor (let i = theirsAt + 1; i < settleAt; i++) {\n+\t\t\tconst e = entries[i]!;\n+\t\t\tif (e.agent === c0.settler.agent && e.type === \"sync\" && (e.version ?? 0) >= c0.theirs.version) {\n+\t\t\t\tend = i;\n \t\t\t\tbreak;\n \t\t\t}\n \t\t}\n \t}\n-\tif (refusedAt < 0) notes.push(\"no refused push found; used the draft just before the settle\");\n-\tconst mine = draftBefore(c0.settler.agent, refusedAt >= 0 ? refusedAt : settleAt);\n-\tconst theirPublish = entries[theirsAt]!;\n-\tconst theirIds = (theirPublish.changes as string[] | undefined) ?? [];\n-\tconst theirs = theirIds.map((id) => atoms.get(id)).filter((a): a is Atom => a !== undefined);\n-\tconst found = collisions(mine, theirs, c0.file);\n-\t// File order, by where theirs' first standing line sits in theirs' version.\n-\tlet theirFile: string[] = [];\n-\ttry {\n-\t\ttheirFile = abso(\"show\", `${c0.theirs.version}:${c0.file}`).split(/\\r?\\n/);\n-\t} catch {\n-\t\tnotes.push(\"couldn't read theirs' file\");\n+\tconst { base, draft } = draftBefore(c0.settler.agent, end);\n+\tconst baseSet = sharedAt.get(base);\n+\tif (!baseSet) {\n+\t\tfor (const c of group) results.push({ ...c, yours: null, notes: `no shared version ${base} in this log` });\n+\t\tcontinue;\n \t}\n-\tconst placed = found\n-\t\t.map((g) => {\n-\t\t\tconst t = standing(g, \"theirs\", c0.file);\n-\t\t\tconst at = t.length > 0 ? theirFile.indexOf(t[0]!) : -1;\n-\t\t\treturn { g, at, yours: standing(g, \"yours\", c0.file), theirs: t };\n-\t\t})\n-\t\t.sort((x, y) => x.at - y.at);\n-\tif (placed.length !== group.length)\n-\t\tnotes.push(`found ${placed.length} collisions for ${group.length} settled blocks`);\n+\tconst yoursText = textOf(new Set([...baseSet, ...draft]), c0.file);\n+\tconst baseText = textOf(baseSet, c0.file);\n+\tconst theirText = textOf(theirSet, c0.file);\n+\tconst found = blocks(yoursText, baseText, theirText);\n+\tif (found.length !== group.length) notes.push(`git found ${found.length} blocks for ${group.length} settled`);\n \tgroup.forEach((c, i) => {\n-\t\tconst p = placed[i];\n-\t\tconst base = p\n-\t\t\t? [...new Set(p.g.flatMap((x) => x.a.deletes))]\n-\t\t\t\t\t.filter((d) => !p.g.some((x) => insertedIds(x.a, c.file).includes(d)))\n-\t\t\t\t\t.map((d) => lineText.get(d)?.text)\n-\t\t\t\t\t.filter((t): t is string => t !== undefined && !MARKER.test(t))\n-\t\t\t: null;\n+\t\tconst b = found.length === group.length ? found[i] : undefined;\n \t\tresults.push({\n \t\t\t...c,\n-\t\t\tbase,\n-\t\t\tyours: p ? p.yours : null,\n-\t\t\ttheirsLines: p ? p.theirs : null,\n-\t\t\tcontext:\n-\t\t\t\tp && p.at >= 0\n-\t\t\t\t\t? {\n-\t\t\t\t\t\t\tbefore: theirFile.slice(Math.max(0, p.at - 15), p.at),\n-\t\t\t\t\t\t\tafter: theirFile.slice(p.at + p.theirs.length, p.at + p.theirs.length + 15),\n-\t\t\t\t\t\t}\n-\t\t\t\t\t: { before: [], after: [] },\n-\t\t\tnotes: [...notes, ...(p ? [] : [\"no collision paired with this block\"])].join(\"; \"),\n+\t\t\tbase: b?.base ?? null,\n+\t\t\tyours: b?.yours ?? null,\n+\t\t\ttheirsLines: b?.theirs ?? null,\n+\t\t\tcontext: b\n+\t\t\t\t? {\n+\t\t\t\t\t\tbefore: theirText.slice(Math.max(0, b.at - 15), b.at),\n+\t\t\t\t\t\tafter: theirText.slice(b.at + b.theirs.length, b.at + b.theirs.length + 15),\n+\t\t\t\t\t}\n+\t\t\t\t: { before: [], after: [] },\n+\t\t\tnotes: [...notes, ...(b ? [] : [\"blocks don't pair one to one, so none is used\"])].join(\"; \"),\n \t\t\trecoveredBy: \"replay\",\n \t\t});\n \t});"}],"ci":null}