Archilyzer · Source

archilyzer

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

commit 99e80022bb69fb2f6eb28f0fa2ca6eada4d8b826
parent 6acdfab86aa933c6fc8b15031e987ce3dd2d7985
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 17 Nov 2026 17:07:14 -0500

the Reads page acts only on the reads it counted; the route calls the functions, the CLI refuses unknown flags (review 1, MUST 1, SHOULD 8)

MUST 1: with nothing ticked, Re-read sent no ids and the server queued EVERY stale read of the video
(a filtered view, a Find, "Pick every new read" alike), and idsOf silently dropped ids it did not
like (an unscoped run when all were dropped). Now the page always sends the exact ids it counted
(reread: the counted rows; pick: the unpicked ones in view; replace: the previewed, ticked ones);
lib/report/readsApi.mjs (the route's body) requires them and refuses a list naming any id no read
could have (reads.mjs READ_ID_RE: any timeline id, and a piece's role up to a 24-character screen id
and line 99) -- 400, never narrowed. Unscoped runs are the CLI's alone (no --only).
SHOULD 8: the route calls the functions directly (no argv from page text); `umtool reads` refuses a
flag a subcommand does not take (exit 2, the --json error shape), honours `--` as the end of flags,
and has --dry-run on undo (whether, or why not), reread (what would be queued) and pick (what would
be picked). `reread --one --json` prints JSON.
Also on the page: Undo is offered only while it applies (the GET's replaceUndoState), and says why
when it does not; an Everywhere's undo goes back to the entry it changed; a thread piece plays its
own parts; the runner's specific reason (its last turn's error, what it waits for) heads the
waiting line.
Tests: readsApi.test.mjs (a filtered view re-reads only its rows; unscoped, empty and bad-id
requests 400 with nothing queued or written; a 99-character id accepted), readsCli.test.mjs SHOULD 8.

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

Diffstat:
Mumtool/app/api/report/reads/route.ts | 95+++++++++++--------------------------------------------------------------------
Mumtool/components/projects/ReadsPanel.tsx | 49++++++++++++++++++++++++++++++-------------------
Mumtool/docs/cli.md | 10+++++-----
Mumtool/lib/cli/groups.mjs | 9+++++----
Mumtool/lib/cli/verbs.mjs | 6+++---
Aumtool/lib/report/readsApi.mjs | 130+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/readsApi.test.mjs | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/readsCli.mjs | 66+++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mumtool/lib/report/readsCli.test.mjs | 32++++++++++++++++++++++++++++++++
9 files changed, 332 insertions(+), 130 deletions(-)

diff --git a/umtool/app/api/report/reads/route.ts b/umtool/app/api/report/reads/route.ts @@ -2,74 +2,34 @@ import { projectRef } from "@/lib/projects"; import { refuseCaller } from "@/lib/report/caller"; import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; import { REPORTS_ROOT } from "@/lib/projects/core.mjs"; -import { readsCommand } from "@/lib/report/readsCli.mjs"; -import { postsCommand } from "@/lib/report/postsCli.mjs"; -import { queueView } from "@/lib/report/readsQueue.mjs"; +import { readsGet, readsPost } from "@/lib/report/readsApi.mjs"; import { kickQueue, queueDir, queueRunnerStatus } from "@/lib/queue/runner"; export const dynamic = "force-dynamic"; -// A VIDEO's READS (lane reads-find; the Reads page, components/projects/ReadsPanel.tsx): every write is the CLI's own -// command (`umtool reads …`, lib/report/readsCli.mjs), run here in-process with --json. +// A VIDEO's READS (lane reads-find; the Reads page, components/projects/ReadsPanel.tsx): lib/report/readsApi.mjs +// answers -- the functions `umtool reads` runs, called directly (never an argv built from what a page typed). // -// GET ?project[&find&case=1&word=1&stale=1&character=<id>] the reads (and Find's matches), and the queue -// POST {project, op: "preview", from, to, scope: "reads"|"say", case?, word?, only?} replace --dry-run [--say-only] -// POST {project, op: "replace", …the same} replace (These reads: one undo point; Everywhere: an entry) -// POST {project, op: "undo"} reads undo (the newest replace) -// POST {project, op: "unsay", word} posts say remove <word> (an Everywhere taken back) -// POST {project, op: "reread", only?} reads reread [--only] -- steps of the app's queue -// POST {project, op: "stop"} reads queue --stop -// POST {project, op: "retry", read} reads queue --retry <read> -// POST {project, op: "pick", which: "new"|"old", only?} reads pick +// GET ?project[&find&case=1&word=1&stale=1&character=<id>] the reads (and Find's matches), the queue, the undo +// POST {project, op: "preview", from, to, scope: "reads"|"say", case?, word?, only?} +// POST {project, op: "replace", from, to, scope, case?, word?, only} (These reads names the previewed reads) +// POST {project, op: "undo"} the newest replace (These reads, or an Everywhere) taken back +// POST {project, op: "reread", only} the reads counted, queued on the app's queue +// POST {project, op: "stop"} · {op: "retry", read} · {op: "pick", which: "new"|"old", only} const headers = { "cache-control": "no-store" }; - -async function cli(args: string[], { posts = false }: { posts?: boolean } = {}) { - const out: string[] = []; - const err: string[] = []; - const code = posts - ? await postsCommand([...args, "--json"], { root: REPORTS_ROOT, out: (s: string) => out.push(s), err: (s: string) => err.push(s) }) - : await readsCommand([...args, "--json"], { root: REPORTS_ROOT, out: (s: string) => out.push(s), err: (s: string) => err.push(s), queueDir: queueDir() }); - let json: Record<string, unknown> | null = null; - try { - json = JSON.parse(out.join("\n") || "null"); - } catch { - json = null; - } - return { code, json, error: code === 0 ? null : (json?.error as string | undefined) ?? (err.join("\n") || "refused") }; -} - -/** The queue as the page shows it, its waiting sentence completed with the app's own runner (its job runner busy). */ -async function queueOf(project: { id: string; dir: string }) { - const v = await queueView(project, { reportsRoot: REPORTS_ROOT, queueDir: queueDir() }); - const st = queueRunnerStatus(); - const waiting = v.waiting ?? (v.counts.waiting && st.waiting ? `waiting: ${st.waiting}` : v.counts.waiting && !st.armed ? "waiting: this umtool app does not run the queue (UMTOOL_QUEUE_RUNNER is off) -- the app that holds the lease runs it" : null); - return { ...v, waiting }; -} +const ctx = () => ({ reportsRoot: REPORTS_ROOT, queueDir: queueDir(), runner: queueRunnerStatus(), kick: kickQueue }); export async function GET(request: Request) { const url = new URL(request.url); const project = await projectRef(String(url.searchParams.get("project") ?? "")); if (!project) return Response.json({ error: "no such project" }, { status: 404 }); - const q = url.searchParams; - const args = [project.id]; - const find = q.get("find"); - if (find && find.trim()) args.push("--find", find); - if (q.get("case") === "1") args.push("--case"); - if (q.get("word") === "1") args.push("--word"); - if (q.get("stale") === "1") args.push("--stale"); - const character = q.get("character"); - if (character && /^[a-z0-9][a-z0-9_-]{0,63}$/i.test(character)) args.push("--character", character); try { - const r = await cli(args); - if (r.code !== 0) return Response.json({ error: r.error }, { status: 400, headers }); - return Response.json({ ...r.json, queue: await queueOf(project) }, { headers }); + return Response.json(await readsGet(project, url.searchParams, ctx()), { headers }); } catch (e) { return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500, headers }); } } -const idsOf = (v: unknown) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string" && /^[a-z0-9][a-z0-9:/_-]{0,80}$/i.test(x)) : []); - export async function POST(request: Request) { const cross = crossSiteRefusal(request.headers); if (cross) return Response.json({ error: cross }, { status: 403 }); @@ -79,38 +39,9 @@ export async function POST(request: Request) { if (!b) return Response.json({ error: "bad json" }, { status: 400 }); const project = await projectRef(String(b.project ?? "")); if (!project) return Response.json({ error: "no such project" }, { status: 404 }); - const op = String(b.op ?? ""); - const only = idsOf(b.only); - const onlyArgs = only.length ? ["--only", only.join(",")] : []; - let args: string[] | null = null; - let posts = false; - if (op === "preview" || op === "replace") { - const from = typeof b.from === "string" ? b.from : ""; - const to = typeof b.to === "string" ? b.to : ""; - if (!from.trim()) return Response.json({ error: "find what? (the words to replace)" }, { status: 400 }); - args = [project.id, "replace", from, to, ...(b.case === true ? ["--case"] : []), ...(b.word === true ? ["--word"] : []), ...(b.scope === "say" ? ["--say-only"] : []), ...onlyArgs, ...(op === "preview" ? ["--dry-run"] : [])]; - if (b.scope === "say" && b.word !== true) return Response.json({ error: "Everywhere, from now on matches whole words only (a pronunciation entry): turn Whole word on" }, { status: 400, headers }); - } else if (op === "undo") args = [project.id, "undo"]; - else if (op === "unsay") { - const word = typeof b.word === "string" ? b.word.trim() : ""; - if (!word) return Response.json({ error: "which entry?" }, { status: 400 }); - args = ["say", project.id, "remove", word]; - posts = true; - } else if (op === "reread") args = [project.id, "reread", ...onlyArgs]; - else if (op === "stop") args = [project.id, "queue", "--stop"]; - else if (op === "retry") { - const read = idsOf([b.read])[0]; - if (!read) return Response.json({ error: "which read?" }, { status: 400 }); - args = [project.id, "queue", "--retry", read]; - } else if (op === "pick") { - if (b.which !== "new" && b.which !== "old") return Response.json({ error: "pick which: new or old" }, { status: 400 }); - args = [project.id, "pick", `--${b.which}`, ...onlyArgs]; - } else return Response.json({ error: `no op ${op}` }, { status: 400 }); try { - const r = await cli(args, { posts }); - if (r.code !== 0) return Response.json({ error: r.error }, { status: 400, headers }); - if (op === "reread" || op === "retry") kickQueue(); - return Response.json({ ok: true, ...r.json, queue: await queueOf(project) }, { headers }); + const r = await readsPost(project, b, ctx()); + return Response.json(r.json, { status: r.status, headers }); } catch (e) { return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500, headers }); } diff --git a/umtool/components/projects/ReadsPanel.tsx b/umtool/components/projects/ReadsPanel.tsx @@ -13,14 +13,15 @@ import { narrationHref, playHref, postBenchHref } from "@/lib/hrefs"; // away and a Pick on either. Every button is a form and a job; nothing here asks a model. // --------------------------------------------------------------------------- -type Take = { index: number | null; file: string | null; key: string | null; reading: number; tuning: Record<string, number> | null; tunedBy: string | null } | null; +type Take = { index: number | null; takeFile?: string | null; file: string | null; files?: string[]; key: string | null; reading: number; tuning: Record<string, number> | null; tunedBy: string | null } | null; type Read = { id: string; kind: "post" | "thread" | "screen" | "card"; item: string; role: string | null; character: { id: string; name: string } | null; voice: string | null; spoken: string; said: string | null; storedAt: string | null; editable: boolean; why: string | null; state: string; because: string[]; take: Take; newTake: Take; matches?: { start: number; end: number }[]; }; type QueueRow = { read: string; item: string; kind: string; qid: string; state: string; error: string | null; before: Take; batch: string }; type Queue = { rows: QueueRow[]; waiting: string | null; counts: Record<string, number>; batch: string | null }; -type View = { counts: Record<string, number>; reads: Read[]; find?: { matches: number; lines: number }; queue: Queue }; +type Undo = { scope: "reads" | "say"; available: boolean; why: string | null; entry?: { word: string; say: string }; was?: { word: string; say: string } | null } | null; +type View = { counts: Record<string, number>; reads: Read[]; find?: { matches: number; lines: number }; queue: Queue; undo: Undo }; type Line = { id: string; kind: string; item: string; before: string; after: string; creates: string | null }; type Preview = | { scope: "reads"; lines: Line[]; skipped: { id: string; why: string }[]; notes: Record<string, string[]>; refused: Record<string, string[]>; matches: number } @@ -65,7 +66,6 @@ export default function ReadsPanel({ project, initialState = "all", initialChara const [to, setTo] = useState(""); const [preview, setPreview] = useState<Preview | null>(null); const [skip, setSkip] = useState<Set<string>>(new Set()); - const [undo, setUndo] = useState<{ scope: "reads" } | { scope: "say"; word: string } | null>(null); const [ticked, setTicked] = useState<Set<string>>(new Set()); const [characters, setCharacters] = useState<{ id: string; name: string }[]>([]); @@ -128,22 +128,24 @@ export default function ReadsPanel({ project, initialState = "all", initialChara const only = preview.scope === "reads" ? preview.lines.map((l) => l.id).filter((id) => !skip.has(id)) : []; if (preview.scope === "reads" && !only.length) throw new Error("no line is ticked"); await post({ project, op: "replace", from: find, to, scope: preview.scope, case: matchCase, word, ...(preview.scope === "reads" ? { only } : {}) }); - setUndo(preview.scope === "reads" ? { scope: "reads" } : { scope: "say", word: preview.entry.word }); setNotice(preview.scope === "reads" ? `rewritten: ${only.length} read${only.length === 1 ? "" : "s"} (the shown text untouched) -- they are stale now` : `"${preview.entry.word}" is said "${preview.entry.say}" in every read of a post now -- ${preview.stale.length} read${preview.stale.length === 1 ? "" : "s"} stale`); setPreview(null); }); + // UNDO: offered only while it applies (the route's replaceUndoState: the draft still as the replace left it, the + // entry still as Everywhere set it) -- else said why, quietly. + const undo = view?.undo ?? null; const takeBack = () => run(async () => { - if (!undo) return; - await post(undo.scope === "reads" ? { project, op: "undo" } : { project, op: "unsay", word: undo.word }); - setUndo(null); - setNotice(undo.scope === "reads" ? "the replace is taken back: every line as it was" : "the pronunciation entry is removed"); + if (!undo?.available) return; + await post({ project, op: "undo" }); + setNotice(undo.scope === "reads" ? "the replace is taken back: every line as it was" : undo.was ? `"${undo.was.word}" is said "${undo.was.say}" again, as before` : "the pronunciation entry is removed"); }); const reads = useMemo(() => view?.reads ?? [], [view]); const changed = reads.filter((r) => r.state === "stale"); const toQueue = ticked.size ? [...ticked] : changed.map((r) => r.id); const reread = () => run(async () => { - const j = (await post({ project, op: "reread", ...(ticked.size ? { only: [...ticked] } : {}) })) as { steps?: { reads: string[] }[]; skipped?: { id: string; why: string }[] }; + // EXACTLY the reads the button counts -- never "every stale read of the video" (the route refuses an unscoped one). + const j = (await post({ project, op: "reread", only: toQueue })) as { steps?: { reads: string[] }[]; skipped?: { id: string; why: string }[] }; const n = (j.steps ?? []).reduce((a, s) => a + s.reads.length, 0); setNotice(n ? `${n} line${n === 1 ? "" : "s"} queued, one item at a time, in cut order -- each joins its list unpicked` : `nothing queued${j.skipped?.length ? `: ${j.skipped.map((s) => `${s.id} (${s.why})`).join(", ")}` : ""}`); setTicked(new Set()); @@ -153,28 +155,31 @@ export default function ReadsPanel({ project, initialState = "all", initialChara const queue = view?.queue ?? null; const batchRows = (queue?.rows ?? []).filter((r) => r.batch === queue?.batch); const byId = useMemo(() => new Map(reads.map((r) => [r.id, r])), [reads]); - const audioOf = (item: string, t: Take) => (!t ? null : t.key ? `/api/report/narration/audio?${new URLSearchParams({ project, card: item, key: t.key })}` : t.file ? `/api/report/file?${new URLSearchParams({ project, path: t.file })}` : null); + // What a read plays: a card's reading; a post's take; a thread piece's OWN parts, one after another (never the joined take). + const audioOf = (item: string, t: Take): string[] => (!t ? [] : t.key ? [`/api/report/narration/audio?${new URLSearchParams({ project, card: item, key: t.key })}`] : (t.files?.length ? t.files : t.file ? [t.file] : []).map((f) => `/api/report/file?${new URLSearchParams({ project, path: f })}`)); const newOf = (q: QueueRow) => { const r = byId.get(q.read); return r ? (r.state === "unpicked" ? r.newTake : r.take) : null; }; const player = useRef<HTMLAudioElement | null>(null); const [playing, setPlaying] = useState<string | null>(null); - const playOne = (key: string, url: string | null, then?: () => void) => { + const playOne = (key: string, urls: string[], then?: () => void) => { player.current?.pause(); - if (!url) return then?.(); + if (!urls.length) return then?.(); + const [url, ...more] = urls; const a = new Audio(url); player.current = a; setPlaying(key); a.onended = () => { + if (more.length) return playOne(key, more, then); setPlaying(null); then?.(); }; void a.play().catch(() => setPlaying(null)); }; const listenThrough = () => { - const list = batchRows.filter((q) => q.state === "done").map((q) => ({ key: `${q.read}:new`, url: audioOf(q.item, newOf(q)) })).filter((x) => x.url); - const next = (i: number) => (i < list.length ? playOne(list[i].key, list[i].url, () => next(i + 1)) : setPlaying(null)); + const list = batchRows.filter((q) => q.state === "done").map((q) => ({ key: `${q.read}:new`, urls: audioOf(q.item, newOf(q)) })).filter((x) => x.urls.length); + const next = (i: number) => (i < list.length ? playOne(list[i].key, list[i].urls, () => next(i + 1)) : setPlaying(null)); next(0); }; const pick = (which: "new" | "old", only?: string[]) => run(async () => { @@ -184,7 +189,8 @@ export default function ReadsPanel({ project, initialState = "all", initialChara if (!view) return <p className="text-[12px] text-muted" data-reads-loading="">{error ?? "reading…"}</p>; const c = view.counts; - const unpicked = reads.filter((r) => r.state === "unpicked").length; + const unpickedIds = reads.filter((r) => r.state === "unpicked").map((r) => r.id); + const unpicked = unpickedIds.length; return ( <div className="space-y-4 text-[12.5px]" data-reads={project}> @@ -253,7 +259,7 @@ export default function ReadsPanel({ project, initialState = "all", initialChara </> ) : ( <p className="m-0 text-text" data-reads-preview-say=""> - Everywhere, from now on: &ldquo;{preview.entry.word}&rdquo; said &ldquo;{preview.entry.say}&rdquo;{preview.was ? ` (now "${preview.was}")` : ""} in every read of a post, present and future (a pronunciation entry) -- {preview.stale.length} read{preview.stale.length === 1 ? "" : "s"} made stale{preview.stale.length ? `: ${preview.stale.map((s) => s.id).join(", ")}` : ""} + Everywhere, from now on: &ldquo;{preview.entry.word}&rdquo; said &ldquo;{preview.entry.say}&rdquo; in every read of a post, present and future (a pronunciation entry){preview.was ? ` -- changes the existing entry (was "${preview.was}")` : ""} -- {preview.stale.length} read{preview.stale.length === 1 ? "" : "s"} made stale{preview.stale.length ? `: ${preview.stale.map((s) => s.id).join(", ")}` : ""} {preview.cards.length > 0 && <span className="block text-[11px] text-muted" data-reads-preview-cards="">cards are not said through the lexicon: use These reads for {preview.cards.join(", ")}</span>} </p> )} @@ -268,7 +274,12 @@ export default function ReadsPanel({ project, initialState = "all", initialChara <p className="m-0 flex flex-wrap items-center gap-2" data-reads-notice=""> {notice && <span className="text-text-2">{notice}</span>} {error && <span className="text-doubt-text" data-reads-error="">{error}</span>} - {undo && <button type="button" className="ink-link" disabled={busy} onClick={() => void takeBack()} aria-label={undo.scope === "reads" ? "Undo the replace" : "Remove the pronunciation entry"} data-reads-undo={undo.scope}>{undo.scope === "reads" ? "Undo the replace" : "Remove the entry"}</button>} + {undo?.available && ( + <button type="button" className="ink-link" disabled={busy} onClick={() => void takeBack()} aria-label={undo.scope === "reads" ? "Undo the replace" : undo.was ? "Put the pronunciation entry back as it was" : "Remove the pronunciation entry"} data-reads-undo={undo.scope}> + {undo.scope === "reads" ? "Undo the replace" : undo.was ? `Back to "${undo.was.say}"` : "Remove the entry"} + </button> + )} + {undo && !undo.available && undo.why && <span className="text-[11px] text-muted" data-reads-undo-gone="">no undo of the last replace: {undo.why}</span>} </p> )} @@ -276,7 +287,7 @@ export default function ReadsPanel({ project, initialState = "all", initialChara <button type="button" className={buttonVariants({ variant: "go", size: "sm" })} disabled={busy || !toQueue.length} onClick={() => void reread()} aria-label={`Re-read ${toQueue.length} changed line${toQueue.length === 1 ? "" : "s"}`} data-reads-reread={toQueue.length}> Re-read {toQueue.length} {ticked.size ? "ticked" : "changed"} line{toQueue.length === 1 ? "" : "s"} </button> - {unpicked > 0 && <button type="button" className={btn} disabled={busy} onClick={() => void pick("new")} aria-label="Pick every new read" data-reads-pick-all="">Pick every new read ({unpicked})</button>} + {unpicked > 0 && <button type="button" className={btn} disabled={busy} onClick={() => void pick("new", unpickedIds)} aria-label="Pick every new read" data-reads-pick-all="">Pick every new read ({unpicked})</button>} </div> {queue && queue.rows.length > 0 && ( @@ -349,7 +360,7 @@ export default function ReadsPanel({ project, initialState = "all", initialChara {r.state}{r.because.length ? <span className="block text-[11px]">{r.because.map((b) => BECAUSE[b] ?? b).join(", ")}</span> : null} </td> <td className={cell}> - {url ? <button type="button" className="ink-link" onClick={() => playOne(`${r.id}:take`, url)} aria-label={`Play what ${r.id} plays now`} data-read-play={r.id}>▶ play</button> : <span className="text-muted">—</span>} + {url.length ? <button type="button" className="ink-link" onClick={() => playOne(`${r.id}:take`, url)} aria-label={`Play what ${r.id} plays now`} data-read-play={r.id}>▶ play</button> : <span className="text-muted">—</span>} </td> </tr> ); diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -50,8 +50,8 @@ Inbox cannot disagree about what is wrong with one. | `review-pass <project> verdict like\|maybe\|no\|clear [--note T] [--json]` | the pass's **verdict on the draft**, one locked call: a draft that differs from its parent version only by what the walk and the review pass write (verdict, correction, reason, reject note, walk note, ★) judges the PARENT and saves nothing; otherwise the draft is saved as the next version and that is judged (`takes/verdicts.json`) | | `narration <project> [<card>] [--list] [--json]` · `<card> --read [--text "…"] [--reading N|next] [--temperature t] [--top-p p] [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n]` · `<card> --pick <key>` · `<card> [--text "…"] [--reading N] [tuning flags | --tuning-off]` | a **card's narration** and its readings ([knobs.md](knobs.md#a-cards-narration-read-again), `lib/report/cardNarrationCli.mjs`): the words a stock voice says over a card (spoken only — no card draws them), its reading and Orpheus tuning; `--read` asks the editor for one reading (a job; it waits while render mode holds the machine) and keeps it in `out/narration/` without changing the card (`--reading next`: one past the highest these words were read at); `--pick <key>` makes the card play a kept reading (its words, reading and tuning; nothing synthesized) — a verdict on the same words is kept; without either, the card's words, reading and tuning are set. The narration page's Read again, Read edited text, Tune and Pick run these. | | `reads <project> [--find <text> [--case] [--word]] [--stale] [--character <id>] [--json]` | **a video's reads** ([knobs.md](knobs.md#the-reads-of-a-video), `lib/report/reads.mjs`): every line a voice reads — a post's script, a thread read's pieces (his words, a parent, the quoted or a linked post), its screen lines, a card's narration — with the words it SAYS (never what is shown), where they are kept, the take that plays and its state: `fresh`, `stale` (other words, the lexicon, a character's settings — the rows `cast stale` lists — or its voice since), `unpicked` (re-read, waiting for a pick), `none`, `recorded` (yours: never stale, never re-read). An id is the item's, `<item>/<role>` for a thread piece. `--find` searches the spoken text only (`--case`, `--word`). | -| `reads <project> replace <from> <to> [--case] [--word] [--say-only] [--only <id>,…] [--dry-run] [--json]` · `reads <project> undo` | **Replace**, two scopes, neither synthesizing and neither touching what is shown (operator ruling 3; `lib/report/readsReplace.mjs`): **these reads** rewrites the matched reads' spoken text in ONE undo point (`auto-before-reads-replace`) — a post's script (marked for reading), a screen line's said-as (made when it has none), a card's narration; a parent, the quoted or a linked post is said as shown (only `--say-only` changes it); a recorded read is never replaced; the preview names what a changed post loses (its approval, as a new script takes it), a card's review verdict given on the old words, and what the build would refuse (refused whole). **`--say-only`: everywhere, from now on** — a pronunciation entry (`posts say add`'s writer): every read of a post says it that way; whole words; never a card. `undo` takes back the newest replace and refuses any other undo point. | -| `reads <project> reread [--stale] [--only <id>,…] [--wait [--timeout <s>]] [--json]` · `reads <project> queue [--stop] [--retry <id>] [--json]` · `reads <project> pick --new|--old [--only <id>,…] [--json]` | **the re-read queue** (`lib/report/readsQueue.mjs`): the stale reads (or `--only` those) queued on the app's durable queue (`umtool queue ls`), ONE step per item in cut order, none waiting on another — `reads <p> reread --one <item> --only <ids>`, which judges the item again and runs the item's bench command (`readAgainArgv.mjs`: a post's take as the bench asks it, `--bench-slurs`; a thread piece's `--for`/`--tuned … reading:next`; a card's own reading), the tuning a plain press asks (only what the line owned). The editor's `tts-file` jobs, one at a time; render mode holds them. A re-read joins its list UNPICKED. `queue` says each row's state and, in one sentence, why they wait; `--stop` cancels what has not started; `--retry` puts one back. `pick --new` makes every unpicked re-read play, `--old` goes back to what played before (a card: its old words and reading) — one undo point. | +| `reads <project> replace <from> <to> [--case] [--word] [--say-only] [--only <id>,…] [--dry-run] [--json]` · `reads <project> undo [--dry-run]` | **Replace**, two scopes, neither synthesizing and neither touching what is shown (operator ruling 3; `lib/report/readsReplace.mjs`): **these reads** rewrites the matched reads' spoken text in ONE undo point (`auto-before-reads-replace`) — a post's script (marked for reading), a screen line's said-as (made when it has none), a card's narration; a parent, the quoted or a linked post is said as shown (only `--say-only` changes it); a recorded read is never replaced; the preview names what a changed post loses (its approval, as a new script takes it), a card's review verdict given on the old words, and what the build would refuse (refused whole). **`--say-only`: everywhere, from now on** — a pronunciation entry (`posts say add`'s writer): every read of a post says it that way; whole words; never a card. `undo` takes back the newest replace -- These reads only while the draft is still exactly what it left (a re-read landing or any edit since: refused, said why), an Everywhere back to the entry it changed (its spoken form and note) or the entry it added removed; `--dry-run` says which, or why not. A flag a subcommand does not take is refused; `--` ends the flags. | +| `reads <project> reread [--stale] [--only <id>,…] [--wait [--timeout <s>]] [--dry-run] [--json]` · `reads <project> queue [--stop] [--retry <id>] [--json]` · `reads <project> pick --new|--old [--only <id>,…] [--dry-run] [--json]` | **the re-read queue** (`lib/report/readsQueue.mjs`): the stale reads (or `--only` those) queued on the app's durable queue (`umtool queue ls`), ONE step per item in cut order, none waiting on another — `reads <p> reread --one <item> --only <ids>`, which judges the item again and runs the item's bench command (`readAgainArgv.mjs`: a post's take as the bench asks it, `--bench-slurs`; a thread piece's `--for`/`--tuned … reading:next`; a card's own reading), the tuning a plain press asks (only what the line owned). The editor's `tts-file` jobs, one at a time; render mode holds them. A re-read joins its list UNPICKED. `queue` says each row's state and, in one sentence, why they wait; `--stop` cancels what has not started; `--retry` puts one back. `pick --new` makes every unpicked re-read play, `--old` goes back to what played before (a card: its old words and reading) — one undo point. | | `present <project> [--take <take> \| --cut] [--json] [--public] [--open] [--url <origin>]` | **present mode**: the cut as slides, navigated like a deck (`/projects/<p>/present`) — prints the address and every slide (its kind, id — a post's `<channel>/<id>`, a clip's id, `section-<n>`, `day-<YYYY-MM-DD>` — date, words and censor counts); `--json` the payload (each post's card as Play draws it and its censor data by kind, each clip's spans, the dividers); `--public` the payload a public page would carry (censored, no reveal data); `--open` opens it; `<address>#<slide id>` opens a slide ([knobs.md](knobs.md#present-mode-the-cut-as-slides-navigated-like-a-deck)) | | `set <project> <clip> key=value …` | a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)); on ANY entry (a post item, a still, a clip) `hideModules=diet,streak`, `shelfNote='…'` and `chapter='…'` (its name in the chapter list, one line of at most 100 characters; `chapter=` none); `--take <t>` writes the entry knobs into that take's patch; `key=` clears one ([knobs.md](knobs.md#marks)) | | `intro <project> [key=value …] [--off] [--json]` · `intro <project> --take <take> --off\|--on` | **the intro** the cut opens on (`render.intro`): with no key, prints it as written, what the cut opens with (a `title-card`'s words resolved) and each version's on/off; `key=value` writes it through the look writer (`style` `seconds` 3.5–8 `mark` `ground` `sound` (`false` silent) `site` `title` `lines` (`a\|b`, ≤ 3) and the brand's keys; `key=` clears one; a new intro starts as `boot-dark`); `--off` takes it off the cut; `--take <t> --off` that version opens on no intro (its patch's `render.intro: null`), `--on` on the cut's again. **Exit 1** on a value the build refuses ([knobs.md](knobs.md#the-intro-played-and-edited)) | @@ -219,10 +219,10 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `narration <project> [<card>] [--read] [--text TEXT] [--reading READING] [--pick PICK] [--temperature N] [--top-p N] [--top-k N] [--min-p N] [--repeat-penalty N] [--chunk-takes N] [--tuning-off] [--list]` | a card's narration: its words, reading and tuning; a reading made, or picked | form · *draft* | | `reads <project> [--find FIND] [--case] [--word] [--stale] [--character CHARACTER]` | every line a voice reads: what it says, the take that plays, fresh or stale; Find over the spoken text only | form · *project* | | `reads <project> replace <from> <to> [--case] [--word] [--say-only] [--only ONLY] [--dry-run]` | Replace in the spoken text: these reads (one undo point), or everywhere from now on (a pronunciation entry); never the shown text, never a synthesis | form · *draft* | -| `reads <project> undo` | the newest replace taken back (refused when the newest undo point is not one) | form · *draft* | -| `reads <project> reread [--stale] [--only ONLY] [--wait] [--timeout N] [--one ONE]` | the stale reads queued, one step per item in cut order, each the bench's own command; re-reads join unpicked | form · *project* | +| `reads <project> undo [--dry-run]` | the newest replace taken back: These reads only while nothing was written since; an Everywhere back to the entry it changed | form · *draft* | +| `reads <project> reread [--stale] [--only ONLY] [--wait] [--timeout N] [--one ONE] [--dry-run]` | the stale reads queued, one step per item in cut order, each the bench's own command; re-reads join unpicked | form · *project* | | `reads <project> queue [--stop] [--retry RETRY]` | each queued read's state and why they wait; stop what has not started, retry one | form · *project* | -| `reads <project> pick [--new] [--old] [--only ONLY]` | Pick: every unpicked re-read made the one that plays (--new), or back to what played before (--old); one undo point | form · *draft* | +| `reads <project> pick [--new] [--old] [--only ONLY] [--dry-run]` | Pick: every unpicked re-read made the one that plays (--new), or back to what played before (--old); one undo point | form · *draft* | | `present <project> [--take TAKE] [--cut] [--public]` | present mode's address and slides | form · *project* | | `set <project> <clip> key=value… [--mark MARK] [--take TAKE]` | a clip's knobs: claim, marks, audio, blur, fx … | form · *draft* | | `intro <project> [key=value…] [--off] [--take TAKE] [--on]` | the intro the cut opens on (render.intro) | form · *draft* | diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -306,16 +306,17 @@ export const GROUPS = [ " fresh / stale / unpicked / none / recorded; --find over the spoken text only", " umtool reads <project> replace <from> <to> [--case] [--word] [--say-only] [--only <ids>] [--dry-run] THESE READS'", " spoken text (one undo point; never the shown text), or --say-only EVERYWHERE (a pronunciation entry);", - " neither synthesizes · undo: the newest replace taken back", + " neither synthesizes · undo [--dry-run]: the newest replace taken back while nothing was written since", " umtool reads <project> reread [--only <ids>] [--wait] the stale reads queued on the app's queue, one step per", " item, each the bench's command; re-reads join unpicked · queue [--stop] [--retry <id>] · pick --new|--old", + " (--dry-run on reread and pick: what would be queued or picked; a flag a subcommand does not take is refused)", ], docs: [ ["`reads <project> [--find <text> [--case] [--word]] [--stale] [--character <id>] [--json]`", "**a video's reads** ([knobs.md](knobs.md#the-reads-of-a-video), `lib/report/reads.mjs`): every line a voice reads — a post's script, a thread read's pieces (his words, a parent, the quoted or a linked post), its screen lines, a card's narration — with the words it SAYS (never what is shown), where they are kept, the take that plays and its state: `fresh`, `stale` (other words, the lexicon, a character's settings — the rows `cast stale` lists — or its voice since), `unpicked` (re-read, waiting for a pick), `none`, `recorded` (yours: never stale, never re-read). An id is the item's, `<item>/<role>` for a thread piece. `--find` searches the spoken text only (`--case`, `--word`)."], - ["`reads <project> replace <from> <to> [--case] [--word] [--say-only] [--only <id>,…] [--dry-run] [--json]` · `reads <project> undo`", - "**Replace**, two scopes, neither synthesizing and neither touching what is shown (operator ruling 3; `lib/report/readsReplace.mjs`): **these reads** rewrites the matched reads' spoken text in ONE undo point (`auto-before-reads-replace`) — a post's script (marked for reading), a screen line's said-as (made when it has none), a card's narration; a parent, the quoted or a linked post is said as shown (only `--say-only` changes it); a recorded read is never replaced; the preview names what a changed post loses (its approval, as a new script takes it), a card's review verdict given on the old words, and what the build would refuse (refused whole). **`--say-only`: everywhere, from now on** — a pronunciation entry (`posts say add`'s writer): every read of a post says it that way; whole words; never a card. `undo` takes back the newest replace and refuses any other undo point."], - ["`reads <project> reread [--stale] [--only <id>,…] [--wait [--timeout <s>]] [--json]` · `reads <project> queue [--stop] [--retry <id>] [--json]` · `reads <project> pick --new\|--old [--only <id>,…] [--json]`", + ["`reads <project> replace <from> <to> [--case] [--word] [--say-only] [--only <id>,…] [--dry-run] [--json]` · `reads <project> undo [--dry-run]`", + "**Replace**, two scopes, neither synthesizing and neither touching what is shown (operator ruling 3; `lib/report/readsReplace.mjs`): **these reads** rewrites the matched reads' spoken text in ONE undo point (`auto-before-reads-replace`) — a post's script (marked for reading), a screen line's said-as (made when it has none), a card's narration; a parent, the quoted or a linked post is said as shown (only `--say-only` changes it); a recorded read is never replaced; the preview names what a changed post loses (its approval, as a new script takes it), a card's review verdict given on the old words, and what the build would refuse (refused whole). **`--say-only`: everywhere, from now on** — a pronunciation entry (`posts say add`'s writer): every read of a post says it that way; whole words; never a card. `undo` takes back the newest replace -- These reads only while the draft is still exactly what it left (a re-read landing or any edit since: refused, said why), an Everywhere back to the entry it changed (its spoken form and note) or the entry it added removed; `--dry-run` says which, or why not. A flag a subcommand does not take is refused; `--` ends the flags."], + ["`reads <project> reread [--stale] [--only <id>,…] [--wait [--timeout <s>]] [--dry-run] [--json]` · `reads <project> queue [--stop] [--retry <id>] [--json]` · `reads <project> pick --new\|--old [--only <id>,…] [--dry-run] [--json]`", "**the re-read queue** (`lib/report/readsQueue.mjs`): the stale reads (or `--only` those) queued on the app's durable queue (`umtool queue ls`), ONE step per item in cut order, none waiting on another — `reads <p> reread --one <item> --only <ids>`, which judges the item again and runs the item's bench command (`readAgainArgv.mjs`: a post's take as the bench asks it, `--bench-slurs`; a thread piece's `--for`/`--tuned … reading:next`; a card's own reading), the tuning a plain press asks (only what the line owned). The editor's `tts-file` jobs, one at a time; render mode holds them. A re-read joins its list UNPICKED. `queue` says each row's state and, in one sentence, why they wait; `--stop` cancels what has not started; `--retry` puts one back. `pick --new` makes every unpicked re-read play, `--old` goes back to what played before (a card: its old words and reading) — one undo point."], ], }, diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -248,14 +248,14 @@ export const VERBS = Object.freeze([ project(), arg("from", { type: "text", help: "the words to find" }), arg("to", { type: "text", help: "what to say instead" }), bool("--case", "with case"), bool("--word", "whole words"), bool("--say-only", "everywhere, from now on: a pronunciation entry (whole words; never a card)"), opt("--only", { help: "these read ids only, comma separated" }), dry(), ], { shape: "reads <project> replace <from> <to>" }), - form("reads undo", "draft", "the newest replace taken back (refused when the newest undo point is not one)", [project()], { shape: "reads <project> undo" }), + form("reads undo", "draft", "the newest replace taken back: These reads only while nothing was written since; an Everywhere back to the entry it changed", [project(), dry()], { shape: "reads <project> undo" }), form("reads reread", "project", "the stale reads queued, one step per item in cut order, each the bench's own command; re-reads join unpicked", [ project(), bool("--stale", "every stale read (the default)"), opt("--only", { help: "these read ids only, comma separated" }), bool("--wait", "until they end"), num("--timeout", { help: "--wait's limit, s" }), - opt("--one", { help: "one queue step's item (the umtool app runs it)" }), + opt("--one", { help: "one queue step's item (the umtool app runs it)" }), dry(), ], { shape: "reads <project> reread" }), form("reads queue", "project", "each queued read's state and why they wait; stop what has not started, retry one", [project(), bool("--stop", "cancel what has not started"), opt("--retry", { help: "a failed or stopped read's id" })], { shape: "reads <project> queue" }), form("reads pick", "draft", "Pick: every unpicked re-read made the one that plays (--new), or back to what played before (--old); one undo point", [ - project(), bool("--new", "the new reads"), bool("--old", "what played before"), opt("--only", { help: "these read ids only, comma separated" }), + project(), bool("--new", "the new reads"), bool("--old", "what played before"), opt("--only", { help: "these read ids only, comma separated" }), dry(), ], { shape: "reads <project> pick" }), form("present", "project", "present mode's address and slides", [project(), takeOpt({ help: "that take's cut (default the latest)" }), bool("--cut", "the manifest alone"), bool("--public", "as a public page would carry it")]), form("set", "draft", "a clip's knobs: claim, marks, audio, blur, fx …", [project(), clip(), pairs({ help: "key=value, one per line (claim.at=190.2, audio.gain=-3, `key=` clears)" }), opt("--mark", { help: "the mark the claim.* keys set" }), takeOpt()], B(["clip"], { clip: "{id}" })), diff --git a/umtool/lib/report/readsApi.mjs b/umtool/lib/report/readsApi.mjs @@ -0,0 +1,130 @@ +// THE READS PAGE's REQUESTS (lane reads-find; app/api/report/reads/route.ts is this, behind its guards): every +// request answered by the same functions `umtool reads` runs (reads.mjs, readsReplace.mjs, readsQueue.mjs), called +// directly -- never an argv built from what a page typed. A write that acts on reads names them (`only`): the ids +// the page counted, each checked; a list that names one id no read could have is refused whole (400), never +// narrowed -- an unscoped re-read, pick or replace is the CLI's alone (no --only). +// +// Plain ESM: tested without the app (readsApi.test.mjs). +import { READ_KINDS, filterReads, findInReads, projectReads, readIdsOf } from "./reads.mjs"; + +const view = (x) => ({ id: x.id, kind: x.kind, item: x.item, role: x.role, character: x.character, voice: x.voice, spoken: x.spoken, said: x.said, storedAt: x.storedAt, editable: x.editable, why: x.why, queueable: x.queueable !== false, state: x.state, because: x.because, take: x.take, newTake: x.newTake, ...(x.matches ? { matches: x.matches } : {}) }); +void READ_KINDS; + +class Refused extends Error { + constructor(message, status = 400) { + super(message); + this.status = status; + } +} + +/** `only` from a body: required here (`need`), each id checked. */ +function onlyOf(body, need) { + if (body.only === undefined || body.only === null) { + if (need) throw new Refused("which reads? (only: the ids of the reads this acts on)"); + return null; + } + const r = readIdsOf(body.only); + if (r.error) throw new Refused(r.error); + return r.ids; +} + +const text = (v, what) => { + if (typeof v !== "string") throw new Refused(`${what} is text`); + return v; +}; + +/** + * The queue as the page shows it: its waiting sentence completed with the app's own runner -- its specific reason + * (its last turn's error, what it waits for, not armed in this process) before the general one. + */ +export async function queueOf(project, { reportsRoot, queueDir, runner = null }) { + const { queueView } = await import("./readsQueue.mjs"); + const v = await queueView(project, { reportsRoot, queueDir }); + if (!v.counts.waiting) return v; + const st = runner ?? {}; + const specific = st.lastError ? `waiting: the app's queue runner's last turn failed -- ${st.lastError}` : st.waiting ? `waiting: ${st.waiting}` : st.armed === false && st.enabled === false ? "waiting: this umtool app does not run the queue (UMTOOL_QUEUE_RUNNER is off here) -- the app that holds the queue's lease runs it" : null; + return { ...v, waiting: specific && !/render mode/.test(v.waiting ?? "") ? specific : v.waiting }; +} + +/** GET: the reads (filtered, with Find's matches), the queue, and whether the newest replace can be taken back. */ +export async function readsGet(project, q, o) { + const { rows, counts, tuningStale } = await projectReads(project, { reportsRoot: o.reportsRoot }); + const character = q.get("character"); + let list = filterReads(rows, { stale: q.get("stale") === "1", character: character && /^[a-z0-9][a-z0-9_-]{0,63}$/i.test(character) ? character : null }); + const find = q.get("find"); + const opts = { matchCase: q.get("case") === "1", word: q.get("word") === "1" }; + let found = null; + if (find && find.trim()) { + found = findInReads(list, find, opts); + list = found.rows; + } + const { replaceUndoState } = await import("./readsReplace.mjs"); + return { + ok: true, project: project.id, counts, settingsStale: tuningStale.length, reads: list.map(view), + ...(found ? { find: { text: find, ...opts, matches: found.matches, lines: found.lines } } : {}), + queue: await queueOf(project, o), undo: await replaceUndoState(project), + }; +} + +/** + * POST: one op -- `{ status, json }`. preview / replace (`scope` "reads" | "say"; a replace of These reads names the + * previewed reads), undo (the newest replace, of either scope), reread (the reads counted), stop, retry, pick (the + * reads it picks). + */ +export async function readsPost(project, body, o) { + try { + const op = String(body.op ?? ""); + const R = await import("./readsReplace.mjs"); + const Q = await import("./readsQueue.mjs"); + const opts = { matchCase: body.case === true, word: body.word === true, reportsRoot: o.reportsRoot }; + const qo = { reportsRoot: o.reportsRoot, queueDir: o.queueDir }; + let json; + if (op === "preview" || op === "replace") { + const from = text(body.from, "from"); + const to = text(body.to ?? "", "to"); + if (!from.trim()) throw new Refused("find what? (the words to replace)"); + if (body.scope === "say") { + if (!opts.word) throw new Refused(R.SAY_WHOLE_WORDS); + if (op === "preview") { + const plan = await R.sayOnlyPlan(project, from, to, opts); + json = { scope: "say", entry: plan.entry, was: plan.was, stale: plan.stale, cards: plan.cards, matches: plan.matches }; + } else { + const done = await R.applySayOnly(project, from, to, opts); + json = { scope: "say", entry: done.result.entry, changed: done.result.changed, was: done.plan.was, stale: done.plan.stale }; + } + } else if (body.scope === "reads") { + const only = onlyOf(body, op === "replace"); + if (op === "preview") { + const plan = await R.replacePlan(project, from, to, { ...opts, only }); + json = { scope: "reads", lines: plan.lines, skipped: plan.skipped, notes: plan.notes, refused: plan.refused, matches: plan.matches }; + } else { + const done = await R.applyReplace(project, from, to, { ...opts, only }); + json = { scope: "reads", lines: done.plan.lines, token: done.result.token ?? null }; + } + } else throw new Refused("scope is reads or say"); + } else if (op === "undo") { + const st = await R.replaceUndoState(project); + if (!st) throw new Refused("nothing to undo: no replace was made here"); + json = st.scope === "say" ? { scope: "say", ...(await R.undoSayOnly(project)) } : { scope: "reads", ...(await R.undoReplace(project)) }; + } else if (op === "reread") { + const only = onlyOf(body, true); + json = await Q.enqueueRereads(project, { ...qo, only, by: "the Reads page" }); + o.kick?.(); + } else if (op === "stop") json = await Q.stopQueue(project, qo); + else if (op === "retry") { + const [read] = onlyOf({ only: [body.read] }, true); + json = await Q.retryRead(project, read, qo); + o.kick?.(); + } else if (op === "pick") { + if (body.which !== "new" && body.which !== "old") throw new Refused("pick which: new or old"); + const only = onlyOf(body, true); + const r = await Q.pickReads(project, { which: body.which, only, reportsRoot: o.reportsRoot }); + json = { picked: r.picked, token: r.result?.token ?? null }; + } else throw new Refused(`no op ${op}`); + return { status: 200, json: { ok: true, ...json, queue: await queueOf(project, o), undo: await R.replaceUndoState(project) } }; + } catch (e) { + const known = e instanceof Refused || ["ReplaceError", "QueueError", "StructureRefused", "StaleToken", "SayError"].includes(e?.constructor?.name); + if (!known) throw e; + return { status: e instanceof Refused ? e.status : e?.constructor?.name === "StaleToken" ? 409 : 400, json: { ok: false, error: e?.constructor?.name === "StructureRefused" ? e.errors.join("; ") : e.message } }; + } +} diff --git a/umtool/lib/report/readsApi.test.mjs b/umtool/lib/report/readsApi.test.mjs @@ -0,0 +1,65 @@ +// THE READS PAGE's REQUESTS (lane reads-find, review 1 MUST 1; readsApi.mjs, the route's body): a write acts only on +// the reads it names -- the ids the page counted -- and a list naming an id no read could have is refused whole, never +// narrowed to an unscoped run. Temp dirs, invented people; noLiveEditor first. +import "./noLiveEditor.mjs"; +import assert from "node:assert/strict"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { readsGet, readsPost } from "./readsApi.mjs"; +import { listSteps } from "../queue/store.mjs"; +import { readManifestOf, readsProject } from "./reads.fixtures.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-reads-api-")); +after(() => rm(ROOT, { recursive: true, force: true })); +delete process.env.UMTOOL_CAST_FILE; + +async function changed(name) { + const p = await readsProject(ROOT, name); + const m = await readManifestOf(p); + m.timeline[0].narration.script = m.timeline[0].narration.script.replace("noon", "twelve noon"); + m.timeline[3].narration.text = "Six months later, the north pier opened again."; + await writeFile(path.join(p.dir, "video.manifest.json"), JSON.stringify(m, null, 2)); + return { p, o: { reportsRoot: p.root, queueDir: path.join(p.root, ".umtool-queue") } }; +} + +test("MUST 1: a filtered view re-reads ONLY the reads it counted; no `only`, a bad id, an empty list: 400, nothing queued", async () => { + const { p, o } = await changed("only"); + // The page's view: the stale reads of the ferry character -- p-1 only (the card has no character). + const g = await readsGet(p, new URLSearchParams({ stale: "1", character: "ferry" }), o); + assert.deepEqual(g.reads.map((r) => r.id), ["p-1"]); + for (const body of [{ op: "reread" }, { op: "reread", only: [] }, { op: "reread", only: ["p-1", "p 1"] }, { op: "reread", only: "p-1" }]) { + const r = await readsPost(p, body, o); + assert.equal(r.status, 400, JSON.stringify(body)); + } + assert.deepEqual(await listSteps(o.queueDir), [], "nothing queued by a refused request"); + const r = await readsPost(p, { op: "reread", only: g.reads.map((x) => x.id) }, o); + assert.equal(r.status, 200); + assert.deepEqual(r.json.steps.map((s) => s.item), ["p-1"], "the card, stale too, is not re-read"); + // An id as long as the model makes (a 64-character item, a 24-character screen id, line 12): accepted. + const long = `${"x".repeat(64)}/screen:${"s".repeat(24)}:12`; + const r2 = await readsPost(p, { op: "reread", only: [long] }, o); + assert.equal(r2.status, 200); + assert.match(r2.json.skipped[0].why, /no such read/); +}); + +test("MUST 1: pick and a replace of These reads name their reads; refused unscoped", async () => { + const { p, o } = await changed("scoped"); + assert.equal((await readsPost(p, { op: "pick", which: "new" }, o)).status, 400); + assert.equal((await readsPost(p, { op: "replace", scope: "reads", from: "north", to: "northern" }, o)).status, 400); + const before = await readManifestOf(p); + assert.equal((await readsPost(p, { op: "replace", scope: "reads", from: "north", to: "northern", only: ["c-1", "bad id"] }, o)).status, 400); + assert.deepEqual(await readManifestOf(p), before); + // The previewed ids: only those change. + const prev = await readsPost(p, { op: "preview", scope: "reads", from: "north", to: "northern" }, o); + assert.deepEqual(prev.json.lines.map((l) => l.id), ["p-1", "c-1"]); + const done = await readsPost(p, { op: "replace", scope: "reads", from: "north", to: "northern", only: ["c-1"] }, o); + assert.equal(done.status, 200); + const m = await readManifestOf(p); + assert.match(m.timeline[3].narration.text, /northern/); + assert.doesNotMatch(m.timeline[0].narration.script, /northern/); + assert.equal(done.json.undo.available, true); + // Everywhere with Whole word off: refused in the page's words. + assert.match((await readsPost(p, { op: "preview", scope: "say", from: "pier", to: "peer" }, o)).json.error, /whole words only/); +}); diff --git a/umtool/lib/report/readsCli.mjs b/umtool/lib/report/readsCli.mjs @@ -18,10 +18,10 @@ import { READ_KINDS, filterReads, findInReads, projectReads } from "./reads.mjs" export const READS_USAGE = [ "usage: umtool reads <project> [--find <text> [--case] [--word]] [--stale] [--character <id>] [--json]", " umtool reads <project> replace <from> <to> [--case] [--word] [--say-only] [--only <id>,…] [--dry-run] [--json]", - " umtool reads <project> undo [--json]", - " umtool reads <project> reread [--stale] [--only <id>,…] [--wait [--timeout <s>]] [--json]", + " umtool reads <project> undo [--dry-run] [--json]", + " umtool reads <project> reread [--stale] [--only <id>,…] [--wait [--timeout <s>]] [--dry-run] [--json]", " umtool reads <project> queue [--stop] [--retry <id>] [--json]", - " umtool reads <project> pick --new|--old [--only <id>,…] [--json]", + " umtool reads <project> pick --new|--old [--only <id>,…] [--dry-run] [--json]", " A VIDEO's READS: every line a voice reads -- a post's script, a thread read's pieces (his words, a parent, the", " quoted or a linked post), its screen lines, a card's narration -- with what it SAYS (never what is shown), the", " take that plays and its state: fresh, stale (other words, the lexicon, a character's settings or voice since),", @@ -33,8 +33,10 @@ export const READS_USAGE = [ " as shown (only --say-only changes it), a recorded read is never replaced. --say-only: EVERYWHERE, FROM NOW ON --", " a pronunciation entry (umtool posts say add): every read of a post says it that way; whole words always (--word", " is implied), never a card. --dry-run: the preview (line, before -> after; what goes; what the build would refuse), nothing written.", - " Neither synthesizes: the changed reads show as stale. undo: the newest replace taken back (refused when the", - " newest undo point is not one). reread: the stale reads (--only: those) queued, one step per item in cut order", + " Neither synthesizes: the changed reads show as stale. undo: the newest replace taken back -- These reads only", + " while the draft is still as it left it (nothing written since), an Everywhere back to the entry it changed (or", + " the entry removed); --dry-run says which, or why not. Every subcommand refuses a flag it does not take; -- ends", + " the flags (a `to` that starts with dashes). --dry-run on reread and pick: what would be queued or picked. reread: the stale reads (--only: those) queued, one step per item in cut order", " on the umtool app's queue (umtool queue ls), each the bench's own command; a re-read joins the list UNPICKED.", " --wait: until they end (exit 1 when one failed). queue: each queued read's state, and why they wait; --stop", " cancels what has not started; --retry <id> puts a failed or stopped one back. pick --new: every unpicked", @@ -43,6 +45,16 @@ export const READS_USAGE = [ class ReadsUsage extends Error {} +/** Each subcommand's flags (besides --json, --help). */ +const FLAGS_OF = Object.freeze({ + "": ["--find", "--case", "--word", "--stale", "--character"], + replace: ["--case", "--word", "--say-only", "--only", "--dry-run"], + undo: ["--dry-run"], + reread: ["--stale", "--only", "--wait", "--timeout", "--one", "--dry-run"], + queue: ["--stop", "--retry"], + pick: ["--new", "--old", "--only", "--dry-run"], +}); + const VALUED = new Set(["--find", "--character", "--only", "--one", "--retry", "--timeout"]); /** @@ -53,12 +65,15 @@ const VALUED = new Set(["--find", "--character", "--only", "--one", "--retry", " export async function readsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), queueDir = undefined } = {}) { const flags = new Map(); const words = []; + let ended = false; for (let i = 0; i < args.length; i += 1) { const a = args[i]; - if (VALUED.has(a)) { + // `--`: every word after it is a word (a `to` that starts with dashes), never a flag. + if (!ended && a === "--") ended = true; + else if (!ended && VALUED.has(a)) { flags.set(a, args[i + 1] ?? ""); i += 1; - } else if (a.startsWith("--")) flags.set(a, true); + } else if (!ended && a.startsWith("--")) flags.set(a, true); else words.push(a); } const str = (k) => (typeof flags.get(k) === "string" ? flags.get(k) : null); @@ -71,6 +86,11 @@ export async function readsCommand(args, { root = REPORTS_ROOT, out = (s) => con } const say = (j, text) => out(json ? JSON.stringify(j, null, 2) : text); try { + // Each subcommand's own flags; any other is refused (never ignored: `undo --dry-run` must not undo). + const allowed = FLAGS_OF[sub ?? ""]; + if (!allowed) throw new ReadsUsage(`reads: replace, undo, reread, queue or pick (not ${sub}); none lists the reads`); + const unknown = [...flags.keys()].filter((f) => f !== "--json" && f !== "--help" && !allowed.includes(f)); + if (unknown.length) throw new ReadsUsage(`${unknown.join(", ")}: not a flag of \`reads <p>${sub ? ` ${sub}` : ""}\` (its flags: ${allowed.join(" ") || "none"}; -- ends the flags)`); const r = await resolveProject(projectArg, root); if (r.ambiguous) throw new ReadsUsage(`"${projectArg}" is the name of ${r.ambiguous.length} projects -- pass its id`); if (!r.project) throw new ReadsUsage(`no project matches "${projectArg}"`); @@ -99,13 +119,13 @@ export async function readsCommand(args, { root = REPORTS_ROOT, out = (s) => con const R = await import("./readsReplace.mjs"); if (flags.has("--say-only")) { const plan = await R.sayOnlyPlan(project, from, to, { ...opts, word: true, reportsRoot: root }); - const head = `EVERYWHERE, FROM NOW ON: "${plan.entry.word}" said "${plan.entry.say}"${plan.was ? ` (was "${plan.was}")` : ""} in every read of a post -- ${plan.stale.length} read(s) made stale: ${plan.stale.map((s) => s.id).join(", ") || "none"}${plan.cards.length ? `; ${R.SAY_NOT_CARDS} (${plan.cards.join(", ")})` : ""}`; + const head = `EVERYWHERE, FROM NOW ON: "${plan.entry.word}" said "${plan.entry.say}" in every read of a post${plan.was ? ` -- changes the existing entry (was "${plan.was}")` : ""} -- ${plan.stale.length} read(s) made stale: ${plan.stale.map((s) => s.id).join(", ") || "none"}${plan.cards.length ? `; ${R.SAY_NOT_CARDS} (${plan.cards.join(", ")})` : ""}`; if (flags.has("--dry-run")) { say({ ok: true, dryRun: true, scope: "say", entry: plan.entry, was: plan.was, stale: plan.stale, cards: plan.cards, matches: plan.matches }, head); return 0; } const done = await R.applySayOnly(project, from, to, { ...opts, word: true, reportsRoot: root }); - say({ ok: true, scope: "say", entry: done.result.entry, changed: done.result.changed, stale: plan.stale, cards: plan.cards }, `${head}\n ${done.result.changed}; undo: umtool posts say ${project.id} remove "${plan.entry.word}"`); + say({ ok: true, scope: "say", entry: done.result.entry, changed: done.result.changed, stale: plan.stale, cards: plan.cards }, `${head}\n ${done.result.changed}; undo: umtool reads ${project.id} undo (${plan.was ? `back to "${plan.was}"` : "the entry removed"})`); return 0; } const only = ids("--only"); @@ -127,20 +147,31 @@ export async function readsCommand(args, { root = REPORTS_ROOT, out = (s) => con return 0; } if (sub === "undo") { - const { undoReplace } = await import("./readsReplace.mjs"); - const res = await undoReplace(project); - say({ ok: true, ...res }, `${project.id}: the newest replace taken back`); + const R = await import("./readsReplace.mjs"); + const st = await R.replaceUndoState(project); + if (!st) throw new R.ReplaceError("nothing to undo: no replace was made here"); + if (flags.has("--dry-run")) { + say({ ok: true, dryRun: true, ...st }, st.available ? `would take back the newest ${st.scope === "say" ? `Everywhere ("${st.entry.word}"${st.was ? `, back to "${st.was.say}"` : ", the entry removed"})` : "replace of These reads"}` : `would refuse: ${st.why}`); + return 0; + } + const res = st.scope === "say" ? await R.undoSayOnly(project) : await R.undoReplace(project); + say({ ok: true, scope: st.scope, ...res }, st.scope === "say" ? (res.restored ? `"${res.restored.word}" is said "${res.restored.say}" again` : `the entry for "${res.removed.word}" removed`) : `${project.id}: the newest replace taken back`); return 0; } const Q = await import("./readsQueue.mjs"); if (sub === "reread" && str("--one") !== null) { - const res = await Q.runOneItem(project, str("--one"), ids("--only"), { reportsRoot: root, log: (s) => out(s) }); + const res = await Q.runOneItem(project, str("--one"), ids("--only"), { reportsRoot: root, log: (s) => !json && out(s) }); + if (json) out(JSON.stringify({ ok: res.code === 0, item: str("--one"), argv: res.argv, reads: res.reads, code: res.code }, null, 2)); return res.code; } if (sub === "reread") { const only = ids("--only"); - const res = await Q.enqueueRereads(project, { ...qo, only: only.length ? only : null }); - const head = res.steps.length ? `${res.steps.reduce((a, s) => a + s.reads.length, 0)} read(s) queued, ${res.steps.length} step(s), in cut order: ${res.steps.map((s) => `${s.qid} ${s.item}`).join(", ")}` : "nothing queued"; + const res = await Q.enqueueRereads(project, { ...qo, only: only.length ? only : null, dryRun: flags.has("--dry-run") }); + const head = res.steps.length ? `${res.steps.reduce((a, s) => a + s.reads.length, 0)} read(s) ${res.dryRun ? "would be queued" : "queued"}, ${res.steps.length} step(s), in cut order: ${res.steps.map((s) => `${s.qid ?? "-"} ${s.item}`).join(", ")}` : "nothing queued"; + if (res.dryRun) { + say({ ok: true, dryRun: true, steps: res.steps, skipped: res.skipped }, [head, ...res.skipped.map((s) => ` ${s.id}: ${s.why}`)].join("\n")); + return 0; + } const tail = res.skipped.map((s) => ` ${s.id}: ${s.why}`); if (!flags.has("--wait") || !res.steps.length) { say({ ok: true, batch: res.batch?.id ?? null, steps: res.steps, skipped: res.skipped }, [head, ...tail].join("\n")); @@ -188,8 +219,9 @@ export async function readsCommand(args, { root = REPORTS_ROOT, out = (s) => con if (sub === "pick") { if (flags.has("--new") === flags.has("--old")) throw new ReadsUsage("pick takes --new or --old"); const only = ids("--only"); - const res = await Q.pickReads(project, { which: flags.has("--new") ? "new" : "old", only: only.length ? only : null, reportsRoot: root }); - say({ ok: true, picked: res.picked, token: res.result.token ?? null }, `picked (${flags.has("--new") ? "the new reads" : "what played before"}): ${res.picked.map((x) => x.item).join(", ")} -- one undo point`); + const res = await Q.pickReads(project, { which: flags.has("--new") ? "new" : "old", only: only.length ? only : null, reportsRoot: root, dryRun: flags.has("--dry-run") }); + if (res.dryRun) say({ ok: true, dryRun: true, picked: res.picked }, `would pick (${flags.has("--new") ? "the new reads" : "what played before"}): ${res.picked.map((x) => x.item).join(", ")}`); + else say({ ok: true, picked: res.picked, token: res.result.token ?? null }, `picked (${flags.has("--new") ? "the new reads" : "what played before"}): ${res.picked.map((x) => x.item).join(", ")} -- one undo point`); return 0; } throw new ReadsUsage(`reads: replace, undo, reread, queue or pick (not ${sub}); none lists the reads`); diff --git a/umtool/lib/report/readsCli.test.mjs b/umtool/lib/report/readsCli.test.mjs @@ -104,3 +104,35 @@ test("SHOULD 6: his line from a synthesized take (--post-take) -- the page and ` assert.match(row.why, /take 1/); assert.equal(r.json.settingsStale, cast.count); }); + +// REVIEW 1, SHOULD 8: each subcommand refuses a flag it does not take (never ignores it); `--` ends the flags; +// --dry-run on undo, reread and pick changes nothing; errors keep the --json shape. +test("SHOULD 8: unknown flags refused; -- ends the flags; --dry-run changes nothing; --json errors", async () => { + const p = await readsProject(ROOT, "flags"); + let r = await cli(p, ["reread", "--bogus", "--json"]); + assert.equal(r.code, 2); + assert.match(r.json.error, /--bogus: not a flag of `reads <p> reread`/); + r = await cli(p, ["queue", "--dry-run"]); + assert.equal(r.code, 2, "queue takes no --dry-run"); + // A `to` that starts with dashes, after --. + r = await cli(p, ["replace", "--dry-run", "--json", "--", "north", "--north--"]); + assert.equal(r.code, 0, r.text); + assert.equal(r.json.lines[0].after.includes("--north-- pier"), true); + const m0 = await readManifestOf(p); + await cli(p, ["replace", "north", "northern"]); + const m1 = await readManifestOf(p); + r = await cli(p, ["undo", "--dry-run", "--json"]); + assert.deepEqual([r.code, r.json.dryRun, r.json.available], [0, true, true]); + assert.deepEqual(await readManifestOf(p), m1, "undo --dry-run undoes nothing"); + r = await cli(p, ["reread", "--dry-run", "--json"]); + assert.deepEqual(r.json.steps.map((s) => s.item), ["p-1", "c-1"]); + r = await cli(p, ["queue", "--json"]); + assert.equal(r.json.rows.length, 0, "reread --dry-run queues nothing"); + r = await cli(p, ["pick", "--new", "--dry-run", "--json"]); + assert.equal(r.code, 1, "nothing to pick: refused, as the real one would be"); + // queue --retry of a read never queued, and of a step that cannot be retried: the --json error shape. + r = await cli(p, ["queue", "--retry", "p-1", "--json"]); + assert.deepEqual([r.code, r.json.ok], [1, false]); + await cli(p, ["undo"]); + assert.deepEqual(await readManifestOf(p), m0); +});