// RESPELL AN ARTICLE — plan, then apply, a transcript mis-hearing's correction across // an article's quotes (`archilyzer reports respell`; lib/citations/respell.mjs says // what a respelling is). // // The files, for iteration n (default: the iteration the article's current report // came from): // - reports//iterations//report.json — through writeIterationFile; // - reports//report.json — when it is n's report (the article is current on n, // or has no iterations), through writeArticle (audience and video kept); // - //i/video.manifest.json — the iteration's video project, // when it has one, and the report.json the chain copied beside it. // Each report gains `respellings`, the manifest too (every quote check, and the // video's cut-to-quote, apply them from then on). Before a write, the file as it was // is copied to the project's `revisions/-before-respell.` (beside the // manifest's other revisions; an article with no iterations: // // revisions/), so a respell is undone by copying it back. // // A respelled video shows the new words only once it is rebuilt: the plan says so. import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises"; import path from "node:path"; import { cleanRespellings, type Respelling } from "../citations/respell.mjs"; import type { Paths } from "../paths"; import { currentIteration, iterationFile, projectOf, readIteration, writeIterationFile } from "./iterations"; import { articleFile, ArticleRegistryError, writeArticle } from "./registry"; import { respellManifest } from "./respellManifest.mjs"; import { respellReport, type RespellChange } from "./respellReport"; import type { Report } from "./schema"; import { parseReport } from "./validate"; type StorePaths = Pick; export type RespellTarget = { kind: "iteration-report" | "article-report" | "project-report" | "video-manifest"; file: string; changes: RespellChange[]; }; export type RespellPlan = { article: string; iteration: number | null; respellings: Respelling[]; targets: RespellTarget[]; // Places changed, all files. total: number; notes: string[]; }; export type RespellOptions = { iteration?: number; projectsRoot: string; paths: StorePaths; }; const readJson = async (file: string): Promise => { try { return JSON.parse(await readFile(file, "utf8")); } catch (err) { if ((err as NodeJS.ErrnoException).code === "ENOENT") return null; throw new ArticleRegistryError(`${file} is not readable JSON: ${(err as Error).message}`); } }; const asReport = (raw: unknown, id: string, file: string): Report => { const parsed = parseReport(raw, { id }); if (!parsed.ok) throw new ArticleRegistryError(`${file} is not a report`, parsed.problems.map((p) => p.message)); return parsed.value; }; type Computed = { plan: RespellPlan; writes: { target: RespellTarget; data: unknown; projectDir: string | null }[]; }; async function compute(id: string, input: readonly Respelling[], o: RespellOptions): Promise { const respellings = cleanRespellings(input); if (respellings.length === 0) throw new ArticleRegistryError("no respelling: give at least one heard form and a reading"); const notes: string[] = []; const current = await currentIteration(id, o.paths); const n = o.iteration ?? current.reportFrom ?? current.report ?? null; if (n !== null && !(await readIteration(id, n, o.paths))) { throw new ArticleRegistryError(`"${id}" has no iteration i${n}`); } const writes: Computed["writes"] = []; const projectDir = n !== null ? projectOf(o.projectsRoot, id, n) : null; if (n !== null) { const file = iterationFile(o.paths, id, n, "report.json"); const raw = await readJson(file); if (raw) { asReport(raw, id, file); // The raw document, not the parsed one: the file keeps its own key order. const r = respellReport(raw as Report, respellings); writes.push({ target: { kind: "iteration-report", file, changes: r.changes }, data: r.report, projectDir }); } else notes.push(`i${n} has no report.json of its own`); } const articleIsN = n === null || current.reportFrom === n || current.report === n; const aFile = articleFile(o.paths, id); const aRaw = await readJson(aFile); if (aRaw && articleIsN) { asReport(aRaw, id, aFile); const r = respellReport(aRaw as Report, respellings); writes.push({ target: { kind: "article-report", file: aFile, changes: r.changes }, data: r.report, projectDir }); } else if (aRaw) { notes.push(`the article's report.json is another iteration's (i${current.reportFrom ?? current.report}); not changed`); } else if (n === null) { throw new ArticleRegistryError(`"${id}" has no report.json and no iterations`); } if (projectDir) { // The copy of the report the chain put beside the manifest ("what the cut reads // beside its manifest", umtool chain-run's manifest step). const pFile = path.join(projectDir, "report.json"); const pRaw = await readJson(pFile); if (pRaw && typeof pRaw === "object" && !Array.isArray(pRaw)) { const r = respellReport(pRaw as Report, respellings); writes.push({ target: { kind: "project-report", file: pFile, changes: r.changes }, data: r.report, projectDir }); } const file = path.join(projectDir, "video.manifest.json"); const raw = await readJson(file); if (raw && typeof raw === "object" && !Array.isArray(raw)) { const r = respellManifest(raw as Record, respellings); writes.push({ target: { kind: "video-manifest", file, changes: r.changes }, data: r.manifest, projectDir }); if (r.changes.length) notes.push("the video shows the new words once it is rebuilt (its burned-in quotes and cards)"); } } const targets = writes.map((w) => w.target); return { plan: { article: id, iteration: n, respellings, targets, total: targets.reduce((s, t) => s + t.changes.length, 0), notes }, writes, }; } export async function planRespell(id: string, respellings: readonly Respelling[], o: RespellOptions): Promise { return (await compute(id, respellings, o)).plan; } const stampOf = (d: Date) => d.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z"); // Apply: the plan is computed again (the files may have moved since the preview), // every changed file backed up, then written. Answers the plan applied and the backups. export async function applyRespell( id: string, respellings: readonly Respelling[], o: RespellOptions, now: Date = new Date(), ): Promise<{ plan: RespellPlan; backups: string[] }> { const { plan, writes } = await compute(id, respellings, o); const backups: string[] = []; const stamp = stampOf(now); for (const w of writes) { // A target with no change still gains `respellings` (the checks need them), so // every target is written; a target that already carries them and changes // nothing is left alone. const before = await readFile(w.target.file, "utf8"); const after = `${JSON.stringify(w.data, null, 2)}\n`; if (before === after || JSON.stringify(JSON.parse(before)) === JSON.stringify(w.data)) continue; // Never beside the article in the store (a stray file there is the export's to // trip on): the iteration's project, or the article's folder under the projects root. const backupDir = path.join(w.projectDir ?? path.join(o.projectsRoot, id), "revisions"); await mkdir(backupDir, { recursive: true }); const name = w.target.kind === "video-manifest" ? "manifest.json" : `${w.target.kind}.json`; const backup = path.join(backupDir, `${stamp}-before-respell.${name}`); await copyFile(w.target.file, backup); backups.push(backup); if (w.target.kind === "iteration-report") { await writeIterationFile(id, plan.iteration!, "report.json", w.data as object, o.paths); } else if (w.target.kind === "article-report") { await writeArticle(w.data, { paths: o.paths, keepAudience: true, keepVideo: true }); } else { // The project's own files (the manifest, the report copy): not the store's. await writeFile(w.target.file, after, "utf8"); } } return { plan, backups }; } // The plan as lines a person reads: per file, each changed field, and in it each // changed run of words with a few words either side, «before» → «after». export function formatRespellPlan(plan: RespellPlan): string[] { const out: string[] = []; const rs = plan.respellings.map((r) => `${r.heard.map((h) => `"${h}"`).join(", ")} → "${r.reads}"${r.bracket ? " (bracketed)" : ""}`); out.push(`respell "${plan.article}"${plan.iteration !== null ? ` i${plan.iteration}` : ""}: ${rs.join("; ")}`); for (const t of plan.targets) { out.push(""); out.push(`${t.kind} ${t.file}: ${t.changes.length} change(s)${t.changes.length ? "" : " (gains respellings only)"}`); for (const c of t.changes) { out.push(` ${c.at}`); for (const h of wordHunks(c.before, c.after)) out.push(` ${h}`); } } for (const n of plan.notes) out.push(`note: ${n}`); out.push(""); out.push(`${plan.total} change(s) in ${plan.targets.filter((t) => t.changes.length).length} file(s)`); return out; } const CONTEXT_WORDS = 5; // Each run of words that differs, as "…context «old» → «new» context…" (a word-level // longest common subsequence: the texts are a field each, a few hundred words at most). export function wordHunks(before: string, after: string): string[] { const a = before.split(/\s+/).filter(Boolean); const b = after.split(/\s+/).filter(Boolean); const L: number[][] = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0)); for (let i = a.length - 1; i >= 0; i--) for (let j = b.length - 1; j >= 0; j--) L[i][j] = a[i] === b[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]); // Walk: equal words, or a hunk of removed/added words. type Op = { eq: true; w: string; i: number } | { eq: false; del: string[]; add: string[]; i: number }; const ops: Op[] = []; let i = 0; let j = 0; while (i < a.length || j < b.length) { if (i < a.length && j < b.length && a[i] === b[j]) { ops.push({ eq: true, w: a[i], i }); i++; j++; continue; } const del: string[] = []; const add: string[] = []; const at = i; while ((i < a.length || j < b.length) && !(i < a.length && j < b.length && a[i] === b[j])) { if (j >= b.length || (i < a.length && L[i + 1][j] >= L[i][j + 1])) del.push(a[i++]); else add.push(b[j++]); } ops.push({ eq: false, del, add, i: at }); } const hunks: string[] = []; ops.forEach((op, k) => { if (op.eq) return; const left: string[] = []; for (let x = k - 1; x >= 0 && left.length < CONTEXT_WORDS && ops[x].eq; x--) left.unshift((ops[x] as { w: string }).w); const right: string[] = []; for (let x = k + 1; x < ops.length && right.length < CONTEXT_WORDS && ops[x].eq; x++) right.push((ops[x] as { w: string }).w); const more = (n: number) => (n > 0 ? "…" : ""); hunks.push( `${more(k - left.length)}${left.join(" ")} «${op.del.join(" ")}» → «${op.add.join(" ")}» ${right.join(" ")}${more(ops.length - 1 - k - right.length)}`.replace(/\s+/g, " ").trim(), ); }); return hunks; }