Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit fa3641ad8ab694a025c46d4bac46280335b5ff7c
parent b5172fe49b1f4bf2d1bc78f3d88720a077795628
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 17 Nov 2026 15:35:19 -0500

readsReplace.mjs: Replace over a video's reads in two stated scopes, previewed, never synthesizing

These reads: the spoken text of the matched reads rewritten through each kind's writer in ONE
structural write, always its own undo point (auto-before-reads-replace) -- a post's script
(postNarrationIn, marked for reading), a screen line's said-as (created from the line as read when
it has none), a card's narration (cardNarrationIn); a parent, the quoted or a linked post is listed
"said as shown: only Everywhere changes this", a recorded read is never replaced. The preview says
what the build would refuse (item by item, on a copy), that a changed post loses its approval as a
new script does today, a card's review verdict given on the old words, and an item read before the
rule. undoReplace takes back the newest replace and refuses anything else.
Everywhere, from now on: a pronunciation entry through `posts say add`'s writer, previewed with the
reads it makes stale and the cards it does not reach; whole words only.
Tests: per kind, shown text and drawn cards identical (the reading pin's drawn()), undo, refusal.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Aumtool/lib/report/readsReplace.mjs | 187+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/readsReplace.test.mjs | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 284 insertions(+), 0 deletions(-)

diff --git a/umtool/lib/report/readsReplace.mjs b/umtool/lib/report/readsReplace.mjs @@ -0,0 +1,187 @@ +// REPLACE OVER A VIDEO's READS (lane reads-find; operator ruling 3: an edit changes only what is SPOKEN, never what +// is shown), in two scopes, each previewed before it is applied and neither synthesizing anything: +// +// These reads the spoken text of the matched reads rewritten, in ONE structural write (one undo point, +// `auto-before-reads-replace`, always its own): a post's script (postNarrationIn, marked +// for reading as Save script marks it), a screen line's "said as" (`screens[j].saidAs`, +// created from the line as read when it has none -- the line as shown untouched), a card's +// narration (cardNarrationIn). A parent, the quoted or a linked post has no spoken-only +// words: listed, not changed ("said as shown: only Everywhere changes this"); a recorded +// read is yours and is never replaced. +// Everywhere, from now on a pronunciation entry (postSay.mjs updateLexicon, `umtool posts say add`'s writer): every +// read of a post, present and future, says it that way. Whole words only (the lexicon's +// rule), and never a card's narration (cards are not said through the lexicon). +// +// Either way the reads that changed show as stale (reads.mjs); a re-read is a press (readsQueue.mjs). +// +// Plain ESM: the CLI runs it under bare node. +import { LEGACY_EDIT_TEXT, findPattern, matchesIn, projectReads, readsContext, replaceIn } from "./reads.mjs"; +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"; + +export const REPLACE_OP = "reads-replace"; +export const UNDO_LABEL = `${AUTO_SNAPSHOT_PREFIX}${REPLACE_OP}`; +/** Said where Everywhere is offered with Whole word off. */ +export const SAY_WHOLE_WORDS = "Everywhere, from now on matches whole words only (a pronunciation entry): turn Whole word on"; +/** Said for a card a pronunciation entry does not reach. */ +export const SAY_NOT_CARDS = "cards are not said through the lexicon: use These reads for a card"; + +export class ReplaceError extends Error { + constructor(message) { + super(message); + this.name = "ReplaceError"; + } +} + +const clone = (v) => JSON.parse(JSON.stringify(v)); +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); + +/** What each kind's replace does to a read whose spoken text is still its shown text. */ +function createsNote(r) { + if (!r.shownSpoken) return null; + if (r.kind === "screen") return "creates its said-as (the line as shown is untouched)"; + return "creates its script from the post's words (the post as shown is untouched)"; +} + +/** The writes of a replace, in `m` (inside a write or on a copy): `lines` grouped by item. */ +export function replaceReadsIn(m, lines) { + const byItem = new Map(); + for (const l of lines) byItem.set(l.item, [...(byItem.get(l.item) ?? []), l]); + for (const [item, ls] of byItem) { + const e = (m.timeline ?? []).find((x) => x?.id === item); + if (!e) throw new ReplaceError(`no item ${item} in the cut`); + const cardLine = ls.find((l) => l.kind === "card"); + if (cardLine) { + cardNarrationIn(m, item, { text: cardLine.after }); + continue; + } + const scriptLine = ls.find((l) => l.kind === "post" || (l.kind === "thread" && l.role === "post")); + if (scriptLine) postNarrationIn(m, item, { script: scriptLine.after }, { forReading: true }); + const lineLines = ls.filter((l) => l.kind === "screen"); + if (lineLines.length) { + const next = clone(screensOf(e)); + for (const l of lineLines) { + const [, id, n] = /^screen:([a-z0-9-]+):(\d+)$/.exec(l.role) ?? []; + const sc = next.find((x) => x.id === id); + if (!sc) throw new ReplaceError(`${item} has no screen ${id}`); + const sa = isObj(sc.saidAs) ? { ...sc.saidAs } : {}; + // Back to the line as read: no said-as (its own words again); else its said-as. + if (l.after.replace(/\s+/g, " ").trim() === screenLineSaid(sc, Number(n)).replace(/\s+/g, " ").trim()) delete sa[n]; + else sa[n] = l.after; + if (Object.keys(sa).length) sc.saidAs = sa; + else delete sc.saidAs; + } + postItemIn(m, item, { screens: next }); + } + } + return { items: [...byItem.keys()] }; +} + +/** + * THESE READS, PREVIEWED: `{ scope: "reads", find, to, lines: [{ id, kind, item, role, before, after, storedAt, + * creates }], skipped: [{ id, why }], notes: { <item>: [sentence…] }, refused: { <item>: [error…] }, matches }`. + * `only`: the read ids to change (the rest of the matches left as they are). + */ +export async function replacePlan(project, from, to, { matchCase = false, word = false, only = null, ctx = null, reportsRoot = undefined } = {}) { + if (typeof from !== "string" || !from.trim()) throw new ReplaceError("replace takes the words to find"); + if (typeof to !== "string") throw new ReplaceError("replace takes what to say instead"); + const c = ctx ?? (await readsContext(project, reportsRoot ? { reportsRoot } : {})); + const { rows } = await projectReads(project, { ctx: c }); + const re = findPattern(from, { matchCase, word }); + const keep = only ? new Set(only) : null; + const lines = []; + const skipped = []; + let matches = 0; + for (const r of rows) { + const hits = matchesIn(r.spoken, re); + if (!hits.length || (keep && !keep.has(r.id))) continue; + matches += hits.length; + if (!r.editable) { + skipped.push({ id: r.id, why: r.why ?? "not rewritten here" }); + continue; + } + lines.push({ id: r.id, kind: r.kind, item: r.item, role: r.role, before: r.spoken, after: replaceIn(r.spoken, re, to), storedAt: r.storedAt, creates: createsNote(r) }); + } + const notes = {}; + const say = (item, s) => { + notes[item] = [...(notes[item] ?? []), s]; + }; + const m = c.manifest; + let review = null; + for (const item of new Set(lines.map((l) => l.item))) { + const e = m.timeline.find((x) => x?.id === item); + const row = rows.find((r) => r.item === item); + if (e?.type === "post" && e.narration?.approved && lines.some((l) => l.item === item && (l.kind === "post" || l.role === "post"))) say(item, "its approval goes, as a new script takes it away (Save script does the same)"); + if (row?.legacy) say(item, LEGACY_EDIT_TEXT); + if (e?.type === "card") { + review ??= await (await import("umtool-report-to-video/narration-review")).readNarrationReview(project.dir).catch(() => null); + if (review?.rows?.[item]?.verdict) say(item, `its narration review verdict (${review.rows[item].verdict}) was given on the old words`); + } + } + // What the build would refuse, item by item, on a copy (a said-as saying what a screen masks, …). + const refused = {}; + for (const item of new Set(lines.map((l) => l.item))) { + try { + replaceReadsIn(clone(m), lines.filter((l) => l.item === item)); + } catch (err) { + refused[item] = err instanceof StructureRefused ? err.errors : [err instanceof Error ? err.message : String(err)]; + } + } + return { scope: "reads", find: from, to, matchCase, word, lines, skipped, notes, refused, matches, ctx: c }; +} + +/** + * 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 }`. + */ +export async function applyReplace(project, from, to, o = {}) { + 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 })); + 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 } = {}) { + 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`); + const { withEditNotes } = await import("./edit-guard.mjs"); + const { result } = await withEditNotes(project, async () => undoStructural(project.dir, { token })); + return result; +} + +/** + * EVERYWHERE, FROM NOW ON, PREVIEWED: `{ scope: "say", entry, was, stale: [{ id, kind, item }], cards: [ids], + * matches }` -- the entry it adds (or changes: `was` its spoken form before), every read it would make stale, and + * the cards it does not reach. Refused with Whole word off. + */ +export async function sayOnlyPlan(project, from, to, { matchCase = false, word = true, ctx = null, reportsRoot = undefined } = {}) { + if (!word) throw new ReplaceError(SAY_WHOLE_WORDS); + if (typeof from !== "string" || !from.trim() || typeof to !== "string" || !to.trim()) throw new ReplaceError("Everywhere takes the words to find and how to say them"); + const c = ctx ?? (await readsContext(project, reportsRoot ? { reportsRoot } : {})); + const before = await projectReads(project, { ctx: c }); + const entry = { word: from.replace(/\s+/g, " ").trim(), say: to.trim(), ...(matchCase ? { case: true } : {}) }; + const had = c.lexicon.find((x) => lexiconKey(x) === lexiconKey(entry)) ?? null; + const lexicon = normalizeLexicon([...c.lexicon.filter((x) => lexiconKey(x) !== lexiconKey(entry)), entry]); + const after = await projectReads(project, { ctx: { ...c, lexicon, red: { ...(c.red ?? {}), say: lexicon } } }); + const was = new Map(before.rows.map((r) => [r.id, r])); + const newly = after.rows.filter((r) => (r.state === "stale" || r.state === "unpicked") && (r.because.includes("words") || r.because.includes("lexicon")) && !(was.get(r.id)?.because ?? []).some((b) => b === "words" || b === "lexicon")); + 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 }; +} + +/** EVERYWHERE, APPLIED: the entry through `posts say add`'s writer. 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 } }); + return { plan, result }; +} diff --git a/umtool/lib/report/readsReplace.test.mjs b/umtool/lib/report/readsReplace.test.mjs @@ -0,0 +1,97 @@ +// REPLACE OVER A VIDEO's READS (lane reads-find, readsReplace.mjs): These reads rewrites the SPOKEN text of each kind +// through its own writer in one undo point, the shown text untouched (a post's script, a screen line's said-as made +// when it has none, a card's narration; a context piece and a recorded read listed, never changed); undo restores +// every line; Everywhere adds a pronunciation entry, previews what it makes stale, never reaches a card, and is whole +// words only. Neither synthesizes. Temp dirs, invented people. +import assert from "node:assert/strict"; +import { mkdtemp, readdir, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { cardText } from "umtool-report-to-video/post-item"; +import { projectReads } from "./reads.mjs"; +import { ReplaceError, SAY_WHOLE_WORDS, applyReplace, applySayOnly, replacePlan, sayOnlyPlan, undoReplace } from "./readsReplace.mjs"; +import { manifestToken, updatePostNarration } from "./manifest.mjs"; +import { readLexicon } from "./postSay.mjs"; +import { readManifestOf, readsProject } from "./reads.fixtures.mjs"; +import { drawn } from "../../report-to-video/post-reading-pin.fixtures.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-reads-replace-")); +after(() => rm(ROOT, { recursive: true, force: true })); +delete process.env.UMTOOL_CAST_FILE; +const o = (p, x = {}) => ({ reportsRoot: p.root, ...x }); +/** What a manifest SHOWS: every item with its spoken-only fields left out (narration, a screen's saidAs). */ +const shown = (m) => m.timeline.map(({ narration: _n, ...e }) => ({ ...e, ...(Array.isArray(e.screens) ? { screens: e.screens.map(({ saidAs: _s, ...sc }) => sc) } : {}) })); +const takeFiles = async (p) => (await readdir(path.join(p.dir, "narration", "posts"), { recursive: true })).filter((f) => f.endsWith(".wav")).sort(); + +test("These reads: a post's script, a screen line (said-as created), a card -- one undo point; shown text and drawn card identical; nothing synthesized", async () => { + const p = await readsProject(ROOT, "a"); + const m0 = await readManifestOf(p); + const files0 = await takeFiles(p); + const plan = await replacePlan(p, "north", "northern", o(p)); + assert.deepEqual(plan.lines.map((l) => [l.id, l.creates]), [["p-1", null], ["c-1", null]]); + assert.deepEqual(plan.skipped.map((s) => s.id), ["p-3"], "a recorded read is never replaced"); + // A screen line with no said-as: created from the line as read. + const tolls = await replacePlan(p, "tolls", "toll charges", o(p)); + assert.deepEqual(tolls.lines.map((l) => [l.id, l.before, l.after, l.creates]), [["p-2/screen:s1:0", "Are the tolls going up again?", "Are the toll charges going up again?", "creates its said-as (the line as shown is untouched)"]]); + // A context piece: listed, not changed. + const bridge = await replacePlan(p, "Bridge works", "The bridge works", o(p)); + assert.deepEqual(bridge.lines, []); + assert.match(bridge.skipped[0].why, /said as shown: only Everywhere changes this/); + + await applyReplace(p, "north", "northern", o(p)); + await applyReplace(p, "tolls", "toll charges", o(p)); + const m1 = await readManifestOf(p); + assert.match(m1.timeline[0].narration.script, /northern pier/); + assert.equal(m1.timeline[0].narration.forReading, true, "marked for reading by the one writer"); + assert.equal(m1.timeline[1].screens[0].saidAs["0"], "Are the toll charges going up again?"); + assert.equal(m1.timeline[3].narration.text, "Six months later, the northern pier reopened."); + // RULING 3: what is shown is byte-identical, and so is what the cards draw. + assert.deepEqual(shown(m1), shown(m0)); + assert.equal(cardText(m1.timeline[0]), cardText(m0.timeline[0])); + for (const k of [0, 1]) assert.deepEqual(drawn(m1.timeline[k]), drawn(m0.timeline[k]), m0.timeline[k].id); + assert.deepEqual(await takeFiles(p), files0, "a replace never synthesizes"); + // The changed reads are stale; the others are not. + const by = Object.fromEntries((await projectReads(p, o(p))).rows.map((r) => [r.id, r.state])); + assert.deepEqual([by["p-1"], by["p-2/screen:s1:0"], by["c-1"], by["p-2/screen:s1:1"], by["p-3"]], ["stale", "stale", "stale", "fresh", "recorded"]); + // Undo takes back the newest replace -- every line of it -- and only a replace. + await undoReplace(p); + assert.equal("saidAs" in (await readManifestOf(p)).timeline[1].screens[0], false); + 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\)/); +}); + +test("These reads: the preview says what goes (approval), what the build would refuse, and only the ticked reads change", async () => { + const p = await readsProject(ROOT, "b"); + await updatePostNarration(p.dir, "p-1", { approved: true }, { token: await manifestToken(p.dir) }); + const plan = await replacePlan(p, "north", "northern", o(p)); + assert.match(plan.notes["p-1"].join(" "), /its approval goes, as a new script takes it away/); + // A said-as that says a number the card masks is refused, and the whole write with it. + const bad = await replacePlan(p, "this year", "on 5551234567", o(p)); + assert.ok(bad.refused["p-2"]?.some((x) => /number/.test(x)), JSON.stringify(bad.refused)); + await assert.rejects(applyReplace(p, "this year", "on 5551234567", o(p)), ReplaceError); + // --only: the card alone. + await applyReplace(p, "north", "northern", o(p, { only: ["c-1"] })); + const m = await readManifestOf(p); + assert.match(m.timeline[0].narration.script, /the north pier/); + assert.equal(m.timeline[0].narration.approved, true); + assert.match(m.timeline[3].narration.text, /northern pier/); +}); + +test("Everywhere: a pronunciation entry -- previews the reads it makes stale and the cards it does not reach; whole words only", async () => { + const p = await readsProject(ROOT, "say"); + await assert.rejects(sayOnlyPlan(p, "nort", "x", o(p, { word: false })), (e) => e.message === SAY_WHOLE_WORDS); + const plan = await sayOnlyPlan(p, "pier", "peer", o(p)); + assert.deepEqual(plan.stale.map((s) => s.id), ["p-1"], "the recorded read never; the card is not said through the lexicon"); + assert.deepEqual(plan.cards, ["c-1"]); + const m0 = await readManifestOf(p); + await applySayOnly(p, "pier", "peer", o(p)); + assert.deepEqual(await readLexicon(p.dir), [{ word: "pier", say: "peer" }]); + assert.deepEqual(await readManifestOf(p), m0, "the draft is not touched"); + const row = (await projectReads(p, o(p))).rows.find((r) => r.id === "p-1"); + assert.deepEqual([row.state, row.because], ["stale", ["lexicon"]]); + // 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"); +});