commit 85f77f737a2c31487c7dc23912a9f74d72787f02
parent f62cd28683d985991b24b8112516efc318bf6cdc
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 17 Nov 2026 17:01:21 -0500
reads undo never takes a later edit back; Everywhere's undo restores the entry it changed (review 1, MUST 2, SHOULD 4)
MUST 2: other writers keep one undo point per op for two minutes, so a write after a replace (a
re-read landing) could leave the replace's undo point the newest -- and "Undo the replace" then
restored the pre-replace draft and dropped that write. The replace's record (narration/reads/
replaces.json) keeps the draft's token and its bytes' hash as the replace left them; the undo is
refused, in a sentence, unless the draft is still exactly that and its undo point the newest
(replaceUndoState, which the page reads to offer Undo only while it applies). The token is read
before the plan, so a write between the two is refused.
SHOULD 4: Everywhere over an existing entry changed its spoken form, and its undo was `posts say
remove`, which deleted the entry and its note (and threw with a case and a no-case entry). The
record keeps the entry it replaced; undoSayOnly puts it back whole, or removes only the entry it
added, by its identity. Tests: the scenario of MUST 2; both cases of SHOULD 4 (each failing on the
code before).
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
2 files changed, 140 insertions(+), 10 deletions(-)
diff --git a/umtool/lib/report/readsReplace.mjs b/umtool/lib/report/readsReplace.mjs
@@ -19,6 +19,11 @@ import { LEGACY_EDIT_TEXT, findPattern, matchesIn, projectReads, readsContext, r
import { AUTO_SNAPSHOT_PREFIX, StructureRefused, cardNarrationIn, manifestToken, postItemIn, postNarrationIn, structuralEdit, undoStructural } from "./manifest.mjs";
import { screenLineSaid, screensOf } from "umtool-report-to-video/post-screens";
import { lexiconKey, normalizeLexicon } from "umtool-report-to-video/post-say";
+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { createHash } from "node:crypto";
+import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
+import { withNotesLock } from "../annotations/store.mjs";
export const REPLACE_OP = "reads-replace";
export const UNDO_LABEL = `${AUTO_SNAPSHOT_PREFIX}${REPLACE_OP}`;
@@ -131,28 +136,82 @@ export async function replacePlan(project, from, to, { matchCase = false, word =
return { scope: "reads", find: from, to, matchCase, word, lines, skipped, notes, refused, matches, ctx: c };
}
+/** The replaces made here, newest last: `<project>/narration/reads/replaces.json` -- what an undo checks against. */
+export const REPLACES_FILE = "narration/reads/replaces.json";
+const replacesPath = (dir) => path.join(/* turbopackIgnore: true */ dir, ...REPLACES_FILE.split("/"));
+/** The draft as it is on disk, hashed: what a replace left, compared byte for byte (an undo restores bytes, not times). */
+const draftSha = async (dir) => createHash("sha1").update(await readFile(path.join(/* turbopackIgnore: true */ dir, "video.manifest.json")).catch(() => Buffer.alloc(0))).digest("hex");
+
+/** The records, oldest first: `{ scope: "reads", at, find, to, token, snapshot }` | `{ scope: "say", at, entry, was }`. */
+export async function readReplaces(dir) {
+ try {
+ const j = JSON.parse(await readFile(replacesPath(dir), "utf8"));
+ return Array.isArray(j?.records) ? j.records.filter(isObj) : [];
+ } catch {
+ return [];
+ }
+}
+
+async function withReplaces(dir, fn) {
+ const file = replacesPath(dir);
+ await mkdir(path.dirname(file), { recursive: true });
+ return withNotesLock(file, async () => {
+ const { records, result } = await fn(await readReplaces(dir));
+ const tmp = tmpPathFor(file);
+ await writeFile(tmp, `${JSON.stringify({ version: 1, records: records.slice(-20) }, null, 1)}\n`);
+ await rename(tmp, file);
+ return result;
+ });
+}
+
/**
- * THESE READS, APPLIED: the plan's lines in one structural write (its own undo point). Refused whole when any item
- * is refused (the preview says which), or when nothing would change. Returns `{ plan, result }`.
+ * THESE READS, APPLIED: the plan's lines in one structural write (its own undo point), against the manifest's token
+ * read BEFORE the plan (a write between the two is refused, never laid over). Refused whole when any item is refused
+ * (the preview says which), or when nothing would change. The manifest's token after it is kept with the replace's
+ * record, and the draft's bytes hashed: Undo the replace is offered only while the draft is still exactly what it left. Returns `{ plan, result }`.
*/
export async function applyReplace(project, from, to, o = {}) {
+ const token = o.token ?? (await manifestToken(project.dir));
const plan = await replacePlan(project, from, to, o);
if (Object.keys(plan.refused).length) throw new ReplaceError(`refused: ${Object.entries(plan.refused).map(([i, errs]) => `${i}: ${errs.join("; ")}`).join(" ยท ")} -- leave those reads out (--only) or say it another way`);
if (!plan.lines.length) throw new ReplaceError(plan.matches ? `nothing to rewrite: every match is in a read These reads does not change (${plan.skipped.map((s) => s.id).join(", ")})` : `"${from}" is in no read's spoken text`);
const { withEditNotes } = await import("./edit-guard.mjs");
- const token = o.token ?? (await manifestToken(project.dir));
const { result, editNotes } = await withEditNotes(project, async () => structuralEdit(project.dir, REPLACE_OP, token, (m) => replaceReadsIn(m, plan.lines), { snapshotEvery: 0 }));
+ const sha = await draftSha(project.dir);
+ await withReplaces(project.dir, (records) => ({ records: [...records, { scope: "reads", at: new Date().toISOString(), find: from, to, lines: plan.lines.map((l) => l.id), token: result.token ?? null, sha, snapshot: result.snapshot?.rel ?? null }], result: null }));
return { plan, result, editNotes };
}
-/** Take back the newest replace: refused unless the newest undo point IS a reads-replace. */
-export async function undoReplace(project, { token = null } = {}) {
+/**
+ * Whether the newest replace can be taken back now: `{ scope, available, why }` (null: none was made here). A replace
+ * of These reads only while the draft's token is the one it left (nothing written since -- a re-read landing, a bench
+ * edit) and its undo point is the newest; Everywhere only while the entry is still as it set it.
+ */
+export async function replaceUndoState(project) {
+ const last = (await readReplaces(project.dir)).at(-1);
+ if (!last) return null;
+ if (last.scope === "say") {
+ const { readLexicon } = await import("./postSay.mjs");
+ const now = (await readLexicon(project.dir)).find((x) => lexiconKey(x) === lexiconKey(last.entry));
+ return now && now.say === last.entry.say
+ ? { scope: "say", available: true, why: null, entry: last.entry, was: last.was ?? null }
+ : { scope: "say", available: false, why: `the entry for "${last.entry.word}" changed since (umtool posts say ${project.id} ls)`, entry: last.entry, was: last.was ?? null };
+ }
+ if ((await draftSha(project.dir)) !== last.sha) return { scope: "reads", available: false, why: "the draft changed after the replace (a re-read landed, or another edit): taking the replace back now would take that back too -- undo those from where they were made" };
const { listSnapshots } = await import("./snapshots.mjs");
const top = (await listSnapshots(project.dir)).find((s) => !s.legacy && s.label?.startsWith(AUTO_SNAPSHOT_PREFIX));
- if (!top) throw new ReplaceError("nothing to undo: no undo point in revisions/");
- if (top.label !== UNDO_LABEL) throw new ReplaceError(`the newest change is not a replace (${top.label.slice(AUTO_SNAPSHOT_PREFIX.length)}): take it back first (umtool timeline ${project.id} undo), or undo from the bench`);
+ if (!top || top.label !== UNDO_LABEL) return { scope: "reads", available: false, why: "its undo point is no longer the newest" };
+ return { scope: "reads", available: true, why: null };
+}
+
+/** Take back the newest replace of These reads: refused, in a sentence, unless replaceUndoState says it may be. */
+export async function undoReplace(project, { token = null } = {}) {
+ const st = await replaceUndoState(project);
+ if (!st || st.scope !== "reads") throw new ReplaceError("nothing to undo: the newest replace made here is not one of These reads");
+ if (!st.available) throw new ReplaceError(`not undone: ${st.why}`);
const { withEditNotes } = await import("./edit-guard.mjs");
const { result } = await withEditNotes(project, async () => undoStructural(project.dir, { token }));
+ await withReplaces(project.dir, (records) => ({ records: records.slice(0, -1), result: null }));
return result;
}
@@ -175,13 +234,38 @@ export async function sayOnlyPlan(project, from, to, { matchCase = false, word =
const re = findPattern(from, { matchCase, word: true });
const cards = before.rows.filter((r) => r.kind === "card" && matchesIn(r.spoken, re).length).map((r) => r.id);
const matches = before.rows.reduce((a, r) => a + matchesIn(r.spoken, re).length, 0);
- return { scope: "say", entry, was: had ? had.say : null, stale: newly.map((r) => ({ id: r.id, kind: r.kind, item: r.item })), cards, matches, ctx: c };
+ return { scope: "say", entry, was: had ? had.say : null, wasEntry: had ? { ...had } : null, stale: newly.map((r) => ({ id: r.id, kind: r.kind, item: r.item })), cards, matches, ctx: c };
}
-/** EVERYWHERE, APPLIED: the entry through `posts say add`'s writer. Returns `{ plan, result }`. */
+/**
+ * EVERYWHERE, APPLIED: the entry through `posts say add`'s writer (an entry of the same word changes its spoken form).
+ * What it replaced -- the whole entry, its note too -- is kept with the record, so its undo puts that back.
+ * Returns `{ plan, result }`.
+ */
export async function applySayOnly(project, from, to, o = {}) {
const plan = await sayOnlyPlan(project, from, to, o);
const { updateLexicon } = await import("./postSay.mjs");
const result = await updateLexicon(project.dir, { add: { word: plan.entry.word, say: plan.entry.say, case: plan.entry.case === true, item: null, note: o.note ?? null } });
+ await withReplaces(project.dir, (records) => ({ records: [...records, { scope: "say", at: new Date().toISOString(), entry: { word: result.entry.word, say: result.entry.say, ...(result.entry.case ? { case: true } : {}) }, was: plan.wasEntry }], result: null }));
return { plan, result };
}
+
+/**
+ * EVERYWHERE, TAKEN BACK: the entry it changed back to what it was (its spoken form, its note), or the entry it added
+ * removed -- that one entry, by its identity (word, case, item), never another of the same word. Refused when the
+ * entry changed since.
+ */
+export async function undoSayOnly(project) {
+ const st = await replaceUndoState(project);
+ if (!st || st.scope !== "say") throw new ReplaceError("nothing to take back: the newest replace made here is not an Everywhere");
+ if (!st.available) throw new ReplaceError(`not taken back: ${st.why}`);
+ const { readLexicon, updateLexicon } = await import("./postSay.mjs");
+ let result;
+ if (st.was) result = await updateLexicon(project.dir, { add: { word: st.was.word, say: st.was.say, case: st.was.case === true, item: st.was.item ?? null, note: st.was.note ?? null } });
+ else {
+ const at = (await readLexicon(project.dir)).findIndex((x) => lexiconKey(x) === lexiconKey(st.entry));
+ result = await updateLexicon(project.dir, { remove: at });
+ }
+ await withReplaces(project.dir, (records) => ({ records: records.slice(0, -1), result: null }));
+ return { restored: st.was ?? null, removed: st.was ? null : st.entry, lexicon: result.lexicon };
+}
diff --git a/umtool/lib/report/readsReplace.test.mjs b/umtool/lib/report/readsReplace.test.mjs
@@ -61,7 +61,7 @@ test("These reads: a post's script, a screen line (said-as created), a card -- o
await undoReplace(p);
assert.deepEqual(await readManifestOf(p), m0);
await updatePostNarration(p.dir, "p-1", { approved: true }, { token: await manifestToken(p.dir) });
- await assert.rejects(undoReplace(p), /the newest change is not a replace \(post-narration\)/);
+ await assert.rejects(undoReplace(p), /nothing to undo: the newest replace made here is not one of These reads/);
});
test("These reads: the preview says what goes (approval), what the build would refuse, and only the ticked reads change", async () => {
@@ -96,3 +96,49 @@ test("Everywhere: a pronunciation entry -- previews the reads it makes stale and
// The same word again changes what is said for it (the writer's rule): `was` says so.
assert.equal((await sayOnlyPlan(p, "pier", "pee-er", o(p))).was, "peer");
});
+
+// ---------------------------------------------------------------------------
+// REVIEW 1, MUST 2: Undo the replace never takes a later edit back with it. Other writers keep one undo point per op
+// for two minutes, so a write after a replace may leave the replace's undo point the newest: the undo is refused
+// unless the draft is still exactly what the replace left (its token, kept with the replace's record).
+// ---------------------------------------------------------------------------
+
+test("MUST 2: a bench write before the replace, the replace, a re-read landing after it with no undo point of its own -- the undo is refused", async () => {
+ const p = await readsProject(ROOT, "undo-after");
+ const write = async (patch) => updatePostNarration(p.dir, "p-1", patch, { token: await manifestToken(p.dir) });
+ await write({ lead: 0.3 }); // a bench edit: its op's undo point (post-narration)
+ await applyReplace(p, "north", "northern", o(p));
+ const { replaceUndoState } = await import("./readsReplace.mjs");
+ assert.equal((await replaceUndoState(p)).available, true);
+ // A re-read lands: the same op as the bench edit, inside its two minutes -- no undo point of its own.
+ const m = await readManifestOf(p);
+ await write({ addTake: { ...m.timeline[0].narration.takes[0], file: "narration/posts/1/take-2.orpheus-tara.wav", script: m.timeline[0].narration.script }, keepPick: true });
+ const st = await replaceUndoState(p);
+ assert.equal(st.available, false);
+ assert.match(st.why, /the draft changed after the replace/);
+ await assert.rejects(undoReplace(p), /not undone: the draft changed after the replace/);
+ assert.equal((await readManifestOf(p)).timeline[0].narration.takes.length, 2, "the re-read is still there");
+});
+
+// REVIEW 1, SHOULD 4: Everywhere's undo puts back the entry it changed (its spoken form and its note), and removes only
+// the entry it added -- never another of the same word.
+test("SHOULD 4: an Everywhere over an existing entry is taken back to it; with a case and a no-case entry, only its own goes", async () => {
+ const p = await readsProject(ROOT, "say-undo");
+ const { updateLexicon } = await import("./postSay.mjs");
+ const { undoSayOnly } = await import("./readsReplace.mjs");
+ await updateLexicon(p.dir, { add: { word: "pier", say: "peer", note: "the harbour's word" } });
+ const plan = await sayOnlyPlan(p, "pier", "pee-er", o(p));
+ assert.equal(plan.was, "peer");
+ await applySayOnly(p, "pier", "pee-er", o(p));
+ assert.deepEqual(await readLexicon(p.dir), [{ word: "pier", say: "pee-er" }]);
+ await undoSayOnly(p);
+ assert.deepEqual(await readLexicon(p.dir), [{ word: "pier", say: "peer", note: "the harbour's word" }]);
+ // A case entry and a no-case one of the same word: the undo removes only the one Everywhere added.
+ await updateLexicon(p.dir, { add: { word: "Pier", say: "PEER", case: true } });
+ await applySayOnly(p, "north", "nor-th", o(p));
+ await undoSayOnly(p);
+ assert.deepEqual((await readLexicon(p.dir)).map((x) => x.word), ["pier", "Pier"]);
+ await applySayOnly(p, "pier", "pier two", o(p, { matchCase: false }));
+ await undoSayOnly(p);
+ assert.deepEqual(await readLexicon(p.dir), [{ word: "pier", say: "peer", note: "the harbour's word" }, { word: "Pier", say: "PEER", case: true }]);
+});