{"draft":null,"from":7,"to":318,"files":[{"path":"scripts/autosettle/replay.ts","added":221,"removed":0,"diff":"--- /dev/null\n+++ b/scripts/autosettle/replay.ts\n@@ -0,0 +1,221 @@\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 --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. 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 { 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+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+\tatoms?: string[];\n+\tchanges?: string[];\n+\tcollisions?: { file: string }[];\n+};\n+interface Case {\n+\tid: string;\n+\tfile: string;\n+\tsettler: { agent: string; heldMessage?: string; settleVersion: number; settleMessage?: string };\n+\ttheirs: { agent: string; version: number; message?: string };\n+\tkept: string;\n+\t[k: string]: unknown;\n+}\n+\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+\t.split(\"\\n\")\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+\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 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+\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+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) 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+\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+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+\treturn found;\n+}\n+\n+const results: unknown[] = [];\n+const byGroup = new Map<string, Case[]>();\n+for (const c of cases) {\n+\tconst key = `${c.settler.settleVersion} ${c.file}`;\n+\tbyGroup.set(key, [...(byGroup.get(key) ?? []), c]);\n+}\n+for (const group of byGroup.values()) {\n+\tconst c0 = group[0]!;\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+\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 && (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+\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 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 b = found.length === group.length ? found[i] : undefined;\n+\t\tresults.push({\n+\t\t\t...c,\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});\n+}\n+writeFileSync(out, JSON.stringify(results, null, \"\\t\"));\n+const ok = results.filter((r) => (r as { yours: unknown }).yours !== null).length;\n+console.log(`${results.length} settled blocks; ${ok} with both sides recovered from the log.`);"}],"unmatched":[]}