// `umtool reads` -- A VIDEO's READS from the CLI (lane reads-find, S4 of plans/orpheus-retune.md; reads.mjs,
// readsReplace.mjs, readsQueue.mjs; umtool/docs/knobs.md, "The reads of a video"): every line a voice reads, Find over
// what is SPOKEN, Replace in two stated scopes, the re-read queue, and the picks after it. The Reads page
// (/projects/
/reads) runs these same functions.
//
// umtool reads
[--find [--case] [--word]] [--stale] [--character ] [--json]
// umtool reads replace [--case] [--word] [--say-only] [--only ] [--dry-run] [--json]
// umtool reads undo [--json]
// umtool reads
reread [--stale] [--only ] [--wait [--timeout ]] [--json]
// umtool reads reread --one - --only one queue step (the app runs it)
// umtool reads
queue [--stop] [--retry ] [--json]
// umtool reads pick --new|--old [--only ] [--json]
//
// Plain ESM: the CLI runs it under bare node.
import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
import { READ_KINDS, filterReads, findInReads, projectReads } from "./reads.mjs";
export const READS_USAGE = [
"usage: umtool reads [--find [--case] [--word]] [--stale] [--character ] [--json]",
" umtool reads replace [--case] [--word] [--say-only] [--only ,…] [--dry-run] [--json]",
" umtool reads undo [--dry-run] [--json]",
" umtool reads reread [--stale] [--only ,…] [--wait [--timeout ]] [--dry-run] [--json]",
" umtool reads queue [--stop] [--retry ] [--json]",
" umtool reads pick --new|--old [--only ,…] [--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),",
" unpicked (re-read, waiting for a pick), none (no take yet), recorded (yours: never stale, never re-read). A read's",
" id is its item's, and - / for a piece of a thread read (p-2/screen:s1:0). --find: the spoken text only,",
" without case unless --case, --word for whole words; --stale: the stale and unpicked; --character: one character's.",
" replace: THESE READS -- the spoken text of the matched reads rewritten in ONE undo point (a post's script, 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. --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 -- 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 puts a failed or stopped one back. pick --new: every unpicked",
" re-read made the one that plays; --old: the newest re-reads' reads back to what played before; one undo point.",
].join("\n");
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"]);
/**
* `umtool reads …`
* @param {string[]} args
* @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, sleep?: (ms: number) => Promise, queueDir?: string, tts?: Function | null }} [o]
* `tts`: the editor's tts op as a test hands it (postsCommand's), for `reread --one`
*/
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, tts = null } = {}) {
const flags = new Map();
const words = [];
let ended = false;
for (let i = 0; i < args.length; i += 1) {
const a = args[i];
// `--`: 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)) {
// A valued flag followed by another flag (or nothing) has no value: "" (refused where it matters, never eaten).
const v = args[i + 1];
if (v === undefined || (v.startsWith("--") && v !== "--")) flags.set(a, "");
else {
flags.set(a, v);
i += 1;
}
} 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);
// A list of ids: none when the flag is absent; refused when it is given and names none ("", ",", no value) -- an
// `--only` that names nothing never widens to every read.
const ids = (k) => {
const list = (str(k) ?? "").split(",").map((x) => x.trim()).filter(Boolean);
if (flags.has(k) && !list.length) throw new ReadsUsage(`${k} names no read (give the read ids, comma separated)`);
return list;
};
const json = flags.has("--json");
const [projectArg, sub = null, ...rest] = words;
if (!projectArg || flags.has("--help")) {
out(READS_USAGE);
return projectArg ? 0 : 2;
}
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 = Object.hasOwn(FLAGS_OF, sub ?? "") ? FLAGS_OF[sub ?? ""] : null;
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
${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}"`);
const project = r.project;
const qo = { reportsRoot: root, ...(queueDir ? { queueDir } : {}) };
const opts = { matchCase: flags.has("--case"), word: flags.has("--word") };
if (sub === null) {
const { rows, counts, tuningStale } = await projectReads(project, { reportsRoot: root });
let list = filterReads(rows, { stale: flags.has("--stale"), character: str("--character") });
let found = null;
if (str("--find") !== null) {
found = findInReads(list, str("--find"), opts);
list = found.rows;
}
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, state: x.state, because: x.because, take: x.take, newTake: x.newTake, ...(x.matches ? { matches: x.matches } : {}) });
say({ ok: true, project: project.id, counts, ...(found ? { find: { text: str("--find"), ...opts, matches: found.matches, lines: found.lines } } : {}), reads: list.map(view), settingsStale: tuningStale.length }, [
found ? `"${str("--find")}": ${found.matches} match${found.matches === 1 ? "" : "es"} in ${found.lines} line${found.lines === 1 ? "" : "s"} (spoken text only)` : `${project.id}: ${rows.length} read(s) -- ${Object.entries(counts).filter(([, n]) => n).map(([k, n]) => `${n} ${k}`).join(", ") || "none"}`,
...list.map((x) => ` ${x.state.padEnd(8)} ${x.id.padEnd(22)} ${READ_KINDS[x.kind]}${x.character ? ` · ${x.character.name}` : ""}${x.because.length ? ` (${x.because.join(", ")})` : ""} "${x.spoken.replace(/\s+/g, " ").slice(0, 80)}"`),
].join("\n"));
return 0;
}
if (sub === "replace") {
const [from, to] = rest;
if (from === undefined || to === undefined) throw new ReadsUsage('replace takes the words to find and what to say instead: replace "BRT" "B R T"');
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}" 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 reads ${project.id} undo (${plan.was ? `back to "${plan.was}"` : "the entry removed"})`);
return 0;
}
const only = ids("--only");
const plan = await R.replacePlan(project, from, to, { ...opts, only: only.length ? only : null, reportsRoot: root });
const lines = [
`THESE READS: "${from}" -> "${to}" in ${plan.lines.length} read(s) (${plan.matches} match${plan.matches === 1 ? "" : "es"}); the shown text is never changed`,
...plan.lines.map((l) => ` ${l.id}: "${l.before.replace(/\s+/g, " ").slice(0, 70)}" -> "${l.after.replace(/\s+/g, " ").slice(0, 70)}"${l.creates ? ` (${l.creates})` : ""}`),
...plan.skipped.map((s) => ` ${s.id}: not changed -- ${s.why}`),
...Object.entries(plan.notes).flatMap(([i, ns]) => ns.map((n) => ` ${i}: ${n}`)),
...Object.entries(plan.refused).flatMap(([i, es]) => es.map((e) => ` ${i}: REFUSED -- ${e}`)),
];
const view = { scope: "reads", find: from, to, ...opts, lines: plan.lines, skipped: plan.skipped, notes: plan.notes, refused: plan.refused, matches: plan.matches };
if (flags.has("--dry-run")) {
say({ ok: true, dryRun: true, ...view }, lines.join("\n"));
return 0;
}
const done = await R.applyReplace(project, from, to, { ...opts, only: only.length ? only : null, reportsRoot: root });
say({ ok: true, ...view, snapshot: done.result.snapshot?.rel ?? null, token: done.result.token ?? null }, `${lines.join("\n")}\n written: one undo point (umtool reads ${project.id} undo); the changed reads are stale -- umtool reads ${project.id} reread`);
return 0;
}
if (sub === "undo") {
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" && flags.has("--one")) {
// THE QUEUE STEP's FORM (the app runs it): one item, the reads it names -- never a dry run, a wait or every stale.
if (!str("--one")) throw new ReadsUsage("--one names the item (the queue's step: reread --one - --only )");
const clash = ["--dry-run", "--wait", "--stale", "--timeout"].filter((f) => flags.has(f));
if (clash.length) throw new ReadsUsage(`--one is the queue's step: it takes no ${clash.join(", ")} (umtool reads
reread [--only …] [--dry-run] [--wait] queues)`);
if (!flags.has("--only")) throw new ReadsUsage("--one takes --only (the reads its step was queued for)");
// With --json, stdout is one JSON document: the re-read command's own words go to stderr.
const res = await Q.runOneItem(project, str("--one"), ids("--only"), { reportsRoot: root, log: (s) => (json ? err(s) : out(s)), quiet: json ? { out: err, err } : null, ...(tts ? { tts } : {}) });
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, 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"));
return 0;
}
if (!json) out([head, ...tail].join("\n"));
const until = Date.now() + 1000 * (Number(str("--timeout")) > 0 ? Number(str("--timeout")) : 3600);
const mine = new Set(res.steps.map((s) => s.qid));
let said = null;
for (;;) {
const v = await Q.queueView(project, qo);
const rows = v.rows.filter((x) => mine.has(x.qid));
if (!rows.some((x) => x.state === "waiting" || x.state === "running")) {
const failed = rows.filter((x) => x.state !== "done");
say({ ok: !failed.length, rows }, failed.length ? `${failed.length} read(s) not re-read: ${failed.map((x) => `${x.read} (${x.state}${x.error ? `: ${x.error}` : ""})`).join("; ")}` : `re-read: ${rows.map((x) => x.read).join(", ")} -- each joined its list unpicked (umtool reads ${project.id} pick --new)`);
return failed.length ? 1 : 0;
}
if (!json && v.waiting && v.waiting !== said) out(` ${(said = v.waiting)}`);
if (Date.now() > until) {
say({ ok: false, rows, waiting: v.waiting }, `still going after --timeout: ${rows.map((x) => `${x.read} ${x.state}`).join(", ")}`);
return 3;
}
await sleep(2000);
}
}
if (sub === "queue") {
if (flags.has("--stop")) {
const res = await Q.stopQueue(project, qo);
say({ ok: true, ...res }, `${res.cancelled.length} step(s) stopped${res.running.length ? `; ${res.running.join(", ")} running: it finishes` : ""}`);
return 0;
}
if (str("--retry") !== null) {
const res = await Q.retryRead(project, str("--retry"), qo);
say({ ok: true, requeued: res.requeued }, res.said);
return 0;
}
const v = await Q.queueView(project, qo);
say({ ok: true, ...v }, [
v.rows.length ? `${project.id}: ${Object.entries(v.counts).filter(([, n]) => n).map(([k, n]) => `${n} ${k}`).join(", ")}` : `${project.id}: nothing queued`,
...(v.waiting ? [` ${v.waiting}`] : []),
...v.rows.map((x) => ` ${x.state.padEnd(8)} ${x.read.padEnd(22)} ${x.qid}${x.error ? ` -- ${x.error}` : ""}`),
].join("\n"));
return 0;
}
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, 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`);
} catch (e) {
const known = ["ReadsUsage", "ReplaceError", "QueueError", "StructureRefused", "StaleToken", "SayError"].includes(e?.constructor?.name) || e instanceof ReadsUsage;
if (!known) throw e;
const msg = e?.constructor?.name === "StructureRefused" ? e.errors.join("; ") : e.message;
if (json) out(JSON.stringify({ ok: false, error: msg }, null, 2));
else err(`umtool reads: ${msg}`);
return e instanceof ReadsUsage ? 2 : 1;
}
}