Archilyzer · Source

archilyzer

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

commit 216eedfec393db1c967131d920120003f90ef3d2
parent 898cb9f1ab062a3779e5aaefa39db9d82e2f1a99
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 12 Nov 2026 12:12:34 -0500

umtool, common, editor: anonymity re-check (FIX_FIRST #2) -- the set is the PROJECT's (project-characters-file.mjs projectAnonymousSet: the whole manifest on disk, every variant, before rulings, windows and --only, unioned with a take's), taken from one function by the build, the chrome composer, the lint, the podcast, Play, Present and the previews (onscreen.mjs scheduleForPreview: the chrome preview, still and onscreen routes share it; unresolvable or unread: 409); an anonymous author's item draws no corner QR and no cite or archive link (deck.mjs noQr); in drawn words an anonymous author's URL -- x/twitter/nitter/xcancel/fxtwitter/vxtwitter/fixupx/bsky/threads/truthsocial/youtube/instagram/tiktok, decoded, search from:, intent screen_name, truncated starts of 4+, or a status/post URL of one of their posts (the set's postIds) -- collapses to its bare host, @mentions keep the pseudonym, one pass; lint warns on an anonymous author's unclassified link; the podcast's show notes cite their posts by shown name with no link; a synthesized read says a bare handle (4+ characters, not a common word) as the shown name and keeps what it SAID (`said`), the lint judging that spoken text (no exemption list) and warning on a short or common handle; a shown name that is a real author's handle or name, or another character's handle, is refused (validator with the project's manifest, the writer, the set) and refusals name characters, never handles; the editor's cast-assign task scrubs anonymous handles from every word it sends; speed drift needs provenance (speedAsked true | "item" | "preset", written by the CLI, the thread read, the bench's Re-take through a sidecar, copied by derives) -- a pre-lane take is never speed drift and its re-read asks its own speed; deleteTake restores what moved and names any file left in the trash. Rollback note in knobs.md and the CHANGELOG. Probes 4-9 are tests; probe 7 (byte-identical when unused) still holds

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

Diffstat:
Mcommon/lib/report/draft/tasks/castAssign.test.ts | 23+++++++++++++++++++++--
Mcommon/lib/report/draft/tasks/castAssign.ts | 37+++++++++++++++++++++++++++----------
Meditor/CHANGELOG.md | 11+++++++++++
Mumtool/app/api/report/chrome/preview/route.ts | 13++++++++++++-
Mumtool/app/api/report/onscreen/route.ts | 13++++++++++++-
Mumtool/app/api/report/post-item/route.ts | 12+++++++-----
Mumtool/app/api/report/post-narration/route.ts | 21+++++++++++++++++----
Mumtool/app/api/report/still/route.ts | 13++++++++++++-
Mumtool/docs/knobs.md | 40++++++++++++++++++++++++++++++----------
Mumtool/lib/report/anonRead.test.mjs | 36+++++++++++++++++++++++++++++++-----
Mumtool/lib/report/castProject.mjs | 16+++++++++++-----
Mumtool/lib/report/castStore.mjs | 8+++++---
Mumtool/lib/report/driftSpeed.test.mjs | 32++++++++++++++++++++++++++------
Mumtool/lib/report/onscreen.mjs | 13++++++++++++-
Mumtool/lib/report/postNarrationCli.mjs | 39+++++++++++++++++++++++++--------------
Mumtool/lib/report/postThreadRead.mjs | 3++-
Mumtool/lib/report/present.mjs | 30++++++++++++++++++++++--------
Mumtool/report-to-video/build-podcast.mjs | 21+++++++++++++++++----
Mumtool/report-to-video/build-video.mjs | 6++++--
Mumtool/report-to-video/cast.mjs | 42+++++++++++++++++++++++++++++++++++++++++-
Mumtool/report-to-video/compose-chrome.mjs | 6++++--
Mumtool/report-to-video/deck.mjs | 2++
Mumtool/report-to-video/lint.mjs | 6++++--
Mumtool/report-to-video/package.json | 1+
Mumtool/report-to-video/post-anon.mjs | 252++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mumtool/report-to-video/post-anon.test.mjs | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mumtool/report-to-video/post-narration.mjs | 11++++++-----
Mumtool/report-to-video/project-characters-file.mjs | 18++++++++++++++++++
28 files changed, 683 insertions(+), 166 deletions(-)

diff --git a/common/lib/report/draft/tasks/castAssign.test.ts b/common/lib/report/draft/tasks/castAssign.test.ts @@ -10,7 +10,7 @@ import os from "node:os"; import path from "node:path"; import { jsonReply, startFakeOllama, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs"; import { symlink } from "node:fs/promises"; -import { CAST_ASSIGN_FILE, CAST_CODE_MODEL, CastAssignRefusal, STOCK_VOICE_SPECS, anonymousAuthorsOf, castAssignAnswers, castAuthors, castView, planCastAssign, runCastAssign } from "./castAssign"; +import { CAST_ASSIGN_FILE, CAST_CODE_MODEL, CastAssignRefusal, STOCK_VOICE_SPECS, anonymousAuthorsOf, castAssignAnswers, castAuthors, castView, planCastAssign, runCastAssign, scrubAnonymous } from "./castAssign"; import { GENERATION_PRESETS, GENERATION_TASKS, sanitizeGeneration } from "../../../generationSettings"; import type { LlmConfig } from "../../../llm"; @@ -123,7 +123,7 @@ test("an anonymous author is never sent: a character's handles, an item naming o await writeFile(path.join(dir, "narration", "characters.json"), JSON.stringify({ format: "umtool-project-characters", version: 1, characters: [{ id: "anon-s", name: "S", anonymous: true, shown: "Anon S", handles: ["stranger"] }, { id: "anon-o", name: "O", anonymous: true, shown: "Anon O", handles: [] }], proposed: [{ id: "host", name: "Host", anonymous: true, shown: "Anon H", handles: ["host"], synthetic: { voice: "kokoro:am_adam" }, by: "person" }] })); - assert.deepEqual([...(await anonymousAuthorsOf(dir, m))].sort(), ["host", "other", "stranger"]); + assert.deepEqual([...(await anonymousAuthorsOf(dir, m)).keys()].sort(), ["host", "other", "stranger"]); const asked = ol.requests.length; await assert.rejects(runCastAssign({ project: dir, model: "qwen3:8b", handles: ["stranger", "other", "host"] }, { llm }), /only anonymous ones/); assert.equal(ol.requests.length, asked, "no model asked"); @@ -153,3 +153,22 @@ test("the answers are written inside the project only: a narration symlink, a sy await assert.rejects(runCastAssign({ project: dir2, model: "qwen3:8b", handles: ["host"] }, { llm }), /cast-assign.json is a symlink/); assert.equal(existsSync(path.join(elsewhere, "x.json")), false); }); + +test("re-check d: an anonymous author's handle in anyone's words never reaches a model -- @mentions and their URLs", async () => { + const anon = new Map([["realguy", "Anon 1"]]); + assert.equal(scrubAnonymous("@realguy is lying, see https://x.com/RealGuy/status/1 and x.com/public", anon), "@Anon_1 is lying, see x.com/… and x.com/public"); + const dir = await project("scrub"); + const m = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + m.timeline[0].text = "@realguy is lying"; + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m)); + await mkdir(path.join(dir, "narration"), { recursive: true }); + await writeFile(path.join(dir, "narration", "characters.json"), JSON.stringify({ format: "umtool-project-characters", version: 1, characters: [{ id: "a1", name: "A", anonymous: true, shown: "Anon 1", handles: ["realguy"] }] })); + let prompt = ""; + ol.push((body: { messages: { role: string; content: string }[] }) => { + prompt = body.messages.find((x) => x.role === "user")!.content; + return jsonReply({ authors: [{ handle: "host", character: "Host", voice: "kokoro:am_adam" }] }); + }); + await runCastAssign({ project: dir, model: "qwen3:8b", handles: ["host"] }, { llm }); + assert.match(prompt, /post: @Anon_1 is lying/); + assert.ok(!/realguy/i.test(prompt)); +}); diff --git a/common/lib/report/draft/tasks/castAssign.ts b/common/lib/report/draft/tasks/castAssign.ts @@ -109,13 +109,13 @@ export type CastAuthor = { handle: string; name: string; bio: string; posts: str * post-anon.mjs rule, read here from `<project>/narration/characters.json` (common never imports umtool). No file: * none. A file that cannot be read or parsed REFUSES the ask (an anonymous author could be sent). */ -export async function anonymousAuthorsOf(dir: string, manifest: Record<string, unknown>): Promise<Set<string>> { +export async function anonymousAuthorsOf(dir: string, manifest: Record<string, unknown>): Promise<Map<string, string>> { const file = path.join(dir, "narration", "characters.json"); let raw: string; try { raw = await readFile(file, "utf8"); } catch (e) { - if ((e as NodeJS.ErrnoException)?.code === "ENOENT") return new Set(); + if ((e as NodeJS.ErrnoException)?.code === "ENOENT") return new Map(); throw new CastAssignRefusal(`${file} cannot be read (${(e as Error).message}): an anonymous author could be sent to a model -- nothing asked`); } let doc: { characters?: unknown; proposed?: unknown }; @@ -124,24 +124,40 @@ export async function anonymousAuthorsOf(dir: string, manifest: Record<string, u } catch (e) { throw new CastAssignRefusal(`${file} is not JSON (${(e as Error).message}): an anonymous author could be sent to a model -- nothing asked`); } - const out = new Set<string>(); - const ids = new Set<string>(); + // handle -> the shown name the words are rewritten with (umtool's pass draws the same). + const out = new Map<string, string>(); + const ids = new Map<string, string>(); for (const list of [doc?.characters, doc?.proposed]) { for (const c of Array.isArray(list) ? (list as Record<string, unknown>[]) : []) { if (!c || typeof c !== "object" || c.anonymous !== true) continue; - if (typeof c.id === "string") ids.add(c.id.toLowerCase()); - for (const h of Array.isArray(c.handles) ? c.handles : []) if (handleKey(h)) out.add(handleKey(h)); + const shown = typeof c.shown === "string" && c.shown.trim() ? c.shown.trim() : "Anon"; + if (typeof c.id === "string") ids.set(c.id.toLowerCase(), shown); + for (const h of Array.isArray(c.handles) ? c.handles : []) if (handleKey(h) && !out.has(handleKey(h))) out.set(handleKey(h), shown); } } for (const e of (Array.isArray(manifest.timeline) ? manifest.timeline : []) as (Post & { narration?: { character?: unknown } })[]) { const id = typeof e?.narration?.character === "string" ? e.narration.character.trim().toLowerCase() : ""; - if (e?.type === "post" && id && ids.has(id) && handleKey(e.handle)) out.add(handleKey(e.handle)); + if (e?.type === "post" && id && ids.has(id) && handleKey(e.handle) && !out.has(handleKey(e.handle))) out.set(handleKey(e.handle), ids.get(id)!); } return out; } +const escRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +const pseudonym = (shown: string) => shown.replace(/[^A-Za-z0-9_]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 64) || "anon"; + +/** + * An author's words as they may reach a model: an @mention of an anonymous author made the pseudonym ("@Anon_1"), + * a platform URL naming one collapsed to its host -- umtool's post-anon.mjs rule, in one pass. + */ +export function scrubAnonymous(text: string, anon: Map<string, string>): string { + if (!text || !anon.size) return text; + const hs = [...anon.keys()].sort((a, b) => b.length - a.length).map(escRe).join("|"); + const re = new RegExp(String.raw`(?<![\w.@])@(${hs})(?![A-Za-z0-9_]|\.[A-Za-z0-9])|(?<![\w@.\-/])(?:https?:\/\/)?(?:(?:www|mobile|m)\.)?((?:x|twitter|nitter|xcancel|fxtwitter|vxtwitter|fixupx|truthsocial|youtube|instagram|tiktok)\.(?:com|net)|bsky\.app|threads\.(?:net|com))\/(?:profile\/|@)?(${hs})(?![A-Za-z0-9_]|\.[A-Za-z0-9])[^\s]*`, "giu"); + return text.replace(re, (all, at: string | undefined, host: string | undefined) => (at ? `@${pseudonym(anon.get(at.toLowerCase()) ?? "Anon")}` : host ? `${host.toLowerCase()}/…` : all)); +} + /** The authors to ask about, from the cut's post items: each one's display name, bio (when captured) and words. */ -export function castAuthors(manifest: Record<string, unknown>, handles?: string[], { except = new Set<string>() }: { except?: Set<string> } = {}): CastAuthor[] { +export function castAuthors(manifest: Record<string, unknown>, handles?: string[], { except = new Map<string, string>() }: { except?: Map<string, string> } = {}): CastAuthor[] { const want = handles?.length ? new Set(handles.map(handleKey)) : null; const out = new Map<string, CastAuthor>(); for (const e of (Array.isArray(manifest.timeline) ? manifest.timeline : []) as Post[]) { @@ -150,8 +166,9 @@ export function castAuthors(manifest: Record<string, unknown>, handles?: string[ if (!h || !HANDLE_RE.test(h) || (want && !want.has(h)) || except.has(h)) continue; const a = out.get(h) ?? { handle: h, name: "", bio: "", posts: [] }; if (!a.name) a.name = plainLine(e.author, NAME_MAX); - if (!a.bio) a.bio = plainLine([e.pronouns, e.bio].filter((x) => typeof x === "string").join(" "), 300); - const text = plainLine(e.text, 400); + // An anonymous author's handle in anyone's words never reaches a model (scrubAnonymous). + if (!a.bio) a.bio = plainLine(scrubAnonymous([e.pronouns, e.bio].filter((x) => typeof x === "string").join(" "), except), 300); + const text = plainLine(scrubAnonymous(typeof e.text === "string" ? e.text : "", except), 400); if (text && a.posts.length < 3) a.posts.push(text); out.set(h, a); } diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,17 @@ # Changelog ## [Unreleased] +- **umtool: anonymity covers the whole project, every link, the podcast and the previews; old reads keep their speed.** Re-checking the anonymous characters found several gaps. An item that named one in another variant, or one dropped by a ruling, `--only`, a window or a take, left the author in clear. The deck's corner QR on an anonymous author's post item still led to the real post. Links were rewritten with the status id kept. The podcast's show notes and the chrome preview, still and onscreen routes had no pass at all. Now: + - The set is built from the whole project manifest (and a take's), and the build, the chrome composer, the podcast, Play, Present and the previews all take it from one function. + - An anonymous author's item draws no QR and no cite or archive link. + - In drawn words, a link to an anonymous author (more hosts now, decoded and truncated forms too) or to one of their posts collapses to its bare host, e.g. `x.com/…`. + - The show notes cite those posts by the shown name with no link. + - A synthesized read now says a bare handle as the shown name too, and the take keeps what it actually said. Lint judges that spoken text, and warns on short or common-word handles and on links it can't classify. + - A shown name that matches a real author's handle or name is refused. A refusal names characters, never a handle. + - A model is never sent an anonymous author's handle, even in someone else's post. + - Speed drift is claimed only where a take records where its speed came from. A take made before this has no such record: it is never flagged, and a re-read asks for its own speed again. + - A failed take delete names any file it could not put back. + - **Rollback note:** an earlier umtool refuses takes that carry `said` or `speedAsked`, and proposals with `by: "person"`. Those keys are written only when they carry information (knobs.md says by which action). - **umtool: anonymity belongs to the handle, everywhere the video shows or says it.** Review of the anonymous characters found real names getting through. An item that named another character still showed its author's real name. A character named on one item didn't cover the same author's other posts. Handles inside x.com and Bluesky links were drawn as written, deck popup posts weren't anonymised at all, a read said "@handle" aloud, and deleting a recording could break a thread read made from it. Now one set of anonymous handles is built per video: every handle an anonymous character lists, plus the author of every item that names one. The build, the chrome composer and Play all draw from it: post cards, mentions and platform URLs (rewritten in one pass), deck popup posts (without their screenshot and QR code), the promise panel and chat replay names. A captured thread shot is not drawn while the video has any anonymous author. A synthesized read says the shown name, and the take records that it did. A recorded or older take that says the handle or the display name is a lint error. A display name written inside post text is a lint warning, and names inside attachments are said to be the operator's to check. An unreadable `characters.json`, or anonymity that can't be resolved, now stops the build, Play's card and a read. Two anonymous characters can no longer share a shown name. In `cast assign`, a row changed by hand belongs to the person: a model never sees it or overwrites it. An author covered by an anonymous character is never sent to a model at all. The model's prompt keeps the authors' words fenced, and its answers file is refused through a symlink. A take that a thread read uses can't be deleted (nothing is moved). A single take made with `--speed` keeps that speed: it isn't flagged as drift, and a re-read asks for the same speed. A thread take that mixes synthesized and recorded parts says so in its disclosure. - **umtool: the model can propose characters too, only when you ask.** `umtool cast assign <p> --model` (the Voices page's "Ask the model too (optional)") asks a new generation task, `cast-assign`, routed by `settings.generation` like the others (local in every preset but `api`), about the authors the rule proposed for. The model gets each author's display name, bio and a few of their posts, fenced as data, and answers with a name, a stock voice, a speed and a direction. Each field is checked: the voice must be a stock voice, the speed 0.5–2, the name and the direction one plain line. The editor job writes only `narration/cast-assign.json`, and umtool lays the checked fields over its own proposed rows through its one writer. Where the answer fails, the rule's row stays; if the model cannot be reached, the command exits 1 and the rule's proposals stand. `--model --dry-run` asks nothing. The model is never asked without the flag or the button, and the MCP's `generate` does not offer the task. - **umtool: a character's changed speed shows its reads as stale.** Changing a character's preset speed left every read made at the old speed looking current: drift compared voices only. A picked read synthesized at another speed than the one it would be asked at now (the item's own, else the preset's; a thread read keeps the `--speed` it was made with) is now listed as drift on the Voices page, in `umtool cast project` and in `umtool lint`, as "kokoro:am_michael ×1.1 → ×1.25", and `cast reread` re-reads it. Orpheus reads and converted recordings never drift by speed. diff --git a/umtool/app/api/report/chrome/preview/route.ts b/umtool/app/api/report/chrome/preview/route.ts @@ -136,7 +136,18 @@ export async function POST(request: Request) { return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 404 }); } } - const { variantManifest, schedule } = await scheduleForPreview(r.project, manifest, r.variant, draft, postsDraft, { claimsDraft, estimate }); + // Anonymity unresolvable, or this video's characters unread (onscreen.mjs scheduleForPreview): 409, as Play. + let preview; + try { + preview = await scheduleForPreview(r.project, manifest, r.variant, draft, postsDraft, { claimsDraft, estimate }); + } catch (e) { + if ((e as { anonymity?: boolean }).anonymity) { + const msg = e instanceof Error ? e.message : String(e); + return Response.json({ error: msg }, { status: 409 }); + } + throw e; + } + const { variantManifest, schedule } = preview; const render = (variantManifest.render ?? {}) as Record<string, unknown>; if (!deckOn(render)) { return Response.json( diff --git a/umtool/app/api/report/onscreen/route.ts b/umtool/app/api/report/onscreen/route.ts @@ -45,7 +45,18 @@ export async function GET(request: Request) { const r = await resolveReport(url.searchParams.get("project") ?? "", url.searchParams.get("variant")); if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); - const { variantManifest: cut, metas, schedule } = await scheduleForPreview(r.project, r.manifest, r.variant); + // Anonymity unresolvable, or this video's characters unread (onscreen.mjs scheduleForPreview): 409, as Play. + let preview; + try { + preview = await scheduleForPreview(r.project, r.manifest, r.variant); + } catch (e) { + if ((e as { anonymity?: boolean }).anonymity) { + const msg = e instanceof Error ? e.message : String(e); + return Response.json({ error: msg }, { status: 409 }); + } + throw e; + } + const { variantManifest: cut, metas, schedule } = preview; const entries = (cut.timeline ?? []) as Entry[]; const render = cut.render ?? {}; const deck = resolveDeck(render); diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts @@ -23,7 +23,7 @@ import { withTakeScope } from "@/lib/report/takeScope.mjs"; import { isTakeId } from "@/lib/report/takes.mjs"; import { projectRedaction } from "@/lib/report/postRedaction.mjs"; import { readProjectCharacters } from "@/lib/report/castStore.mjs"; -import { anonymiseManifest } from "umtool-report-to-video/post-anon"; +import { anonymiseManifest, anonymousHandles } from "umtool-report-to-video/post-anon"; export const dynamic = "force-dynamic"; @@ -68,11 +68,13 @@ type Entry = Record<string, unknown> & { id: string; type?: string; media?: Arra * resolve REFUSES the card (CardRefused) -- never a card with the real names. */ class CardRefused extends Error {} -async function anonymised(project: { dir: string }, m: Record<string, unknown>) { +async function anonymised(project: { dir: string }, m: Record<string, unknown>, base: Record<string, unknown> | null = null) { const read = await readProjectCharacters(project.dir).catch((e: unknown) => ({ doc: null, error: e instanceof Error ? e.message : String(e) })); if (read.error) throw new CardRefused(`this video's characters are not read (${read.error}): an anonymous author could be drawn under their own name -- fix narration/characters.json first`); try { - return anonymiseManifest(m, read.doc) as Record<string, unknown>; + // The PROJECT's set: the project's manifest (every variant) and the take's, applied to the card's manifest. + const set = anonymousHandles(read.doc, ...[base, m].filter(Boolean)); + return anonymiseManifest(m, read.doc, { set }) as Record<string, unknown>; } catch (e) { throw new CardRefused(e instanceof Error ? e.message : String(e)); } @@ -81,7 +83,7 @@ async function anonymised(project: { dir: string }, m: Record<string, unknown>) async function itemOf(project: { dir: string }, manifest: Record<string, unknown>, id: string, take: string | null, { anon = false }: { anon?: boolean } = {}) { let m = manifest; if (take) m = (await resolveTakeManifest(project.dir, take, { base: manifest })).manifest as Record<string, unknown>; - if (anon) m = await anonymised(project, m); + if (anon) m = await anonymised(project, m, manifest); const tl = (Array.isArray(m.timeline) ? m.timeline : []) as Entry[]; const at = tl.findIndex((e) => e?.type === "post" && e.id === id); // `ctx`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in) and the scene its @@ -171,7 +173,7 @@ export async function GET(request: Request) { return new Response(e instanceof Error ? e.message : String(e), { status: 400 }); } try { - m = await anonymised(r.project, m); + m = await anonymised(r.project, m, r.manifest as Record<string, unknown>); } catch (e) { return new Response(e instanceof Error ? e.message : String(e), { status: 409, headers: noStore }); } diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -1,4 +1,4 @@ -import { mkdir, readdir, rm, stat, writeFile } from "node:fs/promises"; +import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { POST_DERIVE_OPS, POST_DERIVE_ROUTES, derivedFileOf, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takeIdOf, takesDirOf, @@ -126,7 +126,7 @@ export async function GET(request: Request) { const derive = q.get("derive"); if (derive !== null) { // A derived take: source the take it came from, its step recorded, its parts (renamed) kept. - const takes = (e.narration?.takes ?? []) as Array<{ file: string; voice?: string; script?: string; parts?: Array<{ n: number }> }>; + const takes = (e.narration?.takes ?? []) as Array<{ file: string; voice?: string; script?: string; parts?: Array<{ n: number }>; speed?: number; speedAsked?: true | "item" | "preset"; said?: string }>; const from = takes[Number(derive)]; if (!from) return Response.json({ state: "failed", error: `no take ${derive}` }, { headers: noStore }); const op = String(q.get("op") ?? ""); @@ -142,6 +142,8 @@ export async function GET(request: Request) { file: rel, engine: "derived", voice: (voice ? voice.split(":").pop() : null) ?? from.voice ?? "?", seconds: meas.seconds, source: { kind: "take", from: takeIdOf(from) }, steps: [{ op, ...(engine ? { engine } : {}), ...(voice ? { voice } : {}), ...pitched, ranAt: new Date().toISOString(), job }], script: from.script ?? script, at: new Date().toISOString(), jobId: job, ...(Number.isFinite(meas.lufs) ? { lufs: meas.lufs } : {}), + // Its audio is its source's words at its source's speed: what it said and where that speed came from. + ...(typeof from.speed === "number" ? { speed: from.speed } : {}), ...(from.speedAsked !== undefined ? { speedAsked: from.speedAsked } : {}), ...(typeof from.said === "string" ? { said: from.said } : {}), ...(Array.isArray(from.parts) ? { parts: from.parts.map((p) => ({ ...p, file: `${partsRel}/p${String(p.n).padStart(2, "0")}.wav` })) } : {}), }; const { result } = await withEditNotes(r.project, async () => updatePostNarration(r.project.dir, id, { addTake: derived }, { token: await manifestToken(r.project.dir) })); @@ -149,8 +151,16 @@ export async function GET(request: Request) { } // What its audio does with the script's slurs (post-slurs.mjs): as the POST above asked for it. const red = await projectRedaction(r.project.dir, m); - const { slurs, lexicon } = spokenRead(script, e, red, { voice: benchVoice(red) }); + const spoken = spokenRead(script, e, red, { voice: benchVoice(red) }); + const { slurs, lexicon } = spoken; + // What the POST asked (its speed and where it came from), kept beside the file until the take is made. + const askFile = `${abs}.ask.json`; + const ask = (await readFile(askFile, "utf8").then(JSON.parse, () => null)) as { speed?: number; speedAsked?: true | "item" | "preset" } | null; + await rm(askFile, { force: true }); const take = { + ...(typeof ask?.speed === "number" ? { speed: ask.speed } : {}), ...(ask?.speedAsked !== undefined ? { speedAsked: ask.speedAsked } : {}), + // What it said, when an anonymous handle made that differ from the script (post-anon.mjs; the lint reads it). + ...(spoken.anonymised ? { said: spoken.text } : {}), ...(slurs ? { slurs } : {}), // The pronunciation entries it said (post-say.mjs), as the POST above applied them. ...(lexicon ? { lexicon } : {}), @@ -267,7 +277,10 @@ async function postHere(request: Request) { // so a beep falls back to skip here (the CLI's --take times it and beeps). const red = await projectRedaction(r.project.dir, m); const spoken = spokenRead(script, e, red, { voice: benchVoice(red) }).text; - const jobId = await startJob("/api/ops/tts", { text: spoken, engine, voice, out: path.join(r.project.dir, ...rel.split("/")), ...(speed ? { speed } : {}) }); + const out = path.join(r.project.dir, ...rel.split("/")); + // Its speed and where it came from, for the take the GET makes when the job is done (a sidecar, removed then). + if (speed) await writeFile(`${out}.ask.json`, JSON.stringify({ speed, speedAsked: body.speed !== undefined && body.speed !== null ? true : (e.narration as { speed?: number } | undefined)?.speed != null ? "item" : "preset" })); + const jobId = await startJob("/api/ops/tts", { text: spoken, engine, voice, out, ...(speed ? { speed } : {}) }); return Response.json({ ok: true, jobId, file: rel, engine, voice, script }, { headers: noStore }); } if (body.op === "derive") { diff --git a/umtool/app/api/report/still/route.ts b/umtool/app/api/report/still/route.ts @@ -23,7 +23,18 @@ export async function GET(request: Request) { const r = await resolveReport(url.searchParams.get("project") ?? "", url.searchParams.get("variant")); if ("error" in r) return new Response(r.error, { status: r.status }); - const { variantManifest, schedule } = await scheduleForPreview(r.project, r.manifest, r.variant); + // Anonymity unresolvable, or this video's characters unread (onscreen.mjs scheduleForPreview): 409, as Play. + let preview; + try { + preview = await scheduleForPreview(r.project, r.manifest, r.variant); + } catch (e) { + if ((e as { anonymity?: boolean }).anonymity) { + const msg = e instanceof Error ? e.message : String(e); + return new Response(msg, { status: 409 }); + } + throw e; + } + const { variantManifest, schedule } = preview; const render = (variantManifest.render ?? {}) as Record<string, unknown>; if (!deckOn(render)) return new Response("the deck is off for this manifest", { status: 409 }); const { chrome, ...rest } = render; diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -1491,8 +1491,10 @@ human-filtered voices". A character carries two, picked by how the read is made: the tts op's; absent: 1). Speed is the only parameter the tts op takes beside the voice (Orpheus's emotion is in the script, its `<sigh>` `<laugh>` tags; Orpheus has no speed and is asked none). It reaches a single take, the bench's Re-take and every part of a thread read; `--speed` on the command wins, then the item's own `narration.speed`. - A single take made with `--speed` records `speedAsked`: that speed is kept as asked (not drift; `cast reread` asks - it again), as a thread read's `read.speed` is. + A take records where its speed came from (`speedAsked`: `true` the command's `--speed`, `"item"` the item's own, + `"preset"` the character's). Speed DRIFT is claimed only for `"item"` / `"preset"` takes; one asked by its command is + kept as asked, and a take that says nothing (made before it was recorded) is never speed drift. `cast reread` of a + take whose speed is not 1 asks that speed again, unless it came from the item or the preset (the new one applies). A picked read synthesized at another speed than the one it would be asked at now is **drift**, as one in another voice is (`umtool cast project <p>`, the Voices page, `umtool lint`: "kokoro:am_michael ×1.1 -> ×1.25"; a thread read made with `--speed` keeps it as asked; Orpheus and a converted recording never drift by speed). @@ -1512,10 +1514,12 @@ synthetic voice), never from a preset. writer in `castStore.mjs` -- `projectCharactersWrite`: a token, an undo point a write in `characters.undo.json`, atomic, a broken file never overwritten) are the cast's shape, for people who must **not enter the pool**: they live in that video only. One may be **`anonymous: true`** with a **`shown`** name -- what the Voices page, `umtool cast -project` and a recording's note call them, never their own name -- and on the cut (`post-anon.mjs`, the build's, -the chrome composer's and Play's one pass). **Anonymity belongs to the HANDLE, project-wide**: one set of anonymous -handles is built -- every handle an anonymous character lists, and the author handle of every item that names an -anonymous character by id -- and every surface below consults it, never an item's `narration.character` alone (the +project` and a recording's note call them, never their own name -- and on the cut (`post-anon.mjs`, one pass for +the build, the chrome composer, the podcast, Play, Present and the previews). **Anonymity belongs to the HANDLE, +project-wide**: ONE set of anonymous handles is built (`project-characters-file.mjs` `projectAnonymousSet`) from the +WHOLE project manifest -- every variant, before rulings, windows or `--only`, and a take's own manifest too -- every +handle an anonymous character lists, and the author handle of every item that names an anonymous character by id -- +and every surface below consults it, never an item's `narration.character` alone (the character an item names decides its voice; the set decides who is shown). An item naming an anonymous character with no handle of its own, or one handle under two shown names, REFUSES the build and Play's card. Two anonymous characters are never shown alike (refused); one with no `shown` gets a distinct "Anon n" by id order. @@ -1523,20 +1527,36 @@ characters are never shown alike (refused); one with no `shown` gets a distinct | surface | anonymous handle | |---|---| | a post card: the item's head and strip, parents, quoted and linked posts, a repost line, "Replying to", a thread read's and a scene's tiles, a side card, the vertical cut | **covered**: the shown name alone (no handle beside it), no badge, a neutral avatar (its initial on the card's muted colour, never their picture); not blurred by the privacy rule (`redact: true` still blurs) | -| an @mention or a platform URL in drawn words (x.com / twitter.com /handle…, bsky.app/profile/handle…, threads, truthsocial, youtube @) | **covered**: the pseudonym (`@Anon_1`, `x.com/Anon_1/status/…`), one word for one, in ONE pass (no chaining) | +| an @mention in drawn words | **covered**: the pseudonym (`@Anon_1`), one word for one, in ONE pass (no chaining) | +| a URL in drawn words that names an anonymous handle (x.com, twitter.com, nitter, xcancel, fxtwitter, vxtwitter, fixupx, bsky.app/profile, threads, truthsocial, youtube @, instagram, tiktok; decoded; `search?q=from:`, `intent/user?screen_name=`; a truncated one whose 4+ visible characters start a handle) or is a status/post URL of a post an anonymous author wrote | **covered**: collapsed to its bare host (`x.com/…`) | +| any other URL in an anonymous author's own words | **warned** (lint): drawn as written | +| a post ITEM's corner QR, its cite or archive link | **not drawn** for an anonymous author's item (`noQr`) | | a captured thread shot of a post item | **not drawn** while the video has any anonymous handle (it pictures posts whose authors cannot all be known); lint warns | | a deck popup post (`posts[]`) by an anonymous handle, its feed | **covered**: the shown name, no screenshot, no QR code (both would name them); a popup's thread shot not drawn; lint warns | | the promise panel's speakers, a chat replay's names and words | **covered**: the pseudonym / the shown name, no picture | | the chapters a build makes, the deck subtitle | **covered** | -| a SYNTHESIZED read (a single take, a thread read's parts) | **covered**: the handle said as the shown name; the take records `anonymised` | -| a recorded take, or one made before, that says a handle or the display name | **refused**: a lint ERROR on the picked read (a take refuses it): read or record it again | +| the podcast's show notes (`out/<variant>/show-notes.md`) | **covered**: an anonymous author's post cited by the shown name, with no link | +| Present mode's payload; the chrome preview, the still and the onscreen routes (`scheduleForPreview`) | **covered**; unresolvable or unread: 409 | +| `umtool export` (chapters, toc, description) | **not affected**: it names clips and their links only, never a post's author or url | +| YouTube / social drafts (the editor's media tasks) | **not affected**: they read clips and the report, never the post items' authors | +| a SYNTHESIZED read (a single take, a thread read's parts; the bench's Re-take) | **covered**: the @handle -- and the bare handle, when 4+ characters and not a common word -- said as the shown name; a single take keeps what it SAID (`said`) when that differs from its script | +| a short or common-word handle said bare | **warned** (lint): said as written | +| a recorded take, or one made before, that says a handle or the display name | **refused**: a lint ERROR on the picked read, judged on what it SAID (`said`, else its script; a thread's parts) -- a take refuses it: read or record it again | +| a shown name (or its pseudonym) that is a real author's handle or name, or another character's handle | **refused** (the writer, the build, Play) | | `characters.json` unreadable, or refused | **refused**: the build, Play's card and a read | | a display name written out inside post words | **warned** (lint): not rewritten -- edit the words or redact the name | | names or handles inside attachments (pictures, receipts, a screenshot's own reply line) | **not covered**: yours to check (lint says so) | | `umtool export --format chapters` | **not covered**: it reads the manifest as written | A cut with no anonymous handle renders byte-identically to before. An `anonymous` flag a manifest carries itself is -stripped by the pass: only the pass sets it. The default is the next unused of **"Anon 1", "Anon 2" …** (`cast.mjs` +stripped by the pass: only the pass sets it. A refusal names characters and items, never a real handle. + +**ROLLBACK NOTE.** An umtool from before this lane REFUSES a manifest whose takes carry `said` or `speedAsked`, and a +characters file whose proposals say `by: "person"`. They are written only when they carry information: `said` by a +synthesized read whose words named an anonymous handle (posts narrate --take, --take --thread is not, the bench's +Re-take, a derive of such a take); `speedAsked` by a read that was asked a speed (the flag, the item's own, the +preset's; a derive copies it); `by: "person"` by `umtool cast assign --change` and the Voices page's Change. Before +rolling back, re-read or delete those takes (or remove the keys) and accept or reject the changed proposals. The default is the next unused of **"Anon 1", "Anon 2" …** (`cast.mjs` `ANON_NAME_PATTERN`, the one place the pattern is written). A preset is optional here: a character with no synthetic voice leaves the voice to the layers under it. It has no narrator (the narrator is the cast's). `narration/voices.json` keeps working under it and is never rewritten by these commands. diff --git a/umtool/lib/report/anonRead.test.mjs b/umtool/lib/report/anonRead.test.mjs @@ -48,12 +48,14 @@ test("a synthesized read says the shown name: a single take and a thread read's const m = await manifest(); const t = await makeTake(project, m.timeline[0], { render: m.render, ask: stubAsk(asked), redaction: red }); assert.equal(asked[0].text, "Thanks Anon 1 for this."); - assert.deepEqual(t.take.anonymised, ["realguy"]); - assert.equal(t.take.script, "Thanks @RealGuy for this.", "the script kept as written; anonymised records what was said"); + assert.equal(t.take.said, "Thanks Anon 1 for this.", "what it said is kept: the lint reads it"); + assert.equal(t.take.script, "Thanks @RealGuy for this.", "the script kept as written"); + assert.equal(t.take.speedAsked, undefined, "no speed asked: no key"); const r = await threadTake(project, (await manifest()).timeline[1], { red, ask: stubAsk(asked), lanes: null, map: {}, cast: {}, item: null }); const parentAsk = asked.find((b) => /anything/.test(b.text)); assert.equal(parentAsk.text, "Ask Anon 1 anything"); - assert.deepEqual(r.take.anonymised, ["realguy"]); + assert.equal(r.take.said, undefined, "a thread take's script IS what it said"); + assert.ok(!/realguy/i.test(r.take.script)); for (const b of asked) assert.ok(!/realguy/i.test(b.text), b.text); }); @@ -96,7 +98,31 @@ test("should-fix g: a single take made with an explicit --speed is kept as asked const drift = projectCharacters(m, { cast: cast2 }).characters.flatMap((c) => c.drift); assert.equal(drift.length, 1); assert.deepEqual(rereadPlan("anon", m, drift, ["host"]).items[0].argv, ["posts", "narrate", "anon", "p-1", "--take", "--speed", "1.3"]); - // Without speedAsked (a preset's speed that has since gone): drift, re-read at the preset's (none). + // Without speedAsked (a take made before it was recorded): unknown is no claim -- not drift. const m2 = manifestOf([post("p-1", "host", "Host", { narration: { takes: [{ ...take, speedAsked: undefined }], pick: 0 } })]); - assert.equal(projectCharacters(m2, { cast }).characters.flatMap((c) => c.drift).length, 1); + assert.equal(projectCharacters(m2, { cast }).characters.flatMap((c) => c.drift).length, 0); +}); + +test("must-fix 5: a bare handle after an @mention is said as the shown name too; the lint judges what was SAID", async () => { + const red = { anon: { realguy: "Anon 1" } }; + const asked = []; + const m = await manifest(); + const e = { ...m.timeline[0], narration: { script: "@realguy said it. realguy, stop." } }; + const t = await makeTake(project, e, { render: m.render, ask: stubAsk(asked), redaction: red }); + assert.equal(asked.at(-1).text, "Anon 1 said it. Anon 1, stop."); + assert.equal(t.take.said, "Anon 1 said it. Anon 1, stop."); + const { anonymityProblems } = await import("umtool-report-to-video/post-anon"); + const doc = JSON.parse(await readFile(path.join(DIR, "narration", "characters.json"), "utf8")); + const lint = (take) => anonymityProblems({ timeline: [{ ...e, narration: { takes: [take], pick: 0 } }] }, doc).errors; + assert.deepEqual(lint(t.take), [], "what it said holds no handle"); + assert.equal(lint({ ...t.take, said: "Anon 1 said it. realguy, stop." }).length, 1, "a bare handle said: an error"); + assert.equal(lint({ ...t.take, said: undefined }).length, 1, "a recording says its script"); +}); + +test("must-fix 6 (ii): every take maker records where its speed came from -- the flag, the item's own", async () => { + const asked = []; + const m = await manifest(); + const e = m.timeline[0]; + assert.equal((await makeTake(project, e, { render: m.render, speed: 1.3, ask: stubAsk(asked), redaction: null })).take.speedAsked, true); + assert.equal((await makeTake(project, { ...e, narration: { ...e.narration, speed: 1.1 } }, { render: m.render, ask: stubAsk(asked), redaction: null })).take.speedAsked, "item"); }); diff --git a/umtool/lib/report/castProject.mjs b/umtool/lib/report/castProject.mjs @@ -41,11 +41,14 @@ export function resolverFor({ map = {}, cast = null, project = null, render = {} narrator: e.narration?.voice ?? k.voice, engine: e.narration?.engine ?? k.engine, }); const own = role === "post" && handleKey(handle) === handleKey(e.handle) ? e.narration?.speed ?? null : null; - // The speed a read was ASKED at by its command is kept as asked: a thread read's `read.speed`, a single take's - // `speedAsked` speed -- never drift, and its re-read asks it again (rereadPlan). - const asked = typeof tr?.speed === "number" ? tr.speed : !tr && take?.speedAsked === true && typeof take.speed === "number" ? take.speed : null; - const speed = readSpeedOf({ flag: asked, preset: v.speed ?? null, own, engine: v.engine }); const { speed: _preset, ...rest } = v; + // SPEED DRIFT is claimed only where the take says where its speed came from (`speedAsked`: "preset" / "item" -- + // the speed it would be asked at now is compared). Asked by its command (true, a thread read's `read.speed`): kept as + // asked. A take that says nothing (made before it was recorded) is never speed drift: its own speed is the answer. + const prov = take?.speedAsked ?? (typeof tr?.speed === "number" ? true : undefined); + if (read?.kind === "tts" && prov !== "preset" && prov !== "item") return { ...rest, ...(typeof read.speed === "number" ? { speed: read.speed } : {}) }; + const asked = typeof tr?.speed === "number" ? tr.speed : null; + const speed = readSpeedOf({ flag: asked, preset: v.speed ?? null, own, engine: v.engine }); return { ...rest, ...(speed !== null ? { speed } : {}) }; }; } @@ -209,7 +212,10 @@ export function rereadPlan(projectId, manifest, drift, handles) { const e = tl.find((x) => x?.id === r.id); const takes = e?.narration?.takes ?? []; const t = takes[Number.isInteger(e?.narration?.pick) ? e.narration.pick : 0] ?? null; - const argv = ["posts", "narrate", projectId, r.id, "--take", ...(r.thread ? ["--thread", ...threadArgvOf(t?.read, { handles: [...want], author: e?.handle, takes })] : t?.speedAsked === true && typeof t.speed === "number" ? ["--speed", String(t.speed)] : [])]; + // A single take's own speed is asked again -- an old read never comes back at another speed -- unless it came + // from the character's preset or the item (that is what a re-read takes anew). + const keepSpeed = !r.thread && typeof t?.speed === "number" && t.speed !== 1 && t.speedAsked !== "preset" && t.speedAsked !== "item"; + const argv = ["posts", "narrate", projectId, r.id, "--take", ...(r.thread ? ["--thread", ...threadArgvOf(t?.read, { handles: [...want], author: e?.handle, takes })] : keepSpeed ? ["--speed", String(t.speed)] : [])]; return { ...r, take: t?.file ?? null, argv }; }); return { items, skipped }; diff --git a/umtool/lib/report/castStore.mjs b/umtool/lib/report/castStore.mjs @@ -147,7 +147,7 @@ function withCastLock(fn) { return run; } -function writeKind(kind, file, mutate, { token = null, what = "an edit" } = {}) { +function writeKind(kind, file, mutate, { token = null, what = "an edit", manifests = [] } = {}) { return withCastLock(async () => { const read = await readKind(kind, file); if (read.error && read.exists) throw new CastError(`${read.error} -- fix the file first; nothing written`, 409); @@ -161,7 +161,7 @@ function writeKind(kind, file, mutate, { token = null, what = "an edit" } = {}) const extra = { proposed: JSON.parse(JSON.stringify(Array.isArray(read.cast.proposed) ? read.cast.proposed : [])) }; const result = mutate(chars, extra) ?? {}; const doc = kind.doc(chars.map((c) => foldWritten(c, was.get(c?.id) ?? null)), extra); - const errors = kind.validate(doc, path.basename(file)); + const errors = kind.validate(doc, path.basename(file), { manifests }); if (errors.length) throw new CastError(`refused: ${errors.join("; ")}`); const points = [...(await readCastUndo(file)), { at: new Date().toISOString(), what, text: read.exists ? read.text : null }].slice(-CAST_UNDO_KEEP); await writeAtomic(undoFileOf(file), `${JSON.stringify({ file: path.basename(file), points }, null, 1)}\n`); @@ -209,7 +209,9 @@ export const undoCast = (file, o) => undoKind(CAST_KIND, file, o); * @param {{ token?: string | null, what?: string }} [o] */ export async function projectCharactersWrite(dir, mutate, o) { - const { cast, ...rest } = await writeKind(PROJECT_KIND, projectCharactersFile(dir), mutate, o); + // The project's manifest: a shown name that is a real author's handle or name is refused (cast.mjs anonShownClashes). + const manifest = await readFile(path.join(/* turbopackIgnore: true */ dir, "video.manifest.json"), "utf8").then(JSON.parse, () => null); + const { cast, ...rest } = await writeKind(PROJECT_KIND, projectCharactersFile(dir), mutate, { ...o, ...(manifest ? { manifests: [manifest] } : {}) }); return { ...rest, doc: cast }; } diff --git a/umtool/lib/report/driftSpeed.test.mjs b/umtool/lib/report/driftSpeed.test.mjs @@ -1,7 +1,9 @@ -// DRIFT TRACKS SPEED (cast.mjs voiceDrift, castProject.mjs resolverFor): a picked read synthesized at another speed -// than its character's preset asks now is stale, as one in another voice is -- a single take by its `speed`, a thread -// read by each part's; the item's own speed and a thread read's own --speed answer before the preset; Orpheus (no -// speed) and a converted recording never drift by speed. +// DRIFT TRACKS SPEED (cast.mjs voiceDrift, castProject.mjs resolverFor) -- where a take SAYS where its speed came +// from (`speedAsked` "preset" / "item"): a picked read synthesized at another speed than its character's preset asks +// now is stale, as one in another voice is -- a single take by its `speed`, a thread read by each part's; the item's +// own speed and a thread read's own --speed answer before the preset; Orpheus (no speed) and a converted recording +// never drift by speed. A take that says nothing (made before the lane: unknown) is never speed drift, and a re-read +// of it asks its own speed again. import assert from "node:assert/strict"; import { test } from "node:test"; import { projectCharacters, rereadPlan } from "./castProject.mjs"; @@ -14,7 +16,7 @@ const cast = (speed) => ({ { id: "orph", name: "Orph", handles: ["orph"], synthetic: { voice: "orpheus:zac" } }, ], }); -const single = (o = {}) => ({ file: "narration/posts/1/take-1.kokoro.wav", engine: "kokoro", voice: "am_michael", seconds: 2, script: "Hi.", ...o }); +const single = (o = {}) => ({ file: "narration/posts/1/take-1.kokoro.wav", engine: "kokoro", voice: "am_michael", seconds: 2, script: "Hi.", speedAsked: "preset", ...o }); const post = (id, handle, narration, o = {}) => ({ type: "post", id, handle, author: handle, text: "words", narration, ...o }); const m = (...timeline) => ({ render: { postNarration: { engine: "kokoro", voice: "af_heart" } }, timeline }); const driftOf = (manifest, c) => projectCharacters(manifest, { cast: c }).characters.flatMap((x) => x.drift); @@ -41,7 +43,7 @@ test("a thread read's parts: each at its preset's speed now; the read's own --sp { n: 1, role: "parent:0", voice: "bf_emma", engine: "kokoro", ...(guestSpeed ? { speed: guestSpeed } : {}), text: "q", file: "narration/parts-cache/a.wav", start: 0, seconds: 1 }, { n: 2, role: "post", voice: "am_michael", engine: "kokoro", ...(hostSpeed ? { speed: hostSpeed } : {}), text: "a", file: "narration/parts-cache/b.wav", start: 1.8, seconds: 1 }, ]; - const thread = (p, read = { kind: "thread", parents: "0" }) => ({ file: "narration/posts/1/take-2.kokoro-thread.wav", engine: "kokoro", voice: "bf_emma+am_michael", seconds: 3, script: "q\n\na", parts: p, read }); + const thread = (p, read = { kind: "thread", parents: "0" }) => ({ file: "narration/posts/1/take-2.kokoro-thread.wav", engine: "kokoro", voice: "bf_emma+am_michael", seconds: 3, script: "q\n\na", parts: p, read, speedAsked: read.speed ? true : "preset" }); const e = (t) => post("p1", "host", { takes: [t], pick: 0 }, { parents: [{ id: "9", handle: "guest", author: "Guest", text: "q" }] }); assert.deepEqual(driftOf(m(e(thread(parts(1.1, 0.9)))), cast(1.1)), []); const rows = driftOf(m(e(thread(parts(1.1, 0.9)))), cast(1.25)); @@ -52,3 +54,21 @@ test("a thread read's parts: each at its preset's speed now; the read's own --sp const orph = post("p2", "orph", { takes: [{ file: "narration/posts/2/take-1.orpheus.wav", engine: "orpheus", voice: "zac", seconds: 2, script: "x" }], pick: 0 }); assert.deepEqual(driftOf(m(orph), cast(null)), []); }); + +test("a PRE-LANE take (no speedAsked): never speed drift -- unknown is no claim -- and a re-read asks its own speed again", () => { + const old = { file: "narration/posts/1/take-1.kokoro.wav", engine: "kokoro", voice: "am_michael", seconds: 2, script: "Hi.", speed: 1.2 }; + const m1 = m(post("p1", "host", { takes: [old], pick: 0 })); + assert.deepEqual(driftOf(m1, cast(null)), [], "a --speed 1.2 read with no preset"); + assert.deepEqual(driftOf(m1, cast(1.1)), [], "a preset that differs: no claim either"); + assert.deepEqual(driftOf(m(post("p1", "host", { takes: [{ ...old, speed: undefined }], pick: 0 })), cast(1.1)), []); + // Drift by its VOICE: the re-read keeps the speed it was read at. + const castB = { ...cast(null), characters: [{ id: "host", name: "Host", handles: ["host"], synthetic: { voice: "kokoro:am_adam" } }] }; + const rows = driftOf(m1, castB); + assert.equal(rows.length, 1); + assert.deepEqual(rereadPlan("p", m1, rows, ["host"]).items[0].argv, ["posts", "narrate", "p", "p1", "--take", "--speed", "1.2"]); + // A preset take whose preset changed: re-read at the new preset (no --speed kept). + const p1 = m(post("p1", "host", { takes: [{ ...old, speed: 1.1, speedAsked: "preset" }], pick: 0 })); + const prow = driftOf(p1, cast(1.3)); + assert.equal(prow.length, 1); + assert.deepEqual(rereadPlan("p", p1, prow, ["host"]).items[0].argv, ["posts", "narrate", "p", "p1", "--take"]); +}); diff --git a/umtool/lib/report/onscreen.mjs b/umtool/lib/report/onscreen.mjs @@ -450,7 +450,18 @@ export async function scheduleForPreview( project, manifest, variant, draft = new Map(), postsDraft = {}, { resolver = previewPostResolver(), claimsDraft = new Map(), estimate = false } = {}, ) { - const picked = selectVariant(manifest, variant); + // ON-SCREEN ANONYMISING (post-anon.mjs), as the build: the PROJECT's set (every variant), applied before any + // schedule is built -- the ONE place the chrome preview, the still and the onscreen routes share. Unresolvable, or + // this video's characters unread: refused (`status` 409), never a preview with the real names. + let anonymity; + try { + const { projectAnonymousSet } = await import("umtool-report-to-video/project-characters-file"); + anonymity = await projectAnonymousSet(project.dir, manifest); + } catch (e) { + throw Object.assign(new Error(e instanceof Error ? e.message : String(e)), { status: 409, anonymity: true }); + } + const { anonymiseManifest } = await import("umtool-report-to-video/post-anon"); + const picked = anonymiseManifest(selectVariant(manifest, variant), anonymity.doc, { set: anonymity.set }); // A stacked vertical deck is previewed at its build's render: the 9:16 frame, its geometry (vertical-deck.mjs). const selected = stackedDeckWanted(picked.render) ? { ...picked, render: verticalRender(picked.render) } : picked; const entries = selected.timeline ?? []; diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -412,15 +412,16 @@ export async function makeTake(project, e, { script = null, note = null, engine file: rel, engine: result?.engine ?? eng, voice: result?.voice ?? vox, seconds: m.seconds ?? Number(result?.seconds), source: { kind: "tts", engine: result?.engine ?? eng, voice: result?.voice ?? vox, script: words }, script: words, at: new Date().toISOString(), ...(note ? { note } : {}), ...(spd !== null && eng !== "orpheus" ? { speed: spd } : {}), - // Asked by --speed: kept as asked (the drift guard compares with it; a re-read asks it again). - ...(speed !== null && eng !== "orpheus" ? { speedAsked: true } : {}), + // Where its speed came from (cast.mjs speedAskedOf): the command's --speed (kept as asked), the item's own, the + // character's preset (drift when that changes). No speed asked: no key. + ...(spd !== null && eng !== "orpheus" ? { speedAsked: speed !== null ? true : e.narration?.speed != null ? "item" : "preset" } : {}), ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), jobId, // What its audio does with the slurs the script holds (post-slurs.mjs), and its words when timed for a beep. ...(slurs ? { slurs } : {}), ...(timed ? { words: timed } : {}), // The pronunciation entries it said (post-say.mjs; `umtool posts say <p> stale` reads them). ...(said.lexicon ? { lexicon: said.lexicon } : {}), - // The anonymous handles it said as their shown names (post-anon.mjs): the script is kept as written. - ...(said.anonymised ? { anonymised: said.anonymised } : {}), + // What it SAID, when an anonymous handle made that differ from the script (post-anon.mjs): the lint reads it. + ...(said.anonymised ? { said: said.text } : {}), }; const patch = { addTake: take, ...(script !== null && script !== e.narration?.script ? { script: words } : {}) }; const { result: wrote, editNotes } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, patch, { token: await manifestToken(project.dir) })); @@ -926,6 +927,8 @@ export async function deriveTake(project, e, { from, op, engine = null, voice = steps: [{ op, ...(ran ? { engine: ran } : {}), ...(landed ? { voice: landed } : {}), ...pitched, ...(params ? { params } : {}), ranAt: new Date().toISOString(), job: jobId }], script: t.script ?? e.narration?.script ?? "", at: new Date().toISOString(), jobId, ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), ...(parts ? { parts } : {}), + // Its audio is its source's words at its source's speed: what it said and where that speed came from, copied. + ...(typeof t.speed === "number" ? { speed: t.speed } : {}), ...(t.speedAsked !== undefined ? { speedAsked: t.speedAsked } : {}), ...(typeof t.said === "string" ? { said: t.said } : {}), }; const { result } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, { addTake: take }, { token: await manifestToken(project.dir) })); return { take, result }; @@ -1026,20 +1029,28 @@ export async function deleteTake(project, e, index) { await mkdir(trash, { recursive: true }); const stamp = new Date().toISOString().replace(/[:.]/g, "-"); const moved = []; - for (const rel of [t.file, String(t.file).replace(/\.wav$/, ".parts")]) { - const from = path.join(project.dir, ...String(rel).split("/")); - const to = path.join(trash, `${stamp}-${path.basename(from)}`); - if (await stat(from).catch(() => null)) { - await rename(from, to); - moved.push([from, to]); - } - } try { + for (const rel of [t.file, String(t.file).replace(/\.wav$/, ".parts")]) { + const from = path.join(project.dir, ...String(rel).split("/")); + const to = path.join(trash, `${stamp}-${path.basename(from)}`); + if (await stat(from).catch(() => null)) { + await rename(from, to); + moved.push([from, to]); + } + } const { result } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, { dropTake: index }, { token: await manifestToken(project.dir) })); return result; } catch (err) { - // The write refused: the files go back where they were. - for (const [from, to] of moved) await rename(to, from).catch(() => {}); + // A move or the write failed: what moved goes back where it was -- and what cannot is said, file by file. + const stuck = []; + for (const [from, to] of moved) { + try { + await rename(to, from); + } catch (re) { + stuck.push(`${path.relative(project.dir, to)} (belongs at ${path.relative(project.dir, from)}: ${re instanceof Error ? re.message : re})`); + } + } + if (stuck.length) throw new NarrateError(`${err instanceof Error ? err.message : err} -- and ${stuck.length} file(s) could NOT be put back, still in the trash: ${stuck.join("; ")}`); throw err; } } diff --git a/umtool/lib/report/postThreadRead.mjs b/umtool/lib/report/postThreadRead.mjs @@ -466,7 +466,8 @@ export async function threadTake(project, e, opts = {}) { parts: meta, ...(plan.slurs ? { slurs: plan.slurs } : {}), ...(plan.lexicon.length ? { lexicon: plan.lexicon } : {}), - ...(plan.anonymised.length ? { anonymised: plan.anonymised } : {}), + // Where its parts' speeds came from: --speed (kept as asked), else their characters' presets / the item's own. + ...(plan.pieces.some((p) => typeof p.speed === "number") ? { speedAsked: typeof speed === "number" ? true : "preset" } : {}), read: readRecordOf({ parents, skip, quoted, linked, readSeen, overrides, voice, speed, postTake }), }; const patch = { addTake: take, ...(plan.script ? { script: plan.script } : {}) }; diff --git a/umtool/lib/report/present.mjs b/umtool/lib/report/present.mjs @@ -445,13 +445,27 @@ export async function presentPayload(project, { take = null, bare = false, canUn // The redaction is the cut's own (its terms, its channels' markup, its slur filter: a take's patch can switch it), // read off the cut that plays; its censored attachments laid on each post item before it is planned. let red = null; - const r = await playViewWith(project, { - take, bare, - postFor: async (manifest) => { - red = await projectRedaction(project.dir, manifest, { say: false }); - return (e) => censorEntry(e, red); - }, - }); + // ON-SCREEN ANONYMISING (post-anon.mjs), the project's set: every post item and the deck's words (its subtitles, + // its QRs) as the build draws them. Unresolvable, or this video's characters unread: refused. + let anonymity = null; + let r; + try { + r = await playViewWith(project, { + take, bare, + postFor: async (manifest) => { + red = await projectRedaction(project.dir, manifest, { say: false }); + const { projectAnonymousSet } = await import("umtool-report-to-video/project-characters-file"); + anonymity = await projectAnonymousSet(project.dir, manifest); + const { anonymiseEntry } = await import("umtool-report-to-video/post-anon"); + const set = anonymity.set; + return (e) => censorEntry(anonymiseEntry(e, set), red); + }, + }); + } catch (e) { + return { error: e instanceof Error ? e.message : String(e) }; + } if ("error" in r) return r; - return presentFrom({ view: r.view, manifest: r.manifest, red, canUncensor }); + const { anonymiseManifest } = await import("umtool-report-to-video/post-anon"); + const manifest = anonymity ? anonymiseManifest(r.manifest, anonymity.doc, { set: anonymity.set }) : r.manifest; + return presentFrom({ view: r.view, manifest, red, canUncensor }); } diff --git a/umtool/report-to-video/build-podcast.mjs b/umtool/report-to-video/build-podcast.mjs @@ -161,7 +161,8 @@ export function podcastFfmeta(chapters, { title = null, disclosure = null } = {} /** * Every source the podcast cites, once, in cut order: each heard clip's link * (the QR's rule: its citeUrl, else its moment on the archive; none for a `src` - * clip without one), each still's citeUrl, each post's own url. + * clip without one), each still's citeUrl, each post's own url -- an anonymous author's post (post-anon.mjs: `noQr`) + * by its shown name and with NO link. */ export function citedSources(manifest, items, titles) { const heard = new Set(items.filter((i) => i.kind === "segment").map((i) => i.id)); @@ -172,6 +173,7 @@ export function citedSources(manifest, items, titles) { seen.add(url); out.push({ label, url }); }; + const named = new Set(); (manifest.timeline ?? []).forEach((e, i) => { if (e.type === "clip" && heard.has(e.id)) add(titles[i], deckQrUrl(e, manifest.provenance ?? {})); else if (e.type === "image" && e.citeUrl) add(titles[i], e.citeUrl); @@ -180,7 +182,13 @@ export function citedSources(manifest, items, titles) { if (!p || p.hide) continue; const who = p.author ?? (p.handle ? "@" + p.handle : "a post"); const about = [p.platform, p.date ? String(p.date).slice(0, 10) : null].filter(Boolean).join(", "); - add(about ? who + " (" + about + ")" : who, p.url); + const label = about ? who + " (" + about + ")" : who; + if (p.noQr === true || p.anonymous === true) { + if (!named.has(label)) out.push({ label, url: null }); + named.add(label); + continue; + } + add(label, p.url); } return out; } @@ -191,7 +199,7 @@ export function showNotes({ manifest, chapters, sources, disclosure = null, dura if (manifest.subtitle) lines.push("", manifest.subtitle); if (duration != null) lines.push("", `Length: ${clock(duration)}`); lines.push("", "## Chapters", "", ...chapters.map((c) => `- ${clock(c.start)} — ${c.title}`)); - if (sources.length) lines.push("", "## Sources", "", ...sources.map((s) => `- ${s.label} — <${s.url}>`)); + if (sources.length) lines.push("", "## Sources", "", ...sources.map((s) => (s.url ? `- ${s.label} — <${s.url}>` : `- ${s.label}`))); if (disclosure) lines.push("", disclosure); return lines.join("\n") + "\n"; } @@ -279,7 +287,12 @@ export async function buildPodcast({ manifestPath, variant = "sourced", out = nu const whole = JSON.parse(await readFile(manifestPath, "utf8")); const errors = validatePodcast(whole); if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`); - const manifest = selectVariant(whole, variant); + // ON-SCREEN ANONYMISING's set (post-anon.mjs), the project's: an anonymous author's post is cited by its shown + // name and with no link (citedSources); refused as the build is. + const { projectAnonymousSet } = await import("./project-characters-file.mjs"); + const { anonymiseManifest } = await import("./post-anon.mjs"); + const anonymity = await projectAnonymousSet(path.dirname(path.resolve(manifestPath)), whole); + const manifest = anonymiseManifest(selectVariant(whole, variant), anonymity.doc, { set: anonymity.set }); const { render } = manifest; const settings = resolvePodcast(render); const outRoot = out ?? path.join(path.dirname(path.resolve(manifestPath)), "out"); diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -253,7 +253,7 @@ import { readPostRedaction } from "./post-redact-files.mjs"; import { dropMarks, redactEntry } from "./post-redact.mjs"; import { avatarUrls } from "./post-avatars.mjs"; import { anonymiseManifest } from "./post-anon.mjs"; -import { readProjectCharactersFor } from "./project-characters-file.mjs"; +import { projectAnonymousSet, readProjectCharactersFor } from "./project-characters-file.mjs"; export { readProjectCharactersFor }; import { applyPostCombo } from "./post-combo-render.mjs"; @@ -6616,7 +6616,9 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // ON-SCREEN ANONYMISING (post-anon.mjs): an author who is one of this video's anonymous characters is drawn under // the shown name on every card below -- the cut, the vertical cut, a side card, the chapters. No anonymous // character: the manifest as it was. - const manifest = anonymiseManifest(selectVariant(ruled.manifest, variant), await readProjectCharactersFor(manifestDir)); + // The set is the PROJECT's (projectAnonymousSet: every variant, before rulings and --only), applied to what is drawn. + const anonymity = await projectAnonymousSet(manifestDir, whole); + const manifest = anonymiseManifest(selectVariant(ruled.manifest, variant), anonymity.doc, { set: anonymity.set }); // THE BASIC OUTPUT MODE (render.mode, basic.mjs): the footage alone. Every // render of the cut gets it -- a take, `umtool build`, this CLI -- because the // mode is read here, off the manifest every layer resolved into. The runs diff --git a/umtool/report-to-video/cast.mjs b/umtool/report-to-video/cast.mjs @@ -270,7 +270,7 @@ export function validateCast(doc, where = "cast.json") { } /** Every reason a project's characters document is refused (empty: it is fine). */ -export function validateProjectCharacters(doc, where = "characters.json") { +export function validateProjectCharacters(doc, where = "characters.json", { manifests = [] } = {}) { if (!isObj(doc)) return [`${where} must be {"format": "${PROJECT_CHARACTERS_FORMAT}", "version": ${PROJECT_CHARACTERS_VERSION}, "characters": [...]}`]; const errors = []; if (doc.format !== PROJECT_CHARACTERS_FORMAT) errors.push(`${where}: format must be "${PROJECT_CHARACTERS_FORMAT}"`); @@ -287,6 +287,8 @@ export function validateProjectCharacters(doc, where = "characters.json") { if (shownSeen.has(k)) errors.push(`${where}.characters[${i}]: "${str(c.shown).trim()}" is ${shownSeen.get(k)}'s shown name already (two anonymous characters are never shown alike)`); else shownSeen.set(k, str(c.id)); }); + // A shown name that is another character's handle, or (with the project's manifests) a real author's. + errors.push(...anonShownClashes(list, manifests).map((m) => `${where}: ${m}`)); if (doc.proposed !== undefined) { if (!Array.isArray(doc.proposed)) errors.push(`${where}.proposed must be a list`); else { @@ -409,6 +411,44 @@ export function anonShownMap(characters) { return out; } +/** The shown name as a handle ("Anon 1" -> "Anon_1"): post-anon.mjs pseudonymOf's rule, here for the validator. */ +const pseudonymKey = (shown) => str(shown).replace(/[^A-Za-z0-9_]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 64).toLowerCase() || "anon"; + +/** + * Every anonymous character's shown name (or its pseudonym) that is ALSO a real author's handle or display name in + * `manifests` (their posts, parents, quoted, linked, repost, popups -- an author an anonymous character covers + * excepted) or ANY other character's handle, case-insensitive: sentences naming characters, never a real handle. + * `only`: these shown names alone. + */ +export function anonShownClashes(characters, manifests = [], { only = null } = {}) { + const list = (Array.isArray(characters) ? characters : []).filter(isObj); + const shown = anonShownMap(list); + const covered = new Set(list.filter((c) => c.anonymous === true).flatMap((c) => (Array.isArray(c.handles) ? c.handles : []).map((h) => handleKey(h)))); + const real = new Map(); + const note = (v, what) => { + const k = str(v).trim().toLowerCase().replace(/^@+/, ""); + if (k && !real.has(k)) real.set(k, what); + }; + for (const m of manifests) { + for (const e of [...(Array.isArray(m?.timeline) ? m.timeline : []).filter((x) => x?.type === "post"), ...(Array.isArray(m?.posts) ? m.posts : [])]) { + for (const w of [e, ...(Array.isArray(e?.parents) ? e.parents : []), ...(Array.isArray(e?.links) ? e.links : []), e?.quoted, e?.repostedBy].filter(isObj)) { + if (covered.has(handleKey(w.handle))) continue; + note(w.handle, `an author's handle in ${str(e.id) || "a post"}`); + note(w.author, `an author's name in ${str(e.id) || "a post"}`); + } + } + } + const errors = []; + for (const c of list.filter((x) => x.anonymous === true)) { + const s = shown.get(c.id); + if (!s || (only && !only.has(s))) continue; + for (const o of list) if (o !== c) for (const h of Array.isArray(o.handles) ? o.handles : []) if ([s.toLowerCase(), pseudonymKey(s)].includes(handleKey(h))) errors.push(`${c.id}'s shown name "${s}" is ${o.id}'s handle: an anonymous author's posts would be pinned on another -- give it another shown name`); + const hit = real.get(s.toLowerCase()) ?? real.get(pseudonymKey(s)); + if (hit) errors.push(`${c.id}'s shown name "${s}" is also ${hit}: an anonymous author's posts would be pinned on a real one -- give it another shown name`); + } + return errors; +} + /** The next unused shown name of ANON_NAME_PATTERN among a project's characters ("Anon 3"). */ export function nextAnonName(characters) { const used = new Set((Array.isArray(characters) ? characters : []).flatMap((c) => [str(c?.shown).trim().toLowerCase(), str(c?.name).trim().toLowerCase()])); diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs @@ -43,7 +43,7 @@ import { ensureWriteDir } from "../lib/report/storage.mjs"; import { chromeCacheKey, frameCount, pageDuration, hyperframesCommand, sha256, transitionOf } from "./deck.mjs"; import { GSAP_FILE } from "./chrome-deck.mjs"; import { anonymiseManifest } from "./post-anon.mjs"; -import { readProjectCharactersFor } from "./project-characters-file.mjs"; +import { projectAnonymousSet } from "./project-characters-file.mjs"; import { fxGeometry, threadShotOf } from "./deck.mjs"; import { FRAME_KEY_REGIONS, frameKeys } from "./frame-keys.mjs"; import { FRAME_KEYS_FILE, SPARSE_FILE } from "./chunked-encode.mjs"; @@ -880,7 +880,9 @@ export async function composeChrome({ // clips it does not play. // ON-SCREEN ANONYMISING (post-anon.mjs): the build's own pass, over the manifest this composer reads itself -- a // popup post or a promise speaker by an anonymous handle is drawn as the cut draws them; refused as the build is. - const manifest = anonymiseManifest(selectVariant(JSON.parse(await readFile(manifestPath, "utf8")), variant), await readProjectCharactersFor(path.dirname(path.resolve(manifestPath)))); + const raw = JSON.parse(await readFile(manifestPath, "utf8")); + const anonymity = await projectAnonymousSet(path.dirname(path.resolve(manifestPath)), raw); + const manifest = anonymiseManifest(selectVariant(raw, variant), anonymity.doc, { set: anonymity.set }); // THE STACKED VERTICAL DECK (vertical-deck.mjs): a 9:16 cut that keeps its deck is composed at the render the // build makes it with (vertical.mjs verticalRender) -- the build passes its own (`render`: a `--vertical` // build of a landscape manifest, its knobs); Play the cut and the previews read the manifest's. diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -1375,6 +1375,8 @@ export function deckQrUrl(entry, provenance = {}, { links = DECK_DEFAULTS.qr.lin } if (entry.type === "image") return entry.citeUrl ?? null; // A post item: the post's own page, or its archive's (postQrUrl, the posts' `links` rule). + // An anonymous author's item (post-anon.mjs `noQr`): no code -- any link to their post would name them. + if (entry.type === "post" && entry.noQr === true) return null; if (entry.type === "post") return entry.citeUrl ?? (entry.url ? postQrUrl({ ...entry, postId: String(entry.post ?? "").split("/")[1] }, provenance, { links: links === "original" ? "original" : "archive" }) : null); return null; } diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -558,11 +558,13 @@ export async function lintManifestFile(manifestPath, { const base = lintManifest(manifest, { manifestDir, whole, only, narrationSeconds, draftsReview, narrationUnreviewed, final, draftsUnreviewed }); // ANONYMITY (post-anon.mjs): what a read says, and what the pass cannot fix by itself. This video's characters // unread is an error: the build refuses it too. - const { readProjectCharactersFor } = await import("./project-characters-file.mjs"); + const { projectAnonymousSet } = await import("./project-characters-file.mjs"); const { anonymityProblems } = await import("./post-anon.mjs"); let anon; try { - anon = anonymityProblems(manifest, await readProjectCharactersFor(manifestDir)); + // The PROJECT's set (every variant; a take's own entries too), judged on what this cut draws and says. + const { doc, set } = await projectAnonymousSet(manifestDir, whole); + anon = anonymityProblems(manifest, doc, { set }); } catch (e) { anon = { errors: [e instanceof Error ? e.message : String(e)], warnings: [] }; } diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -89,6 +89,7 @@ "./cast": "./cast.mjs", "./cast-assign": "./cast-assign.mjs", "./post-anon": "./post-anon.mjs", + "./project-characters-file": "./project-characters-file.mjs", "./post-redact-files": "./post-redact-files.mjs", "./post-slurs": "./post-slurs.mjs", "./post-thread": "./post-thread.mjs", diff --git a/umtool/report-to-video/post-anon.mjs b/umtool/report-to-video/post-anon.mjs @@ -34,7 +34,7 @@ // (the same object): a cut with none renders byte-identically. // // PURE and dependency-free (beyond cast.mjs / post-say.mjs). -import { anonShownMap, projectCharactersOf } from "./cast.mjs"; +import { anonShownClashes, anonShownMap, projectCharactersOf } from "./cast.mjs"; import { handleKey } from "./post-say.mjs"; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); @@ -53,30 +53,54 @@ export const pseudonymOf = (shown) => str(shown).replace(/[^A-Za-z0-9_]+/g, "_") /** * THE VIDEO's ANONYMOUS HANDLES: `Map<handle (lower case), shown>` -- every handle an anonymous character lists, and - * the author handle of every post item that names an anonymous character by id (see the head). Throws - * AnonymityError for what it cannot resolve. + * the author handle of every post item that names an anonymous character by id, in ANY of `manifests` (the whole + * project manifest -- every variant, before rulings, windows or `--only` -- and a take's own: projectAnonymousSet, + * project-characters-file.mjs, gives the build, the composer, the lint, Play and the previews this one set). The map + * carries `postIds`: the native ids of every post an anonymous author wrote that the manifests know (a status URL of + * one is theirs). Throws AnonymityError for what it cannot resolve -- naming characters and items, never a real handle. * * @param {any} doc characters.json's document (null: none) - * @param {any} [manifest] + * @param {...any} manifests + * @returns {Map<string, string> & { postIds: Set<string> }} */ -export function anonymousHandles(doc, manifest = null) { +export function anonymousHandles(doc, ...manifests) { const chars = projectCharactersOf(doc); const shown = anonShownMap(chars); - const out = new Map(); - const put = (h, s, why) => { + const out = /** @type {Map<string, string> & { postIds: Set<string> }} */ (new Map()); + const why = new Map(); + const put = (h, s, label) => { const k = handleKey(h); if (!k) return; - if (out.has(k) && out.get(k) !== s) throw new AnonymityError(`@${k} is shown as "${out.get(k)}" and as "${s}" (${why}): one handle, one anonymous character -- fix narration/characters.json or the item`); + if (out.has(k) && out.get(k) !== s) throw new AnonymityError(`one author's handle is shown as "${out.get(k)}" (${why.get(k)}) and as "${s}" (${label}): one handle, one anonymous character -- fix narration/characters.json or the item`); + if (!out.has(k)) why.set(k, label); out.set(k, s); }; for (const c of chars) if (c.anonymous === true) for (const h of c.handles ?? []) put(h, shown.get(c.id), `${c.id}'s handles`); - for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { + const tls = manifests.flatMap((m) => (Array.isArray(m?.timeline) ? m.timeline : [])); + for (const e of tls) { if (e?.type !== "post") continue; const id = str(e.narration?.character).trim().toLowerCase(); if (!id || !shown.has(id)) continue; if (!handleKey(e.handle)) throw new AnonymityError(`${e.id} names the anonymous character ${id} but has no author handle to hide: give the item its handle, or name another character`); put(e.handle, shown.get(id), `${e.id} names ${id}`); } + // A shown name (or its pseudonym) that is a real author's handle or display name pins posts on a real person. + if (out.size) { + const clash = anonShownClashes(chars, manifests, { only: new Set(out.values()) })[0]; + if (clash) throw new AnonymityError(clash); + } + // The posts the anonymous authors wrote, by native id. + out.postIds = new Set(); + const idOf = (v) => str(v).match(/(?:^|\/)([A-Za-z0-9_-]{4,})$/)?.[1] ?? ""; + const statusOf = (u) => str(u).match(/\/(?:status|statuses|post|posts|video|reel|p)\/([A-Za-z0-9_-]+)/)?.[1] ?? ""; + for (const m of manifests) { + for (const e of [...(Array.isArray(m?.timeline) ? m.timeline : []).filter((x) => x?.type === "post"), ...(Array.isArray(m?.posts) ? m.posts : [])]) { + for (const w of [e, ...(Array.isArray(e?.parents) ? e.parents : []), ...(Array.isArray(e?.links) ? e.links : []), e?.quoted].filter(isObj)) { + if (!out.has(handleKey(w.handle))) continue; + for (const v of [w === e ? idOf(e.post) : "", str(w.id), str(w.originalId), statusOf(w.url)]) if (v && v.length >= 4) out.postIds.add(v.toLowerCase()); + } + } + } return out; } @@ -87,33 +111,120 @@ function asAnon(who, shown) { } const escRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -/** A URL's prefix that names an account by its handle, per platform (the handle follows it). */ -const URL_PREFIX = String.raw`(?<![A-Za-z0-9.-])(?:(?:www|mobile)\.)?(?:(?:x|twitter)\.com/|bsky\.app/profile/|threads\.(?:net|com)/@|truthsocial\.com/@|youtube\.com/@)`; +/** The hosts whose URLs name an account by its handle (the first path segment, `@` or not; Bluesky's `profile/<h>`). */ +export const PLATFORM_HOSTS = Object.freeze(["x.com", "twitter.com", "nitter.net", "xcancel.com", "fxtwitter.com", "vxtwitter.com", "fixupx.com", "bsky.app", "threads.net", "threads.com", "truthsocial.com", "youtube.com", "instagram.com", "tiktok.com"]); +/** A URL in words: an optional scheme, a host (www./mobile./m. dropped), its path -- never an e-mail's host. */ +const URL_SRC = String.raw`(?<![\w@.\-/])(?:https?:\/\/)?(?:(?:www|mobile|m)\.)?(?<host>(?:[a-z0-9-]+\.)+[a-z]{2,})(?<path>\/[^\s<>"'\x60]*)?`; +/** + * Words a handle is never said bare for (only its @form is replaced): too short to be told from words, or a word itself. + * A bare one of these left in a read is a lint WARNING. + */ +const COMMON_WORDS = new Set(("able about above after again against also always among another answer anything around away back because become been " + + "before being below best better between both bring build call came come could daily dark days dead does done down each early easy even ever " + + "every face fact fair fall family fast feel fine first five follow food free from front full game girl give good great green group grow " + + "half hand happy hard have head hear heart help here high hold home hope hour house idea info into just keep kind king know land last late " + + "learn left less life light like line list little live long look lord love made main make many mark mind more most move much music must " + + "name near need never news next nice night none note nothing only open other over page part past people place plan play point post power " + + "real really right road room said same save says seen self send shop show side sign since some song soon sound start stay still stop " + + "story such sure take talk team tell than that their them then there these they thing think this those time today told took tour town " + + "true truth turn very view wait walk want watch water week well went were what when where which while white whole wild will with word " + + "work world year yes young your guest host stranger friend other someone person people anon user admin official media " + + "daily truth movie music sport sports games radio show channel stream live video clip").split(/\s+/)); +/** Can a handle be told apart as a bare word in a read (4+ characters, not a common word)? */ +export const bareSayable = (h) => str(h).length >= 4 && !COMMON_WORDS.has(str(h).toLowerCase()); + const memo = new WeakMap(); -/** The one-pass pattern for a set: `(@ | a platform URL's prefix)(one of the handles)` not followed by a handle's character. */ -function patternOf(set) { - const hit = memo.get(set); - if (hit) return hit; +/** The one-pass pattern for a set: a URL | an @mention of a handle | (spoken only) a bare handle. */ +function patternOf(set, spoken = false) { + const cache = memo.get(set) ?? {}; + const key = spoken ? "s" : "w"; + if (cache[key] !== undefined) return cache[key]; const hs = [...set.keys()].sort((a, b) => b.length - a.length).map(escRe); - const re = hs.length ? new RegExp(String.raw`((?<![A-Za-z0-9_.])@|${URL_PREFIX})(${hs.join("|")})(?![A-Za-z0-9_]|\.[A-Za-z0-9])`, "gi") : null; - memo.set(set, re); + const bare = spoken ? [...set.keys()].filter(bareSayable).sort((a, b) => b.length - a.length).map(escRe) : []; + const alts = [URL_SRC]; + if (hs.length) alts.push(String.raw`(?<![\w.@])@(?<at>${hs.join("|")})(?![A-Za-z0-9_]|\.[A-Za-z0-9])`); + if (bare.length) alts.push(String.raw`(?<![\w.@/])(?<bare>${bare.join("|")})(?![\w]|\.[A-Za-z0-9])`); + const re = new RegExp(alts.join("|"), "giu"); + memo.set(set, { ...cache, [key]: re }); return re; } +const safeDecode = (s) => { + try { + return decodeURIComponent(s); + } catch { + return s; + } +}; + /** - * `text` with every @mention of an anonymous handle, and every platform URL carrying one, made the pseudonym's -- in - * ONE pass (no replacement is looked at again). The same string when none is in it. + * IS THIS URL an anonymous author's (pure)? A platform URL whose account segment (`/<h>`, `/@<h>`, Bluesky's + * `/profile/<h>`), `search?q=from:<h>` or `intent/user?screen_name=<h>` names an anonymous handle -- decoded first, + * any case -- or one truncated ("x.com/realgu…") whose visible start (4+ characters) begins one; or a status/post URL + * of a post an anonymous author wrote (`set.postIds`), on any host. + */ +export function anonymousUrl(host, path, set) { + const h = str(host).toLowerCase().replace(/^(?:www|mobile|m)\./, ""); + const raw = str(path); + const truncated = /(?:…|\.\.\.)$/.test(raw); + const p = safeDecode(raw.replace(/(?:…|\.\.\.)$/, "")); + const status = p.match(/\/(?:status|statuses|post|posts|video|reel|p)\/([A-Za-z0-9_-]+)/)?.[1]; + if (status && set.postIds?.has(status.toLowerCase())) return true; + if (!PLATFORM_HOSTS.includes(h)) return false; + const [pathPart, query = ""] = p.split(/\?/, 2); + const segs = pathPart.split(/[/#]/).filter(Boolean); + const cands = []; + if (segs.length) cands.push(h === "bsky.app" && segs[0].toLowerCase() === "profile" ? segs[1] ?? "" : segs[0].replace(/^@/, "")); + const q = new URLSearchParams(query.split("#")[0]); + const from = (q.get("q") ?? "").match(/from:@?([A-Za-z0-9_.-]+)/i)?.[1]; + if (from) cands.push(from); + if (q.get("screen_name")) cands.push(q.get("screen_name")); + for (const c of cands.map((x) => handleKey(x))) { + if (!c) continue; + if (set.has(c)) return true; + // Truncated where the account segment is the last thing seen: its visible start. + if (truncated && segs.length === 1 && c.length >= 4 && [...set.keys()].some((k) => k.startsWith(c))) return true; + } + return false; +} + +/** One pass over `text` (see anonymiseWords / speakAnonymised): `{ text, handles, urls }` -- what it replaced. */ +function rewrite(text, set, spoken) { + const handles = new Set(); + let urls = 0; + const re = patternOf(set, spoken); + const out = text.replace(re, (...args) => { + const all = args[0]; + const g = args.at(-1); + if (g.host !== undefined) { + // A URL: an anonymous author's is collapsed to its bare host ("x.com/…"); trailing punctuation kept. + const path = g.path ?? ""; + const tail = path.match(/[.,;:!?)\]]+$/)?.[0] ?? ""; + const core = tail ? path.slice(0, -tail.length) : path; + if (!core || !anonymousUrl(g.host, core, set)) return all; + urls += 1; + return `${g.host.toLowerCase().replace(/^(?:www|mobile|m)\./, "")}/…${tail}`; + } + const h = (g.at ?? g.bare ?? "").toLowerCase(); + const s = set.get(h); + if (!s) return all; + handles.add(h); + return spoken ? s : `@${pseudonymOf(s)}`; + }); + return { text: out, handles: [...handles], urls }; +} + +/** + * `text` as a card draws it: every @mention of an anonymous handle made the pseudonym's ("@Anon_1"), every URL of an + * anonymous author's (anonymousUrl) collapsed to its bare host ("x.com/…") -- one word for one, in ONE pass (no + * replacement is looked at again). The same string when none is in it. * @param {string} text * @param {Map<string, string>} set anonymousHandles' */ export function anonymiseWords(text, set) { - if (typeof text !== "string" || !set?.size) return text; - const re = patternOf(set); - if (!re) return text; - return text.replace(re, (all, pre, h) => { - const s = set.get(h.toLowerCase()); - return s ? `${pre}${pseudonymOf(s)}` : all; - }); + if (typeof text !== "string" || !set?.size || !text) return text; + const r = rewrite(text, set, false); + return r.handles.length || r.urls ? r.text : text; } /** An object with the words of `keys` anonymised; the object itself when none changed. */ @@ -166,6 +277,11 @@ export function anonymiseEntry(e0, set) { o.handle = pseudonymOf(ownShown); o.anonymous = true; delete o.badge; + // No link to their post anywhere: no corner QR (deck.mjs deckQrUrl), no cite or archive link. + o.noQr = true; + delete o.citeUrl; + delete o.siteUrl; + delete o.siteChannel; } const refs = (list) => { if (!Array.isArray(list)) return list; @@ -207,9 +323,9 @@ function anonymisePopup(p0, set) { const p = unflag(p0); if (!isObj(p) || !set.size) return p; const s = set.get(handleKey(p.handle)) ?? null; - let out = withWords(p, set, ["text", "url", "siteUrl"]); + let out = withWords(p, set, ["text", "url"]); if (s) { - const { shot: _s, thread: _t, siteUrl: _u, shotMaxHeight: _h, ...rest } = asAnon(out, s); + const { shot: _s, thread: _t, siteUrl: _u, siteChannel: _c, citeUrl: _ci, shotMaxHeight: _h, ...rest } = asAnon(out, s); out = { ...rest, noQr: true }; } // A popup's thread shot pictures the posts above it: with any anonymous handle, never drawn. @@ -225,10 +341,16 @@ function anonymisePopup(p0, set) { * video has no anonymous handle and nothing carried a stray flag. `doc`: characters.json's document. The set is kept * on the result as `anonymousHandles` (`{ <handle>: <shown> }`) for the modules that draw a handle of their own (the * promise panel, a chat replay). Throws AnonymityError for what it cannot resolve. + * + * @param {any} manifest + * @param {any} doc + * @param {{ set?: (Map<string, string> & { postIds?: Set<string> }) | null }} [o] */ -export function anonymiseManifest(manifest, doc) { +export function anonymiseManifest(manifest, doc, { set: given = null } = {}) { if (!isObj(manifest)) return manifest; - const set = anonymousHandles(doc, manifest); + // The PROJECT's set when the caller has it (projectAnonymousSet: the whole manifest, every variant, a take's too); + // else this manifest's own. + const set = given ?? anonymousHandles(doc, manifest); let changed = false; const tl = Array.isArray(manifest.timeline) ? manifest.timeline.map((e) => { const n = anonymiseEntry(e, set); @@ -240,14 +362,24 @@ export function anonymiseManifest(manifest, doc) { if (n !== p) changed = true; return n; }) : manifest.posts; - const stray = "anonymousHandles" in manifest; + const stray = "anonymousHandles" in manifest || "anonymousPostIds" in manifest; if (!changed && !set.size && !stray) return manifest; - const { anonymousHandles: _x, ...rest } = manifest; - return { ...rest, ...(tl !== undefined ? { timeline: tl } : {}), ...(posts !== undefined ? { posts } : {}), ...(set.size ? { anonymousHandles: Object.fromEntries(set) } : {}) }; + const { anonymousHandles: _x, anonymousPostIds: _y, ...rest } = manifest; + return { + ...rest, ...(tl !== undefined ? { timeline: tl } : {}), ...(posts !== undefined ? { posts } : {}), + ...(set.size ? { anonymousHandles: Object.fromEntries(set), anonymousPostIds: [...(set.postIds ?? [])] } : {}), + }; } -/** The anonymous handles a manifest carries after the pass (`anonymousHandles`): `Map<handle, shown>`. */ -export const anonymousHandlesOf = (manifest) => new Map(Object.entries(isObj(manifest?.anonymousHandles) ? manifest.anonymousHandles : {}).filter(([, v]) => typeof v === "string")); +/** The anonymous set a manifest carries after the pass (`anonymousHandles`, `anonymousPostIds`): anonymousHandles' shape. */ +export function anonymousHandlesOf(manifest) { + const m = /** @type {Map<string, string> & { postIds: Set<string> }} */ (new Map(Object.entries(isObj(manifest?.anonymousHandles) ? manifest.anonymousHandles : {}).filter(([, v]) => typeof v === "string"))); + m.postIds = new Set(Array.isArray(manifest?.anonymousPostIds) ? manifest.anonymousPostIds.map(String) : []); + return m; +} + +/** Deck popup posts (`manifest.posts[]`) as the set has them -- after a preview's unsaved draft is laid on (onscreen.mjs). */ +export const anonymisePosts = (posts, set) => (Array.isArray(posts) && set?.size ? posts.map((p) => anonymisePopup(p, set)) : posts); /** * A chat replay's messages (chat.mjs chatSchedule's `clips`) as the anonymous set has them: a message whose author is @@ -275,25 +407,19 @@ export function anonymiseChatClips(clips, set) { } /** - * WHAT A SYNTHESIZED READ SAYS for an anonymous handle (post-redact.mjs spokenRead): `@realguy` said as the shown name - * ("Anon 1"), a platform URL carrying one made the pseudonym's -- one pass. `{ text, handles }`: `handles` the + * WHAT A SYNTHESIZED READ SAYS for an anonymous handle (post-redact.mjs spokenRead): `@realguy` -- and the bare + * handle as a whole word, when it can be told from words (bareSayable: 4+ characters, not a common word) -- said as + * the shown name ("Anon 1"); an anonymous author's URL collapsed to its host. One pass. `{ text, handles }`: the * anonymous handles it replaced (lower case; none: the same text). * @param {string} text * @param {Map<string, string> | Record<string, string> | null} set */ export function speakAnonymised(text, set) { - const m = set instanceof Map ? set : new Map(Object.entries(isObj(set) ? set : {})); - if (typeof text !== "string" || !m.size) return { text, handles: [] }; - const re = patternOf(m); - if (!re) return { text, handles: [] }; - const handles = new Set(); - const out = text.replace(re, (all, pre, h) => { - const s = m.get(h.toLowerCase()); - if (!s) return all; - handles.add(h.toLowerCase()); - return pre === "@" ? s : `${pre}${pseudonymOf(s)}`; - }); - return { text: out, handles: [...handles] }; + const m = set instanceof Map ? set : new Map(Object.entries(isObj(set) ? set : {}).filter(([k, v]) => k !== "postIds" && typeof v === "string")); + if (!(set instanceof Map) && Array.isArray(set?.postIds)) /** @type {any} */ (m).postIds = new Set(set.postIds); + if (typeof text !== "string" || !m.size || !text) return { text, handles: [] }; + const r = rewrite(text, m, true); + return r.handles.length || r.urls ? { text: r.text, handles: r.handles } : { text, handles: [] }; } /** The take a post item plays (narration.pick, else the first; none when off) -- post-narration.mjs pickedTake's rule. */ @@ -313,11 +439,15 @@ const phraseRe = (s) => new RegExp(`(?<![\\p{L}\\p{N}_])${escRe(s)}(?![\\p{L}\\p * a captured thread shot or a popup's screenshot and QR code not drawn; attachments are the operator's to check * Messages name the shown name, never the real one. An anonymity the pass cannot resolve is an ERROR. * @returns {{ errors: string[], warnings: string[] }} + * + * @param {any} manifest + * @param {any} doc + * @param {{ set?: (Map<string, string> & { postIds?: Set<string> }) | null }} [o] */ -export function anonymityProblems(manifest, doc) { +export function anonymityProblems(manifest, doc, { set: given = null } = {}) { let set; try { - set = anonymousHandles(doc, manifest); + set = given ?? anonymousHandles(doc, manifest); } catch (e) { return { errors: [e instanceof Error ? e.message : String(e)], warnings: [] }; } @@ -340,11 +470,25 @@ export function anonymityProblems(manifest, doc) { if (e?.type !== "post") continue; const t = playing(e); if (t) { - const said = [str(t.script), ...(Array.isArray(t.parts) ? t.parts.map((p) => str(p?.text)) : [])].join("\n"); - const done = new Set(Array.isArray(t.anonymised) ? t.anonymised : []); - for (const [h, shown] of set) if (!done.has(h) && phraseRe(h).test(said)) errors.push(`timeline ${e.id}: its picked read says ${shown}'s handle as written -- an anonymous author's: re-read it (a synthesized read says "${shown}") or record it again without it`); + // WHAT IT SAYS: a synthesized take's spoken text (`said`, kept when it differs from the script), else its script + // (a recording says its script) -- and a thread read's parts. Judged as said: no exemption list. + const said = [str(t.said) || str(t.script), ...(Array.isArray(t.parts) ? t.parts.map((p) => str(p?.text)) : [])].join("\n"); + for (const [h, shown] of set) { + const at = new RegExp(`(?<![\\w.@])@${escRe(h)}(?![A-Za-z0-9_]|\\.[A-Za-z0-9])`, "iu").test(said); + const bare = phraseRe(h).test(said.replace(new RegExp(`@${escRe(h)}`, "giu"), " ")); + if (at || (bare && bareSayable(h))) errors.push(`timeline ${e.id}: its picked read says ${shown}'s handle -- an anonymous author's: re-read it (a synthesized read says "${shown}") or record it again without it`); + else if (bare) warnings.push(`timeline ${e.id}: its picked read says a word that is ${shown}'s handle (short or a common word: it is said as written) -- check it is not them`); + } for (const [n, shown] of names) if (phraseRe(n).test(said)) errors.push(`timeline ${e.id}: its picked read says ${shown}'s display name -- an anonymous author's: re-read or record it again without it`); } + // An anonymous author's own words: a URL the pass cannot classify (not a platform's, not one of their posts). + if (set.has(handleKey(e.handle))) { + for (const m of str(e.text).matchAll(new RegExp(URL_SRC, "giu"))) { + const g = m.groups ?? {}; + if (!g.path || g.path === "/") continue; + if (!anonymousUrl(g.host, g.path.replace(/[.,;:!?)\]]+$/, ""), set)) warnings.push(`timeline ${e.id}: ${set.get(handleKey(e.handle))}'s words carry a link the pass cannot classify (${g.host}/…) -- drawn as written: check it does not lead to them`); + } + } const drawn = whoOf(e).flatMap((w) => [str(w.text), str(w.paraphrase)]).join("\n"); for (const [n, shown] of names) if (phraseRe(n).test(drawn)) warnings.push(`timeline ${e.id}: its words write out ${shown}'s display name -- the card draws words as written: edit them, or redact the name (umtool posts redact)`); if (typeof e.parentShot === "string") warnings.push(`timeline ${e.id}: its captured thread shot is not drawn -- this video has anonymous authors, and a shot may picture them (the card's "Replying to" line stands in)`); diff --git a/umtool/report-to-video/post-anon.test.mjs b/umtool/report-to-video/post-anon.test.mjs @@ -61,28 +61,64 @@ test("probe 2: an anonymous character named on an item by id, holding no handles // Unresolvable: an item naming an anonymous character with no handle of its own -- refused, never drawn in clear. assert.throws(() => anonymiseManifest({ timeline: [base({ handle: "", narration: { character: "anon-1" } })] }, doc([anonNoH])), AnonymityError); // One handle under two shown names: refused. - assert.throws(() => anonymousHandles(doc([ANON, { id: "anon-2", name: "B", anonymous: true, shown: "Anon 2", handles: [] }]), { timeline: [base({ narration: { character: "anon-2" } })] }), /shown as "Anon 1" and as "Anon 2"/); + assert.throws(() => anonymousHandles(doc([ANON, { id: "anon-2", name: "B", anonymous: true, shown: "Anon 2", handles: [] }]), { timeline: [base({ narration: { character: "anon-2" } })] }), /shown as "Anon 1" \(anon-1's handles\) and as "Anon 2" \(p1 names anon-2\)/); }); -test("probe 3: handles in drawn URLs (x.com, twitter.com, bsky.app, any case, dotted Bluesky handles) -- one pass, no chaining", () => { +test("probe 3 / re-check 2: a URL of an anonymous author's is collapsed to its host; @mentions keep the pseudonym; one pass", () => { const set = anonymousHandles(doc([ANON, { id: "anon-b", name: "B", anonymous: true, shown: "Anon B", handles: ["real.bsky.social"] }])); - assert.equal(anonymiseWords("see https://x.com/RealGuy/status/1850000000000000000 now", set), "see https://x.com/Anon_1/status/1850000000000000000 now"); - assert.equal(anonymiseWords("https://mobile.twitter.com/realguy and twitter.com/REALGUY?s=20", set), "https://mobile.twitter.com/Anon_1 and twitter.com/Anon_1?s=20"); - assert.equal(anonymiseWords("@Real.Bsky.Social. hi https://bsky.app/profile/real.bsky.social/post/3k", set), "@Anon_B. hi https://bsky.app/profile/Anon_B/post/3k"); - // Not a handle: another domain ending in x.com, a longer handle, an e-mail. - assert.equal(anonymiseWords("netflix.com/RealGuy @realguys me@realguy.com", set), "netflix.com/RealGuy @realguys me@realguy.com"); - // RT text; the drawn card of a status URL in the post's own words. + const cases = [ + ["see https://x.com/RealGuy/status/1850000000000000000 now", "see x.com/… now"], + ["https://mobile.twitter.com/realguy and twitter.com/REALGUY?s=20", "twitter.com/… and twitter.com/…"], + ["@Real.Bsky.Social. hi https://bsky.app/profile/real.bsky.social/post/3k", "@Anon_B. hi bsky.app/…"], + ["https://nitter.net/realguy/status/1 https://xcancel.com/realguy https://fxtwitter.com/realguy/status/1", "nitter.net/… xcancel.com/… fxtwitter.com/…"], + ["https://vxtwitter.com/realguy/status/1 https://fixupx.com/realguy https://www.instagram.com/realguy/", "vxtwitter.com/… fixupx.com/… instagram.com/…"], + ["https://x.com/%72ealguy/status/1 and https://x.com/@realguy", "x.com/… and x.com/…"], + ["https://x.com/search?q=from%3Arealguy https://twitter.com/intent/user?screen_name=realguy", "x.com/… twitter.com/…"], + ["x.com/realgu… and twitter.com/realguy/sta…", "x.com/… and twitter.com/…"], + ["x.com/realguy.", "x.com/…."], + ["@realguy's take (@RealGuy)", "@Anon_1's take (@Anon_1)"], + ]; + for (const [i, o] of cases) assert.equal(anonymiseWords(i, set), o, i); + // Not theirs: another domain, a longer handle, an e-mail, a truncated start under 4 characters, another account. + for (const same of ["netflix.com/RealGuy @realguys me@realguy.com", "x.com/rea…", "https://x.com/public/status/1"]) assert.equal(anonymiseWords(same, set), same); + // A status URL of a post an anonymous author wrote, on any account's path or host. + const [own] = pass(base({ post: "x/1850000000000000000", url: "https://x.com/RealGuy/status/1850000000000000000" }), doc([ANON]), [base({ id: "p2", author: "P", handle: "p", text: "see https://x.com/i/web/status/1850000000000000000 and https://archive.example/s/1850000000000000000/status/1850000000000000000" })]); + assert.equal(own.url, "x.com/…"); + const tl2 = anonymiseManifest({ timeline: [base({ post: "x/1850000000000000000" }), base({ id: "p2", author: "P", handle: "p", text: "see https://x.com/i/web/status/1850000000000000000" })] }, doc([ANON])).timeline; + assert.equal(tl2[1].text, "see x.com/…"); + // RT text, a quoted post's url, the drawn cards. const [rt] = pass(base({ author: "P", handle: "p", text: "RT @RealGuy: something", repostedBy: { author: "Real Guy", handle: "RealGuy" } })); assert.deepEqual(leaks(card(rt)), []); - const [u] = pass(base({ text: "see https://x.com/RealGuy/status/1850000000000000000 now" })); - assert.deepEqual(leaks(card(u)), []); - // A quoted post's url too. const [q] = pass(base({ author: "P", handle: "p", quoted: { id: "q", author: "Real Guy", handle: "RealGuy", text: "q", url: "https://x.com/RealGuy/status/123456" } })); - assert.equal(q.quoted.url, "https://x.com/Anon_1/status/123456"); + assert.equal(q.quoted.url, "x.com/…"); assert.deepEqual(leaks(card(q)), []); - // NO CHAINING: a pseudonym that equals another anonymous handle is not rewritten again. - const chain = doc([ANON, { id: "anon-2", name: "B", anonymous: true, shown: "realguy", handles: ["bob"] }]); - assert.equal(pass(base({ author: "P", handle: "p", text: "@bob and @RealGuy" }), chain)[0].text, "@realguy and @Anon_1"); + // NO CHAINING. + const chain = doc([ANON, { id: "anon-2", name: "B", anonymous: true, shown: "Bob Two", handles: ["bob"] }]); + assert.equal(pass(base({ author: "P", handle: "p", text: "@bob and @RealGuy" }), chain)[0].text, "@Bob_Two and @Anon_1"); +}); + +test("re-check 1: the set is the PROJECT's -- an item naming the character in another variant, or dropped from the cut, still covers its author", async () => { + const { selectVariant } = await import("./build-video.mjs"); + const anonNoH = { ...ANON, handles: [] }; + const whole = { timeline: [ + base({ id: "p1", handle: "realguy", text: "mine", variant: "full", narration: { character: "anon-1" } }), + base({ id: "p2", author: "Pub", handle: "pub", text: "@realguy is wrong", parents: [{ id: "9", author: "Real Guy", handle: "realguy", text: "q" }] }), + ] }; + const set = anonymousHandles(doc([anonNoH]), whole); + for (const v of ["full", "sourced"]) { + const a = anonymiseManifest(selectVariant(whole, v), doc([anonNoH]), { set }); + const p2 = a.timeline.find((e) => e.id === "p2"); + assert.deepEqual([p2.text, p2.parents[0].author], ["@Anon_1 is wrong", "Anon 1"], v); + } + // projectAnonymousSet: the project's manifest on disk and a take's manifest, unioned. + const { projectAnonymousSet } = await import("./project-characters-file.mjs"); + const dir = path.join(TMP, "whole"); + await mkdir(path.join(dir, "narration"), { recursive: true }); + await writeFile(path.join(dir, "narration", "characters.json"), JSON.stringify(doc([anonNoH]))); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(whole)); + const take = { timeline: [whole.timeline[1]] }; + const r = await projectAnonymousSet(dir, take); + assert.deepEqual([...r.set.keys()], ["realguy"], "the take's cut drops p1; the project's manifest still names it"); }); test("probe 4: deck popup posts -- the shown name, no screenshot, no QR; a thread shot never drawn with anonymity in the video", () => { @@ -96,7 +132,7 @@ test("probe 4: deck popup posts -- the shown name, no screenshot, no QR; a threa assert.equal(m.timeline[0].parentShot, undefined, "the shot may picture an anonymous grandparent: never drawn"); const [a, b] = m.posts; assert.deepEqual([a.author, a.handle, a.anonymous, a.noQr, a.shot, a.thread, a.siteUrl], ["Anon 1", "Anon_1", true, true, undefined, undefined, undefined]); - assert.equal(a.url, "https://x.com/Anon_1/status/1"); + assert.equal(a.url, "x.com/…"); assert.deepEqual(postWho(a), { name: "Anon 1", platform: postWho(b).platform }); assert.deepEqual([b.shot, b.thread, b.text], ["shots/b.png", undefined, "cc @Anon_1"], "a public author's own shot stays; its thread shot does not"); assert.deepEqual(m.anonymousHandles, { realguy: "Anon 1" }); @@ -157,7 +193,10 @@ test("should-fix b: two anonymous characters are never shown alike; ones with no }); test("probe 6: what a synthesized read says -- the shown name, never the handle; the handles it replaced", () => { - assert.deepEqual(speakAnonymised("thanks @RealGuy, see https://x.com/realguy/status/1", { realguy: "Anon 1" }), { text: "thanks Anon 1, see https://x.com/Anon_1/status/1", handles: ["realguy"] }); + assert.deepEqual(speakAnonymised("thanks @RealGuy, see https://x.com/realguy/status/1", { realguy: "Anon 1" }), { text: "thanks Anon 1, see x.com/…", handles: ["realguy"] }); + // A bare handle as a whole word too -- when it can be told from words; a short or common one only by its @form. + assert.equal(speakAnonymised("@realguy said it. realguy, stop. Realguys no.", { realguy: "Anon 1" }).text, "Anon 1 said it. Anon 1, stop. Realguys no."); + assert.equal(speakAnonymised("@news said: the news is out", { news: "Anon N" }).text, "Anon N said: the news is out"); const said = spokenRead("RT @RealGuy: hi", { id: "p" }, { anon: { realguy: "Anon 1" } }); assert.ok(!/realguy/i.test(said.text), said.text); assert.deepEqual(said.anonymised, ["realguy"]); @@ -169,14 +208,14 @@ test("the lint: a picked read that says an anonymous handle or name is an ERROR; const m = { timeline: [ base({ id: "p1", narration: { takes: [take({ engine: "recorded", script: "I am @RealGuy" })], pick: 0 } }), - base({ id: "p2", author: "P", handle: "p", text: "Real Guy said so", narration: { takes: [take({ engine: "kokoro", script: "thanks @RealGuy", anonymised: ["realguy"] })], pick: 0 } }), + base({ id: "p2", author: "P", handle: "p", text: "Real Guy said so", narration: { takes: [take({ engine: "kokoro", script: "thanks @RealGuy", said: "thanks Anon 1" })], pick: 0 } }), base({ id: "p3", author: "P", handle: "p", parentShot: "s.png", narration: { takes: [take({ engine: "kokoro", script: "as Real Guy put it" })], pick: 0 } }), ], posts: [{ id: "x1", handle: "realguy", author: "Real Guy", text: "x" }], }; const r = anonymityProblems(m, doc([ANON])); assert.deepEqual(r.errors.map((x) => x.replace(/:.*/, "")), ["timeline p1", "timeline p3"]); - assert.match(r.errors[0], /says Anon 1's handle as written/); + assert.match(r.errors[0], /says Anon 1's handle/); assert.match(r.errors[1], /says Anon 1's display name/); for (const x of [...r.errors, ...r.warnings]) assert.ok(!/RealGuy|Real Guy|realguy/.test(x), `the lint never repeats the real name: ${x}`); assert.ok(r.warnings.some((w) => /p2: its words write out Anon 1's display name/.test(w))); @@ -210,3 +249,50 @@ test("the build reads this video's characters beside the manifest: none is none; test("anonymiseEntry on its own takes the set", () => { assert.equal(anonymiseEntry(base(), new Map([["realguy", "Anon 1"]])).author, "Anon 1"); }); + +test("re-check: a short or common handle said bare is a WARNING; an anonymous author's unclassified link is a WARNING", () => { + const d = doc([{ id: "n", name: "N", anonymous: true, shown: "Anon N", handles: ["news"] }, ANON]); + const take = (script) => ({ file: "narration/posts/1/take-1.wav", seconds: 2, engine: "recorded", script }); + const r = anonymityProblems({ timeline: [ + base({ id: "p1", author: "P", handle: "p", narration: { takes: [take("the news is out")], pick: 0 } }), + base({ id: "p2", text: "my blog https://myblog.example/about and https://x.com/public" }), + ] }, d); + assert.deepEqual(r.errors, []); + assert.ok(r.warnings.some((w) => /p1: its picked read says a word that is Anon N's handle/.test(w))); + assert.ok(r.warnings.some((w) => /p2: Anon 1's words carry a link the pass cannot classify \(myblog.example\/…\)/.test(w))); +}); + +test("should-fix a/b: a shown name that is a real author's handle or name, or another character's handle, is refused -- naming characters, never the real handle", () => { + const pat = doc([{ id: "a2", name: "Bob", anonymous: true, shown: "Pat", handles: ["bob"] }]); + const m = { timeline: [base({ id: "p", author: "Pat", handle: "pat", text: "@bob said" })] }; + assert.match(validateProjectCharacters(pat, "c", { manifests: [m] }).join(), /a2's shown name "Pat" is also an author's handle in p/); + assert.throws(() => anonymiseManifest(m, pat), /a2's shown name "Pat"/); + const two = doc([ANON, { id: "a2", name: "B", anonymous: true, shown: "realguy", handles: ["bob"] }]); + assert.match(validateProjectCharacters(two).join(), /a2's shown name "realguy" is anon-1's handle/); + // The unresolvable message names characters and items, never the handle. + const r = anonymityProblems({ timeline: [base({ id: "p3", handle: "realguy", narration: { character: "a3" } })] }, doc([ANON, { id: "a3", name: "O", anonymous: true, shown: "Anon 3", handles: [] }])); + assert.equal(r.errors.length, 1); + assert.ok(!/realguy/i.test(r.errors[0]), r.errors[0]); +}); + +test("re-check 2: no deck QR for an anonymous author's item, with citeUrl or an archive channel", async () => { + const { deckQrUrl } = await import("./deck.mjs"); + const prov = { siteOrigin: "https://archive.example" }; + const e = base({ post: "realguy-x/1850000000000000000", url: "https://x.com/realguy/status/1850000000000000000" }); + for (const x of [e, { ...e, citeUrl: e.url }, { ...e, siteChannel: "realguy-x" }]) { + const [a] = anonymiseManifest({ provenance: prov, timeline: [x] }, doc([ANON])).timeline; + assert.equal(deckQrUrl(a, prov, { links: "archive" }), null); + assert.equal(deckQrUrl(a, prov, { links: "original" }), null); + assert.equal(a.citeUrl, undefined); + } + assert.ok(deckQrUrl(base({ author: "P", handle: "p", url: "https://x.com/p/status/1" }), prov), "a public author's keeps its code"); +}); + +test("re-check 3: the podcast's show notes cite an anonymous author's post by the shown name, with no link", async () => { + const { citedSources, showNotes } = await import("./build-podcast.mjs"); + const m = anonymiseManifest({ title: "T", provenance: {}, timeline: [], posts: [{ id: "pp", platform: "x", author: "Real Guy", handle: "realguy", date: "2026-01-01", text: "x", url: "https://x.com/realguy/status/1850000000000000000" }, { id: "pq", platform: "x", author: "Pub", handle: "pub", date: "2026-01-01", text: "y", url: "https://x.com/pub/status/2" }] }, doc([ANON])); + const notes = showNotes({ manifest: m, chapters: [], sources: citedSources(m, [], []) }); + assert.ok(!/realguy|Real Guy|1850000000000000000/i.test(notes), notes); + assert.match(notes, /^- Anon 1 \(x, 2026-01-01\)$/m); + assert.match(notes, /^- Pub \(x, 2026-01-01\) — <https:\/\/x.com\/pub\/status\/2>$/m); +}); diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -192,9 +192,10 @@ const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice", "follow", "thread"]); // `character`: the character THIS item's own read is made with (cast.mjs: the project's own, else the cast's) -- absent: by its author's handle. const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "character", "takes", "pick", "approved", "off", "window"]); -// `anonymised`: the anonymous handles a synthesized read said as their shown names (post-anon.mjs); `speedAsked`: a -// single take's speed was the command's --speed (kept as asked: the drift guard and a re-read). -const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs", "lexicon", "read", "anonymised", "speedAsked"]); +// `said`: what a synthesized read SAID when an anonymous handle made it differ from its script (post-anon.mjs; the +// lint reads it); `speedAsked`: where its speed came from -- true (the command's --speed: kept as asked), "item" (the +// item's own), "preset" (its character's: drift when that changes). Absent: unknown -- never speed drift. +const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs", "lexicon", "read", "said", "speedAsked"]); const STEP_KEYS = new Set(["op", "engine", "voice", "pitch", "semitones", "params", "ranAt", "job", "drop", "tempo", "spans", "pauses", "revoice"]); // `role` (post-thread.mjs): the text a part reads -- "post", "quoted", "parent:<i>", "media:<i>"; `voice`, `piece`: the batch's; // `engine`: the part's own when it is not the take's (a cast voice that names its engine: postThreadRead.mjs). @@ -654,8 +655,8 @@ export function validatePostNarration(e) { if (t.slurs !== undefined && !["said", "skip", "placeholder"].includes(t.slurs)) errors.push(`${tw}.slurs must be said, skip or placeholder`); // The pronunciation entries its read applied (post-say.mjs), and how a thread read was asked for (postThreadRead.mjs). errors.push(...takeLexiconErrors(t.lexicon, `${tw}.lexicon`)); - if (t.anonymised !== undefined && !(Array.isArray(t.anonymised) && t.anonymised.length <= 300 && t.anonymised.every((h) => typeof h === "string" && /^[a-z0-9_.-]{1,64}$/.test(h)))) errors.push(`${tw}.anonymised must be the anonymous handles its read said as shown names`); - if (t.speedAsked !== undefined && t.speedAsked !== true) errors.push(`${tw}.speedAsked must be true or absent`); + if (t.said !== undefined && (typeof t.said !== "string" || t.said.length > 50000)) errors.push(`${tw}.said must be the words its read said`); + if (t.speedAsked !== undefined && t.speedAsked !== true && t.speedAsked !== "item" && t.speedAsked !== "preset") errors.push(`${tw}.speedAsked must be true, "item" or "preset"`); if (t.read !== undefined && !(isObj(t.read) && t.read.kind === "thread" && JSON.stringify(t.read).length <= 4000)) errors.push(`${tw}.read must be {kind: "thread", …} (how the thread read was asked for)`); if (t.words !== undefined) { // Its script's words, timed in take seconds (the editor's transcription, aligned: word-zoom.mjs scriptWordTimes). diff --git a/umtool/report-to-video/project-characters-file.mjs b/umtool/report-to-video/project-characters-file.mjs @@ -31,3 +31,21 @@ export async function readProjectCharactersFor(manifestDir) { return doc; } + +/** + * THE PROJECT's ANONYMOUS SET (post-anon.mjs anonymousHandles), the ONE place the build, the chrome composer, the lint + * and the previews take it from: this video's characters beside `manifestDir`, over the WHOLE project manifest on disk + * (`video.manifest.json`: every variant, before rulings, windows or `--only`) and `whole` -- the manifest being drawn as + * its file holds it (a take's render manifest, a lint's scratch copy: its patch's entries count too). Throws when the + * characters cannot be read or the anonymity cannot be resolved. + * + * @param {string} manifestDir + * @param {any} [whole] + * @returns {Promise<{ doc: any, set: Map<string, string> & { postIds: Set<string> } }>} + */ +export async function projectAnonymousSet(manifestDir, whole = null) { + const { anonymousHandles } = await import("./post-anon.mjs"); + const doc = await readProjectCharactersFor(manifestDir); + const project = await readFile(path.join(manifestDir, "video.manifest.json"), "utf8").then(JSON.parse, () => null); + return { doc, set: anonymousHandles(doc, ...[project, whole].filter(Boolean)) }; +}