commit b72d3fe572b28969f52a0a14c52269e29595d6c7
parent 0101029a7e777aa2de67dffe2dbe3c03afa92195
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 12 Nov 2026 03:21:15 -0500
Merge branch 'main' into lane/local-sweep
Diffstat:
362 files changed, 23360 insertions(+), 1058 deletions(-)
diff --git a/.gitignore b/.gitignore
@@ -91,6 +91,8 @@ yarn-error.log*
/export/.compose-cache/
# per-site docker build outputs (out/, .next, public/, caches) — one dir per site
/export/.export-builds/
+# remote archives' documents cached on disk (common/lib/archiveCache-server.ts)
+/export/.archive-cache/
/transcripts/index.mdb/
# homepage (hub) generated public data (regenerate with `pnpm build:homepage`)
diff --git a/AGENTS.md b/AGENTS.md
@@ -165,9 +165,15 @@ The high-value loop: point the MCP at a public instance, ask about a subject, th
fetching cheap. Clip media for a cited moment goes through the `fetch_clip` MCP tool
(→ the editor's `POST /api/media/fetch-window`, paced, cookie-aware and provenanced),
never `yt-dlp --download-sections` by hand; that command is only the fallback for a
-machine with no editor. The editor fetches only for a channel it already archives (a
-`transcripts/channels/<slug>/`), so an MCP pointed at a public site with a fresh editor
-gets a 404 `Channel "<slug>" not found` on every clip.
+machine with no editor. The editor fetches for a channel it archives (a
+`transcripts/channels/<slug>/`) — or, when the ask names a **connected archive**
+(`settings.remoteArchives`: /sites → Connected archives, `pnpm ops archives`;
+TRANSCRIPT_SITE_URL's is connected by default), for that archive's channel, which it
+registers on first need as a **remote-only** channel (config only, no `url`; inert to
+every sync, lane, cleanup and build — CHANNEL.md `remoteOnly`). `fetch_clip` over a
+`remote:` source and umtool's chain name the archive; an archive not connected still
+answers 404 `Channel "<slug>" not found`, naming the connect. A remote-only channel's
+Rumble window (a whole recording) is refused with its size until `allowWholeRecording`.
**`full: true` and "Persist source video" download the source even when a transcript or
captions exist** (`forceMedia` on `downloadOneManaged`, release 10 slice N; "Persist kept
diff --git a/CHANNEL.md b/CHANNEL.md
@@ -39,6 +39,9 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f
| `lastFullDownloadAt` | sync state | SYNC STATE. When a full download pass last completed (ISO time). |
| `lastFullSweepAt` | sync state | SYNC STATE. When this channel last paid for a sync FULL SWEEP — the deep pass that re-enumerates the whole listing to refresh `playlist` and flag videos that have left it. Stamped by the sweep; read by the cadence gate to decide whether the next sync sweeps or stays on the cheap newest-first paged walk. |
| `excludeFromBuild` | config | Leave this channel out of every site build. |
+| `remoteOnly` | config | A REMOTE-ONLY channel: held only to fetch clip windows that a connected archive's citations name (settings.remoteArchives). Registered by the editor the first time a window of it is asked for, with no listing sweep. Inert: no sync, no lane, no cleanup, no auto-download, on no site, in no index build; the channel list shows it as remote-only. A whole-recording platform's window (Rumble) is refused with the recording's size until the ask says `allowWholeRecording`. |
+| `remoteArchive` | config | A remote-only channel's archive: the origin whose corpus.json names it. |
+| `remoteUrl` | config | A remote-only channel's page on its platform, as its archive's corpus.json named it (spec 6). Informational: a remote-only channel has no `url`, so nothing syncs it. |
| `excludeFromCleanup` | config | Leave this channel's reclaimable bytes out of the aggregate "cleanable data" total on /cleanup and its badge. The per-channel cleanup sweeps stay available; only the running total changes. |
| `cleanAfterCaptureUnverified` | config | Let clean-after-capture (settings `diarization.cleanAfterCapture`) delete this channel's audio with NO availability check. Only for a channel with no `url`: with no source there is nothing to list, so the automatic per-video clean holds every such channel ("no source to check: clean by hand") unless this is true. The manual Clean audio sweep is unaffected. Absent/false = held. |
| `syncIntervalMinutes` | config | Auto-sync cadence: the scheduler syncs this channel when `now - lastSyncedAt >= syncIntervalMinutes`. Absent = inherit the global default; 0 = auto-sync off (still manually syncable); positives clamp to [1, 44640] (~31 days). A missing `url`, or a `sync` tier of paused in the channel-priority document, also disables auto-sync. |
@@ -57,6 +60,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f
| `mirror` | config | For a channel that MIRRORS another creator's streams: the creator's channels it copies (`of`, their slugs). The mirror scan (`pnpm ops mirror-scan`) pairs each of this channel's videos with the creator's by date and title and writes `transcripts/mirrors/<slug>.json`: which videos the creator still has public, removed or never uploaded, and which of the creator's removed videos this channel holds. Private: never published. An object without a usable `of` is dropped. See [`mirror`](#mirror). |
| `wayback` | config | A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest", auto?: true}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture's original URL. Each capture imported (`pnpm ops import-page`, the channel page's **Import a capture**) becomes a page record in the channel's posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped. `auto: true` lets the download lane import the captures a later scan (`pnpm ops wayback-scan`, the **Captures** tab) adds, one job each at archive.org's pace; absent, nothing is imported unasked. Release 37 lane F: a target's `sources` (`["wayback", "archive.today"]`; absent = the Wayback Machine alone) says which archives hold its copies, and an archive.today copy imported into the channel is a page record like a capture (OPERATING.md, "Archived pages: the Wayback Machine and archive.today"); the form calls the kind "Archived pages". |
| `xSearch` | config | An X SEARCH channel (platform `"twitter"`, `sourceKind` `"social"`, `url` the search page): a saved X search across accounts, its records the matching posts from ANY author. `{query, since?, until?, windowMonths?, lang?, exclude?}` — `query` as X's search box takes it (words, `"phrases"`, `OR`, `-term`, `from:`, `to:`, `@mention`, `url:`, `filter:`, `lang:` pass through; `since:`, `until:` and `max_id:` are refused — the walk adds them); `since`/`until` the days walked between (YYYY-MM-DD; `since` inclusive, `until` exclusive; absent `until` = tomorrow, and each later fetch searches what is new); `windowMonths` each search window's span (1–12, default 3); `lang` a language code added as `lang:<code>`; `exclude` the handles **Never archive** hid from the leads view (lower case). A fetch walks the windows newest first through gallery-dl's search, resumable, at the older walk's pace and with its login (OPERATING.md, "X search"). Never on a site. An object without a valid query is dropped. |
+| `localMedia` | config | Opt-in external MP4 library: {sourceId, directory, playback?}. The sourceId is a stable lowercase identifier; directory is an absolute server/container path. Source files remain externally owned. Playback is off unless explicitly true, and this flag alone does not authorize public serving. Removing or changing configuration must never move or delete source files. Do not reuse an existing sourceId for a different library; reconcile references explicitly. Private configuration: never include source paths in public exports. |
#### `downloadFilter`
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -103,7 +103,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi
| `archilyzer docs cli` | `[--check]` | write COMMANDS.md from this command table and `pnpm ops --help` |
| `archilyzer settings example` | `[--check]` | write settings.json.example + SETTINGS.md from the schema |
| `archilyzer tts setup` | `[--engine kokoro\|orpheus\|espeak-ng] [--from <dir>] [--python <py>] [--check]` | install a text-to-speech engine under settings.tts.home/<engine> (default ~/.local/share/archilyzer/tts/<engine>): a python venv with its pinned packages (uv venv --python 3.12 when uv is on PATH, else --python <py> -m venv) — kokoro-onnx for kokoro, onnxruntime and numpy for orpheus — and its model files, downloaded once (kokoro: the kokoro-onnx model-files-v1.0 release; orpheus: the Q8\_0 GGUF and the SNAC decoder from Hugging Face, 3.5 GB) one stream at a time with no retries, verified by size and sha256; --from <dir> takes already-downloaded model files from <dir> instead (hard links where it can, else copies; verified the same way); orpheus's llama-server is not installed here (settings.tts.orpheus.serverBin) but is checked; --check installs nothing, lists what is missing and exits 1 when anything is |
-| `archilyzer voice setup` | `--engine deepfilternet\|openvoice\|seed-vc\|rnnoise [--from <dir>] [--python <py>] [--home <dir>] [--dry-run] [--check]` | install a voice engine under settings.voice.home/<engine> (default ~/.local/share/archilyzer/voice/<engine>), saying first what it fetches and how big: deepfilternet is DeepFilterNet's static binary (v0.5.6, 36 MB, its GitHub release); openvoice and seed-vc are a python 3.12 venv (uv venv when uv is on PATH, else --python <py> -m venv) with torch 2.4.0's CPU wheels and their pinned packages, the engine's code at a pinned commit (git fetch --depth 1), and its weights from Hugging Face (openvoice: the v2 converter, 131 MB; seed-vc: the DiT, whisper-small, BigVGAN v2 and CAM++, 1.9 GB) — one download at a time with no retries, each verified by size and sha256; rnnoise needs nothing (ffmpeg's arnndn and the model in the repo) and setup says whether ffmpeg has it; --from <dir> takes already-downloaded files from <dir>/<name> (hard links where it can); --home installs elsewhere (then point settings.voice.home at it); --dry-run says what it would fetch and stops; --check installs nothing, lists what is missing and exits 1 when anything is |
+| `archilyzer voice setup` | `--engine deepfilternet\|openvoice\|seed-vc\|rnnoise [--with f0] [--from <dir>] [--python <py>] [--home <dir>] [--dry-run] [--check]` | install a voice engine under settings.voice.home/<engine> (default ~/.local/share/archilyzer/voice/<engine>), saying first what it fetches and how big: deepfilternet is DeepFilterNet's static binary (v0.5.6, 36 MB, its GitHub release); openvoice and seed-vc are a python 3.12 venv (uv venv when uv is on PATH, else --python <py> -m venv) with torch 2.4.0's CPU wheels and their pinned packages, the engine's code at a pinned commit (git fetch --depth 1), and its weights from Hugging Face (openvoice: the v2 converter, 131 MB; seed-vc: the DiT, whisper-small, BigVGAN v2 and CAM++, 1.9 GB; --with f0 adds seed-vc's OPTIONAL f0-conditioned 44.1 kHz model, its BigVGAN and the RMVPE pitch tracker, 1.49 GB — what voice-convert's pitch source and contour run on, and an install without it still converts at the target's pitch) — one download at a time with no retries, each verified by size and sha256; rnnoise needs nothing (ffmpeg's arnndn and the model in the repo) and setup says whether ffmpeg has it; --from <dir> takes already-downloaded files from <dir>/<name> (hard links where it can); --home installs elsewhere (then point settings.voice.home at it); --dry-run says what it would fetch and stops; --check installs nothing, lists what is missing and exits 1 when anything is (an optional group is said, and counted only with --with) |
| `archilyzer service install` | `[--mode docker\|host] [--apps <a,b>] [--sites <id>:<port>,…] [--overlays <name,…>\|none] [--bind <host>] [--editor-port <n>] [--umtool-port <n>] [--editor-memory <N>G] [--umtool-memory <N>G] [--idle-boot] [--no-housekeeping] [--linger] [--no-start] [--force] [--dry-run]` | install the apps as systemd USER units and start them: docker mode (the default when `docker compose` answers) is ONE unit, archilyzer.service, running `docker compose up` in the foreground with a profile per --apps (editor, umtool, site, homepage, ollama; default editor) and the overlays given or found (anthropic when the key file exists, storage when docker-compose.storage.yml does); host mode is archilyzer-editor.service and archilyzer-umtool.service (node running `next start` from the app dir, -H --bind default 0.0.0.0, ports 3001/3050, MemoryHigh/Max sized from MemTotal) plus archilyzer-site-<id>.service per --sites (a built bundle on 127.0.0.1) and archilyzer-housekeeping.timer, weekly and Persistent, starting the oneshot archilyzer-housekeeping.service (`archilyzer housekeeping --by timer`; a run the heavy slot turns away exits 75 and is retried hourly for a day; --no-housekeeping leaves the pair out); each unit refuses to start while its build or image is missing. A unit already installed under the same name is ADOPTED when identical and shown as a diff and refused when not (--force replaces it; a running unit is not restarted); --no-start enables without starting; --linger runs loginctl enable-linger (start at boot with nobody logged in); --dry-run prints the units and commands and writes nothing. Linux and systemd only |
| `archilyzer service status` | | read-only: each installed archilyzer unit's state, enablement and pid; for an app its build id, its port and what / answers; the transcription lane's held state; in docker mode each container; for archilyzer-housekeeping.timer its next and last trigger and the last recorded run |
| `archilyzer service logs` | `[--apps <a,b>] [--lines <n>] [--follow]` | the units' journal (journalctl --user), the last 200 lines by default |
@@ -131,6 +131,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `delete-article` | delete-article deletes an article, as `archilyzer reports delete <id>` does: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? (unpublish it, and drop a site page naming it with no report of its own, first). It removes the article's directory (report, video, history, notes, iterations), each iteration's video project under settings.generation.projectsRoot and its staged exports. Refused with the plan (409): a published article or such a site page without "force"; a queued or running iteration, force or not. | `pnpm ops delete-article --json '{"id":"demo-article","dryRun":true}'`<br>`pnpm ops delete-article --json '{"id":"demo-article","force":true}'` |
| `delete-iteration` | delete-iteration deletes one iteration and its video project: {"id", "n"}, "dryRun"?. Its number is never given again. Refused with the plan (409), no override: the current article, the iteration its report.json came from, the current video, a queued or running one, one another revises or copies. | `pnpm ops delete-iteration --json '{"id":"demo-article","n":3}'` |
| `delete-site` | delete-site deletes a site, plan first: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? It removes sites/<id>/ (site.json, its pool and pages, tags, charts, its reports), its publish state and last bundle (export/.export-builds/<id>/) and compose's staging for it (export/.export-index/sites/<id>/). Channel data is never touched; the Pages project, what was deployed and a deployed hub are kept (a delete does not undeploy). Refused with the plan (409) unless "force": a deploy target (cloudflareProject), a deploy in its publish state, reports of its own. Refused, force or not: no such site (404), a site dir that is a link, a publish stage running. | `pnpm ops delete-site --json '{"id":"demo-site","dryRun":true}'` |
+| `archives` | archives connects a published archive as a source: {"connect": "<origin>"} reads <origin>/corpus.json once (its title, totals and channels) and saves it in settings.remoteArchives; "dryRun"? answers the probe and writes nothing; an origin connected already writes nothing. A federation hub, a cited-only site, one with no channels or one that does not answer is refused. {"remove": "<id or origin>"} drops one. Create, research and the MCP offer each connected archive; a sweep over it cites it. | `pnpm ops archives --json '{"connect":"https://jeralyzer.pages.dev","dryRun":true}'` |
| `create-channel` | create-channel is the New channel form: {"fields": {"name", "handling": "youtube"\|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?, "socialHandle"?, …}} with channel-config's patch keys; "slug"? (else derived from the name), "sites"? (absent = on no site). "fetchPlaylist", "fetchPostsNow" and "prioritizeDownload" are the form's checkboxes, OFF unless true; a job they start comes back as jobId(s), so --wait follows it. An X search page URL (x.com/search?q=…), or "platform": "x-search" with "xSearchQuery" (and "xSearchSince"?, "xSearchUntil"?, "xSearchWindowMonths"?, "xSearchLang"?), makes an X SEARCH channel: the matching posts from any account, walked by fetch-posts in search windows; never on a site (sites refused). | `pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}'`<br>`pnpm ops create-channel --json '{"fields":{"name":"Demo search","handling":"transcribe","url":"https://x.com/search?q=%22demo%20phrase%22"}}'` |
| `rename-channel` | rename-channel moves a channel to a new slug, as Danger → Rename does: {"slug", "newSlug"}. Refused while the channel is busy (a job, a lane unit, media in transition) or when the new slug is taken. Old links break. | `pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}'` |
| `delete-channel` | delete-channel removes a channel's whole directory, as Danger → Delete does: {"slug", "confirm"} — "confirm" must repeat the slug. Every site whose pool or cited scope names it is rewritten without it (answered as "sitesUpdated"; a site whose write is refused is a "warnings" line). No undo outside the transcripts/ repo's own history. | `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` |
@@ -143,6 +144,11 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `attach-media` | attach-media copies each held video's file out of a LOCAL archive into the saved-video store, as its source container (nothing fetched): {"slug", "source"} — an absolute path to a directory, a .zip (read in place) or a .7z. The id is the folder's trailing "(<id>)", else the file's yt-dlp suffix; "items": \[{"id", "path"}\] names exact files (path inside the source), "match" narrows the folders by regex. "createRecords": true writes a record for a video the channel does not hold; "replace": true re-attaches over a saved container. "fillDates": true gives a held record attach-media made (saved-video.json origin "local-archive") that has no upload\_date the date from its folder's description.txt, through the metadata history ("dated" in the log and summary); a record with a date, or one attach-media did not make, is never touched. "dryRun": true logs each folder's class (attach, not-held, already-attached, lost, no-media, unmatched, ambiguous, and dated) and the held videos with no media in it, and writes nothing. The log ends with a summary: line; a re-run resumes. | `pnpm ops attach-media --json '{"slug":"demo-yt","source":"/abs/YouTube.zip","match":"aaaaaaaaaaa\|bbbbbbbbbbb","fillDates":true,"dryRun":true}' --wait` |
| `import-media` | import-media makes ONE file from outside the archive a normal transcribed item: {"slug", "path"} (absolute) and which record — "url" (the source page: one metadata-only pass makes or refreshes the record, under the id the archive keys it by — Rumble's URL id), "id" (a record already here) or "meta": {"title", "date"?, "duration"?, "description"?} (by hand). ffprobe must read it; an MPEG-TS, a .part or an FLV is remuxed -c copy to mp4 (+faststart), never re-encoded. It lands in the saved-video store only when longer than a container already there ("replace": true lands it anyway), then audio.<fmt>, the archive line and media-import.json. "move": true removes the original once the copy verifies; "audio": false lands the container only; "transcribe": true queues a transcribe-one job (held by any pause; without it the transcription lane takes it by its rules); "doNotClean": true marks it, with "note". "dryRun": true says what it would do and writes nothing. A directory, a .zip or a .7z goes to attach-media ("id", "replace", "dryRun" only). | `pnpm ops import-media --json '{"slug":"demo-rumble","path":"/abs/stream.mp4.part","url":"https://rumble.com/v1abcde-title.html","move":true}' --wait`<br>`pnpm ops import-media --json '{"slug":"demo-archive","path":"/abs/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"},"dryRun":true}' --wait` |
| `record-live` | record-live records a live stream until it ends, then lands it as import-media lands a file: {"slug", "url"} (or "id" of a record here), "fromStart"? (true: yt-dlp --live-from-start — Rumble's DVR playlist holds a stream's first 4 hours), "maxHeight"? (720; null = the tallest), "separate"? (true: the video at maxHeight plus the best audio, merged — the default on YouTube, whose live streams from the start offer no single stream with both; false: one muxed stream — Rumble, Kick), "transcribe"?, "doNotClean"?, "note"?, "dryRun"?. On Rumble a refused yt-dlp falls back to the page's own playlist (a browser under xvfb, then ffmpeg). On Kick ("kick.com/<channel>" or its VOD) the ongoing VOD is polled from its first segment beside the channel's live stream. One job per stream; job cancel stops it with SIGINT and lands what it has (video and audio left unmerged are merged, -c copy); the longest part wins. Refused for a stream that is not live. "preclip": true (or {"everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine", "project"}, over settings.livePreclip) starts live-preclip once the first part begins, and implies "transcribe". | `pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'`<br>`pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}'` |
+| `local-media-configure` | local-media-configure gives a video channel a LOCAL MEDIA LIBRARY: {"slug", "sourceId", "directory"} — a stable lowercase id and an absolute directory on the editor server whose recordings stay where they are (never copied, moved or deleted). Written through the channel config; a channel that already has one is refused, and so is queued or running channel work. Playback is not set. Synchronous. | `pnpm ops local-media-configure --json '{"slug":"demo-local","sourceId":"library-1","directory":"/mnt/recordings"}'` |
+| `local-media-preview` | local-media-preview scans the library and writes nothing: {"slug"} -> {preview: {sourceToken, counts, candidates}}. Each .mp4 directly in the directory (not its subdirectories) with its same-named .info.json and .vtt (or .srt) is "new", "existing" (its record is held) or "issue" (with issues). The sourceToken and a candidate's fingerprint (or preparationFingerprint, when it has no .info.json) are what the other local-media actions take. An unreachable library is an error, never an empty preview. | `pnpm ops local-media-preview --json '{"slug":"demo-local"}'` |
+| `local-media-prepare` | local-media-prepare reviews details for a recording with no .info.json and writes nothing: {"slug", "sourceToken", "media", "sourceFingerprint" (the candidate's preparationFingerprint), "details": {"mode": "inspect" \| "manual", "title", "recordedDate"? (YYYY-MM-DD), "durationSeconds"? (manual)}} -> {review: {metadata, fingerprint}}. "inspect" measures the duration with ffprobe. Import it with local-media-import, the review's fingerprint and "preparation": {"sourceFingerprint", "details"}. | `pnpm ops local-media-prepare --json '{"slug":"demo-local","sourceToken":"<token>","media":"talk.mp4","sourceFingerprint":"<fp>","details":{"mode":"inspect","title":"A talk"}}'` |
+| `local-media-import` | local-media-import imports library recordings as one job on the channel's queue: {"slug", "sourceToken", "selected": \[{"media", "fingerprint", "preparation"?}\]} from a preview, or {"slug", "allNew": true} for every "new" candidate of a fresh preview (the first 1000 in the scan's order, with "remaining" in the answer and the log when there are more). Each record gets metadata.info.json, transcript.en.vtt and external-media.json; the video stays in the library. Every selection is re-checked first (a changed file is stale; a held record is left unchanged). Drainable between recordings; searchable after the next index build. | `pnpm ops local-media-import --json '{"slug":"demo-local","allNew":true}' --wait` |
+| `local-media-link` | local-media-link links a record the channel already holds to its library original: {"slug", "sourceToken", "media", "fingerprint", "dryRun"?} for an "existing" candidate. Only when the library's .info.json and transcript match the record's byte for byte is external-media.json written ("attached"; "already-linked"; "conflict" keeps a different one). Nothing else changes, and no playback is granted. "dryRun" answers "ready" without writing. | `pnpm ops local-media-link --json '{"slug":"demo-local","sourceToken":"<token>","media":"talk.mp4","fingerprint":"<fp>","dryRun":true}'` |
| `live-preclip` | live-preclip transcribes and mines a recording WHILE it records: {"slug", "id", "action"?: "start" (default) \| "stop" \| "status" \| "finalize"}, and for start "everyMinutes"? (10), "maxChunkMinutes"? (20), "overlapSeconds"? (15), "scan"? (true: the laugh scan), "mine"? (true), "project"? (the umtool project, <id>-live). One job per stream beside the recorder's: each tick reads only the new span of the growing file (never writing it), transcribes it on a worker lease (one at a time — a busy worker coalesces ticks), splices it into data/<id>/live-transcript.json (provisional) and grows the umtool project. Skipped and said: under 30 s new, MemAvailable under HEAVY\_MIN\_FREE\_MB (6000), the store's disk under 2 GB. When the stream lands: the clock check (flagged when the landed video's start differs), then the final transcript supersedes the live one. stop cancels the job, never the recording; status prints the state; finalize does the supersede by hand. No network request. | `pnpm ops live-preclip --json '{"slug":"demo-yt","id":"<videoId>","action":"status"}'` |
| `live-clip` | live-clip makes a shareable clip of a stream still live: {"slug", "id", "start", "end"} (seconds of the stream, at most 2:20) or "clip" (a clip id of the project), "project"? (<id>-live), "replace"?. umtool cuts the window from the recording now (the editor's /api/media/live-window: the part being written, or the saved video once landed; no network), adds the clip, and makes its short with the live transcript's captions. With --wait the result (the short's URL) is stdout. | `pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait` |
| `prepare-playable` | prepare-playable remuxes each of a channel's saved containers, losslessly (-c copy), into a browser-playable mp4 (+faststart) or webm, and makes one single-file torrent per copy, under playable/ beside the saved-video store: {"slug"}. "ids" narrows it; "trackers": \[...\] is each .torrent's announce list (none by default; the infohash does not depend on it); "root" names another playable root. A video prepared from the same source (by sha256) is skipped; "dryRun": true logs each decision. | |
@@ -173,13 +179,13 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `tag-videos` | tag-videos pins, unpins, suppresses or unsuppresses one tag on many videos in ONE write: {"tag", "op": "add" \| "remove" \| "suppress" \| "unsuppress", "videos": \[{"slug", "id"}, ...\]}. "remove" unpins only — a rule's hit survives; "suppress" rejects it. The write records who asked (ARCHILYZER\_AGENT); a big list goes in --file. | `pnpm ops tag-videos --file ids.json` |
| `keep-videos` | keep-videos sets the "Do not clean" marker on every held video of a channel whose title or description matches a download-filter pattern: {"slug", "match", "fields"?: \["title" \| "description"\], "note"?, "dryRun"?}. A match not held is reported in "notDownloaded", never created; a fresh channel wants metadata-scan first. Or by id: {"slug", "ids": \[...\], "note"?, "dryRun"?} — a held video is marked now, one not held yet (a live stream, a VOD not fetched) is PENDING and marked when its record is first written (a download, an import, a recording); "pendingAll" lists the channel's pending ids. | `pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}'` |
| `persist-videos` | persist-videos saves specific videos, across channels, to the saved-video store: {"items": \[{"slug", "id"}, ...\]}. "format": "original" \| "video\_720" (default: each channel's own). "replace": "above-height" also re-fetches a saved one whose height is unknown or above that quality (default "never"). "gapMs" pauses between downloads (default the batch gap), "minFreeMemMb" waits for that much free memory before each. "dryRun": true answers with the buckets (saved, wrongHeight, toFetch, noUrl, unknown) and starts nothing. One job per channel, on its download queue; a low disk or a rate limit stops it, and running the same body again resumes — saved videos are skipped. Over a copy already in the store (an import, an attach, a live recording or an earlier download) the download becomes the active one and the old copy is kept beside it, flagged for a check (`get saved-alternates`); nothing is deleted. | `pnpm ops persist-videos --file list.json --wait` |
-| `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?, "force"?}, ...\], "requestedBy", "manifest"?} fetches a list. A window of a recording whose availability says deleted or private is refused (unresolved) unless the item names a "webpageUrl" (a copy: find-copy) or "force": true (a stale reading; or check its availability again on the channel page's Diagnostics). "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. "storedUrl": "fallback" \| "only" (default "never") cuts a window from the media URL its record's metadata.info.json stores — Odysee's CDN file (\*.odycdn.com), the only platform allowed — when the page lookup is rate-limited ("fallback": after a 429) or without asking the page at all ("only"). A held or cooling platform still runs its windows that have one; the rest are refused or left for a later run. Same queue, same gaps; the window's provenance says source "stored-media-url". "minGapSeconds" (items only, 30–3600) sets this run's pause between two fetches in place of the platform's floor (Rumble's 120 s); still jittered up to half again. Shorter than the default risks Rumble's IP-wide Cloudflare challenge; a Retry keeps it. A window on a whole-recording platform (settings.clips .wholeRecordingPlatforms, default Rumble) is not seeked: the video is saved whole once, as "Persist source video" saves it, on the platform's download queue, and its windows are cut from it — a remote Rumble seek put the picture 1-4 s off the sound. A failed whole download fails its windows with the download's message. "wholeRecording": false fetches every window of the run by a remote seek instead. A fetched window whose picture still runs off its sound is set aside (<from>-<to>.desynced.<ext>) and fails; a held one is set aside and fetched again (check-windows). | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` |
+| `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?, "force"?}, ...\], "requestedBy", "manifest"?} fetches a list. A window of a recording whose availability says deleted or private is refused (unresolved) unless the item names a "webpageUrl" (a copy: find-copy) or "force": true (a stale reading; or check its availability again on the channel page's Diagnostics). "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. "storedUrl": "fallback" \| "only" (default "never") cuts a window from the media URL its record's metadata.info.json stores — Odysee's CDN file (\*.odycdn.com), the only platform allowed — when the page lookup is rate-limited ("fallback": after a 429) or without asking the page at all ("only"). A held or cooling platform still runs its windows that have one; the rest are refused or left for a later run. Same queue, same gaps; the window's provenance says source "stored-media-url". "minGapSeconds" (items only, 30–3600) sets this run's pause between two fetches in place of the platform's floor (Rumble's 120 s); still jittered up to half again. Shorter than the default risks Rumble's IP-wide Cloudflare challenge; a Retry keeps it. "archive" (items only) names the CONNECTED archive the items cite (settings.remoteArchives): a channel this editor does not hold is registered as a remote-only channel of it (config only, no listing; answered in "registered"; a dry run registers nothing), and a remote-only channel's page URL comes from the archive's record. Its window on a whole-recording platform is refused with the recording's estimated size unless "allowWholeRecording": true. Another origin registers nothing. A media URL's transient 403 (googlevideo's) is asked once more after a pause before it counts toward the two-403 stop. A window on a whole-recording platform (settings.clips .wholeRecordingPlatforms, default Rumble) is not seeked: the video is saved whole once, as "Persist source video" saves it, on the platform's download queue, and its windows are cut from it — a remote Rumble seek put the picture 1-4 s off the sound. A failed whole download fails its windows with the download's message. "wholeRecording": false fetches every window of the run by a remote seek instead. A fetched window whose picture still runs off its sound is set aside (<from>-<to>.desynced.<ext>) and fails; a held one is set aside and fetched again (check-windows). | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` |
| `cut-release` | cut-release turns a changelog's \[Unreleased\] into "## \[<version>\] - <date>": {"workspace": "editor" \| "export" \| "all", "version": "X.Y.Z" \| "next" \| "next-minor", "commit": boolean (default false), "date": "YYYY-MM-DD" (default today)}. "all" cuts both with ONE version and commits each ("Release <workspace> <version>") — or neither: every check runs before either file is written. Only an editor built from release 10 or later has the route (an older one answers 404); with no editor running, `archilyzer release cut` does the same locally. | `pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'` |
| `amend-release` | amend-release rewrites the LATEST release of one changelog: {"workspace": "editor" \| "export", "release": "<its version, as you saw it>", "version": "patch" \| "minor" \| "major" (a bump of the release BEFORE it) \| "X.Y.Z", "date": "YYYY-MM-DD", "fold": true (the \[Unreleased\] bullets move into it), "commit": boolean (default false)} -- or {"uncut": true} to withdraw it, its bullets back under \[Unreleased\]. An older release is refused. A version change commits as that version's release ("Release editor 0.12.0") with the amend in the body; history is never rewritten. The same amend again changes nothing. With no editor running, `archilyzer release amend` does the same locally. | `pnpm ops amend-release --json '{"workspace":"editor","release":"0.11.1","version":"minor","commit":true}'` |
| `transcribe` | transcribe runs ONE local file through a local transcription worker, as a job: {"path": "/abs/file"} (audio or video), "start"/"end" (seconds) for a window, "workerId" (a settings worker id; default: the one auto-transcribe would get), "out" (an absolute path for the result JSON, never inside the corpus). The result is {path, window, worker: {id, appId, model, device}, cues: \[{start, end, text}\], text, ...}, cue times on the file's own clock. "words": true adds words: \[{w, start, end, conf?}\] on the same clock -- from parakeet, which keeps its word timestamps; \[\] from an engine that does not. "whilePaused": true runs it during a pause-all on a worker the pause alone switched off (never one drained, degraded or disabled by hand); the pause stays on. With --wait it is printed on stdout (the response and the log go to stderr), so `pnpm ops transcribe ... --wait \| jq -r .text` works. | `pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait`<br>`pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait` |
| `tts` | tts speaks a line with a local text-to-speech engine and a STOCK voice, as a job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8, at most 20,000 characters), "engine" (kokoro \| orpheus \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...; orpheus: leah, zac, ...), "speed" (0.5-2; orpheus has none) — defaults from settings.tts (kokoro, af\_heart, 1) — and "out" (an absolute .wav path the result is copied to, never inside the corpus). The expressive tags <laugh> <chuckle> <sigh> <cough> <sniffle> <groan> <yawn> <gasp> are performed by orpheus and stripped for the others; any other <...> is refused. Numbers, years, money and times are spoken (2024: "twenty twenty-four"). The result is {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure}: wav is the 48 kHz mono WAV the editor wrote (out, or its cache), disclosure the line a narrated export carries. The same ask again is answered from the cache (cached: true, no engine run). Kokoro and orpheus need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU (a local llama-server the editor starts and stops) and waits while a transcription holds it. With --wait the result is printed on stdout. | `pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait`<br>`pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait` |
| `voice-enhance` | voice-enhance cleans a speech recording up (denoise, soften the room, level it) as a job on the `voice` queue, behind the heavy slot: {"file": "/abs/take.wav", "out": "/abs/clean.wav"} (never inside the corpus; 48 kHz mono, exactly as long as the input), "engine" (deepfilternet \| rnnoise; settings.voice), "params" (the engine's knobs: lufs, highpass, attenLimDb, postFilter, mix), "parts" (\[{file, out}\], a take recorded part by part). deepfilternet needs `archilyzer voice setup --engine deepfilternet`; rnnoise needs nothing. The result is {op, engine, wav, seconds, samples, sampleRate, engineMs, durationMs, waitedMs, gainDb, params, parts?, synthetic}; with --wait it is printed on stdout. | |
-| `voice-convert` | voice-convert keeps a recording's performance (timing, pitch contour) and swaps its timbre for a STOCK synthetic voice, as voice-enhance's job: the same body plus "voice" — "<tts engine>:<stock voice>" (orpheus:zac, orpheus:leah, kokoro:am\_michael, ...; settings.voice.convert.target); a file, a path or a recording is REFUSED as a target (no real person's voice) — and "engine" (openvoice \| seed-vc, each installed by `archilyzer voice setup --engine <id>`). The target's reference is synthesized once through the tts op and kept. The result adds target, voice, synthetic: true and the disclosure line. | |
+| `voice-convert` | voice-convert keeps a recording's performance (timing, pitch contour) and swaps its timbre for a STOCK synthetic voice, as voice-enhance's job: the same body plus "voice" — "<tts engine>:<stock voice>" (orpheus:zac, orpheus:leah, kokoro:am\_michael, ...; settings.voice.convert.target); a file, a path or a recording is REFUSED as a target (no real person's voice) — and "engine" (openvoice \| seed-vc, each installed by `archilyzer voice setup --engine <id>`). "pitch" is where the result's pitch comes from (settings.voice.convert.pitch): "target" — the stock voice's own, the read's intonation flattened to it; "source" — the pitch the take was read at (raise your voice and it rises); "contour" — the read's rises and falls, moved as a whole to the stock voice's register. "semitones" (-12 to 12) then moves a followed pitch; left out, a followed pitch takes settings.voice.convert.semitones (0 unless set). source and contour are seed-vc's, on its optional f0 model (`archilyzer voice setup --engine seed-vc --with f0`; slower, 44.1 kHz); openvoice refuses them. The target's reference is synthesized once through the tts op and kept. The result adds target, voice, pitch (semitones and f0 — the medians heard and the move applied — when followed), synthetic: true and the disclosure line. | |
| `settings` | settings patches settings.json through the editor's one writer: {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"diarization":{"cleanAfterCapture":true}}}'`<br>`pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` |
| `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | |
| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /settings) — for a jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The editor also rechecks by itself on a timer (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off; `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`). dismiss-service clears a service's cookie alert by hand: {"service"}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` |
@@ -220,6 +226,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `find-clips` | find-clips runs the clip finder's chain for ONE video as one job: {"slug", "id", "target"? (the cut's seconds), "segment"? (one umtool found, "s2"), "project"? (the umtool project a run makes), "whilePaused"?, "dryRun"?}. Persist the source video, the corpus transcript, word timings (data/<id>/words.json), the chat replay (YouTube), diarization — each step skipped when its output exists, named in the log — then umtool's clip finder (POST UMTOOL\_URL/api/report/clips {mode: "new"}), followed to the end. "whilePaused": true runs this one video past the holds: the two transcriptions during a pause-all on a worker the pause alone switched off, and its diarization in the job when the backfill lane is held. "dryRun": true answers each step's plan and starts nothing. With --wait the result — {project, url, created, segments: \[{id, from, to, why}\], steps} — is printed on stdout. | `pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","segment":"s2","whilePaused":true}' --wait` |
| `fetch-chat-backlog` | fetch-chat-backlog fetches a channel's stream chats after its downloads: {"slug", "dryRun"?, "limit"?, "queueKey"?} — every held video whose metadata says it was a stream (live\_status was\_live / post\_live) and whose chat is not here, newest first, one at a time through fetch-chat's pass with the batch downloads' gap between two, as one fetch-chat-backlog job on the platform's download queue; a raw replay already here is only normalized. It stops on a rate limit, a held platform, three failures in a row, a drain or "limit" chats; a re-run skips the chats here and the streams known to have none (chat-backlog.json), and a restart resumes it. The download lane queues it by itself (25 a run) for a channel whose "chat" is "later" once it has nothing left to download. "dryRun": true counts from the disk and starts nothing: chats, normalizeOnly, have, settled, notStreams, ids (the first 50). | `pnpm ops fetch-chat-backlog --json '{"slug":"demo-yt","dryRun":true}'` |
| `x-run` | x-run fetches several X posts channels IN SEQUENCE as ONE job on X's queue: {"channels": \[slug, ...\]} in that order, each a fetch-posts sync new of at most 200 posts ("limit": N, 1-200, caps it lower), X's queue gap (pacing.jobGapSeconds.twitter) between two channels. Before EACH channel the jar is checked again: once it is past social.x.maxCookieAgeMinutes (or the X alert is up) the run stops and the rest are DEFERRED until the next refresh. It never refreshes the jar: Refresh cookies on /settings, then {"resume": "<run id>"} runs the deferred channels (the console's Resume; a Retry of the job is the same). One run at a time; refused before a job on a stale jar (a new run's channels are kept, deferred). An interrupted run is not resumed on boot: it ends deferred. Answers {jobId, run}; get x-run follows it. The log ends with @@x-run {id, status, stopped?, counts, summary}. | `pnpm ops x-run --json '{"channels":["example-x","other-x"]}'`<br>`pnpm ops x-run --json '{"resume":"xr-01J…"}'` |
+| `lookout-run` | lookout-run lists what a saved lookout (settings.lookouts) would read: {"id", "dryRun": true, "days"?, "maxVideos"?, "until"?: "YYYY-MM-DD"}. Every video of its channels whose AIR date (release\_timestamp, else timestamp, in the lookout's timeZone — not the UTC upload\_date) falls in the window; a duplicate upload of one recording, and a stream's cut-down, folded into it (each named, with why and its score); the longest maxVideos recordings read and the rest listed as skipped for the cap; under minSeconds and no transcript yet listed too. A local media library channel or a slug this archive does not hold is named in "refused". Answers {plan: {window, counts, read, skipped, refused, estimate}}: readCalls is one per transcript chunk, priced once a run has been measured. Synchronous, reads text only, writes nothing; without "dryRun": true it is refused (the model run is not in this build). | `pnpm ops lookout-run --json '{"id":"example-week","dryRun":true}'`<br>`pnpm ops lookout-run --json '{"id":"example-week","dryRun":true,"days":3,"until":"2026-11-10"}'` |
### Usage, flags and environment
@@ -245,6 +252,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait]
pnpm ops get x-run [<run id>]
pnpm ops get cleanup <slug>
pnpm ops get speakers
+ pnpm ops get lookouts [<id>]
pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]
pnpm ops get transcript <videoId> [--slug <slug>]
pnpm ops get coverage <slug>
@@ -297,6 +305,8 @@ get saved-alternates [<slug>] lists every saved video holding two copies:
get sites lists every site: id, title, siteUrl, Pages project, audience,
listed, search, publish policy, channels, citedChannels. (`get publish`
is the status.)
+get archives lists the connected archives: id, origin, title, addedAt;
+ TRANSCRIPT_SITE_URL's, when set and not stored, is listed with fromEnv.
get workers, get auto-queue and get scheduler are /workers, the four lanes
of /operations, and /operations/sync — the payloads those pages poll.
get services is the dashboard's cookie refresh alerts: each service
@@ -336,6 +346,11 @@ get speakers is the speakers readout the lane deck and /cleanup print
noFingerprintPossible (diarized, audio already gone), per channel with
corpus-disk channels first; and the lane: armed, held, the operations
it dispatches, its order, cleanAfterCapture and requireVoiceprints.
+get lookouts [<id>] is the saved lookouts (settings.lookouts, SETTINGS.md):
+ each one's channels, days, cap and zone, its runs (transcripts/.lookouts/
+ <id>/), the latest run (when, window, model, calls, seconds, ideas), how
+ many of that run's ideas have no verdict yet, and the verdicts given.
+ Reads settings and the store only, never a channel's videos.
get cleanup <slug> is one channel's /cleanup row: what each sweep would
reclaim (they overlap — never add them), what holds the rest, and the
failed-transcriptions count. measured: false means unknown, not zero.
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -98,7 +98,11 @@ Tokens, credentials and knobs a running process reads. Most configuration is not
| `REPORTS_DIR` | `~/reports` (or the parent of `SONG_REPORTS_DIR`) | umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete. | common/lib/report/delete.ts, common/bin/case.ts, umtool (lib/paths.mjs) |
| `SONG_REPORTS_DIR` | unset | umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete and `archilyzer case` read (as umtool does). | common/lib/report/delete.ts, common/bin/case.ts, umtool (song/paths.mjs) |
| `UMTOOL_URL` | unset (no link; the MCP's `notes` off) | umtool's front door; when set, the video page links to it, its Find clips hands the recording to umtool's clip finder (the `find-clips` job posts to `/api/report/clips` with WORKER_TOKEN), and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). Unset: Find clips is disabled. | editor/app/channels/[slug]/videos/[id]/page.tsx, common/lib/umtoolUrl.ts, mcp/src/archivalTools.ts |
-| `TRANSCRIPT_SITE_URL` | — | MCP server: one published archive to read over HTTP. | mcp/src/sources.ts |
+| `TRANSCRIPT_SITE_URL` | — | MCP server: one published archive to read over HTTP. Also the default connected archive (common/lib/remoteArchives.ts): the editor, umtool and the MCP offer it as a source when settings.remoteArchives does not list it, without writing it. | mcp/src/sources.ts |
+| `ARCHILYZER_ALLOW_PRIVATE_ARCHIVES` | off | `1` lets the editor connect an archive whose host is this machine or its network (loopback, private, link-local, a `.local` name, or a name resolving to such an address), which is refused otherwise: umtool, which can connect one, is open on the LAN. TRANSCRIPT_SITE_URL's archive, and one already written in settings.json, are connected without it. The check is made once, when the archive is connected: a name re-pointed at a private address afterwards is not rechecked (the archive is still read on its own origin only). | common/controller/remoteArchives.ts |
+| `ARCHIVE_CACHE_DIR` | `.archive-cache` beside EXPORT_BUILDS_DIR | Where a remote archive's documents (corpus.json, manifests, shard pages) are kept on disk, by the archive's build: a sweep over a published archive downloads a shard once per build, not once per sweep. In a container it is on the builds volume. | common/lib/archiveCache-server.ts |
+| `ARCHIVE_CACHE_MAX_MB` | 512 | The disk cache of remote archive documents' size cap, MB: past it the least recently used are dropped. | common/lib/archiveCache-server.ts |
+| `ARCHIVE_CACHE` | on (off under node's test runner) | `0` reads remote archives without the disk cache (every read over the network, still one at a time); `1` turns it on under node's test runner, where it is off. | common/lib/archiveCache-server.ts |
| `TRANSCRIPT_HUB_URL` | — | MCP server: a hub, federating every archive it lists. | mcp/src/sources.ts |
| `TRANSCRIPT_LOCAL_DIR` | — | MCP server: a composed public dir on disk. | mcp/src/sources.ts |
| `TRANSCRIPT_PLATFORM_LINKS` | off | `1` cites platform watch pages instead of the archive's own pages. | common/lib/archive/reader-fs.ts |
diff --git a/OPERATING.md b/OPERATING.md
@@ -916,21 +916,41 @@ pnpm ops get generation-usage
pnpm archilyzer voice setup --engine deepfilternet --dry-run # what it fetches, how big; then without --dry-run
pnpm archilyzer voice setup --engine openvoice
pnpm archilyzer voice setup --engine seed-vc --check
+pnpm archilyzer voice setup --engine seed-vc --with f0 # the optional f0 model (1.49 GB): a conversion that follows your pitch
pnpm ops voice-enhance --json '{"file":"/abs/take.wav","out":"/abs/take.clean.wav"}' --wait
pnpm ops voice-convert --json '{"file":"/abs/take.wav","out":"/abs/take.zac.wav","voice":"orpheus:zac"}' --wait
umtool posts narrate <project> <item> --derive 1 --op enhance
umtool posts narrate <project> <item> --derive 2 --op convert --voice zac --engine seed-vc
+pnpm ops voice-convert --json '{"file":"/abs/take.wav","out":"/abs/take.bella.wav","voice":"kokoro:af_bella","engine":"seed-vc","pitch":"source","semitones":2}' --wait
+umtool posts narrate <project> <item> --derive 2 --op convert --voice kokoro:af_bella --engine seed-vc --pitch contour
+umtool cast set <character> --convert-engine seed-vc --convert-pitch contour --convert-semitones 2
```
- Two editor ops over a speech recording, each a job on the `voice` queue, one at a time, its engine run behind the
heavy slot with the engine's declared estimate (`settings.voice.heavyEstimateMB`): **enhance** (denoise, soften the
- room, level by one static gain) and **convert** (the timing and pitch contour kept, the timbre swapped for a STOCK
- synthetic voice). The result is a 48 kHz mono WAV exactly as long as the input; `out` is never inside the corpus.
+ room, level by one static gain) and **convert** (the timing kept, the timbre swapped for a STOCK
+ synthetic voice; the pitch as `pitch` says, below). The result is a 48 kHz mono WAV exactly as long as the input; `out` is never inside the corpus.
umtool's derived takes are the usual caller: a new take from take n, the original kept, a parted take part by part.
- **A convert target is a stock voice of our own TTS engines** — `orpheus:zac`, `orpheus:leah`, `kokoro:am_michael`,
or a bare name one engine has (`zac`). A file, a path or a recording is refused, whatever it holds: these engines
clone from seconds of audio, so no real person's voice is ever a target. Its reference (the voice reading "The North
Wind and the Sun") is asked of the `tts` op the first time and kept under `settings.voice.home/targets/`.
+- **The pitch a conversion lands on** is `pitch` (default `settings.voice.convert.pitch`, `target`):
+ - `target`: the stock voice's own pitch. The converter is given none of yours, so a read with a median of 128 Hz and
+ one of 237 Hz both come out near 197 Hz, and the range narrows — voice acting is flattened.
+ - `source`: the pitch you read at. Raise your voice for a character and the result is raised the same.
+ - `contour`: your rises and falls, moved as a whole so their median sits on the stock voice's. Read in your ordinary
+ voice and the character speaks in its own register with your intonation.
+ - `semitones` (-12 to 12) moves a followed pitch (`source`, `contour`); with `target` it is refused.
+ - `source` and `contour` are seed-vc's, on its f0-conditioned 44.1 kHz model: optional files, fetched by `voice setup
+ --engine seed-vc --with f0`. openvoice refuses them; without the files the op refuses, naming that command. An
+ install without them still converts at the target's pitch. It takes about 1.7 times as long as seed-vc's plain run (measured: 170 s against 103 s for a 7 s read on a busy machine) and
+ declares its own estimate (`settings.voice.heavyEstimateMB["seed-vc-f0"]`, 6500 MB: a take of 20 s or more peaks near 5.8 GB).
+ - The result says what was done: `pitch`, `semitones`, and `f0` — the median pitch heard in the target's reference
+ and in your take, and the whole move applied, in semitones.
+ - In umtool a character keeps its pitch in the cast (`umtool cast set <id> --convert-pitch …`), so every recording
+ made that character's lands the same way; `--pitch` / `--semitones` on `posts narrate … --recording` or `--derive`
+ are for one read.
- Engines (`settings.voice`): enhance `deepfilternet` (DeepFilterNet 3, the default) or `rnnoise` (ffmpeg's arnndn,
nothing to install); convert `openvoice` (OpenVoice v2's converter, the default) or `seed-vc` (Seed-VC v1, closer
to the target, several times slower). All on the CPU. `voice setup` says what it fetches first; `--check` lists
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -49,6 +49,7 @@ A copied example PINS every default it spells — including each lane's `autoQue
| [`attribution`](#attribution) | object — see below |
| [`archiveOrg`](#archiveorg) | object — see below |
| [`archives`](#archives) | object — see below |
+| [`remoteArchives`](#remotearchives) | `[]` |
| [`publish`](#publish) | object — see below |
| [`reportSchedule`](#reportschedule) | object — see below |
| [`seeder`](#seeder) | object — see below |
@@ -58,6 +59,7 @@ A copied example PINS every default it spells — including each lane's `autoQue
| [`clips`](#clips) | object — see below |
| [`jobs`](#jobs) | object — see below |
| [`serviceCookies`](#servicecookies) | object — see below |
+| [`lookouts`](#lookouts) | object — see below |
## `adminTitle`
@@ -908,6 +910,27 @@ Default:
}
```
+## `remoteArchives`
+
+The PUBLISHED ARCHIVES this machine reads as sources (demo epic D1, lib/remoteArchives.ts): each a site serving `/corpus.json`, connected once by its origin (the editor's /sites → Connect an archive, umtool's Source chip, or `pnpm ops archives`). Create, research and the MCP offer each one; a sweep over one cites that origin; a clip window cited from one registers a REMOTE-ONLY channel (CHANNEL.md `remoteOnly`) to fetch it. TRANSCRIPT_SITE_URL, when set and not listed here, is offered too without being written. Empty = none. See RemoteArchive.
+
+#### `remoteArchives[]`
+
+Per entry — each entry spells its own values.
+
+| Key | Description |
+|---|---|
+| `id` | A slug, unique among the connected archives: the archive's own `site.id` from its corpus.json when that is free, else one made from its host. What `pnpm ops archives` removes by. |
+| `origin` | The archive's origin: an http(s) URL with no trailing slash, query or fragment, where `/corpus.json` is served. Sweeps over it cite it (`remote:<origin>`), whatever `generation.citationOrigin` says. |
+| `title` | The archive's `site.title`, as its corpus.json said when it was connected. |
+| `addedAt` | When it was connected (ISO-8601). |
+
+Default:
+
+```json
+[]
+```
+
## `publish`
The publish LANE (release 18): a runner that, when the index is stale, updates it and then builds — and, where a site's own `publish.auto` (site.json) says so, deploys — what changed, one stage at a time on the `publish` queue. OFF by default; the manual stages (Publish now, Build, Deploy) work either way. See PublishSettings and common/publish/publishRunner.ts.
@@ -1057,8 +1080,8 @@ The voice ops (release 39): a speech recording ENHANCED (denoised, de-reverbed,
| `home` | `""` | Where `archilyzer voice setup` installs the voice engines, one directory per engine (`<home>/deepfilternet`: its binary; `<home>/openvoice`, `<home>/seed-vc`: a python venv, a pinned checkout and the weights), and where the stock targets' reference clips are kept (`<home>/targets/`). Blank = `~/.local/share/archilyzer/voice`. Absolute, or `~/`-relative. |
| `threads` | `4` | CPU threads a torch engine (openvoice, seed-vc) may use. 1–16. |
| `enhance` | object — see below | The enhance op's default engine. See VoiceEnhanceSettings (`voice.enhance` below). |
-| `convert` | object — see below | The convert op's default engine and target. See VoiceConvertSettings (`voice.convert` below). |
-| `heavyEstimateMB` | object — see below | Per engine id: the memory (MB) its job is admitted to the machine's heavy slot with (`queue-lock --heavy --estimate`) — it runs only when that much is free above the floor. The defaults are the 2026-11-03 bake-off's measured peaks plus a margin. An engine left out takes its default; 0 declares nothing (the job then runs ALONE in the slot). |
+| `convert` | object — see below | The convert op's default engine, target and pitch. See VoiceConvertSettings (`voice.convert` below). |
+| `heavyEstimateMB` | object — see below | Per engine id: the memory (MB) its job is admitted to the machine's heavy slot with (`queue-lock --heavy --estimate`) — it runs only when that much is free above the floor. The defaults are the 2026-11-03 bake-off's measured peaks plus a margin; `seed-vc-f0` is seed-vc's run when it follows the input's pitch (`pitch: source \| contour` — another, bigger model; measured 2026-11-11 over a take long enough to fill a 30 s window: 5.8 GB). An engine left out takes its default; 0 declares nothing (the job then runs ALONE in the slot). |
#### `voice.enhance`
@@ -1072,6 +1095,8 @@ The voice ops (release 39): a speech recording ENHANCED (denoised, de-reverbed,
|---|---|---|
| `engine` | `"openvoice"` | The engine `voice-convert` uses when the request names none: `openvoice` (OpenVoice v2's tone-colour converter, MIT, light) or `seed-vc` (Seed-VC v1, GPL-3.0, a closer timbre match, slower). Both run on the CPU; `archilyzer voice setup --engine <id>` installs one. An unknown id falls back to the default. |
| `target` | `"orpheus:zac"` | The stock synthetic voice a conversion lands on when the request names none: `<tts engine>:<stock voice>` (`orpheus:zac`, `orpheus:leah`, `kokoro:am_michael`, …). Never a file or a recording — no real person's voice is a target. Its reference clip is synthesized once through the `tts` op and kept under `home`. Anything else falls back to `orpheus:zac`. |
+| `pitch` | `"target"` | The pitch a conversion lands on when the request names none — for an engine that can follow the input's (seed-vc, with its optional f0 model: `archilyzer voice setup --engine seed-vc --with f0`; openvoice always lands on the target's). `target`: the stock voice's own pitch — the read's intonation is flattened to it (what there was before). `source`: the pitch the take was read at — raise your voice and the result rises. `contour`: the read's rises and falls, moved as a whole so their median sits on the stock voice's. Anything else falls back to `target`. |
+| `semitones` | `0` | Semitones a FOLLOWED pitch (`source`, `contour`) is moved by when the request names none: -12 to 12, 0 = as followed. Ignored for `target`. It applies to a request that names its own `pitch` too: `{"pitch": "source"}` with no `semitones` is moved by this many — send `"semitones": 0` for none. |
Default:
@@ -1084,13 +1109,16 @@ Default:
},
"convert": {
"engine": "openvoice",
- "target": "orpheus:zac"
+ "target": "orpheus:zac",
+ "pitch": "target",
+ "semitones": 0
},
"heavyEstimateMB": {
"deepfilternet": 400,
"rnnoise": 300,
"openvoice": 2000,
- "seed-vc": 3500
+ "seed-vc": 3500,
+ "seed-vc-f0": 6500
}
}
```
@@ -1370,3 +1398,41 @@ Default:
]
}
```
+
+## `lookouts`
+
+Saved lookouts (lane/lookout): each names channels, a number of days back and an optional prompt, and a run reads those channels' recent transcripts — by air date, duplicate uploads and stream cut-downs folded in — and answers with video ideas. OFF and empty by default; nothing a lookout writes is published. `pnpm ops get lookouts` is the readout, `pnpm ops lookout-run --json '{"id":"…","dryRun":true}'` lists what one would read. See LookoutsSettings and common/lib/lookoutSettings.ts.
+
+#### `lookouts`
+
+| Key | Default | Description |
+|---|---|---|
+| `enabled` | `false` | The lookouts' master switch. Off: no lookout runs, by hand or after a sync; a dry run (`pnpm ops lookout-run --json '{"id":"…","dryRun":true}'`) still lists what a lookout would read, and writes nothing. Default false. |
+| `afterSync` | `false` | Run each lookout after a sync of one of its channels finishes — at most once a day per lookout, never while render mode holds the machine. Not acted on before the after-sync slice lands. Default false. |
+| `items` | `[]` | The saved lookouts, one entry each (`lookouts.items[]` below). The list is replaced whole by a settings patch. Default [] — no lookout. |
+
+#### `lookouts.items[]`
+
+Per entry — each entry spells its own values.
+
+| Key | Description |
+|---|---|
+| `id` | The lookout's id: a lowercase slug (`a-z`, `0-9`, `-`, at most 64), the name its runs and verdicts are kept under (`transcripts/.lookouts/<id>/`). Omitted: made from `label`. An entry with neither is dropped, and so is a second entry with an id already used. |
+| `label` | What the lookout is called on its page. Omitted: the id. |
+| `channels` | The channel slugs it reads (`transcripts/channels/<slug>/`). A local media library channel, or a slug this archive does not hold (a channel only on a remote site), is refused by name when the lookout runs. |
+| `days` | How many days back it reads, today included, by AIR date in `timeZone` (`release_timestamp`, else `timestamp`, from the video's metadata — not yt-dlp's UTC `upload_date`). Clamped to [1, 60]; default 7. |
+| `prompt` | What the operator wants from the ideas, added to the grouping step only — the per-video reading is the same for every lookout. At most 4000 characters; default "". |
+| `maxVideos` | The most recordings one run reads, after duplicate uploads and stream cut-downs are folded in: the longest first, and every one left out listed as skipped for the cap. Clamped to [1, 500]; default 40. |
+| `minSeconds` | Videos shorter than this are not read (and are counted as skipped). Clamped to [0, 3600]; default 90. |
+| `timeZone` | The IANA time zone its days are counted in ("America/New_York"). "" = the machine's. An unknown zone is dropped to "". Default "". |
+| `siteOrigin` | The public site its links are built on ("https://example.pages.dev"), when the channels are published; "" = each video's source URL with its start second. Default "". |
+
+Default:
+
+```json
+{
+ "enabled": false,
+ "afterSync": false,
+ "items": []
+}
+```
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -1131,11 +1131,12 @@ export const COMMANDS: Command[] = [
{
path: ["voice", "setup"],
usage:
- "--engine deepfilternet|openvoice|seed-vc|rnnoise [--from <dir>] [--python <py>] [--home <dir>] [--dry-run] [--check] install a voice engine under settings.voice.home/<engine> (default ~/.local/share/archilyzer/voice/<engine>), saying first what it fetches and how big: deepfilternet is DeepFilterNet's static binary (v0.5.6, 36 MB, its GitHub release); openvoice and seed-vc are a python 3.12 venv (uv venv when uv is on PATH, else --python <py> -m venv) with torch 2.4.0's CPU wheels and their pinned packages, the engine's code at a pinned commit (git fetch --depth 1), and its weights from Hugging Face (openvoice: the v2 converter, 131 MB; seed-vc: the DiT, whisper-small, BigVGAN v2 and CAM++, 1.9 GB) — one download at a time with no retries, each verified by size and sha256; rnnoise needs nothing (ffmpeg's arnndn and the model in the repo) and setup says whether ffmpeg has it; --from <dir> takes already-downloaded files from <dir>/<name> (hard links where it can); --home installs elsewhere (then point settings.voice.home at it); --dry-run says what it would fetch and stops; --check installs nothing, lists what is missing and exits 1 when anything is",
- flags: { engine: "string", from: "string", python: "string", home: "string", "dry-run": "boolean", check: "boolean" },
+ "--engine deepfilternet|openvoice|seed-vc|rnnoise [--with f0] [--from <dir>] [--python <py>] [--home <dir>] [--dry-run] [--check] install a voice engine under settings.voice.home/<engine> (default ~/.local/share/archilyzer/voice/<engine>), saying first what it fetches and how big: deepfilternet is DeepFilterNet's static binary (v0.5.6, 36 MB, its GitHub release); openvoice and seed-vc are a python 3.12 venv (uv venv when uv is on PATH, else --python <py> -m venv) with torch 2.4.0's CPU wheels and their pinned packages, the engine's code at a pinned commit (git fetch --depth 1), and its weights from Hugging Face (openvoice: the v2 converter, 131 MB; seed-vc: the DiT, whisper-small, BigVGAN v2 and CAM++, 1.9 GB; --with f0 adds seed-vc's OPTIONAL f0-conditioned 44.1 kHz model, its BigVGAN and the RMVPE pitch tracker, 1.49 GB — what voice-convert's pitch source and contour run on, and an install without it still converts at the target's pitch) — one download at a time with no retries, each verified by size and sha256; rnnoise needs nothing (ffmpeg's arnndn and the model in the repo) and setup says whether ffmpeg has it; --from <dir> takes already-downloaded files from <dir>/<name> (hard links where it can); --home installs elsewhere (then point settings.voice.home at it); --dry-run says what it would fetch and stops; --check installs nothing, lists what is missing and exits 1 when anything is (an optional group is said, and counted only with --with)",
+ flags: { engine: "string", with: "string", from: "string", python: "string", home: "string", "dry-run": "boolean", check: "boolean" },
run: async ({ flags }) =>
(await import("./voice-setup")).main({
...(typeof flags.engine === "string" ? { engine: flags.engine } : {}),
+ ...(typeof flags.with === "string" ? { with: flags.with.split(",").map((x) => x.trim()).filter(Boolean) } : {}),
...(typeof flags.from === "string" ? { from: flags.from } : {}),
...(typeof flags.python === "string" ? { python: flags.python } : {}),
...(typeof flags.home === "string" ? { home: flags.home } : {}),
diff --git a/common/bin/compose-site.channelFacts.test.ts b/common/bin/compose-site.channelFacts.test.ts
@@ -0,0 +1,42 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { channelFactsOf } from "./compose-site";
+
+// corpus.json spec 6 (demo epic D1): each channel's platform and its page,
+// read from its config.
+test("channel facts: the configured platform, else the URL's; the URL only when public http(s)", async () => {
+ const root = mkdtempSync(path.join(tmpdir(), "compose-facts-"));
+ try {
+ const put = (slug: string, config: Record<string, unknown>) => {
+ mkdirSync(path.join(root, slug), { recursive: true });
+ writeFileSync(path.join(root, slug, "config.json"), JSON.stringify({ name: slug, handling: "youtube", ...config }));
+ };
+ put("yt", { url: "https://www.youtube.com/@alpha" });
+ put("rum", { url: "https://rumble.com/c/beta", platform: "rumble" });
+ put("mix", {}); // a curated mix: no url, no platform
+ put("odd", { url: "file:///x" });
+ // Not a channel's page to publish (review of 9fddc3bb): a playlist, a feed
+ // with a token, a fragment, credentials. The platform is still said.
+ put("playlist", { url: "https://www.youtube.com/playlist?list=PLabc" });
+ put("feed", { url: "https://feeds.example.test/rss", platform: "youtube" });
+ put("tokenfeed", { url: "https://feeds.example.test/rss?token=s3cret", platform: "youtube" });
+ put("frag", { url: "https://www.youtube.com/@gamma#videos" });
+ put("creds", { url: "https://user:pw@www.youtube.com/@delta" });
+ const facts = await channelFactsOf({ channelsDir: root } as Parameters<typeof channelFactsOf>[0], ["yt", "rum", "mix", "odd", "missing", "playlist", "feed", "tokenfeed", "frag", "creds"]);
+ assert.deepEqual(facts, {
+ yt: { platform: "youtube", url: "https://www.youtube.com/@alpha" },
+ rum: { platform: "rumble", url: "https://rumble.com/c/beta" },
+ playlist: { platform: "youtube" },
+ feed: { platform: "youtube", url: "https://feeds.example.test/rss" },
+ tokenfeed: { platform: "youtube" },
+ frag: { platform: "youtube" },
+ creds: { platform: "youtube" },
+ });
+ assert.equal(JSON.stringify(facts).includes("s3cret"), false);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
diff --git a/common/bin/compose-site.localMedia.test.ts b/common/bin/compose-site.localMedia.test.ts
@@ -0,0 +1,116 @@
+// Integration (lane/local-media re-review B1): a local recording's transcript
+// is composed only into a PRIVATE-audience site, through the REAL index build
+// and the REAL site compose, over a temp corpus — and stays out of a public
+// site's tree whatever site composed into public/ before it.
+//
+// One channel holding an online record and a local recording, on a public site
+// P and a private site V. public/transcripts/<slug> is ONE directory every site
+// composes into in turn; P must never ship the private tree V left there
+// (compose P, V, P), and V must never ship the shared tree P left (V, P, V).
+//
+// Run with: node_modules/.bin/tsx --test common/bin/compose-site.localMedia.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "compose-local-media-"));
+Object.assign(process.env, {
+ TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"),
+ SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"),
+ SITES_DIR: path.join(ROOT, "transcripts", "sites"),
+ SETTINGS_FILE: path.join(ROOT, "settings.json"),
+ EXPORT_PUBLIC_DIR: path.join(ROOT, "public"),
+ EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"),
+ EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"),
+ EDITOR_CHANGELOG_FILE: path.join(ROOT, "editor-CHANGELOG.md"),
+ EXPORT_CHANGELOG_FILE: path.join(ROOT, "export-CHANGELOG.md"),
+ CHARTS_CONFIG_FILE: path.join(ROOT, "chart-templates.json"),
+ SEARCH_ALIASES_FILE: path.join(ROOT, "transcripts", "search-aliases.json"),
+ CURATED_TAGS_FILE: path.join(ROOT, "transcripts", "tags.json"),
+ ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"),
+ ARCHILYZER_SOURCE_SCRATCH: path.join(ROOT, "source-scratch"),
+});
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { buildIndex } = await import("../controller/buildIndex");
+const { main: composeSite } = await import("./compose-site");
+const { prepareManualLocalRecordingMetadata } = await import("../lib/localRecordingMetadata");
+
+const paths = getPaths();
+const CH = "mixed";
+const LOCAL = "local-" + "7".repeat(32);
+const quiet = () => {};
+const writeJson = (file: string, value: unknown) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, JSON.stringify(value, null, 2));
+};
+
+writeJson(paths.settingsFile, {});
+writeJson(path.join(paths.channelsDir, CH, "config.json"), {
+ handling: "youtube", name: "Mixed", url: "https://www.youtube.com/@mixed/videos",
+ localMedia: { sourceId: "library-1", directory: path.join(ROOT, "library") },
+});
+const vtt = (text: string) => `WEBVTT\n\n00:00:01.000 --> 00:00:03.000\n${text}\n`;
+const online = path.join(paths.channelsDir, CH, "data", "onlinevideo");
+writeJson(path.join(online, "metadata.info.json"), {
+ id: "onlinevideo", title: "Online", upload_date: "20260601", duration: 120,
+ webpage_url: "https://www.youtube.com/watch?v=onlinevideo", extractor_key: "Youtube",
+});
+writeFileSync(path.join(online, "transcript.en.vtt"), vtt("an online cue"));
+const local = path.join(paths.channelsDir, CH, "data", LOCAL);
+writeJson(path.join(local, "metadata.info.json"), prepareManualLocalRecordingMetadata({ id: LOCAL, filename: "talk.mp4", title: "A private talk" }));
+writeFileSync(path.join(local, "transcript.en.vtt"), vtt("a private local cue"));
+const site = (siteId: string, extra: Record<string, unknown> = {}) =>
+ writeJson(path.join(paths.sitesDir, siteId, "site.json"), {
+ siteId, siteTitle: siteId, siteDescription: "fixture", headerTitle: siteId, homeTagline: "",
+ socialLinks: [], groups: [{ id: "default", name: "All channels", selectedByDefault: true }],
+ defaultGroupId: "default", channels: [{ slug: CH, groupId: "default" }],
+ siteUrl: `https://${siteId}.example.test`, archives: false, ...extra,
+ });
+site("pub");
+site("priv", { audience: "private" });
+await buildIndex({ paths, onLog: quiet });
+
+// Every file under public/transcripts/<CH>, read whole: a local id or its cue
+// anywhere in it (a page, the manifest's slugToPage) is a leak.
+function transcriptTree(): string {
+ const dir = path.join(paths.exportTranscriptsDir, CH);
+ return readdirSync(dir).map((f) => readFileSync(path.join(dir, f), "utf8")).join("\n");
+}
+async function compose(siteId: string): Promise<string> {
+ const log = console.log;
+ console.log = quiet;
+ try {
+ await composeSite({ siteId, paths });
+ } finally {
+ console.log = log;
+ }
+ return transcriptTree();
+}
+const assertPublic = (tree: string, when: string) => {
+ assert.doesNotMatch(tree, new RegExp(LOCAL), `${when}: no local id in the public site's tree`);
+ assert.doesNotMatch(tree, /a private local cue/, `${when}: no local cue`);
+ assert.match(tree, /an online cue/, `${when}: the online record is there`);
+};
+const assertPrivate = (tree: string, when: string) => {
+ assert.match(tree, new RegExp(LOCAL), `${when}: the private site carries the local recording`);
+ assert.match(tree, /a private local cue/, `${when}: and its cue`);
+ assert.match(tree, /an online cue/, `${when}: and the online record`);
+};
+
+test("compose P, V, P: the public site never ships the private tree the private site left", async () => {
+ assertPublic(await compose("pub"), "P first");
+ assertPrivate(await compose("priv"), "then V");
+ assertPublic(await compose("pub"), "P again, shared tree unchanged");
+ assertPublic(await compose("pub"), "P a third time, its own compose last");
+});
+
+test("compose V, P, V: the private site never ships the shared tree the public site left", async () => {
+ assertPrivate(await compose("priv"), "V first");
+ assertPublic(await compose("pub"), "then P");
+ assertPrivate(await compose("priv"), "V again, private tree unchanged");
+});
diff --git a/common/bin/compose-site.ts b/common/bin/compose-site.ts
@@ -21,10 +21,12 @@
// reports, site.json (no channels) and corpus.json (`site.scope: "cited"`) —
// see composeCitedSite.
+import { writeJsonAtomic } from "../lib/jsonFile-server";
+import { isLocalRecord } from "../lib/localMedia";
import path from "node:path";
import { cp, link, mkdir, rm, readdir, access, readFile, writeFile, stat, rename } from "node:fs/promises";
import type { Dirent } from "node:fs";
-import { getPaths, type Paths } from "../lib/paths";
+import { getPaths, sharedPrivateTranscriptsDir, type Paths } from "../lib/paths";
import { dirSignature } from "../lib/dirSignature";
import { getSite, resolveSocialLinks, resolveHubUrl, type Site } from "../lib/site";
import { getSettings } from "../lib/settings";
@@ -69,6 +71,7 @@ import {
type ArchiveManifestEntry,
} from "../lib/archiveOptions";
import { readChannelConfig } from "../controller/channels";
+import { detectPlatform } from "../lib/platform";
import { isWaybackPagesChannel } from "../lib/waybackPages/config";
import { builtSiteIdIn } from "../lib/builtExport";
import { publishedMemberSlugs } from "../lib/postsVisibility";
@@ -218,6 +221,42 @@ async function composeCitedSite(
// environment variable the build passes it to compose as.
export const ALLOW_MISSING_MEDIA_ENV = "REPORTS_ALLOW_MISSING_MEDIA";
+// corpus.json's per-channel `platform` and `url` (spec 6): the configured
+// platform, else the one its URL names; the URL only when it is a plain public
+// http(s) page — NO query, fragment or userinfo (publicChannelUrl): a config's
+// url may be a playlist or a single video (`?list=`, `?v=`), or a feed with a
+// token in its query, and none of that is a channel's page to publish. The
+// platform is kept either way. Read from each channel's config.json; an
+// unreadable one is simply unknown.
+/** A config url fit to publish as a channel's page: http(s), no userinfo, query or fragment; else undefined. */
+export function publicChannelUrl(raw: string): string | undefined {
+ let u: URL;
+ try {
+ u = new URL(raw);
+ } catch {
+ return undefined;
+ }
+ if (u.protocol !== "https:" && u.protocol !== "http:") return undefined;
+ if (u.username || u.password || u.search || u.hash || raw.includes("?") || raw.includes("#")) return undefined;
+ return raw;
+}
+
+export async function channelFactsOf(
+ paths: Parameters<typeof readChannelConfig>[0],
+ slugs: readonly string[],
+): Promise<Record<string, { platform?: string; url?: string }>> {
+ const out: Record<string, { platform?: string; url?: string }> = {};
+ for (const slug of slugs) {
+ const config = await readChannelConfig(paths, slug).catch(() => null);
+ if (!config) continue;
+ const raw = typeof config.url === "string" ? config.url.trim() : "";
+ const url = publicChannelUrl(raw);
+ const platform = config.platform ?? detectPlatform(raw || undefined) ?? undefined;
+ if (platform || url) out[slug] = { ...(platform ? { platform } : {}), ...(url ? { url } : {}) };
+ }
+ return out;
+}
+
// Emit the AI-discovery surface — a small FIXED set of site-root files
// (llms.txt, corpus.json, robots.txt, sitemap.xml). These document how to
// navigate the already-served paginated shards; they never enumerate per-video
@@ -288,6 +327,11 @@ export async function emitAiFiles(
if (config && isWaybackPagesChannel(config)) channelKinds[slug] = "wayback-pages";
}
+ // Where each channel is (spec 6, demo epic D1): its platform and its page
+ // there, from its config — what a machine with no copy of the channel needs
+ // to fetch a cited moment's media. A channel with neither says nothing.
+ const channelFacts = await channelFactsOf(paths, descriptor.channels.map((c) => c.slug));
+
// Whether this site published a curated vocabulary. Presence of the file is
// the fact — it was written (or removed) just above, by the same rule that
// decides whether any tag means anything on this site.
@@ -304,6 +348,7 @@ export async function emitAiFiles(
private: isPrivateSite(site),
reportCount: composed.reports.length,
cited: isCitedSite(site),
+ channelFacts,
});
await writePublicFile(
path.join(paths.exportPublicDir, "corpus.json"),
@@ -727,6 +772,33 @@ async function writeComposeCache(p: string, cache: ComposeCache): Promise<void>
// under a constant signature and the contract stays unconditional.
export const MANIFEST_ONLY_SIGNATURE = "manifest-only";
+// A ledger entry for a destination being copied right now (reconcileChannelTree).
+const COPY_IN_PROGRESS = "copy in progress";
+
+// The ledger of what each public/<tree>/<slug> was last copied from: beside the
+// index, never in public/ (it names staging paths).
+export function composeTreesLedgerPath(paths: Pick<Paths, "exportIndexDir">): string {
+ return path.join(paths.exportIndexDir, "compose-trees.json");
+}
+
+// WHICH TRANSCRIPT TREE A SITE COPIES (lane/local-media slice 1 ruling). The
+// shared tree leaves local recordings out; a channel that holds one also has a
+// full tree under sharedPrivateTranscriptsDir. A PRIVATE-audience site copies
+// that one where it exists; every other site, and every channel without one,
+// copies the shared tree. Fail-closed: a public site never reads the private root.
+export function transcriptsSourceFor(
+ paths: Pick<Paths, "exportSharedDir" | "exportSharedTranscriptsDir">,
+ privateSite: boolean,
+): (slug: string) => Promise<string> {
+ return async (slug) => {
+ if (privateSite) {
+ const full = path.join(sharedPrivateTranscriptsDir(paths), slug);
+ if (await exists(full)) return full;
+ }
+ return path.join(paths.exportSharedTranscriptsDir, slug);
+ };
+}
+
export async function reconcileChannelTree(
kind: string,
srcRoot: string,
@@ -734,16 +806,42 @@ export async function reconcileChannelTree(
memberSlugs: string[],
prev: Record<string, string>,
log: (m: string) => void,
+ opts: {
+ // Where one member's tree comes from, when not `srcRoot/<slug>`: the
+ // transcripts of a private-audience site (transcriptsSourceFor).
+ srcFor?: (slug: string) => Promise<string>;
+ // WHAT EACH DESTINATION HOLDS (lane/local-media re-review B1). public/<tree>
+ // is ONE directory every site composes into in turn, while `prev` is THIS
+ // site's cache: once two sites copy a channel from different sources (the
+ // shared tree, a private site's full tree), `prev` cannot say what another
+ // site left there — a public site would trust, and ship, the private tree.
+ // The ledger records, per destination, the source dir and signature it was
+ // last copied from (outside public/, never published); a destination is
+ // trusted only when that record matches this compose's source. A copy in
+ // progress is recorded as such first, so a cut-short copy is never trusted.
+ // A destination with no record was copied before the ledger existed, from
+ // the shared tree (no other source existed): `prev` decides, and only when
+ // this compose's source is the shared tree too.
+ ledgerFile?: string;
+ } = {},
): Promise<Record<string, string>> {
+ const { srcFor, ledgerFile } = opts;
// A linked tree (a worktree's public/<tree> → the primary's) becomes this
// checkout's own before anything is copied into or pruned from it.
await ownDir(destRoot);
+ const ledger: Record<string, string> | null = ledgerFile
+ ? await readFile(ledgerFile, "utf8").then((raw) => JSON.parse(raw) as Record<string, string>, () => ({}))
+ : null;
+ const persistLedger = async () => {
+ if (ledgerFile && ledger) await writeJsonAtomic(ledgerFile, ledger);
+ };
const next: Record<string, string> = {};
const memberSet = new Set(memberSlugs);
let copied = 0;
let skipped = 0;
for (const slug of memberSlugs) {
- const src = path.join(srcRoot, slug);
+ const sharedSrc = path.join(srcRoot, slug);
+ const src = srcFor ? await srcFor(slug) : sharedSrc;
const dest = path.join(destRoot, slug);
// Exclude the per-channel manifest.json — its `generatedAt` churns every
// mutation build; the page files capture real content changes.
@@ -754,15 +852,27 @@ export async function reconcileChannelTree(
if (sig === "") {
// No source for this member — ensure no stale dest survives.
await rm(dest, { recursive: true, force: true });
+ if (ledger) delete ledger[dest];
continue;
}
- if (prev[slug] === sig && (await exists(dest))) {
+ const copiedFrom = `${src}\0${sig}`;
+ const trusted =
+ (await exists(dest)) &&
+ (ledger && dest in ledger
+ ? ledger[dest] === copiedFrom
+ : prev[slug] === sig && src === sharedSrc);
+ if (trusted) {
next[slug] = sig;
skipped++;
continue;
}
+ if (ledger) {
+ ledger[dest] = COPY_IN_PROGRESS;
+ await persistLedger();
+ }
await rm(dest, { recursive: true, force: true });
await cp(src, dest, { recursive: true });
+ if (ledger) ledger[dest] = copiedFrom;
next[slug] = sig;
copied++;
}
@@ -777,8 +887,10 @@ export async function reconcileChannelTree(
for (const e of entries) {
if (e.isDirectory() && !memberSet.has(e.name)) {
await rm(path.join(destRoot, e.name), { recursive: true, force: true });
+ if (ledger) delete ledger[path.join(destRoot, e.name)];
}
}
+ await persistLedger();
log(`[compose] ${kind}: ${copied} copied, ${skipped} unchanged.`);
return next;
}
@@ -843,9 +955,12 @@ export async function main(
// last (it is written below, every compose); another name, or none, and the
// site's own stages (summaries, stats, duplicates) are composed afresh.
//
- // The per-channel tree signatures stay trusted: those trees are copies of
- // the SHARED trees, the same bytes whichever site copied them, and a
- // channel another site pruned is re-copied because its directory is gone.
+ // The per-channel trees are trusted by what each destination was last
+ // copied FROM (reconcileChannelTree's ledger), not by this site's cache: a
+ // private-audience site copies a channel's FULL transcript tree where a
+ // public one copies the shared tree (transcriptsSourceFor), so the same
+ // destination can hold either; a channel another site pruned is re-copied
+ // because its directory is gone.
const cachePath = composeCachePath(paths, siteId);
const lastComposed = builtSiteIdIn(paths.exportPublicDir);
const cached = await readComposeCache(cachePath);
@@ -912,6 +1027,7 @@ export async function main(
memberSlugs,
cache.transcripts,
console.log,
+ { srcFor: transcriptsSourceFor(paths, isPrivateSite(site)), ledgerFile: composeTreesLedgerPath(paths) },
);
cache.subs = await reconcileChannelTree(
"subs",
@@ -920,6 +1036,7 @@ export async function main(
memberSlugs,
cache.subs,
console.log,
+ { ledgerFile: composeTreesLedgerPath(paths) },
);
// The social-post corpus: same shared-tree shape, same incremental reconcile.
// Only social member channels have a source dir; reconcileChannelTree treats a
@@ -940,6 +1057,7 @@ export async function main(
postsListed ? memberSlugs.filter((slug) => postsListed.has(slug)) : memberSlugs,
cache.posts ?? {},
console.log,
+ { ledgerFile: composeTreesLedgerPath(paths) },
);
// The AI-digest corpus: same shared-tree shape again. Sparse — only channels
// with at least one digest have a source dir, and reconcileChannelTree treats
@@ -951,6 +1069,7 @@ export async function main(
memberSlugs,
cache.digests ?? {},
console.log,
+ { ledgerFile: composeTreesLedgerPath(paths) },
);
// Subs also carries a per-site manifest.json (tiny — copied every build).
const subsManifestSrc = path.join(
@@ -1169,7 +1288,9 @@ export async function main(
}
const clusters = report.clusters
.filter((c) => clusterIsPublishable(c, dupOverrides))
- .map((c) => filterClusterToChannels(c, memberSet))
+ .map((c) => filterClusterToChannels(c, memberSet,
+ // A local recording only in a private-audience site's duplicates.
+ isPrivateSite(site) ? undefined : (r) => !isLocalRecord(r)))
.filter((c): c is NonNullable<typeof c> => c !== null);
if (clusters.length > 0) {
const filtered: DuplicateReport = {
diff --git a/common/bin/reports-delete.ts b/common/bin/reports-delete.ts
@@ -18,6 +18,7 @@
// refused, or a path could not be removed; 2 for usage, or no such article or
// iteration.
+import { projectsRootFrom } from "../lib/projectsRoot.mjs";
import os from "node:os";
import path from "node:path";
import type { GenerationSettings } from "../lib/generationSettings";
@@ -103,7 +104,7 @@ const expandHome = (p: string) => (p === "~" ? os.homedir() : p.startsWith("~/")
// settings.generation.projectsRoot, `~` expanded; blank = ~/reports/articles
// (controller/reportDraft.ts projectsRootOf, which a bin does not import).
export const projectsRootOf = (gen: Pick<GenerationSettings, "projectsRoot">): string =>
- gen.projectsRoot ? expandHome(gen.projectsRoot) : path.join(os.homedir(), "reports", "articles");
+ projectsRootFrom(gen.projectsRoot);
// The CLI row's options, from the flags and the settings.
export async function deleteRow(
diff --git a/common/bin/reports-import-local-runs.ts b/common/bin/reports-import-local-runs.ts
@@ -34,6 +34,7 @@
// Exit 0 when every run is importable (dry run) or imported (apply), or was
// imported before; 1 when any is refused or fails; 2 for a usage error.
+import { projectsRootFrom } from "../lib/projectsRoot.mjs";
import { cp, lstat, mkdir, readdir, readFile, rename, rm, stat } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
@@ -761,7 +762,7 @@ export function defaultGenerationWriter(env: NodeJS.ProcessEnv = process.env, fe
const expandHome = (p: string) => (p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p);
// settings.generation.projectsRoot, `~` expanded; blank = ~/reports/articles
// (controller/reportDraft.ts projectsRootOf, which a bin does not import).
-const projectsRootOf = (gen: GenerationSettings) => (gen.projectsRoot ? expandHome(gen.projectsRoot) : path.join(os.homedir(), "reports", "articles"));
+const projectsRootOf = (gen: GenerationSettings) => (projectsRootFrom(gen.projectsRoot));
// The CLI row's options, from the flags and the settings.
export async function importRow(flags: { apply?: boolean; runs?: string; only?: string; "move-projects"?: boolean; generation?: string }): Promise<number> {
diff --git a/common/bin/voice-setup.test.ts b/common/bin/voice-setup.test.ts
@@ -1,10 +1,11 @@
import { test, after } from "node:test";
import assert from "node:assert/strict";
-import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
+import { mkdtemp, mkdir, open, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { main, voiceSetupPlan } from "./voice-setup";
-import { VOICE_ENGINES } from "../lib/voiceApps";
+import { SEEDVC_F0_FILES, SEEDVC_FILES, VOICE_ENGINES } from "../lib/voiceApps";
+import { VOICE_CODE_MARKER, voiceGroupState, voiceInstallState } from "../lib/voiceInstall";
// Run with:
// pnpm --filter yt-dlp-transcript-common exec tsx --test bin/voice-setup.test.ts
@@ -32,7 +33,16 @@ test("the plan names every file, its size and its source, and the total", () =>
assert.ok(plan.some((l) => /a python 3\.12 venv \(uv\), with: torch==2\.4\.0\+cpu/.test(l)));
assert.ok(plan.some((l) => /the code: https:\/\/github\.com\/Plachtaa\/seed-vc at 51383efd/.test(l)));
assert.ok(plan.some((l) => /whisper-small\/model\.safetensors — 967\.0 MB from https:\/\/huggingface\.co\/openai\/whisper-small\/resolve\/973afd24/.test(l)));
- assert.match(plan.at(-1)!, /files: 1\.88 GB/);
+ // The optional f0 group is listed after the total, not fetched or counted…
+ const total = plan.findIndex((l) => /^ {2}files: /.test(l));
+ assert.match(plan[total], /files: 1\.88 GB/);
+ assert.match(plan[total + 1], /optional, not fetched without `--with f0` — the f0-conditioned 44\.1 kHz model/);
+ assert.ok(plan.slice(total).some((l) => /rmvpe\.pt — 181\.2 MB from https:\/\/huggingface\.co\/lj1995\/VoiceConversionWebUI\/resolve\/e6d0c1a1/.test(l)));
+ assert.match(plan.at(-1)!, /1\.49 GB more/);
+ // …and with --with f0 it is part of what is fetched.
+ const withF0 = voiceSetupPlan(VOICE_ENGINES["seed-vc"], ["f0"]);
+ assert.ok(withF0.some((l) => /bigvgan-44k\/bigvgan_generator\.pt — 489\.0 MB from https:\/\/huggingface\.co\/nvidia\/bigvgan_v2_44khz_128band_512x\/resolve\/95a9d1dc/.test(l)));
+ assert.match(withF0.at(-1)!, /files: 3\.38 GB/);
assert.match(voiceSetupPlan(VOICE_ENGINES.deepfilternet).at(-1)!, /files: 36\.4 MB$/);
assert.match(voiceSetupPlan(VOICE_ENGINES.rnnoise)[0], /nothing to download/);
});
@@ -55,6 +65,58 @@ test("--check over an empty home lists what is missing and exits 1", async () =>
assert.match(c.lines.join("\n"), /DeepFilterNet 3 at .*empty\/deepfilternet — missing:\n {2}- deep-filter\nRun `archilyzer voice setup --engine deepfilternet`/);
});
+async function sparse(dir: string, files: readonly { name: string; bytes: number }[]) {
+ for (const f of files) {
+ const p = path.join(dir, f.name);
+ await mkdir(path.dirname(p), { recursive: true });
+ const fh = await open(p, "w");
+ await fh.truncate(f.bytes);
+ await fh.close();
+ }
+}
+
+test("seed-vc's f0 files are optional: an install without them checks out, --with f0 counts them", async () => {
+ const home = path.join(ROOT, "seed-home");
+ const dir = path.join(home, "seed-vc");
+ const seed = VOICE_ENGINES["seed-vc"];
+ assert.ok(seed.setup.kind === "python-venv");
+ if (seed.setup.kind !== "python-venv") return;
+ await mkdir(path.join(dir, "venv", "bin"), { recursive: true });
+ await writeFile(path.join(dir, "venv", "bin", "python"), "");
+ await mkdir(path.join(dir, "code"), { recursive: true });
+ await writeFile(path.join(dir, "code", VOICE_CODE_MARKER), `${seed.setup.code.commit}\n`);
+ await sparse(dir, SEEDVC_FILES);
+ // The install made before the group existed is installed; the group is said.
+ const state = voiceInstallState(seed, { home, voiceModelsDir: ROOT });
+ assert.equal(state.installed, true);
+ assert.deepEqual(state.optional.map((g) => [g.id, g.installed, g.missing.length]), [["f0", false, SEEDVC_F0_FILES.length]]);
+ // --check (the venv here is a stub, so the import fails: read the lines about the group).
+ const plain = capture();
+ await main({ engine: "seed-vc", check: true, home, log: plain.log });
+ assert.ok(plain.lines.some((l) => /optional f0 \(.*follows the input's pitch.*\): not installed — `archilyzer voice setup --engine seed-vc --with f0` fetches it/.test(l)), plain.lines.join("\n"));
+ assert.equal(plain.lines.some((l) => /- rmvpe\.pt/.test(l)), false);
+ const asked = capture();
+ assert.equal(await main({ engine: "seed-vc", check: true, with: ["f0"], home, log: asked.log }), 1);
+ assert.ok(asked.lines.some((l) => /^ {2}- rmvpe\.pt$/.test(l)));
+ assert.match(asked.lines.at(-1)!, /Run `archilyzer voice setup --engine seed-vc --with f0`/);
+ // There: said as installed.
+ await sparse(dir, SEEDVC_F0_FILES);
+ assert.equal(voiceGroupState(seed, "f0", { home })!.installed, true);
+ const there = capture();
+ await main({ engine: "seed-vc", check: true, with: ["f0"], home, log: there.log });
+ assert.ok(there.lines.some((l) => /with f0 \(.*\): installed/.test(l)));
+ assert.equal(there.lines.some((l) => /rmvpe/.test(l)), false);
+ // A group the engine does not have.
+ const no = capture();
+ assert.equal(await main({ engine: "seed-vc", with: ["f1"], dryRun: true, home, log: no.log }), 2);
+ assert.match(no.lines[0], /seed-vc has no optional group "f1" — --with is one of f0/);
+ assert.equal(await main({ engine: "openvoice", with: ["f0"], dryRun: true, home, log: no.log }), 2);
+ // --dry-run --with f0 lists them as fetched.
+ const dry = capture();
+ assert.equal(await main({ engine: "seed-vc", with: ["f0"], dryRun: true, home, log: dry.log }), 0);
+ assert.ok(dry.lines.some((l) => /with f0 — the f0-conditioned/.test(l)));
+});
+
test("an engine is required, by its id", async () => {
const c = capture();
assert.equal(await main({ log: c.log }), 2);
diff --git a/common/bin/voice-setup.ts b/common/bin/voice-setup.ts
@@ -15,6 +15,11 @@
// code/ Plachtaa/seed-vc at a pinned commit
// … the DiT (440 MB), whisper-small (967
// MB), BigVGAN v2 (449 MB), CAM++ (28 MB)
+// … (--with f0) OPTIONAL: the f0-conditioned 44.1 kHz
+// DiT (821 MB), its BigVGAN (489 MB) and
+// RMVPE (181 MB) — what `pitch: source |
+// contour` runs on; an install without
+// them converts at the target's pitch
// install.json what was installed, and when
// rnnoise has nothing to install (ffmpeg, and the model in the repo): setup
// says whether ffmpeg has `arnndn`.
@@ -31,7 +36,9 @@
//
// `--check` installs nothing: it lists what is missing (the venv, the package
// importing, the checkout at its commit, each file at its size) and exits 1
-// when anything is.
+// when anything is. An optional group that is not there is SAID (with the
+// command that fetches it) and does not fail the check, unless it was asked
+// for (`--check --with f0`).
//
// Scratch (pip's build dirs) goes to `<install dir>/.tmp`, never the OS temp
// dir: it may be a small RAM tmpfs.
@@ -48,6 +55,7 @@ import {
voiceInstallDir,
voiceVenvPython,
type VoiceEngine,
+ type VoiceFileGroup,
} from "../lib/voiceApps";
import { VOICE_CODE_MARKER, voiceInstallState } from "../lib/voiceInstall";
import { DEFAULT_VOICE_SETTINGS, resolveVoiceHome } from "../lib/voiceSettings";
@@ -58,6 +66,8 @@ import { adoptModelFile, downloadModelFile, verifyModelFile } from "./tts-setup"
export type VoiceSetupOptions = {
engine?: string;
from?: string;
+ // Optional file groups to install too (seed-vc: "f0").
+ with?: string[];
python?: string;
check?: boolean;
dryRun?: boolean;
@@ -76,8 +86,22 @@ function mb(n: number): string {
return n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)} MB` : `${(n / 1000).toFixed(1)} kB`;
}
-/** What setup fetches for an engine, in words: one line each, then the total. */
-export function voiceSetupPlan(engine: VoiceEngine): string[] {
+/** The engine's optional groups by these ids, or the ids it does not have. */
+export function pickVoiceGroups(engine: VoiceEngine, ids: readonly string[]): { groups: VoiceFileGroup[]; unknown: string[]; known: string[] } {
+ const all = engine.setup.kind === "python-venv" ? engine.setup.optional ?? [] : [];
+ return {
+ groups: all.filter((g) => ids.includes(g.id)),
+ unknown: ids.filter((id) => !all.some((g) => g.id === id)),
+ known: all.map((g) => g.id),
+ };
+}
+
+/**
+ * What setup fetches for an engine, in words: one line each, then the total.
+ * The optional groups asked for (`withGroups`) are fetched and counted; the
+ * others are listed after, as what `--with <id>` would add.
+ */
+export function voiceSetupPlan(engine: VoiceEngine, withGroups: readonly string[] = []): string[] {
const s = engine.setup;
if (s.kind === "bundled") return [`${engine.label}: nothing to download (${s.hint})`];
const lines: string[] = [];
@@ -90,7 +114,20 @@ export function voiceSetupPlan(engine: VoiceEngine): string[] {
lines.push(` ${f.name} — ${mb(f.bytes)} from ${f.url}`);
total += f.bytes;
}
+ const optional = s.kind === "python-venv" ? s.optional ?? [] : [];
+ for (const g of optional.filter((x) => withGroups.includes(x.id))) {
+ lines.push(` with ${g.id} — ${g.label}:`);
+ for (const f of g.files) {
+ lines.push(` ${f.name} — ${mb(f.bytes)} from ${f.url}`);
+ total += f.bytes;
+ }
+ }
lines.push(` files: ${mb(total)}${s.kind === "python-venv" ? " (plus the packages: torch's CPU wheels are ~200 MB)" : ""}`);
+ for (const g of optional.filter((x) => !withGroups.includes(x.id))) {
+ lines.push(` optional, not fetched without \`--with ${g.id}\` — ${g.label}:`);
+ for (const f of g.files) lines.push(` ${f.name} — ${mb(f.bytes)} from ${f.url}`);
+ lines.push(` ${mb(g.files.reduce((n, f) => n + f.bytes, 0))} more`);
+ }
return lines;
}
@@ -138,24 +175,43 @@ export async function main(opts: VoiceSetupOptions = {}): Promise<number> {
}
const dir = voiceInstallDir(home, engine);
+ const picked = pickVoiceGroups(engine, opts.with ?? []);
+ if (picked.unknown.length) {
+ log(`voice setup: ${engine.id} has no optional group "${picked.unknown.join('", "')}" — ${picked.known.length ? `--with is one of ${picked.known.join(", ")}` : "it has none"}`);
+ return 2;
+ }
+ const withIds = picked.groups.map((g) => g.id);
if (opts.check) {
const state = voiceInstallState(engine, { home, voiceModelsDir: paths.voiceModelsDir });
const missing = [...state.missing];
if (setup.kind === "python-venv" && !missing.some((m) => m.startsWith("the python venv"))) {
if ((await importsAt(voiceVenvPython(dir), setup.importName)) === null) missing.push(`${setup.importName} does not import in the venv`);
}
+ // A group asked for is part of the check; one not asked for is only said.
+ for (const g of state.optional) if (withIds.includes(g.id)) missing.push(...g.missing);
+ const said = () => {
+ for (const g of state.optional) {
+ if (g.installed) log(` with ${g.id} (${g.label}): installed`);
+ else if (!withIds.includes(g.id)) {
+ log(` optional ${g.id} (${g.label}): not installed — \`archilyzer voice setup --engine ${engine.id} --with ${g.id}\` fetches it`);
+ }
+ }
+ };
+ const withArg = withIds.map((id) => ` --with ${id}`).join("");
if (missing.length === 0) {
log(`${engine.label}: installed at ${dir}`);
+ said();
return 0;
}
log(`${engine.label} at ${dir} — missing:`);
for (const m of missing) log(` - ${m}`);
- log(`Run \`archilyzer voice setup --engine ${engine.id}\` to install it.`);
+ said();
+ log(`Run \`archilyzer voice setup --engine ${engine.id}${withArg}\` to install it.`);
return 1;
}
log(`${opts.dryRun ? "Would install" : "Installing"} ${engine.label} (${engine.license}) at ${dir}:`);
- for (const l of voiceSetupPlan(engine)) log(l);
+ for (const l of voiceSetupPlan(engine, withIds)) log(l);
if (opts.dryRun) return 0;
const scratch = path.join(dir, ".tmp");
@@ -215,7 +271,7 @@ export async function main(opts: VoiceSetupOptions = {}): Promise<number> {
}
}
// 4. The files, one at a time.
- for (const spec of setup.files) {
+ for (const spec of [...setup.files, ...picked.groups.flatMap((g) => g.files)]) {
const target = path.join(dir, spec.name);
await mkdir(path.dirname(target), { recursive: true });
if ((await verifyModelFile(target, spec)) === "ok") {
@@ -238,10 +294,14 @@ export async function main(opts: VoiceSetupOptions = {}): Promise<number> {
return 1;
}
const state = voiceInstallState(engine, { home, voiceModelsDir: paths.voiceModelsDir });
- if (!state.installed) {
- log(`voice setup: still missing ${state.missing.join("; ")}`);
+ const stillMissing = [...state.missing, ...state.optional.filter((g) => withIds.includes(g.id)).flatMap((g) => g.missing)];
+ if (stillMissing.length) {
+ log(`voice setup: still missing ${stillMissing.join("; ")}`);
return 1;
}
+ // What is there now, whichever run fetched it.
+ const groupsThere = picked.known.filter((id) => state.optional.find((g) => g.id === id)?.installed);
+ const optionalGroups = pickVoiceGroups(engine, groupsThere).groups;
await writeJsonAtomic(
path.join(dir, "install.json"),
{
@@ -250,10 +310,13 @@ export async function main(opts: VoiceSetupOptions = {}): Promise<number> {
license: engine.license,
...(setup.kind === "python-venv" ? { packages: setup.packages, code: setup.code } : {}),
files: setup.files.map((f) => ({ name: f.name, bytes: f.bytes, sha256: f.sha256, url: f.url })),
+ ...(optionalGroups.length
+ ? { optional: optionalGroups.map((g) => ({ id: g.id, files: g.files.map((f) => ({ name: f.name, bytes: f.bytes, sha256: f.sha256, url: f.url })) })) }
+ : {}),
installedAt: new Date().toISOString(),
},
{ indent: 2 },
);
- log(`${engine.label} installed: ${dir}`);
+ log(`${engine.label} installed: ${dir}${optionalGroups.length ? ` (with ${optionalGroups.map((g) => g.id).join(", ")})` : ""}`);
return 0;
}
diff --git a/common/components/SearchSessionContext.tsx b/common/components/SearchSessionContext.tsx
@@ -835,6 +835,8 @@ function useSearchSessionState() {
const passesFilter = useMemo(() => {
return (t: Summary) => {
if (committedChannels.has(channelKeyOf(t))) return false;
+ // Undated is outside any bounded range (lib/search/evalTree.ts).
+ if ((committedDateFrom || committedDateTo) && !t.uploadDate) return false;
if (committedDateFrom && t.uploadDate < committedDateFrom) return false;
if (committedDateTo && t.uploadDate > committedDateTo) return false;
if (t.isLivestream ? committedNol : committedNov) return false;
diff --git a/common/controller/adoptLocalMediaReference.test.ts b/common/controller/adoptLocalMediaReference.test.ts
@@ -0,0 +1,107 @@
+import test, {type TestContext} from "node:test";
+import assert from "node:assert/strict";
+import {mkdtemp,mkdir,writeFile,readFile,readdir,readlink,rm,symlink,link} from "node:fs/promises";
+import path from "node:path";
+import os from "node:os";
+import type {Paths} from "../lib/paths";
+import {previewLocalMedia} from "./localMediaImport";
+import {adoptLocalMediaReference} from "./adoptLocalMediaReference";
+async function fixture(t:TestContext) {
+ const root=await mkdtemp(path.join(os.tmpdir(),"adopt-local-"));t.after(()=>rm(root,{recursive:true,force:true}));
+ const paths={channelsDir:path.join(root,"channels")} as Paths;
+ const channel=path.join(paths.channelsDir,"sample"),record=path.join(channel,"data","video-1"),source=path.join(root,"source");
+ await mkdir(record,{recursive:true});await mkdir(source);
+ const config={handling:"youtube",platform:"youtube",localMedia:{sourceId:"library-1",directory:source}};
+ await writeFile(path.join(channel,"config.json"),JSON.stringify(config));
+ const metadata=JSON.stringify({id:"video-1",title:"Original",duration:3,upload_date:"20261031",webpage_url:"https://www.youtube.com/watch?v=video-1"});
+ const transcript="WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nOriginal cue\n";
+ const media="雪 % '$ recording.mp4",stem=media.slice(0,-4);
+ await writeFile(path.join(source,media),"original bytes");
+ await writeFile(path.join(source,stem+".info.json"),metadata);await writeFile(path.join(source,stem+".vtt"),transcript);
+ await writeFile(path.join(record,"metadata.info.json"),metadata);await writeFile(path.join(record,"transcript.en.vtt"),transcript);
+ await symlink(path.join(source,media),path.join(record,"local-preview.mp4"));
+ const p=await previewLocalMedia(paths,"sample");assert.equal(p.candidates[0].status,"existing");
+ const selection={sourceToken:p.sourceToken,media,fingerprint:p.candidates[0].fingerprint!};
+ const ref=path.join(record,"external-media.json");
+ return {root,paths,channel,record,source,metadata,transcript,media,stem,selection,ref,config};
+}
+test("preview writes nothing; attach adds only a reference, preserving all original files and prototype link",async t=>{
+ const f=await fixture(t);const before=(await readdir(f.record)).sort();
+ assert.equal((await adoptLocalMediaReference(f.paths,"sample",f.selection)).status,"ready");
+ assert.deepEqual((await readdir(f.record)).sort(),before);
+ assert.equal((await adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true})).status,"attached");
+ assert.equal(await readFile(path.join(f.source,f.media),"utf8"),"original bytes");
+ assert.equal(await readFile(path.join(f.record,"metadata.info.json"),"utf8"),f.metadata);
+ assert.equal(await readFile(path.join(f.record,"transcript.en.vtt"),"utf8"),f.transcript);
+ assert.equal(await readlink(path.join(f.record,"local-preview.mp4")),path.join(f.source,f.media));
+ assert.deepEqual(JSON.parse(await readFile(f.ref,"utf8")),{version:1,kind:"external",sourceId:"library-1",relativePath:f.media});
+ assert.deepEqual((await readdir(f.record)).sort(),[...before,"external-media.json"].sort());
+});
+test("repeat application is already-linked without changing reference bytes",async t=>{
+ const f=await fixture(t);await adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true});const before=await readFile(f.ref,"utf8");
+ assert.equal((await adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true})).status,"already-linked");assert.equal(await readFile(f.ref,"utf8"),before);
+});
+for(const name of ["metadata.info.json","transcript.en.vtt"]) test(`refuse mismatched ${name}`,async t=>{
+ const f=await fixture(t);await writeFile(path.join(f.record,name),"different");
+ await assert.rejects(adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true}),/differs/);
+ await assert.rejects(readFile(f.ref));
+});
+test("corrupt or conflicting reference is preserved, never repaired automatically",async t=>{
+ const f=await fixture(t);for(const content of ["bad-json",JSON.stringify({version:1,kind:"external",sourceId:"other",relativePath:f.media})]) {
+ await writeFile(f.ref,content);assert.equal((await adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true})).status,"conflict");assert.equal(await readFile(f.ref,"utf8"),content);
+ }
+});
+test("concurrent adoption publishes one complete reference",async t=>{
+ const f=await fixture(t);const results=await Promise.all([1,2].map(()=>adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true})));
+ assert.equal(results.filter(r=>r.status==="attached").length,1,JSON.stringify(results));assert.equal(results.filter(r=>r.status==="already-linked").length,1,JSON.stringify(results));
+ assert.equal(JSON.parse(await readFile(f.ref,"utf8")).relativePath,f.media);
+});
+test("source change since preview refuses attachment",async t=>{
+ const f=await fixture(t);await writeFile(path.join(f.source,f.stem+".vtt"),f.transcript+"\n00:00:02.000 --> 00:00:03.000\nNew\n");
+ await assert.rejects(adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true}));await assert.rejects(readFile(f.ref));
+});
+test("late metadata change prevents publication and cleans staging only",async t=>{
+ const f=await fixture(t);
+ await assert.rejects(adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true},{beforePublish:()=>writeFile(path.join(f.record,"metadata.info.json"),"competing edit")}));
+ assert.equal(await readFile(path.join(f.record,"metadata.info.json"),"utf8"),"competing edit");await assert.rejects(readFile(f.ref));
+ assert.equal((await readdir(f.channel)).some(n=>n.startsWith(".local-media-reference-")),false);
+});
+test("competing reference publication survives without overwrite",async t=>{
+ const f=await fixture(t);const r=await adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true},{beforePublish:()=>writeFile(f.ref,"competing reference")});
+ assert.equal(r.status,"conflict");assert.equal(await readFile(f.ref,"utf8"),"competing reference");
+});
+test("cancellation before work or just before publication creates no reference",async t=>{
+ const f=await fixture(t);const c=new AbortController();c.abort();
+ await assert.rejects(adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true,signal:c.signal}));
+ const later=new AbortController();await assert.rejects(adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true,signal:later.signal},{beforePublish:async()=>later.abort()}));
+ await assert.rejects(readFile(f.ref));
+});
+test("configuration change during verification refuses publication",async t=>{
+ const f=await fixture(t);await assert.rejects(adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true},{beforePublish:()=>writeFile(path.join(f.channel,"config.json"),JSON.stringify({...f.config,localMedia:{...f.config.localMedia,sourceId:"changed"}}))}));
+ await assert.rejects(readFile(f.ref));
+});
+test("linked archive transcript is refused",async t=>{
+ const f=await fixture(t);await rm(path.join(f.record,"transcript.en.vtt"));await symlink(path.join(f.source,f.stem+".vtt"),path.join(f.record,"transcript.en.vtt"));
+ await assert.rejects(adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true}));await assert.rejects(readFile(f.ref));
+});
+
+test("reference read retries when hard-link cleanup changes inode metadata",async t=>{
+ const f=await fixture(t);await adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true});
+ const extra=path.join(f.root,"staging-link.json");await link(f.ref,extra);
+ let hookRan=false;
+ const result=await adoptLocalMediaReference(f.paths,"sample",f.selection,{}, {
+ afterReferenceRead:async()=>{
+ hookRan=true;
+ await new Promise(r=>setTimeout(r,5));
+ await rm(extra); // Same publication cleanup race, forced during the read.
+ },
+ });
+ assert.equal(hookRan,true);assert.equal(result.status,"already-linked");
+});
+test("retry reads changed reference content instead of accepting stale bytes",async t=>{
+ const f=await fixture(t);await adoptLocalMediaReference(f.paths,"sample",f.selection,{apply:true});
+ const result=await adoptLocalMediaReference(f.paths,"sample",f.selection,{}, {
+ afterReferenceRead:async()=>writeFile(f.ref,"conflicting writer"),
+ });
+ assert.equal(result.status,"conflict");assert.equal(await readFile(f.ref,"utf8"),"conflicting writer");
+});
+\ No newline at end of file
diff --git a/common/controller/adoptLocalMediaReference.ts b/common/controller/adoptLocalMediaReference.ts
@@ -0,0 +1,119 @@
+import { localTranscriptVtt, localTranscriptFingerprint } from "../lib/localMediaTranscript";
+import path from "node:path";
+import { constants } from "node:fs";
+import { lstat, open, realpath, mkdtemp, link, rm } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import { previewLocalMedia } from "./localMediaImport";
+import { readChannelConfig } from "./channels";
+import { channelWriters } from "./channelWriters";
+import { onDrive } from "../lib/storageHealth";
+import { openExternalMedia } from "../lib/externalMediaResolver-server";
+import { localMediaFingerprint } from "../lib/localMediaScan";
+import { EXTERNAL_MEDIA_FILENAME, coerceExternalMediaReference } from "../lib/localMedia";
+import { writeExternalMediaReference } from "../lib/externalMedia-server";
+
+type Selection = { sourceToken: string; media: string; fingerprint: string };
+export type LocalMediaAdoptionResult = { status: "ready" | "attached" | "already-linked" | "conflict"; stagingCleanupFailed?: boolean };
+
+// Exact bounded bytes, not decoded-text equality: distinct malformed UTF-8
+// sequences must not compare equal merely because decoding replaced them.
+async function bytes(root: string, name: string, afterRead?: () => Promise<void>) {
+ if (!name || name === "." || name === ".." || /[\\/]/.test(name)) throw new Error("Invalid companion name");
+ const file=path.join(root,name), before=await lstat(file);
+ if (!before.isFile() || before.isSymbolicLink() || before.size>32*1024*1024) throw new Error("Expected bounded regular companion file");
+ const h=await open(file,constants.O_RDONLY | (constants.O_NOFOLLOW??0) | (constants.O_NONBLOCK??0));
+ try {
+ const s=await h.stat();
+ if (!s.isFile() || s.dev!==before.dev || s.ino!==before.ino || s.size!==before.size) throw new Error("Companion changed");
+ const buffer=Buffer.alloc(s.size+1); let n=0;
+ while(n<buffer.length) { const r=await h.read(buffer,n,buffer.length-n,n); if(!r.bytesRead) break; n+=r.bytesRead; }
+ await afterRead?.();
+ const after=await h.stat();
+ if(n!==s.size || after.size!==s.size || after.mtimeMs!==s.mtimeMs || after.ctimeMs!==s.ctimeMs) throw new Error("Companion changed");
+ return buffer.subarray(0,n);
+ } finally { await h.close(); }
+}
+
+// Separate from import: occupied records are NEVER silently merged by scanning.
+// This explicit operation requires exact existing metadata/transcript matches.
+// It publishes only a new sidecar and never changes/removes prototype links.
+export async function adoptLocalMediaReference(paths: Paths, slug: string,
+ selection: Selection, options: { apply?: boolean; signal?: AbortSignal } = {},
+ testHooks: { beforePublish?: () => Promise<void>; afterReferenceRead?: () => Promise<void> } = {}): Promise<LocalMediaAdoptionResult> {
+ if (!selection || typeof selection.sourceToken!=="string" || typeof selection.media!=="string" || typeof selection.fingerprint!=="string") throw new Error("Invalid selection");
+ async function verify() {
+ options.signal?.throwIfAborted();
+ if(channelWriters(slug,{includeQueued:true}).length) throw new Error("Finish channel work before attaching a reference");
+ const preview=await previewLocalMedia(paths,slug);
+ if(preview.sourceToken!==selection.sourceToken) throw new Error("Library configuration changed; preview again");
+ const row=preview.candidates.find(r=>r.media===selection.media);
+ if(!row || row.status!=="existing" || !row.directoryId || row.fingerprint!==selection.fingerprint) throw new Error("Existing selection changed or is not eligible");
+ const config=(await readChannelConfig(paths,slug))?.localMedia;
+ if(!config) throw new Error("Library unavailable");
+ const reference={version:1 as const,kind:"external" as const,sourceId:config.sourceId,relativePath:row.media};
+ // The closure has no writes and always closes its media handle, even if the
+ // storage watchdog times out before it settles. A late read cannot publish.
+ const source=await onDrive(config.directory,async()=>{
+ const root=await realpath(config.directory);
+ const media=await openExternalMedia({config,reference,purpose:"inspect"});
+ if(media.status!=="ready") throw new Error("Source unavailable");
+ try {
+ const first=await media.handle.stat();
+ const metadata=await bytes(root,row.metadata), transcript=await bytes(root,row.transcript);
+ const last=await media.handle.stat();
+ const fp=localMediaFingerprint(row.media,metadata.toString("utf8"),localTranscriptFingerprint(row.transcript,transcript.toString("utf8")),last);
+ if(fp!==selection.fingerprint || first.size!==last.size || first.mtimeMs!==last.mtimeMs || first.ctimeMs!==last.ctimeMs) throw new Error("Source changed; preview again");
+ return {metadata,transcript: /\.srt$/i.test(row.transcript) ? Buffer.from(localTranscriptVtt(row.transcript,transcript.toString("utf8")), "utf8") : transcript};
+ } finally { await media.handle.close(); }
+ });
+ const channel=path.join(paths.channelsDir,slug), data=path.join(channel,"data"), record=path.join(data,row.directoryId);
+ for(const dir of [channel,data,record]) { const s=await lstat(dir); if(!s.isDirectory() || s.isSymbolicLink()) throw new Error("Expected real archive directories"); }
+ const metadata=await bytes(record,"metadata.info.json"), transcript=await bytes(record,"transcript.en.vtt");
+ if(!metadata.equals(source.metadata) || !transcript.equals(source.transcript)) throw new Error("Existing metadata or transcript differs; manual review required");
+ // Repeat the configuration/relocation guards after the source reads too.
+ const after=await previewLocalMedia(paths,slug);
+ const match=after.candidates.find(r=>r.media===selection.media);
+ if(after.sourceToken!==selection.sourceToken || match?.status!=="existing" || match.fingerprint!==selection.fingerprint) throw new Error("Library changed during verification");
+ options.signal?.throwIfAborted();
+ return {channel,record,reference};
+ }
+ const checked=await verify();
+ async function existing():Promise<LocalMediaAdoptionResult | null> {
+ try { await lstat(path.join(checked.record,EXTERNAL_MEDIA_FILENAME)); }
+ catch(e) { if((e as NodeJS.ErrnoException).code==="ENOENT") return null; throw e; }
+ // Removing the winner's staging hard link updates the published inode's
+ // ctime too. A concurrent reader correctly rejects that unstable snapshot,
+ // but it must retry a bounded number of times before declaring a conflict.
+ // Keep all identity/size/mtime/ctime checks; never accept bytes from a read
+ // that changed, and never overwrite a reference even if all retries fail.
+ for (let attempt=0; attempt<3; attempt++) {
+ try {
+ const content=await bytes(checked.record,EXTERNAL_MEDIA_FILENAME,
+ attempt===0 ? testHooks.afterReferenceRead : undefined);
+ const stored=coerceExternalMediaReference(JSON.parse(content.toString("utf8")));
+ return {status:JSON.stringify(stored)===JSON.stringify(checked.reference)?"already-linked":"conflict"};
+ } catch { /* A fresh read may succeed once the competing publisher settles. */ }
+ }
+ return {status:"conflict"};
+ }
+ const found=await existing(); if(found) return found;
+ if(options.apply!==true) return {status:"ready"};
+ const stage=await mkdtemp(path.join(checked.channel,".local-media-reference-"));
+ let result:LocalMediaAdoptionResult={status:"conflict"};
+ try {
+ // Use the declared sidecar writer in our private staging directory, then a
+ // hard link publishes complete JSON without replacing any existing target.
+ // These are corpus-only hard links; never hard-link an original MP4.
+ await writeExternalMediaReference(stage,checked.reference);
+ await testHooks.beforePublish?.();
+ await verify();
+ options.signal?.throwIfAborted();
+ if(channelWriters(slug,{includeQueued:true}).length) throw new Error("Channel work started; retry later");
+ try { await link(path.join(stage,EXTERNAL_MEDIA_FILENAME),path.join(checked.record,EXTERNAL_MEDIA_FILENAME)); result={status:"attached"}; }
+ catch(e) { if((e as NodeJS.ErrnoException).code!=="EEXIST") throw e; result=(await existing())??{status:"conflict"}; }
+ return result;
+ } finally {
+ try { await rm(stage,{recursive:true,force:true}); }
+ catch { result.stagingCleanupFailed=true; }
+ }
+}
diff --git a/common/controller/archiveTranscripts.ts b/common/controller/archiveTranscripts.ts
@@ -19,6 +19,7 @@
// prettyPrint is overridden, staging rewrites each cues file instead of
// hard-linking it (slower, but bounded).
+import { LOCAL_RECORDING_ID_RE } from "../lib/localMedia";
import path from "node:path";
import {
access,
@@ -164,6 +165,14 @@ async function stageChannel(
} catch {
videoIds = [];
}
+ // A local recording (its dir is its `local-<32 hex>` id) is in no archive zip
+ // in lane/local-media slice 1: the zip is a published download, and the cache
+ // is one per channel across every site, public and private.
+ const localIds = videoIds.filter((id) => LOCAL_RECORDING_ID_RE.test(id));
+ if (localIds.length > 0) {
+ videoIds = videoIds.filter((id) => !LOCAL_RECORDING_ID_RE.test(id));
+ log(`Archive ${ch.slug}: ${localIds.length} local recording(s) left out of the zip`);
+ }
log(`Archive ${ch.slug}: scanning ${videoIds.length} videos`);
diff --git a/common/controller/attachMedia.ts b/common/controller/attachMedia.ts
@@ -53,7 +53,8 @@
// in flight and removes its staging file.
import path from "node:path";
-import { appendFile, mkdir, readFile, readdir, rm, stat } from "node:fs/promises";
+import { appendFile, lstat, mkdir, readFile, readdir, rm, stat } from "node:fs/promises";
+import { EXTERNAL_MEDIA_FILENAME } from "../lib/localMedia";
import { createWriteStream } from "node:fs";
import { pipeline } from "node:stream/promises";
import { Transform, type TransformCallback } from "node:stream";
@@ -441,12 +442,18 @@ export async function attachMedia(opts: AttachMediaOptions): Promise<AttachMedia
pointers.set(id, p);
}
}
+ // Held records linked to a local media library original: never attached.
+ const localMedia = new Set<string>();
+ for (const id of held) {
+ if (await lstat(path.join(dataDir, id, EXTERNAL_MEDIA_FILENAME)).then(() => true, () => false)) localMedia.add(id);
+ }
const folders = groupArchiveFolders(source.files);
const plan = planAttach({
folders,
held,
attached,
+ localMedia,
...(opts.createRecords ? { createRecords: true } : {}),
...(opts.replace ? { replace: true } : {}),
...(match ? { match } : {}),
diff --git a/common/controller/autoRunner.test.ts b/common/controller/autoRunner.test.ts
@@ -926,3 +926,38 @@ test("a manual-downloads channel projects no download work but keeps its transcr
"side by side, only the automatic channel's backlog counts",
);
});
+
+// --- Remote-only: on no lane (demo epic D1) --------------------------------
+//
+// A remote-only channel holds a connected archive's clip windows. Even with a
+// video dir on disk and a report that lists work, no lane draws it.
+
+test("a remote-only channel is no lane's work, whatever its report lists", async () => {
+ const paths = pendingFixture();
+ const transcribeOp = bucketLaneOperationId("transcription");
+ const downloadOp = bucketLaneOperationId("download");
+ const slug = "remote";
+ const channelDir = path.join(paths.channelsDir, slug);
+ mkdirSync(path.join(channelDir, "data", `${slug}-on-disk`), { recursive: true });
+ const config = { handling: "youtube", platform: "youtube", remoteOnly: true, remoteArchive: "https://stub.test", downloadMode: "manual" };
+ writeFileSync(path.join(channelDir, "config.json"), JSON.stringify(config));
+ writeFileSync(
+ path.join(channelDir, "snapshot.json"),
+ JSON.stringify({
+ generatedAt: new Date().toISOString(),
+ totals: { videos: 1, downloaded: 1, transcribed: 0 },
+ buckets: { downloadedNoTranscript: [`${slug}-on-disk`] },
+ undownloadedIds: [`${slug}-listed`],
+ backfill: {
+ ...(downloadOp ? { [downloadOp]: { ids: [`${slug}-listed`] } } : {}),
+ ...(transcribeOp ? { [transcribeOp]: { ids: [`${slug}-on-disk`] } } : {}),
+ },
+ }),
+ );
+ forgetChannelMedia(slug);
+ const ch = { slug, config: config as never };
+ // Every lane there is (main's Speakers work runs inside them), not a list that can fall behind.
+ for (const lane of LANES) {
+ assert.equal(await laneTotal(lane, paths, [ch]), 0, `the ${lane} lane skips a remote-only channel`);
+ }
+});
diff --git a/common/controller/autoRunner.ts b/common/controller/autoRunner.ts
@@ -3,7 +3,7 @@ import { readdir, stat } from "node:fs/promises";
import { audioFilesToRemove } from "../lib/mediaFiles";
import { audioBytesPerHour, spaceComparator } from "../lib/spaceOrder";
import type { Paths } from "../lib/paths";
-import type { ChannelConfig } from "../lib/channelConfig";
+import { isRemoteOnlyChannel, type ChannelConfig } from "../lib/channelConfig";
import { mapConcurrent } from "../lib/concurrency";
import { getPaths } from "../lib/paths";
import { getSettings, type SiteSettings } from "../lib/settings";
@@ -400,6 +400,9 @@ async function listChannelMeta(
return {
meta: configs
.filter(({ slug }) => !isChannelPaused(priority, slug, kind))
+ // A REMOTE-ONLY channel (demo epic D1) is on no lane at all: it holds a
+ // connected archive's clip windows and nothing a lane could work on.
+ .filter(({ config }) => !isRemoteOnlyChannel(config))
// A MANUAL-DOWNLOADS CHANNEL is not on the download lane's list at all
// (lib/manualDownloads.ts): its listing's backlog, its retries, its
// metadata scan and its chat backlog are all things nobody asked for.
diff --git a/common/controller/browserLookupJob.ts b/common/controller/browserLookupJob.ts
@@ -21,6 +21,7 @@
// The job's log ends with `summary: {json}` — the per-video statuses and the
// listing's counts — for the UI to read back into sentences.
+import { localMediaMetadataRefusal } from "../lib/localMedia";
import path from "node:path";
import { assertChannelTextReadable } from "../lib/channelMedia";
import type { ChannelConfig } from "../lib/channelConfig";
@@ -77,6 +78,11 @@ export async function runBrowserLookupJob(opts: BrowserLookupJobOpts): Promise<S
}
const bad = ids.filter((id) => !isVideoIdSegment(id));
if (bad.length) return { ok: false, error: `Not a video id: ${bad.join(", ")}.` };
+ // A local media library channel or a local recording (review fix 5).
+ for (const id of [undefined, ...ids]) {
+ const localRefusal = localMediaMetadataRefusal(slug, channelConfig, id);
+ if (localRefusal) return { ok: false, error: localRefusal };
+ }
if (opts.listing) {
const refusal = browserListingRefusal(channelConfig);
if (refusal) return { ok: false, error: refusal };
diff --git a/common/controller/buildIndex.ts b/common/controller/buildIndex.ts
@@ -93,6 +93,7 @@ import {
siteSummariesDir,
siteSubsDir,
} from "../lib/site";
+import { isPrivateSite } from "../lib/siteSchema";
import {
type ChannelConfig,
type ChannelHandling,
@@ -107,7 +108,7 @@ import {
heldReason,
} from "../lib/channelMediaHold";
import { resolveChannelGroupId } from "../lib/channelGroups";
-import type { Paths } from "../lib/paths";
+import { sharedPrivateTranscriptsDir, type Paths } from "../lib/paths";
import {
CAPTION_TRACK_RULE_VERSION,
captionInputs,
@@ -149,7 +150,7 @@ import {
readPostAvailability,
postsAvailabilityPath,
} from "../lib/posts-server";
-import { isSocialChannel } from "../lib/channelConfig";
+import { isRemoteOnlyChannel, isSocialChannel } from "../lib/channelConfig";
import { publishedMemberSlugs } from "../lib/postsVisibility";
import {
DIGESTS_MANIFEST_VERSION,
@@ -175,6 +176,8 @@ import {
import { tagsForSite } from "../lib/curatedTags";
import { compileRecordedDateRule, deriveRecordedDate } from "../lib/recordedDate";
import { loadTranscribeOutcome } from "../lib/transcribeOutcome-server";
+import { localRecordingProblem } from "../lib/localRecordingMetadata";
+import { isLocalRecord } from "../lib/localMedia";
// v10: multi-site build. Shared per-channel transcript/subs pages are written
// once; per-site summaries + subs manifests are filtered selections. Bumped to
@@ -445,6 +448,12 @@ async function scanSource(
log(`Skipping channel ${ch.name}: excluded from build`);
continue;
}
+ // A remote-only channel (demo epic D1) holds an archive's clip windows,
+ // not a corpus of its own: it is in no index build.
+ if (isRemoteOnlyChannel(cfg)) {
+ log(`Skipping channel ${ch.name}: remote-only`);
+ continue;
+ }
channels.set(ch.name, cfg);
// A social channel carries posts, not videos: it has no data/ dir to walk,
// and routing it through the video scan would only ever produce noise. Its
@@ -1102,18 +1111,34 @@ export async function buildIndex({
}
}
}
- if (!summary.uploadDate) {
+ if (!summary.uploadDate && summary.platform !== "local") {
log(`Skipping ${s.channelSlug}/${s.videoDir}: no upload_date`);
return;
}
+ // A local recording enters only when its marker validates — read
+ // from the metadata itself, since a fresh normalized summary does not
+ // carry it (lib/transcripts-server.ts, platformFromMetadata).
+ if (summary.platform === "local") {
+ const problem = await readFile(s.metaPath, "utf8")
+ .then((raw) => localRecordingProblem(JSON.parse(raw)))
+ .catch((e: unknown) => `unreadable metadata: ${(e as Error).message}`);
+ if (problem) {
+ log(`Skipping ${s.channelSlug}/${s.videoDir}: invalid local_recording metadata (${problem})`);
+ return;
+ }
+ }
// The channel's recorded-date rule, applied to the summary as it
// stands (a normalized one included): set when it reads a date, and
// never carried over from an older derivation.
- delete summary.recordedDate;
- const recordedRe = recordedDateRes.get(s.channelSlug);
- if (recordedRe) {
- const recorded = deriveRecordedDate(recordedRe, summary.title, summary.uploadDate);
- if (recorded) summary.recordedDate = recorded;
+ // A source-less recording's explicit date is not a title-derived
+ // publication fact. Keep it, including when a channel rule changes.
+ if (summary.platform !== "local") {
+ delete summary.recordedDate;
+ const recordedRe = recordedDateRes.get(s.channelSlug);
+ if (recordedRe) {
+ const recorded = deriveRecordedDate(recordedRe, summary.title, summary.uploadDate);
+ if (recorded) summary.recordedDate = recorded;
+ }
}
// A SALVAGE transcript says so on its record (release 30, lane Q):
// only a whisper transcript can be one, and only one carrying the
@@ -1564,12 +1589,18 @@ export async function buildIndex({
};
if (sharedNeedsBuild) {
- for (const channelSlug of Array.from(channelConfigs.keys()).sort()) {
- // A held channel's pages are left exactly as the last build wrote them:
- // not rewritten, not pruned, and (below) not removed. After a full rebuild
- // its records are gone, and a rewrite would publish it empty.
- if (held.has(channelSlug)) continue;
- const channelDir = path.join(transcriptsOutDir, channelSlug);
+ // One channel's transcript tree into `channelDir`. The SHARED tree (what every
+ // site copies) leaves local recordings out; a channel that holds one also
+ // gets a FULL tree under sharedPrivateTranscriptsDir, copied into private-
+ // audience sites only (lib/localMedia.ts isLocalRecord). `hashSlug` keys the
+ // page hashes, so the two trees never share a page's hash.
+ const writeTranscriptTree = async (
+ channelSlug: string,
+ channelDir: string,
+ hashSlug: string,
+ includeLocal: boolean,
+ ): Promise<{ sawLocal: boolean }> => {
+ let sawLocal = false;
await mkdir(channelDir, { recursive: true });
const writer = createPageWriter({
@@ -1577,22 +1608,26 @@ export async function buildIndex({
fileName: pageFileName,
maxPageBytes: maxTranscriptPageBytes,
ensureDir: false,
- getPrevHash: (idx) => pageHashes.get([channelSlug, idx])?.hash,
+ getPrevHash: (idx) => pageHashes.get([hashSlug, idx])?.hash,
setHash: (idx, record) => {
- pageHashes.put([channelSlug, idx], record);
+ pageHashes.put([hashSlug, idx], record);
},
onLog: log,
});
for (const { key } of byChannel.getRange({
start: [channelSlug],
- end: [channelSlug, ""],
+ end: [channelSlug, "\uffff"],
})) {
const ck = key as ChannelKey;
if (ck[0] !== channelSlug) continue;
const indexKey: IndexKey = [ck[1], ck[0], ck[2]];
const summary = sums.get(indexKey);
if (!summary) continue;
+ if (isLocalRecord(summary)) {
+ sawLocal = true;
+ if (!includeLocal) continue;
+ }
const cueList = cues.get(indexKey);
// `track` + `altTracks` only on a record that has an alternate, so every
// other record's page bytes are what they were.
@@ -1622,8 +1657,8 @@ export async function buildIndex({
pagesDeleted++;
}
for (const { key } of pageHashes.getRange({
- start: [channelSlug, pageCount],
- end: [channelSlug, Number.MAX_SAFE_INTEGER],
+ start: [hashSlug, pageCount],
+ end: [hashSlug, Number.MAX_SAFE_INTEGER],
})) {
pageHashes.remove(key as PageHashKey);
}
@@ -1640,6 +1675,38 @@ export async function buildIndex({
path.join(channelDir, "manifest.json"),
channelManifest,
);
+ return { sawLocal };
+ };
+
+ const privateTranscriptsOutDir = sharedPrivateTranscriptsDir(paths);
+ for (const channelSlug of Array.from(channelConfigs.keys()).sort()) {
+ // A held channel's pages are left exactly as the last build wrote them:
+ // not rewritten, not pruned, and (below) not removed. After a full rebuild
+ // its records are gone, and a rewrite would publish it empty.
+ if (held.has(channelSlug)) continue;
+ const { sawLocal } = await writeTranscriptTree(
+ channelSlug, path.join(transcriptsOutDir, channelSlug), channelSlug, false,
+ );
+ const privateHashSlug = `private:${channelSlug}`;
+ if (sawLocal) {
+ await writeTranscriptTree(
+ channelSlug, path.join(privateTranscriptsOutDir, channelSlug), privateHashSlug, true,
+ );
+ } else {
+ await rm(path.join(privateTranscriptsOutDir, channelSlug), { recursive: true, force: true });
+ for (const { key } of pageHashes.getRange({
+ start: [privateHashSlug, 0],
+ end: [privateHashSlug, Number.MAX_SAFE_INTEGER],
+ })) {
+ pageHashes.remove(key as PageHashKey);
+ }
+ }
+ }
+ // A private tree for a channel that is gone goes with it.
+ for (const e of await readdir(privateTranscriptsOutDir, { withFileTypes: true }).catch(() => [] as Dirent[])) {
+ if (!channelConfigs.has(e.name)) {
+ await rm(path.join(privateTranscriptsOutDir, e.name), { recursive: true, force: true });
+ }
}
await pageHashes.flushed;
@@ -1803,6 +1870,10 @@ export async function buildIndex({
if (!stored || stored.length === 0) continue;
const summary = sums.get(indexKey);
if (!summary) continue;
+ // A local recording's caption track is its transcript, carried in the
+ // transcript trees; the shared subs tree leaves it out for every site
+ // in lane/local-media slice 1 (no private subs variant).
+ if (isLocalRecord(summary)) continue;
const display = toDisplaySummary(summary, {
state: stateByIndexKey.get(indexKeyId(indexKey)),
});
@@ -2180,6 +2251,8 @@ export async function buildIndex({
const indexKey: IndexKey = [ck[1], ck[0], ck[2]];
const digest = digests.get(indexKey);
if (!digest) continue;
+ // Shared digests leave local recordings out for every site (slice 1).
+ if (isLocalRecord({ id: ck[2], platform: sums.get(indexKey)?.platform })) continue;
await digestWriter.push(JSON.stringify(digest), digest.id);
digestCount++;
}
@@ -2328,6 +2401,7 @@ export async function buildIndex({
.map((c) => c.slug)
.filter((slug) => !memberSlugs.includes(slug));
const slugSet = new Set(memberSlugs);
+ const sitePrivate = isPrivateSite(site);
const slugGroup = new Map<string, string>();
for (const m of site.channels) {
slugGroup.set(
@@ -2360,6 +2434,10 @@ export async function buildIndex({
// Only when the visibility rule withholds a member, so a site it does
// not touch keeps the fingerprint it had.
...(withheld.length > 0 ? { withheld } : {}),
+ // A private site carries local recordings a public one leaves out
+ // (lib/localMedia.ts isLocalRecord): flipping the audience rebuilds it.
+ // Only on a private site, so a public site keeps the fingerprint it had.
+ ...(sitePrivate ? { private: true } : {}),
});
const fpKey = `siteFp:${site.siteId}`;
if (
@@ -2423,11 +2501,18 @@ export async function buildIndex({
// streaming every member record — no second walk of the corpus. compose
// joins these to the site's effective vocabulary to write /tags.json.
const tagCounter = createTagCounter();
+ let localLeftOut = 0;
for (const { key, value } of sums.getRange({ reverse: true })) {
const ik = key as IndexKey;
if (!slugSet.has(ik[1])) continue;
const stored = value as TranscriptSummary;
+ // A local recording is built only into a PRIVATE-audience site (until
+ // slice 4): not in a public site's pages, counts or tags.
+ if (!sitePrivate && isLocalRecord(stored)) {
+ localLeftOut++;
+ continue;
+ }
// A tag scoped to other sites (curated `sites`) is not this site's:
// dropped from its summaries and its counts. A copy only when it moves —
// the stored value is the LMDB cursor's.
@@ -2447,6 +2532,11 @@ export async function buildIndex({
if (buffer.length >= pageSize) await flushPage();
}
await flushPage();
+ if (localLeftOut > 0) {
+ log(
+ `Site ${site.siteId}: ${localLeftOut} local recording(s) left out — a public site carries none until private playback (slice 4); a private-audience site carries them.`,
+ );
+ }
// Written even when empty (a tiny `{tags:{}}`), so a site that loses its
// last tagged video does not keep serving a stale count file. compose
diff --git a/common/controller/buildIndexLocalRecording.test.ts b/common/controller/buildIndexLocalRecording.test.ts
@@ -0,0 +1,213 @@
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "build-index-local-"));
+const PINNED: Record<string, string> = {
+ TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"),
+ SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"),
+ SITES_DIR: path.join(ROOT, "transcripts", "sites"),
+ SETTINGS_FILE: path.join(ROOT, "settings.json"),
+ EXPORT_PUBLIC_DIR: path.join(ROOT, "public"),
+ EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"),
+ EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"),
+ EDITOR_CHANGELOG_FILE: path.join(ROOT, "editor-CHANGELOG.md"),
+ EXPORT_CHANGELOG_FILE: path.join(ROOT, "export-CHANGELOG.md"),
+ CHARTS_CONFIG_FILE: path.join(ROOT, "chart-templates.json"),
+ SEARCH_ALIASES_FILE: path.join(ROOT, "transcripts", "search-aliases.json"),
+ CURATED_TAGS_FILE: path.join(ROOT, "transcripts", "tags.json"),
+ ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"),
+ ARCHILYZER_SOURCE_SCRATCH: path.join(ROOT, "source-scratch"),
+};
+Object.assign(process.env, PINNED);
+delete process.env.ARCHILYZER_INDEX_ALLOW_HELD;
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { buildIndex } = await import("./buildIndex");
+const { open } = await import("lmdb");
+
+const paths = getPaths();
+
+const { commitLocalMediaRecord } = await import("../lib/localMediaCommit-server");
+const { prepareManualLocalRecordingMetadata } = await import("../lib/localRecordingMetadata");
+const writeJson = (file: string, value: unknown) => {
+ mkdirSync(path.dirname(file), {recursive: true});
+ writeFileSync(file, JSON.stringify(value));
+};
+const channel = "classroom";
+const dataDirectory = path.join(paths.channelsDir, channel, "data");
+const transcript = "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nSynthetic classroom discovery phrase\n";
+const first = "local-" + "a".repeat(32), second = "local-" + "b".repeat(32);
+const metadata = (id: string, recordedDate?: string) => prepareManualLocalRecordingMetadata({id,
+ filename: "Lesson 2020-01-01.mp4", recordedDate});
+async function commit(id: string, recordedDate?: string) {
+ return commitLocalMediaRecord({dataDirectory, directoryId: id,
+ metadata: JSON.stringify(metadata(id, recordedDate)), transcript,
+ reference: {version: 1, kind: "external", sourceId: "library-1", relativePath: "Lesson.mp4"}});
+}
+function summaries(): Array<{id: string; platform: string; uploadDate: string; recordedDate?: string; webpageUrl: string}> {
+ const root = open({path: paths.lmdbPath, maxDbs: 18, compression: true});
+ try {
+ const sums = root.openDB({name: "sums", encoding: "msgpack"});
+ return Array.from(sums.getRange(), ({value}) => value);
+ } finally { root.close(); }
+}
+// The FULL tree (local recordings included) a private-audience site copies;
+// the shared tree every other site copies leaves them out (review fix 3).
+function pages(root = path.join(paths.exportSharedDir, "private", "transcripts")): string {
+ const dir = path.join(root, channel);
+ return readdirSync(dir).filter(f => f.endsWith(".json")).map(f => readFileSync(path.join(dir,f),"utf8")).join("\n");
+}
+
+test("source-less commits reach real search pages; retries and title rules retain explicit facts", async () => {
+ writeFileSync(paths.settingsFile, "{}");
+ writeJson(path.join(paths.channelsDir,channel,"config.json"), {handling: "youtube", name: "Classroom"});
+ mkdirSync(dataDirectory, {recursive: true});
+ writeJson(path.join(paths.sitesDir,"localtest","site.json"), {
+ siteId: "localtest", siteTitle: "Test", siteDescription: "fixture", headerTitle: "Test", audience: "private",
+ homeTagline: "", socialLinks: [], groups: [{id:"default",name:"All",selectedByDefault:true}],
+ defaultGroupId: "default", channels: [{slug:channel,groupId:"default"}],
+ });
+ assert.deepEqual(await commit(first), {status:"imported"});
+ const logs: string[] = [];
+ await buildIndex({paths, onLog: line => logs.push(line)});
+ assert.deepEqual(summaries().map(s=>s.id), [first]);
+ assert.match(pages(), /Synthetic classroom discovery phrase/);
+ assert.match(pages(), /"platform":\s*"local"/);
+ assert.doesNotMatch(pages(), /youtube.com/);
+ // The shared tree, which a public site copies, carries no local recording.
+ assert.doesNotMatch(pages(paths.exportSharedTranscriptsDir), /"platform":\s*"local"/);
+ assert.deepEqual(await commit(first), {status:"occupied"});
+ assert.deepEqual(await commit(second, "2024-02-29"), {status:"imported"});
+ const online = path.join(dataDirectory,"online-no-date");
+ writeJson(path.join(online,"metadata.info.json"), {id:"online-no-date",title:"Undated online",extractor_key:"Youtube"});
+ writeFileSync(path.join(online,"transcript.en.vtt"),transcript);
+ await buildIndex({paths, onLog: line => logs.push(line)});
+ assert.equal(summaries().length, 2);
+ assert.ok(logs.some(line => line.includes("online-no-date: no upload_date")));
+ writeJson(path.join(paths.channelsDir,channel,"config.json"), {handling:"youtube",name:"Classroom",
+ recordedDate:{titlePattern:String.raw`(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})`}});
+ await buildIndex({paths, onLog: () => {}});
+ for (const summary of summaries()) {
+ assert.equal(summary.platform,"local");
+ // The recording date is a local recording's date (review B2); none, undated.
+ assert.equal(summary.uploadDate, summary.id === second ? "20240229" : "");
+ assert.equal(summary.webpageUrl, "");
+ assert.equal(summary.recordedDate, summary.id === second ? "20240229" : undefined);
+ }
+ assert.match(pages(), /"recordedDate":\s*"20240229"/);
+});
+
+test("invalid local metadata cannot create a corpus record", async () => {
+ const id="local-"+"c".repeat(32);
+ for (const value of [{...metadata(id),webpage_url:"https://example.com/video"}, {...metadata(id),id:first}]) {
+ await assert.rejects(commitLocalMediaRecord({dataDirectory,directoryId:id,metadata:JSON.stringify(value),transcript,
+ reference:{version:1,kind:"external",sourceId:"library-1",relativePath:"Lesson.mp4"}}));
+ }
+ assert.equal(readdirSync(dataDirectory).includes(id),false);
+});
+
+test("a malformed local_recording written past the importer is skipped with a log line, not thrown", async () => {
+ const id = "local-" + "d".repeat(32);
+ const dir = path.join(dataDirectory, id);
+ writeJson(path.join(dir, "metadata.info.json"), {...metadata(id), local_recording: {version: 99}});
+ writeFileSync(path.join(dir, "transcript.en.vtt"), transcript);
+ const logs: string[] = [];
+ await buildIndex({paths, onLog: line => logs.push(line)});
+ assert.ok(!summaries().some(s => s.id === id));
+ assert.ok(logs.some(line => line.includes(`${id}: invalid local_recording metadata`)), logs.join("\n"));
+ assert.ok(!logs.some(line => line.includes("Failed to process")), logs.join("\n"));
+ rmSync(dir, {recursive: true, force: true});
+});
+
+// Review B2: an undated local record (uploadDate "") through the index, the
+// summaries page order, the stats run and the recency index the lanes read.
+test("an undated local record pages last, keeps a stats row, and reads as unknown to the recency index", async () => {
+ const { siteSummariesDir } = await import("../lib/site");
+ const { buildStats } = await import("./buildStats");
+ const { openUploadDateIndex } = await import("./recencyIndex");
+ // The first test's undated ONLINE record is skipped by the index, and so,
+ // on main, re-"added" by every stats run: out of this one's count.
+ rmSync(path.join(dataDirectory, "online-no-date"), {recursive: true, force: true});
+ const online = path.join(dataDirectory, "onlinedated");
+ writeJson(path.join(online, "metadata.info.json"), {id: "onlinedated", title: "Dated online",
+ extractor_key: "Youtube", upload_date: "20250101", webpage_url: "https://www.youtube.com/watch?v=onlinedated"});
+ writeFileSync(path.join(online, "transcript.en.vtt"), transcript);
+ await buildIndex({paths, onLog: () => {}});
+ const dir = siteSummariesDir(paths, "localtest");
+ const listed: Array<{id: string; date: string}> = readdirSync(dir).filter(f => /^page-\d+\.json$/.test(f)).sort()
+ .flatMap(f => JSON.parse(readFileSync(path.join(dir, f), "utf8")));
+ // Newest first: the dated online record, the dated local one, then the undated one last.
+ assert.deepEqual(listed.map(r => r.id), ["onlinedated", second, first]);
+ assert.deepEqual(listed.map(r => r.date), ["2025-01-01", "2024-02-29", ""]);
+
+ const logs: string[] = [];
+ const once = await buildStats({paths, onLog: line => logs.push(line)});
+ assert.ok(once.added >= 3, JSON.stringify(once));
+ const twice = await buildStats({paths, onLog: () => {}});
+ // Without a row for the undated record it was "added" every run, and every
+ // site's stats bundle rewritten.
+ assert.equal(twice.added, 0, JSON.stringify(twice));
+ assert.equal(twice.shortCircuited, true, JSON.stringify(twice));
+
+ const recency = openUploadDateIndex(paths, [channel]);
+ try {
+ const dates = recency.datesBySlug.get(channel)!;
+ assert.equal(dates.get(first), "");
+ assert.equal(dates.get(second), "20240229");
+ assert.equal(dates.get("onlinedated"), "20250101");
+ } finally { await recency.close(); }
+ rmSync(online, {recursive: true, force: true});
+});
+
+// Review fix 3 (the publish boundary): a PUBLIC site's build leaves local
+// recordings out — its summaries, counts and stats — and says so once with the
+// count; a PRIVATE-audience site carries them; compose picks the private
+// transcript tree for the private site only; the hub's whole-pool stats have none.
+test("a public site leaves local recordings out and says so; a private one carries them", async () => {
+ const { siteSummariesDir, siteStatsDir } = await import("../lib/site");
+ const { buildStats } = await import("./buildStats");
+ const { transcriptsSourceFor } = await import("../bin/compose-site");
+ const online = path.join(dataDirectory, "onlinepublic");
+ writeJson(path.join(online, "metadata.info.json"), {id: "onlinepublic", title: "Online public", extractor_key: "Youtube",
+ upload_date: "20250102", webpage_url: "https://www.youtube.com/watch?v=onlinepublic"});
+ writeFileSync(path.join(online, "transcript.en.vtt"), transcript);
+ writeJson(path.join(paths.sitesDir, "publictest", "site.json"), {
+ siteId: "publictest", siteTitle: "Public", siteDescription: "fixture", headerTitle: "Public",
+ homeTagline: "", socialLinks: [], groups: [{id: "default", name: "All", selectedByDefault: true}],
+ defaultGroupId: "default", channels: [{slug: channel, groupId: "default"}],
+ });
+ const logs: string[] = [];
+ await buildIndex({paths, onLog: line => logs.push(line)});
+ const listed = (site: string) => {
+ const dir = siteSummariesDir(paths, site);
+ const ids = readdirSync(dir).filter(f => /^page-\d+\.json$/.test(f))
+ .flatMap(f => JSON.parse(readFileSync(path.join(dir, f), "utf8")) as Array<{id: string}>).map(r => r.id);
+ const manifest = JSON.parse(readFileSync(path.join(dir, "manifest.json"), "utf8")) as {totalCount: number};
+ return {ids, total: manifest.totalCount};
+ };
+ const pub = listed("publictest"), priv = listed("localtest");
+ assert.deepEqual(pub.ids, ["onlinepublic"]);
+ assert.equal(pub.total, 1);
+ assert.ok(priv.ids.includes(first) && priv.ids.includes(second) && priv.ids.includes("onlinepublic"), priv.ids.join());
+ assert.equal(logs.filter(l => /Site publictest: 2 local recording\(s\) left out/.test(l)).length, 1, logs.join("\n"));
+ assert.ok(!logs.some(l => /Site localtest: .* local recording/.test(l)));
+
+ // Compose's choice of transcript tree: the private one only for a private site.
+ assert.equal(await transcriptsSourceFor(paths, false)(channel), path.join(paths.exportSharedTranscriptsDir, channel));
+ assert.equal(await transcriptsSourceFor(paths, true)(channel), path.join(paths.exportSharedDir, "private", "transcripts", channel));
+ assert.equal(await transcriptsSourceFor(paths, true)("no-locals"), path.join(paths.exportSharedTranscriptsDir, "no-locals"));
+
+ const pool = path.join(ROOT, "pool-stats");
+ await buildStats({paths, onLog: () => {}, wholePoolStatsDir: pool});
+ const statsIds = (dir: string) => readdirSync(dir).filter(f => /^page-\d+\.json$/.test(f))
+ .flatMap(f => JSON.parse(readFileSync(path.join(dir, f), "utf8")) as Array<{id: string}>).map(r => r.id);
+ assert.deepEqual(statsIds(siteStatsDir(paths, "publictest")), ["onlinepublic"]);
+ assert.ok(statsIds(siteStatsDir(paths, "localtest")).includes(first));
+ assert.deepEqual(statsIds(pool), ["onlinepublic"]);
+ rmSync(online, {recursive: true, force: true});
+ rmSync(path.join(paths.sitesDir, "publictest"), {recursive: true, force: true});
+});
diff --git a/common/controller/buildStats.test.ts b/common/controller/buildStats.test.ts
@@ -814,3 +814,27 @@ test("(z) no write this file caused landed outside its temp root", () => {
assert.deepEqual(outside, []);
assert.ok(fsCalls.some((c) => c.write), "the spy saw the writes");
});
+
+// demo epic D1: a remote-only channel's clip-window dirs are no corpus — in no
+// index build and no stats build.
+test("a remote-only channel is in no index and no stats build", async () => {
+ resetCorpus();
+ seedVideo("own1");
+ addCaptions("own1", "2026-07-11T12:00:00Z");
+ writeJson(path.join(paths.channelsDir, "remote-ch", "config.json"), {
+ handling: "youtube",
+ name: "Remote",
+ platform: "youtube",
+ remoteOnly: true,
+ remoteArchive: "https://stub.test",
+ downloadMode: "manual",
+ });
+ seedVideo("r1", "2026-07-11T11:00:00Z", {}, "remote-ch");
+ addCaptions("r1", "2026-07-11T12:00:00Z", "remote-ch");
+ const indexLog: string[] = [];
+ await buildIndex({ paths, onLog: (s) => indexLog.push(s) });
+ assert.ok(indexLog.some((l) => /Skipping channel remote-ch: remote-only/.test(l)), indexLog.join("\n"));
+ const { byId } = await runStats();
+ assert.ok(byId.has("own1"));
+ assert.equal(byId.has("r1"), false);
+});
diff --git a/common/controller/buildStats.ts b/common/controller/buildStats.ts
@@ -31,6 +31,8 @@
// other scanned, when the other can publish truncated pages. The editor's build
// jobs share the "build" queue by default; the CLI is outside every queue.
+import { isLocalRecord } from "../lib/localMedia";
+import { isPrivateSite } from "../lib/siteSchema";
import path from "node:path";
import { createHash } from "node:crypto";
import {
@@ -61,7 +63,7 @@ import {
readVideoFiles,
} from "../lib/videoStatus";
import type { VideoStatus } from "../lib/stats";
-import type { ChannelConfig } from "../lib/channelConfig";
+import { isRemoteOnlyChannel, type ChannelConfig } from "../lib/channelConfig";
import { readChannelConfigFile } from "./channels";
import { inspectChannelMedia } from "../lib/channelMedia";
import {
@@ -307,6 +309,8 @@ async function scanSource(
continue;
}
if (cfg.excludeFromBuild) continue;
+ // A remote-only channel (demo epic D1) is in no build.
+ if (isRemoteOnlyChannel(cfg)) continue;
channels.set(ch.name, cfg);
// An unreadable text tier is not an empty channel (lib/channelMedia.ts):
// the readdir below would fail and every one of its stats would be removed.
@@ -549,7 +553,11 @@ export async function buildStats({
parsedMeta,
e.configName,
);
- if (!base.uploadDate) return;
+ // An undated LOCAL recording is indexed (lib/transcripts-server.ts,
+ // summarize), so it has a stats row too — without one it would count
+ // as "added" on every run and rewrite every site's bundle. Its row
+ // falls in no time bucket (chartAggregate.xLabelsForStat).
+ if (!base.uploadDate && base.platform !== "local") return;
// The key buildIndex stored this video's cues under, when it has a
// record: its uploadDate comes from transcript.cues.json when that
// is fresh, which the metadata's can differ from. The computed key
@@ -633,19 +641,22 @@ export async function buildStats({
const sites = listSites(paths);
const siteIds = new Set(sites.map((s) => s.siteId));
- const siteFingerprint = (slugs: string[]): string =>
+ const siteFingerprint = (slugs: string[], privateSite: boolean): string =>
JSON.stringify({
gen: generation,
max: STATS_MAX_PAGE_BYTES,
channels: slugs,
state: stateSignature,
+ // A private site's bundle carries local recordings (lib/localMedia.ts
+ // isLocalRecord); only there, so a public site keeps its fingerprint.
+ ...(privateSite ? { private: true } : {}),
});
// Decide which sites need a rebuild before paying to collect the dataset.
const plans = await Promise.all(
sites.map(async (site) => {
const slugs = site.channels.map((c) => c.slug);
- const fp = siteFingerprint(slugs);
+ const fp = siteFingerprint(slugs, isPrivateSite(site));
const outDir = siteStatsDir(paths, site.siteId);
const siteManifestPath = path.join(outDir, "manifest.json");
const stored = meta.get(`statsFp:${site.siteId}`) as string | undefined;
@@ -705,7 +716,10 @@ export async function buildStats({
}
signal?.throwIfAborted();
const slugSet = new Set(plan.slugs);
- const filtered = all.filter((s) => slugSet.has(s.channelSlug));
+ // A local recording only in a PRIVATE-audience site's bundle (until slice 4).
+ const sitePrivate = isPrivateSite(plan.site);
+ const filtered = all.filter((s) => slugSet.has(s.channelSlug) && (sitePrivate || !isLocalRecord(s)));
+ const siteCounts = countByChannel(filtered);
const { pageCount } = await writePages(
plan.outDir,
filtered,
@@ -715,7 +729,7 @@ export async function buildStats({
.map((slug) => ({
slug,
name: channels.get(slug)?.name ?? slug,
- count: perChannel.get(slug) ?? 0,
+ count: siteCounts.get(slug) ?? 0,
}))
.sort((a, b) => a.slug.localeCompare(b.slug));
const manifest: StatsManifest = {
@@ -746,10 +760,9 @@ export async function buildStats({
// bundles. Always rewritten when requested (stats records are small).
if (wholePoolStatsDir) {
const unlistedOnly = channelsOnlyOnUnlistedSites(sites);
- const pooled =
- unlistedOnly.size > 0
- ? all.filter((s) => !unlistedOnly.has(s.channelSlug))
- : all;
+ // The hub and homepage are public: no local recording (until slice 4).
+ const pooled = all.filter((s) => !unlistedOnly.has(s.channelSlug) && !isLocalRecord(s));
+ const poolCounts = countByChannel(pooled);
const { pageCount } = await writePages(
wholePoolStatsDir,
pooled,
@@ -760,7 +773,7 @@ export async function buildStats({
.map((slug) => ({
slug,
name: channels.get(slug)?.name ?? slug,
- count: perChannel.get(slug) ?? 0,
+ count: poolCounts.get(slug) ?? 0,
}))
.sort((a, b) => a.slug.localeCompare(b.slug));
const manifest: StatsManifest = {
@@ -815,3 +828,9 @@ export async function buildStats({
durationMs: Date.now() - t0,
};
}
+
+function countByChannel(stats: readonly VideoStat[]): Map<string, number> {
+ const out = new Map<string, number>();
+ for (const s of stats) out.set(s.channelSlug, (out.get(s.channelSlug) ?? 0) + 1);
+ return out;
+}
diff --git a/common/controller/channelSnapshot.test.ts b/common/controller/channelSnapshot.test.ts
@@ -1062,3 +1062,47 @@ test("a skip-Shorts channel keeps its listed Shorts out of the work list and the
await rm(keeping.dir, { recursive: true, force: true });
}
});
+
+// lane/local-media review fix 4: a local media library's record is never a
+// replace-auto-captions candidate (the opt-in `autoSubsOnly` bucket the
+// transcription lane draws with `replaceAutoSubs`), nor in any download bucket,
+// even when its imported VTT sniffs as YouTube's speech recognition.
+test("a local recording, and a local library channel's record, are in no acquisition bucket", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "ttb-snap-local-"));
+ const ts = (s: number) => new Date(s * 1000).toISOString().slice(11, 23);
+ const asr = "WEBVTT\nKind: captions\nLanguage: en\n\n" + [1, 3, 5, 7, 9].map((a) =>
+ `${ts(a)} --> ${ts(a + 2)} align:start position:0%\nword<${ts(a)}><c> more</c>\n`).join("\n");
+ const local = "local-" + "c".repeat(32);
+ try {
+ const paths = { channelsDir: path.join(dir, "channels") } as Paths;
+ const record = async (slug: string, id: string, meta: unknown) => {
+ const videoDir = path.join(paths.channelsDir, slug, "data", id);
+ await mkdir(videoDir, { recursive: true });
+ await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify(meta));
+ await writeFile(path.join(videoDir, "transcript.en.vtt"), asr);
+ };
+ const channel = async (slug: string, config: unknown) => {
+ await mkdir(path.join(paths.channelsDir, slug), { recursive: true });
+ await writeFile(path.join(paths.channelsDir, slug, "config.json"), JSON.stringify(config));
+ await writeFile(path.join(paths.channelsDir, slug, "playlist"), "");
+ };
+ const lib = { sourceId: "library-1", directory: path.join(dir, "library") };
+ await channel("hybrid", { handling: "youtube", url: "https://www.youtube.com/@hybrid", localMedia: lib });
+ await record("hybrid", "onlineasr01", { id: "onlineasr01", webpage_url: "https://www.youtube.com/watch?v=onlineasr01" });
+ await record("hybrid", local, { id: local, title: "Talk", local_recording: { version: 1, titleSource: "filename", inspection: "manual", durationSource: "unknown" } });
+ await channel("archive", { handling: "youtube", sourceKind: "video", localMedia: lib });
+ await record("archive", "providerasr", { id: "providerasr", webpage_url: "https://www.youtube.com/watch?v=providerasr" });
+
+ const hybrid = await generateChannelSnapshot(paths, "hybrid");
+ assert.deepEqual(hybrid.buckets.autoSubsOnly, ["onlineasr01"], "the online control is a candidate");
+ const archive = await generateChannelSnapshot(paths, "archive");
+ assert.deepEqual(archive.buckets.autoSubsOnly, []);
+ for (const snap of [hybrid, archive]) {
+ for (const ids of [snap.buckets.downloadedNoTranscript, snap.buckets.partialDownloads, snap.undownloadedIds]) {
+ assert.ok(!ids.includes(local) && !ids.includes("providerasr"), JSON.stringify(ids));
+ }
+ }
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/controller/channelSnapshot.ts b/common/controller/channelSnapshot.ts
@@ -1,4 +1,5 @@
import { writeJsonAtomic } from "../lib/jsonFile-server";
+import { localMediaFetchRefusal } from "../lib/localMedia";
import path from "node:path";
import type { Dirent } from "node:fs";
import { lstat, readdir, readFile, stat } from "node:fs/promises";
@@ -1653,7 +1654,9 @@ export async function generateChannelSnapshot(
// provenance we can't prove ("unknown") is never a candidate, so a human
// caption track is never scheduled for replacement. The corrupt-full-source
// and failed-short-audio `continue`s above already excluded terminal videos.
- const asrVtt = files.hasYtVtt && vttProvenance === "asr";
+ // A local media library's record (lib/localMedia.ts) is never a
+ // replace-auto-captions candidate: it has no online source to fetch audio from.
+ const asrVtt = files.hasYtVtt && vttProvenance === "asr" && !localMediaFetchRefusal(slug, config, id);
if (asrVtt && files.hasWhisper) {
// Our transcript won; the old ASR VTT lingers as a backup. do-not-clean
// dirs are excluded so the count matches what the manual purge removes.
diff --git a/common/controller/configureLocalMedia.test.ts b/common/controller/configureLocalMedia.test.ts
@@ -0,0 +1,67 @@
+import { test, type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, writeFile, readFile, readdir, rm } from "node:fs/promises";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import { configureLocalMedia } from "./configureLocalMedia";
+import { readChannelConfig } from "./channels";
+import type { Paths } from "../lib/paths";
+
+async function fixture(t: TestContext) {
+ const root = await mkdtemp(path.join(tmpdir(), "local-media-controller-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const source = path.join(root, "source");
+ const paths = { channelsDir: path.join(root, "channels") };
+ const channel = path.join(paths.channelsDir, "sample");
+ await mkdir(source); await mkdir(channel, { recursive: true });
+ const config = { handling: "youtube", platform: "youtube", localMedia: { sourceId: "library-1", directory: source } };
+ await writeFile(path.join(channel, "config.json"), JSON.stringify(config));
+ async function add(name: string, id = name) {
+ await writeFile(path.join(source, name + ".mp4"), "synthetic video");
+ await writeFile(path.join(source, name + ".info.json"), JSON.stringify({ id, title: "Synthetic", duration: 3, upload_date: "20261030", webpage_url: `https://www.youtube.com/watch?v=${id}` }));
+ await writeFile(path.join(source, name + ".vtt"), "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nSynthetic cue\n");
+ }
+ return { root, source, paths, channel, config, add };
+}
+async function unconfigured(f: Awaited<ReturnType<typeof fixture>>) {
+ await writeFile(path.join(f.channel,"config.json"), JSON.stringify({handling:"youtube", platform:"youtube", name:"Preserved", lastSyncedAt:"2026-10-30T00:00:00Z"}));
+}
+
+test("initial setup preserves unrelated config, creates no records, and does not enable playback", async t => {
+ const f=await fixture(t); await unconfigured(f);
+ const result=await configureLocalMedia(f.paths as Paths,"sample",{sourceId:"external-1",directory:f.source,playback:true});
+ assert.deepEqual(result,{sourceId:"external-1",directory:f.source});
+ assert.equal((await readChannelConfig(f.paths as Paths,"sample"))?.name,"Preserved");
+ assert.deepEqual(await readdir(f.channel),["config.json"]);
+ assert.deepEqual(await readdir(f.source),[]);
+});
+
+test("an established library cannot be replaced or disabled by initial setup", async t => {
+ const f=await fixture(t);
+ const before=await readFile(path.join(f.channel,"config.json"),"utf8");
+ await assert.rejects(configureLocalMedia(f.paths as Paths,"sample",{sourceId:"different",directory:f.source}),/already has a library/);
+ assert.equal(await readFile(path.join(f.channel,"config.json"),"utf8"),before);
+});
+
+test("two concurrent setup attempts have one winner", async t => {
+ const f=await fixture(t); await unconfigured(f);
+ const results=await Promise.allSettled(["first","second"].map(sourceId=>configureLocalMedia(f.paths as Paths,"sample",{sourceId,directory:f.source})));
+ assert.equal(results.filter(r=>r.status==="fulfilled").length,1);
+ assert.equal(results.filter(r=>r.status==="rejected").length,1);
+});
+
+test("invalid paths, overlapping corpus and missing source are refused without changing config", async t => {
+ const f=await fixture(t); await unconfigured(f);
+ const before=await readFile(path.join(f.channel,"config.json"),"utf8");
+ for(const directory of ["relative",f.channel,f.root,path.join(f.root,"missing")]) {
+ await assert.rejects(configureLocalMedia(f.paths as Paths,"sample",{sourceId:"library",directory}));
+ }
+ await assert.rejects(configureLocalMedia(f.paths as Paths,"../sample",{sourceId:"library",directory:f.source}),/Invalid channel/);
+ assert.equal(await readFile(path.join(f.channel,"config.json"),"utf8"),before);
+});
+
+test("relocation blocks setup", async t => {
+ const f=await fixture(t); await unconfigured(f);
+ await writeFile(path.join(f.channel,".relocating.json"),JSON.stringify({target:path.join(f.root,"media"),scope:"media",phase:"copy",direction:"out"}));
+ await assert.rejects(configureLocalMedia(f.paths as Paths,"sample",{sourceId:"library",directory:f.source}));
+});
diff --git a/common/controller/configureLocalMedia.ts b/common/controller/configureLocalMedia.ts
@@ -0,0 +1,50 @@
+import path from "node:path";
+import { libraryLocationProblem } from "./localMediaLocation";
+import { lstat, realpath } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import { coerceLocalMediaConfig } from "../lib/localMedia";
+import { patchChannelConfig, readChannelConfig } from "./channels";
+import { channelWriters } from "./channelWriters";
+import { assertChannelTextReadable, readRelocationMarker } from "../lib/channelMedia";
+
+function overlaps(a: string, b: string): boolean {
+ const rel = path.relative(a, b);
+ return !rel || rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
+}
+
+// Initial opt-in only. Changing an established source needs an explicit
+// reconciliation flow: the same relative names could identify different videos.
+// Keep this restriction in the controller, not just disabled form inputs.
+export async function configureLocalMedia(paths: Paths, slug: string, input: unknown) {
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug) || slug.endsWith(".")) throw new Error("Invalid channel slug");
+ const parsed = coerceLocalMediaConfig(input);
+ if (!parsed || !path.isAbsolute(parsed.directory)) throw new Error("Enter a library ID and an absolute directory path on the editor server");
+ // This setup enables importing only; playback requires its own future flow.
+ const localMedia = { sourceId: parsed.sourceId, directory: parsed.directory };
+ const channel = path.join(paths.channelsDir, slug);
+ const info = await lstat(channel);
+ if (!info.isDirectory() || info.isSymbolicLink()) throw new Error("Channel must be a real directory");
+ const current = await readChannelConfig(paths, slug);
+ if (!current || current.sourceKind === "social") throw new Error("A video channel is required");
+ if (current.localMedia) throw new Error("This channel already has a library. Changing it requires reference reconciliation");
+ await assertChannelTextReadable(paths, slug, current);
+ if (await readRelocationMarker(paths, slug)) throw new Error("Finish channel relocation before configuring a library");
+ const source = await realpath(localMedia.directory);
+ if (!(await lstat(source)).isDirectory()) throw new Error("Library location must be a directory");
+ const corpus = await realpath(channel);
+ if (overlaps(source, corpus) || overlaps(corpus, source)) throw new Error("Library and channel directories must be separate");
+ const misplaced = await libraryLocationProblem(paths, source);
+ if (misplaced) throw new Error(misplaced);
+ const written = await patchChannelConfig(paths, slug, {}, {
+ derive: fresh => {
+ // Rechecked inside the existing config lock: concurrent setup requests
+ // cannot replace the winner, and stale config cannot erase other changes.
+ if (fresh.localMedia) throw new Error("This channel already has a library");
+ if (fresh.sourceKind === "social") throw new Error("A video channel is required");
+ if (channelWriters(slug, { includeQueued: true }).length) throw new Error("Finish or cancel channel work before configuring its library");
+ return { localMedia };
+ },
+ });
+ if (!written?.localMedia) throw new Error("Channel configuration is unavailable");
+ return written.localMedia;
+}
diff --git a/common/controller/curatedTagsBuild.test.ts b/common/controller/curatedTagsBuild.test.ts
@@ -217,7 +217,7 @@ test("compose 1: the site publishes /tags.json and corpus.json points at it", as
const corpus = JSON.parse(
readFileSync(path.join(paths.exportPublicDir, "corpus.json"), "utf8"),
);
- assert.equal(corpus.spec, 5);
+ assert.equal(corpus.spec, 6);
assert.equal(corpus.tags.videoField, "curatedTags");
assert.match(corpus.tags.url, /\/tags\.json$/);
assert.match(
diff --git a/common/controller/fetchLiveChat.ts b/common/controller/fetchLiveChat.ts
@@ -30,6 +30,7 @@
// `needsMedia` (jobs/jobKinds.ts): it WRITES the raw replay, which is a
// tierable big file, and the normalizer moves it into the channel's media/.
+import { localMediaFetchRefusal } from "../lib/localMedia";
import path from "node:path";
import { readFile, readdir, stat } from "node:fs/promises";
import {
@@ -112,6 +113,9 @@ export async function liveChatPlan(
}
const videoDir = path.join(paths.channelsDir, slug, "data", videoId);
if (!(await isDirectory(videoDir))) return { kind: "refused", error: notFetchedRefusal(videoId, slug) };
+ // A local media record has no chat to fetch (review fix 5), before any branch.
+ const localRefusal = localMediaFetchRefusal(slug, config, videoId);
+ if (localRefusal) return { kind: "refused", error: localRefusal };
const fresh = await isLiveChatCuesFresh(videoDir);
if (fresh.fresh) return { kind: "fresh", cuesPath: fresh.cuesPath };
const entries = await readdir(videoDir).catch(() => [] as string[]);
diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts
@@ -33,11 +33,20 @@ process.env.FAKE_ARGS_LOG = ARGS_LOG;
await writeFile(
BIN,
`#!/usr/bin/env node
-import { appendFileSync, writeFileSync } from "node:fs";
+import { appendFileSync, existsSync, writeFileSync } from "node:fs";
const args = process.argv.slice(2);
appendFileSync(process.env.FAKE_ARGS_LOG, JSON.stringify(args) + "\\n");
const url = args[args.length - 1];
const fail = (msg) => { process.stderr.write(msg + "\\n"); process.exit(1); };
+if (url.includes("/m403once")) {
+ // The media URL refuses the first ask of this URL only (demo epic D1).
+ const mark = process.env.FAKE_ARGS_LOG + "." + Buffer.from(url).toString("hex");
+ if (!existsSync(mark)) {
+ writeFileSync(mark, "1");
+ fail("[https @ 0x1] HTTP error 403 Forbidden\\nhttps://rr1.googlevideo.example/videoplayback Server returned 403 Forbidden (access denied)\\nERROR: ffmpeg exited with code 1");
+ }
+}
+if (url.includes("/m403always")) fail("[https @ 0x1] HTTP error 403 Forbidden\\nhttps://rr1.googlevideo.example/videoplayback Server returned 403 Forbidden (access denied)\\nERROR: ffmpeg exited with code 1");
if (url.includes("/403")) fail("ERROR: [download] Got error: HTTP Error 403: Forbidden");
if (url.includes("/429")) fail("ERROR: [youtube] x: HTTP Error 429: Too Many Requests");
if (url.includes("/gone")) fail("ERROR: [youtube] x: Video unavailable. This video has been removed by the uploader");
@@ -836,3 +845,43 @@ test("one clock: a window held ON the map's clock is answered from the cache", a
assert.equal(r.cached.length, 1);
assert.equal(c.cuts.length, 0);
});
+
+// demo epic D1: a transient media 403 (googlevideo's) is asked once more after a pause.
+test("a media URL's 403 is asked once more after a pause, and then fetched", async () => {
+ const h = harness();
+ const before = await spawns();
+ const r = await go(await corpus(), [item("v1", "/m403once")], h);
+ assert.equal(r.failed.length, 0);
+ assert.equal(r.fetched.length, 1);
+ assert.equal((await spawns()) - before, 2, "one retry");
+ assert.deepEqual(h.rec.sleeps, [1000], "the pause before the retry (the run's gap here)");
+ assert.deepEqual(h.rec.backoffs, []);
+});
+
+test("a media 403 that persists fails once, counts once toward the streak; a Rumble 403 is never retried", async () => {
+ const h = harness();
+ const before = await spawns();
+ const r = await go(await corpus(), [item("v1", "/m403always"), item("v2", "/ok")], h);
+ assert.equal(r.stopped, undefined, "one failed window is not a streak");
+ assert.deepEqual(r.failed.map((f) => [f.item.id, f.class]), [["v1", "network"]]);
+ assert.equal((await spawns()) - before, 3, "v1 twice, v2 once");
+ const { isTransientMedia403 } = await import("./fetchWindows");
+ assert.equal(isTransientMedia403("x Server returned 403 Forbidden (access denied)", "youtube"), true);
+ assert.equal(isTransientMedia403("x Server returned 403 Forbidden (access denied)", "rumble"), false);
+ assert.equal(isTransientMedia403("ERROR: [download] Got error: HTTP Error 403: Forbidden", "youtube"), false);
+});
+
+// lane/local-media: the job-level backstop. A local library channel's item and
+// a local recording's are failed "local-media" before any URL is looked up.
+test("a local media library channel and a local recording fail local-media, and the run goes on", async () => {
+ const LOCAL = { ...CONFIG, url: undefined, localMedia: { sourceId: "library-1", directory: "/mnt/library" } };
+ const h = harness({ readChannelConfig: async (_p, slug) => (slug === "lib" ? LOCAL : CONFIG) });
+ const r = await go(
+ await corpus(),
+ [{ ...item("v1", "/ok"), slug: "lib" }, { ...item("v1", "/ok"), id: "local-" + "b".repeat(32) }, item("v2", "/ok")],
+ h,
+ );
+ assert.deepEqual(r.failed.map((f) => f.class), ["local-media", "local-media"]);
+ for (const f of r.failed) assert.match(f.message ?? "", /no online source, so no clip can be fetched/);
+ assert.equal(r.fetched.length, 1);
+});
diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts
@@ -1,4 +1,5 @@
import path from "node:path";
+import { localMediaFetchRefusal } from "../lib/localMedia";
import type { Paths } from "../lib/paths";
import type { ChannelConfig } from "../lib/channelConfig";
import type { SiteSettings } from "../lib/settings";
@@ -195,6 +196,21 @@ function testGapMs(): number | undefined {
return Number.isFinite(raw) && raw > 0 ? raw : undefined;
}
+// A TRANSIENT MEDIA 403 (demo epic D1): the page answered and gave a media URL,
+// and that URL refused the stream — ffmpeg's "Server returned 403 Forbidden"
+// (googlevideo above all, measured in D0: one in ten windows, fine on a manual
+// re-ask). That is the media host, not the platform turning us away and not a
+// cookie that went stale (lib/serviceCookies.ts raises no alert for it): the
+// window is asked ONCE more after a pause, before it counts toward the
+// network streak. A Rumble 403 is its Cloudflare (and a removed video answers
+// 403 too): never retried here.
+const MEDIA_403 = /Server returned 403 Forbidden|HTTP error 403 Forbidden/;
+export const MEDIA_403_RETRY_MS = 20_000;
+
+export function isTransientMedia403(message: string, platform: string): boolean {
+ return platform !== "rumble" && MEDIA_403.test(message) && !/\[Rumble/.test(message);
+}
+
export type FetchWindowsItem = {
slug: string;
id: string;
@@ -236,7 +252,10 @@ export type FetchWindowsFailureClass =
// aside, not kept.
| "desynced"
// No page URL to fetch from.
- | "no-url";
+ | "no-url"
+ // A local media library channel or a local recording: no online source
+ // (lib/localMedia.ts localMediaFetchRefusal).
+ | "local-media";
export type FetchWindowsFailure = {
item: FetchWindowsItem;
@@ -757,6 +776,13 @@ export async function fetchWindows({
progress();
continue;
}
+ const localRefusal = localMediaFetchRefusal(item.slug, config, item.id);
+ if (localRefusal) {
+ fail(item, "local-media", localRefusal);
+ done += 1;
+ progress();
+ continue;
+ }
const unreadable = await textProblem(item.slug);
if (unreadable) {
fail(item, "unreachable", unreadable);
@@ -1148,6 +1174,23 @@ export async function fetchWindows({
out = await attempt({ ...stored, why: "rate-limited" });
}
+ // A TRANSIENT MEDIA 403 (the header above FetchWindowsItem): once more,
+ // after a pause, before it counts.
+ if (!out.ok && !usedStored && classOf(out.e) === "network" && isTransientMedia403((out.e as Error).message, platform)) {
+ const pause = gapMs ?? testGapMs() ?? Math.max(gap, MEDIA_403_RETRY_MS);
+ log(` ${label}: the media URL answered 403 — asking once more in ${Math.round(pause / 1000)}s.`);
+ await deps.sleep(pause, signal);
+ const after = interrupted();
+ if (after) {
+ fail(item, "network", (out.e as Error).message);
+ done += 1;
+ progress();
+ stop(after, i + 1);
+ break;
+ }
+ out = await attempt(null);
+ }
+
if (out.ok) {
networkStreak = 0;
// THE SYNC CHECK on what the fetch produced (the header): a desynced
diff --git a/common/controller/findVideoSourceUrlLocal.test.ts b/common/controller/findVideoSourceUrlLocal.test.ts
@@ -0,0 +1,57 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { findVideoSourceUrl } from "./undownloadedVideos";
+import { defaultWebpageUrl } from "../lib/platform";
+
+// lane/local-media review fix 4: the one resolver every lane and door asks for a
+// video's page URL — the download lane, the replace-auto-captions unit (which
+// passes the channel with a transcribe-handling override), transcribe-one's
+// owed download, reacquire, persist-videos — answers NULL for a local record,
+// so `defaultWebpageUrl("local", id)` (which is "") never reaches yt-dlp.
+
+test("findVideoSourceUrl: null for a local recording, a local library channel and platform \"local\"", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "source-url-local-"));
+ try {
+ const paths = { channelsDir: path.join(dir, "channels") } as Paths;
+ const local = "local-" + "d".repeat(32);
+ const write = async (slug: string, config: ChannelConfig, id: string, meta: unknown, playlist = "") => {
+ await mkdir(path.join(paths.channelsDir, slug, "data", id), { recursive: true });
+ await writeFile(path.join(paths.channelsDir, slug, "config.json"), JSON.stringify(config));
+ await writeFile(path.join(paths.channelsDir, slug, "playlist"), playlist);
+ await writeFile(path.join(paths.channelsDir, slug, "data", id, "metadata.info.json"), JSON.stringify(meta));
+ };
+ const lib = { sourceId: "library-1", directory: "/mnt/library" };
+ const hybrid: ChannelConfig = { handling: "youtube", platform: "youtube", url: "https://www.youtube.com/@h", localMedia: lib };
+ // A local recording in an online channel: a youtube platform would rebuild a URL from its id.
+ await write("hybrid", hybrid, local, { id: local, title: "Talk", local_recording: { version: 1 } },
+ `https://www.youtube.com/watch?v=${local}\n`);
+ assert.equal(await findVideoSourceUrl(paths, "hybrid", local, hybrid), null);
+ // The replace-auto-captions unit's override config: still null.
+ assert.equal(await findVideoSourceUrl(paths, "hybrid", local, { ...hybrid, handling: "transcribe" }), null);
+ // No config passed: read from disk, still null.
+ assert.equal(await findVideoSourceUrl(paths, "hybrid", local), null);
+ // A local library channel's provider-metadata record: no online source either.
+ const archive: ChannelConfig = { handling: "youtube", sourceKind: "video", localMedia: lib };
+ await write("archive", archive, "aaaaaaaaaaa", { id: "aaaaaaaaaaa", webpage_url: "https://www.youtube.com/watch?v=aaaaaaaaaaa" });
+ assert.equal(await findVideoSourceUrl(paths, "archive", "aaaaaaaaaaa", archive), null);
+ // A record carrying the local marker under any id.
+ await write("hybrid", hybrid, "markedonly", { id: "markedonly", local_recording: { version: 1 } });
+ assert.equal(await findVideoSourceUrl(paths, "hybrid", "markedonly", hybrid), null);
+ // A channel whose platform is "local": "" is not a URL.
+ const localPlatform: ChannelConfig = { handling: "youtube", platform: "local" };
+ await mkdir(path.join(paths.channelsDir, "lp", "data", "x1"), { recursive: true });
+ await writeFile(path.join(paths.channelsDir, "lp", "config.json"), JSON.stringify(localPlatform));
+ assert.equal(defaultWebpageUrl("local", "x1"), "");
+ assert.equal(await findVideoSourceUrl(paths, "lp", "x1", localPlatform), null);
+ // An online record of the online channel is unchanged.
+ await write("hybrid", hybrid, "dQw4w9WgXcQ", { id: "dQw4w9WgXcQ", webpage_url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ" });
+ assert.equal(await findVideoSourceUrl(paths, "hybrid", "dQw4w9WgXcQ", hybrid), "https://www.youtube.com/watch?v=dQw4w9WgXcQ");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/controller/importMedia.ts b/common/controller/importMedia.ts
@@ -28,6 +28,7 @@
// multi-GB copy never holds a platform's download queue. `needsMedia`: it
// writes the container and the audio.
+import { localMediaWriteRefusal } from "./localMediaDoors";
import path from "node:path";
import { mkdir, readdir, rm, stat } from "node:fs/promises";
import type { ChannelConfig } from "../lib/channelConfig";
@@ -310,6 +311,10 @@ export async function runImportMediaJob(opts: ImportMediaJobOpts): Promise<Strea
}
const target = await resolveImportTarget(paths, req);
if ("error" in target) return { ok: false, error: target.error, ...(target.info ? { info: true } : {}) };
+ // The record it would land in: never a local recording, a local library
+ // channel's, or one linked to a library original (review fix 5).
+ const localRefusal = await localMediaWriteRefusal(paths, req.slug, opts.channelConfig, target.id);
+ if (localRefusal) return { ok: false, error: localRefusal };
if (target.kind === "url" && !target.exists && !req.dryRun) {
const held = await heldPlatformRefusal(target.platform, "The metadata fetch", paths);
if (held) return { ok: false, info: true, error: held };
diff --git a/common/controller/localMediaDoors.ts b/common/controller/localMediaDoors.ts
@@ -0,0 +1,25 @@
+import path from "node:path";
+import { lstat } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import { EXTERNAL_MEDIA_FILENAME, localMediaFetchRefusal } from "../lib/localMedia";
+
+// THE DOORS THAT WRITE MEDIA INTO A RECORD (import-media, attach-media; review
+// fix 5): besides a local library channel or a local recording
+// (localMediaFetchRefusal's sentence), a record LINKED to a library original —
+// one with `external-media.json`, a provider id included — is refused: its
+// video is the library's, never a copy in the saved-video store. `lstat`, not
+// the sidecar's loader: a malformed reference must refuse too.
+export async function localMediaWriteRefusal(
+ paths: Pick<Paths, "channelsDir">,
+ slug: string,
+ config: { localMedia?: unknown; url?: string | null } | null | undefined,
+ id?: string,
+): Promise<string | null> {
+ const fetch = localMediaFetchRefusal(slug, config, id);
+ if (fetch) return fetch;
+ if (!id || /[\\/]|^\.\.?$/.test(id)) return null;
+ const linked = await lstat(path.join(paths.channelsDir, slug, "data", id, EXTERNAL_MEDIA_FILENAME)).then(() => true, () => false);
+ return linked
+ ? `"${slug}/${id}" is linked to a local media library original (${EXTERNAL_MEDIA_FILENAME}), so no media is written into it.`
+ : null;
+}
diff --git a/common/controller/localMediaImport.test.ts b/common/controller/localMediaImport.test.ts
@@ -0,0 +1,218 @@
+import { test, type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, writeFile, readFile, readdir, rm } from "node:fs/promises";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import { previewLocalMedia, importLocalMedia } from "./localMediaImport";
+
+async function fixture(t: TestContext) {
+ const root = await mkdtemp(path.join(tmpdir(), "local-media-controller-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const source = path.join(root, "source");
+ const paths = { channelsDir: path.join(root, "channels") };
+ const channel = path.join(paths.channelsDir, "sample");
+ await mkdir(source); await mkdir(channel, { recursive: true });
+ const config = { handling: "youtube", platform: "youtube", localMedia: { sourceId: "library-1", directory: source } };
+ await writeFile(path.join(channel, "config.json"), JSON.stringify(config));
+ async function add(name: string, id = name) {
+ await writeFile(path.join(source, name + ".mp4"), "synthetic video");
+ await writeFile(path.join(source, name + ".info.json"), JSON.stringify({ id, title: "Synthetic", duration: 3, upload_date: "20261030", webpage_url: `https://www.youtube.com/watch?v=${id}` }));
+ await writeFile(path.join(source, name + ".vtt"), "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nSynthetic cue\n");
+ }
+ return { root, source, paths, channel, config, add };
+}
+function selection(preview: Awaited<ReturnType<typeof previewLocalMedia>>) {
+ return { sourceToken: preview.sourceToken, selected: preview.candidates.filter(r => r.status === "new").map(r => ({ media: r.media, fingerprint: r.fingerprint! })) };
+}
+async function sourceBytes(source: string) {
+ const out: Record<string,string> = {};
+ for (const name of (await readdir(source)).sort()) out[name] = (await readFile(path.join(source,name))).toString("base64");
+ return out;
+}
+test("preview creates nothing; import then rescan detects additions without changing sources", async (t) => {
+ const f = await fixture(t); await f.add("first");
+ const before = await sourceBytes(f.source);
+ const p = await previewLocalMedia(f.paths,"sample");
+ assert.deepEqual(await readdir(f.channel), ["config.json"]);
+ assert.equal(p.counts.new,1);
+ const result = await importLocalMedia(f.paths,"sample",selection(p));
+ assert.equal(result.records[0].status,"imported"); assert.equal(result.needsIndexUpdate,true);
+ assert.deepEqual(await sourceBytes(f.source),before);
+ assert.deepEqual((await previewLocalMedia(f.paths,"sample")).counts,{discovered:1,new:0,existing:1,issues:0});
+ assert.equal((await importLocalMedia(f.paths,"sample",selection(p))).records[0].status,"occupied");
+ await f.add("second");
+ const next = await previewLocalMedia(f.paths,"sample");
+ assert.equal(next.counts.new,1); assert.equal(next.counts.existing,1);
+ assert.equal((await importLocalMedia(f.paths,"sample",selection(next))).records[0].status,"imported");
+ assert.equal((await previewLocalMedia(f.paths,"sample")).counts.existing,2);
+});
+test("changed transcript after preview is stale and no record is written", async (t) => {
+ const f=await fixture(t); await f.add("first"); const p=await previewLocalMedia(f.paths,"sample");
+ await writeFile(path.join(f.source,"first.vtt"),"WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nChanged text\n");
+ const result=await importLocalMedia(f.paths,"sample",selection(p));
+ assert.equal(result.records[0].status,"stale"); assert.equal(result.needsIndexUpdate,false);
+ assert.deepEqual(await readdir(f.channel),["config.json"]);
+});
+test("source configuration change invalidates preview", async (t) => {
+ const f=await fixture(t); await f.add("first"); const p=await previewLocalMedia(f.paths,"sample");
+ await writeFile(path.join(f.channel,"config.json"),JSON.stringify({...f.config,localMedia:{...f.config.localMedia,sourceId:"different"}}));
+ await assert.rejects(importLocalMedia(f.paths,"sample",selection(p)),/configuration changed/);
+});
+test("duplicate introduced after preview blocks import", async (t) => {
+ const f=await fixture(t); await f.add("first"); const p=await previewLocalMedia(f.paths,"sample");
+ await f.add("duplicate","first");
+ const result=await importLocalMedia(f.paths,"sample",selection(p));
+ assert.equal(result.records[0].status,"issue"); assert.match(result.records[0].reason!,/Duplicate/);
+});
+test("incomplete destination is an issue, not an already imported success", async (t) => {
+ const f=await fixture(t); await f.add("first");
+ await mkdir(path.join(f.channel,"data","first"),{recursive:true});
+ const p=await previewLocalMedia(f.paths,"sample");
+ assert.equal(p.counts.issues,1); assert.equal(p.counts.existing,0);
+ assert.match(p.candidates[0].issues.join(),/incomplete/);
+});
+test("retired data layout refuses preview", async (t) => {
+ const f=await fixture(t); await f.add("first");
+ await writeFile(path.join(f.channel,"config.json"),JSON.stringify({...f.config,dataDir:path.join(f.root,"legacy")}));
+ await assert.rejects(previewLocalMedia(f.paths,"sample"));
+});
+test("source overlapping corpus is refused before writes", async (t) => {
+ const f=await fixture(t);
+ await writeFile(path.join(f.channel,"config.json"),JSON.stringify({...f.config,localMedia:{...f.config.localMedia,directory:f.root}}));
+ await assert.rejects(previewLocalMedia(f.paths,"sample"),/overlap|The library directory contains the corpus/);
+ assert.deepEqual(await readdir(f.channel),["config.json"]);
+});
+test("cancellation and empty selection write nothing", async (t) => {
+ const f=await fixture(t); await f.add("first"); const p=await previewLocalMedia(f.paths,"sample");
+ const signal=AbortSignal.abort();
+ assert.equal((await importLocalMedia(f.paths,"sample",{...selection(p),signal})).cancelled,true);
+ assert.equal((await importLocalMedia(f.paths,"sample",{sourceToken:p.sourceToken,selected:[]})).needsIndexUpdate,false);
+ assert.deepEqual(await readdir(f.channel),["config.json"]);
+});
+test("invented selection and missing media do not create records", async (t) => {
+ const f=await fixture(t); await f.add("first"); const p=await previewLocalMedia(f.paths,"sample");
+ await rm(path.join(f.source,"first.mp4"));
+ assert.equal((await importLocalMedia(f.paths,"sample",selection(p))).records[0].status,"stale");
+ assert.deepEqual(await readdir(f.channel),["config.json"]);
+});
+test("duplicate selection and unsafe channel slug are rejected", async (t) => {
+ const f=await fixture(t); await f.add("first"); const p=await previewLocalMedia(f.paths,"sample");
+ const request=selection(p); request.selected.push(request.selected[0]);
+ await assert.rejects(importLocalMedia(f.paths,"sample",request),/selection/);
+ await assert.rejects(previewLocalMedia(f.paths,"../escape"),/slug/);
+});
+
+test("media-only relocation blocks import even while text is readable", async (t) => {
+ const f=await fixture(t); await f.add("first");
+ await writeFile(path.join(f.channel,".relocating.json"),JSON.stringify({ target:path.join(f.root,"other","media"),scope:"media",phase:"copy",direction:"out" }));
+ await assert.rejects(previewLocalMedia(f.paths,"sample"),/relocation/);
+ assert.deepEqual((await readdir(f.channel)).sort(),[".relocating.json","config.json"]);
+});
+test("missing source fails instead of reporting an empty successful preview", async (t) => {
+ const f=await fixture(t); await rm(f.source,{recursive:true});
+ await assert.rejects(previewLocalMedia(f.paths,"sample"));
+ assert.deepEqual(await readdir(f.channel),["config.json"]);
+});
+
+import type { Paths } from "../lib/paths";
+import type { JobRunContext } from "../jobs/streamCommand";
+import { localMediaJobOptions, selectAllNew, LOCAL_MEDIA_IMPORT_MAX } from "./localMediaImportJob";
+import { getJobKind, isIngestKind } from "../jobs/jobKinds";
+
+function jobContext(drain = new AbortController()): JobRunContext {
+ return { drainSignal: drain.signal } as JobRunContext;
+}
+
+test("drain stops between publications and reports progress for completed records", async (t) => {
+ const f = await fixture(t); await f.add("first"); await f.add("second");
+ const p = await previewLocalMedia(f.paths, "sample");
+ const drain = new AbortController(); const statuses: string[] = [];
+ const result = await importLocalMedia(f.paths, "sample", {
+ ...selection(p), drainSignal: drain.signal,
+ onRecord: (row, completed) => { statuses.push(row.status); assert.equal(completed, 1); drain.abort(); },
+ });
+ assert.equal(result.drained, true); assert.equal(result.cancelled, false);
+ assert.deepEqual(statuses, ["imported"]);
+ assert.equal((await readdir(path.join(f.channel, "data"))).length, 1);
+});
+
+test("progress observer failure cannot reclassify a published record", async (t) => {
+ const f = await fixture(t); await f.add("first");
+ const p = await previewLocalMedia(f.paths, "sample");
+ const result = await importLocalMedia(f.paths, "sample", {
+ ...selection(p), onRecord: () => { throw new Error("display unavailable"); },
+ });
+ assert.deepEqual(result.records.map(r => r.status), ["imported"]);
+ assert.equal(result.needsIndexUpdate, true);
+});
+
+test("managed job owns its queued selection, reports progress, and declares ingest guards", async (t) => {
+ const f = await fixture(t); await f.add("first");
+ const p = await previewLocalMedia(f.paths, "sample"); const request = selection(p);
+ const job = localMediaJobOptions(f.paths as Paths, "sample", request);
+ request.selected[0].media = "changed-by-caller.mp4";
+ request.sourceToken = "changed";
+ assert.equal(job.queueKey, "channel:sample"); assert.equal(job.channelSlug, "sample");
+ assert.equal(job.spec, undefined);
+ assert.equal(getJobKind(job.kind)?.needsText, true);
+ assert.equal(getJobKind(job.kind)?.needsMedia, undefined);
+ assert.equal(getJobKind(job.kind)?.drainable, true);
+ assert.equal(getJobKind(job.kind)?.replayable, false);
+ assert.equal(isIngestKind(job.kind), true);
+ const log: string[] = []; const progress: number[] = [];
+ await job.fn(line => log.push(line), new AbortController().signal, snap => progress.push(snap.current!), jobContext());
+ assert.deepEqual(progress, [0, 1]);
+ assert.ok(log.some(line => line.includes("Imported 1")));
+ // Points at what exists today (the index build), never slice 4's button.
+ assert.ok(log.some(line => line.includes("searchable after the next index build (`pnpm ops build-index`")), log.join("\n"));
+ assert.ok(!log.some(line => line.includes("Update searchable library")));
+ assert.ok(log.every(line => !line.includes(f.source)));
+});
+
+test("managed job fails honestly for a stale selection after publishing another record", async (t) => {
+ const f = await fixture(t); await f.add("first"); await f.add("second");
+ const p = await previewLocalMedia(f.paths, "sample");
+ const job = localMediaJobOptions(f.paths as Paths, "sample", selection(p));
+ await writeFile(path.join(f.source, "second.vtt"), "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nChanged\n");
+ const log: string[] = [];
+ await assert.rejects(job.fn(line => log.push(line), new AbortController().signal, () => {}, jobContext()), /require review/);
+ assert.deepEqual(await readdir(path.join(f.channel, "data")), ["first"]);
+ assert.ok(log.some(line => line.includes("Imported 1; already occupied 0; rejected 1")));
+});
+
+test("pre-start drain and cancellation write nothing; empty job request is rejected", async (t) => {
+ const f = await fixture(t); await f.add("first");
+ const p = await previewLocalMedia(f.paths, "sample");
+ const stop = new AbortController(); stop.abort();
+ const job = localMediaJobOptions(f.paths as Paths, "sample", selection(p));
+ await job.fn(() => {}, new AbortController().signal, () => {}, jobContext(stop));
+ await job.fn(() => {}, stop.signal, () => {}, jobContext());
+ assert.deepEqual(await readdir(f.channel), ["config.json"]);
+ assert.throws(() => localMediaJobOptions(f.paths as Paths, "sample", {sourceToken: p.sourceToken, selected: []}), /Select between/);
+});
+
+// Review fix 7: over 1000 new recordings, "all new" takes the first 1000 in the
+// preview's (sorted) order and says how many are left, in the job's log too.
+test("selectAllNew takes the first 1000 new in order and counts the rest; the job log says so", async (t) => {
+ const candidates = Array.from({ length: 1003 }, (_, i) => ({
+ media: `r${String(i).padStart(4, "0")}.mp4`, fingerprint: `fp${i}`, status: i === 5 ? "issue" as const : "new" as const,
+ metadata: "", transcript: "", issues: [], warnings: [],
+ }));
+ const { request, remaining } = selectAllNew({ sourceToken: "t", candidates, counts: { discovered: 1003, new: 1002, existing: 0, issues: 1 } });
+ assert.equal(LOCAL_MEDIA_IMPORT_MAX, 1000);
+ assert.equal(request.selected.length, 1000);
+ assert.equal(request.selected[0].media, "r0000.mp4");
+ assert.ok(!request.selected.some((s) => s.media === "r0005.mp4"));
+ assert.equal(request.selected[999].media, "r1000.mp4");
+ assert.equal(remaining, 2);
+ assert.equal(request.remaining, 2);
+ assert.equal(selectAllNew({ sourceToken: "t", candidates: candidates.slice(0, 3), counts: { discovered: 3, new: 3, existing: 0, issues: 0 } }).request.remaining, undefined);
+
+ const f = await fixture(t); await f.add("first");
+ const p = await previewLocalMedia(f.paths, "sample");
+ const job = localMediaJobOptions(f.paths as Paths, "sample", { ...selection(p), remaining: 2 });
+ const log: string[] = [];
+ await job.fn(line => log.push(line), new AbortController().signal, () => {}, jobContext());
+ const said = log.filter(line => line.startsWith("2 more new recording(s) were not selected (one import takes at most 1000)"));
+ assert.equal(said.length, 2, log.join("\n"));
+});
diff --git a/common/controller/localMediaImport.ts b/common/controller/localMediaImport.ts
@@ -0,0 +1,287 @@
+import { localTranscriptVtt, localTranscriptFingerprint } from "../lib/localMediaTranscript";
+import { libraryLocationProblem, type LibraryLocationPaths } from "./localMediaLocation";
+import path from "node:path";
+import { createHash } from "node:crypto";
+import { prepareLocalRecordingMetadata, prepareManualLocalRecordingMetadata } from "../lib/localRecordingMetadata";
+import { probeLocalRecording } from "../lib/localRecordingProbe-server";
+import { localRecordingId, parseLocalRecordingDetails, type LocalRecordingDetails } from "../lib/localRecordingDetails";
+import { lstat, mkdir, readdir, realpath } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import { channelConfigSchema } from "../lib/channelConfigSchema";
+import { readJsonFile } from "../lib/jsonFile-server";
+import { assertChannelTextReadable, readRelocationMarker } from "../lib/channelMedia";
+import { onDrive, stalledLocationForPath } from "../lib/storageHealth";
+import { scanLocalMedia, localMediaFingerprint, readLocalMediaText, type LocalMediaScan } from "../lib/localMediaScan";
+import { openExternalMedia } from "../lib/externalMediaResolver-server";
+import { commitLocalMediaRecord, type LocalMediaCommitResult } from "../lib/localMediaCommit-server";
+
+type ImportPaths = Pick<Paths, "channelsDir"> & Partial<Pick<Paths, "ffprobeBin">>;
+export type LocalMediaPreview = LocalMediaScan & { sourceToken: string };
+export type LocalMediaSelection = { media: string; fingerprint: string;
+ preparation?: { sourceFingerprint: string; details: LocalRecordingDetails };
+};
+export type LocalMediaImportResult = {
+ records: Array<{ media: string; status: "imported" | "occupied" | "failed" | "stale" | "issue"; reason?: string; incomplete?: boolean; warnings?: string[]; stagingCleanupFailed?: boolean }>;
+ cancelled: boolean;
+ drained: boolean;
+ needsIndexUpdate: boolean;
+};
+function inside(root: string, item: string) {
+ const rel = path.relative(root, item);
+ return !rel || rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
+}
+async function optionalStat(file: string) {
+ try { return await lstat(file); }
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error; }
+}
+async function context(paths: ImportPaths, slug: string) {
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug) || slug.endsWith(".")) throw new Error("Invalid channel slug");
+ const channel = path.join(paths.channelsDir, slug);
+ const channelInfo = await lstat(channel);
+ if (!channelInfo.isDirectory() || channelInfo.isSymbolicLink()) throw new Error("Channel must be a real directory");
+ const raw = await readJsonFile(path.join(channel, "config.json"));
+ const config = raw.ok ? channelConfigSchema.parse(raw.value) : null;
+ if (!config || config.sourceKind === "social" || !config.localMedia) throw new Error("Video channel has no valid local media source");
+ await assertChannelTextReadable(paths, slug, config);
+ // Imports are writers: conservatively refuse any relocation, even a media-only
+ // move that leaves text readable. Job integration must also declare its needs.
+ if (await readRelocationMarker(paths, slug)) throw new Error("Channel relocation is in progress");
+ if (!path.isAbsolute(config.localMedia.directory)) throw new Error("Source path is not absolute on this server");
+ if (stalledLocationForPath(config.localMedia.directory)) throw new Error("Source drive is not answering");
+ const source = await onDrive(config.localMedia.directory, () => realpath(config.localMedia!.directory));
+ // Also at use: a config can arrive by hand or by `pnpm ops channel-config`.
+ const misplaced = await libraryLocationProblem(paths as LibraryLocationPaths, source);
+ if (misplaced) throw new Error(misplaced);
+ const canonicalChannel = await realpath(channel);
+ // Never write corpus records into the external library, or scan corpus files
+ // as an external library. Compare canonical paths in BOTH directions.
+ if (inside(source, canonicalChannel) || inside(canonicalChannel, source)) throw new Error("Source and channel directories overlap");
+ const data = path.join(canonicalChannel, "data");
+ const dataInfo = await optionalStat(data);
+ if (dataInfo && (!dataInfo.isDirectory() || dataInfo.isSymbolicLink())) throw new Error("Channel data must be a real directory");
+ const sourceToken = createHash("sha256").update(JSON.stringify([config.localMedia, source, canonicalChannel])).digest("hex");
+ return { source, data, config: config.localMedia, sourceToken };
+}
+
+// No writes. Read config fresh and apply existing channel guards before walking
+// data/. An absent data directory is a new channel; other read errors propagate.
+export async function previewLocalMedia(paths: ImportPaths, slug: string): Promise<LocalMediaPreview> {
+ const c = await context(paths, slug);
+ const entries = await optionalStat(c.data) ? await readdir(c.data) : [];
+ const scan = await onDrive(c.source, () => scanLocalMedia({ sourceDirectory: c.source, existingDirectoryIds: entries }));
+ for (const row of scan.candidates) {
+ // A recording without provider metadata has the same reserved identity
+ // before and after subtitle generation. Never offer generation over an
+ // existing local record, even if that record is incomplete.
+ if (row.transcriptionNeedsDetails && entries.includes(localRecordingId(slug, c.config.sourceId, row.media))) {
+ row.generatedMetadata = true;
+ row.directoryId = localRecordingId(slug, c.config.sourceId, row.media);
+ row.recordId = row.directoryId;
+ row.status = "existing";
+ row.issues = [];
+ row.warnings.push("A local recording destination already exists; saved files were left unchanged, not reverified");
+ delete row.transcriptionFingerprint;
+ delete row.transcriptionNeedsDetails;
+ }
+ if (row.preparationFingerprint) {
+ row.generatedMetadata = true;
+ row.directoryId = localRecordingId(slug, c.config.sourceId, row.media);
+ row.recordId = row.directoryId;
+ if (entries.includes(row.directoryId)) {
+ // A generated record is reserved by library/name, so rescanning or a
+ // changed file cannot silently create another identity or overwrite it.
+ row.issues = [];
+ row.warnings.push("A local recording destination already exists; saved files were left unchanged, not reverified");
+ row.status = "existing";
+ delete row.preparationFingerprint;
+ }
+ }
+ if (!row.directoryId || !entries.includes(row.directoryId)) continue;
+ const dir = path.join(c.data, row.directoryId);
+ const info = await lstat(dir);
+ const metadata = info.isDirectory() && !info.isSymbolicLink() ? await optionalStat(path.join(dir, "metadata.info.json")) : null;
+ if (!metadata?.isFile() || metadata.isSymbolicLink()) {
+ row.issues.push("Destination is occupied or incomplete; manual review required"); row.status = "issue";
+ } else { row.savedRecordAvailable = true; }
+ }
+ scan.counts = { discovered: scan.candidates.length, new: 0, existing: 0, issues: 0 };
+ for (const row of scan.candidates) {
+ if (row.status === "issue") scan.counts.issues++; else scan.counts[row.status]++;
+ }
+ const after = await context(paths, slug);
+ if (after.sourceToken !== c.sourceToken) throw new Error("Source configuration changed during preview; rescan");
+ return { ...scan, sourceToken: c.sourceToken };
+}
+
+// Application service, intentionally independent of React. Caller selects only
+// media names + freshness tokens returned by preview. Roots/IDs are derived
+// from stored config and fresh scanning, never accepted from request paths.
+// The eventual managed-job wrapper must provide per-channel queueing and block
+// concurrent rename/delete/config edits. Directory reservation still protects
+// against two import calls racing to publish the same new record.
+export async function importLocalMedia(paths: ImportPaths, slug: string, request: {
+ sourceToken: string; selected: readonly LocalMediaSelection[]; signal?: AbortSignal;
+ // Drain finishes the current publication; cancellation may leave a reviewable
+ // partial record. Progress observers cannot change the outcome of a write.
+ drainSignal?: AbortSignal;
+ onRecord?: (record: LocalMediaImportResult["records"][number], completed: number) => void;
+}): Promise<LocalMediaImportResult> {
+ if (!Array.isArray(request.selected) || request.selected.length > 1000
+ || request.selected.some(s => !s || typeof s.media !== "string" || typeof s.fingerprint !== "string")
+ || new Set(request.selected.map(s => s.media)).size !== request.selected.length) {
+ throw new Error("Invalid or duplicate selection");
+ }
+ const out: LocalMediaImportResult = { records: [], cancelled: false, drained: false, needsIndexUpdate: false };
+ const record = (item: LocalMediaImportResult["records"][number]) => {
+ out.records.push(item);
+ // A failed progress display must never turn a successfully published record
+ // into a failed import or cause a second attempt to publish it.
+ try { request.onRecord?.(item, out.records.length); } catch { /* observer only */ }
+ };
+ if (request.signal?.aborted) return { ...out, cancelled: true };
+ if (request.drainSignal?.aborted) return { ...out, drained: true };
+ const preview = await previewLocalMedia(paths, slug);
+ if (preview.sourceToken !== request.sourceToken) throw new Error("Source configuration changed; rescan before importing");
+ for (const selection of request.selected) {
+ if (request.signal?.aborted) { out.cancelled = true; break; }
+ if (request.drainSignal?.aborted) { out.drained = true; break; }
+ const row = preview.candidates.find(candidate => candidate.media === selection.media);
+ if (selection.preparation) {
+ if (row?.status === "existing" && row.generatedMetadata) {
+ record({media: row.media, status: "occupied", reason: "Existing local record left unchanged"}); continue;
+ }
+ try {
+ const prepared = await preparedBytes(paths, slug, {
+ sourceToken: request.sourceToken, media: selection.media,
+ sourceFingerprint: selection.preparation.sourceFingerprint,
+ details: selection.preparation.details,
+ }, request.signal);
+ if (prepared.fingerprint !== selection.fingerprint) throw new Error("Reviewed details changed; prepare again");
+ const current = await context(paths, slug);
+ if (current.sourceToken !== request.sourceToken) throw new Error("Source configuration changed");
+ request.signal?.throwIfAborted();
+ await mkdir(current.data, {recursive: false}).catch(error => {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ });
+ const committed = await commitLocalMediaRecord({dataDirectory: current.data,
+ directoryId: prepared.metadata.id, metadata: JSON.stringify(prepared.metadata),
+ transcript: prepared.transcript, reference: prepared.reference, signal: request.signal});
+ if (committed.status === "imported") out.needsIndexUpdate = true;
+ record({media: selection.media, ...committed, warnings: row?.warnings});
+ } catch {
+ record({media: selection.media, status: "failed", reason: request.signal?.aborted
+ ? "cancelled" : "Prepared recording changed or is unavailable; preview and prepare again"});
+ }
+ continue;
+ }
+ if (!row || row.fingerprint !== selection.fingerprint) {
+ record({ media: selection.media, status: "stale", reason: "Source changed or disappeared; rescan" }); continue;
+ }
+ if (row.status === "issue") {
+ record({ media: row.media, status: "issue", reason: row.issues.join("; ") }); continue;
+ }
+ if (row.status === "existing") {
+ record({ media: row.media, status: "occupied", reason: "Existing record left unchanged" }); continue;
+ }
+ try {
+ const c = await context(paths, slug);
+ if (c.sourceToken !== request.sourceToken) throw new Error("Source configuration changed; rescan");
+ const reference = { version: 1, kind: "external", sourceId: c.config.sourceId, relativePath: row.media };
+ // No writes occur in the watchdog's closure: if it times out, a late
+ // operation may still finish. Its handle always closes inside the closure,
+ // so a timeout cannot leak a descriptor or later publish a record.
+ const bytes = await onDrive(c.source, async () => {
+ const opened = await openExternalMedia({ config: c.config, reference, purpose: "inspect" });
+ if (opened.status !== "ready") throw new Error("Source media unavailable or refused");
+ try {
+ const before = await opened.handle.stat();
+ const metadata = await readLocalMediaText(c.source, row.metadata);
+ const transcript = await readLocalMediaText(c.source, row.transcript);
+ const after = await opened.handle.stat();
+ if (localMediaFingerprint(row.media, metadata, localTranscriptFingerprint(row.transcript, transcript), before) !== selection.fingerprint
+ || localMediaFingerprint(row.media, metadata, localTranscriptFingerprint(row.transcript, transcript), after) !== selection.fingerprint) {
+ throw new Error("Source changed after preview; rescan");
+ }
+ return { metadata, transcript: localTranscriptVtt(row.transcript, transcript) };
+ } finally { await opened.handle.close(); }
+ });
+ request.signal?.throwIfAborted();
+ const current = await context(paths, slug);
+ if (current.sourceToken !== request.sourceToken) throw new Error("Source configuration changed; rescan");
+ await mkdir(current.data, { recursive: false }).catch(error => {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ });
+ const committed: LocalMediaCommitResult = await commitLocalMediaRecord({
+ dataDirectory: current.data, directoryId: row.directoryId!, ...bytes, reference, signal: request.signal,
+ });
+ if (committed.status === "imported") out.needsIndexUpdate = true;
+ record({ media: row.media, ...committed, warnings: row.warnings });
+ } catch (error) {
+ record({ media: row.media, status: "failed", reason: request.signal?.aborted ? "cancelled" : "Import refused; rescan and check source/channel availability" });
+ }
+ }
+ out.cancelled = request.signal?.aborted === true;
+ return out;
+}
+
+export type LocalRecordingPreparationRequest = {
+ sourceToken: string; media: string; sourceFingerprint: string; details: LocalRecordingDetails;
+};
+
+// Read-only preparation. The returned review is not a stored draft or a grant
+// to serve media. Import repeats inspection and all source checks in its normal
+// channel job, and compares the reviewed facts before committing any text.
+async function preparedBytes(paths: ImportPaths, slug: string,
+ request: LocalRecordingPreparationRequest, signal?: AbortSignal) {
+ if (!request || typeof request.sourceToken !== "string" || typeof request.media !== "string"
+ || typeof request.sourceFingerprint !== "string") throw new Error("Invalid preparation request");
+ const details = parseLocalRecordingDetails(request.details);
+ signal?.throwIfAborted();
+ const preview = await previewLocalMedia(paths, slug);
+ const row = preview.candidates.find(item => item.media === request.media);
+ if (preview.sourceToken !== request.sourceToken || !row?.preparationFingerprint
+ || row.preparationFingerprint !== request.sourceFingerprint) throw new Error("Recording is no longer eligible; preview again");
+ const c = await context(paths, slug);
+ if (c.sourceToken !== request.sourceToken) throw new Error("Library configuration changed");
+ const reference = {version: 1 as const, kind: "external" as const, sourceId: c.config.sourceId, relativePath: row.media};
+ const result = await onDrive(c.source, async () => {
+ const opened = await openExternalMedia({config: c.config, reference, purpose: "inspect"});
+ if (opened.status !== "ready") throw new Error("Recording unavailable");
+ try {
+ const before = await opened.handle.stat();
+ if (await optionalStat(path.join(c.source, row.metadata))) throw new Error("Metadata appeared; preview again");
+ const transcript = await readLocalMediaText(c.source, row.transcript);
+ if (localMediaFingerprint(row.media, "", localTranscriptFingerprint(row.transcript, transcript), before) !== request.sourceFingerprint) throw new Error("Source changed");
+ const input = {id: localRecordingId(slug, c.config.sourceId, row.media), filename: row.media,
+ title: details.title, recordedDate: details.recordedDate};
+ // Only server configuration chooses the executable. Inspection failure
+ // never silently turns into manual preparation.
+ const metadata = details.mode === "inspect"
+ ? prepareLocalRecordingMetadata({...input, probe: await probeLocalRecording({
+ file: path.join(c.source, row.media), ffprobeBin: paths.ffprobeBin ?? "ffprobe", signal})})
+ : prepareManualLocalRecordingMetadata({...input, durationSeconds: details.durationSeconds, fileSizeBytes: before.size});
+ const after = await opened.handle.stat();
+ const named = await lstat(path.join(c.source, row.media));
+ const currentTranscript = await readLocalMediaText(c.source, row.transcript);
+ if (!named.isFile() || named.isSymbolicLink()
+ || localMediaFingerprint(row.media, "", localTranscriptFingerprint(row.transcript, currentTranscript), after) !== request.sourceFingerprint
+ || localMediaFingerprint(row.media, "", localTranscriptFingerprint(row.transcript, currentTranscript), named) !== request.sourceFingerprint
+ || await optionalStat(path.join(c.source, row.metadata))) throw new Error("Source changed during preparation");
+ return {metadata, transcript: localTranscriptVtt(row.transcript, transcript), reference,
+ fingerprint: localMediaFingerprint(row.media, JSON.stringify(metadata), localTranscriptFingerprint(row.transcript, transcript), after)};
+ } finally { await opened.handle.close(); }
+ });
+ signal?.throwIfAborted();
+ const current = await context(paths, slug);
+ if (current.sourceToken !== request.sourceToken || await optionalStat(path.join(current.data, result.metadata.id))) {
+ throw new Error("Library changed or recording already occupied; preview again");
+ }
+ return result;
+}
+
+export async function prepareLocalMediaRecording(paths: ImportPaths, slug: string,
+ request: LocalRecordingPreparationRequest) {
+ const result = await preparedBytes(paths, slug, request);
+ // Never return archive paths or the whole transcript to the form.
+ return {metadata: result.metadata, fingerprint: result.fingerprint};
+}
diff --git a/common/controller/localMediaImportJob.ts b/common/controller/localMediaImportJob.ts
@@ -0,0 +1,96 @@
+import { parseLocalRecordingDetails } from "../lib/localRecordingDetails";
+import type { Paths } from "../lib/paths";
+import { channelQueueKey } from "../lib/queueKeys";
+import { importLocalMedia, type LocalMediaPreview, type LocalMediaSelection } from "./localMediaImport";
+import { runManagedFunction, type RunManagedFunctionOpts } from "../jobs/streamCommand";
+
+export type LocalMediaJobRequest = {
+ sourceToken: string;
+ selected: readonly LocalMediaSelection[];
+ // New recordings left for a later run (selectAllNew): said in the job's log.
+ remaining?: number;
+};
+
+// One job imports at most this many recordings.
+export const LOCAL_MEDIA_IMPORT_MAX = 1000;
+
+// EVERY NEW RECORDING of a fresh preview, at most LOCAL_MEDIA_IMPORT_MAX of them:
+// the first in the preview's order (the scan's sorted file names, so a re-run
+// after an import takes the next ones), and how many new ones are left over.
+// Review fix 7 (lane/local-media): over the cap it was a generic refusal.
+export function selectAllNew(preview: LocalMediaPreview): { request: LocalMediaJobRequest; remaining: number } {
+ const all = preview.candidates
+ .filter((c) => c.status === "new" && c.fingerprint)
+ .map((c) => ({ media: c.media, fingerprint: c.fingerprint! }));
+ const selected = all.slice(0, LOCAL_MEDIA_IMPORT_MAX);
+ const remaining = all.length - selected.length;
+ return { request: { sourceToken: preview.sourceToken, selected, ...(remaining > 0 ? { remaining } : {}) }, remaining };
+}
+
+// Keep the managed job's body testable with synthetic sources, without starting
+// the application's registry or snapshot timers. The production entry point
+// below always uses runManagedFunction, including its enqueue/start guards.
+export function localMediaJobOptions(paths: Paths, slug: string, request: LocalMediaJobRequest): RunManagedFunctionOpts {
+ if (!request || typeof request.sourceToken !== "string" || !Array.isArray(request.selected)
+ || request.selected.length === 0 || request.selected.length > LOCAL_MEDIA_IMPORT_MAX
+ || request.selected.some(s => !s || typeof s.media !== "string" || typeof s.fingerprint !== "string")
+ || new Set(request.selected.map(s => s.media)).size !== request.selected.length) {
+ throw new Error("Select between 1 and 1000 distinct recordings from a fresh preview");
+ }
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug) || slug.endsWith(".")) throw new Error("Invalid channel slug");
+ // A caller must not be able to mutate a request while it waits in the queue.
+ const selected = request.selected.map(({ media, fingerprint, preparation }) => {
+ if (preparation !== undefined && (!preparation || typeof preparation.sourceFingerprint !== "string")) {
+ throw new Error("Invalid recording preparation");
+ }
+ return {media, fingerprint, ...(preparation ? {preparation: {
+ sourceFingerprint: preparation.sourceFingerprint, details: parseLocalRecordingDetails(preparation.details),
+ }} : {})};
+ });
+ const sourceToken = request.sourceToken;
+ const remaining = typeof request.remaining === "number" && Number.isSafeInteger(request.remaining) && request.remaining > 0
+ ? request.remaining : 0;
+ const leftOverLine = remaining
+ ? `${remaining} more new recording(s) were not selected (one import takes at most ${LOCAL_MEDIA_IMPORT_MAX}); import again after this one to take the next ${Math.min(remaining, LOCAL_MEDIA_IMPORT_MAX)}.`
+ : null;
+ return {
+ kind: "import-local-media",
+ queueKey: channelQueueKey(slug),
+ paths,
+ channelSlug: slug,
+ // No spec: replaying persisted names/tokens after source edits is misleading.
+ // The operator takes a new preview to retry or continue a drained batch.
+ fn: async (onLog, signal, setProgress, ctx) => {
+ setProgress({ metric: "entries", initial: 0, target: selected.length, current: 0 });
+ if (leftOverLine) onLog(leftOverLine);
+ onLog("Rechecking selected external recordings before import...");
+ const result = await importLocalMedia(paths, slug, {
+ sourceToken, selected, signal, drainSignal: ctx.drainSignal,
+ onRecord: (record, completed) => {
+ // JSON quoting prevents filenames with newlines from forging log lines.
+ // Absolute library roots never enter these progress messages.
+ onLog(JSON.stringify({ recording: record.media, status: record.status, reason: record.reason, warnings: record.warnings, incomplete: record.incomplete }));
+ setProgress({ metric: "entries", initial: 0, target: selected.length, current: completed });
+ },
+ });
+ const imported = result.records.filter(r => r.status === "imported").length;
+ const occupied = result.records.filter(r => r.status === "occupied").length;
+ const rejected = result.records.length - imported - occupied;
+ onLog(`Imported ${imported}; already occupied ${occupied}; rejected ${rejected}; unprocessed ${selected.length - result.records.length}.`);
+ if (leftOverLine) onLog(leftOverLine);
+ // What works today: the records are searchable after the next index build.
+ if (result.needsIndexUpdate) onLog("Import complete. The imported recordings are searchable after the next index build (`pnpm ops build-index`, or a site build).");
+ // The existing managed-job completion hook requests a channel snapshot,
+ // including on failure/cancellation. This job does not build/publish a site.
+ if (result.cancelled) { onLog("Import cancelled."); return; }
+ if (result.drained) onLog("Import stopped between recordings. Preview again to continue.");
+ if (rejected || result.records.some(r => r.stagingCleanupFailed)) {
+ throw new Error("Some selected recordings require review. Saved records were retained; preview again before retrying.");
+ }
+ },
+ };
+}
+
+export async function startLocalMediaImportJob(paths: Paths, slug: string, request: LocalMediaJobRequest) {
+ return runManagedFunction(localMediaJobOptions(paths, slug, request));
+}
diff --git a/common/controller/localMediaLifecycle.test.ts b/common/controller/localMediaLifecycle.test.ts
@@ -0,0 +1,123 @@
+import { test, type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import { createHash } from "node:crypto";
+import { mkdtemp, mkdir, writeFile, readFile, readdir, rm } from "node:fs/promises";
+import { execa } from "execa";
+import type { Paths } from "../lib/paths";
+import { commitLocalMediaRecord } from "../lib/localMediaCommit-server";
+import { loadExternalMediaReference } from "../lib/externalMedia-server";
+import { deleteChannel } from "./channels";
+import { cleanExtraAudioFormats } from "./cleanExtraAudioFormats";
+import { archiveTranscripts, archiveCombinedTranscripts } from "./archiveTranscripts";
+
+// Real controllers, real ZIP files, synthetic external bytes. A private marker
+// in config/reference/metadata makes accidental whole-folder export observable.
+// The original media has no corpus symlink and no saved-video managed pointer.
+async function fixture(t: TestContext) {
+ const root = await mkdtemp(path.join(tmpdir(), "external-lifecycle-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const source = path.join(root, "private-source-directory");
+ const corpus = path.join(root, "corpus");
+ const paths = {
+ transcriptsDir: corpus, channelsDir: path.join(corpus, "channels"),
+ savedVideosDir: path.join(corpus, "saved"), sitesDir: path.join(corpus, "sites"),
+ lmdbPath: path.join(corpus, "index.mdb"),
+ } as Paths;
+ const data = path.join(paths.channelsDir, "sample", "data");
+ await mkdir(data, { recursive: true }); await mkdir(source);
+ const media = "private-filename-sentinel.mp4";
+ const sourceId = "private-library-sentinel";
+ const reference = {version:1 as const,kind:"external" as const,sourceId,relativePath:media};
+ const transcript = "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nPublic transcript cue\n";
+ const metadata = JSON.stringify({id:"record1",title:"Public title",duration:3,upload_date:"20261030",webpage_url:"https://www.youtube.com/watch?v=record1",_filename:path.join(source,media)});
+ await writeFile(path.join(source,media),"original external media sentinel");
+ await writeFile(path.join(source,"original.vtt"),transcript);
+ await writeFile(path.join(source,"original.info.json"),metadata);
+ await writeFile(path.join(paths.channelsDir,"sample","config.json"),JSON.stringify({handling:"youtube",platform:"youtube",name:"Public channel",audioFormat:"mp3",localMedia:{sourceId,directory:source}}));
+ assert.equal((await commitLocalMediaRecord({dataDirectory:data,directoryId:"record1",metadata,transcript,reference})).status,"imported");
+ const video = path.join(data,"record1");
+ async function hashes() {
+ const result:Record<string,string>={};
+ for(const name of (await readdir(source)).sort()) result[name]=createHash("sha256").update(await readFile(path.join(source,name))).digest("hex");
+ return result;
+ }
+ return {root,paths,source,sourceId,media,video,reference,hashes,before:await hashes()};
+}
+
+async function inspectZip(archive: string) {
+ const listing = await execa("unzip",["-Z1",archive]);
+ const files=listing.stdout.split(/\r?\n/).filter(name=>name && !name.endsWith("/"));
+ const entries:Record<string,string>={};
+ for(const name of files) entries[name]=(await execa("unzip",["-p",archive,name])).stdout;
+ return entries;
+}
+
+for(const includeMetadata of [true,false]) {
+ test(`per-channel ZIP excludes private source/reference fields (metadata=${includeMetadata})`,async t=>{
+ const f=await fixture(t);
+ const result=await archiveTranscripts({paths:f.paths,channelSlugs:["sample"],build:{format:"zip",includeMetadata},onLog:()=>{}});
+ assert.equal(result.totalTranscripts,1,JSON.stringify(result.skipped));
+ assert.equal(result.archives.length,1);
+ const entries=await inspectZip(result.archives[0].archivePath);
+ assert.deepEqual(Object.keys(entries).sort(),["sample/channel.json","sample/record1/transcript.cues.json"]);
+ const text=JSON.stringify(entries);
+ for(const secret of [f.source,f.sourceId,f.media,"external-media.json","localMedia","_filename","original external media sentinel"]) assert.equal(text.includes(secret),false,secret);
+ assert.match(entries["sample/record1/transcript.cues.json"],/Public transcript cue/);
+ assert.equal(JSON.parse(entries["sample/channel.json"]).name,"Public channel");
+ assert.deepEqual(await loadExternalMediaReference(f.video),f.reference);
+ assert.deepEqual(await f.hashes(),f.before);
+ });
+}
+
+test("combined ZIP exposes only public manifest and transcript entries",async t=>{
+ const f=await fixture(t);
+ const result=await archiveCombinedTranscripts({paths:f.paths,channelSlugs:["sample"],build:{format:"zip"},onLog:()=>{}});
+ assert.equal(result.totalTranscripts,1,JSON.stringify(result.skipped));
+ assert.ok(result.archivePath);
+ const entries=await inspectZip(result.archivePath);
+ assert.deepEqual(Object.keys(entries).sort(),["manifest.json","sample/channel.json","sample/record1/transcript.cues.json"]);
+ const text=JSON.stringify(entries);
+ for(const secret of [f.source,f.sourceId,f.media,"external-media.json","localMedia","_filename"]) assert.equal(text.includes(secret),false,secret);
+ assert.match(text,/Public transcript cue/);
+ assert.deepEqual(await f.hashes(),f.before);
+});
+
+test("extra-audio cleanup removes managed audio without touching external files or reference",async t=>{
+ const f=await fixture(t);
+ await writeFile(path.join(f.video,"audio.mp3"),"kept managed audio");
+ await writeFile(path.join(f.video,"audio.wav"),"redundant managed audio");
+ const result=await cleanExtraAudioFormats({paths:f.paths,channelSlug:"sample",onLog:()=>{}});
+ assert.equal(result.removedFiles,1);
+ assert.equal((await readdir(f.video)).includes("audio.wav"),false);
+ assert.equal(await readFile(path.join(f.video,"audio.mp3"),"utf8"),"kept managed audio");
+ assert.deepEqual(await loadExternalMediaReference(f.video),f.reference);
+ assert.deepEqual(await f.hashes(),f.before);
+});
+
+test("deleting a channel removes corpus references but preserves external source files",async t=>{
+ const f=await fixture(t);
+ await deleteChannel(f.paths,"sample");
+ assert.deepEqual(await readdir(f.paths.channelsDir),[]);
+ assert.deepEqual(await f.hashes(),f.before);
+});
+
+// Review fix 3: a local recording is in no archive zip in slice 1 (the zip is
+// a published download, cached once per channel across public and private sites).
+test("a local recording is left out of the channel's archive zip, and the log says so",async t=>{
+ const f=await fixture(t);
+ const { prepareManualLocalRecordingMetadata } = await import("../lib/localRecordingMetadata");
+ const id="local-"+"9".repeat(32);
+ const data=path.join(f.paths.channelsDir,"sample","data");
+ assert.equal((await commitLocalMediaRecord({dataDirectory:data,directoryId:id,
+ metadata:JSON.stringify(prepareManualLocalRecordingMetadata({id,filename:"talk.mp4"})),
+ transcript:"WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nLocal only cue\n",
+ reference:{version:1,kind:"external",sourceId:f.sourceId,relativePath:"talk.mp4"}})).status,"imported");
+ const logs:string[]=[];
+ const result=await archiveTranscripts({paths:f.paths,channelSlugs:["sample"],build:{format:"zip",includeMetadata:true},onLog:l=>logs.push(l)});
+ const entries=await inspectZip(result.archives[0].archivePath);
+ assert.deepEqual(Object.keys(entries).sort(),["sample/channel.json","sample/record1/transcript.cues.json"]);
+ assert.equal(JSON.stringify(entries).includes("Local only cue"),false);
+ assert.ok(logs.some(l=>l.includes("1 local recording(s) left out of the zip")),logs.join("\n"));
+});
diff --git a/common/controller/localMediaLocation.test.ts b/common/controller/localMediaLocation.test.ts
@@ -0,0 +1,96 @@
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+// Review fix 2 (lane/local-media): a library may not lie inside the corpus, a
+// saved-video store, a channel's media tier, a storage location, or the
+// checkout. One sentence each, at configure time and at use (preview).
+// Synthetic dirs; nothing outside the temp root is touched.
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "local-media-location-"));
+const T = path.join(ROOT, "transcripts");
+const DRIVE = path.join(ROOT, "drive");
+const STORE = path.join(ROOT, "saved-videos");
+const OWN_STORE = path.join(ROOT, "own-store");
+const MEDIA = path.join(DRIVE, "media-tier", "other", "media");
+const LOCATION = path.join(ROOT, "cold");
+Object.assign(process.env, {
+ TRANSCRIPTS_DIR: T,
+ SAVED_VIDEOS_DIR: STORE,
+ SETTINGS_FILE: path.join(ROOT, "settings.json"),
+ ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"),
+});
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+writeFileSync(path.join(ROOT, "settings.json"), JSON.stringify({
+ storage: { locations: [{ id: "cold", label: "Cold drive", root: LOCATION, autoRepoint: false }], defaultLocationId: "cold" },
+}));
+const json = (file: string, value: unknown) => { mkdirSync(path.dirname(file), { recursive: true }); writeFileSync(file, JSON.stringify(value)); };
+json(path.join(T, "channels", "sample", "config.json"), { handling: "youtube", name: "Sample" });
+json(path.join(T, "channels", "other", "config.json"), { handling: "youtube", name: "Other", mediaDir: MEDIA, savedVideosDir: OWN_STORE });
+for (const d of [MEDIA, STORE, OWN_STORE, LOCATION, path.join(ROOT, "fine")]) mkdirSync(path.join(d, "lib"), { recursive: true });
+mkdirSync(path.join(T, "channels", "other", "data", "x", "lib"), { recursive: true });
+mkdirSync(path.join(T, "loose", "lib"), { recursive: true });
+
+const { getPaths } = await import("../lib/paths");
+const { libraryLocationProblem } = await import("./localMediaLocation");
+const { configureLocalMedia } = await import("./configureLocalMedia");
+const { previewLocalMedia } = await import("./localMediaImport");
+const paths = getPaths();
+
+test("each owned tree is refused with a sentence naming it; a directory outside all of them is fine", async () => {
+ const cases: Array<[string, RegExp]> = [
+ [path.join(MEDIA, "lib"), /inside channel "other"'s media directory/],
+ [path.join(OWN_STORE, "lib"), /inside channel "other"'s saved-video store/],
+ [path.join(STORE, "lib"), /inside the saved-video store/],
+ [path.join(T, "channels", "other", "data", "x", "lib"), /inside the corpus/],
+ [path.join(T, "loose", "lib"), /inside the corpus/],
+ [path.join(LOCATION, "lib"), /inside storage location "Cold drive"/],
+ [path.join(paths.monorepoRoot, "editor"), /inside the Archilyzer checkout/],
+ ];
+ for (const [dir, re] of cases) {
+ const problem = await libraryLocationProblem(paths, dir);
+ assert.ok(problem, dir);
+ assert.match(problem!, re);
+ assert.match(problem!, /; choose a directory outside it\.$/);
+ }
+ assert.equal(await libraryLocationProblem(paths, path.join(ROOT, "fine", "lib")), null);
+});
+
+test("configure refuses a misplaced library and leaves the config as it was", async () => {
+ const before = readFileSync(path.join(T, "channels", "sample", "config.json"), "utf8");
+ await assert.rejects(configureLocalMedia(paths, "sample", { sourceId: "library-1", directory: path.join(LOCATION, "lib") }),
+ /inside storage location "Cold drive"/);
+ assert.equal(readFileSync(path.join(T, "channels", "sample", "config.json"), "utf8"), before);
+});
+
+test("a misplaced library written into the config by hand is refused at preview", async () => {
+ json(path.join(T, "channels", "sample", "config.json"), { handling: "youtube", name: "Sample",
+ localMedia: { sourceId: "library-1", directory: path.join(STORE, "lib") } });
+ await assert.rejects(previewLocalMedia(paths, "sample"), /inside the saved-video store/);
+});
+
+// Re-review F1: a library that CONTAINS an owned tree is refused too.
+test("a library containing a channel's media dir, the store, a storage location or the checkout is refused", async () => {
+ const cases: Array<[string, RegExp]> = [
+ [path.join(DRIVE, "media-tier"), /contains channel "other"'s media directory/],
+ [ROOT, /contains channel "other"'s media directory/],
+ [path.dirname(paths.monorepoRoot), /contains the Archilyzer checkout/],
+ ];
+ for (const [dir, re] of cases) {
+ const problem = await libraryLocationProblem(paths, dir);
+ assert.ok(problem, dir);
+ assert.match(problem!, re);
+ assert.match(problem!, /; choose a directory that does not\.$/);
+ }
+ const { mkdirSync } = await import("node:fs");
+ const holder = path.join(ROOT, "holder");
+ mkdirSync(holder, { recursive: true });
+ const only = (root: string, what: RegExp) =>
+ libraryLocationProblem({ channelsDir: "/nonexistent-archilyzer-test/channels", savedVideosDir: root }, path.dirname(root), { channels: [] })
+ .then((p) => assert.match(p ?? "", what));
+ await only(path.join(holder, "store"), /contains the saved-video store/);
+ assert.match(await libraryLocationProblem({ channelsDir: "/nonexistent-archilyzer-test/channels" }, path.dirname(LOCATION), { channels: [] }) ?? "",
+ /contains storage location "Cold drive"/);
+});
diff --git a/common/controller/localMediaLocation.ts b/common/controller/localMediaLocation.ts
@@ -0,0 +1,75 @@
+import path from "node:path";
+import { realpath } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import { getSettings } from "../lib/settings";
+import { listChannelConfigs } from "./channels";
+
+// WHERE A LOCAL MEDIA LIBRARY MAY NOT LIVE (lane/local-media review fix 2).
+//
+// A library is a directory of recordings the archive does not own: never
+// written, moved or deleted by it. So it may not lie inside anything the
+// archive DOES own or manage — the corpus (every channel's text and its
+// in-place media), the saved-video store (the global one and a channel's own
+// `savedVideosDir`), a channel's media tier (`mediaDir`, on another drive), a
+// configured storage location (whose tree a relocation rewrites), or the
+// Archilyzer checkout — nor contain one. One sentence for each, naming it.
+//
+// Checked where the library is configured (configureLocalMedia, the New
+// channel form) AND where it is used (the import's context), since a config
+// can also arrive by hand or by `pnpm ops channel-config`. Every root is
+// optional: a caller holding only `channelsDir` gets the checks it can make.
+
+export type LibraryLocationPaths = Pick<Paths, "channelsDir"> &
+ Partial<Pick<Paths, "transcriptsDir" | "savedVideosDir" | "monorepoRoot">>;
+
+function inside(root: string, candidate: string): boolean {
+ const rel = path.relative(root, candidate);
+ return !rel || (rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
+}
+
+// The canonical form of a root: realpath when it exists (a symlinked drive
+// resolves to where its files are), else as written.
+async function canonical(dir: string): Promise<string> {
+ return realpath(dir).catch(() => path.resolve(dir));
+}
+
+/**
+ * Why `directory` may not be a library, or null. `directory` should already be
+ * canonical (realpath) — it is compared against canonical roots.
+ */
+export async function libraryLocationProblem(
+ paths: LibraryLocationPaths,
+ directory: string,
+ opts: { channels?: Array<{ slug: string; config: { mediaDir?: string; savedVideosDir?: string } }> } = {},
+): Promise<string | null> {
+ const lib = path.resolve(directory);
+ const channels = opts.channels ?? (await listChannelConfigs(paths as Paths).catch(() => []));
+ // What the archive owns, most specific first, so a sentence names the
+ // narrowest owner.
+ const owned: Array<{ what: string; root: string }> = [];
+ for (const { slug, config } of channels) {
+ if (config.mediaDir) owned.push({ what: `channel "${slug}"'s media directory`, root: await canonical(config.mediaDir) });
+ if (config.savedVideosDir) owned.push({ what: `channel "${slug}"'s saved-video store`, root: await canonical(config.savedVideosDir) });
+ }
+ if (paths.savedVideosDir) owned.push({ what: "the saved-video store", root: await canonical(paths.savedVideosDir) });
+ // The corpus root when known (getPaths() always has it); a caller holding
+ // only `channelsDir` gets that tree checked.
+ owned.push({ what: "the corpus", root: await canonical(paths.transcriptsDir ?? paths.channelsDir) });
+ let locations: Array<{ label: string; root: string }> = [];
+ try { locations = getSettings().storage?.locations ?? []; } catch { /* no settings: no locations */ }
+ for (const location of locations) {
+ if (location.root) owned.push({ what: `storage location "${location.label}"`, root: await canonical(location.root) });
+ }
+ if (paths.monorepoRoot) owned.push({ what: "the Archilyzer checkout", root: await canonical(paths.monorepoRoot) });
+ // Inside an owned tree: the scan would read the archive's own files as
+ // recordings, and a move or a clean could change them under the library.
+ for (const { what, root } of owned) {
+ if (inside(root, lib)) return `The library directory is inside ${what} (${root}); choose a directory outside it.`;
+ }
+ // CONTAINING one (re-review F1): the library is read-only, so nothing is lost,
+ // but a scan of it would offer archive-owned media as recordings.
+ for (const { what, root } of owned) {
+ if (inside(lib, root)) return `The library directory contains ${what} (${root}); choose a directory that does not.`;
+ }
+ return null;
+}
diff --git a/common/controller/localMediaPreparation.test.ts b/common/controller/localMediaPreparation.test.ts
@@ -0,0 +1,166 @@
+import { test, type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, writeFile, readFile, readdir, rm, symlink, chmod } from "node:fs/promises";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import { execFileSync } from "node:child_process";
+import { previewLocalMedia, prepareLocalMediaRecording, importLocalMedia, type LocalRecordingPreparationRequest } from "./localMediaImport";
+import { localRecordingId, parseLocalRecordingDetails } from "../lib/localRecordingDetails";
+
+async function fixture(t: TestContext, realVideo = false) {
+ const root = await mkdtemp(path.join(tmpdir(), "local-preparation-"));
+ t.after(() => rm(root, {recursive: true, force: true}));
+ const source = path.join(root, "originals");
+ const paths = {channelsDir: path.join(root, "channels"), ffprobeBin: "ffprobe"};
+ const channel = path.join(paths.channelsDir, "sample");
+ await mkdir(source); await mkdir(channel, {recursive: true});
+ const config = {handling: "youtube", localMedia: {sourceId: "library-1", directory: source}};
+ await writeFile(path.join(channel, "config.json"), JSON.stringify(config));
+ const media = "Classroom lesson.mp4";
+ const file = path.join(source, media);
+ if (realVideo) execFileSync("ffmpeg", ["-v", "error", "-f", "lavfi", "-i", "color=c=black:s=32x32:r=5", "-t", "1", "-c:v", "mpeg4", file], {timeout: 15000});
+ else await writeFile(file, "synthetic manual fixture");
+ const transcript = path.join(source, "Classroom lesson.vtt");
+ await writeFile(transcript, "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nSynthetic classroom phrase\n");
+ const sidecar = path.join(source, "Classroom lesson.info.json");
+ const preview = await previewLocalMedia(paths, "sample");
+ assert.ok(preview.candidates[0].preparationFingerprint);
+ const request: LocalRecordingPreparationRequest = {sourceToken: preview.sourceToken, media,
+ sourceFingerprint: preview.candidates[0].preparationFingerprint!, details: {mode: "manual", title: "Classroom lesson"}};
+ const selection = (review: {fingerprint: string}, input = request) => ({sourceToken: input.sourceToken,
+ selected: [{media, fingerprint: review.fingerprint, preparation: {sourceFingerprint: input.sourceFingerprint, details: input.details}}]});
+ return {root, source, paths, channel, file, transcript, sidecar, media, request, selection, config};
+}
+async function bytes(root: string) {
+ const result: Record<string, string> = {};
+ for (const name of await readdir(root)) result[name] = (await readFile(path.join(root, name))).toString("base64");
+ return result;
+}
+
+test("manual review writes nothing, then the normal importer saves local metadata and reference only", async t => {
+ const f = await fixture(t);
+ f.paths.ffprobeBin = path.join(f.root, "deliberately-absent");
+ const before = await bytes(f.source);
+ const review = await prepareLocalMediaRecording(f.paths, "sample", f.request);
+ assert.deepEqual(await readdir(f.channel), ["config.json"]);
+ assert.equal(review.metadata.duration, undefined);
+ assert.equal(review.metadata.recorded_date, undefined);
+ assert.equal(review.metadata.local_recording.inspection, "manual");
+ assert.equal(JSON.stringify(review).includes(f.root), false);
+ const result = await importLocalMedia(f.paths, "sample", f.selection(review));
+ assert.equal(result.records[0].status, "imported");
+ assert.equal(result.needsIndexUpdate, true);
+ const dest = path.join(f.channel, "data", review.metadata.id);
+ assert.deepEqual((await readdir(dest)).sort(), ["external-media.json", "metadata.info.json", "transcript.en.vtt"]);
+ assert.deepEqual(JSON.parse(await readFile(path.join(dest, "metadata.info.json"), "utf8")), review.metadata);
+ assert.equal(await readFile(path.join(dest, "transcript.en.vtt"), "utf8"), await readFile(f.transcript, "utf8"));
+ assert.deepEqual(await bytes(f.source), before);
+ const after = await previewLocalMedia(f.paths, "sample");
+ assert.equal(after.candidates[0].status, "existing");
+ assert.equal(after.candidates[0].preparationFingerprint, undefined);
+ assert.equal((await importLocalMedia(f.paths, "sample", f.selection(review))).records[0].status, "occupied");
+ assert.deepEqual(await bytes(f.source), before);
+});
+
+test("inspection measures a real MP4, rechecks during import and never changes original bytes", async t => {
+ const f = await fixture(t, true), before = await bytes(f.source);
+ f.request.details = {mode: "inspect", title: "Science class", recordedDate: "2024-02-29"};
+ const review = await prepareLocalMediaRecording(f.paths, "sample", f.request);
+ assert.ok(review.metadata.duration! > 0);
+ assert.equal(review.metadata.local_recording.durationSource, "ffprobe");
+ assert.equal(review.metadata.recorded_date, "20240229");
+ assert.equal((await importLocalMedia(f.paths, "sample", f.selection(review))).records[0].status, "imported");
+ assert.deepEqual(await bytes(f.source), before);
+});
+
+test("changed media, transcript, or newly supplied metadata refuses a reviewed import", async t => {
+ for (const change of ["media", "transcript", "metadata"]) {
+ const f = await fixture(t);
+ const review = await prepareLocalMediaRecording(f.paths, "sample", f.request);
+ if (change === "media") await writeFile(f.file, "replacement recording with different bytes");
+ else if (change === "transcript") await writeFile(f.transcript, "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nEdited cue\n");
+ else await writeFile(f.sidecar, "{}");
+ const result = await importLocalMedia(f.paths, "sample", f.selection(review));
+ assert.equal(result.records[0].status, "failed", change);
+ assert.deepEqual(await readdir(f.channel), ["config.json"]);
+ }
+});
+
+test("existing invalid metadata and missing transcripts never offer generation", async t => {
+ const f = await fixture(t);
+ await writeFile(f.sidecar, "not JSON");
+ assert.equal((await previewLocalMedia(f.paths, "sample")).candidates[0].preparationFingerprint, undefined);
+ await assert.rejects(prepareLocalMediaRecording(f.paths, "sample", f.request));
+ await rm(f.sidecar); await rm(f.transcript);
+ assert.equal((await previewLocalMedia(f.paths, "sample")).candidates[0].preparationFingerprint, undefined);
+ assert.deepEqual(await readdir(f.channel), ["config.json"]);
+});
+
+test("source links, path requests, relocation and stale configuration are refused", async t => {
+ const f = await fixture(t);
+ await assert.rejects(prepareLocalMediaRecording(f.paths, "sample", {...f.request, media: "../outside.mp4"}));
+ await assert.rejects(prepareLocalMediaRecording(f.paths, "../sample", f.request));
+ await rm(f.file); await writeFile(path.join(f.root, "outside.mp4"), "outside");
+ await symlink(path.join(f.root, "outside.mp4"), f.file);
+ await assert.rejects(prepareLocalMediaRecording(f.paths, "sample", f.request));
+ const g = await fixture(t);
+ await writeFile(path.join(g.channel, "config.json"), JSON.stringify({...g.config, localMedia: {...g.config.localMedia, sourceId: "changed"}}));
+ await assert.rejects(prepareLocalMediaRecording(g.paths, "sample", g.request));
+ await writeFile(path.join(g.channel, "config.json"), JSON.stringify(g.config));
+ await writeFile(path.join(g.channel, ".relocating.json"), JSON.stringify({target:path.join(g.root,"other","media"),scope:"media",direction:"out",phase:"copy"}));
+ await assert.rejects(prepareLocalMediaRecording(g.paths, "sample", g.request), /relocation/);
+});
+
+test("missing ffprobe fails explicitly; manual preparation and stable identity remain available", async t => {
+ const f = await fixture(t);
+ f.paths.ffprobeBin = path.join(f.root, "absent-probe");
+ await assert.rejects(prepareLocalMediaRecording(f.paths, "sample", {...f.request, details: {...f.request.details, mode: "inspect"}}), /ffprobe is unavailable/);
+ const first = await prepareLocalMediaRecording(f.paths, "sample", f.request);
+ const second = await prepareLocalMediaRecording(f.paths, "sample", {...f.request, details: {mode:"manual",title:"Changed title",durationSeconds:3,recordedDate:"2026-01-01"}});
+ assert.equal(first.metadata.id, second.metadata.id);
+ assert.notEqual(first.fingerprint, second.fingerprint);
+ assert.equal(first.metadata.id, localRecordingId("sample", "library-1", f.media));
+ assert.deepEqual(await readdir(f.channel), ["config.json"]);
+});
+
+test("modified form facts or cancelled import cannot publish the old review", async t => {
+ const f = await fixture(t);
+ const review = await prepareLocalMediaRecording(f.paths, "sample", f.request);
+ const changed = {...f.request, details: {...f.request.details, title: "Changed after review"}};
+ assert.equal((await importLocalMedia(f.paths, "sample", f.selection(review, changed))).records[0].status, "failed");
+ assert.equal((await importLocalMedia(f.paths, "sample", {...f.selection(review), signal: AbortSignal.abort()})).cancelled, true);
+ assert.deepEqual(await readdir(f.channel), ["config.json"]);
+});
+
+test("replacement during probe cannot publish or return a usable review", async t => {
+ const f = await fixture(t);
+ const executable = path.join(f.root, "replace-probe");
+ await writeFile(executable, "#!/usr/bin/env node\n" +
+ `require('fs').writeFileSync(${JSON.stringify(f.file)}, 'changed during probe');` +
+ "process.stdout.write(JSON.stringify({format:{duration:1},streams:[{codec_type:'video'}]}));\n");
+ await chmod(executable, 0o755);
+ f.paths.ffprobeBin = executable;
+ await assert.rejects(prepareLocalMediaRecording(f.paths,"sample",{...f.request,details:{...f.request.details,mode:"inspect"}}));
+ assert.deepEqual(await readdir(f.channel), ["config.json"]);
+});
+
+test("queued detail snapshots allow only intended fields and manual durations", () => {
+ const original = {mode: "manual", title: " Lesson ", durationSeconds: 4, file: "/untrusted", executable: "untrusted"};
+ const details = parseLocalRecordingDetails(original);
+ original.title = "changed";
+ assert.deepEqual(details, {mode: "manual", title: "Lesson", durationSeconds: 4});
+ for (const bad of [null, {}, {mode:"inspect",title:"Lesson",durationSeconds:4},
+ {mode:"manual",title:"Lesson",durationSeconds:-1}, {mode:"manual",title:"Lesson",recordedDate:3}]) {
+ assert.throws(() => parseLocalRecordingDetails(bad));
+ }
+});
+
+// Review fix 6: a local recording's id is unique across channels — the same
+// library id and file name in two channels are two records.
+test("localRecordingId includes the channel: same library and file in two channels, two ids", () => {
+ const a = localRecordingId("channel-a", "library-1", "talk.mp4");
+ const b = localRecordingId("channel-b", "library-1", "talk.mp4");
+ assert.notEqual(a, b);
+ assert.match(a, /^local-[0-9a-f]{32}$/);
+ assert.equal(a, localRecordingId("channel-a", "library-1", "talk.mp4"));
+});
diff --git a/common/controller/localMediaSrt.test.ts b/common/controller/localMediaSrt.test.ts
@@ -0,0 +1,77 @@
+import { test, type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, writeFile, readFile, readdir, rm } from "node:fs/promises";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import { previewLocalMedia, prepareLocalMediaRecording, importLocalMedia } from "./localMediaImport";
+import { adoptLocalMediaReference } from "./adoptLocalMediaReference";
+import { srtToVtt } from "../lib/localMediaTranscript";
+import { parseVtt } from "../lib/vtt";
+import type { Paths } from "../lib/paths";
+
+const SRT = "1\r\n00:00:01,125 --> 00:00:02,875\r\nA classroom phrase\r\nSecond line\r\n";
+async function fixture(t: TestContext, online = true) {
+ const root = await mkdtemp(path.join(tmpdir(), "local-srt-"));
+ t.after(() => rm(root, {recursive:true, force:true}));
+ const source = path.join(root, "originals"), paths = {channelsDir: path.join(root,"channels")};
+ const channel = path.join(paths.channelsDir,"sample");
+ await mkdir(source); await mkdir(channel,{recursive:true});
+ await writeFile(path.join(channel,"config.json"),JSON.stringify({handling:"youtube",localMedia:{sourceId:"library-1",directory:source}}));
+ await writeFile(path.join(source,"lesson.mp4"),"synthetic video");
+ await writeFile(path.join(source,"lesson.srt"),SRT);
+ if(online) await writeFile(path.join(source,"lesson.info.json"),JSON.stringify({id:"lesson",title:"Lesson",duration:3,upload_date:"20260101",webpage_url:"https://www.youtube.com/watch?v=lesson"}));
+ const preview = () => previewLocalMedia(paths,"sample");
+ const p = await preview();
+ const selection = {sourceToken:p.sourceToken,selected:[{media:"lesson.mp4",fingerprint:p.candidates[0].fingerprint!}]};
+ return {source,paths,channel,preview,p,selection};
+}
+test("SRT import saves canonical VTT and preserves originals; retry and verification use the same conversion", async t => {
+ const f=await fixture(t);
+ const names=await readdir(f.source);
+ assert.equal(f.p.candidates[0].transcript,"lesson.srt");
+ assert.ok(f.p.candidates[0].warnings.some(w=>w.includes("SRT")));
+ assert.equal((await importLocalMedia(f.paths,"sample",f.selection)).records[0].status,"imported");
+ const record=path.join(f.channel,"data","lesson");
+ const vtt=await readFile(path.join(record,"transcript.en.vtt"),"utf8");
+ assert.equal(vtt,srtToVtt(SRT));
+ assert.deepEqual(parseVtt(vtt),[{start:1.125,end:2.875,text:"A classroom phrase Second line"}]);
+ assert.equal(await readFile(path.join(f.source,"lesson.srt"),"utf8"),SRT);
+ assert.deepEqual(await readdir(f.source),names);
+ assert.equal((await importLocalMedia(f.paths,"sample",f.selection)).records[0].status,"occupied");
+ await rm(path.join(record,"external-media.json"));
+ const p=await f.preview();
+ const linked=await adoptLocalMediaReference(f.paths as Paths,"sample",{sourceToken:p.sourceToken,media:"lesson.mp4",fingerprint:p.candidates[0].fingerprint!},{apply:true});
+ assert.equal(linked.status,"attached");
+});
+test("SRT works with reviewed manual metadata and cannot reuse a review after source text changes", async t => {
+ for(const changed of [false,true]) {
+ const f=await fixture(t,false), row=f.p.candidates[0];
+ const details={mode:"manual" as const,title:"Classroom"};
+ const request={sourceToken:f.p.sourceToken,media:row.media,sourceFingerprint:row.preparationFingerprint!,details};
+ const review=await prepareLocalMediaRecording(f.paths,"sample",request);
+ if(changed) await writeFile(path.join(f.source,"lesson.srt"),SRT.replace("1\r\n","9\r\n"));
+ const result=await importLocalMedia(f.paths,"sample",{sourceToken:request.sourceToken,selected:[{media:row.media,fingerprint:review.fingerprint,preparation:{sourceFingerprint:request.sourceFingerprint,details}}]});
+ assert.equal(result.records[0].status,changed?"failed":"imported");
+ if(!changed) assert.equal(await readFile(path.join(f.channel,"data",review.metadata.id,"transcript.en.vtt"),"utf8"),srtToVtt(SRT));
+ else assert.deepEqual(await readdir(f.channel),["config.json"]);
+ }
+});
+test("VTT takes precedence, including invalid VTT; newly added VTT invalidates an SRT selection", async t => {
+ const f=await fixture(t);
+ await writeFile(path.join(f.source,"lesson.vtt"),"WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nChosen VTT\n");
+ const p=await f.preview();
+ assert.equal(p.candidates[0].transcript,"lesson.vtt");
+ assert.equal((await importLocalMedia(f.paths,"sample",f.selection)).records[0].status,"stale");
+ await writeFile(path.join(f.source,"lesson.vtt"),"bad VTT");
+ assert.equal((await f.preview()).candidates[0].status,"issue");
+ assert.deepEqual(await readdir(f.channel),["config.json"]);
+});
+test("malformed SRT and non-UTF8 input are review issues and cannot create a record", async t => {
+ const f=await fixture(t);
+ for(const bytes of [Buffer.from("bad subtitle"),Buffer.from([0xff,0xfe,0x31,0x00])]) {
+ await writeFile(path.join(f.source,"lesson.srt"),bytes);
+ assert.equal((await f.preview()).candidates[0].status,"issue");
+ assert.equal((await importLocalMedia(f.paths,"sample",f.selection)).needsIndexUpdate,false);
+ }
+ assert.deepEqual(await readdir(f.channel),["config.json"]);
+});
diff --git a/common/controller/localTranscriptionEligibility.test.ts b/common/controller/localTranscriptionEligibility.test.ts
@@ -0,0 +1,97 @@
+import { test, type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, writeFile, readFile, readdir, rm, symlink } from "node:fs/promises";
+import path from "node:path";
+import os from "node:os";
+import { previewLocalMedia, importLocalMedia } from "./localMediaImport";
+import { localRecordingId } from "../lib/localRecordingDetails";
+
+async function fixture(t: TestContext) {
+ const root = await mkdtemp(path.join(os.tmpdir(), "local-transcription-eligibility-"));
+ t.after(() => rm(root, {recursive:true, force:true}));
+ const source = path.join(root, "source");
+ const paths = {channelsDir:path.join(root, "channels")};
+ const channel = path.join(paths.channelsDir, "sample");
+ await mkdir(source); await mkdir(channel, {recursive:true});
+ await writeFile(path.join(channel,"config.json"), JSON.stringify({handling:"youtube",localMedia:{sourceId:"library-1",directory:source}}));
+ await writeFile(path.join(source,"lesson.mp4"),"synthetic video fixture");
+ const preview = () => previewLocalMedia(paths,"sample");
+ return {source,paths,channel,preview};
+}
+const metadata = (id="lesson") => ({id,title:"Lesson",duration:10,upload_date:"20261103",webpage_url:"https://www.youtube.com/watch?v="+id});
+
+test("missing subtitles become transcription-eligible but remain blocked for import; preview writes nothing", async t => {
+ const f=await fixture(t);
+ const before=await readFile(path.join(f.source,"lesson.mp4"));
+ const preview=await f.preview(),row=preview.candidates[0];
+ assert.ok(row.transcriptionFingerprint);
+ assert.equal(row.transcriptionNeedsDetails,true);
+ assert.equal(row.status,"issue");
+ assert.equal(row.fingerprint,undefined);
+ assert.equal(row.preparationFingerprint,undefined);
+ const result=await importLocalMedia(f.paths,"sample",{sourceToken:preview.sourceToken,selected:[{media:row.media,fingerprint:row.transcriptionFingerprint!}]});
+ assert.equal(result.records.length,1);
+ assert.equal(result.records[0].status,"stale");
+ assert.deepEqual(await readFile(path.join(f.source,"lesson.mp4")),before);
+ assert.deepEqual(await readdir(f.source),["lesson.mp4"]);
+ assert.ok(!(await readdir(f.channel)).includes("data"));
+});
+
+test("valid provider metadata is retained; metadata and media changes invalidate the eligibility token", async t => {
+ const f=await fixture(t),file=path.join(f.source,"lesson.info.json");
+ await writeFile(file,JSON.stringify(metadata()));
+ const first=(await f.preview()).candidates[0];
+ assert.ok(first.transcriptionFingerprint);
+ assert.equal(first.transcriptionNeedsDetails,undefined);
+ assert.equal(first.directoryId,"lesson");
+ await writeFile(file,JSON.stringify({...metadata(),title:"Changed"}));
+ const second=(await f.preview()).candidates[0];
+ assert.notEqual(second.transcriptionFingerprint,first.transcriptionFingerprint);
+ await writeFile(path.join(f.source,"lesson.mp4"),"changed synthetic video fixture");
+ assert.notEqual((await f.preview()).candidates[0].transcriptionFingerprint,second.transcriptionFingerprint);
+});
+
+test("existing SRT or VTT blocks generation even when empty, malformed, a directory or a symlink", async t => {
+ const f=await fixture(t);
+ for(const ext of [".vtt",".srt"]) {
+ const target=path.join(f.source,"lesson"+ext);
+ for(const text of ["","malformed subtitles"]) {
+ await writeFile(target,text);
+ assert.equal((await f.preview()).candidates[0].transcriptionFingerprint,undefined);
+ assert.equal(await readFile(target,"utf8"),text);
+ }
+ await rm(target); await mkdir(target);
+ assert.equal((await f.preview()).candidates[0].transcriptionFingerprint,undefined);
+ await rm(target,{recursive:true});
+ await symlink(path.join(f.source,"absent-subtitle"),target);
+ assert.equal((await f.preview()).candidates[0].transcriptionFingerprint,undefined);
+ await rm(target);
+ }
+ assert.ok((await f.preview()).candidates[0].transcriptionFingerprint);
+});
+
+test("invalid metadata, source media links and duplicate identities cannot qualify", async t => {
+ const f=await fixture(t),file=path.join(f.source,"lesson.info.json");
+ for(const value of ["{",JSON.stringify({...metadata(),duration:0}),JSON.stringify({...metadata(),id:"other"})]) {
+ await writeFile(file,value);
+ assert.equal((await f.preview()).candidates[0].transcriptionFingerprint,undefined);
+ }
+ await writeFile(file,JSON.stringify(metadata()));
+ await writeFile(path.join(f.source,"duplicate.mp4"),"fixture");
+ await writeFile(path.join(f.source,"duplicate.info.json"),JSON.stringify(metadata()));
+ assert.ok((await f.preview()).candidates.every(row=>!row.transcriptionFingerprint));
+ await rm(path.join(f.source,"duplicate.mp4"));
+ await rm(path.join(f.source,"lesson.mp4"));
+ await symlink(file,path.join(f.source,"lesson.mp4"));
+ assert.equal((await f.preview()).candidates[0].transcriptionFingerprint,undefined);
+});
+
+test("occupied generated and provider identities are blocked even with incomplete saved records", async t => {
+ const f=await fixture(t);
+ const id=localRecordingId("sample","library-1","lesson.mp4");
+ await mkdir(path.join(f.channel,"data",id),{recursive:true});
+ assert.equal((await f.preview()).candidates[0].transcriptionFingerprint,undefined);
+ await writeFile(path.join(f.source,"lesson.info.json"),JSON.stringify(metadata()));
+ await mkdir(path.join(f.channel,"data","lesson"));
+ assert.equal((await f.preview()).candidates[0].transcriptionFingerprint,undefined);
+});
diff --git a/common/controller/lookoutPlan.test.ts b/common/controller/lookoutPlan.test.ts
@@ -0,0 +1,375 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, rm, writeFile, readdir } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { sanitizeLookoutItem } from "../lib/lookoutSettings";
+import { metaDatesOf, planLookout, LookoutPlanRefusal } from "./lookoutPlan";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/lookoutPlan.test.ts
+//
+// The dry run over a fixture corpus (lane/lookout slice 1, acceptance a): a
+// stream whose UTC upload date is the next day, its twin upload on another
+// channel and a cut-down of it → the plan lists the stream ONCE, on the local
+// date, with both alternates. Every channel name here is invented.
+
+// The real start of an evening stream: 2026-11-04T01:20:53Z, which is
+// 2026-11-03 20:20 in New York — `upload_date` says 4 Nov, the air says 3 Nov.
+const STREAM_RELEASE = 1793755253;
+const STREAM_UPLOAD = 1793754765;
+
+// Deterministic words: a small LCG over a synthetic vocabulary, so the texts
+// have real shingles and two "transcripts" of the same speech differ the way
+// two ASR engines do (a word in ten replaced).
+function words(seed: number, n: number): string[] {
+ let x = seed >>> 0;
+ const out: string[] = [];
+ for (let i = 0; i < n; i++) {
+ x = (Math.imul(x, 1664525) + 1013904223) >>> 0;
+ out.push(`w${(x >>> 16) % 2000}`);
+ }
+ return out;
+}
+function garble(ws: string[], seed: number, every = 10): string[] {
+ return ws.map((w, i) => (i % every === seed % every ? `x${i}` : w));
+}
+function cuesOf(ws: string[], seconds: number) {
+ const per = 10;
+ const n = Math.ceil(ws.length / per);
+ const step = seconds / n;
+ return Array.from({ length: n }, (_, i) => ({
+ start: Math.round(i * step * 100) / 100,
+ end: Math.round((i + 1) * step * 100) / 100,
+ text: ws.slice(i * per, (i + 1) * per).join(" "),
+ }));
+}
+
+type VideoFixture = {
+ channel: string;
+ dir: string;
+ id?: string;
+ title: string;
+ platform: string;
+ duration: number;
+ uploadDate: string;
+ timestamp?: number;
+ releaseTimestamp?: number;
+ liveStatus?: string;
+ text?: string[];
+};
+
+async function writeVideo(channelsDir: string, v: VideoFixture): Promise<void> {
+ const dir = path.join(channelsDir, v.channel, "data", v.dir);
+ await mkdir(dir, { recursive: true });
+ const meta: Record<string, unknown> = {
+ id: v.id ?? v.dir,
+ title: v.title,
+ formats: [{ format_id: "1", url: "https://example.invalid/f" }],
+ duration: v.duration,
+ live_status: v.liveStatus ?? "not_live",
+ webpage_url: `https://example.invalid/watch/${v.dir}`,
+ upload_date: v.uploadDate,
+ };
+ if (v.timestamp !== undefined) meta.timestamp = v.timestamp;
+ if (v.releaseTimestamp !== undefined) meta.release_timestamp = v.releaseTimestamp;
+ await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(meta, null, 1));
+ if (v.text) {
+ await writeFile(
+ path.join(dir, "transcript.cues.json"),
+ JSON.stringify({
+ version: 2,
+ source: v.platform === "youtube" ? "vtt" : "whisper",
+ slug: `${v.channel}/${v.id ?? v.dir}`,
+ id: v.id ?? v.dir,
+ channelSlug: v.channel,
+ title: v.title,
+ uploadDate: v.uploadDate,
+ duration: v.duration,
+ channel: v.channel,
+ description: "",
+ platform: v.platform,
+ webpageUrl: `https://example.invalid/${v.dir}`,
+ cues: cuesOf(v.text, v.duration),
+ }),
+ );
+ }
+}
+
+async function fixture(): Promise<{ root: string; paths: Paths }> {
+ const root = await mkdtemp(path.join(os.tmpdir(), "lookout-plan-"));
+ const transcriptsDir = path.join(root, "transcripts");
+ const channelsDir = path.join(transcriptsDir, "channels");
+ const channel = async (slug: string, config: Record<string, unknown>) => {
+ await mkdir(path.join(channelsDir, slug, "data"), { recursive: true });
+ await writeFile(path.join(channelsDir, slug, "config.json"), JSON.stringify(config));
+ };
+ await channel("alpha-rumble", { name: "Alpha", handling: "transcribe", url: "https://rumble.com/c/alpha-invented" });
+ await channel("alpha-clips", { name: "Alpha Clips", handling: "youtube", url: "https://www.youtube.com/@alpha-invented" });
+ await channel("alpha-library", { name: "Library", handling: "transcribe", localMedia: { sourceId: "library-1", directory: "/mnt/recordings" } });
+
+ const stream = words(1, 6000);
+ // The stream on one channel, dated by its start.
+ await writeVideo(channelsDir, {
+ channel: "alpha-rumble",
+ dir: "v1stream",
+ id: "v0embed1",
+ title: "Election Night LIVE!",
+ platform: "rumble",
+ duration: 7200,
+ uploadDate: "20261104",
+ timestamp: STREAM_UPLOAD,
+ releaseTimestamp: STREAM_RELEASE,
+ liveStatus: "was_live",
+ text: stream,
+ });
+ // Its twin upload on another channel: the same title, a second longer,
+ // captions from another engine; uploaded the next morning.
+ await writeVideo(channelsDir, {
+ channel: "alpha-clips",
+ dir: "TwinUpload1",
+ title: "Election Night LIVE!",
+ platform: "youtube",
+ duration: 7201,
+ uploadDate: "20261104",
+ timestamp: 1793790000,
+ text: garble(stream, 3),
+ });
+ // A cut-down: twelve minutes of the stream, re-titled.
+ await writeVideo(channelsDir, {
+ channel: "alpha-clips",
+ dir: "CutDown0001",
+ title: "He SNAPPED On Air",
+ platform: "youtube",
+ duration: 720,
+ uploadDate: "20261104",
+ timestamp: 1793800000,
+ text: garble(stream.slice(2000, 2600), 7),
+ });
+ // An unrelated video in the window.
+ await writeVideo(channelsDir, {
+ channel: "alpha-clips",
+ dir: "Unrelated01",
+ title: "Something Else Entirely",
+ platform: "youtube",
+ duration: 600,
+ uploadDate: "20261105",
+ timestamp: 1793880000,
+ text: words(99, 1500),
+ });
+ // A short.
+ await writeVideo(channelsDir, {
+ channel: "alpha-clips",
+ dir: "ShortOne001",
+ title: "A Short #shorts",
+ platform: "youtube",
+ duration: 58,
+ uploadDate: "20261104",
+ timestamp: 1793810000,
+ text: words(7, 120),
+ });
+ // In the window, no transcript yet.
+ await writeVideo(channelsDir, {
+ channel: "alpha-clips",
+ dir: "NoCues00001",
+ title: "Not Transcribed",
+ platform: "youtube",
+ duration: 900,
+ uploadDate: "20261105",
+ timestamp: 1793870000,
+ });
+ // The UTC trap the other way: 2026-11-03T04:30Z is 2 Nov in New York —
+ // `upload_date` puts it inside a 3–5 Nov window, the air date does not.
+ await writeVideo(channelsDir, {
+ channel: "alpha-rumble",
+ dir: "v1latenight",
+ title: "Late Night",
+ platform: "rumble",
+ duration: 1200,
+ uploadDate: "20261103",
+ timestamp: 1793680200,
+ text: words(55, 2000),
+ });
+ // Long before the window.
+ await writeVideo(channelsDir, {
+ channel: "alpha-rumble",
+ dir: "v1old",
+ title: "Old",
+ platform: "rumble",
+ duration: 1200,
+ uploadDate: "20260101",
+ timestamp: 1767268800,
+ text: words(56, 2000),
+ });
+ return { root, paths: { transcriptsDir, channelsDir } as Paths };
+}
+
+function lookout(over: Record<string, unknown> = {}) {
+ const item = sanitizeLookoutItem({
+ id: "alpha-week",
+ channels: ["alpha-rumble", "alpha-clips"],
+ days: 3,
+ timeZone: "America/New_York",
+ ...over,
+ });
+ assert.ok(item);
+ return item;
+}
+
+test("the stream is listed once, on its local date, with its twin and its cut-down", async () => {
+ const { root, paths } = await fixture();
+ try {
+ const plan = await planLookout(paths, lookout(), { until: "2026-11-05" });
+ assert.deepEqual(plan.refused, []);
+ assert.deepEqual(plan.window, { from: "2026-11-03", to: "2026-11-05", days: 3, timeZone: "America/New_York" });
+ const keys = plan.read.map((r) => `${r.channel}/${r.video}`);
+ assert.deepEqual(keys, ["alpha-rumble/v1stream", "alpha-clips/Unrelated01"]);
+ const s = plan.read[0]!;
+ assert.equal(s.airDate, "2026-11-03", "the air date in New York, not the UTC upload date");
+ assert.equal(s.dateSource, "release_timestamp");
+ assert.equal(s.airAt, "2026-11-04T01:20:53.000Z");
+ assert.equal(s.id, "v0embed1", "the record's id beside its directory");
+ assert.deepEqual(
+ s.folded.map((f) => [`${f.channel}/${f.video}`, f.reason]),
+ [
+ ["alpha-clips/TwinUpload1", "duplicate-upload"],
+ ["alpha-clips/CutDown0001", "covered-by-stream"],
+ ],
+ );
+ assert.equal(s.folded[0]!.titleMatch, true);
+ assert.ok(s.folded[1]!.score >= 0.4, `cut-down share ${s.folded[1]!.score}`);
+ assert.equal(s.folded[0]!.airDate, "2026-11-04");
+ assert.equal(plan.counts.inWindow, 5, "stream, twin, cut-down, unrelated, short — not the late-night one");
+ assert.equal(plan.counts.noTranscript, 1);
+ assert.equal(plan.counts.underMinSeconds, 1);
+ assert.equal(plan.counts.qualified, 4);
+ assert.equal(plan.counts.duplicateUploads, 1);
+ assert.equal(plan.counts.coveredByStream, 1);
+ assert.equal(plan.counts.recordings, 2);
+ assert.equal(plan.counts.read, 2);
+ assert.equal(plan.counts.skippedForCap, 0);
+ assert.deepEqual(
+ plan.skipped.map((k) => [k.video, k.reason]),
+ [
+ ["ShortOne001", "under-min-seconds"],
+ ["NoCues00001", "no-transcript"],
+ ],
+ );
+ const bare = plan.skipped.find((k) => k.video === "NoCues00001")!;
+ assert.equal(bare.title, "Not Transcribed", "named from its metadata");
+ assert.equal(bare.url, "https://example.invalid/watch/NoCues00001");
+ assert.ok(!keys.includes("alpha-rumble/v1latenight"), "aired 2 Nov in New York");
+ assert.ok(s.chunks > 1, "a two-hour stream is several chunks");
+ assert.equal(plan.estimate.readCalls, plan.read.reduce((n, r) => n + r.chunks, 0));
+ assert.equal(plan.estimate.secondsPerCall, null, "no run measured yet");
+ // Nothing was written: the corpus holds exactly what the fixture put there.
+ assert.deepEqual((await readdir(paths.transcriptsDir)).sort(), ["channels"]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("in UTC the late-night video is in the window and the stream moves to 4 Nov", async () => {
+ const { root, paths } = await fixture();
+ try {
+ const plan = await planLookout(paths, lookout({ timeZone: "UTC" }), { until: "2026-11-05" });
+ const byKey = new Map(plan.read.map((r) => [`${r.channel}/${r.video}`, r]));
+ assert.equal(byKey.get("alpha-rumble/v1stream")?.airDate, "2026-11-04");
+ assert.equal(byKey.get("alpha-rumble/v1latenight")?.airDate, "2026-11-03");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("the cap reads the longest recordings and lists the rest with what folded into them", async () => {
+ const { root, paths } = await fixture();
+ try {
+ const plan = await planLookout(paths, lookout(), { until: "2026-11-05", maxVideos: 1 });
+ assert.deepEqual(plan.read.map((r) => r.video), ["v1stream"]);
+ assert.equal(plan.counts.skippedForCap, 1);
+ const cap = plan.skipped.find((k) => k.reason === "cap");
+ assert.equal(cap?.video, "Unrelated01");
+ assert.deepEqual(cap?.folded, []);
+ assert.ok((cap?.chunks ?? 0) >= 1);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a local library and a slug the archive does not hold are refused by name; the rest is read", async () => {
+ const { root, paths } = await fixture();
+ try {
+ const plan = await planLookout(
+ paths,
+ lookout({ channels: ["alpha-library", "remote-only-invented", "alpha-rumble"] }),
+ { until: "2026-11-05" },
+ );
+ assert.deepEqual(
+ plan.refused.map((r) => r.channel),
+ ["alpha-library", "remote-only-invented"],
+ );
+ assert.match(plan.refused[0]!.reason, /local media library/);
+ assert.match(plan.refused[1]!.reason, /remote site/);
+ assert.deepEqual(plan.read.map((r) => r.video), ["v1stream"]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a directory unchanged since before the window is listed, not opened", async () => {
+ const { root, paths } = await fixture();
+ try {
+ // Every fixture directory was made just now; a window years later starts
+ // after all of their ctimes, so none can hold a video aired in it.
+ const plan = await planLookout(paths, lookout(), { until: "2031-01-10" });
+ assert.equal(plan.counts.scanned, 8);
+ assert.equal(plan.counts.examined, 0);
+ assert.equal(plan.counts.inWindow, 0);
+ const now = await planLookout(paths, lookout(), { until: "2026-11-05" });
+ assert.equal(now.counts.examined, 8);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a lookout with no channels is refused", async () => {
+ const { root, paths } = await fixture();
+ try {
+ await assert.rejects(planLookout(paths, lookout({ channels: [] })), LookoutPlanRefusal);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("metaDatesOf reads the scalars wherever yt-dlp put them", () => {
+ // YouTube's order: upload_date then timestamp, near the end; a comment's
+ // nested timestamp earlier is not taken, nor a storyboard fragment's duration.
+ const yt =
+ '{"id": "a", "formats": [{"format_id": "sb0", "fragments": [{"url": "u", "duration": 496.98}, {"url": "u", "duration": 250.02}]}], ' +
+ '"comments": [{"timestamp": 1600000000}], "duration": 747, "live_status": "not_live", "webpage_url": "https://example.invalid/a", ' +
+ '"upload_date": "20261106", "timestamp": 1793993883, "is_live": false}';
+ assert.deepEqual(metaDatesOf(yt), {
+ releaseTimestamp: null,
+ timestamp: 1793993883,
+ uploadDate: "20261106",
+ liveStatus: "not_live",
+ duration: 747,
+ title: null,
+ webpageUrl: "https://example.invalid/a",
+ });
+ // Rumble's order: timestamp early, release_timestamp later, upload_date last.
+ const rumble =
+ '{"id": "v", "title": "She said \\"no\\" \\u2014 caf\u00c3\u00a9", "timestamp": 1793754765, "duration": 12970, "live_status": "was_live", ' +
+ '"release_timestamp": 1793755253, "upload_date": "20261104"}';
+ assert.deepEqual(metaDatesOf(rumble), {
+ releaseTimestamp: 1793755253,
+ timestamp: 1793754765,
+ uploadDate: "20261104",
+ liveStatus: "was_live",
+ duration: 12970,
+ // Escapes decoded, and the file's UTF-8 bytes (a string argument stands for them, one char a byte).
+ title: 'She said "no" — café',
+ webpageUrl: null,
+ });
+});
diff --git a/common/controller/lookoutPlan.ts b/common/controller/lookoutPlan.ts
@@ -0,0 +1,522 @@
+// WHAT A LOOKOUT WOULD READ — stages 1 and 2 of a lookout run, with no model
+// (lane/lookout slice 1). `pnpm ops lookout-run {"id", "dryRun": true}` answers
+// this; the run itself (slice 2) reads exactly the `read` list it returns.
+//
+// Stage 1, select: every video of the lookout's channels whose AIR date
+// (lib/lookout.ts airDateOf: `release_timestamp`, else `timestamp`, in the
+// lookout's zone) falls in the window. A video with no transcript yet is listed
+// and not read; one under `minSeconds` is listed and not read.
+// Stage 2, fold and cap: duplicate uploads and a stream's cut-downs are folded
+// into one recording (lib/lookout.ts foldRecordings); then the longest
+// `maxVideos` recordings are read and every other one is listed as skipped for
+// the cap — with what was folded into it.
+//
+// READS ONLY TEXT, WRITES NOTHING. Per channel: `data/` listed, each video's
+// transcript.cues.json HEAD (its UTC upload date and duration), and for the
+// few within two days of the window its metadata.info.json (the timestamps)
+// and its whole cues (the text the folding compares). Behind the text guard
+// (lib/channelMedia.ts): a channel whose text cannot be read is refused by
+// name, never read as empty. No network, no model.
+//
+// REFUSED BY NAME in v1: a local media library channel, and a slug this
+// archive does not hold (a channel only on a remote site).
+
+import { open as openFile, readFile, stat } from "node:fs/promises";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { assertChannelTextReadable } from "../lib/channelMedia";
+import { mapConcurrent } from "../lib/concurrency";
+import { comparisonText, shingles } from "../lib/duplicates";
+import { LOCAL_RECORDING_ID_RE } from "../lib/localMedia";
+import {
+ LOOKOUT_SHINGLE_SIZE,
+ addDays,
+ airDateOf,
+ foldRecordings,
+ inWindow,
+ isoOfUploadDate,
+ lookoutWindow,
+ type AirDate,
+ type DedupeVideo,
+ type LookoutPlan,
+ type LookoutPlanFolded,
+ type LookoutPlanRead,
+ type LookoutPlanSkipped,
+ type LookoutPlanVideo,
+ type LookoutWindow,
+} from "../lib/lookout";
+import type { LookoutItem } from "../lib/lookoutSettings";
+import { measuredSecondsPerCall } from "../lib/lookoutStore";
+import { CHUNK_CHARS, chunksOf } from "../lib/report/draft/tasks/sweep-pipeline";
+import type { Cue } from "../lib/vtt";
+import { CUES_JSON_FILENAME } from "../lib/videoStatus";
+import { readChannelConfig } from "./channels";
+import { heldVideoIds } from "./videoCues";
+
+export type LookoutPlanOptions = {
+ /** Override the lookout's `days` for this plan. */
+ days?: number;
+ /** Override the lookout's `maxVideos` for this plan. */
+ maxVideos?: number;
+ /** The window's last day (YYYY-MM-DD); default today in the lookout's zone. */
+ until?: string;
+ now?: Date;
+ /** Files read at once (default 32). */
+ concurrency?: number;
+};
+
+export class LookoutPlanRefusal extends Error {}
+
+const META_FILENAME = "metadata.info.json";
+const CUES_HEAD_BYTES = 16 * 1024;
+const META_TAIL_BYTES = 16 * 1024;
+// A video whose UTC upload date is this many days outside the window cannot
+// air inside it (the zone moves a date by one; a stream's start precedes its
+// upload by hours) and is not read further.
+const PREFILTER_SLACK_DAYS = 2;
+
+// THE DIRECTORY'S ctime, FIRST. A big channel holds thousands of video
+// directories and a lookout wants a week of them; opening every one's cues is
+// ~1 ms a file (23,516 directories: 28 s, measured 11 Nov), a stat is a
+// seventh of that. A video that aired in the window got its transcript after
+// it aired, and writing transcript.cues.json — created or renamed into place —
+// sets its directory's ctime, which no copy or `touch` can set back. So a
+// directory whose ctime is before the window (less the slack) cannot hold a
+// video that aired in it with a transcript, and is not opened. A bulk pass that
+// touches every directory only makes this slower, never wrong. A video with no
+// transcript yet is listed only if its directory changed in that time too.
+const CTIME_SLACK_MS = PREFILTER_SLACK_DAYS * 86_400_000 + 14 * 3_600_000;
+
+async function readHead(file: string, bytes: number): Promise<string | null> {
+ let fh;
+ try {
+ fh = await openFile(file, "r");
+ const buf = Buffer.allocUnsafe(bytes);
+ const { bytesRead } = await fh.read(buf, 0, bytes, 0);
+ return buf.toString("latin1", 0, bytesRead);
+ } catch {
+ return null;
+ } finally {
+ await fh?.close().catch(() => {});
+ }
+}
+
+async function readTail(file: string, bytes: number): Promise<string | null> {
+ let fh;
+ try {
+ fh = await openFile(file, "r");
+ const { size } = await fh.stat();
+ const len = Math.min(bytes, size);
+ const buf = Buffer.allocUnsafe(len);
+ await fh.read(buf, 0, len, size - len);
+ return buf.toString("latin1");
+ } catch {
+ return null;
+ } finally {
+ await fh?.close().catch(() => {});
+ }
+}
+
+const num = (s: string | undefined): number | null => {
+ if (s === undefined) return null;
+ const n = Number(s);
+ return Number.isFinite(n) ? n : null;
+};
+
+function lastMatch(text: string, re: RegExp): RegExpExecArray | null {
+ let last: RegExpExecArray | null = null;
+ for (const m of text.matchAll(re)) last = m as RegExpExecArray;
+ return last;
+}
+
+export type MetaDates = {
+ releaseTimestamp: number | null;
+ timestamp: number | null;
+ uploadDate: string | null;
+ liveStatus: string | null;
+ duration: number | null;
+ /** The record's title and page URL — what a video with no transcript is listed by. */
+ title: string | null;
+ webpageUrl: string | null;
+};
+
+// The JSON string after the first `"<key>":` in `buf`, decoded (escapes and
+// UTF-8); null when it is absent, not a string, or longer than `max` bytes.
+function stringOf(buf: Buffer, key: string, max = 4096): string | null {
+ const at = buf.indexOf(`"${key}":`, 0, "latin1");
+ if (at < 0) return null;
+ let i = at + key.length + 3;
+ while (i < buf.length && (buf[i] === 0x20 || buf[i] === 0x0a || buf[i] === 0x0d || buf[i] === 0x09)) i++;
+ if (buf[i] !== 0x22) return null;
+ const end = Math.min(buf.length, i + 1 + max);
+ for (let j = i + 1; j < end; j++) {
+ if (buf[j] === 0x5c) j++;
+ else if (buf[j] === 0x22) {
+ try {
+ const v: unknown = JSON.parse(buf.toString("utf8", i, j + 1));
+ return typeof v === "string" && v.trim() ? v : null;
+ } catch {
+ return null;
+ }
+ }
+ }
+ return null;
+}
+
+// The value after `"<key>":` at byte `at` of `buf` (whitespace skipped): a
+// number's digits, or a string's contents — never more than 64 bytes.
+function valueAt(buf: Buffer, at: number, key: string): string | null {
+ let i = at + key.length + 3;
+ while (i < buf.length && (buf[i] === 0x20 || buf[i] === 0x0a || buf[i] === 0x0d || buf[i] === 0x09)) i++;
+ const quoted = buf[i] === 0x22;
+ if (quoted) i++;
+ const end = Math.min(buf.length, i + 64);
+ let j = i;
+ while (j < end && (quoted ? buf[j] !== 0x22 : /[0-9.a-z_]/.test(String.fromCharCode(buf[j]!)))) j++;
+ return j > i ? buf.toString("latin1", i, j) : null;
+}
+
+function first(buf: Buffer, key: string): string | null {
+ const at = buf.indexOf(`"${key}":`, 0, "latin1");
+ return at < 0 ? null : valueAt(buf, at, key);
+}
+
+function last(buf: Buffer, key: string, before = buf.length): { at: number; value: string | null } | null {
+ const at = buf.lastIndexOf(`"${key}":`, before, "latin1");
+ return at < 0 ? null : { at, value: valueAt(buf, at, key) };
+}
+
+/**
+ * The dating fields of a metadata.info.json, found by byte search — a YouTube
+ * record is megabytes of formats and caption URLs, and only these five scalars
+ * (and the title and page URL, two short strings) are wanted, so the file is
+ * never decoded whole or parsed. `release_timestamp` is
+ * taken wherever it is (no nested object carries one); `duration` is the last
+ * before `upload_date` (formats' fragments carry their own); `timestamp` is the one
+ * right after the last `upload_date` (yt-dlp's top-level order) when it is
+ * there, else the last in the file; airDateOf then refuses any timestamp more
+ * than two days from `upload_date`.
+ */
+export function metaDatesOf(input: Buffer | string): MetaDates {
+ const buf = typeof input === "string" ? Buffer.from(input, "latin1") : input;
+ const upload = last(buf, "upload_date");
+ let timestamp: string | null = null;
+ if (upload) {
+ const next = buf.indexOf('"timestamp":', upload.at, "latin1");
+ // Adjacent: only the upload date's value and a comma lie between them.
+ if (next > 0 && next - upload.at < 40) timestamp = valueAt(buf, next, "timestamp");
+ }
+ timestamp ??= last(buf, "timestamp")?.value ?? null;
+ const uploadDate = upload?.value && /^\d{8}$/.test(upload.value) ? upload.value : null;
+ const live = first(buf, "live_status");
+ // The record's own duration, not a format's: a YouTube storyboard format
+ // lists `"fragments": [{"duration": …}]` long before the top-level key, so
+ // the first in the file can be one sheet's seconds. The top-level one is the
+ // last before `upload_date`; with no upload date, the last in the file.
+ const duration = (upload ? last(buf, "duration", upload.at) : last(buf, "duration"))?.value ?? first(buf, "duration");
+ return {
+ releaseTimestamp: num(first(buf, "release_timestamp") ?? undefined),
+ timestamp: num(timestamp ?? undefined),
+ uploadDate,
+ liveStatus: live && /^[a-z_]+$/.test(live) ? live : null,
+ duration: num(duration ?? undefined),
+ // yt-dlp writes `id` then `title` first, before any nested object; the
+ // page URL has no nested namesake (`webpage_url_basename` is another key).
+ title: stringOf(buf, "title"),
+ webpageUrl: stringOf(buf, "webpage_url"),
+ };
+}
+
+type Scanned = {
+ channel: string;
+ video: string;
+ dir: string;
+ hasCues: boolean;
+ headUploadDate: string | null;
+ headDuration: number | null;
+};
+
+async function scanVideo(channel: string, dataDir: string, video: string): Promise<Scanned> {
+ const dir = path.join(dataDir, video);
+ const head = await readHead(path.join(dir, CUES_JSON_FILENAME), CUES_HEAD_BYTES);
+ if (head !== null) {
+ return {
+ channel,
+ video,
+ dir,
+ hasCues: true,
+ headUploadDate: /"uploadDate":\s*"(\d{8})"/.exec(head)?.[1] ?? null,
+ headDuration: num(/"duration":\s*(\d+(?:\.\d+)?)/.exec(head)?.[1]),
+ };
+ }
+ // No transcript: its upload date from the metadata's tail, where yt-dlp
+ // writes it (controller/recencyIndex.ts measured 99.8 %).
+ const tail = await readTail(path.join(dir, META_FILENAME), META_TAIL_BYTES);
+ return {
+ channel,
+ video,
+ dir,
+ hasCues: false,
+ headUploadDate: tail ? (lastMatch(tail, /"upload_date":\s*"(\d{8})"/g)?.[1] ?? null) : null,
+ headDuration: null,
+ };
+}
+
+type Cand = Scanned & {
+ air: AirDate;
+ meta: MetaDates | null;
+};
+
+type Loaded = {
+ video: LookoutPlanVideo;
+ cues: Cue[];
+ chars: number;
+ chunks: number;
+ shingles: Set<string>;
+};
+
+function cueLines(cues: readonly Cue[]): [number, string][] {
+ return cues.filter((c) => c.text.trim()).map((c) => [Math.floor(c.start), c.text.trim()] as [number, string]);
+}
+
+const NOT_FINISHED = new Set(["is_live", "is_upcoming"]);
+
+/**
+ * The plan for one lookout: what it would read, what it would not and why,
+ * and the estimate. Writes nothing.
+ */
+export async function planLookout(
+ paths: Paths,
+ item: LookoutItem,
+ opts: LookoutPlanOptions = {},
+): Promise<LookoutPlan> {
+ const days = opts.days ?? item.days;
+ const maxVideos = opts.maxVideos ?? item.maxVideos;
+ const window: LookoutWindow = lookoutWindow({ days, timeZone: item.timeZone, until: opts.until, now: opts.now });
+ const limit = opts.concurrency ?? 32;
+ const warnings: string[] = [];
+ const refused: LookoutPlan["refused"] = [];
+ if (item.channels.length === 0) throw new LookoutPlanRefusal(`lookout "${item.id}" names no channels`);
+
+ // ─── Stage 1: select ───
+ const scanned: Scanned[] = [];
+ let listed = 0;
+ for (const channel of item.channels) {
+ const config = await readChannelConfig(paths, channel);
+ if (!config) {
+ refused.push({ channel, reason: "not a channel this archive holds (a channel only on a remote site is not read in v1)" });
+ continue;
+ }
+ if (config.localMedia && !config.url?.trim()) {
+ refused.push({ channel, reason: "a local media library channel (not read in v1)" });
+ continue;
+ }
+ let dataDir: string;
+ try {
+ dataDir = (await assertChannelTextReadable(paths, channel, config)).dataDir;
+ } catch (err) {
+ refused.push({ channel, reason: (err as Error).message });
+ continue;
+ }
+ const videos = [...(await heldVideoIds(dataDir))].sort();
+ listed += videos.length;
+ const since = Date.parse(`${window.from}T00:00:00Z`) - CTIME_SLACK_MS;
+ const changed = await mapConcurrent(videos, limit, (v) =>
+ stat(path.join(dataDir, v)).then(
+ (st) => st.ctimeMs >= since,
+ () => false,
+ ),
+ );
+ const recent = videos.filter((_, i) => changed[i]);
+ scanned.push(...(await mapConcurrent(recent, limit, (v) => scanVideo(channel, dataDir, v))));
+ }
+
+ const lo = addDays(window.from, -PREFILTER_SLACK_DAYS);
+ const hi = addDays(window.to, PREFILTER_SLACK_DAYS);
+ const near = scanned.filter((s) => {
+ const d = isoOfUploadDate(s.headUploadDate);
+ return d === null || (d >= lo && d <= hi);
+ });
+ // A YouTube record's metadata is ~10 MB: a few at a time, never 32 at once
+ // in the editor's heap.
+ const dated = await mapConcurrent(near, Math.min(limit, 4), async (s): Promise<Cand | null> => {
+ let meta: MetaDates | null = null;
+ try {
+ meta = metaDatesOf(await readFile(path.join(s.dir, META_FILENAME)));
+ } catch {
+ meta = null;
+ }
+ const air = airDateOf(
+ {
+ releaseTimestamp: meta?.releaseTimestamp,
+ timestamp: meta?.timestamp,
+ uploadDate: meta?.uploadDate ?? s.headUploadDate,
+ },
+ window.timeZone,
+ );
+ return air && inWindow(air.date, window) ? { ...s, air, meta } : null;
+ });
+ const inWin = dated.filter((c): c is Cand => c !== null);
+
+ const skipped: LookoutPlanSkipped[] = [];
+ const brief = (c: Cand, over: Partial<LookoutPlanVideo> = {}): LookoutPlanVideo => ({
+ channel: c.channel,
+ video: c.video,
+ id: c.video,
+ // From the metadata: all a video with no transcript has to be named by.
+ title: c.meta?.title ?? "",
+ platform: "",
+ airDate: c.air.date,
+ airAt: c.air.at,
+ dateSource: c.air.source,
+ duration: c.headDuration ?? c.meta?.duration ?? null,
+ url: c.meta?.webpageUrl ?? null,
+ ...over,
+ });
+
+ // The transcripts of what is in the window: each read whole, once.
+ const loaded = new Map<string, Loaded>();
+ const withCues = inWin.filter((c) => c.hasCues);
+ const loads = await mapConcurrent(withCues, Math.min(limit, 8), async (c) => {
+ let doc: Record<string, unknown> | null = null;
+ try {
+ doc = JSON.parse(await readFile(path.join(c.dir, CUES_JSON_FILENAME), "utf8")) as Record<string, unknown>;
+ } catch {
+ warnings.push(`${c.channel}/${c.video}: transcript.cues.json is not readable JSON — treated as no transcript`);
+ }
+ return { c, doc };
+ });
+ let underMin = 0;
+ let other = 0;
+ let noTranscript = 0;
+ for (const c of inWin) {
+ if (!c.hasCues) {
+ noTranscript++;
+ skipped.push({ ...brief(c), reason: "no-transcript" });
+ }
+ }
+ for (const { c, doc } of loads) {
+ if (!doc) {
+ noTranscript++;
+ skipped.push({ ...brief(c), reason: "no-transcript" });
+ continue;
+ }
+ const cues = (Array.isArray(doc.cues) ? doc.cues : []).filter(
+ (x): x is Cue => !!x && typeof (x as Cue).start === "number" && typeof (x as Cue).text === "string",
+ );
+ const lastEnd = cues.length ? Math.round(cues[cues.length - 1]!.end) : null;
+ const duration = (typeof doc.duration === "number" && doc.duration > 0 ? doc.duration : null) ?? c.meta?.duration ?? lastEnd;
+ const video = brief(c, {
+ id: typeof doc.id === "string" ? doc.id : c.video,
+ title: typeof doc.title === "string" && doc.title ? doc.title : (c.meta?.title ?? ""),
+ platform: typeof doc.platform === "string" ? doc.platform : "",
+ duration,
+ url: typeof doc.webpageUrl === "string" && doc.webpageUrl ? doc.webpageUrl : (c.meta?.webpageUrl ?? null),
+ });
+ if (video.platform === "local" || LOCAL_RECORDING_ID_RE.test(video.id)) {
+ other++;
+ skipped.push({ ...video, reason: "local-recording" });
+ continue;
+ }
+ if (c.meta?.liveStatus && NOT_FINISHED.has(c.meta.liveStatus)) {
+ other++;
+ skipped.push({ ...video, reason: "not-finished" });
+ continue;
+ }
+ if (duration !== null && duration < item.minSeconds) {
+ underMin++;
+ skipped.push({ ...video, reason: "under-min-seconds" });
+ continue;
+ }
+ const chars = cues.reduce((s, x) => s + x.text.length, 0);
+ loaded.set(`${c.channel}/${c.video}`, {
+ video,
+ cues,
+ chars,
+ chunks: chunksOf(cueLines(cues), CHUNK_CHARS).length,
+ shingles: shingles(comparisonText(cues), LOOKOUT_SHINGLE_SIZE),
+ });
+ }
+
+ // ─── Stage 2: fold, then cap ───
+ const dedupe: DedupeVideo[] = [...loaded.entries()].map(([key, l]) => ({
+ key,
+ title: l.video.title,
+ platform: l.video.platform,
+ duration: l.video.duration,
+ airAt: l.video.airAt ?? l.video.airDate,
+ shingles: l.shingles,
+ }));
+ const groups = foldRecordings(dedupe);
+ const foldedOf = (keys: ReturnType<typeof foldRecordings>[number]["folded"]): LookoutPlanFolded[] =>
+ keys.map(({ key, ...rest }) => ({ ...loaded.get(key)!.video, ...rest }));
+ const read: LookoutPlanRead[] = [];
+ let duplicateUploads = 0;
+ let coveredByStream = 0;
+ let capped = 0;
+ for (const g of groups) {
+ for (const f of g.folded) {
+ if (f.reason === "duplicate-upload") duplicateUploads++;
+ else coveredByStream++;
+ }
+ const p = loaded.get(g.primary)!;
+ if (read.length < maxVideos) {
+ read.push({ ...p.video, chars: p.chars, chunks: p.chunks, folded: foldedOf(g.folded) });
+ } else {
+ capped++;
+ skipped.push({ ...p.video, reason: "cap", chunks: p.chunks, folded: foldedOf(g.folded) });
+ }
+ }
+
+ const readCalls = read.reduce((s, r) => s + r.chunks, 0);
+ const measured = await measuredSecondsPerCall(paths, item.id).catch(() => null);
+ const order: Record<string, number> = { cap: 0, "under-min-seconds": 1, "no-transcript": 2, "not-finished": 3, "local-recording": 4 };
+ skipped.sort(
+ (a, b) =>
+ order[a.reason]! - order[b.reason]! ||
+ (a.airDate < b.airDate ? -1 : a.airDate > b.airDate ? 1 : 0) ||
+ (`${a.channel}/${a.video}` < `${b.channel}/${b.video}` ? -1 : 1),
+ );
+ const datedByUploadDate = inWin.filter((c) => c.air.source === "upload_date").length;
+ if (datedByUploadDate) {
+ warnings.push(`${datedByUploadDate} video(s) in the window carry no timestamp: dated by their UTC upload_date, which may be a day off`);
+ }
+
+ return {
+ version: 1,
+ lookout: { id: item.id, label: item.label },
+ channels: item.channels,
+ refused,
+ window,
+ minSeconds: item.minSeconds,
+ maxVideos,
+ generatedAt: (opts.now ?? new Date()).toISOString(),
+ counts: {
+ scanned: listed,
+ examined: scanned.length,
+ inWindow: inWin.length - noTranscript,
+ noTranscript,
+ underMinSeconds: underMin,
+ qualified: loaded.size,
+ duplicateUploads,
+ coveredByStream,
+ recordings: groups.length,
+ read: read.length,
+ skippedForCap: capped,
+ otherSkipped: other,
+ datedByUploadDate,
+ },
+ read,
+ skipped,
+ estimate: {
+ readCalls,
+ secondsPerCall: measured ? Math.round(measured.secondsPerCall * 10) / 10 : null,
+ seconds: measured ? Math.round(readCalls * measured.secondsPerCall) : null,
+ basis: measured
+ ? `${measured.calls} calls over the last ${measured.runs} run(s); grouping calls (a few) not included`
+ : "no run has been measured yet: the first run records its seconds per call",
+ },
+ warnings,
+ };
+}
+
diff --git a/common/controller/refreshVideoMetadata.ts b/common/controller/refreshVideoMetadata.ts
@@ -43,6 +43,7 @@
// The job around it (queue, kind, refusals) is refreshVideoMetadataJob.ts;
// this module needs no registry, so a test drives it with a stub runner.
+import { localMediaMetadataRefusal } from "../lib/localMedia";
import path from "node:path";
import { readFile, stat } from "node:fs/promises";
import {
@@ -123,6 +124,9 @@ export async function resolveRefreshTarget(
if (!(await isDirectory(videoDir))) {
return { ok: false, error: notFetchedRefusal(videoId, slug) };
}
+ // A local media record has no source to read metadata from (review fix 5).
+ const localRefusal = localMediaMetadataRefusal(slug, config, videoId);
+ if (localRefusal) return { ok: false, error: localRefusal };
const url = await findVideoSourceUrl(paths, slug, videoId, config);
if (!url) {
return {
diff --git a/common/controller/remoteArchives.test.ts b/common/controller/remoteArchives.test.ts
@@ -0,0 +1,122 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { connectRemoteArchive, removeRemoteArchive, RemoteArchiveError, type RemoteArchiveDeps } from "./remoteArchives";
+import type { RemoteArchive } from "../lib/remoteArchives";
+import type { FetchLike } from "../lib/remoteArchives-server";
+
+const CORPUS = {
+ spec: 6,
+ kind: "site",
+ generatedAt: "2026-11-08T00:00:00.000Z",
+ site: { id: "stubalyzer", title: "Stubalyzer" },
+ totals: { channels: 1, videos: 3 },
+ channels: [{ slug: "alpha", name: "Alpha", videoCount: 3 }],
+};
+
+function world(initial: RemoteArchive[] = [], env: Record<string, string> = {}) {
+ let stored: unknown = initial;
+ const writes: RemoteArchive[][] = [];
+ const asked: string[] = [];
+ const fetch: FetchLike = async (url) => {
+ asked.push(url);
+ return new Response(JSON.stringify(CORPUS), { status: 200 });
+ };
+ const deps: RemoteArchiveDeps = {
+ stored: () => stored,
+ save: async (next) => {
+ writes.push(next);
+ stored = next;
+ },
+ fetch,
+ now: () => new Date("2026-11-11T12:00:00Z"),
+ env,
+ // No real DNS in a test: every name is a public address unless a test says.
+ lookup: async () => [{ address: "93.184.216.34" }],
+ };
+ return { deps, writes, asked, stored: () => stored };
+}
+
+test("connect: probed once, saved with the archive's own id and title", async () => {
+ const w = world();
+ const r = await connectRemoteArchive({ origin: "https://stub.test/" }, w.deps);
+ assert.deepEqual(w.asked, ["https://stub.test/corpus.json"]);
+ assert.equal(r.already, false);
+ assert.deepEqual(w.writes, [[{ id: "stubalyzer", origin: "https://stub.test", title: "Stubalyzer", addedAt: "2026-11-11T12:00:00.000Z" }]]);
+ // Again: nothing written, it says so.
+ const again = await connectRemoteArchive({ origin: "stub.test" }, w.deps);
+ assert.equal(again.already, true);
+ assert.equal(w.writes.length, 1);
+});
+
+test("a dry run reads and writes nothing", async () => {
+ const w = world();
+ const r = await connectRemoteArchive({ origin: "https://stub.test", dryRun: true }, w.deps);
+ assert.equal(r.already, null);
+ assert.equal(r.probe.totals.videos, 3);
+ assert.equal(w.writes.length, 0);
+});
+
+test("the environment's archive can be connected (stored) but not removed", async () => {
+ const w = world([], { TRANSCRIPT_SITE_URL: "https://stub.test" });
+ await assert.rejects(removeRemoteArchive("https://stub.test", w.deps), (e: unknown) => e instanceof RemoteArchiveError && /TRANSCRIPT_SITE_URL/.test((e as Error).message));
+ const r = await connectRemoteArchive({ origin: "https://stub.test" }, w.deps);
+ assert.equal(r.already, false);
+ assert.equal(w.writes.length, 1);
+});
+
+test("remove by id or by origin; an unknown one is refused, naming what is connected", async () => {
+ const a: RemoteArchive = { id: "a", origin: "https://a.test", title: "A", addedAt: "2026-11-11T00:00:00.000Z" };
+ const b: RemoteArchive = { id: "b", origin: "https://b.test", title: "B", addedAt: "2026-11-11T00:00:00.000Z" };
+ const w = world([a, b]);
+ assert.deepEqual(await removeRemoteArchive("a", w.deps), a);
+ assert.deepEqual(await removeRemoteArchive("https://b.test/", w.deps), b);
+ assert.deepEqual(w.stored(), []);
+ await assert.rejects(removeRemoteArchive("zzz", w.deps), /no connected archive "zzz" — connected: none/);
+});
+
+// demo epic D1 review, blocker 2c: this machine or its network is not connected unless decided here.
+test("a local or private archive host is refused before anything is asked of it; the operator's own word allows it", async () => {
+ for (const origin of ["http://127.0.0.1:4100", "http://[::1]:8080", "http://localhost:3000", "http://nas.local", "http://10.0.0.7", "http://192.168.1.20/archive"]) {
+ const w = world();
+ await assert.rejects(connectRemoteArchive({ origin }, w.deps), /an archive on this machine or its network is connected only when/, origin);
+ assert.deepEqual(w.asked, [], `${origin}: nothing asked`);
+ }
+ // A public name that resolves to a private address.
+ const sneaky = world();
+ sneaky.deps.lookup = async () => [{ address: "93.184.216.34" }, { address: "192.168.1.9" }];
+ await assert.rejects(connectRemoteArchive({ origin: "https://rebind.example" }, sneaky.deps), /a name for a local or private address \(192\.168\.1\.9\)/);
+ assert.deepEqual(sneaky.asked, []);
+ // Decided on this machine: the editor's environment, TRANSCRIPT_SITE_URL, or settings.json.
+ const allowed = world([], { ARCHILYZER_ALLOW_PRIVATE_ARCHIVES: "1" });
+ assert.equal((await connectRemoteArchive({ origin: "http://127.0.0.1:4100" }, allowed.deps)).already, false);
+ const fromEnv = world([], { TRANSCRIPT_SITE_URL: "http://127.0.0.1:4100" });
+ assert.equal((await connectRemoteArchive({ origin: "http://127.0.0.1:4100" }, fromEnv.deps)).already, false);
+ const stored = world([{ id: "lan", origin: "http://10.0.0.7", title: "LAN", addedAt: "2026-11-11T00:00:00.000Z" }]);
+ assert.equal((await connectRemoteArchive({ origin: "http://10.0.0.7" }, stored.deps)).already, true);
+});
+
+// demo epic D1 re-review, must-fix 2: the address forms a URL may spell, and a redirect at connect.
+test("a local address in any spelling is refused at connect, nothing asked; allowed only by the operator's own word", async () => {
+ for (const origin of ["http://[::ffff:7f00:1]", "http://[::ffff:127.0.0.1]:3001", "http://[::1]", "http://0.0.0.0:3001", "http://2130706433", "http://0x7f000001", "http://0177.0.0.1", "http://127.1"]) {
+ const w = world();
+ await assert.rejects(connectRemoteArchive({ origin }, w.deps), /an archive on this machine or its network is connected only when/, origin);
+ assert.deepEqual(w.asked, [], `${origin}: nothing asked`);
+ assert.equal(w.writes.length, 0, `${origin}: nothing written`);
+ const allowed = world([], { ARCHILYZER_ALLOW_PRIVATE_ARCHIVES: "1" });
+ assert.equal((await connectRemoteArchive({ origin }, allowed.deps)).already, false, `${origin}: allowed when decided here`);
+ }
+});
+
+test("a public archive that redirects its corpus.json to a private address is not followed and not connected", async () => {
+ for (const location of ["http://127.0.0.1:3001/corpus.json", "http://[::ffff:7f00:1]/corpus.json", "http://169.254.169.254/latest/meta-data/", "http://2130706433/corpus.json", "//localhost:3001/corpus.json"]) {
+ const w = world();
+ const asked: string[] = [];
+ w.deps.fetch = async (url) => {
+ asked.push(url);
+ return new Response(null, { status: 302, headers: { location } });
+ };
+ await assert.rejects(connectRemoteArchive({ origin: "https://stub.test" }, w.deps), /an archive's documents are read from its own origin only/, location);
+ assert.deepEqual(asked, ["https://stub.test/corpus.json"], `${location}: the redirect is not followed`);
+ assert.equal(w.writes.length, 0, `${location}: nothing written`);
+ }
+});
diff --git a/common/controller/remoteArchives.ts b/common/controller/remoteArchives.ts
@@ -0,0 +1,76 @@
+// CONNECT AN ARCHIVE (demo epic D1, item 1): the one place
+// settings.remoteArchives is changed. The editor's ops action
+// (`pnpm ops archives`) and its /sites form call these; umtool's Source chip
+// asks the editor's action — so every connect is probed the same way and
+// written by the editor's one settings writer.
+//
+// connect probe `<origin>/corpus.json` (lib/remoteArchives-server.ts) and,
+// unless `dryRun`, add { id, origin, title, addedAt }. An origin
+// already connected answers what it is and writes nothing.
+// remove drop the entry by id (or origin). The TRANSCRIPT_SITE_URL entry
+// is not stored, so it cannot be removed here: it goes with the
+// variable.
+
+import { connectedArchives, findConnectedArchive, freeArchiveId, sanitizeRemoteArchives, archiveOriginOf, type ConnectedArchive, type RemoteArchive } from "../lib/remoteArchives";
+import { ArchiveProbeError, probeArchive, type ArchiveProbe, type FetchLike } from "../lib/remoteArchives-server";
+import { privateHostRefusal, type LookupAll } from "../lib/archiveHosts-server";
+
+export type RemoteArchiveDeps = {
+ // The stored list (settings.remoteArchives).
+ stored: () => unknown;
+ // Write the whole list (the editor's saveSettings({ remoteArchives })).
+ save: (next: RemoteArchive[]) => Promise<void>;
+ fetch?: FetchLike;
+ now?: () => Date;
+ env?: Record<string, string | undefined>;
+ // The host check's name lookup (archiveHosts-server.ts); a test's fake.
+ lookup?: LookupAll;
+};
+
+export type ConnectResult = {
+ probe: ArchiveProbe;
+ archive: ConnectedArchive;
+ // true: it was connected already (nothing written); false: added now; null: a dry run.
+ already: boolean | null;
+};
+
+export async function connectRemoteArchive(o: { origin: string; dryRun?: boolean }, deps: RemoteArchiveDeps): Promise<ConnectResult> {
+ // This machine or its network: refused before anything is asked of it,
+ // unless decided here (archiveHosts-server.ts).
+ const origin = archiveOriginOf(o.origin);
+ const env = deps.env ?? process.env;
+ if (origin && env.ARCHILYZER_ALLOW_PRIVATE_ARCHIVES !== "1" && !findConnectedArchive(connectedArchives(deps.stored(), env), origin)) {
+ const refused = await privateHostRefusal(origin, { lookup: deps.lookup });
+ if (refused) throw new ArchiveProbeError(refused);
+ }
+ const probe = await probeArchive(o.origin, { fetch: deps.fetch });
+ const list = connectedArchives(deps.stored(), deps.env);
+ const have = findConnectedArchive(list, probe.origin);
+ if (have && !have.fromEnv) return { probe, archive: have, already: true };
+ const stored = sanitizeRemoteArchives(deps.stored());
+ const archive: RemoteArchive = {
+ id: freeArchiveId(probe.origin, stored.map((a) => a.id), probe.siteId),
+ origin: probe.origin,
+ title: probe.title,
+ addedAt: (deps.now?.() ?? new Date()).toISOString(),
+ };
+ if (o.dryRun) return { probe, archive, already: null };
+ await deps.save([...stored, archive]);
+ return { probe, archive, already: false };
+}
+
+export class RemoteArchiveError extends Error {}
+
+/** Remove a stored archive by id or origin; answers the removed entry. */
+export async function removeRemoteArchive(which: string, deps: RemoteArchiveDeps): Promise<RemoteArchive> {
+ const stored = sanitizeRemoteArchives(deps.stored());
+ const origin = archiveOriginOf(which);
+ const hit = stored.find((a) => a.id === which || (origin !== null && a.origin === origin));
+ if (!hit) {
+ const env = connectedArchives(deps.stored(), deps.env).find((a) => a.fromEnv && (a.id === which || a.origin === origin));
+ if (env) throw new RemoteArchiveError(`${env.origin} comes from TRANSCRIPT_SITE_URL, not settings.json — unset the variable to stop offering it`);
+ throw new RemoteArchiveError(`no connected archive "${which}" — connected: ${stored.map((a) => a.id).join(", ") || "none"}`);
+ }
+ await deps.save(stored.filter((a) => a !== hit));
+ return hit;
+}
diff --git a/common/controller/remoteOnlyChannel.test.ts b/common/controller/remoteOnlyChannel.test.ts
@@ -0,0 +1,162 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, readFileSync, rmSync, mkdirSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import {
+ WHOLE_RECORDING_REFUSED,
+ archiveRecordOf,
+ archiveRecordPageHref,
+ ensureRemoteOnlyChannel,
+ estimateRecordingBytes,
+ wholeRecordingRefusal,
+} from "./remoteOnlyChannel";
+import type { GetJson } from "../lib/remoteArchives-server";
+import { detectPlatform } from "../lib/detectPlatform.mjs";
+import type { Paths } from "../lib/paths";
+import { isRemoteOnlyChannel, remoteOnlyRefusal } from "../lib/channelConfig";
+
+// demo epic D1 item 5: a channel cited from a connected archive is registered
+// remote-only on first need — config only — and its records come from the archive.
+
+const ORIGIN = "https://stub.test";
+const DOCS: Record<string, unknown> = {
+ [`${ORIGIN}/corpus.json`]: {
+ spec: 6,
+ site: { id: "stub", title: "Stub" },
+ channels: [
+ { slug: "alpha", name: "Alpha", videoCount: 2, platform: "youtube", url: "https://www.youtube.com/@alpha", manifests: { transcripts: `${ORIGIN}/transcripts/alpha/manifest.json` } },
+ { slug: "rum", name: "Rum", videoCount: 1, platform: "rumble", manifests: { transcripts: `${ORIGIN}/transcripts/rum/manifest.json` } },
+ ],
+ },
+ [`${ORIGIN}/transcripts/alpha/manifest.json`]: { pageCount: 1, slugToPage: { a1: 0, a2: 0 } },
+ [`${ORIGIN}/transcripts/alpha/page-0000.json`]: [
+ { id: "a1", title: "One", duration: 600, webpageUrl: "https://www.youtube.com/watch?v=a1" },
+ { id: "a2", title: "Two", duration: 7980, webpageUrl: "https://www.youtube.com/watch?v=a2" },
+ ],
+};
+
+function fake(): GetJson & { asked: string[] } {
+ const asked: string[] = [];
+ const f = (async (url: string) => {
+ asked.push(url);
+ if (!(url in DOCS)) throw new Error(`${url} answered HTTP 404`);
+ return DOCS[url];
+ }) as GetJson & { asked: string[] };
+ f.asked = asked;
+ return f;
+}
+
+function pool(): { paths: Paths; root: string } {
+ const root = mkdtempSync(path.join(tmpdir(), "remote-only-"));
+ return { root, paths: { channelsDir: path.join(root, "channels") } as unknown as Paths };
+}
+
+test("first need registers config only: remote-only, manual, the platform, no url", async () => {
+ const { paths, root } = pool();
+ try {
+ const r = await ensureRemoteOnlyChannel(paths, "alpha", { origin: ORIGIN }, { getJson: fake() });
+ assert.equal(r.registered, true);
+ const onDisk = JSON.parse(readFileSync(path.join(paths.channelsDir, "alpha", "config.json"), "utf8"));
+ assert.deepEqual(onDisk, {
+ name: "Alpha",
+ handling: "youtube",
+ platform: "youtube",
+ remoteOnly: true,
+ remoteArchive: ORIGIN,
+ remoteUrl: "https://www.youtube.com/@alpha",
+ downloadMode: "manual",
+ });
+ assert.equal("url" in onDisk, false, "nothing that syncs by url can sync it");
+ assert.equal(isRemoteOnlyChannel(r.config), true);
+ assert.match(remoteOnlyRefusal("alpha", r.config)!, /alpha is a remote-only channel of https:\/\/stub\.test/);
+ // Second need: the one on disk, nothing read.
+ const f = fake();
+ const again = await ensureRemoteOnlyChannel(paths, "alpha", { origin: ORIGIN }, { getJson: f });
+ assert.equal(again.registered, false);
+ assert.deepEqual(f.asked, []);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("a channel held here is never touched; one the archive does not list is refused, nothing written", async () => {
+ const { paths, root } = pool();
+ try {
+ mkdirSync(path.join(paths.channelsDir, "alpha"), { recursive: true });
+ writeFileSync(path.join(paths.channelsDir, "alpha", "config.json"), JSON.stringify({ name: "Mine", handling: "youtube", url: "https://www.youtube.com/@alpha" }));
+ const r = await ensureRemoteOnlyChannel(paths, "alpha", { origin: ORIGIN }, { getJson: fake() });
+ assert.equal(r.registered, false);
+ assert.equal(r.config.name, "Mine");
+ assert.equal(isRemoteOnlyChannel(r.config), false);
+ await assert.rejects(ensureRemoteOnlyChannel(paths, "nope", { origin: ORIGIN }, { getJson: fake() }), /lists no channel "nope"/);
+ assert.throws(() => readFileSync(path.join(paths.channelsDir, "nope", "config.json")));
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("a cited record's page URL and length come from the archive", async () => {
+ const f = fake();
+ assert.deepEqual(await archiveRecordOf(ORIGIN, "alpha", "a2", { getJson: f }), {
+ webpageUrl: "https://www.youtube.com/watch?v=a2",
+ duration: 7980,
+ title: "Two",
+ });
+ assert.deepEqual(f.asked, [`${ORIGIN}/corpus.json`, `${ORIGIN}/transcripts/alpha/manifest.json`, `${ORIGIN}/transcripts/alpha/page-0000.json`]);
+ assert.equal(await archiveRecordOf(ORIGIN, "alpha", "zz", { getJson: fake() }), null);
+ assert.equal(await archiveRecordOf(ORIGIN, "rum", "r1", { getJson: fake() }), null);
+});
+
+test("a whole recording is refused with its length and estimated size, and the key that allows it", () => {
+ assert.equal(estimateRecordingBytes(3600, 720), 1_125_000_000);
+ assert.equal(estimateRecordingBytes(3600, 360), 360_000_000);
+ const msg = wholeRecordingRefusal({ platform: "rumble", slug: "rum", id: "r1", duration: 7980 });
+ assert.ok(msg.startsWith(WHOLE_RECORDING_REFUSED));
+ assert.match(msg, /Rumble windows are cut from the WHOLE recording/);
+ assert.match(msg, /rum\/r1 is 2:13:00 long, about 2\.5 GB \(estimated\)/);
+ assert.match(msg, /"allowWholeRecording": true/);
+ assert.match(wholeRecordingRefusal({ platform: "rumble", slug: "rum", id: "r1" }), /length is not known to its archive/);
+});
+
+// demo epic D1 review, blocker 2b: an archive is read on its own origin only.
+test("a manifest the corpus names on another origin is not followed: the archive's own is read", async () => {
+ const asked: string[] = [];
+ const docs: Record<string, unknown> = {
+ "https://stub.test/corpus.json": { channels: [{ slug: "a", manifests: { transcripts: "http://192.168.1.1/admin.json" } }] },
+ "https://stub.test/transcripts/a/manifest.json": { slugToPage: { v1: 0 } },
+ "https://stub.test/transcripts/a/page-0000.json": [{ id: "v1", webpageUrl: "https://www.youtube.com/watch?v=v1" }],
+ };
+ const getJson = async (url: string) => {
+ asked.push(url);
+ if (!(url in docs)) throw new Error("404");
+ return docs[url];
+ };
+ assert.equal((await archiveRecordOf("https://stub.test", "a", "v1", { getJson }))?.webpageUrl, "https://www.youtube.com/watch?v=v1");
+ assert.equal(asked.some((u) => u.includes("192.168")), false);
+});
+
+// demo epic D1 re-check: what umtool's chain sends the editor for a record is the URL the check parsed.
+test("a record's page for an ask is the normalised href; one two parsers read differently, or off its platform, is no page", async () => {
+ const docs: Record<string, unknown> = {
+ "https://stub.test/corpus.json": { channels: [{ slug: "a" }] },
+ "https://stub.test/transcripts/a/manifest.json": { slugToPage: { ok: 0, loud: 0, slash: 0, tab: 0, dot: 0, off: 0, none: 0 } },
+ "https://stub.test/transcripts/a/page-0000.json": [
+ { id: "ok", webpageUrl: "https://www.youtube.com/watch?v=ok" },
+ { id: "loud", webpageUrl: "HTTPS://WWW.YouTube.com:443/watch?v=loud" },
+ { id: "slash", webpageUrl: "https://youtube.com\\@evil.example/watch?v=x" },
+ { id: "tab", webpageUrl: "https://you\ttube.com/watch?v=x" },
+ { id: "dot", webpageUrl: "https://rumble.com\\.evil.example/v1" },
+ { id: "off", webpageUrl: "http://169.254.169.254/latest/meta-data/" },
+ { id: "none" },
+ ],
+ };
+ const getJson = async (url: string) => {
+ if (!(url in docs)) throw new Error("404");
+ return docs[url];
+ };
+ const href = (id: string) => archiveRecordPageHref("https://stub.test", "a", id, detectPlatform, { getJson });
+ assert.equal(await href("ok"), "https://www.youtube.com/watch?v=ok");
+ assert.equal(await href("loud"), "https://www.youtube.com/watch?v=loud");
+ for (const id of ["slash", "tab", "dot", "off", "none", "not-held"]) assert.equal(await href(id), null, id);
+});
diff --git a/common/controller/remoteOnlyChannel.ts b/common/controller/remoteOnlyChannel.ts
@@ -0,0 +1,180 @@
+// A REMOTE-ONLY CHANNEL, registered on first need (demo epic D1 item 5).
+//
+// A sweep over a connected archive (settings.remoteArchives) cites moments of
+// channels this editor does not hold. Its clip windows are still fetched HERE —
+// the editor's paced queues, cookie policy and provenance — so the editor needs
+// a channel to put them under. The first time a window of such a channel is
+// asked for, with the archive named, the editor registers it:
+//
+// config only (`remoteOnly: true`, `remoteArchive`, `remoteUrl`, the
+// platform, `downloadMode: "manual"`), and NO `url` — nothing that syncs a
+// channel by its url can sync this one; no listing sweep is run.
+//
+// Every place a real channel is active skips it (lib/channelConfig.ts
+// isRemoteOnlyChannel): the lanes, the sync scheduler, Sync all and every
+// pipeline action, the metadata scan, cleanup, the storage watch, index and
+// stats builds, the site writer, a research run's channel list. The channel
+// list shows it as "remote only".
+//
+// A cited recording's page URL — what a window is fetched from — comes from
+// the archive's own record (archiveRecordOf), since the editor holds no
+// metadata for it; the ask may carry it too (umtool's chain sends it).
+//
+// A WHOLE-RECORDING PLATFORM (settings.clips.wholeRecordingPlatforms, Rumble):
+// a window there is cut from the saved whole recording — for a channel this
+// editor does not archive that is a whole download nobody planned. It is
+// refused with the recording's size (wholeRecordingRefusal) until the ask says
+// `allowWholeRecording: true` (one press: umtool's chain offers it).
+
+import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { PLATFORM_VALUES, type Platform } from "../lib/platform";
+import { corpusUrl, manifestUrl, pageUrl } from "../lib/archive/contract";
+import { WHOLE_RECORDING_REFUSED, archiveOriginOf, recordPage, sameOrigin, type ConnectedArchive } from "../lib/remoteArchives";
+import { archiveChannelFacts, plainGetJson, type ArchiveChannelFacts, type GetJson } from "../lib/remoteArchives-server";
+import { createChannel, readChannelConfig } from "./channels";
+
+export type RemoteOnlyDeps = {
+ // One JSON document over HTTP (the cached reader, item 6); a test's fake.
+ getJson?: GetJson;
+ facts?: (origin: string, slug: string, opts: { getJson?: GetJson }) => Promise<ArchiveChannelFacts>;
+};
+
+export class RemoteOnlyChannelError extends Error {}
+
+/** The config a remote-only channel is registered with, from its archive's facts. */
+export function remoteOnlyConfigOf(archive: Pick<ConnectedArchive, "origin">, facts: ArchiveChannelFacts): ChannelConfig {
+ const platform = facts.platform && (PLATFORM_VALUES as readonly string[]).includes(facts.platform) ? (facts.platform as Platform) : undefined;
+ return {
+ name: facts.name,
+ handling: platform === "youtube" ? "youtube" : "transcribe",
+ ...(platform ? { platform } : {}),
+ remoteOnly: true,
+ remoteArchive: archive.origin,
+ ...(facts.url ? { remoteUrl: facts.url } : {}),
+ downloadMode: "manual",
+ } as ChannelConfig;
+}
+
+/**
+ * The channel's config: the one on disk, or — when there is none — a
+ * remote-only channel registered now from `archive`'s corpus.json. A channel
+ * the archive does not list is refused.
+ */
+export async function ensureRemoteOnlyChannel(
+ paths: Paths,
+ slug: string,
+ archive: Pick<ConnectedArchive, "origin">,
+ deps: RemoteOnlyDeps = {},
+): Promise<{ config: ChannelConfig; registered: boolean }> {
+ const have = await readChannelConfig(paths, slug);
+ if (have) return { config: have, registered: false };
+ const facts = await (deps.facts ?? archiveChannelFacts)(archive.origin, slug, { getJson: deps.getJson });
+ const config = remoteOnlyConfigOf(archive, facts);
+ try {
+ await createChannel(paths, slug, config);
+ } catch (e) {
+ // Two asks at once: the other registered it first.
+ const again = await readChannelConfig(paths, slug);
+ if (again) return { config: again, registered: false };
+ throw e;
+ }
+ return { config: (await readChannelConfig(paths, slug)) ?? config, registered: true };
+}
+
+export type ArchiveRecord = { webpageUrl?: string; duration?: number; platform?: string; title?: string };
+
+/**
+ * A recording's own record in its archive: the transcripts manifest's page for
+ * the id, then the record whose id matches — its page URL and duration. Null
+ * when the archive does not hold it. At most three documents, in order.
+ */
+export async function archiveRecordOf(origin: string, slug: string, id: string, deps: { getJson?: GetJson } = {}): Promise<ArchiveRecord | null> {
+ const base = archiveOriginOf(origin);
+ if (!base) return null;
+ const getJson = deps.getJson ?? plainGetJson();
+ const corpus = (await getJson(corpusUrl(base)).catch(() => null)) as { channels?: { slug?: string; manifests?: { transcripts?: string } }[] } | null;
+ const entry = corpus?.channels?.find((c) => c?.slug === slug);
+ // Only the archive's own origin is read (an archive is untrusted input): a
+ // manifest its corpus.json names elsewhere is not followed.
+ const named = entry?.manifests?.transcripts;
+ const at = typeof named === "string" && sameOrigin(named, base) ? named : manifestUrl("transcripts", slug, base);
+ const manifest = (await getJson(at).catch(() => null)) as { slugToPage?: Record<string, number> } | null;
+ const page = manifest?.slugToPage?.[id] ?? manifest?.slugToPage?.[`${slug}/${id}`];
+ if (typeof page !== "number") return null;
+ const records = (await getJson(pageUrl("transcripts", slug, page, base)).catch(() => null)) as Record<string, unknown>[] | null;
+ const r = (Array.isArray(records) ? records : []).find((x) => x?.id === id);
+ if (!r) return null;
+ const s = (k: string) => (typeof r[k] === "string" && (r[k] as string).trim() ? (r[k] as string).trim() : undefined);
+ const duration = typeof r.duration === "number" && Number.isFinite(r.duration) ? r.duration : undefined;
+ const webpageUrl = s("webpageUrl");
+ return {
+ ...(webpageUrl && /^https?:\/\//i.test(webpageUrl) ? { webpageUrl } : {}),
+ ...(duration !== undefined ? { duration } : {}),
+ ...(s("platform") ? { platform: s("platform") } : {}),
+ ...(s("title") ? { title: s("title") } : {}),
+ };
+}
+
+/**
+ * The page URL an ask for a window carries for a recording of `origin`'s
+ * channel: its archive record's, JUDGED AND NORMALISED (lib/remoteArchives.ts
+ * recordPage) — the URL the check parsed, written back — or null when the
+ * archive holds no record, names no page, or names one that is refused. Never
+ * the record's own string (umtool's chain sends this to the editor, which
+ * judges it again).
+ */
+export async function archiveRecordPageHref(
+ origin: string,
+ slug: string,
+ id: string,
+ detect: (u: string) => string | null,
+ deps: { getJson?: GetJson } = {},
+): Promise<string | null> {
+ const record = await archiveRecordOf(origin, slug, id, deps).catch(() => null);
+ if (!record?.webpageUrl) return null;
+ const page = recordPage(record.webpageUrl, null, detect);
+ return "refused" in page ? null : page.href;
+}
+
+// A whole recording's size, ESTIMATED from its length: what the saved-video
+// store's copy weighs at about this height. Approximate on purpose (no request
+// is made to learn it): video of this kind runs ~0.8 Mb/s at 360p up to ~5 Mb/s
+// at 1080p, audio included.
+const MBPS_BY_HEIGHT: [number, number][] = [
+ [360, 0.8],
+ [480, 1.2],
+ [720, 2.5],
+ [1080, 5],
+];
+
+export function estimateRecordingBytes(durationSec: number, maxHeight = 720): number {
+ const mbps = (MBPS_BY_HEIGHT.find(([h]) => maxHeight <= h) ?? MBPS_BY_HEIGHT[MBPS_BY_HEIGHT.length - 1])[1];
+ return Math.round((durationSec * mbps * 1e6) / 8);
+}
+
+const clock = (s: number) => {
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const sec = Math.floor(s % 60);
+ return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}` : `${m}:${String(sec).padStart(2, "0")}`;
+};
+const gb = (bytes: number) => (bytes >= 1e9 ? `${(bytes / 1e9).toFixed(1)} GB` : `${Math.max(1, Math.round(bytes / 1e6))} MB`);
+
+export { WHOLE_RECORDING_REFUSED };
+
+/**
+ * The refusal of a remote-only channel's window on a whole-recording platform:
+ * the recording's length and estimated size, and the one key that fetches it.
+ */
+export function wholeRecordingRefusal(o: { platform: string; slug: string; id: string; duration?: number; maxHeight?: number }): string {
+ const name = o.platform.charAt(0).toUpperCase() + o.platform.slice(1);
+ const size =
+ o.duration !== undefined
+ ? `${o.slug}/${o.id} is ${clock(o.duration)} long, about ${gb(estimateRecordingBytes(o.duration, o.maxHeight))} (estimated)`
+ : `${o.slug}/${o.id}'s length is not known to its archive`;
+ return (
+ `${WHOLE_RECORDING_REFUSED} ${name} windows are cut from the WHOLE recording, and ${o.slug} is a remote-only channel: ` +
+ `${size}. Send "allowWholeRecording": true to download it whole (once; its windows are cut from it).`
+ );
+}
diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts
@@ -61,6 +61,9 @@
// MCP's, and common cannot import the mcp package.
import os from "node:os";
+import { projectsRootFrom } from "../lib/projectsRoot.mjs";
+import { originOfHandle } from "../lib/remoteArchives";
+import { isRemoteOnlyChannel } from "../lib/channelConfig";
import path from "node:path";
import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
import type { JobProgress } from "../jobs/registry";
@@ -74,6 +77,7 @@ import { webTools } from "../lib/web/tools";
import {
copyIteration,
createIteration,
+ lineageSource,
readIteration,
readIterationFile,
reportSourceOf,
@@ -500,7 +504,7 @@ export function expandHome(p: string): string {
}
export function projectsRootOf(gen: GenerationSettings): string {
- return gen.projectsRoot ? expandHome(gen.projectsRoot) : path.join(os.homedir(), "reports", "articles");
+ return projectsRootFrom(gen.projectsRoot);
}
// The model a task runs on: the asked one, else the route's.
@@ -554,7 +558,10 @@ export type ReportDraftDeps = {
// The editor's channels, as a research run lists them.
async function editorChannelsOf(paths: Paths): Promise<EditorChannel[]> {
- return (await listChannelConfigs(paths)).map(({ slug, config }) => {
+ // A remote-only channel (demo epic D1) is no channel of the editor's own —
+ // it holds an archive's clip windows — so a research run never lists it, or
+ // imports into it.
+ return (await listChannelConfigs(paths)).filter(({ config }) => !isRemoteOnlyChannel(config)).map(({ slug, config }) => {
const c = config as Record<string, unknown>;
const s = (k: string) => (typeof c[k] === "string" && c[k] ? (c[k] as string) : undefined);
const kind = s("sourceKind") ?? (s("postFetcher") ? "posts" : s("handling"));
@@ -571,15 +578,28 @@ async function channelsOfReport(article: string, n: number, paths: Paths): Promi
return [...new Set(Object.values(cites).map((c) => c.channel).filter((c): c is string => !!c))];
}
-// The corpus and the origin the run cites on.
+// The origin a run over a named corpus cites on (demo epic D1 item 3): a
+// published archive's own origin — its moments are its pages — unless
+// settings.generation.citationOrigin is set, which overrides; a hub (whose
+// members each have their own) or a local dir, the citation origin or the
+// project's site, as before.
+export function citationOriginFor(source: string, gen: Pick<GenerationSettings, "citationOrigin">): string {
+ return gen.citationOrigin || originOfHandle(source) || PROJECT_URL;
+}
+
+// The corpus and the origin the run cites on. `inherited`: the corpus the
+// iteration's lineage read (lineageSource) — a revision, a media draft or a
+// refresh of a sweep over an archive reads that archive, not a local build.
export async function resolveCorpus(
body: Pick<ReportDraftBody, "source" | "build">,
channels: string[],
paths: Pick<Paths, "exportBuildsDir" | "sitesDir">,
gen: GenerationSettings,
+ inherited?: string | null,
): Promise<{ source: string; origin: string; build?: string }> {
const fallback = gen.citationOrigin || PROJECT_URL;
- if (body.source) return { source: body.source, origin: fallback };
+ const named = body.source ?? (body.build ? undefined : (inherited ?? undefined));
+ if (named) return { source: named, origin: citationOriginFor(named, gen) };
const b = await pickCorpusBuild(channels, { exportBuildsDir: paths.exportBuildsDir, ...(body.build ? { want: body.build } : {}) });
return { source: `local:${b.dir}`, origin: (await siteOriginOf(b.build, paths.sitesDir)) ?? fallback, build: b.build };
}
@@ -673,7 +693,9 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
})
: null;
const warnings: string[] = [];
- if (cont && !body.source) {
+ // A continuation of a research run over an archive reads that archive
+ // (the run inherits it: lineageSource), so no local build is asked for.
+ if (cont && !body.source && !(await lineageSource(body.article, cont.research.n, paths).catch(() => null))) {
// The sweep reads a composed build: one must hold the widened channels
// (a channel on no site is in none until the operator puts it on one
// and builds it), and an acquisition after the build is not in it.
@@ -715,7 +737,7 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
model,
parent: cont.research.n,
question: cont.question,
- scope: { channels: cont.channels, ...(cont.from ? { from: cont.from } : {}), ...(cont.to ? { to: cont.to } : {}), ...(body.ids ? { ids: body.ids } : {}) },
+ scope: { channels: cont.channels, ...(body.source ? { source: body.source } : {}), ...(cont.from ? { from: cont.from } : {}), ...(cont.to ? { to: cont.to } : {}), ...(body.ids ? { ids: body.ids } : {}) },
},
paths,
)
@@ -728,7 +750,7 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
kind: kindOf(body.task),
model,
...(body.task === "sweep" || body.task === "research"
- ? { question: body.question, scope: { ...(body.channels ? { channels: body.channels } : {}), ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}), ...(body.ids ? { ids: body.ids } : {}), ...(body.triage ? { triage: body.triage } : {}) } }
+ ? { question: body.question, scope: { ...(body.source ? { source: body.source } : {}), ...(body.channels ? { channels: body.channels } : {}), ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}), ...(body.ids ? { ids: body.ids } : {}), ...(body.triage ? { triage: body.triage } : {}) } }
: { parent: body.iteration!, feedback: body.feedback }),
},
paths,
@@ -794,7 +816,7 @@ async function runReportDraft(
let corpus: (CorpusToolsLike & { close(): Promise<void> }) | null = null;
let result: TaskResult | null = null;
try {
- const where = await resolveCorpus(body, channels, paths, gen);
+ const where = await resolveCorpus(body, channels, paths, gen, await lineageSource(body.article, n, paths).catch(() => null));
onLog(`corpus ${where.source}${where.build ? ` (build ${where.build})` : ""}; links on ${where.origin}`);
corpus = await deps.corpusTools(where.source);
const disk = paths.channelsDir;
diff --git a/common/controller/reportDraftSource.test.ts b/common/controller/reportDraftSource.test.ts
@@ -0,0 +1,41 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { citationOriginFor, projectsRootOf, resolveCorpus } from "./reportDraft";
+import { defaultProjectsRoot } from "../lib/projectsRoot.mjs";
+import { defaults } from "../lib/settingsSchema";
+import { PROJECT_URL } from "../lib/project";
+
+// demo epic D1 item 3: a sweep over a published archive cites that archive.
+const gen = (over: Record<string, unknown> = {}) => ({ ...defaults().generation, ...over });
+const paths = { exportBuildsDir: "/nonexistent/builds", sitesDir: "/nonexistent/sites" };
+
+test("a remote source's citations are on its own origin; citationOrigin overrides only when set", () => {
+ assert.equal(citationOriginFor("remote:https://stub.test/", gen()), "https://stub.test");
+ assert.equal(citationOriginFor("remote:https://stub.test", gen({ citationOrigin: "https://mirror.test" })), "https://mirror.test");
+ // A hub's members each have their own origin; a local dir has none: as before.
+ assert.equal(citationOriginFor("hub:https://hub.test", gen()), PROJECT_URL);
+ assert.equal(citationOriginFor("local:/x", gen()), PROJECT_URL);
+});
+
+test("the corpus: the body's source, else the lineage's, before any local build", async () => {
+ assert.deepEqual(await resolveCorpus({ source: "remote:https://stub.test" }, ["alpha"], paths, gen()), { source: "remote:https://stub.test", origin: "https://stub.test" });
+ // A revision with no source of its own reads (and cites) what its sweep read.
+ assert.deepEqual(await resolveCorpus({}, ["alpha"], paths, gen(), "remote:https://stub.test"), { source: "remote:https://stub.test", origin: "https://stub.test" });
+ // A named build wins over the inherited source; with none on disk it is refused as before.
+ await assert.rejects(resolveCorpus({ build: "mine" }, ["alpha"], paths, gen(), "remote:https://stub.test"));
+ await assert.rejects(resolveCorpus({}, ["alpha"], paths, gen(), null));
+});
+
+test("projectsRoot blank: <REPORTS_DIR>/articles when set (a container's volume), else ~/reports/articles", () => {
+ assert.equal(defaultProjectsRoot({ REPORTS_DIR: "/data/reports" }), "/data/reports/articles");
+ assert.match(defaultProjectsRoot({}), /\/reports\/articles$/);
+ const saved = process.env.REPORTS_DIR;
+ process.env.REPORTS_DIR = "/data/reports";
+ try {
+ assert.equal(projectsRootOf(gen()), "/data/reports/articles");
+ assert.equal(projectsRootOf(gen({ projectsRoot: "/elsewhere" })), "/elsewhere");
+ } finally {
+ if (saved === undefined) delete process.env.REPORTS_DIR;
+ else process.env.REPORTS_DIR = saved;
+ }
+});
diff --git a/common/controller/reportRefresh.ts b/common/controller/reportRefresh.ts
@@ -46,6 +46,7 @@ import { readAllPosts } from "../lib/posts-server";
import {
createIteration,
currentIteration,
+ lineageSource,
listIterations,
readIteration,
readIterationFile,
@@ -68,6 +69,7 @@ import { jobOfPaths } from "./researchRuns";
import {
REPORT_DRAFT_JOB_KIND,
REPORT_DRAFT_RESULT_MARKER,
+ citationOriginFor,
llmConfigOf,
type ReportDraftBody,
type ReportDraftDeps,
@@ -303,7 +305,8 @@ export function fetchHooksOf(deps: ReportDraftDeps): FetchHooks {
const c = (await configs()).get(slug);
if (!c) return null;
const platform = platformOfConfig(c);
- return { kind: isPostsChannel(c) ? "posts" : "video", ...(platform ? { platform } : {}) };
+ const localLibrary = !!c.localMedia && !(typeof c.url === "string" && c.url.trim());
+ return { kind: isPostsChannel(c) ? "posts" : "video", ...(platform ? { platform } : {}), ...(localLibrary ? { localLibrary: true as const } : {}) };
},
platformRefusal: (platform) => platformRefusalOf(platform, paths),
bucketOf: async (slug) => {
@@ -399,13 +402,16 @@ async function runRefreshJob(
const hooks: RefreshHooks = {
...fetchHooksOf(deps),
openCorpus: async (channels, prefer) => {
- const b = body.source ? null : body.build ? (await listCorpusBuilds(paths.exportBuildsDir)).find((x) => x.build === body.build) ?? null : await refreshBuild(channels, prefer, paths);
- const source = body.source ?? (b ? `local:${b.dir}` : null);
+ // A refresh of a sweep over a published archive reads (and cites) that
+ // archive (demo epic D1): the source named, else the lineage's.
+ const named = body.source ?? (body.build ? null : await lineageSource(body.article, n, paths).catch(() => null));
+ const b = named ? null : body.build ? (await listCorpusBuilds(paths.exportBuildsDir)).find((x) => x.build === body.build) ?? null : await refreshBuild(channels, prefer, paths);
+ const source = named ?? (b ? `local:${b.dir}` : null);
if (!source) throw new Error(`no composed build holds ${channels.join(", ")} — publish build the site that carries them`);
const missing = b ? channels.filter((c) => !b.channels.includes(c)) : [];
if (missing.length) onLog(`the build ${b!.build} does not hold ${missing.join(", ")}: those are not searched`);
await holder.swap(await deps.corpusTools(source));
- const origin = b ? ((await siteOriginOf(b.build, paths.sitesDir)) ?? fallback) : fallback;
+ const origin = b ? ((await siteOriginOf(b.build, paths.sitesDir)) ?? fallback) : citationOriginFor(source, gen);
return { source, origin, ...(b ? { build: b.build } : {}) };
},
recordOf: async (channel, id) => {
diff --git a/common/controller/storageWatch.ts b/common/controller/storageWatch.ts
@@ -1,3 +1,4 @@
+import { isRemoteOnlyChannel } from "../lib/channelConfig";
import { getPaths, type Paths } from "../lib/paths";
import { withJsonFileLock } from "../lib/jsonFile-server";
import {
@@ -212,6 +213,9 @@ export async function runStorageWatchPass(
const pauseCauses = new Map<string, AutoPauseCause>();
for (const { slug, config } of configs) {
+ // A remote-only channel (demo epic D1) has no media drive to watch and no
+ // lane a pause would hold.
+ if (isRemoteOnlyChannel(config)) continue;
const wasAutoPaused = Boolean(model.channels[slug]?.autoPaused);
// ONE TIER PER CHANNEL (release 17): the drive its MEDIA is on —
// `mediaDir`, or on a channel not yet migrated off the retired
diff --git a/common/controller/undownloadedVideos.ts b/common/controller/undownloadedVideos.ts
@@ -1,4 +1,6 @@
import path from "node:path";
+import { readChannelConfig } from "./channels";
+import { localMediaFetchRefusal } from "../lib/localMedia";
import { readFile } from "node:fs/promises";
import type { Paths } from "../lib/paths";
import type { ChannelConfig } from "../lib/channelConfig";
@@ -25,10 +27,17 @@ export async function findVideoSourceUrl(
config?: ChannelConfig,
): Promise<string | null> {
const channelRoot = path.join(paths.channelsDir, slug);
+ // A LOCAL RECORDING, or any record of a local media library channel, has no
+ // online source (lib/localMedia.ts): null, so no lane, door or download ever
+ // hands yt-dlp a URL built for it — `defaultWebpageUrl("local", id)` is "".
+ if (localMediaFetchRefusal(slug, config ?? (await readChannelConfig(paths, slug).catch(() => null)), videoId)) {
+ return null;
+ }
const metaPath = path.join(channelRoot, "data", videoId, "metadata.info.json");
try {
const raw = await readFile(metaPath, "utf8");
const parsed = JSON.parse(raw);
+ if (parsed?.local_recording !== undefined) return null;
if (typeof parsed?.webpage_url === "string" && parsed.webpage_url) {
return parsed.webpage_url;
}
@@ -46,6 +55,6 @@ export async function findVideoSourceUrl(
// playlist came up empty, so the exact original URL always wins when present.
// Requires a known platform — we don't blindly guess one.
const platform = config?.platform ?? detectPlatform(config?.url ?? null);
- if (platform) return defaultWebpageUrl(platform, videoId);
+ if (platform) return defaultWebpageUrl(platform, videoId) || null;
return null;
}
diff --git a/common/controller/videoTitles.test.ts b/common/controller/videoTitles.test.ts
@@ -1,3 +1,4 @@
+import { prepareManualLocalRecordingMetadata } from "../lib/localRecordingMetadata";
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdir, mkdtemp, rm, unlink, utimes, writeFile, readdir } from "node:fs/promises";
@@ -326,3 +327,26 @@ test("metadata titles are memoized per channel until data/ changes", async () =>
await rm(dir, { recursive: true, force: true });
}
});
+
+
+test("display identifies only valid local metadata matching the saved record", async () => {
+ const { dir, paths } = await fixture("local-display-");
+ try {
+ const id = "local-" + "a".repeat(32);
+ const local = prepareManualLocalRecordingMetadata({ id, filename: "lesson.mp4" });
+ await writeInfo(paths, id, local);
+ assert.equal((await readVideoMetadataForDisplay(paths, SLUG, id)).localRecording, true);
+ for (const info of [
+ { id, title: "Online record without URL", extractor_key: "Youtube" },
+ { ...local, webpage_url: "https://www.youtube.com/watch?v=abc" },
+ { ...local, local_recording: { ...local.local_recording, version: 99 } },
+ { ...local, id: "local-" + "b".repeat(32) },
+ ]) {
+ await writeInfo(paths, id, info);
+ assert.equal((await readVideoMetadataForDisplay(paths, SLUG, id)).localRecording, undefined);
+ }
+ assert.equal((await readVideoMetadataForDisplay(paths, SLUG, "missing")).localRecording, undefined);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/controller/videoTitles.ts b/common/controller/videoTitles.ts
@@ -1,3 +1,4 @@
+import { requireLocalRecordingMetadata } from "../lib/localRecordingMetadata";
// What a channel's videos are CALLED, for the editor's per-channel video list
// and the video page — without downloading anything and without walking the
// corpus.
@@ -282,6 +283,8 @@ export async function readChannelVideoTitles(
}
export type VideoDisplayMetadata = {
+ // True only for validated source-less metadata, never inferred from an ID or missing URL.
+ localRecording?: true;
title?: string;
description?: string;
webpageUrl?: string;
@@ -309,7 +312,14 @@ export async function readVideoMetadataForDisplay(
path.join(channelDataDir(paths, channelSlug), id),
);
if (meta) {
+ let localRecording = false;
+ try {
+ localRecording = requireLocalRecordingMetadata(meta).id === id;
+ } catch {
+ // Ordinary provider metadata (including incomplete records) keeps its existing UI.
+ }
return {
+ ...(localRecording ? { localRecording: true as const } : {}),
title: str(meta.title),
description: str(meta.description),
webpageUrl: str(meta.webpage_url),
diff --git a/common/controller/voiceFile.test.ts b/common/controller/voiceFile.test.ts
@@ -50,7 +50,8 @@ if (kind === "openvoice" || kind === "seed-vc") {
const more = argv.includes("--more") ? JSON.parse(argv[argv.indexOf("--more") + 1]) : [];
for (const m of more) fs.copyFileSync(m.input, m.output);
console.error("voice: " + kind + " converted");
- console.log(JSON.stringify({ op: "convert", engine: kind, sampleRate: 48000, seconds: 1, samples: 48000, engineMs: 5, gainDb: 0 }));
+ const f0 = argv.includes("--pitch") ? { f0: { targetHz: 200, sourceHz: 150, shiftSemitones: 6.98 } } : {};
+ console.log(JSON.stringify({ op: "convert", engine: kind, sampleRate: 48000, seconds: 1, samples: 48000, engineMs: 5, gainDb: 0, ...f0 }));
process.exit(0);
}
const r = spawnSync(process.execPath, [${JSON.stringify(WRAPPER)}, ...argv], { stdio: "inherit" });
@@ -83,7 +84,7 @@ const {
} = await import("./voiceFile");
const { getPaths } = await import("../lib/paths");
const { DEFAULT_VOICE_SETTINGS } = await import("../lib/voiceSettings");
-const { OPENVOICE_FILES, getVoiceEngine, stockTargetPaths, voiceCodeDir } = await import("../lib/voiceApps");
+const { OPENVOICE_FILES, SEEDVC_F0_FILES, SEEDVC_FILES, getVoiceEngine, stockTargetPaths, voiceCodeDir } = await import("../lib/voiceApps");
const { VOICE_CODE_MARKER } = await import("../lib/voiceInstall");
const paths = getPaths();
@@ -122,7 +123,7 @@ async function engineRuns(): Promise<string[][]> {
test("the body keys are umtool's contract", () => {
assert.deepEqual([...VOICE_ENHANCE_BODY_KEYS], ["file", "path", "out", "engine", "params", "parts"]);
- assert.deepEqual([...VOICE_CONVERT_BODY_KEYS], ["file", "path", "out", "engine", "params", "parts", "voice", "target"]);
+ assert.deepEqual([...VOICE_CONVERT_BODY_KEYS], ["file", "path", "out", "engine", "params", "parts", "voice", "target", "pitch", "semitones"]);
});
test("the body's shape is judged before the disk", () => {
@@ -191,6 +192,74 @@ test("an engine is the op's own, and its params are checked", () => {
}
});
+test("a pitch is the engine's to follow: openvoice refuses one, seed-vc takes source and contour", () => {
+ const v = DEFAULT_VOICE_SETTINGS;
+ const ask = (b: Record<string, unknown>, voice = v) => {
+ const p = parseVoiceBody("convert", { file: "/a.wav", out: "/b.wav", ...b });
+ assert.ok(p.ok, !p.ok ? p.error : "");
+ return resolveVoiceRequest("convert", p.ok ? p.value : ({} as never), voice);
+ };
+ const refused = (b: Record<string, unknown>, re: RegExp, voice = v) => {
+ const r = ask(b, voice);
+ assert.ok(!r.ok, JSON.stringify(b));
+ if (!r.ok) {
+ assert.match(r.error, re);
+ // One sentence.
+ assert.equal(r.error.includes("\n"), false);
+ }
+ };
+ // Nothing asked: the target's own pitch, on every engine.
+ for (const engine of ["openvoice", "seed-vc"]) {
+ const r = ask({ engine });
+ assert.ok(r.ok);
+ if (r.ok) assert.deepEqual(r.value.pitch, { pitch: "target", semitones: 0 });
+ }
+ // An enhance has no pitch at all.
+ const en = resolveVoiceRequest("enhance", { file: "/a.wav", out: "/b.wav", engine: "rnnoise" }, v);
+ assert.ok(en.ok && en.value.pitch === undefined);
+ // OpenVoice has one pitch.
+ refused({ engine: "openvoice", pitch: "source" }, /^OpenVoice v2 \(tone-colour converter\) has no pitch control — .* "pitch" and "semitones" are seed-vc's/);
+ refused({ engine: "openvoice", semitones: 2 }, /has no pitch control/);
+ assert.ok(ask({ engine: "openvoice", pitch: "target", semitones: 0 }).ok);
+ // The values.
+ refused({ engine: "seed-vc", pitch: "up" }, /"pitch" is one of target, source, contour \(got "up"\)/);
+ refused({ engine: "seed-vc", pitch: "source", semitones: 13 }, /"semitones" is a number from -12 to 12 \(got 13\)/);
+ refused({ engine: "seed-vc", pitch: "source", semitones: "2" }, /"semitones" is a number from -12 to 12/);
+ // Semitones move a FOLLOWED pitch.
+ refused({ engine: "seed-vc", semitones: 2 }, /"semitones" moves a followed pitch — give "pitch": "source" or "contour"/);
+ refused({ engine: "seed-vc", pitch: "target", semitones: -1 }, /moves a followed pitch/);
+ const src = ask({ engine: "seed-vc", pitch: "source" });
+ assert.ok(src.ok);
+ if (src.ok) assert.deepEqual(src.value.pitch, { pitch: "source", semitones: 0 });
+ const con = ask({ engine: "seed-vc", pitch: "contour", semitones: -1.5 });
+ assert.ok(con.ok);
+ if (con.ok) assert.deepEqual(con.value.pitch, { pitch: "contour", semitones: -1.5 });
+ // settings.voice.convert's defaults: for the engine that can follow, and
+ // never a refusal for the one that cannot.
+ const follow = { ...v, convert: { ...v.convert, pitch: "contour" as const, semitones: 2 } };
+ const d = ask({ engine: "seed-vc" }, follow);
+ assert.ok(d.ok);
+ if (d.ok) assert.deepEqual(d.value.pitch, { pitch: "contour", semitones: 2 });
+ // A request naming its own followed pitch and no semitones takes the default semitones; 0 says none.
+ const named = ask({ engine: "seed-vc", pitch: "source" }, follow);
+ assert.ok(named.ok);
+ if (named.ok) assert.deepEqual(named.value.pitch, { pitch: "source", semitones: 2 });
+ const zero = ask({ engine: "seed-vc", pitch: "source", semitones: 0 }, follow);
+ assert.ok(zero.ok);
+ if (zero.ok) assert.deepEqual(zero.value.pitch, { pitch: "source", semitones: 0 });
+ const over = ask({ engine: "seed-vc", pitch: "target" }, follow);
+ assert.ok(over.ok);
+ if (over.ok) assert.deepEqual(over.value.pitch, { pitch: "target", semitones: 0 });
+ const ov = ask({ engine: "openvoice" }, follow);
+ assert.ok(ov.ok);
+ if (ov.ok) assert.deepEqual(ov.value.pitch, { pitch: "target", semitones: 0 });
+ // The argv: nothing new for the target's pitch.
+ const seed = getVoiceEngine("seed-vc")!;
+ const base = { input: "/a.wav", output: "/b.wav", installDir: "/i", params: {}, threads: 4, targetRef: "/r.wav", bins: { ffmpegBin: "ffmpeg", voiceModelsDir: "/m" } };
+ assert.equal(seed.build({ ...base, pitch: { pitch: "target", semitones: 0 } }).includes("--pitch"), false);
+ assert.deepEqual(seed.build({ ...base, pitch: { pitch: "contour", semitones: 2 } }).slice(-4), ["--pitch", "contour", "--semitones", "2"]);
+});
+
// --- the disk checks -----------------------------------------------------------
test("the disk checks: the input, the out, the install", { skip: SKIP }, async () => {
@@ -353,6 +422,68 @@ test("an engine that fails fails the job with its words", { skip: SKIP }, async
assert.match(r.log, /the voice engine exited 3: voice: engine exploded/);
});
+// A seed-vc install, faked to the pinned sizes with sparse files; `f0` adds the
+// optional group a followed pitch runs on.
+async function fakeSeedVcInstall(f0: boolean): Promise<string> {
+ const dir = path.join(HOME, "seed-vc");
+ await mkdir(path.join(dir, "venv", "bin"), { recursive: true });
+ await writeFile(path.join(dir, "venv", "bin", "python"), "");
+ const seed = getVoiceEngine("seed-vc")!;
+ if (seed.setup.kind !== "python-venv") throw new Error("seed-vc is a venv engine");
+ await mkdir(voiceCodeDir(dir), { recursive: true });
+ await writeFile(path.join(voiceCodeDir(dir), VOICE_CODE_MARKER), `${seed.setup.code.commit}\n`);
+ for (const f of [...SEEDVC_FILES, ...(f0 ? SEEDVC_F0_FILES : [])]) {
+ const p = path.join(dir, f.name);
+ await mkdir(path.dirname(p), { recursive: true });
+ const fh = await open(p, "w");
+ await fh.truncate(f.bytes);
+ await fh.close();
+ }
+ return dir;
+}
+
+test("a followed pitch needs seed-vc's f0 model: refused naming the setup command, then run with its own estimate", { skip: SKIP }, async () => {
+ await fakeSeedVcInstall(false);
+ const askTts = async (body: Record<string, unknown>) => {
+ await tone(String(body.out), 2);
+ return { ok: true as const, jobId: "tts-job-2", stream: new ReadableStream<string>(), done: Promise.resolve({ status: "done" as const, jobId: "tts-job-2" }) };
+ };
+ const take = path.join(OUTSIDE, "p-take.wav");
+ await tone(take, 1);
+ const before = (await engineRuns()).length;
+ // An install without the f0 files still converts at the target's pitch…
+ const plain = await runJob("convert", { file: take, out: path.join(OUTSIDE, "p-plain.wav"), engine: "seed-vc", voice: "espeak-ng:en-us" }, { askTts });
+ assert.equal(plain.status, "done", plain.log ?? plain.error);
+ assert.equal(plain.result.pitch, "target");
+ assert.equal("semitones" in plain.result, false);
+ assert.equal("f0" in plain.result, false);
+ assert.match(plain.log!, /estimate 3500 MB/);
+ const plainRun = (await engineRuns()).at(-1)!;
+ assert.equal(plainRun.includes("--pitch"), false);
+ // …and refuses a followed one, in one sentence, before any job.
+ const runs = (await engineRuns()).length;
+ assert.equal(runs, before + 1);
+ const refused = await runJob("convert", { file: take, out: path.join(OUTSIDE, "p-src.wav"), engine: "seed-vc", voice: "espeak-ng:en-us", pitch: "source" }, { askTts });
+ assert.match(
+ refused.error!,
+ /^pitch "source" needs Seed-VC \(v1, 22 kHz speech\)'s f0 model, which is not installed \(.*voice-home\/seed-vc: missing DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema_v2\.pth; .*rmvpe\.pt; .*\) — run `archilyzer voice setup --engine seed-vc --with f0`$/,
+ );
+ assert.equal(refused.error!.includes("\n"), false);
+ assert.equal((await engineRuns()).length, runs);
+ // With them: the wrapper is told, the f0 run's estimate is declared, the result says what was done.
+ await fakeSeedVcInstall(true);
+ const r = await runJob("convert", { file: take, out: path.join(OUTSIDE, "p-con.wav"), engine: "seed-vc", voice: "espeak-ng:en-us", pitch: "contour", semitones: 2 }, { askTts });
+ assert.equal(r.status, "done", r.log ?? r.error);
+ const run = (await engineRuns()).at(-1)!;
+ assert.equal(run[run.indexOf("--pitch") + 1], "contour");
+ assert.equal(run[run.indexOf("--semitones") + 1], "2");
+ assert.match(r.log!, /Convert to espeak-ng:en-us \(pitch: contour \+2 st\)/);
+ assert.match(r.log!, new RegExp(`estimate ${getVoiceEngine("seed-vc")!.pitch!.defaultEstimateMB} MB`));
+ assert.equal(r.result.pitch, "contour");
+ assert.equal(r.result.semitones, 2);
+ assert.deepEqual(r.result.f0, { targetHz: 200, sourceHz: 150, shiftSemitones: 6.98 });
+});
+
test("a cancelled run stops the engine's whole process group", async () => {
const slow = path.join(BIN, "slow-engine");
await writeFile(slow, `#!/bin/sh\nsleep 30 &\nwait\n`);
diff --git a/common/controller/voiceFile.ts b/common/controller/voiceFile.ts
@@ -8,7 +8,13 @@
// THE BODY is umtool's contract (umtool/lib/report/postNarrationCli.mjs
// deriveTake): `{file, out, engine?, params?, parts?}`, and for convert
// `voice?` — the stock target (`target` is the same key's other name; `path`
-// is `file`'s). `file` is an absolute path to the recording (any format ffmpeg
+// is `file`'s) — and `pitch?` / `semitones?`: the pitch the conversion lands on
+// (lib/voiceApps.ts VoicePitch: `target`, the stock voice's own; `source`, the
+// read's; `contour`, the read's rises and falls at the stock voice's register;
+// `semitones` moves a followed one; defaults settings.voice.convert). An engine
+// with one pitch (openvoice) refuses another; a followed pitch whose model is
+// not installed (seed-vc's optional `f0` files) is refused naming the setup
+// command. `file` is an absolute path to the recording (any format ffmpeg
// reads, at most VOICE_MAX_SECONDS); `out` an absolute `.wav` path the result
// is written to — never inside the corpus, its directory existing; `engine`
// one of the op's engines (default settings.voice.<op>.engine); `params` the
@@ -37,7 +43,9 @@
// THE RESULT is logged as ONE line starting with VOICE_RESULT_MARKER (the
// marker umtool's askEditorOp reads): `{op, engine, wav, seconds, samples,
// sampleRate, engineMs, durationMs, waitedMs, gainDb, params, parts?,
-// target?, voice?, synthetic, disclosure?}`. `wav` is `out`, 48 kHz mono 16-bit, as
+// target?, voice?, pitch?, semitones?, f0?, synthetic, disclosure?}` (`pitch`
+// on every conversion; `f0` — {targetHz, sourceHz, shiftSemitones}, the medians
+// the tracker heard and the whole move — on a followed one). `wav` is `out`, 48 kHz mono 16-bit, as
// long as the input to the sample.
//
// WHAT IT TOUCHES: reads `file` and each part (anywhere); writes `out`, each
@@ -55,9 +63,11 @@ import type { StorageLocation } from "../lib/storageLocations";
import {
NO_CLONING,
VOICE_REFERENCE_TEXT,
+ describeVoicePitch,
getVoiceEngine,
parseStockTarget,
resolveVoiceParams,
+ resolveVoicePitch,
stockTargetPaths,
voiceConvertDisclosure,
voiceEngineIds,
@@ -65,8 +75,9 @@ import {
type StockTarget,
type VoiceEngine,
type VoiceOp,
+ type VoicePitchChoice,
} from "../lib/voiceApps";
-import { voiceInstallState } from "../lib/voiceInstall";
+import { voiceGroupState, voiceInstallState } from "../lib/voiceInstall";
import { DEFAULT_VOICE_SETTINGS, resolveVoiceHome, type VoiceSettings } from "../lib/voiceSettings";
import { getTtsEngine } from "../lib/ttsApps";
import { ttsInstallState } from "../lib/ttsInstall";
@@ -86,7 +97,7 @@ export const VOICE_RESULT_MARKER = "@@voice-result ";
// The bodies the routes accept; anything else is a 400.
export const VOICE_ENHANCE_BODY_KEYS = ["file", "path", "out", "engine", "params", "parts"] as const;
-export const VOICE_CONVERT_BODY_KEYS = [...VOICE_ENHANCE_BODY_KEYS, "voice", "target"] as const;
+export const VOICE_CONVERT_BODY_KEYS = [...VOICE_ENHANCE_BODY_KEYS, "voice", "target", "pitch", "semitones"] as const;
// The longest recording one op takes (a post read in full runs ~25 minutes).
export const VOICE_MAX_SECONDS = 1800;
@@ -103,6 +114,9 @@ export type VoiceFileBody = {
params?: unknown;
parts?: VoicePart[];
target?: string;
+ // Convert: as given, judged against the engine by resolveVoiceRequest.
+ pitch?: unknown;
+ semitones?: unknown;
};
function absWav(key: string, v: unknown, wav: boolean): Check<string> {
@@ -164,6 +178,8 @@ export function parseVoiceBody(op: VoiceOp, body: Record<string, unknown>): Chec
...(body.params !== undefined ? { params: body.params } : {}),
...(parts ? { parts } : {}),
...(target !== undefined ? { target } : {}),
+ ...(op === "convert" && body.pitch !== undefined ? { pitch: body.pitch } : {}),
+ ...(op === "convert" && body.semitones !== undefined ? { semitones: body.semitones } : {}),
},
};
}
@@ -178,6 +194,8 @@ export type VoiceRequest = {
out: string;
parts: VoicePart[];
target?: StockTarget;
+ // Convert: the pitch it lands on (target = the stock voice's own).
+ pitch?: VoicePitchChoice;
};
// The body plus settings.voice, resolved against the registry. Pure.
@@ -194,14 +212,27 @@ export function resolveVoiceRequest(
const params = resolveVoiceParams(engine, body.params);
if (!params.ok) return params;
let target: StockTarget | undefined;
+ let pitch: VoicePitchChoice | undefined;
if (op === "convert") {
const t = parseStockTarget(body.target ?? voice.convert.target);
if (!t.ok) return t;
target = t.value;
+ const p = resolveVoicePitch(engine, { pitch: body.pitch, semitones: body.semitones }, voice.convert);
+ if (!p.ok) return p;
+ pitch = p.value;
}
return {
ok: true,
- value: { op, engine, params: params.value, file: body.file, out: body.out, parts: body.parts ?? [], ...(target ? { target } : {}) },
+ value: {
+ op,
+ engine,
+ params: params.value,
+ file: body.file,
+ out: body.out,
+ parts: body.parts ?? [],
+ ...(target ? { target } : {}),
+ ...(pitch ? { pitch } : {}),
+ },
};
}
@@ -293,6 +324,18 @@ export async function checkVoiceRequest(req: VoiceRequest, ctx: VoiceFileContext
(req.engine.setup.kind === "bundled" ? req.engine.setup.hint : `run \`archilyzer voice setup --engine ${req.engine.id}\``),
};
}
+ // A followed pitch runs on the engine's optional model.
+ if (req.pitch && req.pitch.pitch !== "target" && req.engine.pitch) {
+ const group = voiceGroupState(req.engine, req.engine.pitch.group, { home: ctx.home });
+ if (group && !group.installed) {
+ return {
+ ok: false,
+ error:
+ `pitch "${req.pitch.pitch}" needs ${req.engine.label}'s ${group.id} model, which is not installed (${install.dir}: missing ${group.missing.join("; ")}) — ` +
+ `run \`archilyzer voice setup --engine ${req.engine.id} --with ${group.id}\``,
+ };
+ }
+ }
if (req.target) {
const tts = ctx.tts ?? DEFAULT_TTS_SETTINGS;
const ref = await stockReferenceState(req.target, ctx.home, tts);
@@ -368,6 +411,8 @@ export type EngineRunResult = {
sampleRate?: number;
engineMs?: number;
gainDb?: number;
+ // A followed pitch: the medians the tracker heard and the whole move applied.
+ f0?: { targetHz: number | null; sourceHz: number | null; shiftSemitones: number };
// The parts, when the run had more files (scripts/voice.mjs --more).
more?: { output: string; seconds: number; samples?: number; gainDb?: number }[];
};
@@ -482,12 +527,17 @@ export type VoiceResult = {
// shape a umtool take records).
target?: string;
voice?: string;
+ // Convert: the pitch it landed on, and for a followed one what was heard.
+ pitch?: VoicePitchChoice["pitch"];
+ semitones?: number;
+ f0?: EngineRunResult["f0"];
synthetic: boolean;
disclosure?: string;
};
function describe(req: VoiceRequest, seconds: number): string {
- const what = req.op === "enhance" ? "Enhance" : `Convert to ${req.target!.id}`;
+ const followed = describeVoicePitch(req.pitch);
+ const what = req.op === "enhance" ? "Enhance" : `Convert to ${req.target!.id}${followed ? ` (pitch: ${followed})` : ""}`;
const parts = req.parts.length ? ` and its ${req.parts.length} part(s)` : "";
return `${what}: ${Math.round(seconds * 10) / 10} s of ${req.file}${parts} with ${req.engine.id}`;
}
@@ -520,7 +570,11 @@ export async function enqueueVoiceFile(op: VoiceOp, body: Record<string, unknown
if (!checked.ok) return checked;
const req = checked.value;
const installDir = voiceInstallDir(home, req.engine);
- const estimateMB = voice.heavyEstimateMB[req.engine.id] ?? req.engine.defaultEstimateMB;
+ // A followed pitch is another model's run, with its own estimate.
+ const follows = req.pitch && req.pitch.pitch !== "target" ? req.engine.pitch : undefined;
+ const estimateMB = follows
+ ? (voice.heavyEstimateMB[follows.estimateKey] ?? follows.defaultEstimateMB)
+ : (voice.heavyEstimateMB[req.engine.id] ?? req.engine.defaultEstimateMB);
const asked = Date.now();
return runManagedFunction({
kind: VOICE_JOB_KIND[op],
@@ -558,6 +612,7 @@ export async function enqueueVoiceFile(op: VoiceOp, body: Record<string, unknown
threads: voice.threads,
...(targetRef ? { targetRef } : {}),
...(targetSe ? { targetSe } : {}),
+ ...(req.pitch ? { pitch: req.pitch } : {}),
bins: { ffmpegBin: opts.paths.ffmpegBin, voiceModelsDir: opts.paths.voiceModelsDir },
});
onLog(`Running ${req.engine.label}${req.parts.length ? ` over the take and its ${req.parts.length} part(s)` : ""} behind the heavy slot (estimate ${estimateMB} MB)…`);
@@ -582,6 +637,8 @@ export async function enqueueVoiceFile(op: VoiceOp, body: Record<string, unknown
params: req.params,
...(parts.length ? { parts } : {}),
...(req.target ? { target: req.target.id, voice: req.target.voice, disclosure: voiceConvertDisclosure(req.engine, req.target) } : {}),
+ ...(req.pitch ? { pitch: req.pitch.pitch, ...(req.pitch.pitch !== "target" ? { semitones: req.pitch.semitones } : {}) } : {}),
+ ...(follows && whole.f0 ? { f0: whole.f0 } : {}),
synthetic: op === "convert",
};
onLog(`${VOICE_RESULT_MARKER}${JSON.stringify(result)}`);
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -1520,6 +1520,22 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
queueKeyStrategy: "custom",
needsMedia: true,
},
+ // A LOCAL MEDIA LIBRARY'S RECORDS (controller/localMediaImport.ts): the
+ // metadata, transcript and `external-media.json` of recordings that stay in
+ // the channel's `localMedia.directory`. Text: it writes corpus text only and
+ // never opens a managed big file, so a disconnected managed-media drive does
+ // not hold it (the library has its own read-only resolver and stall check,
+ // and the controller refuses every relocation marker). Drainable between
+ // recordings. An INGEST kind: it writes whole new records. On the channel's
+ // own queue. Not replayable: a retry needs a fresh preview's tokens.
+ "import-local-media": {
+ kind: "import-local-media",
+ label: "Import external media library",
+ drainable: true,
+ replayable: false,
+ queueKeyStrategy: "custom",
+ needsText: true,
+ },
// PLAYABLE COPIES AND THEIR TORRENTS (release 21 D3,
// controller/preparePlayable.ts): each saved container remuxed losslessly
// into a browser's container, and one torrent per copy. Media: it reads the
@@ -1609,6 +1625,7 @@ const INGEST_KINDS: ReadonlySet<string> = new Set([
"quick-availability-check",
"check-maybe-missing",
"attach-media",
+ "import-local-media",
"prepare-playable",
// A gone video's audio from a copy, and the copy's provenance (release 31).
"fetch-copies",
diff --git a/common/jobs/syncScheduler.test.ts b/common/jobs/syncScheduler.test.ts
@@ -287,3 +287,10 @@ test("nextEligibleAfterFailure: the backoff only grows with the jitter", () => {
assert.equal(nextEligibleAfterFailure(0, 1, sched, 0.25, () => 0), 30 * 60_000);
assert.equal(nextEligibleAfterFailure(0, 1, sched, 0.25, () => 1), Math.ceil(30 * 60_000 * 1.25));
});
+
+test("a remote-only channel never syncs, even with a url, and the console says so (demo epic D1)", () => {
+ const channels = [channel("own", 1 * DAY), channel("remote", 1 * DAY, { remoteOnly: true, remoteArchive: "https://stub.test" })];
+ assert.deepEqual(due(channels).due, ["own"]);
+ const view = buildScheduleView({ channels, scheduler: scheduler(), state: emptySchedulerState(), now: NOW, priority: NO_MODEL });
+ assert.deepEqual(view.map((v) => [v.slug, v.autoSyncEligible]), [["own", true], ["remote", false]]);
+});
diff --git a/common/jobs/syncScheduler.ts b/common/jobs/syncScheduler.ts
@@ -1,4 +1,4 @@
-import type { ChannelConfig } from "../lib/channelConfig";
+import { isRemoteOnlyChannel, type ChannelConfig } from "../lib/channelConfig";
import type { SyncSchedulerSettings } from "../lib/settings";
import {
type ChannelPriority,
@@ -141,6 +141,8 @@ export function selectDueChannels(input: SelectDueInput): SelectDueResult {
for (const { slug, config } of channels) {
if (!config.url) continue; // not auto-sync material; no noise in the log
+ // A remote-only channel (demo epic D1) never syncs: it has no listing.
+ if (isRemoteOnlyChannel(config)) continue;
// ONE SKIP. `excludeFromSync` is gone (S5); the document's `sync` tier is
// what it became, and the migration turned each of the 15 channels that
// carried the flag into `overrides: {sync: "paused"}`. Silent `continue` —
@@ -280,6 +282,7 @@ export function buildScheduleView(input: {
autoSyncEligible:
scheduler.enabled &&
!!config.url &&
+ !isRemoteOnlyChannel(config) &&
!isChannelPaused(priority, slug, "sync") &&
interval > 0,
intervalMinutes: interval,
diff --git a/common/lib/archive/contract.test.ts b/common/lib/archive/contract.test.ts
@@ -164,7 +164,7 @@ test("shipsPwa: the site flag, or hub mode", () => {
test("CONTRACT is frozen where it is published", () => {
// These are on the wire. A change here is a change to every deployed archive's
// machine contract, so it belongs in a slice that says so, not in a refactor.
- assert.equal(CONTRACT.corpusSpec, 5);
+ assert.equal(CONTRACT.corpusSpec, 6);
assert.equal(CONTRACT.siteDescriptor, 1);
assert.equal(CONTRACT.manifest, 3);
assert.equal(CONTRACT.transcriptsManifest, 1);
diff --git a/common/lib/archive/contract.ts b/common/lib/archive/contract.ts
@@ -33,8 +33,10 @@ export const CONTRACT = {
// /corpus.json's own `spec`. `generator` is deliberately unversioned; see the
// note in lib/corpus.ts for why a credit line did not bump the spec. 5: a
// site may publish reports (`reports`), and a CITED site (`site.scope:
- // "cited"`) publishes only them — no channels, no shards.
- corpusSpec: 5,
+ // "cited"`) publishes only them — no channels, no shards. 6: each channel
+ // names its `platform` and its `url` on that platform (demo epic D1), so a
+ // client with no local copy of the channel can fetch its recordings' media.
+ corpusSpec: 6,
// /site.json's `contract` (siteDescriptor.ts).
siteDescriptor: 1,
// The four manifest versions (manifest.ts). Each is the version field of one
diff --git a/common/lib/archive/reader-fs.ts b/common/lib/archive/reader-fs.ts
@@ -43,6 +43,7 @@ import {
PageCache,
PromiseMap,
buildDuplicateIndex,
+ channelPlace,
buildStatsIndex,
buildVideoIndex,
coerceReportIndex,
@@ -295,6 +296,7 @@ export class LocalSource implements ArchiveReader {
name: c.name ?? c.slug,
videoCount: c.videoCount,
groupId: c.groupId,
+ ...channelPlace(c),
}));
}
} catch {
diff --git a/common/lib/archive/reader.test.ts b/common/lib/archive/reader.test.ts
@@ -452,3 +452,37 @@ test("PageCache coalesces concurrent callers and drops a rejection", async () =>
await assert.rejects(() => cache.take("bad", boom));
assert.equal(fails, 2);
});
+
+test("spec 6: a channel's platform and page ride on its ref; an older corpus.json is read as before", async () => {
+ const a = makeArchive({
+ [`${ORIGIN}/corpus.json`]: {
+ ...CORPUS,
+ spec: 6,
+ channels: [
+ { slug: "alpha", name: "Alpha", videoCount: 3, platform: "youtube", url: "https://www.youtube.com/@alpha" },
+ { slug: "beta", name: "Beta", videoCount: 1, platform: "", url: "javascript:alert(1)" },
+ ],
+ },
+ });
+ const restore = installFetch(a);
+ try {
+ const channels = await new RemoteSource(ORIGIN).listChannels();
+ assert.equal(channels[0].platform, "youtube");
+ assert.equal(channels[0].url, "https://www.youtube.com/@alpha");
+ // Junk is not carried.
+ assert.equal("platform" in channels[1], false);
+ assert.equal("url" in channels[1], false);
+ } finally {
+ restore();
+ }
+ // spec 3 (the CORPUS fixture): no platform, no url, nothing else changes.
+ const old = fullArchive();
+ const restoreOld = installFetch(old);
+ try {
+ const [alpha] = await new RemoteSource(ORIGIN).listChannels();
+ assert.equal(alpha.slug, "alpha");
+ assert.equal("platform" in alpha, false);
+ } finally {
+ restoreOld();
+ }
+});
diff --git a/common/lib/archive/reader.ts b/common/lib/archive/reader.ts
@@ -73,6 +73,10 @@ export type ChannelRef = {
siteId?: string;
siteTitle?: string;
siteUrl?: string;
+ // Spec 6 (corpus.json): the channel's platform and its page there, when the
+ // archive names them.
+ platform?: string;
+ url?: string;
};
// The site's channel-group definitions, as read from summaries/manifest.json —
@@ -492,7 +496,18 @@ export type CorpusJsonChannel = {
name?: string;
videoCount?: number;
groupId?: string;
+ // Spec 6.
+ platform?: string;
+ url?: string;
};
+
+// A corpus.json channel's spec-6 facts as a ChannelRef carries them: each
+// only when it is a non-empty string.
+export function channelPlace(c: CorpusJsonChannel): { platform?: string; url?: string } {
+ const platform = typeof c.platform === "string" && c.platform.trim() ? c.platform.trim() : undefined;
+ const url = typeof c.url === "string" && /^https?:\/\//i.test(c.url.trim()) ? c.url.trim() : undefined;
+ return { ...(platform ? { platform } : {}), ...(url ? { url } : {}) };
+}
export type SiteCorpusJson = {
channels?: CorpusJsonChannel[];
// The composed site's own declared public origin — the deployed archilyzer
@@ -677,7 +692,13 @@ export class RemoteSource implements ArchiveReader {
// `budgetBytes` lets a hub divide one memory ceiling across its members
// instead of granting each member the full budget (N members × 48 MB is not a
// budget, it's N budgets).
- constructor(baseUrl: string, budgetBytes = pageCacheBudgetBytes()) {
+ // The fetch every read goes through: the global one by default (a browser,
+ // a test that stubs it), the disk cache on a server (demo epic D1:
+ // common/lib/archiveCache-server.ts, passed by mcp/src/sources.ts).
+ private fetchImpl: typeof fetch;
+
+ constructor(baseUrl: string, budgetBytes = pageCacheBudgetBytes(), opts: { fetch?: typeof fetch } = {}) {
+ this.fetchImpl = opts.fetch ?? ((input, init) => fetch(input, init));
this.base = baseUrl.replace(/\/+$/, "");
this.label = `remote:${this.base}`;
this.subsPages = new PageCache<SubsDetail[]>(budgetBytes);
@@ -864,7 +885,7 @@ export class RemoteSource implements ArchiveReader {
p: string,
kind?: string,
): Promise<{ value: T; bytes: number }> {
- const res = await fetch(`${this.base}${p}`);
+ const res = await this.fetchImpl(`${this.base}${p}`);
if (!res.ok) {
throw new ArchiveHttpError(res.status, `${this.base}${p}`, res.statusText);
}
@@ -953,7 +974,7 @@ export class RemoteSource implements ArchiveReader {
slug: string,
): Promise<ChannelDigestsManifest | null> {
const p = manifestUrl("digests", slug);
- const res = await fetch(`${this.base}${p}`);
+ const res = await this.fetchImpl(`${this.base}${p}`);
if (res.status === 404) return null;
if (!res.ok) {
throw new ArchiveHttpError(res.status, `${this.base}${p}`, res.statusText);
@@ -989,6 +1010,7 @@ export class RemoteSource implements ArchiveReader {
videoCount: c.videoCount,
groupId: c.groupId,
siteUrl: this.base,
+ ...channelPlace(c),
}));
}
diff --git a/common/lib/archiveCache-server.test.ts b/common/lib/archiveCache-server.test.ts
@@ -0,0 +1,200 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { ArchiveDiskCache, archiveCacheEnabled } from "./archiveCache-server";
+import type { FetchLike } from "./remoteArchives-server";
+import { RemoteSource } from "./archive/reader";
+
+// demo epic D1 item 6: a remote archive's documents on disk, by build; one
+// request at a time, paced. A fake archive only.
+
+const ORIGIN = "https://stub.test";
+
+function archive() {
+ const docs = new Map<string, { body: unknown; etag: string }>();
+ const put = (p: string, body: unknown, etag: string) => docs.set(`${ORIGIN}${p}`, { body, etag });
+ const asked: { url: string; ifNoneMatch?: string }[] = [];
+ let inFlight = 0;
+ let maxInFlight = 0;
+ const fetch: FetchLike = async (url, init) => {
+ const ifNoneMatch = init?.headers?.["if-none-match"];
+ asked.push({ url, ...(ifNoneMatch ? { ifNoneMatch } : {}) });
+ inFlight += 1;
+ maxInFlight = Math.max(maxInFlight, inFlight);
+ await new Promise((r) => setTimeout(r, 5));
+ inFlight -= 1;
+ const d = docs.get(url);
+ if (!d) return new Response("nope", { status: 404 });
+ if (ifNoneMatch === d.etag) return new Response(null, { status: 304 });
+ return new Response(JSON.stringify(d.body), { status: 200, headers: { etag: d.etag } });
+ };
+ return { put, asked, fetch, maxInFlight: () => maxInFlight };
+}
+
+function cacheOn(a: ReturnType<typeof archive>, clock: { t: number }, sleeps: number[] = []) {
+ const dir = mkdtempSync(path.join(tmpdir(), "archive-cache-"));
+ const cache = new ArchiveDiskCache({
+ dir,
+ fetch: a.fetch,
+ now: () => clock.t,
+ sleep: async (ms) => {
+ sleeps.push(ms);
+ clock.t += ms;
+ },
+ gapMs: 250,
+ corpusTtlMs: 60_000,
+ });
+ return { cache, dir };
+}
+
+test("a shard read twice under one build is read from the network once", async () => {
+ const a = archive();
+ a.put("/corpus.json", { generatedAt: "g1" }, '"c1"');
+ a.put("/transcripts/alpha/page-0000.json", [{ id: "a1" }], '"p1"');
+ const clock = { t: 1_000_000 };
+ const { cache, dir } = cacheOn(a, clock);
+ try {
+ const url = `${ORIGIN}/transcripts/alpha/page-0000.json`;
+ assert.deepEqual(await (await cache.fetch(url)).json(), [{ id: "a1" }]);
+ assert.deepEqual(a.asked.map((x) => x.url), [url, `${ORIGIN}/corpus.json`]);
+ // A second process (a new cache on the same dir) reads it from disk too: one corpus check, no shard.
+ const again = new ArchiveDiskCache({ dir, fetch: a.fetch, now: () => clock.t, sleep: async () => {}, corpusTtlMs: 60_000 });
+ const res = await again.fetch(url);
+ assert.equal(res.headers.get("x-archive-cache"), "disk");
+ assert.deepEqual(await res.json(), [{ id: "a1" }]);
+ assert.deepEqual(a.asked.slice(2).map((x) => x.url), [], "corpus.json within its TTL is the disk's too");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("a new build: the shard is asked conditionally, a 304 keeps the bytes, a change replaces them", async () => {
+ const a = archive();
+ a.put("/corpus.json", { generatedAt: "g1" }, '"c1"');
+ a.put("/transcripts/alpha/page-0000.json", [{ id: "a1" }], '"p1"');
+ const clock = { t: 1_000_000 };
+ const { cache, dir } = cacheOn(a, clock);
+ try {
+ const url = `${ORIGIN}/transcripts/alpha/page-0000.json`;
+ await cache.fetch(url);
+ // The archive is rebuilt; the corpus check is due.
+ a.put("/corpus.json", { generatedAt: "g2" }, '"c2"');
+ clock.t += 61_000;
+ const fresh = new ArchiveDiskCache({ dir, fetch: a.fetch, now: () => clock.t, sleep: async () => {}, corpusTtlMs: 60_000 });
+ const before = a.asked.length;
+ assert.deepEqual(await (await fresh.fetch(url)).json(), [{ id: "a1" }]);
+ const asked = a.asked.slice(before);
+ assert.deepEqual(asked, [
+ { url: `${ORIGIN}/corpus.json`, ifNoneMatch: '"c1"' },
+ { url, ifNoneMatch: '"p1"' },
+ ]);
+ assert.equal(fresh.stats.notModified, 1);
+ // Unchanged since: the disk again, nothing asked.
+ const n = a.asked.length;
+ await fresh.fetch(url);
+ assert.equal(a.asked.length, n);
+ // The page changed in a third build: replaced.
+ a.put("/corpus.json", { generatedAt: "g3" }, '"c3"');
+ a.put("/transcripts/alpha/page-0000.json", [{ id: "a1" }, { id: "a2" }], '"p2"');
+ clock.t += 61_000;
+ const third = new ArchiveDiskCache({ dir, fetch: a.fetch, now: () => clock.t, sleep: async () => {}, corpusTtlMs: 60_000 });
+ assert.deepEqual(await (await third.fetch(url)).json(), [{ id: "a1" }, { id: "a2" }]);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("one request at a time, the gap between them; an archive that does not answer is served from disk", async () => {
+ const a = archive();
+ a.put("/corpus.json", { generatedAt: "g1" }, '"c1"');
+ for (let i = 0; i < 4; i++) a.put(`/transcripts/alpha/page-000${i}.json`, [{ id: `a${i}` }], `"p${i}"`);
+ const clock = { t: 1_000_000 };
+ const sleeps: number[] = [];
+ const { cache, dir } = cacheOn(a, clock, sleeps);
+ try {
+ // Through the reader, as a sweep reads: its 8-wide page window is serialized here.
+ const reader = new RemoteSource(ORIGIN, undefined, { fetch: cache.fetch as unknown as typeof fetch });
+ await Promise.all([0, 1, 2, 3].map((i) => reader.transcriptPage({ key: "alpha", slug: "alpha", name: "alpha" }, i)));
+ assert.equal(a.maxInFlight(), 1, "never two at once");
+ assert.ok(sleeps.length >= 4 && sleeps.every((ms) => ms > 0 && ms <= 250), JSON.stringify(sleeps));
+ // The host goes away: what is on disk still answers (a new process, past the corpus TTL).
+ clock.t += 120_000;
+ const down: FetchLike = async () => {
+ throw new Error("ECONNREFUSED");
+ };
+ const offline = new ArchiveDiskCache({ dir, fetch: down, now: () => clock.t, sleep: async () => {} });
+ assert.deepEqual(await (await offline.fetch(`${ORIGIN}/transcripts/alpha/page-0002.json`)).json(), [{ id: "a2" }]);
+ await assert.rejects(offline.fetch(`${ORIGIN}/transcripts/alpha/page-0009.json`), /ECONNREFUSED/);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("past the size cap the least recently used documents go", async () => {
+ const a = archive();
+ a.put("/corpus.json", { generatedAt: "g1" }, '"c1"');
+ a.put("/a.json", "x".repeat(400), '"a"');
+ a.put("/b.json", "y".repeat(400), '"b"');
+ const clock = { t: 1_000_000 };
+ const dir = mkdtempSync(path.join(tmpdir(), "archive-cache-"));
+ try {
+ const cache = new ArchiveDiskCache({ dir, fetch: a.fetch, now: () => clock.t, sleep: async () => {}, maxBytes: 600 });
+ await cache.fetch(`${ORIGIN}/a.json`);
+ clock.t += 1000;
+ await cache.fetch(`${ORIGIN}/b.json`);
+ await cache.prune();
+ const n = a.asked.length;
+ await cache.fetch(`${ORIGIN}/b.json`);
+ assert.equal(a.asked.length, n, "the newest is kept");
+ await cache.fetch(`${ORIGIN}/a.json`);
+ assert.equal(a.asked.length, n + 1, "the oldest was dropped");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("on by default on a server; off under node's test runner and with ARCHIVE_CACHE=0", () => {
+ assert.equal(archiveCacheEnabled({}), true);
+ assert.equal(archiveCacheEnabled({ ARCHIVE_CACHE: "0" }), false);
+ assert.equal(archiveCacheEnabled({ NODE_TEST_CONTEXT: "child-v8" }), false);
+ assert.equal(archiveCacheEnabled({ NODE_TEST_CONTEXT: "child-v8", ARCHIVE_CACHE: "1" }), true);
+});
+
+// demo epic D1 review follow-up: no archive document past 32 MB is read or kept.
+test("a document over the bound is refused: by its Content-Length, or as it streams; nothing is kept", async () => {
+ const { MAX_ARCHIVE_DOCUMENT_BYTES, OversizeError, readBounded, probeArchive } = await import("./remoteArchives-server");
+ const declared = new Response("{}", { headers: { "content-length": String(MAX_ARCHIVE_DOCUMENT_BYTES + 1) } });
+ await assert.rejects(readBounded(declared, "https://stub.test/a.json"), (e: unknown) => e instanceof OversizeError && /is over 32 MB/.test((e as Error).message));
+ // No length said: counted as it streams, refused at the bound (a small one here).
+ const streamed = new Response(new ReadableStream({ start(c) { for (let i = 0; i < 10; i++) c.enqueue(new Uint8Array(100)); c.close(); } }));
+ await assert.rejects(readBounded(streamed, "https://stub.test/b.json", 500), OversizeError);
+ assert.equal(await readBounded(new Response('{"ok":1}'), "https://stub.test/c.json"), '{"ok":1}');
+ // The probe says so, and the cache keeps nothing.
+ const big: FetchLike = async () => new Response("{}", { status: 200, headers: { "content-length": String(MAX_ARCHIVE_DOCUMENT_BYTES + 1) } });
+ await assert.rejects(probeArchive("https://stub.test", { fetch: big }), /is over 32 MB/);
+ const dir = mkdtempSync(path.join(tmpdir(), "archive-cache-"));
+ try {
+ const cache = new ArchiveDiskCache({ dir, fetch: big, sleep: async () => {} });
+ await assert.rejects(cache.fetch("https://stub.test/corpus.json"), OversizeError);
+ await assert.rejects(cache.fetch("https://stub.test/corpus.json"), OversizeError, "nothing was kept to answer from");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("the cache's cap is 512 MB unless ARCHIVE_CACHE_MAX_MB says otherwise", async () => {
+ const { ARCHIVE_CACHE_DEFAULT_MB } = await import("./archiveCache-server");
+ assert.equal(ARCHIVE_CACHE_DEFAULT_MB, 512);
+ const saved = process.env.ARCHIVE_CACHE_MAX_MB;
+ delete process.env.ARCHIVE_CACHE_MAX_MB;
+ try {
+ assert.equal(new ArchiveDiskCache({ dir: "/nonexistent" }).maxBytes, 512 * 1024 * 1024);
+ process.env.ARCHIVE_CACHE_MAX_MB = "64";
+ assert.equal(new ArchiveDiskCache({ dir: "/nonexistent" }).maxBytes, 64 * 1024 * 1024);
+ } finally {
+ if (saved === undefined) delete process.env.ARCHIVE_CACHE_MAX_MB;
+ else process.env.ARCHIVE_CACHE_MAX_MB = saved;
+ }
+});
diff --git a/common/lib/archiveCache-server.ts b/common/lib/archiveCache-server.ts
@@ -0,0 +1,307 @@
+// REMOTE ARCHIVE READS, CACHED ON DISK (demo epic D1 item 6).
+//
+// A sweep over a published archive reads its shards — transcript pages of up
+// to 8 MB each — and D0 measured every sweep downloading them again: the
+// readers kept them in memory only, for the life of one process. This is the
+// fetch every server-side reader of a remote archive goes through (the MCP's
+// RemoteSource — so the editor's sweeps and umtool's research — the editor's
+// remote-only registration and umtool's chain): a GET of an archive's JSON is
+// answered from disk while the archive's BUILD has not changed.
+//
+// WHAT "NOT CHANGED" MEANS. A published archive is a static build; its
+// `/corpus.json` `generatedAt` names the build. Every document is kept with
+// the generation it was read under and its ETag (and Last-Modified):
+//
+// corpus.json answered from disk for CORPUS_TTL_MS after it was last
+// checked; then asked again CONDITIONALLY (If-None-Match /
+// If-Modified-Since) — a 304 is a few hundred bytes.
+// anything else answered from disk while its generation is the archive's
+// current one; under a new build it is asked again
+// conditionally, and a 304 keeps the bytes (a shard that did
+// not change between two builds is not downloaded twice).
+//
+// When the archive does not answer, a document on disk is served as it is
+// (a cached read beats a failed sweep); only a 200 is ever kept.
+//
+// ONE REQUEST AT A TIME, PACED. Every network request this process makes
+// through the cache waits for the one before it to end, then for GAP_MS more
+// — a sweep's page reads never burst an archive's host. The disk answers are
+// not paced.
+//
+// WHERE. ARCHIVE_CACHE_DIR, else `.archive-cache` beside the export builds
+// (EXPORT_BUILDS_DIR's parent: /data/builds in a container — the builds
+// volume both the editor and umtool mount — export/ on a checkout). Bounded:
+// past ARCHIVE_CACHE_MAX_MB (default 512: the host's disk is nearly full) the least recently used documents
+// are dropped. Never transcripts/ (it is the corpus), never /tmp (it is RAM).
+
+import { createHash } from "node:crypto";
+import { mkdir, readdir, readFile, rm, stat, utimes } from "node:fs/promises";
+import path from "node:path";
+import { getPaths } from "./paths";
+import { writeFileAtomic } from "./atomicFile.mjs";
+import { OffOriginError, fetchOnOrigin, plainGetJson, readBounded, type FetchLike, type GetJson } from "./remoteArchives-server";
+
+export const CORPUS_TTL_MS = 10 * 60_000;
+export const GAP_MS = 250;
+export const ARCHIVE_CACHE_DEFAULT_MB = 512;
+const DEFAULT_MAX_BYTES = ARCHIVE_CACHE_DEFAULT_MB * 1024 * 1024;
+
+type Meta = {
+ url: string;
+ etag?: string;
+ lastModified?: string;
+ // The archive's corpus generatedAt this copy was read (or revalidated) under.
+ generation?: string | null;
+ // When it was last read or revalidated over the network (ms).
+ checkedAt: number;
+ bytes: number;
+};
+
+export type ArchiveCacheOpts = {
+ dir?: string;
+ fetch?: FetchLike;
+ now?: () => number;
+ sleep?: (ms: number) => Promise<void>;
+ gapMs?: number;
+ corpusTtlMs?: number;
+ maxBytes?: number;
+};
+
+export function archiveCacheDir(env: Record<string, string | undefined> = process.env): string {
+ const set = env.ARCHIVE_CACHE_DIR?.trim();
+ if (set) return path.resolve(/* turbopackIgnore: true */ set);
+ return path.join(path.dirname(getPaths().exportBuildsDir), ".archive-cache");
+}
+
+const isCorpus = (url: string) => /\/corpus\.json$/.test(new URL(url).pathname);
+
+type Init = { signal?: AbortSignal; headers?: Record<string, string>; method?: string };
+
+export class ArchiveDiskCache {
+ readonly dir: string;
+ private doFetch: FetchLike;
+ private now: () => number;
+ private sleep: (ms: number) => Promise<void>;
+ private gapMs: number;
+ private corpusTtlMs: number;
+ readonly maxBytes: number;
+ // One network request at a time: each waits on this.
+ private line: Promise<void> = Promise.resolve();
+ private lastEnd = 0;
+ // base (origin[/path]) -> the generation its corpus.json last said.
+ private generations = new Map<string, string | null>();
+ private bases = new Set<string>();
+ private writes = 0;
+ // Counters, for the tests and a log line.
+ readonly stats = { network: 0, disk: 0, notModified: 0 };
+
+ constructor(opts: ArchiveCacheOpts = {}) {
+ this.dir = opts.dir ?? archiveCacheDir();
+ // The global fetch, looked up per call (a test that stubs it is obeyed).
+ this.doFetch = opts.fetch ?? (((u: string, i?: Init) => fetch(u, i)) as unknown as FetchLike);
+ this.now = opts.now ?? Date.now;
+ this.sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
+ this.gapMs = opts.gapMs ?? GAP_MS;
+ this.corpusTtlMs = opts.corpusTtlMs ?? CORPUS_TTL_MS;
+ const mb = Number(process.env.ARCHIVE_CACHE_MAX_MB);
+ this.maxBytes = opts.maxBytes ?? (Number.isFinite(mb) && mb > 0 ? mb * 1024 * 1024 : DEFAULT_MAX_BYTES);
+ }
+
+ private fileOf(url: string): string {
+ const h = createHash("sha256").update(url).digest("hex");
+ return path.join(this.dir, h.slice(0, 2), h);
+ }
+
+ private async readMeta(file: string): Promise<Meta | null> {
+ try {
+ return JSON.parse(await readFile(`${file}.meta.json`, "utf8")) as Meta;
+ } catch {
+ return null;
+ }
+ }
+
+ // The archive base a URL belongs to: a base whose corpus.json was read
+ // (an archive served under a path), else its origin.
+ private baseOf(url: string): string {
+ const u = new URL(url);
+ const s = `${u.protocol}//${u.host}${u.pathname}`;
+ let best = `${u.protocol}//${u.host}`;
+ for (const b of this.bases) if (s.startsWith(`${b}/`) && b.length > best.length) best = b;
+ return best;
+ }
+
+ /** The archive's current build, by its corpus.json (read through this cache); undefined when it cannot be told. */
+ private async generationOf(base: string): Promise<string | null | undefined> {
+ if (!this.generations.has(base)) {
+ const res = await this.fetch(`${base}/corpus.json`).catch(() => null);
+ if (!res?.ok) return undefined;
+ }
+ return this.generations.get(base);
+ }
+
+ /** Run `fn` as the only network request in flight, after the gap. */
+ private paced<T>(fn: () => Promise<T>): Promise<T> {
+ const run = this.line.then(async () => {
+ const wait = this.lastEnd + this.gapMs - this.now();
+ if (this.lastEnd > 0 && wait > 0) await this.sleep(wait);
+ try {
+ return await fn();
+ } finally {
+ this.lastEnd = this.now();
+ }
+ });
+ this.line = run.then(
+ () => undefined,
+ () => undefined,
+ );
+ return run;
+ }
+
+ private respond(body: string, meta: Meta, from: "disk" | "network"): Response {
+ return new Response(body, {
+ status: 200,
+ headers: { "content-type": "application/json", "x-archive-cache": from, ...(meta.etag ? { etag: meta.etag } : {}) },
+ });
+ }
+
+ private async keep(file: string, body: string, meta: Meta): Promise<void> {
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFileAtomic(file, body);
+ await writeFileAtomic(`${file}.meta.json`, JSON.stringify(meta));
+ if (++this.writes % 20 === 1) await this.prune().catch(() => {});
+ }
+
+ /** A fetch: a GET of an http(s) URL goes through the cache; anything else straight on. */
+ fetch = async (input: string | URL | Request, init?: Init): Promise<Response> => {
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
+ const method = init?.method ?? (input instanceof Request ? input.method : "GET");
+ if (method !== "GET" || !/^https?:\/\//i.test(url)) return this.doFetch(url, init);
+ const file = this.fileOf(url);
+ const meta = await this.readMeta(file);
+ const corpus = isCorpus(url);
+ const base = corpus ? url.replace(/\/corpus\.json$/, "") : this.baseOf(url);
+ let generation: string | null | undefined;
+ if (meta) {
+ if (corpus) {
+ if (this.now() - meta.checkedAt < this.corpusTtlMs) return this.fromDisk(file, meta, base, true);
+ } else {
+ generation = await this.generationOf(base);
+ if (generation !== undefined && generation !== null && meta.generation === generation) return this.fromDisk(file, meta, base, false);
+ }
+ }
+ const headers: Record<string, string> = { accept: "application/json" };
+ if (meta?.etag) headers["if-none-match"] = meta.etag;
+ if (meta?.lastModified) headers["if-modified-since"] = meta.lastModified;
+ let res: Response;
+ try {
+ // On the archive's own origin only: a redirect elsewhere is refused (fetchOnOrigin).
+ res = await this.paced(() => fetchOnOrigin(this.doFetch, url, { ...(init?.signal ? { signal: init.signal } : {}), headers }));
+ } catch (e) {
+ // An off-origin redirect is a refusal, never an outage: nothing on disk answers it.
+ if (e instanceof OffOriginError) throw e;
+ // The archive did not answer: what is on disk is the answer.
+ if (meta) return this.fromDisk(file, meta, base, corpus);
+ throw e;
+ }
+ this.stats.network += 1;
+ if (res.status === 304 && meta) {
+ this.stats.notModified += 1;
+ const g = corpus ? undefined : (generation ?? (await this.generationOf(base)));
+ const next: Meta = { ...meta, checkedAt: this.now(), ...(corpus ? {} : { generation: g ?? meta.generation ?? null }) };
+ await writeFileAtomic(`${file}.meta.json`, JSON.stringify(next)).catch(() => {});
+ return this.fromDisk(file, next, base, corpus, true);
+ }
+ if (!res.ok) {
+ if (meta && res.status >= 500) return this.fromDisk(file, meta, base, corpus);
+ return res;
+ }
+ // Bounded: a document past MAX_ARCHIVE_DOCUMENT_BYTES is refused, never kept.
+ const body = await readBounded(res, url);
+ if (corpus) this.noteCorpus(base, body);
+ const next: Meta = {
+ url,
+ ...(res.headers.get("etag") ? { etag: res.headers.get("etag")! } : {}),
+ ...(res.headers.get("last-modified") ? { lastModified: res.headers.get("last-modified")! } : {}),
+ generation: corpus ? (this.generations.get(base) ?? null) : (generation ?? (await this.generationOf(base)) ?? null),
+ checkedAt: this.now(),
+ bytes: body.length,
+ };
+ await this.keep(file, body, next).catch(() => {});
+ return this.respond(body, next, "network");
+ };
+
+ private noteCorpus(base: string, body: string): void {
+ this.bases.add(base);
+ try {
+ const gen = (JSON.parse(body) as { generatedAt?: unknown }).generatedAt;
+ this.generations.set(base, typeof gen === "string" && gen ? gen : null);
+ } catch {
+ this.generations.set(base, null);
+ }
+ }
+
+ private async fromDisk(file: string, meta: Meta, base: string, corpus: boolean, counted = false): Promise<Response> {
+ const body = await readFile(file, "utf8");
+ if (corpus) this.noteCorpus(base, body);
+ if (!counted) this.stats.disk += 1;
+ // Recently used: the prune drops the oldest first.
+ const t = new Date(this.now());
+ await utimes(file, t, t).catch(() => {});
+ return this.respond(body, meta, "disk");
+ }
+
+ /** Drop the least recently used documents past the size cap. */
+ async prune(): Promise<void> {
+ const files: { file: string; bytes: number; at: number }[] = [];
+ for (const sub of await readdir(this.dir).catch(() => [] as string[])) {
+ const d = path.join(this.dir, sub);
+ for (const name of await readdir(d).catch(() => [] as string[])) {
+ if (name.endsWith(".meta.json") || name.includes(".tmp-")) continue;
+ const st = await stat(path.join(d, name)).catch(() => null);
+ if (st?.isFile()) files.push({ file: path.join(d, name), bytes: st.size, at: st.mtimeMs });
+ }
+ }
+ let total = files.reduce((n, f) => n + f.bytes, 0);
+ if (total <= this.maxBytes) return;
+ files.sort((a, b) => a.at - b.at);
+ for (const f of files) {
+ if (total <= this.maxBytes) break;
+ await rm(f.file, { force: true });
+ await rm(`${f.file}.meta.json`, { force: true });
+ total -= f.bytes;
+ }
+ }
+}
+
+// One cache per directory per process (every route bundle shares it), so
+// "one request at a time" holds across every reader in the process.
+const g = globalThis as { __archiveDiskCaches?: Map<string, ArchiveDiskCache> };
+const caches = (g.__archiveDiskCaches ??= new Map());
+
+/**
+ * Whether the server-side readers use the disk cache: yes, unless
+ * ARCHIVE_CACHE=0 — or the process is a unit test under node's runner
+ * (NODE_TEST_CONTEXT), whose fakes must never meet another test's cached
+ * bytes; such a test builds its own ArchiveDiskCache on a temp dir.
+ */
+export function archiveCacheEnabled(env: Record<string, string | undefined> = process.env): boolean {
+ if (env.ARCHIVE_CACHE === "0") return false;
+ if (env.ARCHIVE_CACHE === "1") return true;
+ return !env.NODE_TEST_CONTEXT;
+}
+
+/** This process's disk cache of archive documents (ARCHIVE_CACHE_DIR, else the default). */
+export function archiveCache(): ArchiveDiskCache {
+ const dir = archiveCacheDir();
+ let c = caches.get(dir);
+ if (!c) {
+ c = new ArchiveDiskCache({ dir });
+ caches.set(dir, c);
+ }
+ return c;
+}
+
+/** The archive documents' reader for the editor's registration and umtool's chain: through the disk cache. */
+export function cachedArchiveGetJson(): GetJson {
+ return archiveCacheEnabled() ? plainGetJson(archiveCache().fetch as unknown as FetchLike) : plainGetJson();
+}
diff --git a/common/lib/archiveHosts-server.test.ts b/common/lib/archiveHosts-server.test.ts
@@ -0,0 +1,112 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { isPrivateAddress, privateHostRefusal } from "./archiveHosts-server";
+
+// demo epic D1 review, blocker 2c: an archive host on this machine or its network.
+
+test("private addresses: loopback, private, link-local, CGNAT, unspecified, IPv6 local, v4-mapped", () => {
+ for (const a of ["127.0.0.1", "10.1.2.3", "172.20.0.1", "192.168.0.1", "169.254.169.254", "100.64.0.1", "0.0.0.0", "::1", "fd00::1", "fe80::1", "::ffff:127.0.0.1", "[::1]"]) {
+ assert.equal(isPrivateAddress(a), true, a);
+ }
+ for (const a of ["93.184.216.34", "172.32.0.1", "2606:4700::1", "8.8.8.8"]) assert.equal(isPrivateAddress(a), false, a);
+});
+
+test("an IPv6 address carrying a private IPv4 is private, in the spelling the URL parser writes (re-review, must-fix 2)", () => {
+ // What `new URL("http://[::ffff:127.0.0.1]")` makes of its host.
+ assert.equal(new URL("http://[::ffff:127.0.0.1]/").hostname, "[::ffff:7f00:1]");
+ for (const a of [
+ "[::ffff:7f00:1]", // 127.0.0.1
+ "[::ffff:a00:1]", // 10.0.0.1
+ "[::ffff:a9fe:a9fe]", // 169.254.169.254
+ "::ffff:c0a8:1", // 192.168.0.1
+ "0:0:0:0:0:ffff:7f00:1",
+ "::ffff:10.0.0.1",
+ "::7f00:1", // IPv4-compatible 127.0.0.1
+ "64:ff9b::7f00:1", // NAT64 of 127.0.0.1
+ "64:ff9b::10.0.0.1",
+ "64:ff9b::a9fe:a9fe",
+ "fec0::1", // site-local
+ "feff::1",
+ "fe80::1%eth0",
+ "ff02::1",
+ "fc00::1",
+ "::",
+ "0:0:0:0:0:0:0:1",
+ ]) {
+ assert.equal(isPrivateAddress(a), true, a);
+ }
+ for (const a of [
+ "[::ffff:5db8:d822]", // 93.184.216.34
+ "::ffff:8.8.8.8",
+ "64:ff9b::808:808", // NAT64 of 8.8.8.8
+ "2606:4700::1",
+ "2001:db8::fe80:1",
+ "fe00::1",
+ ]) {
+ assert.equal(isPrivateAddress(a), false, a);
+ }
+});
+
+test("a mapped literal in an origin is refused at connect, and a name resolving to one too", async () => {
+ const lookup = async (h: string) => (h === "mapped.example" ? [{ address: "::ffff:a00:2" }] : [{ address: "93.184.216.34" }]);
+ assert.match((await privateHostRefusal("http://[::ffff:127.0.0.1]:3001", { lookup }))!, /a local or private address/);
+ assert.match((await privateHostRefusal("http://[64:ff9b::a9fe:a9fe]", { lookup }))!, /a local or private address/);
+ assert.match((await privateHostRefusal("https://mapped.example", { lookup }))!, /\(::ffff:a00:2\)/);
+ assert.equal(await privateHostRefusal("http://[::ffff:5db8:d822]", { lookup }), null);
+});
+
+test("the other ways an IPv6 literal carries a private IPv4: NAT64's local-use prefix, IPv4-translated, 6to4", () => {
+ for (const a of ["::ffff:0:7f00:1", "::ffff:0:10.0.0.1", "2002:7f00:1::", "2002:c0a8:101::1", "2002:a9fe:a9fe::"]) {
+ assert.equal(isPrivateAddress(a), true, a);
+ }
+ for (const a of ["::ffff:0:808:808", "2002:808:808::1"]) assert.equal(isPrivateAddress(a), false, a);
+ // 64:ff9b:1::/48 is local-use whole: private wherever an IPv4 sits in it, and when it carries a public one.
+ for (const a of ["64:ff9b:1::7f00:1", "64:ff9b:1::808:808", "64:ff9b:1:7f00:0:1::", "64:ff9b:1:a00:0:1::", "64:ff9b:1:ffff:ffff:ffff:ffff:ffff", "64:ff9b:1::"]) {
+ assert.equal(isPrivateAddress(a), true, a);
+ }
+ // Its neighbours are not it.
+ for (const a of ["64:ff9b:2::808:808", "64:ff9b:10::1"]) assert.equal(isPrivateAddress(a), false, a);
+});
+
+test("every spelling of a local address in an origin is refused: decimal, hex, octal, short, a trailing dot, bracketed IPv6", async () => {
+ const { archiveOriginOf } = await import("./remoteArchives");
+ // The names' answers are what a resolver gives for them; nothing here is asked of the network.
+ const lookup = async (h: string) => (/^localhost\.?$/.test(h) || /\.local\.?$/.test(h) ? [{ address: "127.0.0.1" }] : [{ address: "93.184.216.34" }]);
+ for (const typed of [
+ "http://[::ffff:7f00:1]",
+ "http://[::ffff:127.0.0.1]",
+ "http://[0:0:0:0:0:ffff:127.0.0.1]",
+ "http://[::1]",
+ "http://[::]",
+ "http://0.0.0.0",
+ "http://0",
+ "http://2130706433", // 127.0.0.1 as one decimal number
+ "http://3232235777", // 192.168.1.1
+ "http://0x7f000001",
+ "http://0x7f.0.0.1",
+ "http://017700000001",
+ "http://0177.0.0.1",
+ "http://127.1",
+ "http://127.0.0.1.",
+ "http://169.254.169.254.",
+ "http://LOCALHOST",
+ "http://localhost.",
+ "http://nas.local.",
+ "http://router.lan",
+ "http://[64:ff9b:1::7f00:1]",
+ "http://[2002:7f00:1::]",
+ ]) {
+ const origin = archiveOriginOf(typed);
+ assert.ok(origin, `${typed} is an origin`);
+ assert.match((await privateHostRefusal(origin, { lookup })) ?? "", /a local or private address|a local name/, typed);
+ }
+});
+
+test("a host's refusal: literal, by name, by what the name resolves to; a public one passes", async () => {
+ const lookup = async (h: string) => (h === "inside.example" ? [{ address: "10.0.0.2" }] : [{ address: "93.184.216.34" }]);
+ assert.match((await privateHostRefusal("http://169.254.169.254", { lookup }))!, /a local or private address/);
+ assert.match((await privateHostRefusal("http://box.localhost:3000", { lookup }))!, /a local name/);
+ assert.match((await privateHostRefusal("https://inside.example", { lookup }))!, /\(10\.0\.0\.2\)/);
+ assert.equal(await privateHostRefusal("https://jeralyzer.pages.dev", { lookup }), null);
+});
+
diff --git a/common/lib/archiveHosts-server.ts b/common/lib/archiveHosts-server.ts
@@ -0,0 +1,121 @@
+// WHICH HOSTS AN ARCHIVE MAY BE (demo epic D1 review, blocker 2c).
+//
+// Connecting an archive makes this machine read the origin's documents — and
+// umtool, which can connect one, is open on the LAN. So an origin whose host is
+// this machine or the local network (loopback, private, link-local, CGNAT, a
+// `.localhost`/`.local`/`.internal` name, or a name that RESOLVES to such an
+// address) is refused at connect, before its corpus.json is asked for —
+// unless the operator decided otherwise ON THIS MACHINE:
+//
+// - ARCHILYZER_ALLOW_PRIVATE_ARCHIVES=1 in the editor's own environment
+// (a stub archive in a test, an archive served on the LAN on purpose);
+// - the origin is TRANSCRIPT_SITE_URL's (the environment's archive);
+// - the origin is already in settings.json (written there by hand).
+//
+// Nothing else checks: once connected, an archive is read on its own origin
+// only (remoteArchives-server.ts fetchOnOrigin). A name re-pointed at a
+// private address after it was connected is not re-checked.
+
+import { lookup as dnsLookup } from "node:dns/promises";
+import { isIP } from "node:net";
+
+export type LookupAll = (host: string) => Promise<{ address: string }[]>;
+
+const defaultLookup: LookupAll = (host) => dnsLookup(host, { all: true });
+
+function v4Private(a: string): boolean {
+ const p = a.split(".").map(Number);
+ if (p.length !== 4 || p.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false;
+ const [x, y] = p;
+ return (
+ x === 0 ||
+ x === 10 ||
+ x === 127 ||
+ (x === 100 && y >= 64 && y <= 127) ||
+ (x === 169 && y === 254) ||
+ (x === 172 && y >= 16 && y <= 31) ||
+ (x === 192 && y === 168) ||
+ x >= 224
+ );
+}
+
+/**
+ * An IPv6 address as its eight 16-bit groups, or null. The URL parser writes
+ * an IPv4-mapped literal in hex (`[::ffff:127.0.0.1]` becomes
+ * `[::ffff:7f00:1]`), so the groups are what is compared, never the text.
+ */
+function v6Groups(address: string): number[] | null {
+ let a = address;
+ // A dotted IPv4 tail is two groups.
+ const tail = /^(.*:)(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(a);
+ if (tail) {
+ const b = tail.slice(2).map(Number);
+ if (b.some((n) => n > 255)) return null;
+ a = `${tail[1]}${((b[0] << 8) | b[1]).toString(16)}:${((b[2] << 8) | b[3]).toString(16)}`;
+ }
+ const halves = a.split("::");
+ if (halves.length > 2) return null;
+ const parse = (part: string) => (part === "" ? [] : part.split(":").map((g) => (/^[0-9a-f]{1,4}$/.test(g) ? parseInt(g, 16) : NaN)));
+ const head = parse(halves[0]);
+ const rest = halves.length === 2 ? parse(halves[1]) : [];
+ const fill = halves.length === 2 ? 8 - head.length - rest.length : 0;
+ if (fill < 0) return null;
+ const groups = [...head, ...new Array<number>(fill).fill(0), ...rest];
+ return groups.length === 8 && groups.every((g) => Number.isInteger(g)) ? groups : null;
+}
+
+const v4Of = (hi: number, lo: number) => `${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`;
+
+/**
+ * Whether an IP address is loopback, private, link-local, site-local, CGNAT,
+ * unspecified or multicast — in IPv6 also when it only CARRIES such an IPv4
+ * address: IPv4-mapped (`::ffff:a.b.c.d`, in either spelling), the old
+ * IPv4-compatible form (`::a.b.c.d`), NAT64 (`64:ff9b::/96`), IPv4-translated
+ * (`::ffff:0:a.b.c.d`) and 6to4 (`2002::/16`). NAT64's local-use block
+ * `64:ff9b:1::/48` is private whole.
+ */
+export function isPrivateAddress(address: string): boolean {
+ const a = address.replace(/^\[|\]$/g, "").toLowerCase();
+ const kind = isIP(a);
+ if (kind === 4) return v4Private(a);
+ if (kind !== 6) return false;
+ const g = v6Groups(a.split("%")[0]);
+ if (!g) return true; // an IPv6 literal this cannot read is not vouched for
+ const zero = (from: number, to: number) => g.slice(from, to).every((n) => n === 0);
+ if (zero(0, 7) && (g[7] === 0 || g[7] === 1)) return true; // ::, ::1
+ if (zero(0, 5) && g[5] === 0xffff) return v4Private(v4Of(g[6], g[7])); // IPv4-mapped
+ if (zero(0, 6)) return v4Private(v4Of(g[6], g[7])); // IPv4-compatible (deprecated)
+ if (g[0] === 0x64 && g[1] === 0xff9b && zero(2, 6)) return v4Private(v4Of(g[6], g[7])); // NAT64
+ if (g[0] === 0x64 && g[1] === 0xff9b && g[2] === 1) return true; // 64:ff9b:1::/48, NAT64's local-use block: never globally routable, whatever it carries
+ if (zero(0, 4) && g[4] === 0xffff && g[5] === 0) return v4Private(v4Of(g[6], g[7])); // IPv4-translated ::ffff:0:a.b.c.d
+ if (g[0] === 0x2002) return v4Private(v4Of(g[1], g[2])); // 6to4 2002:a.b.c.d::/48
+ return (
+ (g[0] & 0xfe00) === 0xfc00 || // fc00::/7 unique local
+ (g[0] & 0xffc0) === 0xfe80 || // fe80::/10 link-local
+ (g[0] & 0xffc0) === 0xfec0 || // fec0::/10 site-local (deprecated)
+ (g[0] & 0xff00) === 0xff00 // ff00::/8 multicast
+ );
+}
+
+const PRIVATE_NAME = /(^|\.)(localhost|local|internal|lan|home\.arpa)$/i;
+
+/**
+ * Why `origin`'s host may not be connected, or null: a private address
+ * literally, a private name, or a name resolving to a private address. A name
+ * that does not resolve is left to the probe, which says it did not answer.
+ */
+export async function privateHostRefusal(origin: string, opts: { lookup?: LookupAll } = {}): Promise<string | null> {
+ let host: string;
+ try {
+ host = new URL(origin).hostname.replace(/^\[|\]$/g, "");
+ } catch {
+ return null;
+ }
+ const say = (why: string) =>
+ `${origin} is ${why} — an archive on this machine or its network is connected only when the editor runs with ARCHILYZER_ALLOW_PRIVATE_ARCHIVES=1, or names it in TRANSCRIPT_SITE_URL or settings.json`;
+ if (isIP(host)) return isPrivateAddress(host) ? say("a local or private address") : null;
+ if (PRIVATE_NAME.test(host)) return say("a local name");
+ const found = await (opts.lookup ?? defaultLookup)(host).catch(() => [] as { address: string }[]);
+ const inside = found.find((f) => isPrivateAddress(f.address));
+ return inside ? say(`a name for a local or private address (${inside.address})`) : null;
+}
diff --git a/common/lib/archiveTrust.test.ts b/common/lib/archiveTrust.test.ts
@@ -0,0 +1,157 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { connectedArchives, disconnectedArchiveRefusal, isPlatformHost, recordPage, recordPageRefusal, sameOrigin } from "./remoteArchives";
+import { fetchOnOrigin, OffOriginError, plainGetJson, type FetchLike } from "./remoteArchives-server";
+import { detectPlatform } from "./detectPlatform.mjs";
+
+// demo epic D1 review, blocker 2: an archive is untrusted input.
+
+test("a record's page URL: only a video platform's host, the channel's own platform, no credentials", () => {
+ const r = (u: string | undefined, p: string | null = null) => recordPageRefusal(u, p, detectPlatform);
+ assert.equal(r("https://www.youtube.com/watch?v=a1", "youtube"), null);
+ assert.equal(r("https://rumble.com/v9-x.html"), null);
+ assert.match(r("http://127.0.0.1:3001/api/ops/settings")!, /127\.0\.0\.1:3001 is not a video platform's host/);
+ assert.match(r("http://10.0.0.5/threads/123/")!, /is not a video platform's host/, "xenforo is a path on any host: never a window's page");
+ assert.match(r("https://evil.example/watch?v=a1")!, /is not a video platform's host/);
+ assert.match(r("https://rumble.com/v9-x.html", "youtube")!, /rumble\.com is rumble, and the channel is youtube's/);
+ assert.match(r("https://user:pw@www.youtube.com/watch?v=a1")!, /is not a page URL a window is fetched from/);
+ assert.match(r("file:///etc/passwd")!, /is not a page URL a window is fetched from/);
+ assert.equal(r(undefined), "no page URL");
+});
+
+test("a record's page URL: a look-alike of a platform's host is not that platform (re-review, must-fix 1)", () => {
+ const r = (u: string, p: string | null = null) => recordPageRefusal(u, p, detectPlatform);
+ // detectPlatform says "youtube" of each of these (a bare endsWith); the host table does not.
+ for (const u of [
+ "https://evilyoutube.com/watch?v=a1",
+ "https://notrumble.com/v9-x.html",
+ "https://fakeodysee.com/@a/b",
+ "https://xtwitch.tv/videos/1",
+ "https://akick.com/video/1",
+ "https://www.youtube.com.evil.example/watch?v=a1",
+ "https://youtu.be.evil.example/a1",
+ "https://web.archive.org/web/2020/https://www.youtube.com/watch?v=a1",
+ "https://notbitchute.com/video/a/",
+ "https://notyoutube.com/watch?v=a1",
+ "https://evil-rumble.com/v9-x.html",
+ "https://rumble.comevil.example/v9-x.html",
+ "https://evil.example/youtube.com/watch?v=a1",
+ "https://youtube.com%2eevil.example/watch?v=a1",
+ "https://youtubе.com/watch?v=a1", // a Cyrillic е
+ ]) {
+ assert.match(r(u)!, /is not a video platform's host/, u);
+ }
+ assert.match(r("https://evilyoutube.com/watch?v=a1", "youtube")!, /^evilyoutube\.com is not a video platform's host/);
+ // The platforms' own hosts, bare and under a subdomain.
+ for (const u of [
+ "https://youtube.com/watch?v=a1",
+ "https://m.youtube.com/watch?v=a1",
+ "https://music.youtube.com/watch?v=a1",
+ "https://youtu.be/a1",
+ "https://rumble.com/v9-x.html",
+ "https://www.rumble.com/v9-x.html",
+ "https://odysee.com/@a/b",
+ "https://www.twitch.tv/videos/1",
+ "https://kick.com/video/1",
+ "https://archive.org/details/x",
+ "https://www.archive.org/details/x",
+ "https://www.bitchute.com/video/a/",
+ "https://old.bitchute.com/video/a/",
+ ]) {
+ assert.equal(r(u), null, u);
+ }
+ assert.equal(isPlatformHost("youtube", "YOUTUBE.com"), true);
+ assert.equal(isPlatformHost("youtube", "youtube.com.evil.example"), false);
+ assert.equal(isPlatformHost("twitter", "x.com"), false, "not a video platform: no table, no host");
+});
+
+// demo epic D1 re-check: the host judged must be the host fetched. Node's URL
+// parser and Python's urlsplit (yt-dlp's) read these differently.
+test("a page URL two parsers read differently is refused unparsed: a backslash, whitespace, a control character", () => {
+ const r = (u: string, p: string | null = null) => recordPageRefusal(u, p, detectPlatform);
+ // What Node makes of the first: the platform's own host. Python's urlsplit says evil.example.
+ assert.equal(new URL("https://youtube.com\\@evil.example/watch?v=x").hostname, "youtube.com");
+ assert.equal(new URL("https://you\ttube.com/watch?v=x").hostname, "youtube.com");
+ for (const u of [
+ "https://youtube.com\\@evil.example/watch?v=x",
+ "https://youtube.com\\@127.0.0.1/x",
+ "https://rumble.com\\.evil.example/v1",
+ "https://you\ttube.com/watch?v=x",
+ " https://youtube.com/watch?v=x",
+ "https://youtube.com/watch?v=x ",
+ "https://youtube.com/watch?v=x\n",
+ "https://youtube.com\r\n@evil.example/",
+ "https://youtube.com/\\evil.example",
+ "https:\\\\youtube.com/watch?v=x",
+ "https://youtube.com/watch?v=x\u0000",
+ "https://youtube.com/wa tch?v=x",
+ "https://youtube.com /watch?v=x",
+ "https://youtube.com @evil.example/",
+ "https://youtube.com/watch?v=x",
+ "https://youtube.com/watch?v=x",
+ "https://youtube.com/watch?v=x\u007f",
+ ]) {
+ assert.match(r(u) ?? "(allowed)", /carries a backslash, whitespace or a control character/, JSON.stringify(u));
+ assert.match(r(u, "youtube") ?? "(allowed)", /carries a backslash, whitespace or a control character/, JSON.stringify(u));
+ }
+});
+
+test("a page URL that passes is handed on as the parser wrote it back, never as it was given", () => {
+ const page = (u: string, p: string | null = null) => recordPage(u, p, detectPlatform);
+ for (const [given, href, platform] of [
+ ["https://www.youtube.com/watch?v=a1", "https://www.youtube.com/watch?v=a1", "youtube"],
+ ["HTTPS://WWW.YouTube.com:443/watch?v=a1", "https://www.youtube.com/watch?v=a1", "youtube"],
+ ["https:youtube.com/watch?v=a1", "https://youtube.com/watch?v=a1", "youtube"],
+ ["https:///youtu.be/a1", "https://youtu.be/a1", "youtube"],
+ ["http://RUMBLE.com", "http://rumble.com/", "rumble"],
+ ["https://rumble.com/a/../v9-x.html", "https://rumble.com/v9-x.html", "rumble"],
+ ["https://youtube.com./watch?v=a1", "https://youtube.com./watch?v=a1", "youtube"],
+ ] as const) {
+ const got = page(given);
+ if ("refused" in got) {
+ // A spelling the platform table does not vouch for is refused, not passed raw.
+ assert.equal(given, "https://youtube.com./watch?v=a1", `${given}: ${got.refused}`);
+ continue;
+ }
+ assert.deepEqual(got, { href, platform }, given);
+ assert.equal(got.href, new URL(given).href);
+ // And the href is its own fixed point: judged again it is the same URL.
+ assert.deepEqual(page(got.href), got);
+ }
+ assert.deepEqual(page("https://rumble.com/v9-x.html", "youtube"), { refused: "rumble.com is rumble, and the channel is youtube's: the archive's page URL is not fetched" });
+});
+
+test("an archive removed from settings is not read for the channel registered from it (re-review, item 6)", () => {
+ const list = connectedArchives([{ id: "stub", origin: "https://stub.test", title: "Stub", addedAt: "2026-11-11T00:00:00Z" }], {});
+ assert.equal(disconnectedArchiveRefusal("https://stub.test", list), null);
+ assert.equal(disconnectedArchiveRefusal("https://stub.test/", list), null);
+ assert.equal(disconnectedArchiveRefusal(undefined, list), null, "a channel naming no archive has none to lose");
+ assert.match(disconnectedArchiveRefusal("https://stub.test", [])!, /^its archive https:\/\/stub\.test is no longer connected/);
+ // The environment's archive counts as connected.
+ assert.equal(disconnectedArchiveRefusal("https://env.test", connectedArchives([], { TRANSCRIPT_SITE_URL: "https://env.test" })), null);
+});
+
+function redirecting(map: Record<string, { status: number; location?: string; body?: unknown }>): FetchLike & { asked: string[] } {
+ const asked: string[] = [];
+ const f = (async (url: string) => {
+ asked.push(url);
+ const d = map[url];
+ if (!d) return new Response("nope", { status: 404 });
+ return new Response(d.body === undefined ? null : JSON.stringify(d.body), { status: d.status, headers: d.location ? { location: d.location } : {} });
+ }) as FetchLike & { asked: string[] };
+ f.asked = asked;
+ return f;
+}
+
+test("an archive's documents are read on its own origin: a same-origin redirect is followed, one elsewhere refused unfollowed", async () => {
+ const f = redirecting({
+ "https://stub.test/corpus.json": { status: 301, location: "/v2/corpus.json" },
+ "https://stub.test/v2/corpus.json": { status: 200, body: { ok: 1 } },
+ "https://stub.test/transcripts/a/manifest.json": { status: 302, location: "http://127.0.0.1:3001/api/ops/settings" },
+ });
+ assert.deepEqual(await plainGetJson(f)("https://stub.test/corpus.json"), { ok: 1 });
+ await assert.rejects(fetchOnOrigin(f, "https://stub.test/transcripts/a/manifest.json"), (e: unknown) => e instanceof OffOriginError && /redirects to http:\/\/127\.0\.0\.1:3001/.test((e as Error).message));
+ assert.equal(f.asked.includes("http://127.0.0.1:3001/api/ops/settings"), false);
+ assert.equal(sameOrigin("https://stub.test:443/x", "https://stub.test"), true);
+ assert.equal(sameOrigin("https://stub.test:8443/x", "https://stub.test"), false);
+});
diff --git a/common/lib/attachMediaPlan.test.ts b/common/lib/attachMediaPlan.test.ts
@@ -190,3 +190,22 @@ test("records: title from the folder name, date and description from description
assert.equal(other.webpage_url, undefined);
assert.equal(other.extractor, undefined);
});
+
+// lane/local-media review fix 5: a held record linked to a local media library
+// original (its external-media.json) is never attached, replace or not.
+test("plan: a held record linked to a local media library is class local-media, never attach", () => {
+ const folders = groupArchiveFolders(ARCHIVE);
+ for (const replace of [false, true]) {
+ const plan = planAttach({
+ folders,
+ held: new Set(["aaaaaaaaaaa"]),
+ attached: new Set(["aaaaaaaaaaa"]),
+ localMedia: new Set(["aaaaaaaaaaa"]),
+ ...(replace ? { replace: true } : {}),
+ });
+ const row = plan.rows.find((r) => r.id === "aaaaaaaaaaa")!;
+ assert.equal(row.class, "local-media");
+ assert.equal(countAttachRows(plan.rows)["local-media"], 1);
+ assert.equal(countAttachRows(plan.rows).attach, 0);
+ }
+});
diff --git a/common/lib/attachMediaPlan.ts b/common/lib/attachMediaPlan.ts
@@ -1,3 +1,4 @@
+import { LOCAL_RECORDING_ID_RE } from "./localMedia";
// WHICH FILE OF A LOCAL ARCHIVE IS WHICH VIDEO (release 21 D1).
//
// The pure half of `attach-media` (controller/attachMedia.ts): given the file
@@ -231,6 +232,10 @@ export const ATTACH_ROW_CLASSES = [
"unmatched",
// More than one video file for one id: name the file with `items`.
"ambiguous",
+ // A held record linked to a local media library original (its
+ // `external-media.json`), or a local recording: never attached — its video
+ // is the library's (lane/local-media review fix 5).
+ "local-media",
] as const;
export type AttachRowClass = (typeof ATTACH_ROW_CLASSES)[number];
@@ -261,6 +266,8 @@ export function planAttach(opts: {
folders: readonly ArchiveFolder[];
held: ReadonlySet<string>;
attached: ReadonlySet<string>;
+ // Held records linked to a local media library original (class "local-media").
+ localMedia?: ReadonlySet<string>;
createRecords?: boolean;
replace?: boolean;
match?: RegExp;
@@ -270,6 +277,9 @@ export function planAttach(opts: {
files?: readonly SourceFile[];
}): AttachPlan {
const classify = (id: string, media: SourceFile, folder: string, source?: ArchiveFolder): AttachRow => {
+ if (opts.localMedia?.has(id) || LOCAL_RECORDING_ID_RE.test(id)) {
+ return { class: "local-media", id, folder, media, ...(source ? { source } : {}) };
+ }
if (opts.held.has(id)) {
if (opts.attached.has(id) && !opts.replace) {
return { class: "already-attached", id, folder, media, ...(source ? { source } : {}) };
diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts
@@ -1,3 +1,4 @@
+import { coerceLocalMediaConfig, type LocalMediaConfig } from "./localMedia";
import { PLATFORM_VALUES, type Platform } from "./platform";
import { coerceWaybackPagesConfig, type WaybackPagesConfig } from "./waybackPages/config";
import { coerceXSearchConfig, type XSearchConfig } from "./xSearch/config";
@@ -35,6 +36,30 @@ export function isSocialChannel(
return config?.sourceKind === "social";
}
+// A REMOTE-ONLY channel (demo epic D1): one the editor holds ONLY to fetch
+// clip windows a connected archive's citations name — config only, no
+// listing, no transcripts of its own. Inert everywhere a real channel is
+// active: no sync, no lane, no cleanup, no auto-download, on no site, in no
+// index build (every guard asks this predicate).
+export function isRemoteOnlyChannel(
+ config: Pick<ChannelConfig, "remoteOnly"> | null | undefined,
+): boolean {
+ return config?.remoteOnly === true;
+}
+
+// The sentence every door that would list, sync or download a channel
+// answers a remote-only one with; null for any other channel.
+export function remoteOnlyRefusal(
+ slug: string,
+ config: Pick<ChannelConfig, "remoteOnly" | "remoteArchive"> | null | undefined,
+): string | null {
+ if (!isRemoteOnlyChannel(config)) return null;
+ return (
+ `${slug} is a remote-only channel${config?.remoteArchive ? ` of ${config.remoteArchive}` : ""}: ` +
+ "it holds that archive's clip windows only, and is never listed, synced or downloaded here"
+ );
+}
+
export type AudioFormat = "m4a" | "mp3" | "opus";
// Who owns audio extraction for a transcribe-handling download:
@@ -244,6 +269,13 @@ export type ChannelConfig = {
lastFullDownloadAt?: string;
lastFullSweepAt?: string;
excludeFromBuild?: boolean;
+ // A remote-only channel (isRemoteOnlyChannel): registered on first need for
+ // a connected archive's clip windows; `remoteArchive` is that archive's
+ // origin and `remoteUrl` the channel's page on its platform, as the archive
+ // named it (never `url`, so nothing that syncs a channel by its url can).
+ remoteOnly?: boolean;
+ remoteArchive?: string;
+ remoteUrl?: string;
excludeFromCleanup?: boolean;
cleanAfterCaptureUnverified?: boolean;
syncIntervalMinutes?: number;
@@ -269,6 +301,8 @@ export type ChannelConfig = {
wayback?: WaybackPagesConfig;
// Release 38: an X search channel's query (lib/xSearch/config.ts).
xSearch?: XSearchConfig;
+ // External library inputs are not managed media. A config change never moves files.
+ localMedia?: LocalMediaConfig;
};
// In the order parseChannelConfig emits (and CHANNEL.md lists) them.
@@ -316,6 +350,16 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = {
lastFullSweepAt:
"SYNC STATE. When this channel last paid for a sync FULL SWEEP — the deep pass that re-enumerates the whole listing to refresh `playlist` and flag videos that have left it. Stamped by the sweep; read by the cadence gate to decide whether the next sync sweeps or stays on the cheap newest-first paged walk.",
excludeFromBuild: "Leave this channel out of every site build.",
+ remoteOnly:
+ "A REMOTE-ONLY channel: held only to fetch clip windows that a connected archive's citations name " +
+ "(settings.remoteArchives). Registered by the editor the first time a window of it is asked for, with no " +
+ "listing sweep. Inert: no sync, no lane, no cleanup, no auto-download, on no site, in no index build; the " +
+ "channel list shows it as remote-only. A whole-recording platform's window (Rumble) is refused with the " +
+ "recording's size until the ask says `allowWholeRecording`.",
+ remoteArchive: "A remote-only channel's archive: the origin whose corpus.json names it.",
+ remoteUrl:
+ "A remote-only channel's page on its platform, as its archive's corpus.json named it (spec 6). Informational: " +
+ "a remote-only channel has no `url`, so nothing syncs it.",
excludeFromCleanup:
"Leave this channel's reclaimable bytes out of the aggregate \"cleanable data\" total on /cleanup and its badge. The per-channel cleanup sweeps stay available; only the running total changes.",
cleanAfterCaptureUnverified:
@@ -351,6 +395,8 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = {
'A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest", auto?: true}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture\'s original URL. Each capture imported (`pnpm ops import-page`, the channel page\'s **Import a capture**) becomes a page record in the channel\'s posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped. `auto: true` lets the download lane import the captures a later scan (`pnpm ops wayback-scan`, the **Captures** tab) adds, one job each at archive.org\'s pace; absent, nothing is imported unasked. Release 37 lane F: a target\'s `sources` (`["wayback", "archive.today"]`; absent = the Wayback Machine alone) says which archives hold its copies, and an archive.today copy imported into the channel is a page record like a capture (OPERATING.md, "Archived pages: the Wayback Machine and archive.today"); the form calls the kind "Archived pages".',
xSearch:
'An X SEARCH channel (platform `"twitter"`, `sourceKind` `"social"`, `url` the search page): a saved X search across accounts, its records the matching posts from ANY author. `{query, since?, until?, windowMonths?, lang?, exclude?}` — `query` as X\'s search box takes it (words, `"phrases"`, `OR`, `-term`, `from:`, `to:`, `@mention`, `url:`, `filter:`, `lang:` pass through; `since:`, `until:` and `max_id:` are refused — the walk adds them); `since`/`until` the days walked between (YYYY-MM-DD; `since` inclusive, `until` exclusive; absent `until` = tomorrow, and each later fetch searches what is new); `windowMonths` each search window\'s span (1–12, default 3); `lang` a language code added as `lang:<code>`; `exclude` the handles **Never archive** hid from the leads view (lower case). A fetch walks the windows newest first through gallery-dl\'s search, resumable, at the older walk\'s pace and with its login (OPERATING.md, "X search"). Never on a site. An object without a valid query is dropped.',
+ localMedia:
+ "Opt-in external MP4 library: {sourceId, directory, playback?}. The sourceId is a stable lowercase identifier; directory is an absolute server/container path. Source files remain externally owned. Playback is off unless explicitly true, and this flag alone does not authorize public serving. Removing or changing configuration must never move or delete source files. Do not reuse an existing sourceId for a different library; reconcile references explicitly. Private configuration: never include source paths in public exports.",
};
// Every key a config.json may carry, in emission order. The unknown-key oracle:
@@ -541,6 +587,9 @@ export const CHANNEL_CONFIG_COERCIONS: {
lastFullDownloadAt: str,
lastFullSweepAt: str,
excludeFromBuild: bool,
+ remoteOnly: (v) => (v === true ? true : undefined),
+ remoteArchive: trimmedNonBlank,
+ remoteUrl: trimmedNonBlank,
excludeFromCleanup: bool,
cleanAfterCaptureUnverified: bool,
syncIntervalMinutes: zeroOrClamped(SYNC_INTERVAL_MIN_MINUTES, SYNC_INTERVAL_MAX_MINUTES),
@@ -565,6 +614,7 @@ export const CHANNEL_CONFIG_COERCIONS: {
mirror: coerceMirrorConfig,
wayback: coerceWaybackPagesConfig,
xSearch: coerceXSearchConfig,
+ localMedia: coerceLocalMediaConfig,
};
// A channel's config.json as a ChannelConfig, or null when it is not a channel
diff --git a/common/lib/channelConfigSchema.test.ts b/common/lib/channelConfigSchema.test.ts
@@ -39,7 +39,7 @@ test("one key list: docs = coercions = schema shape, sync-state keys inside it",
assert.deepEqual(Object.keys(CHANNEL_CONFIG_COERCIONS), [...CHANNEL_CONFIG_KEYS]);
assert.deepEqual(Object.keys(channelConfigObjectSchema.shape), [...CHANNEL_CONFIG_KEYS]);
assert.deepEqual(Object.keys(CHANNEL_CONFIG_FIELD_DOCS), [...CHANNEL_CONFIG_KEYS]);
- assert.equal(CHANNEL_CONFIG_KEYS.length, 43); // 2026-11-11: `cleanAfterCaptureUnverified`
+ assert.equal(CHANNEL_CONFIG_KEYS.length, 47); // 2026-11-11: `cleanAfterCaptureUnverified`; lane/local-media: opt-in `localMedia`; demo epic D1: `remoteOnly`, `remoteArchive`, `remoteUrl`
assert.equal(sameKeys, true);
assert.equal(fits, true);
for (const k of CHANNEL_SYNC_STATE_KEYS) assert.ok(CHANNEL_CONFIG_KEYS.includes(k), k);
@@ -170,3 +170,19 @@ test("the zod schema and the client-safe parser agree, key order included", () =
assert.deepEqual(Object.keys(b ?? {}), Object.keys(a ?? {}));
}
});
+
+test("localMedia is opt-in and both parsers agree on valid and invalid inputs", () => {
+ for (const localMedia of [
+ { sourceId: "library-1", directory: "/mnt/library" },
+ { sourceId: "library-1", directory: "/mnt/library", playback: true },
+ { sourceId: "library-1", directory: "/mnt/library", playback: "true" },
+ { sourceId: "../escape", directory: "/mnt/library" },
+ { sourceId: "library-1", directory: "relative" },
+ ]) {
+ assert.deepEqual(parse({ handling: "youtube", localMedia }), parseChannelConfig({ handling: "youtube", localMedia }));
+ }
+ assert.deepEqual(parse({ handling: "youtube", localMedia: { sourceId: "library-1", directory: "/mnt/library" } })!.localMedia,
+ { sourceId: "library-1", directory: "/mnt/library" });
+ assert.equal("localMedia" in parse({ handling: "youtube" })!, false);
+ assert.equal("localMedia" in parse({ handling: "youtube", localMedia: { sourceId: "x", directory: "relative" } })!, false);
+});
diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts
@@ -68,6 +68,9 @@ export const channelConfigObjectSchema = z.object({
lastFullDownloadAt: field("lastFullDownloadAt"),
lastFullSweepAt: field("lastFullSweepAt"),
excludeFromBuild: field("excludeFromBuild"),
+ remoteOnly: field("remoteOnly"),
+ remoteArchive: field("remoteArchive"),
+ remoteUrl: field("remoteUrl"),
excludeFromCleanup: field("excludeFromCleanup"),
cleanAfterCaptureUnverified: field("cleanAfterCaptureUnverified"),
syncIntervalMinutes: field("syncIntervalMinutes"),
@@ -86,6 +89,7 @@ export const channelConfigObjectSchema = z.object({
mirror: field("mirror"),
wayback: field("wayback"),
xSearch: field("xSearch"),
+ localMedia: field("localMedia"),
});
// Drop every own key whose value is `undefined` (the OMIT rule, above).
diff --git a/common/lib/chartAggregate.ts b/common/lib/chartAggregate.ts
@@ -79,6 +79,7 @@ export function applyFilters(
const platformSet =
f.platforms && f.platforms.length ? new Set(f.platforms) : null;
return stats.filter((s) => {
+ if ((f.dateFrom || f.dateTo) && !s.uploadDate) return false;
if (f.dateFrom && s.uploadDate < f.dateFrom) return false;
if (f.dateTo && s.uploadDate > f.dateTo) return false;
if (channelSet && !channelSet.has(s.channelSlug)) return false;
diff --git a/common/lib/corpus.test.ts b/common/lib/corpus.test.ts
@@ -190,15 +190,36 @@ test("Use with AI is the homepage's AI and MCP doc; the chat is the instance's /
}
});
-test("the spec is 5, and `generator` is still not why", () => {
- // Guard on the reasoning, not just the number: a bump announces a new
- // FETCHABLE document. spec 4 is /tags.json, spec 5 the reports index (and a
- // cited site that publishes only reports). The informational credit string
- // added at spec 3's time breaks no reader and did not bump anything — if
- // either assertion is ever updated, the version-history comment in corpus.ts
- // must justify why.
- assert.equal(CORPUS_SPEC_VERSION, 5);
- assert.equal(buildSiteCorpus(descriptor(), { hasArchives: false }).spec, 5);
+test("the spec is 6, and `generator` is still not why", () => {
+ // Guard on the reasoning, not just the number: a bump announces something a
+ // reader can FETCH that it could not before. spec 4 is /tags.json, spec 5 the
+ // reports index (and a cited site that publishes only reports), spec 6 each
+ // channel's platform and page — where a cited moment's MEDIA is fetched from,
+ // which a machine with no copy of the channel had no way to learn (demo epic
+ // D1). The informational credit string added at spec 3's time breaks no
+ // reader and did not bump anything — if either assertion is ever updated,
+ // the version-history comment in corpus.ts must justify why.
+ assert.equal(CORPUS_SPEC_VERSION, 6);
+ assert.equal(buildSiteCorpus(descriptor(), { hasArchives: false }).spec, 6);
+});
+
+test("spec 6: a channel names its platform and its page there, only when known; llms.txt says so", () => {
+ const corpus = buildSiteCorpus(descriptor({ siteUrl: "https://demo.example" }), {
+ hasArchives: false,
+ channelFacts: { [descriptor().channels[0].slug]: { platform: "youtube", url: "https://www.youtube.com/@demo" } },
+ });
+ const [first, ...rest] = corpus.channels;
+ assert.equal(first.platform, "youtube");
+ assert.equal(first.url, "https://www.youtube.com/@demo");
+ for (const c of rest) {
+ assert.equal("platform" in c, false);
+ assert.equal("url" in c, false);
+ }
+ // Without facts the entries are shaped as at spec 5.
+ for (const c of buildSiteCorpus(descriptor(), { hasArchives: false }).channels) assert.deepEqual(Object.keys(c).filter((k) => k === "platform" || k === "url"), []);
+ const llms = renderSiteLlmsTxt(corpus);
+ assert.match(llms, new RegExp(`- ${first.name} \\(youtube: https://www\\.youtube\\.com/@demo\\) — `));
+ assert.match(llms, /Each channel names its `platform` and its `url` there when known \(spec 6\)/);
});
test("the tags pointer is present only when the site published one", () => {
diff --git a/common/lib/corpus.ts b/common/lib/corpus.ts
@@ -43,6 +43,15 @@ import {
// An older reader sees an empty corpus there, which is the safe reading: there
// is no shard to fetch.
//
+// v6: each channel names WHERE IT IS — `platform` (youtube, rumble, …) and
+// `url`, the channel's own page on that platform, when the archive's operator
+// configured one (demo epic D1). A machine with no copy of the channel (a
+// fresh clone pointed at this archive) needs both to fetch a cited moment's
+// media: the platform decides the pacing and whether a window is a seek or a
+// whole recording. Additive: an older reader ignores both; a reader of an
+// older archive falls back to a shard record's `webpageUrl` / `platform`
+// (common/lib/remoteArchives-server.ts channelFactsOf).
+//
// NOT a v4: the `generator` field added below is deliberately unversioned. Every
// prior bump announced a new FETCHABLE LAYER — a reader that ignored it would
// miss data it could otherwise have retrieved. `generator` is an informational
@@ -166,6 +175,10 @@ export type CorpusChannel = {
name: string;
videoCount: number;
groupId?: string;
+ // Spec 6: the channel's platform and its page there. Each present only when
+ // known: a curated mix of several platforms' videos has no url.
+ platform?: string;
+ url?: string;
manifests: {
transcripts: string;
subs: string;
@@ -279,6 +292,9 @@ export function buildSiteCorpus(
// A CITED site's build: `site.scope: "cited"` and `site.audience` always.
// Its descriptor carries no channels, so the corpus has none.
cited?: boolean;
+ // slug -> where the channel is (spec 6): its platform and its page there,
+ // from its config. A channel absent here, or a field left out, is unknown.
+ channelFacts?: Record<string, { platform?: string; url?: string }>;
},
): SiteCorpus {
const base = descriptor.siteUrl;
@@ -292,6 +308,8 @@ export function buildSiteCorpus(
name: c.name,
videoCount: c.count,
...(c.groupId ? { groupId: c.groupId } : {}),
+ ...(opts.channelFacts?.[c.slug]?.platform ? { platform: opts.channelFacts[c.slug].platform } : {}),
+ ...(opts.channelFacts?.[c.slug]?.url ? { url: opts.channelFacts[c.slug].url } : {}),
...(postCount ? { postCount } : {}),
...(opts.channelKinds?.[c.slug] ? { kind: opts.channelKinds[c.slug] } : {}),
...(digestCount ? { digestCount } : {}),
@@ -459,7 +477,9 @@ export function renderSiteLlmsTxt(
out.push("## Corpus");
out.push(
`- [corpus.json](${corpusUrl(base)}): machine-readable index — ` +
- `channels and how to fetch any transcript from the paginated JSON shards.`,
+ `channels and how to fetch any transcript from the paginated JSON shards. ` +
+ `Each channel names its \`platform\` and its \`url\` there when known (spec 6): ` +
+ `where a cited moment's media is fetched from.`,
);
if (corpus.digestScheme) {
const digested = corpus.channels.reduce(
@@ -499,7 +519,8 @@ export function renderSiteLlmsTxt(
out.push("## Channels");
const shown = corpus.channels.slice(0, LLMS_INLINE_LIMIT);
for (const c of shown) {
- out.push(`- ${c.name} — ${c.videoCount} transcripts: ${c.manifests.transcripts}`);
+ const where = c.url ? ` (${c.platform ? `${c.platform}: ` : ""}${c.url})` : c.platform ? ` (${c.platform})` : "";
+ out.push(`- ${c.name}${where} — ${c.videoCount} transcripts: ${c.manifests.transcripts}`);
}
if (corpus.channels.length > shown.length) {
out.push(
diff --git a/common/lib/duplicates.test.ts b/common/lib/duplicates.test.ts
@@ -562,3 +562,16 @@ test("a contained cluster (clip of a longer video) never shares", () => {
true,
);
});
+
+// lane/local-media review fix 3: a public site's duplicates keep no local recording.
+test("filterClusterToChannels takes a per-record rule: a local recording left out", () => {
+ const c = cluster([
+ ref({ slug: "a/1", channelSlug: "a", platform: "youtube" }),
+ ref({ slug: "a/local-" + "a".repeat(32), channelSlug: "a", platform: "local", id: "local-" + "a".repeat(32) }),
+ ref({ slug: "b/2", channelSlug: "b", platform: "rumble" }),
+ ]);
+ const out = filterClusterToChannels(c, new Set(["a", "b"]), (r) => r.platform !== "local");
+ assert.deepEqual(out?.videoRefs.map((r) => r.slug), ["a/1", "b/2"]);
+ assert.equal(filterClusterToChannels(c, new Set(["a"]), (r) => r.platform !== "local"), null);
+ assert.equal(filterClusterToChannels(c, new Set(["a", "b"]))?.videoRefs.length, 3);
+});
diff --git a/common/lib/duplicates.ts b/common/lib/duplicates.ts
@@ -266,7 +266,7 @@ const PLATFORM_PREFERENCE: ReadonlyArray<string> = [
"bitchute",
];
-function platformRank(platform: string): number {
+export function platformRank(platform: string): number {
const i = PLATFORM_PREFERENCE.indexOf(platform);
return i < 0 ? PLATFORM_PREFERENCE.length : i;
}
@@ -725,9 +725,12 @@ export function strongerMatch(
export function filterClusterToChannels(
cluster: DuplicateCluster,
channelSlugs: Set<string>,
+ // A further per-record rule: a public site keeps no local recording
+ // (lib/localMedia.ts isLocalRecord; bin/compose-site.ts).
+ keepRef?: (ref: DuplicateVideoRef) => boolean,
): DuplicateCluster | null {
const videoRefs = cluster.videoRefs.filter((r) =>
- channelSlugs.has(r.channelSlug),
+ channelSlugs.has(r.channelSlug) && (keepRef ? keepRef(r) : true),
);
if (videoRefs.length < 2) return null;
return {
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -134,7 +134,11 @@ const DECLARED: EnvVarDecl[] = [
{ name: "REPORTS_DIR", audience: "runtime", default: "`~/reports` (or the parent of `SONG_REPORTS_DIR`)", readBy: "common/lib/report/delete.ts, common/bin/case.ts, umtool (lib/paths.mjs)", doc: "umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete." },
{ name: "SONG_REPORTS_DIR", audience: "runtime", default: "unset", readBy: "common/lib/report/delete.ts, common/bin/case.ts, umtool (song/paths.mjs)", doc: "umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete and `archilyzer case` read (as umtool does)." },
{ name: "UMTOOL_URL", audience: "runtime", default: "unset (no link; the MCP's `notes` off)", readBy: "editor/app/channels/[slug]/videos/[id]/page.tsx, common/lib/umtoolUrl.ts, mcp/src/archivalTools.ts", doc: "umtool's front door; when set, the video page links to it, its Find clips hands the recording to umtool's clip finder (the `find-clips` job posts to `/api/report/clips` with WORKER_TOKEN), and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). Unset: Find clips is disabled." },
- { name: "TRANSCRIPT_SITE_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: one published archive to read over HTTP." },
+ { name: "TRANSCRIPT_SITE_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: one published archive to read over HTTP. Also the default connected archive (common/lib/remoteArchives.ts): the editor, umtool and the MCP offer it as a source when settings.remoteArchives does not list it, without writing it." },
+ { name: "ARCHILYZER_ALLOW_PRIVATE_ARCHIVES", audience: "runtime", default: "off", readBy: "common/controller/remoteArchives.ts", doc: "`1` lets the editor connect an archive whose host is this machine or its network (loopback, private, link-local, a `.local` name, or a name resolving to such an address), which is refused otherwise: umtool, which can connect one, is open on the LAN. TRANSCRIPT_SITE_URL's archive, and one already written in settings.json, are connected without it. The check is made once, when the archive is connected: a name re-pointed at a private address afterwards is not rechecked (the archive is still read on its own origin only)." },
+ { name: "ARCHIVE_CACHE_DIR", audience: "runtime", default: "`.archive-cache` beside EXPORT_BUILDS_DIR", readBy: "common/lib/archiveCache-server.ts", doc: "Where a remote archive's documents (corpus.json, manifests, shard pages) are kept on disk, by the archive's build: a sweep over a published archive downloads a shard once per build, not once per sweep. In a container it is on the builds volume." },
+ { name: "ARCHIVE_CACHE_MAX_MB", audience: "runtime", default: "512", readBy: "common/lib/archiveCache-server.ts", doc: "The disk cache of remote archive documents' size cap, MB: past it the least recently used are dropped." },
+ { name: "ARCHIVE_CACHE", audience: "runtime", default: "on (off under node's test runner)", readBy: "common/lib/archiveCache-server.ts", doc: "`0` reads remote archives without the disk cache (every read over the network, still one at a time); `1` turns it on under node's test runner, where it is off." },
{ name: "TRANSCRIPT_HUB_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: a hub, federating every archive it lists." },
{ name: "TRANSCRIPT_LOCAL_DIR", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: a composed public dir on disk." },
{ name: "TRANSCRIPT_PLATFORM_LINKS", audience: "runtime", default: "off", readBy: "common/lib/archive/reader-fs.ts", doc: "`1` cites platform watch pages instead of the archive's own pages." },
diff --git a/common/lib/externalMedia-server.test.ts b/common/lib/externalMedia-server.test.ts
@@ -0,0 +1,38 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, writeFile, readFile, readdir, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { loadExternalMediaReference, writeExternalMediaReference, forgetExternalMediaReference } from "./externalMedia-server";
+import { dropSavedVideo, unpersistSavedVideo, loadSavedVideo } from "./savedVideo-server";
+import { EXTERNAL_MEDIA_FILENAME, type ExternalMediaReference } from "./localMedia";
+
+test("external sidecar round-trips; managed drop/unpersist ignore it; forgetting does not touch source", async (t) => {
+ const root = await mkdtemp(path.join(tmpdir(), "external-media-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const videoDir = path.join(root, "corpus");
+ const source = path.join(root, "external");
+ await mkdir(videoDir); await mkdir(source);
+ await writeFile(path.join(source, "original.mp4"), "externally owned bytes");
+ const value: ExternalMediaReference = { version: 1, kind: "external", sourceId: "library-1", relativePath: "original.mp4" };
+ await writeExternalMediaReference(videoDir, value);
+ assert.deepEqual(await loadExternalMediaReference(videoDir), value);
+ assert.equal(await loadSavedVideo(videoDir), null);
+ assert.equal(await dropSavedVideo(videoDir), 0);
+ assert.equal(await unpersistSavedVideo(videoDir), false);
+ assert.deepEqual(await loadExternalMediaReference(videoDir), value);
+ await forgetExternalMediaReference(videoDir);
+ assert.equal(await loadExternalMediaReference(videoDir), null);
+ assert.deepEqual(await readdir(source), ["original.mp4"]);
+ assert.equal(await readFile(path.join(source, "original.mp4"), "utf8"), "externally owned bytes");
+});
+test("invalid writes refuse; corrupt or future-version references load as null", async (t) => {
+ const root = await mkdtemp(path.join(tmpdir(), "external-media-invalid-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ await assert.rejects(writeExternalMediaReference(root, {} as ExternalMediaReference), /Invalid/);
+ assert.deepEqual(await readdir(root), []);
+ for (const body of ["{", JSON.stringify({ version: 2, kind: "external", sourceId: "x", relativePath: "a.mp4" })]) {
+ await writeFile(path.join(root, EXTERNAL_MEDIA_FILENAME), body);
+ assert.equal(await loadExternalMediaReference(root), null);
+ }
+});
diff --git a/common/lib/externalMedia-server.ts b/common/lib/externalMedia-server.ts
@@ -0,0 +1,17 @@
+import { sidecar, sidecarField } from "./sidecar-server";
+import { EXTERNAL_MEDIA_FILENAME, coerceExternalMediaReference, type ExternalMediaReference } from "./localMedia";
+
+// This sidecar has no saved-video pointer fields and no target-file operations.
+// Forgetting a reference removes only corpus metadata. It cannot remove, move,
+// or open the external recording because this module never resolves its path.
+// Keep resolution/playback in a separate, guarded read-only server module.
+const reference = sidecar(EXTERNAL_MEDIA_FILENAME, sidecarField(coerceExternalMediaReference));
+export const loadExternalMediaReference = reference.load;
+export const forgetExternalMediaReference = reference.remove;
+export async function writeExternalMediaReference(videoDir: string, value: ExternalMediaReference): Promise<void> {
+ // sidecar() validates reads but does not validate writes. Validate explicitly
+ // here so malformed references are never silently persisted by JS callers.
+ const parsed = coerceExternalMediaReference(value);
+ if (!parsed) throw new Error("Invalid external media reference");
+ await reference.write(videoDir, parsed);
+}
diff --git a/common/lib/externalMediaResolver-server.test.ts b/common/lib/externalMediaResolver-server.test.ts
@@ -0,0 +1,102 @@
+import { test, type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, writeFile, readFile, rm, symlink } from "node:fs/promises";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import { openExternalMedia } from "./externalMediaResolver-server";
+
+// Synthetic roots only. The resolver accepts a config and reference so neither
+// tests nor this leaf need to open operator settings or the live corpus.
+async function fixture(t: TestContext) {
+ const root = await mkdtemp(path.join(tmpdir(), "external-resolver-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const source = path.join(root, "source");
+ await mkdir(source);
+ await writeFile(path.join(source, "video.mp4"), "original bytes");
+ return { root, source, config: { sourceId: "library-1", directory: source },
+ reference: { version: 1, kind: "external", sourceId: "library-1", relativePath: "video.mp4" } };
+}
+async function linkOrSkip(t: TestContext, target: string, link: string, directory = false) {
+ try { await symlink(target, link, directory ? "junction" : "file"); return true; }
+ catch (error) {
+ if (process.platform === "win32" && (error as NodeJS.ErrnoException).code === "EPERM") {
+ t.skip("Windows symlink privilege unavailable; verify in Linux container"); return false;
+ }
+ throw error;
+ }
+}
+test("inspect opens read-only, reports size, and preserves original bytes", async (t) => {
+ const f = await fixture(t);
+ const got = await openExternalMedia({ ...f, purpose: "inspect" });
+ assert.equal(got.status, "ready");
+ if (got.status !== "ready") return;
+ try {
+ assert.equal(got.bytes, Buffer.byteLength("original bytes"));
+ assert.equal(await got.handle.readFile("utf8"), "original bytes");
+ await assert.rejects(got.handle.write(Buffer.from("overwrite"), 0, 9, 0));
+ } finally { await got.handle.close(); }
+ assert.equal(await readFile(path.join(f.source, "video.mp4"), "utf8"), "original bytes");
+});
+test("playback requires explicit opt-in; source mismatch is refused", async (t) => {
+ const f = await fixture(t);
+ assert.deepEqual(await openExternalMedia({ ...f, purpose: "playback" }), { status: "refused", reason: "playback-disabled" });
+ assert.deepEqual(await openExternalMedia({ ...f, reference: { ...f.reference, sourceId: "different" }, purpose: "inspect" }),
+ { status: "refused", reason: "source-mismatch" });
+ const got = await openExternalMedia({ ...f, config: { ...f.config, playback: true }, purpose: "playback" });
+ assert.equal(got.status, "ready");
+ if (got.status === "ready") await got.handle.close();
+});
+test("absolute and traversal references are refused before file access", async (t) => {
+ const f = await fixture(t);
+ for (const relativePath of ["../video.mp4", "/etc/video.mp4", "a/../../video.mp4", "C:/video.mp4", "a\\video.mp4"]) {
+ assert.deepEqual(await openExternalMedia({ ...f, reference: { ...f.reference, relativePath }, purpose: "inspect" }),
+ { status: "refused", reason: "invalid-reference" });
+ }
+});
+test("missing configuration and unsupported runtime purposes fail closed", async (t) => {
+ const f = await fixture(t);
+ assert.deepEqual(await openExternalMedia({ ...f, config: null, purpose: "inspect" }), { status: "refused", reason: "invalid-config" });
+ assert.deepEqual(await openExternalMedia({ ...f, purpose: "other" as "inspect" }), { status: "refused", reason: "playback-disabled" });
+});
+test("missing root or media is unavailable without changing the reference", async (t) => {
+ const f = await fixture(t);
+ const before = JSON.stringify(f.reference);
+ await rm(path.join(f.source, "video.mp4"));
+ assert.deepEqual(await openExternalMedia({ ...f, purpose: "inspect" }), { status: "refused", reason: "unavailable" });
+ await rm(f.source, { recursive: true });
+ assert.deepEqual(await openExternalMedia({ ...f, purpose: "inspect" }), { status: "refused", reason: "unavailable" });
+ assert.equal(JSON.stringify(f.reference), before);
+});
+test("directory masquerading as MP4 is not a regular file", async (t) => {
+ const f = await fixture(t);
+ await rm(path.join(f.source, "video.mp4")); await mkdir(path.join(f.source, "video.mp4"));
+ assert.deepEqual(await openExternalMedia({ ...f, purpose: "inspect" }), { status: "refused", reason: "not-regular" });
+});
+test("literal Unicode and percent paths resolve without URL decoding", async (t) => {
+ const f = await fixture(t);
+ const relativePath = "nested/A 'title' $money ⧸ %2e%2e.mp4";
+ await mkdir(path.join(f.source, "nested")); await writeFile(path.join(f.source, relativePath), "literal");
+ const got = await openExternalMedia({ ...f, reference: { ...f.reference, relativePath }, purpose: "inspect" });
+ assert.equal(got.status, "ready");
+ if (got.status === "ready") { try { assert.equal(await got.handle.readFile("utf8"), "literal"); } finally { await got.handle.close(); } }
+});
+test("final-file symlinks are rejected even when their target is within the library", async (t) => {
+ const f = await fixture(t);
+ if (!await linkOrSkip(t, path.join(f.source, "video.mp4"), path.join(f.source, "alias.mp4"))) return;
+ assert.deepEqual(await openExternalMedia({ ...f, reference: { ...f.reference, relativePath: "alias.mp4" }, purpose: "inspect" }), { status: "refused", reason: "unsafe-path" });
+});
+test("ancestor symlink escape and sibling-prefix trick are rejected", async (t) => {
+ const f = await fixture(t);
+ const sibling = f.source + "-outside";
+ await mkdir(sibling); await writeFile(path.join(sibling, "video.mp4"), "outside");
+ if (!await linkOrSkip(t, sibling, path.join(f.source, "escape"), true)) return;
+ assert.deepEqual(await openExternalMedia({ ...f, reference: { ...f.reference, relativePath: "escape/video.mp4" }, purpose: "inspect" }),
+ { status: "refused", reason: "unsafe-path" });
+});
+test("operator configured root may itself be a directory link", async (t) => {
+ const f = await fixture(t);
+ const link = path.join(f.root, "configured-root");
+ if (!await linkOrSkip(t, f.source, link, true)) return;
+ const got = await openExternalMedia({ ...f, config: { ...f.config, directory: link }, purpose: "inspect" });
+ assert.equal(got.status, "ready"); if (got.status === "ready") await got.handle.close();
+});
diff --git a/common/lib/externalMediaResolver-server.ts b/common/lib/externalMediaResolver-server.ts
@@ -0,0 +1,86 @@
+import path from "node:path";
+import { constants, type Stats } from "node:fs";
+import { lstat, open, realpath, stat, type FileHandle } from "node:fs/promises";
+import { coerceExternalMediaReference, coerceLocalMediaConfig } from "./localMedia";
+
+export type ExternalMediaOpenResult =
+ | { status: "ready"; handle: FileHandle; bytes: number }
+ | { status: "refused"; reason: "invalid-config" | "invalid-reference" | "source-mismatch"
+ | "playback-disabled" | "unsafe-path" | "not-regular" | "changed-during-open" | "unavailable" };
+
+function contained(root: string, candidate: string): boolean {
+ const relative = path.relative(root, candidate);
+ return !!relative && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
+}
+
+// Open EXTERNALLY OWNED media for reading only. No write, unlink, rename, or
+// source-directory creation is possible through this module. Returning the
+// verified handle (not a pathname to reopen) preserves file identity for the
+// caller's eventual stream. The caller MUST close a successful handle.
+//
+// Configuration comes from the operator, never a request's supplied root. A
+// playback opt-in is only one gate: HTTP authentication, site exposure policy,
+// channel guards and stalled-drive handling belong in the caller before this
+// low-level helper is used. This slice does not expose an HTTP route.
+//
+// TRUST MODEL: roots and their directory entries are operator-controlled.
+// Refuse symlinks beneath the canonical root, recheck identity after open, and
+// use O_NOFOLLOW when available. These checks defend against ordinary escapes
+// and replacements; portable Node path APIs are NOT equivalent to Linux
+// openat2(RESOLVE_BENEATH) against an adversary concurrently swapping ancestors.
+// Do not offer this resolver as a hostile multi-user filesystem sandbox.
+export async function openExternalMedia(options: {
+ config: unknown;
+ reference: unknown;
+ purpose: "inspect" | "playback";
+}): Promise<ExternalMediaOpenResult> {
+ const config = coerceLocalMediaConfig(options.config);
+ if (!config || !path.isAbsolute(config.directory)) return { status: "refused", reason: "invalid-config" };
+ const ref = coerceExternalMediaReference(options.reference);
+ if (!ref) return { status: "refused", reason: "invalid-reference" };
+ if (config.sourceId !== ref.sourceId) return { status: "refused", reason: "source-mismatch" };
+ // Unknown runtime purpose must fail closed, even for an untyped caller.
+ if (options.purpose !== "inspect" && (options.purpose !== "playback" || config.playback !== true)) {
+ return { status: "refused", reason: "playback-disabled" };
+ }
+ let handle: FileHandle | undefined;
+ try {
+ const root = await realpath(config.directory);
+ if (!(await stat(root)).isDirectory()) return { status: "refused", reason: "unsafe-path" };
+ const parts = ref.relativePath.split("/");
+ let candidate = root;
+ let before: Stats | undefined;
+ for (let index = 0; index < parts.length; index++) {
+ candidate = path.join(candidate, parts[index]);
+ if (!contained(root, candidate)) return { status: "refused", reason: "unsafe-path" };
+ const entry = await lstat(candidate);
+ if (entry.isSymbolicLink()) return { status: "refused", reason: "unsafe-path" };
+ if (index < parts.length - 1 && !entry.isDirectory()) return { status: "refused", reason: "unsafe-path" };
+ before = entry;
+ }
+ if (!before?.isFile()) return { status: "refused", reason: "not-regular" };
+ if (!contained(root, await realpath(candidate))) return { status: "refused", reason: "unsafe-path" };
+ // NONBLOCK avoids hanging if a regular file is replaced by a FIFO between
+ // lstat and open. File kind is checked again on the opened descriptor.
+ handle = await open(candidate, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
+ const opened = await handle.stat();
+ const after = await lstat(candidate);
+ if (!opened.isFile() || !after.isFile() || after.isSymbolicLink()
+ || opened.dev !== before.dev || opened.ino !== before.ino
+ || opened.dev !== after.dev || opened.ino !== after.ino
+ || opened.size !== before.size || opened.mtimeMs !== before.mtimeMs
+ || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs
+ || !contained(root, await realpath(candidate))) {
+ return { status: "refused", reason: "changed-during-open" };
+ }
+ const result: ExternalMediaOpenResult = { status: "ready", handle, bytes: opened.size };
+ handle = undefined; // Ownership transfers only on success; finally closes failures.
+ return result;
+ } catch {
+ // A missing, inaccessible or disconnected source is not an absent record.
+ // Return a bounded private-path-free status; never repair or delete it here.
+ return { status: "refused", reason: "unavailable" };
+ } finally {
+ if (handle) await handle.close();
+ }
+}
diff --git a/common/lib/localMedia.test.ts b/common/lib/localMedia.test.ts
@@ -0,0 +1,42 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { coerceLocalMediaConfig, coerceExternalMediaReference } from "./localMedia";
+
+test("source config preserves identity, trims root, and requires explicit playback opt-in", () => {
+ for (const playback of [undefined, false, "true", 1]) {
+ assert.deepEqual(coerceLocalMediaConfig({ sourceId: "library-1", directory: " /mnt/library ", playback }),
+ { sourceId: "library-1", directory: "/mnt/library" });
+ }
+ assert.deepEqual(coerceLocalMediaConfig({ sourceId: "library-1", directory: "D:\\Media", playback: true, secret: "ignored" }),
+ { sourceId: "library-1", directory: "D:\\Media", playback: true });
+});
+test("invalid config is omitted rather than enabling a fallback library", () => {
+ for (const value of [null, [], {}, { sourceId: "../x", directory: "/mnt/library" },
+ { sourceId: "UPPER", directory: "/mnt/library" }, { sourceId: "x", directory: "relative" },
+ { sourceId: "x", directory: "C:relative" }, { sourceId: "x", directory: "//server/share" },
+ { sourceId: "x", directory: "/mnt/\u0000bad" }]) assert.equal(coerceLocalMediaConfig(value), undefined);
+});
+const ref = (relativePath: string) => ({ version: 1, kind: "external", sourceId: "library-1", relativePath });
+test("references preserve literal Unicode and percent filenames; unknown fields cannot become managed pointers", () => {
+ const value = ref("Folder/A 'title' $money ⧸ | %2e%2e.mp4");
+ assert.deepEqual(coerceExternalMediaReference({ ...value, dir: "/outside", file: "owned.mp4" }), value);
+});
+test("references reject cross-platform traversal and unknown formats", () => {
+ for (const name of ["/absolute.mp4", "../a.mp4", "a/../b.mp4", "a/./b.mp4", "a//b.mp4", "C:/a.mp4",
+ "a\\b.mp4", "a.mp4:stream", "a\u0000.mp4", "a.vtt", "", "./a.mp4"]) {
+ assert.equal(coerceExternalMediaReference(ref(name)), null, name);
+ }
+ for (const value of [null, [], { ...ref("a.mp4"), version: 2 }, { ...ref("a.mp4"), kind: "managed" },
+ { ...ref("a.mp4"), sourceId: "../x" }]) assert.equal(coerceExternalMediaReference(value), null);
+});
+
+test("localMediaFetchRefusal: a library channel with no URL, or a local recording anywhere", async () => {
+ const { localMediaFetchRefusal } = await import("./localMedia");
+ const lib = { localMedia: { sourceId: "library-1", directory: "/mnt/library" } };
+ assert.equal(localMediaFetchRefusal("lib", lib),
+ '"lib" is a local media library channel with no online source, so no clip can be fetched for it.');
+ assert.equal(localMediaFetchRefusal("lib", { ...lib, url: "https://www.youtube.com/@x" }, "dQw4w9WgXcQ"), null);
+ assert.match(localMediaFetchRefusal("lib", { url: "https://www.youtube.com/@x" }, "local-" + "c".repeat(32))!, /is a local recording/);
+ assert.equal(localMediaFetchRefusal("yt", { url: "https://www.youtube.com/@x" }, "dQw4w9WgXcQ"), null);
+ assert.equal(localMediaFetchRefusal("nourl", {}), null);
+});
diff --git a/common/lib/localMedia.ts b/common/lib/localMedia.ts
@@ -0,0 +1,96 @@
+// Client-safe shapes only: no filesystem or zod imports. Channel forms and
+// the server schema must share these coercions without shipping server code.
+// A source ID identifies an operator-approved library, not ownership of it.
+export type LocalMediaConfig = {
+ sourceId: string;
+ directory: string;
+ playback?: true;
+};
+export const EXTERNAL_MEDIA_FILENAME = "external-media.json";
+export type ExternalMediaReference = {
+ version: 1;
+ kind: "external";
+ sourceId: string;
+ relativePath: string;
+};
+function record(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === "object" && !Array.isArray(value);
+}
+export function isLocalMediaSourceId(value: unknown): value is string {
+ return typeof value === "string" && /^[a-z0-9][a-z0-9_-]{0,63}$/.test(value);
+}
+export function coerceLocalMediaConfig(value: unknown): LocalMediaConfig | undefined {
+ if (!record(value) || !isLocalMediaSourceId(value.sourceId)
+ || typeof value.directory !== "string") return undefined;
+ const directory = value.directory.trim();
+ // Syntax only, on either OS. The server must still use its own path rules,
+ // realpath containment, and source access checks before scanning or serving.
+ // UNC roots are deferred; do not treat a drive-relative C:folder as absolute.
+ if (!directory || /[\x00-\x1f\x7f]/.test(directory)
+ || !(directory.startsWith("/") && !directory.startsWith("//")
+ || /^[A-Za-z]:[\\/]/.test(directory))) return undefined;
+ return { sourceId: value.sourceId, directory,
+ ...(value.playback === true ? { playback: true as const } : {}) };
+}
+export function coerceExternalMediaReference(value: unknown): ExternalMediaReference | null {
+ if (!record(value) || value.version !== 1 || value.kind !== "external"
+ || !isLocalMediaSourceId(value.sourceId) || typeof value.relativePath !== "string") return null;
+ const relativePath = value.relativePath;
+ // Store literal filenames using '/' separators, never URL-decode them.
+ // Reject both OSes' escape syntax regardless of the machine doing the read.
+ // No path normalization: it would conceal traversal or change a source name.
+ if (!relativePath || relativePath.length > 4096 || /[\\:\x00-\x1f\x7f]/.test(relativePath)
+ || relativePath.split("/").some((part) => !part || part === "." || part === "..")
+ || !/\.mp4$/i.test(relativePath)) return null;
+ return { version: 1, kind: "external", sourceId: value.sourceId, relativePath };
+}
+
+// A source-less recording's record id (lib/localRecordingDetails.ts assigns it).
+export const LOCAL_RECORDING_ID_RE = /^local-[0-9a-f]{32}$/;
+
+// A LOCAL MEDIA LIBRARY channel (a library and no online URL) or a local
+// recording in any channel has no online source: a clip window, a full-source
+// fetch or a report video's clip cannot be fetched for it. One sentence, the
+// same at every door (the editor's fetch-window and fetch-windows, the
+// fetch-windows job, the evidence planner, umtool's own fetch); null when the
+// fetch may go ahead. Private playback of the local originals is slice 4.
+export function localMediaFetchRefusal(
+ slug: string,
+ config: { localMedia?: unknown; url?: string | null } | null | undefined,
+ id?: string,
+): string | null {
+ const who = localMediaSubject(slug, config, id);
+ return who ? `${who} with no online source, so no clip can be fetched for it.` : null;
+}
+
+// The same rule for the doors that READ METADATA from the source (refresh
+// metadata, the metadata scan, the browser lookup): a sibling sentence.
+export function localMediaMetadataRefusal(
+ slug: string,
+ config: { localMedia?: unknown; url?: string | null } | null | undefined,
+ id?: string,
+): string | null {
+ const who = localMediaSubject(slug, config, id);
+ return who ? `${who} with no online source, so its metadata cannot be read from one.` : null;
+}
+
+function localMediaSubject(
+ slug: string,
+ config: { localMedia?: unknown; url?: string | null } | null | undefined,
+ id?: string,
+): string | null {
+ const localChannel = !!config?.localMedia && !config.url?.trim();
+ const localRecord = typeof id === "string" && LOCAL_RECORDING_ID_RE.test(id);
+ if (!localChannel && !localRecord) return null;
+ return localRecord ? `"${id}" is a local recording` : `"${slug}" is a local media library channel`;
+}
+
+// A record of a local media library's own (platform "local", or its
+// `local-<32 hex>` id where only the id is known). Until private playback
+// (slice 4) decides otherwise, such a record is built only into PRIVATE-audience
+// sites: a public site's shards, counts, stats, duplicates and reports leave it
+// out (controller/buildIndex.ts, controller/buildStats.ts, bin/compose-site.ts,
+// publish/composeReports.ts). Review ruling, lane/local-media slice 1.
+export function isLocalRecord(rec: { platform?: string | null; id?: string | null }): boolean {
+ return rec.platform === "local" || (typeof rec.id === "string" && LOCAL_RECORDING_ID_RE.test(rec.id));
+}
diff --git a/common/lib/localMediaCommit-server.test.ts b/common/lib/localMediaCommit-server.test.ts
@@ -0,0 +1,89 @@
+import { test, type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, readFile, readdir, rm, writeFile, lstat } from "node:fs/promises";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import { commitLocalMediaRecord } from "./localMediaCommit-server";
+
+async function fixture(t: TestContext) {
+ const root = await mkdtemp(path.join(tmpdir(), "local-media-commit-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const dataDirectory = path.join(root, "data"); await mkdir(dataDirectory);
+ const input = { dataDirectory, directoryId: "test-id",
+ metadata: JSON.stringify({ id: "test-id", title: "Synthetic", duration: 3, upload_date: "20261030", webpage_url: "https://www.youtube.com/watch?v=test-id" }),
+ transcript: "WEBVTT\r\n\r\n00:00:01.000 --> 00:00:02.000\r\nSynthetic cue\r\n",
+ reference: { version: 1, kind: "external", sourceId: "library-1", relativePath: "Original ⧸ $title.mp4" } };
+ return { root, input, target: path.join(dataDirectory, "test-id") };
+}
+test("publishes only canonical text/reference files, metadata last, preserving supplied bytes", async (t) => {
+ const f = await fixture(t);
+ const result = await commitLocalMediaRecord(f.input, { afterReserve: async () => {
+ assert.deepEqual(await readdir(f.target), []);
+ assert.deepEqual(await readdir(f.input.dataDirectory), ["test-id"]);
+ } });
+ assert.deepEqual(result, { status: "imported" });
+ assert.deepEqual((await readdir(f.target)).sort(), ["external-media.json", "metadata.info.json", "transcript.en.vtt"]);
+ assert.equal(await readFile(path.join(f.target, "metadata.info.json"), "utf8"), f.input.metadata);
+ assert.equal(await readFile(path.join(f.target, "transcript.en.vtt"), "utf8"), f.input.transcript);
+ assert.deepEqual(JSON.parse(await readFile(path.join(f.target, "external-media.json"), "utf8")), f.input.reference);
+ assert.deepEqual(await readdir(f.root), ["data"]);
+});
+test("retry never overwrites an imported record", async (t) => {
+ const f = await fixture(t); assert.deepEqual(await commitLocalMediaRecord(f.input), { status: "imported" });
+ await writeFile(path.join(f.target, "transcript.en.vtt"), "operator edit");
+ assert.deepEqual(await commitLocalMediaRecord(f.input), { status: "occupied" });
+ assert.equal(await readFile(path.join(f.target, "transcript.en.vtt"), "utf8"), "operator edit");
+});
+test("existing empty directory is occupied, not replaced by rename", async (t) => {
+ const f = await fixture(t); await mkdir(f.target);
+ assert.deepEqual(await commitLocalMediaRecord(f.input), { status: "occupied" });
+ assert.deepEqual(await readdir(f.target), []);
+});
+test("concurrent commits have exactly one winner", async (t) => {
+ const f = await fixture(t);
+ const results = await Promise.all([commitLocalMediaRecord(f.input), commitLocalMediaRecord(f.input)]);
+ assert.deepEqual(results.map(r => r.status).sort(), ["imported", "occupied"]);
+ assert.equal(await readFile(path.join(f.target, "metadata.info.json"), "utf8"), f.input.metadata);
+});
+test("competing file publication is preserved and metadata is not published", async (t) => {
+ const f = await fixture(t);
+ const result = await commitLocalMediaRecord(f.input, { afterReserve: () => writeFile(path.join(f.target, "transcript.en.vtt"), "other producer") });
+ assert.equal(result.status, "failed"); assert.equal(result.incomplete, true);
+ assert.equal(await readFile(path.join(f.target, "transcript.en.vtt"), "utf8"), "other producer");
+ await assert.rejects(lstat(path.join(f.target, "metadata.info.json")), { code: "ENOENT" });
+ assert.deepEqual(await commitLocalMediaRecord(f.input), { status: "occupied" });
+});
+test("cancellation before starting has no writes; cancellation after reservation leaves reviewable partial directory", async (t) => {
+ const f = await fixture(t);
+ const early = new AbortController(); early.abort();
+ await assert.rejects(commitLocalMediaRecord({ ...f.input, signal: early.signal }));
+ assert.deepEqual(await readdir(f.input.dataDirectory), []);
+ const late = new AbortController();
+ const result = await commitLocalMediaRecord({ ...f.input, signal: late.signal }, { afterReserve: async () => { late.abort(); } });
+ assert.deepEqual(result, { status: "failed", incomplete: true, reason: "cancelled" });
+ assert.deepEqual(await readdir(f.target), []);
+ assert.deepEqual(await readdir(f.root), ["data"]);
+});
+test("invalid input is rejected before creating a record or staging directory", async (t) => {
+ const f = await fixture(t);
+ for (const change of [{ directoryId: "../escape" }, { metadata: "{}" }, { transcript: "WEBVTT\n" }, { reference: {} }]) {
+ await assert.rejects(commitLocalMediaRecord({ ...f.input, ...change }));
+ }
+ assert.deepEqual(await readdir(f.root), ["data"]);
+ assert.deepEqual(await readdir(f.input.dataDirectory), []);
+});
+test("injected disk failure leaves no indexable record and never reports success", async (t) => {
+ const f = await fixture(t);
+ const result = await commitLocalMediaRecord(f.input, { afterReserve: async () => { throw Object.assign(new Error("disk full"), { code: "ENOSPC" }); } });
+ assert.deepEqual(result, { status: "failed", incomplete: true, reason: "ENOSPC" });
+ await assert.rejects(lstat(path.join(f.target, "metadata.info.json")), { code: "ENOENT" });
+});
+
+test("failure after publishing transcript still leaves metadata absent and preserves competing reference", async (t) => {
+ const f = await fixture(t);
+ const result = await commitLocalMediaRecord(f.input, { afterReserve: () => writeFile(path.join(f.target, "external-media.json"), "other reference") });
+ assert.equal(result.status, "failed"); assert.equal(result.incomplete, true);
+ assert.equal(await readFile(path.join(f.target, "transcript.en.vtt"), "utf8"), f.input.transcript);
+ assert.equal(await readFile(path.join(f.target, "external-media.json"), "utf8"), "other reference");
+ await assert.rejects(lstat(path.join(f.target, "metadata.info.json")), { code: "ENOENT" });
+});
diff --git a/common/lib/localMediaCommit-server.ts b/common/lib/localMediaCommit-server.ts
@@ -0,0 +1,118 @@
+import { requireLocalRecordingMetadata } from "./localRecordingMetadata";
+import path from "node:path";
+import { link, lstat, mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
+import { coerceExternalMediaReference, EXTERNAL_MEDIA_FILENAME } from "./localMedia";
+import { writeExternalMediaReference } from "./externalMedia-server";
+import { extractVideoId } from "./videoId";
+import { parseVtt } from "./vtt";
+
+export type LocalMediaCommitResult = {
+ status: "imported" | "occupied" | "failed";
+ incomplete?: boolean;
+ reason?: string;
+ stagingCleanupFailed?: boolean;
+};
+
+// TRANSACTION PRIMITIVE, not the application importer. The future controller
+// must supply a guarded, corpus-owned real data directory and freshly read,
+// validated source bytes. This helper has no source-media path and cannot copy
+// or delete the MP4. It validates its immutable input again before any writes.
+//
+// WHY NOT rename(staging, destination): POSIX rename can replace an existing
+// empty directory. Instead, mkdir reserves the destination exclusively, then
+// link publishes each complete staged file WITHOUT replacing an existing name.
+// Metadata is linked LAST because the indexer's discovery requires it. Staging
+// is a sibling of data/, never inside the indexer's recording directory walk.
+// These hard links are between CORPUS files only, never to external media.
+//
+// Failure after reservation leaves a metadata-less partial record for explicit
+// review. Do not recursively roll it back: another producer might have written
+// there meanwhile. A retry returns occupied, never merges/overwrites. This is
+// fail-safe retry handling, not automatic recovery. The caller must surface it.
+// No portable multi-file transaction promises crash durability or protection
+// against an unrelated writer concurrently replacing ancestor directories.
+export async function commitLocalMediaRecord(options: {
+ dataDirectory: string;
+ directoryId: string;
+ metadata: string;
+ transcript: string;
+ reference: unknown;
+ signal?: AbortSignal;
+}, testHooks: { afterReserve?: () => Promise<void> } = {}): Promise<LocalMediaCommitResult> {
+ const { directoryId, metadata, transcript, signal } = options;
+ if (!path.isAbsolute(options.dataDirectory)
+ || !/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(directoryId)
+ || directoryId.endsWith(".") || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(directoryId)) {
+ throw new Error("Invalid corpus directory or recording ID");
+ }
+ const reference = coerceExternalMediaReference(options.reference);
+ if (!reference) throw new Error("Invalid external media reference");
+ if (Buffer.byteLength(metadata) > 32 * 1024 * 1024 || Buffer.byteLength(transcript) > 32 * 1024 * 1024) {
+ throw new Error("Import text exceeds 32 MiB");
+ }
+ let meta;
+ try { meta = JSON.parse(metadata.replace(/^\uFEFF/, "")); } catch { throw new Error("Invalid metadata JSON"); }
+ if (meta && typeof meta === "object" && "local_recording" in meta) {
+ const local = requireLocalRecordingMetadata(meta);
+ if (local.id !== directoryId) throw new Error("Local metadata identity does not match the recording");
+ } else if (!meta || typeof meta !== "object" || Array.isArray(meta) || "entries" in meta
+ || (meta._type !== undefined && meta._type !== "video")
+ || meta.id !== directoryId || typeof meta.webpage_url !== "string"
+ || !/^https?:\/\//i.test(meta.webpage_url) || extractVideoId(meta.webpage_url) !== directoryId
+ || typeof meta.title !== "string" || !meta.title.trim()
+ || typeof meta.duration !== "number" || !Number.isFinite(meta.duration) || meta.duration <= 0
+ || typeof meta.upload_date !== "string" || !/^\d{8}$/.test(meta.upload_date)) {
+ throw new Error("Metadata identity or required fields do not match the recording");
+ }
+ const text = transcript.replace(/^\uFEFF/, "");
+ const cues = parseVtt(text);
+ if (!/^WEBVTT(?:[ \t].*)?(?:\r?\n|$)/.test(text)
+ || !cues.some((cue) => cue.end > cue.start)
+ || cues.some((cue) => !Number.isFinite(cue.start) || !Number.isFinite(cue.end) || cue.start < 0 || cue.end < cue.start)) {
+ throw new Error("Transcript has no usable cues or has reversed intervals");
+ }
+ signal?.throwIfAborted();
+ const rootInfo = await lstat(options.dataDirectory);
+ if (!rootInfo.isDirectory() || rootInfo.isSymbolicLink()) throw new Error("Corpus data directory must be a real directory");
+ const root = await realpath(options.dataDirectory);
+ const target = path.join(root, directoryId);
+ const stage = await mkdtemp(path.join(path.dirname(root), ".local-media-import-"));
+ let reserved = false;
+ let result: LocalMediaCommitResult = { status: "failed" };
+ try {
+ // Stage only validated immutable text, without serializing the original
+ // metadata/transcript again. Bytes supplied by the controller are retained.
+ await writeFile(path.join(stage, "metadata.info.json"), metadata, { flag: "wx" });
+ await writeFile(path.join(stage, "transcript.en.vtt"), transcript, { flag: "wx" });
+ // The declared sidecar's writer (lib/externalMedia-server.ts), into the
+ // private staging dir; the hard link below publishes it.
+ await writeExternalMediaReference(stage, reference);
+ signal?.throwIfAborted();
+ try { await mkdir(target); reserved = true; }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ result = { status: "occupied" };
+ return result;
+ }
+ // Fault-injection seam for transaction boundary tests; production callers
+ // do not supply hooks. It runs before any canonical file is published.
+ await testHooks.afterReserve?.();
+ for (const name of ["transcript.en.vtt", EXTERNAL_MEDIA_FILENAME, "metadata.info.json"]) {
+ signal?.throwIfAborted();
+ const current = await lstat(target);
+ if (!current.isDirectory() || current.isSymbolicLink()) throw new Error("Destination changed");
+ await link(path.join(stage, name), path.join(target, name));
+ }
+ result = { status: "imported" };
+ return result;
+ } catch (error) {
+ result = { status: "failed", incomplete: reserved,
+ reason: signal?.aborted ? "cancelled" : (error as NodeJS.ErrnoException).code || "publication-failed" };
+ return result;
+ } finally {
+ // Only our unique staging directory is eligible for cleanup. A cleanup
+ // failure must not turn a committed record into an apparent failed import.
+ try { await rm(stage, { recursive: true, force: true }); }
+ catch { result.stagingCleanupFailed = true; }
+ }
+}
diff --git a/common/lib/localMediaScan.test.ts b/common/lib/localMediaScan.test.ts
@@ -0,0 +1,174 @@
+import { test, type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, writeFile, readFile, readdir, rm, chmod, symlink } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { scanLocalMedia } from "./localMediaScan";
+
+// Synthetic files only. No getPaths(), live corpus, network, or Docker volumes.
+// Tiny MP4 placeholders are intentional: discovery must never decode or copy
+// video bytes. Integration with ffprobe/playback belongs to a later slice.
+const VTT = "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nA test sentence.\n";
+const meta = (id: string) => ({ id, title: "Synthetic recording", duration: 3,
+ upload_date: "20261029", webpage_url: `https://www.youtube.com/watch?v=${id}` });
+async function fixture(t: TestContext) {
+ const root = await mkdtemp(path.join(tmpdir(), "local-media-scan-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ return root;
+}
+async function add(root: string, name: string, id = name) {
+ await writeFile(path.join(root, `${name}.mp4`), "synthetic video bytes");
+ await writeFile(path.join(root, `${name}.info.json`), JSON.stringify(meta(id)));
+ await writeFile(path.join(root, `${name}.vtt`), VTT);
+}
+const scan = (root: string, existingDirectoryIds: string[] = []) =>
+ scanLocalMedia({ sourceDirectory: root, existingDirectoryIds });
+async function contents(root: string) {
+ const result: Record<string, string> = {};
+ for (const name of (await readdir(root)).sort()) result[name] = (await readFile(path.join(root, name))).toString("base64");
+ return result;
+}
+
+test("new, occupied destination, repeated scan, and later addition preserve all source bytes", async (t) => {
+ const root = await fixture(t);
+ await add(root, "first");
+ const before = await contents(root);
+ assert.deepEqual((await scan(root)).counts, { discovered: 1, new: 1, existing: 0, issues: 0 });
+ const occupied = await scan(root, ["first"]);
+ assert.deepEqual(occupied.counts, { discovered: 1, new: 0, existing: 1, issues: 0 });
+ assert.deepEqual(await scan(root, ["first"]), occupied);
+ assert.deepEqual(await contents(root), before);
+ await add(root, "second");
+ assert.deepEqual((await scan(root, ["first"])).counts, { discovered: 2, new: 1, existing: 1, issues: 0 });
+});
+test("Unicode, quotes, dollars, and spaces remain exact filenames", async (t) => {
+ const root = await fixture(t);
+ const name = "A 'title' $money ⧸ | (録画)";
+ await add(root, name, "safe-id");
+ const result = await scan(root);
+ assert.equal(result.candidates[0].media, `${name}.mp4`);
+ assert.equal(result.candidates[0].status, "new");
+});
+test("missing or mismatched companions are issues; unrelated playlist JSON is ignored", async (t) => {
+ const root = await fixture(t);
+ await writeFile(path.join(root, "alone.mp4"), "media");
+ await writeFile(path.join(root, "other.vtt"), VTT);
+ await writeFile(path.join(root, "playlist.info.json"), '{"_type":"playlist"}');
+ const result = await scan(root);
+ assert.equal(result.counts.discovered, 1);
+ assert.equal(result.candidates[0].issues.length, 2);
+ assert.deepEqual(result.candidates[0].issues, [
+ "Metadata: matching .info.json file not found. Prepare recording details before import.",
+ "Transcript: matching subtitle file not found. Add an SRT or VTT file, or generate a transcript if available.",
+ ]);
+ assert.ok(!JSON.stringify(result).includes(root));
+});
+test("invalid JSON and matched playlist metadata are rejected", async (t) => {
+ const root = await fixture(t);
+ await add(root, "broken"); await add(root, "playlist");
+ await writeFile(path.join(root, "broken.info.json"), "{");
+ await writeFile(path.join(root, "playlist.info.json"), JSON.stringify({ ...meta("playlist"), _type: "playlist", entries: [] }));
+ const result = await scan(root);
+ assert.equal(result.counts.issues, 2);
+ assert.match(result.candidates[0].issues.join(), /invalid JSON/);
+ assert.match(result.candidates[1].issues.join(), /playlist/);
+});
+test("duplicates invalidate both candidates even when one has a bad transcript", async (t) => {
+ const root = await fixture(t);
+ await add(root, "one", "shared"); await add(root, "two", "shared");
+ await writeFile(path.join(root, "two.vtt"), "WEBVTT\n");
+ const result = await scan(root, ["shared"]);
+ assert.equal(result.counts.issues, 2);
+ assert.ok(result.candidates.every((row) => row.issues.includes("Duplicate identity in source scan")));
+});
+test("header-only and reversed-interval transcripts are rejected", async (t) => {
+ const root = await fixture(t);
+ await add(root, "empty"); await add(root, "reverse");
+ await writeFile(path.join(root, "empty.vtt"), "WEBVTT\n");
+ await writeFile(path.join(root, "reverse.vtt"), VTT.replace("00:00:02.000", "00:00:00.000"));
+ assert.equal((await scan(root)).counts.issues, 2);
+});
+test("unsafe record IDs cannot become destinations", async (t) => {
+ const root = await fixture(t);
+ for (const [i, id] of ["..", "../escape", "a/b", "CON", "trailing."].entries()) await add(root, `item${i}`, id);
+ assert.equal((await scan(root)).counts.issues, 5);
+});
+test("native/canonical differences are retained but held for review", async (t) => {
+ const root = await fixture(t);
+ await add(root, "twitch", "v1234");
+ await writeFile(path.join(root, "twitch.info.json"), JSON.stringify({ ...meta("v1234"), webpage_url: "https://www.twitch.tv/videos/1234" }));
+ const row = (await scan(root)).candidates[0];
+ assert.equal(row.recordId, "v1234"); assert.equal(row.directoryId, "1234");
+ assert.equal(row.status, "issue");
+});
+test("unavailable roots fail instead of reporting zero discoveries", async (t) => {
+ const root = await fixture(t);
+ await assert.rejects(scan(path.join(root, "missing")), { code: "ENOENT" });
+ await assert.rejects(scan("relative"), /absolute/);
+});
+test("directory named .mp4 is not a media file", async (t) => {
+ const root = await fixture(t);
+ await mkdir(path.join(root, "directory.mp4"));
+ assert.equal((await scan(root)).candidates[0].status, "issue");
+});
+test("oversized metadata is refused before parsing", async (t) => {
+ const root = await fixture(t);
+ await add(root, "large");
+ const { open } = await import("node:fs/promises");
+ const h = await open(path.join(root, "large.info.json"), "w");
+ try { await h.truncate(32 * 1024 * 1024 + 1); } finally { await h.close(); }
+ assert.match((await scan(root)).candidates[0].issues.join(), /32 MiB/);
+});
+test("source-file symlinks are refused, including escapes", async (t) => {
+ const root = await fixture(t);
+ const outside = await fixture(t);
+ await add(root, "linked");
+ await writeFile(path.join(outside, "outside.mp4"), "outside");
+ await rm(path.join(root, "linked.mp4"));
+ try { await symlink(path.join(outside, "outside.mp4"), path.join(root, "linked.mp4")); }
+ catch (e) {
+ if ((e as NodeJS.ErrnoException).code === "EPERM" && process.platform === "win32") { t.skip("Windows symlink privilege unavailable; run in Linux container"); return; }
+ throw e;
+ }
+ assert.match((await scan(root)).candidates[0].issues.join(), /source links/);
+ assert.equal(await readFile(path.join(outside, "outside.mp4"), "utf8"), "outside");
+});
+test("read-only source files remain readable and unchanged", async (t) => {
+ const root = await fixture(t);
+ await add(root, "readonly");
+ const before = await contents(root);
+ const files = await readdir(root);
+ try {
+ for (const file of files) await chmod(path.join(root, file), 0o444);
+ assert.equal((await scan(root)).counts.new, 1);
+ assert.deepEqual(await contents(root), before);
+ } finally { for (const file of files) await chmod(path.join(root, file), 0o644); }
+});
+
+// The parser reads only hh:mm:ss.mmm cue timings until slice 2 lands its
+// short-form support (with a corpus regression check). Until then a short-form
+// VTT is held for review, never imported with missing or misread cues.
+test("short-form timestamps are held for review, not imported", async (t) => {
+ const root = await fixture(t);
+ await add(root, "short");
+ await writeFile(path.join(root, "short.vtt"), "WEBVTT\n\n00:00.250 --> 00:01.910\nShort cue\n");
+ const row = (await scan(root)).candidates[0];
+ assert.equal(row.status, "issue");
+ assert.match(row.issues.join(), /no usable cues/);
+ assert.equal(row.fingerprint, undefined);
+});
+test("isolated zero-duration cues warn without changing source; all-point transcripts remain blocked", async (t) => {
+ const root = await fixture(t);
+ await add(root, "mixed"); await add(root, "points");
+ const point = "00:00:03.000 --> 00:00:03.000\nPoint cue\n";
+ const mixed = VTT + "\n" + point;
+ await writeFile(path.join(root, "mixed.vtt"), mixed);
+ await writeFile(path.join(root, "points.vtt"), "WEBVTT\n\n" + point);
+ const result = await scan(root, ["mixed"]);
+ assert.equal(result.candidates[0].status, "existing");
+ assert.equal(result.candidates[0].cueCount, 2);
+ assert.match(result.candidates[0].warnings.join(), /1 zero-duration/);
+ assert.equal(result.candidates[1].status, "issue");
+ assert.match(result.candidates[1].issues.join(), /no positive-duration/);
+ assert.equal(await readFile(path.join(root, "mixed.vtt"), "utf8"), mixed);
+});
diff --git a/common/lib/localMediaScan.ts b/common/lib/localMediaScan.ts
@@ -0,0 +1,228 @@
+import { localTranscriptVtt, localTranscriptFingerprint } from "./localMediaTranscript";
+import { createHash } from "node:crypto";
+import type { Stats } from "node:fs";
+import path from "node:path";
+import { lstat, open, readdir, realpath } from "node:fs/promises";
+import { extractVideoId } from "./videoId";
+import { parseVtt } from "./vtt";
+
+// Read-only discovery, not an executable import plan. The caller supplies the
+// destination inventory after applying channel storage guards; this leaf never
+// opens the live corpus. Import must revalidate inputs under its own lock.
+// "existing" means the directory is occupied, not that its contents match.
+export type LocalMediaCandidate = {
+ media: string; metadata: string; transcript: string;
+ savedRecordAvailable?: boolean;
+ recordId?: string; directoryId?: string; title?: string; cueCount?: number;
+ status: "new" | "existing" | "issue";
+ issues: string[];
+ warnings: string[];
+ fingerprint?: string;
+ // Present only when the MP4 and transcript are usable and the metadata file is
+ // absent. Invalid existing metadata is never replaced by generated details.
+ preparationFingerprint?: string;
+ generatedMetadata?: true;
+ // Read-only eligibility for future subtitle generation, never import authority.
+ // Set only when both matching subtitle companions are absent. Existing bad
+ // subtitles remain issues instead of being replaced by generated text.
+ transcriptionFingerprint?: string;
+ transcriptionNeedsDetails?: true;
+};
+export type LocalMediaScan = {
+ candidates: LocalMediaCandidate[];
+ counts: { discovered: number; new: number; existing: number; issues: number };
+};
+const MAX_TEXT_BYTES = 32 * 1024 * 1024;
+
+// Conservative portable names; never sanitize an identity into a collision.
+function safeId(v: unknown): v is string {
+ return typeof v === "string" && /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(v)
+ && !v.endsWith(".") && !/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(v);
+}
+async function regularFile(root: string, name: string): Promise<string> {
+ const file = path.join(root, name);
+ const info = await lstat(file);
+ // Milestone one refuses source symlinks, even within the root. The configured
+ // root itself may be a mount/link. This is a preview over a trusted operator's
+ // directory, not a race-proof filesystem sandbox or a playback authorization.
+ if (!info.isFile() || info.isSymbolicLink()) throw new Error("not a regular file; source links are unsupported");
+ const resolved = await realpath(file);
+ const relative = path.relative(root, resolved);
+ if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
+ throw new Error("file resolves outside source directory");
+ }
+ return resolved;
+}
+// Shared bounded reader for scan/import. Names come from a scan, never raw paths.
+export async function readLocalMediaText(root: string, name: string): Promise<string> {
+ if (!name || name === "." || name === ".." || /[\\/]/.test(name)) throw new Error("Expected a bare source filename");
+ if (/\.srt$/i.test(name)) {
+ let vttPresent = false;
+ try { await lstat(path.join(root, name.slice(0, -4) + ".vtt")); vttPresent = true; }
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
+ if (vttPresent) throw new Error("Matching VTT appeared; preview again");
+ }
+ const handle = await open(await regularFile(root, name), "r");
+ try {
+ const before = await handle.stat();
+ if (!before.isFile() || before.size > MAX_TEXT_BYTES) throw new Error("not a text file or exceeds 32 MiB");
+ // Bound the actual read, too: a file can grow after stat. Never read MP4
+ // contents or allocate a buffer based on an unchecked sidecar's size.
+ const buffer = Buffer.alloc(before.size + 1);
+ let length = 0;
+ while (length < buffer.length) {
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
+ if (!bytesRead) break;
+ length += bytesRead;
+ }
+ const after = await handle.stat();
+ if (length !== before.size || after.size !== before.size || after.mtimeMs !== before.mtimeMs) {
+ throw new Error("file changed during scan; rescan");
+ }
+ try { return new TextDecoder("utf-8", {fatal: true, ignoreBOM: true}).decode(buffer.subarray(0, length)); }
+ catch { throw new Error("Text must use valid UTF-8 encoding"); }
+ } finally { await handle.close(); }
+}
+function reason(error: unknown): string {
+ // Filesystem errors carry absolute operator paths; report their code only.
+ const e = error as { code?: string; message?: string };
+ if (e.code) return e.code;
+ if (error instanceof SyntaxError) return "invalid JSON";
+ if (error instanceof TypeError) return "invalid metadata value or URL";
+ return e.message || "unreadable file";
+}
+export async function scanLocalMedia(options: {
+ sourceDirectory: string;
+ existingDirectoryIds: readonly string[];
+}): Promise<LocalMediaScan> {
+ if (!path.isAbsolute(options.sourceDirectory)) throw new Error("Source directory must be absolute");
+ const root = await realpath(options.sourceDirectory);
+ // Root errors propagate: an unavailable drive is never a successful empty
+ // scan. Per-candidate failures are collected so other recordings remain visible.
+ const names = (await readdir(root)).sort();
+ const existing = new Set(options.existingDirectoryIds);
+ const candidates: LocalMediaCandidate[] = [];
+ for (const media of names.filter((name) => /\.mp4$/i.test(name))) {
+ const base = media.slice(0, -4);
+ const row: LocalMediaCandidate = {
+ media, metadata: `${base}.info.json`, transcript: names.includes(`${base}.vtt`) ? `${base}.vtt` : names.includes(`${base}.srt`) ? `${base}.srt` : `${base}.vtt`,
+ status: "issue", issues: [], warnings: [],
+ };
+ candidates.push(row);
+ let mediaStat: Stats | undefined;
+ let metadataText = "";
+ let metadataMissing = false;
+ let transcriptText = "";
+ let metadataUsable = false;
+ try { mediaStat = await lstat(await regularFile(root, media)); }
+ catch (error) { row.issues.push(`Media: ${reason(error)}`); }
+ try {
+ metadataText = await readLocalMediaText(root, row.metadata);
+ const meta = JSON.parse(metadataText.replace(/^\uFEFF/, ""));
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)
+ || (meta._type !== undefined && meta._type !== "video") || "entries" in meta) {
+ throw new Error("expected video metadata, not a playlist or collection");
+ }
+ if (!safeId(meta.id)) throw new Error("missing or unsafe metadata id");
+ row.recordId = meta.id;
+ if (typeof meta.title !== "string" || !meta.title.trim()) throw new Error("missing title");
+ row.title = meta.title;
+ if (typeof meta.webpage_url !== "string") throw new Error("missing webpage_url");
+ const url = new URL(meta.webpage_url);
+ if (!["http:", "https:"].includes(url.protocol)) throw new Error("webpage_url must be HTTP or HTTPS");
+ const directoryId = extractVideoId(meta.webpage_url);
+ if (!safeId(directoryId)) throw new Error("URL has no safe canonical directory id");
+ row.directoryId = directoryId;
+ // The native metadata ID and canonical directory ID differ on some
+ // platforms. Keep both, use the existing resolver, and hold mismatches
+ // for review in this first slice rather than guessing at platform joins.
+ if (directoryId !== meta.id) row.issues.push("Metadata and canonical URL IDs differ; mapping requires review");
+ if (typeof meta.upload_date !== "string" || !/^\d{8}$/.test(meta.upload_date)) throw new Error("missing YYYYMMDD upload_date");
+ if (typeof meta.duration !== "number" || !Number.isFinite(meta.duration) || meta.duration <= 0) {
+ throw new Error("duration must be a positive number");
+ }
+ metadataUsable = row.issues.length === 0;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
+ // Confirm the companion itself is absent, not a failed read through a
+ // link or an unavailable ancestor. Other metadata errors stay blocked.
+ try { await lstat(path.join(root, row.metadata)); }
+ catch (check) { metadataMissing = (check as NodeJS.ErrnoException).code === "ENOENT"; }
+ }
+ row.issues.push(metadataMissing
+ ? "Metadata: matching .info.json file not found. Prepare recording details before import."
+ : `Metadata: ${reason(error)}`);
+ }
+ try {
+ transcriptText = await readLocalMediaText(root, row.transcript);
+ const text = localTranscriptVtt(row.transcript, transcriptText).replace(/^\uFEFF/, "");
+ if (!/^WEBVTT(?:[ \t].*)?(?:\r?\n|$)/.test(text)) throw new Error("missing WEBVTT header");
+ const cues = parseVtt(text);
+ if (!cues.length || cues.some((cue) => !Number.isFinite(cue.start)
+ || !Number.isFinite(cue.end) || cue.start < 0 || cue.end < cue.start)) {
+ throw new Error("no usable cues or invalid cue intervals");
+ }
+ if (!cues.some((cue) => cue.end > cue.start)) throw new Error("no positive-duration cues");
+ // Whisper-derived transcripts can contain isolated point cues. Keep the
+ // original timing and text: widening or dropping them would change the
+ // source. Warn visibly, while backwards intervals still block import.
+ const zeroDuration = cues.filter((cue) => cue.end === cue.start).length;
+ if (zeroDuration) row.warnings.push(
+ "Transcript: " + zeroDuration + " zero-duration cue(s); original timings preserved",
+ );
+ row.cueCount = cues.length;
+ if (/\.srt$/i.test(row.transcript)) row.warnings.push("Transcript: SRT will be converted to VTT on import; original unchanged");
+ else if (names.includes(`${base}.srt`)) row.warnings.push("Transcript: using matching VTT; SRT is not used");
+ } catch (error) { row.issues.push((error as NodeJS.ErrnoException).code === "ENOENT"
+ ? "Transcript: matching subtitle file not found. Add an SRT or VTT file, or generate a transcript if available."
+ : `Transcript: ${reason(error)}`); }
+ if (mediaStat && (metadataUsable || metadataMissing)) {
+ let absent = true;
+ for (const extension of [".vtt", ".srt"]) {
+ try { await lstat(path.join(root, base + extension)); absent = false; }
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") absent = false; }
+ }
+ if (absent) {
+ row.transcriptionFingerprint = localMediaFingerprint(media, metadataText, "missing-subtitles-v1", mediaStat);
+ if (metadataMissing) row.transcriptionNeedsDetails = true;
+ }
+ }
+ if (!row.issues.length && mediaStat) row.fingerprint = localMediaFingerprint(media, metadataText, localTranscriptFingerprint(row.transcript, transcriptText), mediaStat);
+ if (metadataMissing && mediaStat && row.issues.length === 1 && row.cueCount) {
+ row.preparationFingerprint = localMediaFingerprint(media, "", localTranscriptFingerprint(row.transcript, transcriptText), mediaStat);
+ }
+ }
+ // Include invalid candidates in collisions: fixing a transcript later must
+ // not silently change which physical recording wins the same identity.
+ const identities = new Map<string, Set<LocalMediaCandidate>>();
+ for (const row of candidates) {
+ for (const id of new Set([row.recordId, row.directoryId])) {
+ if (!id) continue;
+ const group = identities.get(id) ?? new Set<LocalMediaCandidate>();
+ group.add(row); identities.set(id, group);
+ }
+ }
+ for (const group of identities.values()) {
+ if (group.size < 2) continue;
+ for (const row of group) {
+ if (!row.issues.includes("Duplicate identity in source scan")) row.issues.push("Duplicate identity in source scan");
+ }
+ }
+ const counts = { discovered: candidates.length, new: 0, existing: 0, issues: 0 };
+ for (const row of candidates) {
+ if (existing.has(row.directoryId!) || row.issues.includes("Duplicate identity in source scan")) {
+ delete row.transcriptionFingerprint;
+ delete row.transcriptionNeedsDetails;
+ }
+ row.status = row.issues.length ? "issue" : existing.has(row.directoryId!) ? "existing" : "new";
+ if (row.status === "issue") counts.issues++;
+ else counts[row.status]++;
+ }
+ return { candidates, counts };
+}
+
+// A freshness token, not authorization or a full-video checksum. Hash the exact
+// text bytes and MP4 filesystem identity without reading gigabytes of video.
+export function localMediaFingerprint(media: string, metadata: string, transcript: string, info: Pick<Stats, "dev" | "ino" | "size" | "mtimeMs" | "ctimeMs">): string {
+ return createHash("sha256").update(JSON.stringify([media, metadata, transcript, info.dev, info.ino, info.size, info.mtimeMs, info.ctimeMs])).digest("hex");
+}
diff --git a/common/lib/localMediaTranscript.test.ts b/common/lib/localMediaTranscript.test.ts
@@ -0,0 +1,25 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { srtToVtt, localTranscriptVtt, localTranscriptFingerprint } from "./localMediaTranscript";
+
+test("SRT preserves multiline Unicode dialogue, emphasis, overlaps and millisecond boundaries", () => {
+ const input = "\uFEFF1\r\n00:00:01,001 --> 00:00:03,999\r\n<i>Hello</i> & welcome\r\n録画\r\n\r\n2\r\n00:00:02,050 --> 00:00:04,500\r\nSecond line\r\n";
+ assert.equal(srtToVtt(input), "WEBVTT\n\n00:00:01.001 --> 00:00:03.999\n<i>Hello</i> & welcome\n録画\n\n00:00:02.050 --> 00:00:04.500\nSecond line\n");
+});
+test("VTT remains byte-for-byte text and SRT freshness includes unconverted source", () => {
+ const vtt = "\uFEFFWEBVTT\r\n\r\n00:00:01.000 --> 00:00:02.000\r\nHi\r\n";
+ assert.equal(localTranscriptVtt("lesson.vtt", vtt), vtt);
+ assert.equal(localTranscriptFingerprint("lesson.vtt",vtt), vtt);
+ const srt = "1\n00:00:01,000 --> 00:00:02,000\nHi\n";
+ assert.equal(srtToVtt(srt),srtToVtt(srt.replace("1\n","2\n")));
+ assert.notEqual(localTranscriptFingerprint("lesson.srt",srt),localTranscriptFingerprint("lesson.srt",srt.replace("1\n","2\n")));
+});
+test("malformed blocks, invalid clocks, reversed intervals and empty tracks fail without dropping cues", () => {
+ for (const input of ["", "WEBVTT", "1\n00:60:00,000 --> 01:01:00,000\nHi", "1\n00:00:02,000 --> 00:00:01,000\nHi", "1\n00:00:01,000 --> 00:00:02,000", "1\n00:00:01,000 --> 00:00:01,000\nHi", "1\n00:00:01,000 --> 00:00:02,000\nValid\n\ninvalid block", "1\n00:00:01,000 --> 00:00:02,000 X1:1\nUnsupported positioning"]) assert.throws(() => srtToVtt(input));
+});
+test("optional sequence numbers and long hours work; literal timestamp tags cannot change caption parsing", () => {
+ const result = srtToVtt("100:00:00,000 --> 100:00:01,000\n<00:00:00.500> <lesson>\n\n2\n100:00:01,000 --> 100:00:01,000\nPoint cue");
+ assert.ok(result.includes("100:00:00.000 --> 100:00:01.000"));
+ assert.ok(result.includes("<00:00:00.500> <lesson>"));
+ assert.ok(result.includes("100:00:01.000 --> 100:00:01.000"));
+});
diff --git a/common/lib/localMediaTranscript.ts b/common/lib/localMediaTranscript.ts
@@ -0,0 +1,37 @@
+// Conversion is confined to local imports. Existing VTT bytes stay unchanged.
+export function localTranscriptFingerprint(name: string, text: string): string {
+ return /\.srt$/i.test(name) ? JSON.stringify(["srt-v1", name, text]) : text;
+}
+
+export function localTranscriptVtt(name: string, text: string): string {
+ return /\.srt$/i.test(name) ? srtToVtt(text) : text;
+}
+
+// Reject malformed blocks rather than quietly dropping dialogue. No subprocess,
+// guessed duration, cue reordering, or timestamp stretching is involved.
+export function srtToVtt(source: string): string {
+ const text = source.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n").trim();
+ if (!text || text.includes("\uFFFD") || text.includes("\0")) throw new Error("SRT is empty or has unsupported text encoding");
+ const timestamp = "(\\d{2,}):([0-5]\\d):([0-5]\\d),([0-9]{3})";
+ const timing = new RegExp("^" + timestamp + "[ \\t]+-->[ \\t]+" + timestamp + "[ \\t]*$");
+ const output: string[] = [];
+ let positive = false;
+ for (const block of text.split(/\n[ \t]*\n+/)) {
+ const lines = block.split("\n");
+ if (/^\d+[ \t]*$/.test(lines[0])) lines.shift();
+ const match = lines.shift()?.match(timing);
+ if (!match || !lines.some(line => line.trim())) throw new Error("SRT has an invalid timing line or empty cue");
+ const seconds = (offset: number) => Number(match[offset]) * 3600 + Number(match[offset + 1]) * 60 + Number(match[offset + 2]) + Number(match[offset + 3]) / 1000;
+ const start = seconds(1), end = seconds(5);
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) throw new Error("SRT has an invalid cue interval");
+ positive ||= end > start;
+ // Keep supported emphasis. Escape other angle brackets so literal dialogue
+ // cannot become VTT timestamps, cue markup, or a block directive.
+ const body = lines.map(line => line.replace(/&(?!amp;|lt;|gt;|nbsp;|lrm;|rlm;)/g, "&")
+ .replace(/<(?!\/?(?:b|i|u)>)/g, "<")).join("\n");
+ const stamp = (offset: number) => `${match[offset]}:${match[offset + 1]}:${match[offset + 2]}.${match[offset + 3]}`;
+ output.push(`${stamp(1)} --> ${stamp(5)}\n${body}`);
+ }
+ if (!positive) throw new Error("SRT has no positive-duration cues");
+ return "WEBVTT\n\n" + output.join("\n\n") + "\n";
+}
diff --git a/common/lib/localRecordingDetails.ts b/common/lib/localRecordingDetails.ts
@@ -0,0 +1,33 @@
+import { createHash } from "node:crypto";
+
+export type LocalRecordingDetails = {
+ mode: "inspect" | "manual";
+ title: string;
+ recordedDate?: string;
+ durationSeconds?: number;
+};
+
+// Stable within one channel's configured library. Changing editable facts or
+// retrying a queued import cannot create another ID. Renaming an original is a
+// different source selection; this is identity assignment, not deduplication.
+// The CHANNEL is part of it (lane/local-media review fix 6): two channels with
+// the same library id and file name are two records, never one id across the
+// corpus (an index key, a citation and a clip all name a record by its id).
+export function localRecordingId(channelSlug: string, sourceId: string, media: string): string {
+ return "local-" + createHash("sha256").update(JSON.stringify(["local-recording-v1", channelSlug, sourceId, media])).digest("hex").slice(0, 32);
+}
+
+export function parseLocalRecordingDetails(value: unknown): LocalRecordingDetails {
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid recording details");
+ const raw = value as Record<string, unknown>;
+ if ((raw.mode !== "manual" && raw.mode !== "inspect") || typeof raw.title !== "string"
+ || !raw.title.trim() || raw.title.length > 1000 || /[\x00-\x1f\x7f]/.test(raw.title)
+ || (raw.recordedDate !== undefined && typeof raw.recordedDate !== "string")
+ || (raw.durationSeconds !== undefined && (raw.mode !== "manual"
+ || typeof raw.durationSeconds !== "number" || !Number.isFinite(raw.durationSeconds) || raw.durationSeconds <= 0))) {
+ throw new Error("Invalid recording details");
+ }
+ return {mode: raw.mode, title: raw.title.trim(),
+ ...(raw.recordedDate !== undefined ? {recordedDate: raw.recordedDate as string} : {}),
+ ...(raw.durationSeconds !== undefined ? {durationSeconds: raw.durationSeconds as number} : {})};
+}
diff --git a/common/lib/localRecordingIntegration.test.ts b/common/lib/localRecordingIntegration.test.ts
@@ -0,0 +1,67 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { prepareManualLocalRecordingMetadata, prepareLocalRecordingMetadata, requireLocalRecordingMetadata, localRecordingProblem } from "./localRecordingMetadata";
+import { summarize, platformFromMetadata, toDisplaySummary } from "./transcripts-server";
+import { defaultWebpageUrl, PLATFORM_VALUES } from "./platform";
+
+const id = "local-" + "a".repeat(32);
+const manual = () => prepareManualLocalRecordingMetadata({id, filename: "Lesson.mp4"});
+
+test("source-less summaries keep unknown dates and duration without a fabricated provider", () => {
+ const value = manual();
+ assert.equal(requireLocalRecordingMetadata(value), value);
+ const summary = summarize("classroom", "20260101_original", value, "Classroom");
+ assert.equal(summary.platform, "local");
+ assert.equal(summary.id, id);
+ assert.equal(summary.webpageUrl, "");
+ assert.equal(summary.uploadDate, "");
+ assert.equal(summary.recordedDate, undefined);
+ assert.equal(summary.duration, 0); // Existing summary convention for unknown duration.
+ assert.equal(toDisplaySummary(summary).date, "");
+ assert.equal(defaultWebpageUrl("local", id), "");
+ assert.ok(PLATFORM_VALUES.includes("local"));
+});
+
+// Review B2: a local recording was never published, so its recording date is
+// its one date — the record sorts and filters by it — and it stays marked as a
+// recording date (recordedDate), never claimed from a provider.
+test("an explicit recording date is the record's date, and stays a recording date", () => {
+ const value = prepareLocalRecordingMetadata({id, filename: "Lesson.mp4", recordedDate: "2024-02-29",
+ probe: {format: {duration: "10.5"}, streams: [{codec_type: "video"}]}});
+ requireLocalRecordingMetadata(value);
+ const summary = summarize("classroom", id, value);
+ assert.equal(summary.recordedDate, "20240229");
+ assert.equal(summary.uploadDate, "20240229");
+ assert.equal(summary.webpageUrl, "");
+ assert.equal(summary.duration, 10.5);
+});
+
+test("a local marker is validated, not used to hide invalid or contradictory metadata", () => {
+ const value = manual();
+ for (const change of [
+ {id: "online-id"}, {title: ""}, {duration: -1}, {filesize: -1},
+ {webpage_url: "https://www.youtube.com/watch?v=anything"}, {upload_date: "20260101"},
+ {local_recording: {}}, {local_recording: {...value.local_recording, durationSource: "ffprobe"}},
+ {recorded_date: "20240230", local_recording: {...value.local_recording, recordedDateSource: "operator"}},
+ {local_recording: {...value.local_recording, privatePath: "/private/archive"}},
+ ]) {
+ assert.throws(() => requireLocalRecordingMetadata({...value, ...change}));
+ assert.ok(localRecordingProblem({...value, ...change}));
+ // Never a throw, and never relabelled as a provider: the index skips it.
+ assert.equal(platformFromMetadata({...value, ...change}), "local");
+ assert.equal(summarize("classroom", id, {...value, ...change}).webpageUrl,
+ "webpage_url" in change ? change.webpage_url : "");
+ }
+ assert.equal(localRecordingProblem(value), null);
+});
+
+test("online metadata retains its provider and date rules even with a local-looking ID", () => {
+ assert.equal(platformFromMetadata({id}), "youtube");
+ for (const [extractor, platform] of [["Youtube", "youtube"], ["Kick", "kick"], ["Rumble", "rumble"],
+ ["Twitch", "twitch"], ["LBRY", "odysee"], ["ArchiveOrg", "archiveorg"], ["BitChute", "bitchute"]]) {
+ assert.equal(platformFromMetadata({extractor_key: extractor}), platform);
+ }
+ const summary = summarize("online", "20260101_original", {id: "video", title: "Online"});
+ assert.equal(summary.uploadDate, "20260101");
+ assert.equal(summary.webpageUrl, "https://www.youtube.com/watch?v=video");
+});
diff --git a/common/lib/localRecordingMetadata.test.ts b/common/lib/localRecordingMetadata.test.ts
@@ -0,0 +1,82 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { prepareLocalRecordingMetadata, prepareManualLocalRecordingMetadata, localRecordingDuration } from "./localRecordingMetadata";
+const id = "local-FAKE-TEST-VALUEFAKE-TEST-VALUE";
+const probe = {format: {duration: "123.456", filename: "/private/archive/lesson.mp4",
+ tags: {creation_time: "2020-01-01", title: "unreviewed tag"}},
+ streams: [{codec_type: "video", disposition: {attached_pic: 0}}]};
+const prepare = (extra = {}) => prepareLocalRecordingMetadata({id, filename: "Classroom lesson.mp4", probe, ...extra});
+test("source-less metadata retains unknown provenance and dates without leaking probe paths", () => {
+ const result = prepare();
+ assert.equal(result.title, "Classroom lesson");
+ assert.equal(result.duration, 123.456);
+ assert.equal(result.local_recording.titleSource, "filename");
+ for (const key of ["upload_date", "recorded_date", "webpage_url", "original_url", "uploader", "timestamp", "extractor"]) assert.equal(key in result, false);
+ assert.equal(JSON.stringify(result).includes("/private"), false);
+ assert.equal(JSON.stringify(result).includes("2020"), false);
+});
+test("operator title/date are distinct from publication metadata and keep identity stable", () => {
+ const result = prepare({title: " Lab session ", recordedDate: "2024-02-29"});
+ assert.equal(result.id, prepare().id);
+ assert.equal(result.title, "Lab session");
+ assert.equal(result.recorded_date, "20240229");
+ assert.equal(result.local_recording.recordedDateSource, "operator");
+ assert.equal("upload_date" in result, false);
+ assert.equal("recorded_date" in prepare({recordedDate: " "}), false);
+});
+test("invalid calendar dates are refused rather than normalized", () => {
+ for (const recordedDate of ["2023-02-29", "2024-04-31", "2024-13-01", "0000-01-01", "yesterday"]) assert.throws(() => prepare({recordedDate}), /real YYYY-MM-DD/);
+});
+test("invalid media durations and audio/cover-only files are refused", () => {
+ for (const value of [undefined, null, true, "N/A", "0x10", "", "-1", 0, -1, Infinity]) {
+ assert.throws(() => localRecordingDuration({...probe, format: {duration: value}}), /duration/);
+ }
+ assert.throws(() => localRecordingDuration({...probe, streams: [{codec_type: "audio"}]}), /video stream/);
+ assert.throws(() => localRecordingDuration({...probe, streams: [{codec_type: "video", disposition: {attached_pic: 1}}]}), /video stream/);
+});
+test("unsafe filenames and identities are refused without sanitizing collisions", () => {
+ for (const filename of ["../lesson.mp4", "C:\\lesson.mp4", "lesson.mkv", "\u0000.mp4", ".mp4"]) assert.throws(() => prepare({filename}));
+ for (const badId of ["providerId", "../local-id", "local-abc"]) assert.throws(() => prepare({id: badId}), /identity/);
+});
+test("preparation is repeatable and does not modify the supplied inspection", () => {
+ const before = JSON.stringify(probe);
+ assert.deepEqual(prepare(), prepare());
+ assert.equal(JSON.stringify(probe), before);
+ assert.equal(prepare({filename: "授業 № 2.MP4"}).title, "授業 № 2");
+});
+
+const manual = (extra = {}) => prepareManualLocalRecordingMetadata({id, filename: "Lesson.mp4", ...extra});
+test("manual preparation needs no probe and leaves duration and date unknown", () => {
+ const metadata = manual({fileSizeBytes: 123456789});
+ assert.equal(metadata.filesize, 123456789);
+ assert.equal(metadata.local_recording.filesizeSource, "filesystem");
+ assert.equal(metadata.local_recording.inspection, "manual");
+ assert.equal(metadata.local_recording.durationSource, "unknown");
+ for (const key of ["duration", "recorded_date", "upload_date", "webpage_url", "timestamp"]) assert.equal(key in metadata, false);
+ assert.equal(metadata.id, prepare().id);
+});
+test("manual duration and date remain operator supplied, never measured or published", () => {
+ const metadata = manual({durationSeconds: 12.5, recordedDate: "2024-02-29", title: " My lesson "});
+ assert.equal(metadata.duration, 12.5);
+ assert.equal(metadata.recorded_date, "20240229");
+ assert.equal(metadata.title, "My lesson");
+ assert.equal(metadata.local_recording.durationSource, "operator");
+ assert.equal(metadata.local_recording.recordedDateSource, "operator");
+ assert.equal(prepare().local_recording.inspection, "ffprobe");
+ assert.equal(prepare().local_recording.durationSource, "ffprobe");
+});
+test("manual mode rejects invalid supplied values instead of replacing them with guesses", () => {
+ for (const durationSeconds of [0, -1, NaN, Infinity, "10", null]) assert.throws(() => manual({durationSeconds}), /duration/);
+ for (const fileSizeBytes of [-1, 1.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1, "12", null]) assert.throws(() => manual({fileSizeBytes}), /file size/);
+ assert.throws(() => manual({recordedDate: "2023-02-29"}), /real YYYY-MM-DD/);
+ assert.throws(() => manual({filename: "../outside.mp4"}));
+});
+test("file dates and probe tags cannot silently become recording facts in manual mode", () => {
+ const metadata = manual({fileSizeBytes: 0, birthtime: "2020-01-01", mtime: "2021-01-01", probe});
+ assert.equal(metadata.filesize, 0);
+ assert.equal("duration" in metadata, false);
+ assert.equal("recorded_date" in metadata, false);
+ assert.equal(JSON.stringify(metadata).includes("2020"), false);
+ assert.equal(JSON.stringify(metadata).includes("/private"), false);
+ assert.deepEqual(manual(), manual());
+});
diff --git a/common/lib/localRecordingMetadata.ts b/common/lib/localRecordingMetadata.ts
@@ -0,0 +1,157 @@
+// Pure preparation only. No archive paths, filesystem writes, or online lookup.
+// The controller assigns a stable library/file identity, reused on retries.
+export type LocalRecordingMetadata = {
+ id: string;
+ title: string;
+ duration?: number;
+ filesize?: number;
+ recorded_date?: string;
+ local_recording: {
+ version: 1;
+ titleSource: "filename" | "operator";
+ inspection: "ffprobe" | "manual";
+ durationSource: "ffprobe" | "operator" | "unknown";
+ filesizeSource?: "filesystem";
+ recordedDateSource?: "operator";
+ };
+};
+function object(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === "object" && !Array.isArray(value)
+ ? value as Record<string, unknown> : null;
+}
+function duration(value: unknown): number | null {
+ // ffprobe represents duration as a decimal string. Do not coerce null, booleans,
+ // hex, or an unavailable duration into a seemingly valid media measurement.
+ if (typeof value === "string" && !/^\d+(?:\.\d+)?$/.test(value)) return null;
+ if (typeof value !== "string" && typeof value !== "number") return null;
+ const number = Number(value);
+ return Number.isFinite(number) && number > 0 ? number : null;
+}
+export function localRecordingDuration(probe: unknown): number {
+ const raw = object(probe);
+ const streams = raw?.streams;
+ if (!Array.isArray(streams) || !streams.some(item => {
+ const stream = object(item);
+ return stream?.codec_type === "video" && object(stream.disposition)?.attached_pic !== 1;
+ })) throw new Error("No video stream found");
+ const seconds = duration(object(raw?.format)?.duration);
+ if (seconds === null) throw new Error("Media duration is unavailable; review the recording");
+ return seconds;
+}
+function recordingDate(value: string | undefined): string | undefined {
+ if (value === undefined || value.trim() === "") return undefined;
+ const date = value.trim();
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || date.slice(0, 4) === "0000") {
+ throw new Error("Recording date must be a real YYYY-MM-DD date");
+ }
+ const parsed = new Date(date + "T00:00:00Z");
+ if (!Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== date) {
+ throw new Error("Recording date must be a real YYYY-MM-DD date");
+ }
+ return date.replace(/-/g, "");
+}
+type RecordingDetails = {
+ id: string;
+ filename: string;
+ title?: string;
+ recordedDate?: string;
+};
+function recordingDetails(input: RecordingDetails) {
+ // A separate namespace avoids interpreting local identities as provider IDs.
+ // It is assigned by the server, never derived from an editable title or date.
+ if (!/^local-[0-9a-f]{32}$/.test(input.id)) throw new Error("Invalid local recording identity");
+ if (!input.filename || /[\\/\x00-\x1f\x7f]/.test(input.filename)
+ || !/\.mp4$/i.test(input.filename)) throw new Error("Expected a bare MP4 filename");
+ const supplied = input.title?.trim();
+ const title = supplied || input.filename.slice(0, -4).trim();
+ if (!title || title.length > 1000 || /[\x00-\x1f\x7f]/.test(title)) throw new Error("Enter a valid title (up to 1000 characters)");
+ const date = recordingDate(input.recordedDate);
+ return { id: input.id, title, date, titleSource: supplied ? "operator" as const : "filename" as const };
+}
+export function prepareLocalRecordingMetadata(input: RecordingDetails & { probe: unknown }): LocalRecordingMetadata {
+ const details = recordingDetails(input);
+ return {
+ id: details.id, title: details.title, duration: localRecordingDuration(input.probe),
+ ...(details.date ? { recorded_date: details.date } : {}),
+ local_recording: {
+ version: 1, titleSource: details.titleSource, inspection: "ffprobe", durationSource: "ffprobe",
+ ...(details.date ? { recordedDateSource: "operator" as const } : {}),
+ },
+ };
+}
+
+// Explicit alternative, never a silent fallback after failed inspection. This
+// path needs neither a process nor a probe result. File size comes from the
+// controller's fresh stat, not the form. It cannot establish duration or dates.
+export function prepareManualLocalRecordingMetadata(input: RecordingDetails & {
+ durationSeconds?: number;
+ fileSizeBytes?: number;
+}): LocalRecordingMetadata {
+ const details = recordingDetails(input);
+ if (input.durationSeconds !== undefined && (typeof input.durationSeconds !== "number"
+ || !Number.isFinite(input.durationSeconds) || input.durationSeconds <= 0)) {
+ throw new Error("Enter a positive duration in seconds, or leave it unknown");
+ }
+ if (input.fileSizeBytes !== undefined && (!Number.isSafeInteger(input.fileSizeBytes) || input.fileSizeBytes < 0)) {
+ throw new Error("Invalid file size");
+ }
+ return {
+ id: details.id, title: details.title,
+ ...(input.durationSeconds !== undefined ? { duration: input.durationSeconds } : {}),
+ ...(input.fileSizeBytes !== undefined ? { filesize: input.fileSizeBytes } : {}),
+ ...(details.date ? { recorded_date: details.date } : {}),
+ local_recording: {
+ version: 1, titleSource: details.titleSource, inspection: "manual",
+ durationSource: input.durationSeconds === undefined ? "unknown" : "operator",
+ ...(input.fileSizeBytes !== undefined ? { filesizeSource: "filesystem" as const } : {}),
+ ...(details.date ? { recordedDateSource: "operator" as const } : {}),
+ },
+ };
+}
+
+// Validate persisted local metadata before it enters the corpus or a summary.
+// A local-looking ID alone is never enough to relabel an online recording.
+export function requireLocalRecordingMetadata(value: unknown): LocalRecordingMetadata {
+ const raw = object(value);
+ const mark = object(raw?.local_recording);
+ const invalid = () => { throw new Error("Invalid local recording metadata"); };
+ if (!raw || !mark) return invalid();
+ const keys = ["id", "title", "duration", "filesize", "recorded_date", "local_recording"];
+ const markKeys = ["version", "titleSource", "inspection", "durationSource", "filesizeSource", "recordedDateSource"];
+ if (Object.keys(raw).some(key => !keys.includes(key))
+ || Object.keys(mark).some(key => !markKeys.includes(key))
+ || mark.version !== 1 || !["filename", "operator"].includes(String(mark.titleSource))
+ || typeof raw.id !== "string" || !/^local-[0-9a-f]{32}$/.test(raw.id)
+ || typeof raw.title !== "string" || raw.title !== raw.title.trim()
+ || !raw.title || raw.title.length > 1000 || /[\x00-\x1f\x7f]/.test(raw.title)) return invalid();
+ if (raw.duration !== undefined && (typeof raw.duration !== "number"
+ || !Number.isFinite(raw.duration) || raw.duration <= 0)) return invalid();
+ if (mark.inspection === "ffprobe") {
+ if (raw.duration === undefined || mark.durationSource !== "ffprobe") return invalid();
+ } else if (mark.inspection === "manual") {
+ if (mark.durationSource !== (raw.duration === undefined ? "unknown" : "operator")) return invalid();
+ } else return invalid();
+ if (raw.filesize !== undefined) {
+ if (typeof raw.filesize !== "number" || !Number.isSafeInteger(raw.filesize)
+ || raw.filesize < 0 || mark.filesizeSource !== "filesystem") return invalid();
+ } else if (mark.filesizeSource !== undefined) return invalid();
+ if (raw.recorded_date !== undefined) {
+ if (typeof raw.recorded_date !== "string" || !/^\d{8}$/.test(raw.recorded_date)
+ || mark.recordedDateSource !== "operator") return invalid();
+ const date = raw.recorded_date;
+ recordingDate(date.slice(0, 4) + "-" + date.slice(4, 6) + "-" + date.slice(6));
+ } else if (mark.recordedDateSource !== undefined) return invalid();
+ return raw as LocalRecordingMetadata;
+}
+
+// The same rule as requireLocalRecordingMetadata, as a value: null when the
+// metadata is a valid local recording, else why not. For the readers that
+// must not throw on one bad file (platformFromMetadata, the index).
+export function localRecordingProblem(value: unknown): string | null {
+ try {
+ requireLocalRecordingMetadata(value);
+ return null;
+ } catch (error) {
+ return (error as Error).message || "Invalid local recording metadata";
+ }
+}
diff --git a/common/lib/localRecordingProbe-server.test.ts b/common/lib/localRecordingProbe-server.test.ts
@@ -0,0 +1,57 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, writeFile, chmod, rm, symlink } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { execFileSync } from "node:child_process";
+import { probeLocalRecording } from "./localRecordingProbe-server";
+import { prepareLocalRecordingMetadata } from "./localRecordingMetadata";
+
+test("real ffprobe inspects synthetic MP4 without changing it or requiring an online source", async () => {
+ const root = await mkdtemp(path.join(tmpdir(), "local-probe-"));
+ try {
+ const file = path.join(root, "Lesson one.mp4");
+ execFileSync("ffmpeg", ["-v", "error", "-f", "lavfi", "-i", "color=c=black:s=32x32:r=5", "-t", "1", "-c:v", "mpeg4", file], {timeout: 15000});
+ const before = await readFile(file);
+ const probe = await probeLocalRecording({file, ffprobeBin: "ffprobe"});
+ assert.ok(probe.format.duration > 0);
+ assert.deepEqual(await readFile(file), before);
+ const metadata = prepareLocalRecordingMetadata({id: "local-FAKE-TEST-VALUEFAKE-TEST-VALUE", filename: "Lesson one.mp4", probe});
+ assert.equal(metadata.title, "Lesson one");
+ assert.equal("upload_date" in metadata, false);
+ assert.equal("webpage_url" in metadata, false);
+ assert.equal(JSON.stringify(probe).includes(root), false);
+ await assert.rejects(probeLocalRecording({file, ffprobeBin: path.join(root, "missing-tool")}), /ffprobe is unavailable.*editor server/);
+ const abort = new AbortController(); abort.abort();
+ await assert.rejects(probeLocalRecording({file, ffprobeBin: "ffprobe", signal: abort.signal}));
+ const linked = path.join(root, "linked.mp4"); await symlink(file, linked);
+ await assert.rejects(probeLocalRecording({file: linked, ffprobeBin: "ffprobe"}), /regular MP4/);
+ } finally { await rm(root, {recursive: true, force: true}); }
+});
+
+test("corrupt MP4 and remote inputs fail without exposing private diagnostic paths", async () => {
+ const root = await mkdtemp(path.join(tmpdir(), "private-probe-"));
+ try {
+ const file = path.join(root, "bad.mp4"); await writeFile(file, "not a video");
+ await assert.rejects(probeLocalRecording({file, ffprobeBin: "ffprobe"}), error => {
+ assert.ok(error instanceof Error); assert.equal(error.message.includes(root), false);
+ return /Media inspection failed/.test(error.message);
+ });
+ await assert.rejects(probeLocalRecording({file: "https://example.com/movie.mp4", ffprobeBin: "ffprobe"}), /absolute local/);
+ } finally { await rm(root, {recursive: true, force: true}); }
+});
+
+test("inspection bounds timeout, output, and invalid JSON from the executable", async () => {
+ const root = await mkdtemp(path.join(tmpdir(), "bounded-probe-"));
+ try {
+ const file = path.join(root, "sample.mp4"); await writeFile(file, "fixture");
+ const bin = path.join(root, "probe-fixture");
+ const script = async (body: string) => { await writeFile(bin, "#!/usr/bin/env node\n" + body + "\n"); await chmod(bin, 0o755); };
+ await script("setInterval(() => {}, 1000)");
+ await assert.rejects(probeLocalRecording({file, ffprobeBin: bin, timeoutMs: 200}), /time limit/);
+ await script("process.stdout.write('x'.repeat(1024 * 1024))");
+ await assert.rejects(probeLocalRecording({file, ffprobeBin: bin}), /output limit/);
+ await script("process.stdout.write('not JSON')");
+ await assert.rejects(probeLocalRecording({file, ffprobeBin: bin}), /invalid data/);
+ } finally { await rm(root, {recursive: true, force: true}); }
+});
diff --git a/common/lib/localRecordingProbe-server.ts b/common/lib/localRecordingProbe-server.ts
@@ -0,0 +1,47 @@
+import { execFile } from "node:child_process";
+import path from "node:path";
+import { lstat } from "node:fs/promises";
+import { localRecordingDuration } from "./localRecordingMetadata";
+
+// Internal process adapter, not an HTTP action. The controller must first resolve
+// the file through the configured library and apply channel/storage guards.
+// ffprobeBin comes from Paths (FFPROBE_BIN), never from form input.
+export async function probeLocalRecording(options: {
+ file: string; ffprobeBin: string; signal?: AbortSignal; timeoutMs?: number;
+}): Promise<{ format: { duration: number }; streams: Array<{ codec_type: "video" }> }> {
+ if (!path.isAbsolute(options.file) || !/\.mp4$/i.test(options.file)) throw new Error("Expected an absolute local MP4 path");
+ options.signal?.throwIfAborted();
+ const before = await lstat(options.file);
+ if (!before.isFile() || before.isSymbolicLink()) throw new Error("Expected a regular MP4 file");
+ const timeout = options.timeoutMs ?? 15000;
+ if (!Number.isFinite(timeout) || timeout < 1 || timeout > 15000) throw new Error("Invalid inspection timeout");
+ const stdout = await new Promise<string>((resolve, reject) => {
+ execFile(options.ffprobeBin, ["-v", "error", "-protocol_whitelist", "file",
+ "-f", "mov", "-show_entries", "format=duration:stream=codec_type:stream_disposition=attached_pic",
+ "-of", "json", options.file], {
+ encoding: "utf8", timeout, maxBuffer: 256 * 1024, killSignal: "SIGKILL",
+ windowsHide: true, signal: options.signal,
+ }, (error, output) => {
+ if (!error) { resolve(output); return; }
+ // Never expose ffprobe stderr: it can contain full private source paths.
+ const code = (error as NodeJS.ErrnoException).code;
+ reject(new Error(options.signal?.aborted ? "Media inspection cancelled"
+ : code === "ENOENT" ? "ffprobe is unavailable on the editor server. Install FFmpeg with ffprobe, or configure FFPROBE_BIN."
+ : code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" ? "Media inspection exceeded its output limit"
+ : error.killed ? "Media inspection exceeded its time limit"
+ : "Media inspection failed; check that the file is a readable MP4"));
+ });
+ });
+ const after = await lstat(options.file);
+ if (!after.isFile() || after.isSymbolicLink() || before.dev !== after.dev || before.ino !== after.ino
+ || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) {
+ throw new Error("Recording changed during inspection; preview again");
+ }
+ options.signal?.throwIfAborted();
+ let raw: unknown;
+ try { raw = JSON.parse(stdout); } catch { throw new Error("Media inspection returned invalid data"); }
+ const duration = localRecordingDuration(raw);
+ // Only facts needed by preparation cross this boundary. No tags, filenames,
+ // source URLs or embedded timestamps are copied into managed metadata.
+ return { format: { duration }, streams: [{ codec_type: "video" }] };
+}
diff --git a/common/lib/lookout.test.ts b/common/lib/lookout.test.ts
@@ -0,0 +1,164 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ COVERED_THRESHOLD,
+ addDays,
+ airDateOf,
+ foldRecordings,
+ inWindow,
+ isIsoDate,
+ localDateOf,
+ lookoutWindow,
+ type DedupeVideo,
+} from "./lookout";
+import { shingles } from "./duplicates";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/lookout.test.ts
+
+// A real start time: 2026-11-04T01:20:53Z, an evening stream in New York.
+const EVENING_STREAM = 1793755253;
+
+test("the UTC trap: an evening stream airs on the local date, not on upload_date's", () => {
+ const ny = airDateOf({ releaseTimestamp: EVENING_STREAM, timestamp: EVENING_STREAM - 488, uploadDate: "20261104" }, "America/New_York");
+ assert.deepEqual(ny, { date: "2026-11-03", at: "2026-11-04T01:20:53.000Z", source: "release_timestamp" });
+ assert.equal(airDateOf({ releaseTimestamp: EVENING_STREAM, uploadDate: "20261104" }, "UTC")?.date, "2026-11-04");
+ assert.equal(airDateOf({ releaseTimestamp: EVENING_STREAM, uploadDate: "20261104" }, "Europe/Berlin")?.date, "2026-11-04");
+});
+
+test("release_timestamp, else timestamp, else upload_date — and a far-off timestamp is not believed", () => {
+ assert.equal(airDateOf({ timestamp: EVENING_STREAM, uploadDate: "20261104" }, "America/New_York")?.source, "timestamp");
+ assert.deepEqual(airDateOf({ uploadDate: "20261104" }, "America/New_York"), { date: "2026-11-04", at: null, source: "upload_date" });
+ // A nested key read by mistake, months away: the upload date wins.
+ assert.deepEqual(airDateOf({ timestamp: 1600000000, uploadDate: "20261104" }, "UTC"), { date: "2026-11-04", at: null, source: "upload_date" });
+ assert.equal(airDateOf({}, "UTC"), null);
+ assert.equal(airDateOf({ timestamp: 0, uploadDate: "garbage" }, "UTC"), null);
+});
+
+test("the window counts calendar days in the lookout's zone, both ends included", () => {
+ assert.deepEqual(lookoutWindow({ days: 7, timeZone: "America/New_York", until: "2026-11-10" }), {
+ from: "2026-11-04",
+ to: "2026-11-10",
+ days: 7,
+ timeZone: "America/New_York",
+ });
+ // "Today" is the zone's today: 03:00Z on 11 Nov is still 10 Nov in New York.
+ const now = new Date("2026-11-11T03:00:00Z");
+ assert.equal(lookoutWindow({ days: 1, timeZone: "America/New_York", now }).to, "2026-11-10");
+ assert.equal(lookoutWindow({ days: 1, timeZone: "UTC", now }).to, "2026-11-11");
+ assert.ok(inWindow("2026-11-04", { from: "2026-11-04", to: "2026-11-10" }));
+ assert.ok(!inWindow("2026-11-03", { from: "2026-11-04", to: "2026-11-10" }));
+ assert.equal(addDays("2026-02-28", 1), "2026-03-01");
+ assert.equal(addDays("2026-03-01", -1), "2026-02-28");
+ assert.ok(isIsoDate("2026-11-10") && !isIsoDate("2026-02-30") && !isIsoDate("20261110"));
+ assert.equal(localDateOf(Date.UTC(2026, 10, 4, 4, 59), "America/New_York"), "2026-11-03");
+});
+
+function text(seed: number, n: number): string[] {
+ let x = seed >>> 0;
+ return Array.from({ length: n }, () => {
+ x = (Math.imul(x, 1664525) + 1013904223) >>> 0;
+ return `w${(x >>> 16) % 3000}`;
+ });
+}
+const sh = (ws: string[]) => shingles(ws.join(" "), 5);
+function vid(key: string, o: Partial<DedupeVideo> & { words: string[] }): DedupeVideo {
+ return {
+ key,
+ title: o.title ?? key,
+ platform: o.platform ?? "youtube",
+ duration: o.duration ?? 600,
+ airAt: o.airAt ?? "2026-11-04T12:00:00.000Z",
+ shingles: sh(o.words),
+ };
+}
+
+test("a twin upload with the same title and runtime is folded, the first on the air read", () => {
+ const ws = text(1, 2000);
+ const groups = foldRecordings([
+ vid("b/yt", { words: ws, title: "Big News!", duration: 824, airAt: "2026-11-04T15:00:00.000Z" }),
+ vid("a/rumble", { words: ws.map((w, i) => (i % 12 === 0 ? "zz" : w)), title: "BIG NEWS", platform: "rumble", duration: 825, airAt: "2026-11-04T14:00:00.000Z" }),
+ ]);
+ assert.equal(groups.length, 1);
+ assert.equal(groups[0]!.primary, "a/rumble");
+ assert.deepEqual(groups[0]!.folded.map((f) => [f.key, f.reason, f.titleMatch]), [["b/yt", "duplicate-upload", true]]);
+});
+
+test("a re-titled mirror is caught by its text; a same-titled different video is caught by its runtime", () => {
+ const ws = text(2, 2000);
+ const retitled = foldRecordings([
+ vid("a/one", { words: ws, title: "THIS IS DISGRACEFUL!", duration: 825 }),
+ vid("b/two", { words: ws, title: "Massive Story Revealed & More", duration: 824, platform: "rumble" }),
+ ]);
+ assert.equal(retitled.length, 1);
+ assert.equal(retitled[0]!.folded[0]!.titleMatch, undefined);
+ assert.ok(retitled[0]!.folded[0]!.score > 0.9);
+ // The same title, a runtime 10 % off, unrelated text: two recordings.
+ const series = foldRecordings([
+ vid("a/ep1", { words: text(3, 2000), title: "Daily Show", duration: 900 }),
+ vid("a/ep2", { words: text(4, 2000), title: "Daily Show", duration: 1000 }),
+ ]);
+ assert.equal(series.length, 2);
+ // The same title and the same runtime, unrelated text: two episodes, both read.
+ const episodes = foldRecordings([
+ vid("a/mon", { words: text(5, 2000), title: "Daily Show", duration: 900 }),
+ vid("a/tue", { words: text(6, 2000), title: "Daily Show", duration: 905 }),
+ ]);
+ assert.equal(episodes.length, 2);
+ // ...unless one has no text to compare: then the title and runtime decide.
+ const silent = foldRecordings([
+ vid("a/mon", { words: text(5, 2000), title: "Daily Show", duration: 900 }),
+ vid("b/copy", { words: [], title: "Daily Show", duration: 905 }),
+ ]);
+ assert.equal(silent.length, 1);
+ // Near-identical text but runtimes far apart is not a twin (it may be a cut-down; see below).
+ const apart = foldRecordings([
+ vid("a/x", { words: ws, duration: 600 }),
+ vid("b/y", { words: ws, duration: 700 }),
+ ]);
+ assert.equal(apart.length, 2);
+});
+
+test("a cut-down is credited to the stream it is cut from, with its share", () => {
+ const stream = text(5, 20000);
+ const groups = foldRecordings([
+ vid("s/stream", { words: stream, duration: 7200, platform: "rumble", airAt: "2026-11-04T01:20:53.000Z" }),
+ vid("c/cut", { words: stream.slice(5000, 6500), duration: 700, title: "Clip" }),
+ vid("c/cut-twin", { words: stream.slice(5000, 6500), duration: 701, title: "Clip", platform: "rumble" }),
+ vid("o/other", { words: text(6, 1500), duration: 700, title: "Other" }),
+ ]);
+ assert.deepEqual(groups.map((g) => g.primary), ["s/stream", "o/other"]);
+ const s = groups[0]!;
+ assert.deepEqual(
+ s.folded.map((f) => [f.key, f.reason, f.matched]).sort(),
+ [
+ ["c/cut", "covered-by-stream", "s/stream"],
+ ["c/cut-twin", "covered-by-stream", "s/stream"],
+ ],
+ );
+ assert.ok(s.folded.every((f) => f.score >= COVERED_THRESHOLD));
+});
+
+test("a short video sharing a little of a stream is not its cut-down", () => {
+ const stream = text(7, 20000);
+ const mixed = [...stream.slice(100, 300), ...text(8, 800)];
+ const groups = foldRecordings([
+ vid("s/stream", { words: stream, duration: 7200 }),
+ vid("c/mixed", { words: mixed, duration: 400 }),
+ ]);
+ assert.equal(groups.length, 2);
+});
+
+test("every input appears exactly once, as a primary or folded", () => {
+ const stream = text(9, 10000);
+ const vids = [
+ vid("s/1", { words: stream, duration: 4000 }),
+ vid("s/2", { words: stream, duration: 4010, platform: "rumble" }),
+ vid("c/1", { words: stream.slice(0, 900), duration: 500 }),
+ vid("c/2", { words: text(10, 900), duration: 500 }),
+ vid("c/3", { words: text(10, 900), duration: 501, platform: "rumble" }),
+ ];
+ const groups = foldRecordings(vids);
+ const seen = groups.flatMap((g) => [g.primary, ...g.folded.map((f) => f.key)]).sort();
+ assert.deepEqual(seen, vids.map((v) => v.key).sort());
+});
diff --git a/common/lib/lookout.ts b/common/lib/lookout.ts
@@ -0,0 +1,407 @@
+// A LOOKOUT'S SELECTION, the pure half (lane/lookout stages 1–2): air dates,
+// the window, and the folding of one recording's several uploads into one read.
+// No I/O — controller/lookoutPlan.ts reads the channels and calls these.
+//
+// AIR DATE, NOT UPLOAD DATE. yt-dlp's `upload_date` is a UTC date, so an
+// evening stream in the Americas lands on the next day: an election-night
+// stream that started at 20:20 in New York is 4 Nov by `upload_date` and 3 Nov
+// on the air. A lookout's days are counted in its own time zone from the
+// metadata's `release_timestamp` (a stream's or premiere's start), else its
+// `timestamp` (the upload), and only when neither is there from `upload_date`,
+// which the plan then marks as such.
+//
+// ONE RECORDING, READ ONCE. Two cases, both decided on the cues, because
+// `transcripts/duplicates.json` is built rarely and does not know this week:
+// - a DUPLICATE UPLOAD — the same recording on two channels or platforms —
+// is two videos whose runtimes agree within 2 % and whose normalised titles
+// match or whose transcripts are near-duplicates (5-word shingle Jaccard ≥
+// 0.35, the duplicate detector's own threshold: two ASR engines over the
+// same audio land at 0.35–0.60). A re-titled mirror is caught by the text.
+// A title match alone is not enough when both have text: two episodes of
+// a show with one title and one length share none, so it also needs a
+// Jaccard of 0.1.
+// - a CUT-DOWN of a stream — a shorter upload whose text is an excerpt of a
+// long recording in the window — is a video under 30 minutes at least 40 %
+// of whose shingles are in one stream (the pilot's measured rule). It is
+// credited to the stream as an alternate source and not read on its own.
+// Every folded video stays in the plan, under the recording it was folded into,
+// with why and its score.
+
+import {
+ DEFAULT_NEAR_THRESHOLD,
+ DEFAULT_SHINGLE_SIZE,
+ DEFAULT_TITLE_DURATION_RATIO,
+ UnionFind,
+ durationsCompatible,
+ intersectionSize,
+ jaccard,
+ normalizeTitleKey,
+ platformRank,
+} from "./duplicates";
+
+// ─── Air dates and the window ───
+
+export type AirDateSource = "release_timestamp" | "timestamp" | "upload_date";
+
+export type AirDate = {
+ /** YYYY-MM-DD in the lookout's time zone (or the UTC upload date, when that is all there is). */
+ date: string;
+ /** ISO 8601 instant, when a timestamp gave it. */
+ at: string | null;
+ source: AirDateSource;
+};
+
+/** The machine's IANA zone (what a lookout's `timeZone: ""` means). */
+export function machineTimeZone(): string {
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
+}
+
+/** `tz`, or the machine's when it is "". */
+export function resolveTimeZone(tz: string): string {
+ return tz ? tz : machineTimeZone();
+}
+
+/** The calendar date (YYYY-MM-DD) of an instant in `tz`. */
+export function localDateOf(ms: number, tz: string): string {
+ const parts = new Intl.DateTimeFormat("en-US", {
+ timeZone: tz,
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit",
+ }).formatToParts(new Date(ms));
+ const get = (t: string) => parts.find((p) => p.type === t)?.value ?? "";
+ return `${get("year")}-${get("month")}-${get("day")}`;
+}
+
+/** "20261104" → "2026-11-04"; null for anything else. */
+export function isoOfUploadDate(yyyymmdd: string | null | undefined): string | null {
+ if (typeof yyyymmdd !== "string" || !/^\d{8}$/.test(yyyymmdd)) return null;
+ return `${yyyymmdd.slice(0, 4)}-${yyyymmdd.slice(4, 6)}-${yyyymmdd.slice(6, 8)}`;
+}
+
+const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
+
+export function isIsoDate(s: unknown): s is string {
+ if (typeof s !== "string" || !ISO_DATE_RE.test(s)) return false;
+ const d = new Date(`${s}T00:00:00Z`);
+ return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === s;
+}
+
+/** A YYYY-MM-DD date `n` days later (negative: earlier). */
+export function addDays(date: string, n: number): string {
+ const d = new Date(`${date}T00:00:00Z`);
+ d.setUTCDate(d.getUTCDate() + n);
+ return d.toISOString().slice(0, 10);
+}
+
+/** Whole days from `a` to `b` (both YYYY-MM-DD). */
+export function daysBetween(a: string, b: string): number {
+ return Math.round((Date.parse(`${b}T00:00:00Z`) - Date.parse(`${a}T00:00:00Z`)) / 86_400_000);
+}
+
+// A timestamp further than this from the record's own UTC `upload_date` is not
+// believed (a nested key read by mistake, a broken record): the upload date is
+// used instead and the plan says so.
+const TIMESTAMP_TRUST_DAYS = 2;
+
+/**
+ * A video's air date in `tz`: its `release_timestamp`, else its `timestamp`
+ * (seconds since the epoch, as yt-dlp writes them), else its `upload_date`.
+ * Null when it has none of the three.
+ */
+export function airDateOf(
+ meta: { releaseTimestamp?: number | null; timestamp?: number | null; uploadDate?: string | null },
+ tz: string,
+): AirDate | null {
+ const upload = isoOfUploadDate(meta.uploadDate);
+ const candidates: [AirDateSource, number | null | undefined][] = [
+ ["release_timestamp", meta.releaseTimestamp],
+ ["timestamp", meta.timestamp],
+ ];
+ for (const [source, ts] of candidates) {
+ if (typeof ts !== "number" || !Number.isFinite(ts) || ts <= 0) continue;
+ const ms = ts * 1000;
+ const utc = new Date(ms).toISOString().slice(0, 10);
+ if (upload && Math.abs(daysBetween(upload, utc)) > TIMESTAMP_TRUST_DAYS) continue;
+ return { date: localDateOf(ms, tz), at: new Date(ms).toISOString(), source };
+ }
+ return upload ? { date: upload, at: null, source: "upload_date" } : null;
+}
+
+export type LookoutWindow = {
+ /** First day read, YYYY-MM-DD, inclusive. */
+ from: string;
+ /** Last day read, YYYY-MM-DD, inclusive. */
+ to: string;
+ days: number;
+ timeZone: string;
+};
+
+/**
+ * The `days` calendar days ending on `until` (default: today in `tz`), both
+ * ends included: days 7 on 11 Nov is 5–11 Nov.
+ */
+export function lookoutWindow(o: { days: number; timeZone: string; until?: string | null; now?: Date }): LookoutWindow {
+ const tz = resolveTimeZone(o.timeZone);
+ const to = o.until && isIsoDate(o.until) ? o.until : localDateOf((o.now ?? new Date()).getTime(), tz);
+ const days = Math.max(1, Math.round(o.days));
+ return { from: addDays(to, -(days - 1)), to, days, timeZone: tz };
+}
+
+export function inWindow(date: string, w: Pick<LookoutWindow, "from" | "to">): boolean {
+ return date >= w.from && date <= w.to;
+}
+
+// ─── One recording, read once ───
+
+export const LOOKOUT_SHINGLE_SIZE = DEFAULT_SHINGLE_SIZE;
+/** Duplicate uploads: transcripts at least this similar (Jaccard) are one recording. */
+export const TWIN_TEXT_THRESHOLD = DEFAULT_NEAR_THRESHOLD;
+/** Duplicate uploads with the same title: their transcripts still share at least this much (Jaccard), when both have text. */
+export const TWIN_TITLE_TEXT_FLOOR = 0.1;
+/** Duplicate uploads: runtimes within this fraction of the longer. */
+export const TWIN_DURATION_RATIO = DEFAULT_TITLE_DURATION_RATIO;
+/** A recording this long or longer is a stream other uploads may be cut from. */
+export const STREAM_MIN_SECONDS = 1800;
+/** A shorter upload with at least this share of its shingles in a stream is that stream's cut-down. */
+export const COVERED_THRESHOLD = 0.4;
+
+export type DedupeVideo = {
+ /** `<channel>/<video dir>` — unique in a plan. */
+ key: string;
+ title: string;
+ platform: string;
+ duration: number | null;
+ /** ISO instant or date the video aired, for the tie-break (earliest first). */
+ airAt: string;
+ /** Shingles of its cue text (`comparisonText` → `shingles`). */
+ shingles: ReadonlySet<string>;
+};
+
+export type FoldReason = "duplicate-upload" | "covered-by-stream";
+
+export type FoldedVideo = {
+ key: string;
+ reason: FoldReason;
+ /** The video it was compared with: the twin it matched, or the stream it is cut from. */
+ matched: string;
+ /** Jaccard (a duplicate upload) or the share of its shingles in the stream (a cut-down), 0–1. */
+ score: number;
+ /** A duplicate upload whose normalised title matched as well. */
+ titleMatch?: boolean;
+};
+
+export type RecordingGroup = {
+ /** The upload read for this recording. */
+ primary: string;
+ /** Every other upload of it, and every cut-down credited to it. */
+ folded: FoldedVideo[];
+};
+
+const round2 = (n: number) => Math.round(n * 100) / 100;
+
+// The upload read for a set of duplicates — and so the date the recording is
+// listed on: the FIRST on the air (a stream is dated by its start, not by the
+// copy posted the next morning), then the preferred platform (duplicates.ts'
+// order), then the longest, then the key.
+function better(a: DedupeVideo, b: DedupeVideo): boolean {
+ if (a.airAt !== b.airAt) return a.airAt < b.airAt;
+ const pa = platformRank(a.platform);
+ const pb = platformRank(b.platform);
+ if (pa !== pb) return pa < pb;
+ const da = a.duration ?? 0;
+ const db = b.duration ?? 0;
+ if (da !== db) return da > db;
+ return a.key < b.key;
+}
+
+/** |A∩B| / |A|: how much of `a` is in `b`. */
+function shareIn(a: ReadonlySet<string>, b: ReadonlySet<string>): number {
+ if (a.size === 0) return 0;
+ return intersectionSize(a as Set<string>, b as Set<string>) / a.size;
+}
+
+/**
+ * Fold `videos` into recordings: duplicate uploads first, then cut-downs of a
+ * stream. Every input appears exactly once — as a group's primary or as one of
+ * its folded videos. Groups come back longest primary first.
+ */
+export function foldRecordings(videos: readonly DedupeVideo[]): RecordingGroup[] {
+ const byKey = new Map(videos.map((v) => [v.key, v]));
+ const uf = new UnionFind();
+ const twinEdge = new Map<string, { score: number; titleMatch: boolean }>();
+ const titleKeys = new Map(videos.map((v) => [v.key, normalizeTitleKey(v.title)]));
+ for (const v of videos) uf.add(v.key);
+ for (let i = 0; i < videos.length; i++) {
+ for (let j = i + 1; j < videos.length; j++) {
+ const a = videos[i]!;
+ const b = videos[j]!;
+ if (!a.duration || !b.duration || !durationsCompatible(a.duration, b.duration, TWIN_DURATION_RATIO)) continue;
+ const ta = titleKeys.get(a.key)!;
+ const titleMatch = ta !== "" && ta === titleKeys.get(b.key);
+ const score = jaccard(a.shingles as Set<string>, b.shingles as Set<string>);
+ // A title is not a recording: a daily show keeps one title and much the
+ // same runtime. With both transcripts in hand a title match still needs
+ // some shared text; with one empty there is only the title to go on.
+ const titleTwin =
+ titleMatch && (a.shingles.size === 0 || b.shingles.size === 0 || score >= TWIN_TITLE_TEXT_FLOOR);
+ if (!titleTwin && score < TWIN_TEXT_THRESHOLD) continue;
+ uf.union(a.key, b.key);
+ twinEdge.set(`${a.key}\n${b.key}`, { score, titleMatch });
+ twinEdge.set(`${b.key}\n${a.key}`, { score, titleMatch });
+ }
+ }
+
+ type Group = { primary: DedupeVideo; members: DedupeVideo[]; folded: FoldedVideo[] };
+ const groups: Group[] = uf.groups().map((keys) => {
+ const members = keys.map((k) => byKey.get(k)!).sort((a, b) => (a.key < b.key ? -1 : 1));
+ const primary = members.reduce((best, v) => (better(v, best) ? v : best));
+ const folded: FoldedVideo[] = members
+ .filter((m) => m !== primary)
+ .map((m) => {
+ const edge = twinEdge.get(`${m.key}\n${primary.key}`);
+ const score = edge?.score ?? jaccard(m.shingles as Set<string>, primary.shingles as Set<string>);
+ return {
+ key: m.key,
+ reason: "duplicate-upload" as const,
+ matched: primary.key,
+ score: round2(score),
+ ...(normalizeTitleKey(m.title) === titleKeys.get(primary.key) ? { titleMatch: true } : {}),
+ };
+ });
+ return { primary, members, folded };
+ });
+
+ const isStream = (g: Group) => (g.primary.duration ?? 0) >= STREAM_MIN_SECONDS;
+ const streams = groups.filter(isStream).map((g) => {
+ // The stream's text is every upload of it: a cut-down posted to YouTube
+ // matches the YouTube copy of a stream better than the other platform's.
+ const all = new Set<string>();
+ for (const m of g.members) for (const s of m.shingles) all.add(s);
+ return { group: g, shingles: all };
+ });
+ const kept: Group[] = [];
+ for (const g of groups) {
+ if (isStream(g) || streams.length === 0) {
+ kept.push(g);
+ continue;
+ }
+ let best: { stream: (typeof streams)[number]; share: number; member: DedupeVideo } | null = null;
+ for (const stream of streams) {
+ for (const m of g.members) {
+ const share = shareIn(m.shingles, stream.shingles);
+ if (!best || share > best.share) best = { stream, share, member: m };
+ }
+ }
+ if (!best || best.share < COVERED_THRESHOLD) {
+ kept.push(g);
+ continue;
+ }
+ const target = best.stream.group;
+ for (const m of g.members) {
+ target.folded.push({
+ key: m.key,
+ reason: "covered-by-stream",
+ matched: target.primary.key,
+ score: round2(shareIn(m.shingles, best.stream.shingles)),
+ });
+ }
+ }
+ return kept
+ .sort((a, b) => (b.primary.duration ?? 0) - (a.primary.duration ?? 0) || (a.primary.key < b.primary.key ? -1 : 1))
+ .map((g) => ({
+ primary: g.primary.key,
+ folded: g.folded.sort((a, b) => (a.reason === b.reason ? (a.key < b.key ? -1 : 1) : a.reason === "duplicate-upload" ? -1 : 1)),
+ }));
+}
+
+// ─── The plan: what a lookout would read ───
+
+/** One video as a plan names it. */
+export type LookoutPlanVideo = {
+ channel: string;
+ /** Its directory under `channels/<channel>/data/`. */
+ video: string;
+ /** The record's id (a Rumble video's directory is its URL slug; its id is the embed id). */
+ id: string;
+ title: string;
+ platform: string;
+ airDate: string;
+ airAt: string | null;
+ dateSource: AirDateSource;
+ /** Seconds; null when neither the cues nor the metadata say. */
+ duration: number | null;
+ url: string | null;
+};
+
+export type LookoutPlanFolded = LookoutPlanVideo & Omit<FoldedVideo, "key">;
+
+export type LookoutPlanRead = LookoutPlanVideo & {
+ /** Characters of transcript text. */
+ chars: number;
+ /** Model-sized chunks (sweep-pipeline's CHUNK_CHARS) — one reading call each. */
+ chunks: number;
+ /** The other uploads of this recording and the cut-downs credited to it. */
+ folded: LookoutPlanFolded[];
+};
+
+export type LookoutSkipReason =
+ | "under-min-seconds"
+ | "no-transcript"
+ | "local-recording"
+ | "not-finished"
+ | "cap";
+
+export type LookoutPlanSkipped = LookoutPlanVideo & {
+ reason: LookoutSkipReason;
+ /** A cap skip carries the uploads folded into it, so nothing it stood for is lost from view. */
+ folded?: LookoutPlanFolded[];
+ chunks?: number;
+};
+
+export type LookoutPlan = {
+ version: 1;
+ lookout: { id: string; label: string };
+ channels: string[];
+ /** Channels named but not read, and why (a local library, a slug this archive does not hold, unreadable text). */
+ refused: { channel: string; reason: string }[];
+ window: LookoutWindow;
+ minSeconds: number;
+ maxVideos: number;
+ generatedAt: string;
+ counts: {
+ /** Video directories listed, across the channels read. */
+ scanned: number;
+ /** Of those, the ones changed since shortly before the window (directory ctime), whose files were read. */
+ examined: number;
+ /** Videos with a transcript whose air date is in the window. */
+ inWindow: number;
+ /** Videos in the window with no transcript yet (not read, listed). */
+ noTranscript: number;
+ underMinSeconds: number;
+ /** In the window, with a transcript, long enough — what is folded and capped. */
+ qualified: number;
+ duplicateUploads: number;
+ coveredByStream: number;
+ /** Recordings after folding. */
+ recordings: number;
+ read: number;
+ skippedForCap: number;
+ /** Other skips: local recordings, live or upcoming videos. */
+ otherSkipped: number;
+ /** In the window, dated by `upload_date` alone (no timestamp in the metadata). */
+ datedByUploadDate: number;
+ };
+ read: LookoutPlanRead[];
+ skipped: LookoutPlanSkipped[];
+ estimate: {
+ /** One reading call per chunk of every recording read (a video with fresh reading notes will need none: slice 2). */
+ readCalls: number;
+ /** Measured over the lookout's last runs; null before the first. */
+ secondsPerCall: number | null;
+ /** readCalls × secondsPerCall, rounded; null when not measured. Grouping calls (a few) are not in it. */
+ seconds: number | null;
+ basis: string;
+ };
+ warnings: string[];
+};
diff --git a/common/lib/lookoutNoChannelNames.test.ts b/common/lib/lookoutNoChannelNames.test.ts
@@ -0,0 +1,75 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { readdir, readFile } from "node:fs/promises";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/lookoutNoChannelNames.test.ts
+//
+// NO CHANNEL IS NAMED IN THE LOOKOUT'S CODE (lane/lookout, acceptance c). A
+// lookout is configured on the machine that runs it; the standing one is a
+// settings patch there, never a default, an example or a fixture here. This
+// test walks every file whose path names a lookout — the libs, the
+// controllers, the ops routes and their tests, and whatever later slices add
+// under those names — and fails on any word of the pilot lookout's channel
+// names. The words are kept as SHA-256 digests so the guard does not itself
+// spell what it forbids.
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const REPO = path.resolve(HERE, "..", "..");
+const ROOTS = ["common/lib", "common/controller", "common/bin", "common/jobs", "editor/app", "umtool/lib", "umtool/app", "umtool/bin"];
+
+// sha256 of each forbidden word (lowercase): the two distinctive words of the
+// pilot lookout's four channel slugs.
+const FORBIDDEN = new Set([
+ "7a0b56a32407bfffffb453b775850130b36277a20de9611f153c0d3bf3dfa153",
+ "877a89b30f7ffb2b5b079e4a84066c05c476a1dda97209fce21d3a4aefac3dfc",
+]);
+
+const sha = (w: string) => createHash("sha256").update(w).digest("hex");
+
+async function lookoutFiles(dir: string, under = false): Promise<string[]> {
+ let entries;
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ return [];
+ }
+ const out: string[] = [];
+ for (const e of entries) {
+ if (e.name === "node_modules" || e.name.startsWith(".")) continue;
+ const p = path.join(dir, e.name);
+ const named = under || /lookout/i.test(e.name);
+ if (e.isDirectory()) out.push(...(await lookoutFiles(p, named)));
+ else if (named && /\.(ts|tsx|mjs|js|json|md)$/.test(e.name)) out.push(p);
+ }
+ return out;
+}
+
+test("the guard is live: its digests match words the repo's own docs use", async () => {
+ // A positive control, so a mistyped digest cannot silently disable the
+ // guard: the repo's instructions and the ops examples DO name these
+ // channels (they predate the lookout), and every digest must match there.
+ const docs = ["AGENTS.md", "plans/FACTS.md", "scripts/archilyzer-ops.mjs"];
+ const seen = new Set<string>();
+ for (const f of docs) {
+ for (const w of (await readFile(path.join(REPO, f), "utf8")).toLowerCase().match(/[a-z0-9]+/g) ?? []) {
+ const d = sha(w);
+ if (FORBIDDEN.has(d)) seen.add(d);
+ }
+ }
+ assert.deepEqual([...seen].sort(), [...FORBIDDEN].sort());
+});
+
+test("no lookout file names a channel of the pilot lookout", async () => {
+ const files = (await Promise.all(ROOTS.map((r) => lookoutFiles(path.join(REPO, r))))).flat();
+ assert.ok(files.length >= 6, `found the lookout's files (${files.length})`);
+ const hits: string[] = [];
+ for (const f of files) {
+ const words = new Set((await readFile(f, "utf8")).toLowerCase().match(/[a-z0-9]+/g) ?? []);
+ for (const w of words) if (FORBIDDEN.has(sha(w))) hits.push(path.relative(REPO, f));
+ }
+ assert.deepEqual(hits, []);
+});
diff --git a/common/lib/lookoutSettings.test.ts b/common/lib/lookoutSettings.test.ts
@@ -0,0 +1,78 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ DEFAULT_LOOKOUTS_SETTINGS,
+ lookoutById,
+ lookoutIdFrom,
+ sanitizeLookoutItem,
+ sanitizeLookouts,
+} from "./lookoutSettings";
+import { defaults, siteSettingsSchema } from "./settingsSchema";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/lookoutSettings.test.ts
+
+test("off and empty by default, in the schema too", () => {
+ assert.deepEqual(DEFAULT_LOOKOUTS_SETTINGS, { enabled: false, afterSync: false, items: [] });
+ assert.deepEqual(sanitizeLookouts(undefined), DEFAULT_LOOKOUTS_SETTINGS);
+ assert.deepEqual(defaults().lookouts, DEFAULT_LOOKOUTS_SETTINGS);
+ assert.deepEqual(siteSettingsSchema.parse({ lookouts: "nonsense" }).lookouts, DEFAULT_LOOKOUTS_SETTINGS);
+});
+
+test("an item gets every default it leaves out", () => {
+ assert.deepEqual(sanitizeLookoutItem({ id: "weekly", channels: ["example-news", "example-live"] }), {
+ id: "weekly",
+ label: "weekly",
+ channels: ["example-news", "example-live"],
+ days: 7,
+ prompt: "",
+ maxVideos: 40,
+ minSeconds: 90,
+ timeZone: "",
+ siteOrigin: "",
+ });
+});
+
+test("an item is coerced, never thrown on", () => {
+ const item = sanitizeLookoutItem({
+ label: " Example Week! ",
+ channels: ["example-news", "example-news", "", 7, "../escape", "ok.slug_1"],
+ days: 999,
+ maxVideos: "12",
+ minSeconds: -5,
+ timeZone: "Mars/Olympus",
+ siteOrigin: "https://example.pages.dev/some/path?q=1",
+ prompt: "x".repeat(5000),
+ });
+ assert.ok(item);
+ assert.equal(item.id, "example-week");
+ assert.equal(item.label, "Example Week!");
+ assert.deepEqual(item.channels, ["example-news", "ok.slug_1"]);
+ assert.equal(item.days, 60);
+ assert.equal(item.maxVideos, 12);
+ assert.equal(item.minSeconds, 0);
+ assert.equal(item.timeZone, "", "an unknown zone falls back to the machine's");
+ assert.equal(item.siteOrigin, "https://example.pages.dev");
+ assert.equal(item.prompt.length, 4000);
+ assert.equal(sanitizeLookoutItem({ timeZone: "America/Chicago", id: "a" })?.timeZone, "America/Chicago");
+ assert.equal(sanitizeLookoutItem({ siteOrigin: "ftp://x.example", id: "a" })?.siteOrigin, "");
+});
+
+test("an item with no usable id is dropped, and so is a second with the same id", () => {
+ const s = sanitizeLookouts({
+ enabled: true,
+ afterSync: "yes",
+ items: [{ channels: ["a"] }, { id: "one", channels: ["a"] }, { id: "one", channels: ["b"] }, "junk", { label: "Two" }],
+ });
+ assert.equal(s.enabled, true);
+ assert.equal(s.afterSync, false, "only true is true");
+ assert.deepEqual(s.items.map((i) => [i.id, i.channels]), [["one", ["a"]], ["two", []]]);
+ assert.equal(lookoutById(s, "two")?.label, "Two");
+ assert.equal(lookoutById(s, "three"), null);
+});
+
+test("lookoutIdFrom makes a slug", () => {
+ assert.equal(lookoutIdFrom("Café Weekly — News"), "cafe-weekly-news");
+ assert.equal(lookoutIdFrom("!!!"), "");
+ assert.equal(lookoutIdFrom("a".repeat(80)).length, 64);
+});
diff --git a/common/lib/lookoutSettings.ts b/common/lib/lookoutSettings.ts
@@ -0,0 +1,182 @@
+// settings.lookouts — saved lookouts (lane/lookout). A lookout is a saved set of
+// channels, a number of days back and an optional prompt; a run reads those
+// channels' recent transcripts and answers with video ideas. Pure: the types,
+// the defaults, the sanitizer settingsSchema.ts runs the block through, and the
+// per-field docs SETTINGS.md renders.
+//
+// OFF AND EMPTY BY DEFAULT, and no channel is named here or anywhere in code: a
+// lookout is configured on the machine that runs it (`pnpm ops settings`), so
+// adding one is a settings patch, never a code change.
+//
+// Slice 1 reads this for the selection only (controller/lookoutPlan.ts, the
+// `lookout-run` dry run); the model run, `afterSync` and the umtool page come in
+// later slices and read the same fields.
+
+import type { FieldDocs } from "./fieldDocs";
+
+export type LookoutItem = {
+ id: string;
+ label: string;
+ channels: string[];
+ days: number;
+ prompt: string;
+ maxVideos: number;
+ minSeconds: number;
+ timeZone: string;
+ siteOrigin: string;
+};
+
+export type LookoutsSettings = {
+ enabled: boolean;
+ afterSync: boolean;
+ items: LookoutItem[];
+};
+
+export const DEFAULT_LOOKOUTS_SETTINGS: LookoutsSettings = {
+ enabled: false,
+ afterSync: false,
+ items: [],
+};
+
+export const LOOKOUT_DEFAULT_DAYS = 7;
+export const LOOKOUT_MAX_DAYS = 60;
+export const LOOKOUT_DEFAULT_MAX_VIDEOS = 40;
+export const LOOKOUT_MAX_MAX_VIDEOS = 500;
+export const LOOKOUT_DEFAULT_MIN_SECONDS = 90;
+export const LOOKOUT_MAX_MIN_SECONDS = 3600;
+export const LOOKOUT_MAX_PROMPT_CHARS = 4000;
+
+// A lookout id is a path segment (`transcripts/.lookouts/<id>/`), so it is a
+// lowercase slug, nothing else.
+export const LOOKOUT_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
+// A channel slug as the channels tree names it (the citations' segment rule).
+const CHANNEL_SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
+
+export const LOOKOUTS_SETTINGS_FIELD_DOCS: FieldDocs<LookoutsSettings> = {
+ enabled:
+ "The lookouts' master switch. Off: no lookout runs, by hand or after a sync; a dry run " +
+ "(`pnpm ops lookout-run --json '{\"id\":\"…\",\"dryRun\":true}'`) still lists what a lookout would read, " +
+ "and writes nothing. Default false.",
+ afterSync:
+ "Run each lookout after a sync of one of its channels finishes — at most once a day per lookout, never while " +
+ "render mode holds the machine. Not acted on before the after-sync slice lands. Default false.",
+ items:
+ "The saved lookouts, one entry each (`lookouts.items[]` below). The list is replaced whole by a settings " +
+ "patch. Default [] — no lookout.",
+};
+
+export const LOOKOUT_ITEM_FIELD_DOCS: FieldDocs<LookoutItem> = {
+ id:
+ "The lookout's id: a lowercase slug (`a-z`, `0-9`, `-`, at most 64), the name its runs and verdicts are kept " +
+ "under (`transcripts/.lookouts/<id>/`). Omitted: made from `label`. An entry with neither is dropped, and so " +
+ "is a second entry with an id already used.",
+ label: "What the lookout is called on its page. Omitted: the id.",
+ channels:
+ "The channel slugs it reads (`transcripts/channels/<slug>/`). A local media library channel, or a slug this " +
+ "archive does not hold (a channel only on a remote site), is refused by name when the lookout runs.",
+ days:
+ "How many days back it reads, today included, by AIR date in `timeZone` (`release_timestamp`, else " +
+ "`timestamp`, from the video's metadata — not yt-dlp's UTC `upload_date`). Clamped to [1, 60]; default 7.",
+ prompt:
+ "What the operator wants from the ideas, added to the grouping step only — the per-video reading is the same " +
+ "for every lookout. At most 4000 characters; default \"\".",
+ maxVideos:
+ "The most recordings one run reads, after duplicate uploads and stream cut-downs are folded in: the longest " +
+ "first, and every one left out listed as skipped for the cap. Clamped to [1, 500]; default 40.",
+ minSeconds:
+ "Videos shorter than this are not read (and are counted as skipped). Clamped to [0, 3600]; default 90.",
+ timeZone:
+ "The IANA time zone its days are counted in (\"America/New_York\"). \"\" = the machine's. An unknown zone is " +
+ "dropped to \"\". Default \"\".",
+ siteOrigin:
+ "The public site its links are built on (\"https://example.pages.dev\"), when the channels are published; " +
+ "\"\" = each video's source URL with its start second. Default \"\".",
+};
+
+function clampInt(value: unknown, fallback: number, min: number, max: number): number {
+ const n = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : NaN;
+ if (!Number.isFinite(n)) return fallback;
+ return Math.min(max, Math.max(min, Math.round(n)));
+}
+
+/** Whether `tz` is an IANA zone this runtime knows. "" is not a zone (it means the machine's). */
+export function isKnownTimeZone(tz: string): boolean {
+ if (!tz) return false;
+ try {
+ new Intl.DateTimeFormat("en-US", { timeZone: tz });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** A lowercase slug made from free text: "My Lookout!" → "my-lookout". */
+export function lookoutIdFrom(text: string): string {
+ return text
+ .normalize("NFKD")
+ .replace(/[̀-ͯ]/g, "")
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 64)
+ .replace(/-+$/, "");
+}
+
+function siteOriginOf(value: unknown): string {
+ if (typeof value !== "string" || !value.trim()) return "";
+ try {
+ const u = new URL(value.trim());
+ if (u.protocol !== "https:" && u.protocol !== "http:") return "";
+ return u.origin;
+ } catch {
+ return "";
+ }
+}
+
+/** One entry, coerced; null when it has no usable id. */
+export function sanitizeLookoutItem(value: unknown): LookoutItem | null {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const r = value as Record<string, unknown>;
+ const rawId = typeof r.id === "string" ? r.id.trim() : "";
+ const rawLabel = typeof r.label === "string" ? r.label.trim() : "";
+ const id = LOOKOUT_ID_RE.test(rawId) ? rawId : lookoutIdFrom(rawId || rawLabel);
+ if (!LOOKOUT_ID_RE.test(id)) return null;
+ const channels: string[] = [];
+ if (Array.isArray(r.channels)) {
+ for (const c of r.channels) {
+ if (typeof c !== "string") continue;
+ const slug = c.trim();
+ if (slug && slug !== ".." && CHANNEL_SLUG_RE.test(slug) && !channels.includes(slug)) channels.push(slug);
+ }
+ }
+ const tz = typeof r.timeZone === "string" ? r.timeZone.trim() : "";
+ const prompt = typeof r.prompt === "string" ? r.prompt.trim().slice(0, LOOKOUT_MAX_PROMPT_CHARS) : "";
+ return {
+ id,
+ label: rawLabel || id,
+ channels,
+ days: clampInt(r.days, LOOKOUT_DEFAULT_DAYS, 1, LOOKOUT_MAX_DAYS),
+ prompt,
+ maxVideos: clampInt(r.maxVideos, LOOKOUT_DEFAULT_MAX_VIDEOS, 1, LOOKOUT_MAX_MAX_VIDEOS),
+ minSeconds: clampInt(r.minSeconds, LOOKOUT_DEFAULT_MIN_SECONDS, 0, LOOKOUT_MAX_MIN_SECONDS),
+ timeZone: isKnownTimeZone(tz) ? tz : "",
+ siteOrigin: siteOriginOf(r.siteOrigin),
+ };
+}
+
+export function sanitizeLookouts(value: unknown): LookoutsSettings {
+ const r = (value && typeof value === "object" && !Array.isArray(value) ? value : {}) as Record<string, unknown>;
+ const items: LookoutItem[] = [];
+ if (Array.isArray(r.items)) {
+ for (const raw of r.items) {
+ const item = sanitizeLookoutItem(raw);
+ if (item && !items.some((i) => i.id === item.id)) items.push(item);
+ }
+ }
+ return { enabled: r.enabled === true, afterSync: r.afterSync === true, items };
+}
+
+/** The saved lookout with this id, or null. */
+export function lookoutById(settings: LookoutsSettings, id: string): LookoutItem | null {
+ return settings.items.find((i) => i.id === id) ?? null;
+}
diff --git a/common/lib/lookoutStore.test.ts b/common/lib/lookoutStore.test.ts
@@ -0,0 +1,167 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, readdir, rm, writeFile, mkdir } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import {
+ LookoutStoreError,
+ ideaKey,
+ listLookoutRunIds,
+ lookoutReadout,
+ lookoutRunFile,
+ lookoutVerdictsFile,
+ lookoutsRoot,
+ measuredSecondsPerCall,
+ newLookoutRunId,
+ readLookoutRun,
+ readLookoutVerdicts,
+ sanitizeLookoutVerdicts,
+ setLookoutVerdict,
+ writeLookoutRun,
+ type LookoutIdea,
+ type LookoutRun,
+} from "./lookoutStore";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/lookoutStore.test.ts
+
+async function corpus() {
+ const transcriptsDir = await mkdtemp(path.join(os.tmpdir(), "lookout-store-"));
+ return { transcriptsDir };
+}
+
+const M = (channel: string, video: string, start: number) => ({ channel, video, start });
+
+test("an idea's key is its story: order-free, 5-second grain, changed by a moment added", () => {
+ const a = ideaKey([M("example-news", "v1", 100), M("example-live", "v2", 2000)]);
+ assert.match(a, /^[0-9a-f]{16}$/);
+ assert.equal(ideaKey([M("example-live", "v2", 2001), M("example-news", "v1", 99)]), a);
+ assert.notEqual(ideaKey([M("example-news", "v1", 100), M("example-live", "v2", 2010)]), a);
+ assert.notEqual(ideaKey([M("example-news", "v1", 100), M("example-live", "v2", 2000), M("example-news", "v3", 5)]), a);
+});
+
+test("the store is a dot path under the corpus, and ids are checked before any path is made", async () => {
+ const p = await corpus();
+ try {
+ assert.equal(lookoutsRoot(p), path.join(p.transcriptsDir, ".lookouts"));
+ assert.equal(lookoutVerdictsFile(p, "weekly"), path.join(p.transcriptsDir, ".lookouts", "weekly", "verdicts.json"));
+ assert.throws(() => lookoutVerdictsFile(p, "../escape"), LookoutStoreError);
+ assert.throws(() => lookoutRunFile(p, "weekly", "../x"), LookoutStoreError);
+ assert.match(newLookoutRunId(new Date("2026-11-11T17:45:00.123Z")), /^20261111T174500Z-[0-9a-f]{4}$/);
+ } finally {
+ await rm(p.transcriptsDir, { recursive: true, force: true });
+ }
+});
+
+test("a verdict is set atomically, keeps the note it had, and two at once both land", async () => {
+ const p = await corpus();
+ try {
+ const k1 = ideaKey([M("example-news", "v1", 10), M("example-news", "v2", 20)]);
+ const k2 = ideaKey([M("example-news", "v3", 10), M("example-news", "v4", 20)]);
+ const now = new Date("2026-11-11T12:00:00Z");
+ await setLookoutVerdict(p, "weekly", { key: k1, verdict: "maybe", note: " check the date ", now });
+ const made = await setLookoutVerdict(p, "weekly", { key: k1, verdict: "make", project: "shorts-2026-11/x", now });
+ assert.deepEqual(made, { verdict: "make", at: now.toISOString(), note: "check the date", project: "shorts-2026-11/x" });
+ await Promise.all([
+ setLookoutVerdict(p, "weekly", { key: k2, verdict: "no", now }),
+ setLookoutVerdict(p, "weekly", { key: k1, verdict: "make", note: "", now }),
+ ]);
+ const v = await readLookoutVerdicts(p, "weekly");
+ assert.equal(v.ideas[k2]?.verdict, "no");
+ assert.equal(v.ideas[k1]?.note, undefined, "an empty note clears it");
+ assert.equal(v.ideas[k1]?.project, "shorts-2026-11/x");
+ // No temp file left beside it.
+ assert.deepEqual(await readdir(path.dirname(lookoutVerdictsFile(p, "weekly"))), ["verdicts.json"]);
+ await assert.rejects(setLookoutVerdict(p, "weekly", { key: "nope", verdict: "make" }), LookoutStoreError);
+ await assert.rejects(
+ setLookoutVerdict(p, "weekly", { key: k1, verdict: "yes" as never }),
+ LookoutStoreError,
+ );
+ } finally {
+ await rm(p.transcriptsDir, { recursive: true, force: true });
+ }
+});
+
+test("a hand-damaged verdicts file reads as what is valid in it", async () => {
+ const k = ideaKey([M("a", "b", 0)]);
+ assert.deepEqual(
+ sanitizeLookoutVerdicts({ ideas: { [k]: { verdict: "make", at: "x" }, bad: { verdict: "make", at: "x" }, [k.replace(/^./, "f")]: { verdict: "meh", at: "x" } } }),
+ { version: 1, ideas: { [k]: { verdict: "make", at: "x" } } },
+ );
+ const p = await corpus();
+ try {
+ await mkdir(path.dirname(lookoutVerdictsFile(p, "weekly")), { recursive: true });
+ await writeFile(lookoutVerdictsFile(p, "weekly"), "{ not json");
+ assert.deepEqual(await readLookoutVerdicts(p, "weekly"), { version: 1, ideas: {} });
+ // ...and is never written over as if it were empty.
+ await assert.rejects(setLookoutVerdict(p, "weekly", { key: k, verdict: "make" }), /unparseable.*not written/);
+ assert.equal(await readFile(lookoutVerdictsFile(p, "weekly"), "utf8"), "{ not json");
+ } finally {
+ await rm(p.transcriptsDir, { recursive: true, force: true });
+ }
+});
+
+function idea(key: string): LookoutIdea {
+ return {
+ id: key.slice(0, 6),
+ key,
+ workingTitle: "t",
+ angle: "a",
+ whyNow: "w",
+ kind: "reversal",
+ estimatedLengthSec: 60,
+ confidence: "high",
+ confidenceWhy: "c",
+ moments: [],
+ caveats: [],
+ sensitive: false,
+ };
+}
+
+function run(runId: string, ideas: LookoutIdea[], calls = 0, seconds = 0): LookoutRun {
+ return {
+ version: 1,
+ lookoutId: "weekly",
+ runId,
+ startedAt: "2026-11-11T12:00:00.000Z",
+ endedAt: "2026-11-11T12:10:00.000Z",
+ status: "done",
+ window: { from: "2026-11-05", to: "2026-11-11", days: 7, timeZone: "UTC" },
+ model: "local-model",
+ calls,
+ seconds,
+ selection: null,
+ ideas,
+ };
+}
+
+test("runs: listed newest first, the latest summarised, unruled ideas counted, seconds per call measured", async () => {
+ const p = await corpus();
+ try {
+ assert.deepEqual(await lookoutReadout(p, "weekly"), {
+ lastRun: null,
+ runs: 0,
+ unruled: 0,
+ verdicts: { make: 0, maybe: 0, no: 0 },
+ });
+ assert.equal(await measuredSecondsPerCall(p, "weekly"), null);
+ const k1 = ideaKey([M("a", "b", 0), M("a", "c", 0)]);
+ const k2 = ideaKey([M("a", "d", 0), M("a", "e", 0)]);
+ await writeLookoutRun(p, run("20261110T120000Z-aaaa", [idea(k1)], 100, 400));
+ await writeLookoutRun(p, run("20261111T120000Z-bbbb", [idea(k1), idea(k2)], 50, 100));
+ await setLookoutVerdict(p, "weekly", { key: k1, verdict: "no" });
+ assert.deepEqual(await listLookoutRunIds(p, "weekly"), ["20261111T120000Z-bbbb", "20261110T120000Z-aaaa"]);
+ const r = await lookoutReadout(p, "weekly");
+ assert.equal(r.runs, 2);
+ assert.equal(r.lastRun?.runId, "20261111T120000Z-bbbb");
+ assert.equal(r.lastRun?.ideas, 2);
+ assert.equal(r.unruled, 1, "the story ruled in an earlier run keeps its verdict");
+ assert.deepEqual(r.verdicts, { make: 0, maybe: 0, no: 1 });
+ assert.deepEqual(await measuredSecondsPerCall(p, "weekly"), { secondsPerCall: 500 / 150, runs: 2, calls: 150 });
+ assert.equal(await readLookoutRun(p, "weekly", "20261109T120000Z-cccc"), null);
+ const text = await readFile(lookoutRunFile(p, "weekly", "20261111T120000Z-bbbb"), "utf8");
+ assert.equal(JSON.parse(text).ideas.length, 2);
+ } finally {
+ await rm(p.transcriptsDir, { recursive: true, force: true });
+ }
+});
diff --git a/common/lib/lookoutStore.ts b/common/lib/lookoutStore.ts
@@ -0,0 +1,371 @@
+// THE LOOKOUT STORE — a lookout's runs, ideas and verdicts on disk, and the one
+// writer of each (lane/lookout). SERVER-ONLY (node:fs).
+//
+// transcripts/.lookouts/<lookoutId>/runs/<runId>.json one run: window, selection, calls, ideas
+// transcripts/.lookouts/<lookoutId>/runs/<runId>.trace.jsonl its trace (slice 2)
+// transcripts/.lookouts/<lookoutId>/verdicts.json the operator's Make / Maybe / No per idea
+//
+// A DOT PATH, like the corpus root's other runtime state (.x-runs, .jobs,
+// .speakers-run.json): it is never a channel, a site or a report, so nothing
+// that composes, indexes, exports or serves the corpus walks into it, and the
+// corpus repo's own .gitignore question does not arise for a name nobody
+// enumerates. Nothing here is published (the lane's rule): a run's ideas carry
+// quotes from transcripts and the operator's notes on them.
+//
+// ONE WRITER PER FILE, atomic (jsonFile-server), in the manner of
+// curatedTagsStore: a verdict is a read-modify-write of the whole
+// verdicts.json under the file's lock, so two marks never interleave. A run
+// file is written whole by the job that made it and never edited after.
+//
+// A VERDICT IS KEYED BY THE IDEA'S STORY, not by the run: `ideaKey` hashes the
+// idea's moments (channel, video, start rounded to 5 s), so the same story
+// found by a later run keeps the verdict it was given.
+
+import { createHash, randomBytes } from "node:crypto";
+import { readdir } from "node:fs/promises";
+import path from "node:path";
+import type { Paths } from "./paths";
+import { LOOKOUT_ID_RE } from "./lookoutSettings";
+import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "./jsonFile-server";
+
+export const LOOKOUTS_DIRNAME = ".lookouts";
+export const LOOKOUT_VERDICTS_FILENAME = "verdicts.json";
+export const LOOKOUT_STORE_VERSION = 1;
+
+// `20261111T174500Z-1a2b`: sorts by time, safe as a file name.
+export const LOOKOUT_RUN_ID_RE = /^\d{8}T\d{6}Z-[0-9a-f]{4}$/;
+
+export class LookoutStoreError extends Error {}
+
+function assertLookoutId(id: string): void {
+ if (!LOOKOUT_ID_RE.test(id)) throw new LookoutStoreError(`"${id}" is not a lookout id (a lowercase slug)`);
+}
+
+function assertRunId(runId: string): void {
+ if (!LOOKOUT_RUN_ID_RE.test(runId)) throw new LookoutStoreError(`"${runId}" is not a lookout run id`);
+}
+
+export function lookoutsRoot(paths: Pick<Paths, "transcriptsDir">): string {
+ return path.join(paths.transcriptsDir, LOOKOUTS_DIRNAME);
+}
+
+export function lookoutDir(paths: Pick<Paths, "transcriptsDir">, id: string): string {
+ assertLookoutId(id);
+ return path.join(lookoutsRoot(paths), id);
+}
+
+export function lookoutRunFile(paths: Pick<Paths, "transcriptsDir">, id: string, runId: string): string {
+ assertRunId(runId);
+ return path.join(lookoutDir(paths, id), "runs", `${runId}.json`);
+}
+
+export function lookoutTraceFile(paths: Pick<Paths, "transcriptsDir">, id: string, runId: string): string {
+ assertRunId(runId);
+ return path.join(lookoutDir(paths, id), "runs", `${runId}.trace.jsonl`);
+}
+
+export function lookoutVerdictsFile(paths: Pick<Paths, "transcriptsDir">, id: string): string {
+ return path.join(lookoutDir(paths, id), LOOKOUT_VERDICTS_FILENAME);
+}
+
+export function newLookoutRunId(now: Date = new Date()): string {
+ const stamp = now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
+ return `${stamp}-${randomBytes(2).toString("hex")}`;
+}
+
+// ─── Ideas ───
+
+/** One dated, verbatim moment of an idea, located by code in its video's cues. */
+export type LookoutMoment = {
+ channel: string;
+ /** The video's directory under `channels/<channel>/data/`. */
+ video: string;
+ /** Its air date, YYYY-MM-DD in the lookout's zone. */
+ date: string;
+ start: number;
+ end: number;
+ quote: string;
+ link?: string;
+ title?: string;
+};
+
+export type LookoutVerdictValue = "make" | "maybe" | "no";
+
+/** An idea as a run stores it: the pilot's shape plus `key` and `sensitive`. */
+export type LookoutIdea = {
+ id: string;
+ key: string;
+ workingTitle: string;
+ angle: string;
+ whyNow: string;
+ kind: string;
+ estimatedLengthSec: number;
+ confidence: "high" | "medium" | "low";
+ confidenceWhy: string;
+ moments: LookoutMoment[];
+ caveats: string[];
+ sensitive: boolean;
+};
+
+/** Seconds rounded to the nearest 5, the grain a story's key is cut at. */
+const grain = (s: number) => Math.round(s / 5) * 5;
+
+/**
+ * The idea's story key: a hash of its sorted moments (channel, video, start
+ * rounded to 5 s). The same moments in any order give the same key; a moment
+ * nudged by a second or two gives the same key; a moment added or removed
+ * gives another.
+ */
+export function ideaKey(moments: readonly Pick<LookoutMoment, "channel" | "video" | "start">[]): string {
+ const parts = [...new Set(moments.map((m) => `${m.channel}/${m.video}@${grain(m.start)}`))].sort();
+ return createHash("sha1").update(parts.join("\n")).digest("hex").slice(0, 16);
+}
+
+// ─── Runs ───
+
+export type LookoutRunStatus = "done" | "partial" | "failed";
+
+/**
+ * A run as stored. Slice 1 defines the shape and reads it; the job that writes
+ * one (and fills `selection`, `calls`, `ideas`) is slice 2's.
+ */
+export type LookoutRun = {
+ version: number;
+ lookoutId: string;
+ runId: string;
+ startedAt: string;
+ endedAt: string | null;
+ status: LookoutRunStatus;
+ window: { from: string; to: string; days: number; timeZone: string };
+ model: string | null;
+ /** Model calls made. */
+ calls: number;
+ /** Wall seconds the model calls took, summed. */
+ seconds: number;
+ /** The selection as the dry run lists it (controller/lookoutPlan.ts LookoutPlan), read and skipped and why. */
+ selection: unknown;
+ ideas: LookoutIdea[];
+ /** What was dropped and why (an unlocatable quote, an invented id, a one-moment idea), counted. */
+ dropped?: Record<string, number>;
+ note?: string;
+};
+
+export type LookoutRunSummary = {
+ runId: string;
+ startedAt: string;
+ endedAt: string | null;
+ status: LookoutRunStatus;
+ window: LookoutRun["window"];
+ model: string | null;
+ calls: number;
+ seconds: number;
+ ideas: number;
+};
+
+function isObject(v: unknown): v is Record<string, unknown> {
+ return typeof v === "object" && v !== null && !Array.isArray(v);
+}
+
+/** Write a run whole (its job is the only writer, once). */
+export async function writeLookoutRun(paths: Pick<Paths, "transcriptsDir">, run: LookoutRun): Promise<string> {
+ const file = lookoutRunFile(paths, run.lookoutId, run.runId);
+ await writeJsonAtomic(file, run, { mkdir: true });
+ return file;
+}
+
+/** One run, or null when it is absent or not a run. */
+export async function readLookoutRun(
+ paths: Pick<Paths, "transcriptsDir">,
+ id: string,
+ runId: string,
+): Promise<LookoutRun | null> {
+ const read = await readJsonFile(lookoutRunFile(paths, id, runId));
+ if (!read.ok || !isObject(read.value)) return null;
+ const v = read.value;
+ if (v.lookoutId !== id || v.runId !== runId || !Array.isArray(v.ideas)) return null;
+ return v as unknown as LookoutRun;
+}
+
+/** The lookout's run ids, newest first. */
+export async function listLookoutRunIds(paths: Pick<Paths, "transcriptsDir">, id: string): Promise<string[]> {
+ let names: string[];
+ try {
+ names = await readdir(path.join(lookoutDir(paths, id), "runs"));
+ } catch {
+ return [];
+ }
+ return names
+ .filter((n) => n.endsWith(".json"))
+ .map((n) => n.slice(0, -".json".length))
+ .filter((n) => LOOKOUT_RUN_ID_RE.test(n))
+ .sort()
+ .reverse();
+}
+
+export function summarizeLookoutRun(run: LookoutRun): LookoutRunSummary {
+ return {
+ runId: run.runId,
+ startedAt: run.startedAt,
+ endedAt: run.endedAt,
+ status: run.status,
+ window: run.window,
+ model: run.model,
+ calls: run.calls,
+ seconds: run.seconds,
+ ideas: run.ideas.length,
+ };
+}
+
+/**
+ * Seconds per model call measured over the lookout's latest runs that made
+ * calls (at most `recent`), or null when none has. What a dry run's estimate
+ * is priced from.
+ */
+export async function measuredSecondsPerCall(
+ paths: Pick<Paths, "transcriptsDir">,
+ id: string,
+ recent = 3,
+): Promise<{ secondsPerCall: number; runs: number; calls: number } | null> {
+ let calls = 0;
+ let seconds = 0;
+ let runs = 0;
+ for (const runId of await listLookoutRunIds(paths, id)) {
+ if (runs >= recent) break;
+ const run = await readLookoutRun(paths, id, runId);
+ if (!run || !(run.calls > 0) || !(run.seconds > 0)) continue;
+ calls += run.calls;
+ seconds += run.seconds;
+ runs++;
+ }
+ return calls > 0 ? { secondsPerCall: seconds / calls, runs, calls } : null;
+}
+
+// ─── Verdicts ───
+
+export type LookoutVerdict = {
+ verdict: LookoutVerdictValue;
+ /** ISO 8601, when it was given. */
+ at: string;
+ note?: string;
+ /** The Shorts project "Make" opened, when it did. */
+ project?: string;
+};
+
+export type LookoutVerdicts = {
+ version: number;
+ /** Keyed by the idea's story key (`ideaKey`). */
+ ideas: Record<string, LookoutVerdict>;
+};
+
+const IDEA_KEY_RE = /^[0-9a-f]{16}$/;
+const VERDICTS: readonly LookoutVerdictValue[] = ["make", "maybe", "no"];
+
+export function isLookoutVerdict(v: unknown): v is LookoutVerdictValue {
+ return typeof v === "string" && (VERDICTS as readonly string[]).includes(v);
+}
+
+export function isIdeaKey(v: unknown): v is string {
+ return typeof v === "string" && IDEA_KEY_RE.test(v);
+}
+
+export function emptyLookoutVerdicts(): LookoutVerdicts {
+ return { version: LOOKOUT_STORE_VERSION, ideas: {} };
+}
+
+/** A verdicts file coerced: an ill-typed entry is dropped, never thrown on. */
+export function sanitizeLookoutVerdicts(value: unknown): LookoutVerdicts {
+ const out = emptyLookoutVerdicts();
+ const ideas = isObject(value) ? value.ideas : null;
+ if (!isObject(ideas)) return out;
+ for (const [key, raw] of Object.entries(ideas)) {
+ if (!isIdeaKey(key) || !isObject(raw) || !isLookoutVerdict(raw.verdict) || typeof raw.at !== "string") continue;
+ const v: LookoutVerdict = { verdict: raw.verdict, at: raw.at };
+ if (typeof raw.note === "string" && raw.note.trim()) v.note = raw.note.trim();
+ if (typeof raw.project === "string" && raw.project.trim()) v.project = raw.project.trim();
+ out.ideas[key] = v;
+ }
+ return out;
+}
+
+export async function readLookoutVerdicts(
+ paths: Pick<Paths, "transcriptsDir">,
+ id: string,
+): Promise<LookoutVerdicts> {
+ const read = await readJsonFile(lookoutVerdictsFile(paths, id));
+ return read.ok ? sanitizeLookoutVerdicts(read.value) : emptyLookoutVerdicts();
+}
+
+export type SetVerdictInput = {
+ key: string;
+ verdict: LookoutVerdictValue;
+ note?: string;
+ project?: string;
+ now?: Date;
+};
+
+/**
+ * THE writer of verdicts.json: one idea's verdict set (replacing the one it
+ * had), under the file's lock, written atomically. A note or project not sent
+ * is kept from the verdict before, so "Make" recording its project does not
+ * erase the operator's note. Refused when verdicts.json is there and is not
+ * readable JSON — it is never overwritten as if it were empty.
+ */
+export async function setLookoutVerdict(
+ paths: Pick<Paths, "transcriptsDir">,
+ id: string,
+ input: SetVerdictInput,
+): Promise<LookoutVerdict> {
+ if (!isIdeaKey(input.key)) throw new LookoutStoreError(`"${input.key}" is not an idea key`);
+ if (!isLookoutVerdict(input.verdict)) throw new LookoutStoreError(`verdict is one of ${VERDICTS.join(", ")}`);
+ const file = lookoutVerdictsFile(paths, id);
+ return withJsonFileLock(file, async () => {
+ // A file that is there and cannot be read is NOT an empty one: writing over
+ // it would drop every verdict it holds for the one being set.
+ const read = await readJsonFile(file);
+ if (!read.ok && read.reason !== "absent") {
+ throw new LookoutStoreError(
+ `${file} is ${read.reason} — the verdict was not written; mend the file or move it aside first`,
+ );
+ }
+ const current = read.ok ? sanitizeLookoutVerdicts(read.value) : emptyLookoutVerdicts();
+ const before = current.ideas[input.key];
+ const v: LookoutVerdict = { verdict: input.verdict, at: (input.now ?? new Date()).toISOString() };
+ const note = input.note !== undefined ? input.note.trim() : before?.note;
+ if (note) v.note = note;
+ const project = input.project !== undefined ? input.project.trim() : before?.project;
+ if (project) v.project = project;
+ current.ideas[input.key] = v;
+ await writeJsonAtomic(file, current, { mkdir: true });
+ return v;
+ });
+}
+
+// ─── The readout (`pnpm ops get lookouts`) ───
+
+export type LookoutReadout = {
+ lastRun: LookoutRunSummary | null;
+ runs: number;
+ /** Ideas in the latest run with no verdict yet. */
+ unruled: number;
+ verdicts: Record<LookoutVerdictValue, number>;
+};
+
+/** What the store holds for one lookout: its runs, the latest one, and how many of its ideas wait for a verdict. */
+export async function lookoutReadout(paths: Pick<Paths, "transcriptsDir">, id: string): Promise<LookoutReadout> {
+ const runIds = await listLookoutRunIds(paths, id);
+ const verdicts = await readLookoutVerdicts(paths, id);
+ const counts: Record<LookoutVerdictValue, number> = { make: 0, maybe: 0, no: 0 };
+ for (const v of Object.values(verdicts.ideas)) counts[v.verdict]++;
+ let latest: LookoutRun | null = null;
+ for (const runId of runIds) {
+ latest = await readLookoutRun(paths, id, runId);
+ if (latest) break;
+ }
+ const unruled = latest ? latest.ideas.filter((i) => !verdicts.ideas[i.key]).length : 0;
+ return {
+ lastRun: latest ? summarizeLookoutRun(latest) : null,
+ runs: runIds.length,
+ unruled,
+ verdicts: counts,
+ };
+}
diff --git a/common/lib/paths.ts b/common/lib/paths.ts
@@ -373,3 +373,11 @@ function findMonorepoRoot(): string {
}
return start;
}
+
+// The FULL per-channel transcript trees, local recordings included, written
+// beside the shared (public-safe) ones only for a channel that holds a local
+// recording, and copied into PRIVATE-audience sites only (lib/localMedia.ts
+// isLocalRecord; controller/buildIndex.ts, bin/compose-site.ts).
+export function sharedPrivateTranscriptsDir(paths: Pick<Paths, "exportSharedDir">): string {
+ return path.join(paths.exportSharedDir, "private", "transcripts");
+}
diff --git a/common/lib/platform.ts b/common/lib/platform.ts
@@ -3,6 +3,7 @@
// cached entries, so no transcriptStore.ts DB_VERSION bump is needed. Posts get
// their own IDB store rather than sharing the transcript cache.
export type Platform =
+ | "local" // A source-less recording, never detected from a provider URL.
| "youtube"
| "rumble"
| "odysee"
@@ -23,6 +24,7 @@ export type Platform =
| "webpage";
export const PLATFORM_VALUES: ReadonlyArray<Platform> = [
+ "local",
"youtube",
"rumble",
"odysee",
@@ -66,6 +68,7 @@ export { detectPlatform, sameXenforoForum };
// Odysee the canonical id is only the claim hash (the channel-name prefix is
// dropped by extractVideoId), so a reconstructed Odysee URL may not resolve.
export function defaultWebpageUrl(platform: Platform, id: string): string {
+ if (platform === "local") return "";
if (platform === "rumble") return `https://rumble.com/${id}`;
if (platform === "odysee") return `https://odysee.com/${id}`;
if (platform === "twitch") return `https://www.twitch.tv/videos/${id}`;
diff --git a/common/lib/projectsRoot.mjs b/common/lib/projectsRoot.mjs
@@ -0,0 +1,37 @@
+// WHERE AN ARTICLE'S VIDEO PROJECTS LIVE when settings.generation.projectsRoot
+// is blank: `<REPORTS_DIR>/articles` when REPORTS_DIR is set — a container
+// sets it to its reports volume (/data/reports, Dockerfile), so a fresh
+// container's projects land on the volume and not in its writable layer —
+// else `~/reports/articles`, the host default since release 27 S6 (demo epic
+// D1 item 3; D0 found a container's projects outside the reports volume).
+//
+// Plain JS (with JSDoc) so umtool's plain-node chain planner
+// (umtool/lib/report/chain.mjs) reads the same rule as the editor's TS.
+
+import os from "node:os";
+import path from "node:path";
+
+/**
+ * @param {Record<string, string | undefined>} [env]
+ * @returns {string}
+ */
+export function defaultProjectsRoot(env = process.env) {
+ const reports = env.REPORTS_DIR?.trim();
+ if (reports) return path.join(path.resolve(/* turbopackIgnore: true */ reports), "articles");
+ return path.join(/* turbopackIgnore: true */ os.homedir(), "reports", "articles");
+}
+
+/** `~` and `~/` expanded against the home directory. */
+export function expandHomeDir(p) {
+ return p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p;
+}
+
+/**
+ * The projects root a settings value names: `~` expanded; blank = the default.
+ * @param {unknown} configured settings.generation.projectsRoot
+ * @param {Record<string, string | undefined>} [env]
+ */
+export function projectsRootFrom(configured, env = process.env) {
+ if (typeof configured !== "string" || !configured.trim()) return defaultProjectsRoot(env);
+ return expandHomeDir(configured.trim());
+}
diff --git a/common/lib/remoteArchives-server.ts b/common/lib/remoteArchives-server.ts
@@ -0,0 +1,264 @@
+// THE REMOTE-ARCHIVE RESOLVER's network half (./remoteArchives.ts is the pure
+// one): what a published archive says about itself, read from its
+// `/corpus.json` — the title, the totals and the channels the Connect form
+// shows before anything is saved.
+//
+// One request per probe, sequential, never in a loop. The fetch is injectable
+// (every test passes a fake; no test calls a real site).
+
+import { archiveOriginOf, sameOrigin } from "./remoteArchives";
+import { corpusUrl, manifestUrl, pageUrl } from "./archive/contract";
+import { detectPlatform } from "./detectPlatform.mjs";
+
+export type FetchLike = (url: string, init?: { signal?: AbortSignal; headers?: Record<string, string> }) => Promise<Response>;
+
+export type ArchiveProbeChannel = {
+ slug: string;
+ name: string;
+ videoCount: number | null;
+ // Spec 6 (corpus.json carries them); absent from an older archive's entry.
+ platform?: string;
+ url?: string;
+};
+
+export type ArchiveProbe = {
+ origin: string;
+ // corpus.json's own: site.id, site.title, spec, generatedAt.
+ siteId: string | null;
+ title: string;
+ description: string;
+ spec: number | null;
+ generatedAt: string | null;
+ totals: { channels: number; videos: number };
+ channels: ArchiveProbeChannel[];
+};
+
+export class ArchiveProbeError extends Error {
+ constructor(
+ message: string,
+ readonly status = 400,
+ ) {
+ super(message);
+ this.name = "ArchiveProbeError";
+ }
+}
+
+const PROBE_TIMEOUT_MS = 15_000;
+const MAX_REDIRECTS = 3;
+
+// The largest archive document read (demo epic D1 review follow-up): a shard
+// page is up to 8 MB; anything past 32 MB is refused, not buffered.
+export const MAX_ARCHIVE_DOCUMENT_BYTES = 32 * 1024 * 1024;
+
+export class OversizeError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "OversizeError";
+ }
+}
+
+/** A response's body as text, refused past `max` bytes (by its Content-Length, then as it streams). */
+export async function readBounded(res: Response, url: string, max = MAX_ARCHIVE_DOCUMENT_BYTES): Promise<string> {
+ const declared = Number(res.headers.get("content-length"));
+ const over = () => new OversizeError(`${url} is over ${Math.round(max / 1024 / 1024)} MB: an archive document that large is not read`);
+ if (Number.isFinite(declared) && declared > max) {
+ await res.body?.cancel().catch(() => {});
+ throw over();
+ }
+ if (!res.body) return "";
+ const reader = res.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > max) {
+ await reader.cancel().catch(() => {});
+ throw over();
+ }
+ chunks.push(value);
+ }
+ return Buffer.concat(chunks).toString("utf8");
+}
+
+export class OffOriginError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "OffOriginError";
+ }
+}
+
+/**
+ * A GET that stays on `url`'s own origin (demo epic D1 review, blocker 2): a
+ * redirect is followed (up to three) only to the same scheme, host and port;
+ * one that leaves it is refused before it is followed. An archive is someone
+ * else's server, and nothing it answers may send this machine elsewhere.
+ */
+export async function fetchOnOrigin(doFetch: FetchLike, url: string, init: { signal?: AbortSignal; headers?: Record<string, string> } = {}): Promise<Response> {
+ let at = url;
+ for (let hop = 0; ; hop++) {
+ const res = await doFetch(at, { ...init, redirect: "manual" } as never);
+ if (res.status < 300 || res.status > 399 || res.status === 304) return res;
+ const location = res.headers.get("location");
+ if (!location) return res;
+ const next = new URL(location, at).href;
+ if (!sameOrigin(next, url)) throw new OffOriginError(`${at} redirects to ${new URL(next).origin}: an archive's documents are read from its own origin only`);
+ if (hop >= MAX_REDIRECTS) throw new OffOriginError(`${url} redirects more than ${MAX_REDIRECTS} times`);
+ at = next;
+ }
+}
+
+const str = (v: unknown): string | null => (typeof v === "string" && v.trim() ? v.trim() : null);
+const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
+
+/**
+ * Read `<origin>/corpus.json` and say what the archive is. Refused, with a
+ * sentence: not an origin, unreachable, not JSON, a federation hub (connect
+ * one of its sites), a cited-only site (it publishes reports, no corpus), or
+ * a site listing no channels.
+ */
+export async function probeArchive(rawOrigin: string, opts: { fetch?: FetchLike; timeoutMs?: number } = {}): Promise<ArchiveProbe> {
+ const origin = archiveOriginOf(rawOrigin);
+ if (!origin) throw new ArchiveProbeError(`"${rawOrigin}" is not an archive's address — type its origin, e.g. https://jeralyzer.pages.dev`);
+ const doFetch = opts.fetch ?? (fetch as unknown as FetchLike);
+ const url = `${origin}/corpus.json`;
+ let res: Response;
+ try {
+ res = await fetchOnOrigin(doFetch, url, { signal: AbortSignal.timeout(opts.timeoutMs ?? PROBE_TIMEOUT_MS), headers: { accept: "application/json" } });
+ } catch (e) {
+ if (e instanceof OffOriginError) throw new ArchiveProbeError(e.message, 502);
+ throw new ArchiveProbeError(`${url} did not answer: ${(e as Error).message}`, 502);
+ }
+ if (!res.ok) throw new ArchiveProbeError(`${url} answered HTTP ${res.status} — is ${origin} a published archive?`, 502);
+ let j: Record<string, unknown>;
+ try {
+ j = JSON.parse(await readBounded(res, url)) as Record<string, unknown>;
+ } catch (e) {
+ if (e instanceof OversizeError) throw new ArchiveProbeError(e.message, 502);
+ throw new ArchiveProbeError(`${url} is not JSON — ${origin} does not serve an archive's contract`, 502);
+ }
+ if (!j || typeof j !== "object" || Array.isArray(j)) throw new ArchiveProbeError(`${url} is not an archive's corpus.json`, 502);
+ if (j.kind === "hub" || Array.isArray(j.sites)) {
+ const sites = Array.isArray(j.sites) ? (j.sites as Record<string, unknown>[]) : [];
+ const names = sites
+ .map((s) => str(s?.url))
+ .filter((u): u is string => !!u)
+ .slice(0, 6);
+ throw new ArchiveProbeError(
+ `${origin} is a federation hub of ${sites.length} site(s), not one archive — connect one of its sites${names.length ? `: ${names.join(", ")}` : ""}`,
+ );
+ }
+ const site = (j.site && typeof j.site === "object" ? j.site : {}) as Record<string, unknown>;
+ if (site.scope === "cited") {
+ throw new ArchiveProbeError(`${origin} publishes only its reports and the moments they cite — it has no corpus to search`);
+ }
+ const rawChannels = Array.isArray(j.channels) ? (j.channels as Record<string, unknown>[]) : [];
+ const channels: ArchiveProbeChannel[] = [];
+ for (const c of rawChannels) {
+ const slug = str(c?.slug);
+ if (!slug) continue;
+ const platform = str(c.platform);
+ const curl = str(c.url);
+ channels.push({
+ slug,
+ name: str(c.name) ?? slug,
+ videoCount: num(c.videoCount),
+ ...(platform ? { platform } : {}),
+ ...(curl ? { url: curl } : {}),
+ });
+ }
+ if (channels.length === 0) throw new ArchiveProbeError(`${origin}'s corpus.json lists no channels — there is nothing to search`);
+ const totals = (j.totals && typeof j.totals === "object" ? j.totals : {}) as Record<string, unknown>;
+ return {
+ origin,
+ siteId: str(site.id),
+ title: str(site.title) ?? origin.replace(/^https?:\/\//, ""),
+ description: str(site.description) ?? "",
+ spec: num(j.spec),
+ generatedAt: str(j.generatedAt),
+ totals: {
+ channels: num(totals.channels) ?? channels.length,
+ videos: num(totals.videos) ?? channels.reduce((n, c) => n + (c.videoCount ?? 0), 0),
+ },
+ channels,
+ };
+}
+
+// ─── A channel's facts: where it is (demo epic D1 item 4) ───
+
+export type ArchiveChannelFacts = {
+ slug: string;
+ name: string;
+ // The platform its recordings are on, or null when the archive does not say
+ // and no record names one.
+ platform: string | null;
+ // Its page on that platform (corpus.json spec 6), or null.
+ url: string | null;
+ // Where the facts came from: corpus.json's channel entry (spec 6), the
+ // channel's first shard record (an older archive), or nowhere.
+ from: "corpus" | "record" | "none";
+ // A record's own page (the fallback's evidence), when one was read.
+ sampleVideoUrl?: string;
+};
+
+export class ArchiveChannelError extends Error {
+ constructor(
+ message: string,
+ readonly status = 404,
+ ) {
+ super(message);
+ this.name = "ArchiveChannelError";
+ }
+}
+
+// One JSON document over HTTP: a throw on anything but a 200. Injectable as
+// `getJson` so the cached reader (item 6) is the one every lookup goes through.
+export type GetJson = (url: string) => Promise<unknown>;
+
+export function plainGetJson(doFetch: FetchLike = fetch as unknown as FetchLike): GetJson {
+ return async (url) => {
+ const res = await fetchOnOrigin(doFetch, url, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS), headers: { accept: "application/json" } });
+ if (!res.ok) throw new ArchiveChannelError(`${url} answered HTTP ${res.status}`, res.status === 404 ? 404 : 502);
+ return JSON.parse(await readBounded(res, url));
+ };
+}
+
+/**
+ * Where an archive's channel is: corpus.json's `platform` and `url` (spec 6);
+ * for an OLDER archive whose entry has no platform, the channel's first shard
+ * record — the transcripts manifest's lowest page, its first record with a
+ * `webpageUrl` — gives the platform (the record's own, else its page's host).
+ * Sequential: at most three documents, one after another. A slug the archive
+ * does not list is refused.
+ */
+export async function archiveChannelFacts(origin: string, slug: string, opts: { getJson?: GetJson; fetch?: FetchLike } = {}): Promise<ArchiveChannelFacts> {
+ const base = archiveOriginOf(origin);
+ if (!base) throw new ArchiveChannelError(`"${origin}" is not an archive's address`, 400);
+ const getJson = opts.getJson ?? plainGetJson(opts.fetch);
+ const corpus = (await getJson(corpusUrl(base))) as { channels?: Record<string, unknown>[] } | null;
+ const entry = (Array.isArray(corpus?.channels) ? corpus!.channels : []).find((c) => c?.slug === slug);
+ if (!entry) throw new ArchiveChannelError(`${base} lists no channel "${slug}"`);
+ const name = str(entry.name) ?? slug;
+ const platform = str(entry.platform);
+ const url = str(entry.url);
+ if (platform) return { slug, name, platform, url: url && /^https?:\/\//i.test(url) ? url : null, from: "corpus" };
+ // An older archive: the first record's page.
+ const manifests = (entry.manifests && typeof entry.manifests === "object" ? entry.manifests : {}) as Record<string, unknown>;
+ // Only the archive's own origin is read: a manifest the corpus names elsewhere is not followed.
+ const named = str(manifests.transcripts);
+ const manifestAt = named && sameOrigin(named, base) ? named : manifestUrl("transcripts", slug, base);
+ const manifest = (await getJson(manifestAt).catch(() => null)) as { slugToPage?: Record<string, unknown> } | null;
+ const pages = Object.values(manifest?.slugToPage ?? {}).filter((n): n is number => typeof n === "number" && Number.isInteger(n) && n >= 0);
+ if (pages.length > 0) {
+ const first = Math.min(...pages);
+ const records = (await getJson(pageUrl("transcripts", slug, first, base)).catch(() => null)) as Record<string, unknown>[] | null;
+ for (const r of Array.isArray(records) ? records : []) {
+ const page = str(r?.webpageUrl);
+ if (!page) continue;
+ const p = str(r.platform) ?? detectPlatform(page);
+ return { slug, name, platform: p, url: url && /^https?:\/\//i.test(url) ? url : null, from: p ? "record" : "none", sampleVideoUrl: page };
+ }
+ }
+ return { slug, name, platform: null, url: url && /^https?:\/\//i.test(url) ? url : null, from: "none" };
+}
diff --git a/common/lib/remoteArchives.test.ts b/common/lib/remoteArchives.test.ts
@@ -0,0 +1,165 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ archiveHandle,
+ archiveOriginOf,
+ connectedArchives,
+ findConnectedArchive,
+ freeArchiveId,
+ originOfHandle,
+ sanitizeRemoteArchives,
+} from "./remoteArchives";
+import { ArchiveChannelError, ArchiveProbeError, archiveChannelFacts, probeArchive, type FetchLike } from "./remoteArchives-server";
+import { defaults } from "./settingsSchema";
+
+test("an archive origin is normalized: https assumed, trailing slash and /corpus.json dropped", () => {
+ assert.equal(archiveOriginOf("jeralyzer.pages.dev"), "https://jeralyzer.pages.dev");
+ assert.equal(archiveOriginOf(" https://Jeralyzer.pages.dev/ "), "https://jeralyzer.pages.dev");
+ assert.equal(archiveOriginOf("https://x.test/corpus.json"), "https://x.test");
+ assert.equal(archiveOriginOf("http://127.0.0.1:4100/arch/"), "http://127.0.0.1:4100/arch");
+ for (const bad of ["", "ftp://x.test", "https://u:p@x.test", "https://x.test/?q=1", "https://x.test/#a", 7, null]) {
+ assert.equal(archiveOriginOf(bad), null, String(bad));
+ }
+});
+
+test("a handle names its archive and back", () => {
+ assert.equal(archiveHandle("https://a.test"), "remote:https://a.test");
+ assert.equal(originOfHandle("remote:https://a.test/"), "https://a.test");
+ assert.equal(originOfHandle("local:/x"), null);
+ assert.equal(originOfHandle(undefined), null);
+});
+
+test("ids: the archive's own site id when free, else from the host, made unique", () => {
+ assert.equal(freeArchiveId("https://jeralyzer.pages.dev", [], "jeralyzer"), "jeralyzer");
+ assert.equal(freeArchiveId("https://jeralyzer.pages.dev", ["jeralyzer"], "jeralyzer"), "jeralyzer-2");
+ assert.equal(freeArchiveId("https://jeralyzer.pages.dev", [], null), "jeralyzer-pages-dev");
+ assert.equal(freeArchiveId("https://jeralyzer.pages.dev", [], "Not A Slug"), "jeralyzer-pages-dev");
+});
+
+test("the stored list is sanitized: bad entries and later duplicates dropped", () => {
+ const out = sanitizeRemoteArchives([
+ { id: "a", origin: "https://a.test/", title: "A", addedAt: "2026-11-11T00:00:00Z" },
+ { id: "b", origin: "https://a.test" }, // same origin
+ { id: "a", origin: "https://other.test" }, // same id
+ { id: "BAD", origin: "https://c.test" },
+ { id: "d", origin: "not a url at all ::" },
+ "junk",
+ { id: "e", origin: "https://e.test" },
+ ]);
+ assert.deepEqual(out, [
+ { id: "a", origin: "https://a.test", title: "A", addedAt: "2026-11-11T00:00:00.000Z" },
+ { id: "e", origin: "https://e.test", title: "e.test", addedAt: "1970-01-01T00:00:00.000Z" },
+ ]);
+ assert.deepEqual(sanitizeRemoteArchives({ not: "an array" }), []);
+ assert.deepEqual(defaults().remoteArchives, []);
+});
+
+test("TRANSCRIPT_SITE_URL is the default archive, listed but never stored, and not twice", () => {
+ const none = connectedArchives([], {});
+ assert.deepEqual(none, []);
+ const env = connectedArchives([], { TRANSCRIPT_SITE_URL: "https://jeralyzer.pages.dev/" });
+ assert.equal(env.length, 1);
+ assert.equal(env[0].origin, "https://jeralyzer.pages.dev");
+ assert.equal(env[0].fromEnv, true);
+ const stored = connectedArchives([{ id: "jeralyzer", origin: "https://jeralyzer.pages.dev", title: "Jeralyzer", addedAt: "2026-11-11T00:00:00Z" }], {
+ TRANSCRIPT_SITE_URL: "https://jeralyzer.pages.dev",
+ });
+ assert.equal(stored.length, 1);
+ assert.equal(stored[0].fromEnv, undefined);
+ assert.equal(findConnectedArchive(stored, "jeralyzer.pages.dev/")?.id, "jeralyzer");
+ assert.equal(findConnectedArchive(stored, "https://elsewhere.test"), null);
+});
+
+// ─── probeArchive, against a fake fetch only ───
+
+const respond = (body: unknown, status = 200): Response =>
+ new Response(typeof body === "string" ? body : JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
+
+function fakeFetch(map: Record<string, () => Response>): FetchLike & { asked: string[] } {
+ const asked: string[] = [];
+ const f = (async (url: string) => {
+ asked.push(url);
+ const r = map[url];
+ if (!r) return respond({ error: "nope" }, 404);
+ return r();
+ }) as FetchLike & { asked: string[] };
+ f.asked = asked;
+ return f;
+}
+
+const CORPUS = {
+ spec: 6,
+ kind: "site",
+ generatedAt: "2026-11-08T08:26:37.854Z",
+ site: { id: "stubalyzer", title: "Stubalyzer", description: "A stub", url: "https://stub.test" },
+ totals: { channels: 2, videos: 30 },
+ channels: [
+ { slug: "alpha", name: "Alpha", videoCount: 20, platform: "youtube", url: "https://www.youtube.com/@alpha", manifests: {} },
+ { slug: "beta", name: "Beta", videoCount: 10, manifests: {} },
+ ],
+};
+
+test("a probe reads corpus.json once and says what the archive holds", async () => {
+ const f = fakeFetch({ "https://stub.test/corpus.json": () => respond(CORPUS) });
+ const p = await probeArchive("stub.test/", { fetch: f });
+ assert.deepEqual(f.asked, ["https://stub.test/corpus.json"]);
+ assert.equal(p.origin, "https://stub.test");
+ assert.equal(p.siteId, "stubalyzer");
+ assert.equal(p.title, "Stubalyzer");
+ assert.equal(p.spec, 6);
+ assert.deepEqual(p.totals, { channels: 2, videos: 30 });
+ assert.deepEqual(p.channels, [
+ { slug: "alpha", name: "Alpha", videoCount: 20, platform: "youtube", url: "https://www.youtube.com/@alpha" },
+ { slug: "beta", name: "Beta", videoCount: 10 },
+ ]);
+});
+
+test("a probe refuses what is not one searchable archive, with a sentence", async () => {
+ const cases: [string, () => Response, RegExp][] = [
+ ["https://a.test/corpus.json", () => respond("<html>", 200), /is not JSON/],
+ ["https://b.test/corpus.json", () => respond({}, 500), /answered HTTP 500/],
+ ["https://c.test/corpus.json", () => respond({ kind: "hub", sites: [{ url: "https://m1.test" }] }), /federation hub of 1 site.*https:\/\/m1\.test/],
+ ["https://d.test/corpus.json", () => respond({ ...CORPUS, site: { scope: "cited" }, channels: [] }), /publishes only its reports/],
+ ["https://e.test/corpus.json", () => respond({ ...CORPUS, channels: [] }), /lists no channels/],
+ ];
+ for (const [url, r, re] of cases) {
+ await assert.rejects(probeArchive(url.replace("/corpus.json", ""), { fetch: fakeFetch({ [url]: r }) }), (e: unknown) => e instanceof ArchiveProbeError && re.test((e as Error).message));
+ }
+ await assert.rejects(probeArchive("ftp://x", { fetch: fakeFetch({}) }), /not an archive's address/);
+ const down = (async () => {
+ throw new Error("ECONNREFUSED");
+ }) as FetchLike;
+ await assert.rejects(probeArchive("https://f.test", { fetch: down }), /did not answer: ECONNREFUSED/);
+});
+
+// ─── archiveChannelFacts (item 4): where a channel is, from corpus.json or its first record ───
+
+test("a spec-6 archive names a channel's platform and page in corpus.json: one read", async () => {
+ const f = fakeFetch({ "https://stub.test/corpus.json": () => respond(CORPUS) });
+ const facts = await archiveChannelFacts("https://stub.test", "alpha", { fetch: f });
+ assert.deepEqual(facts, { slug: "alpha", name: "Alpha", platform: "youtube", url: "https://www.youtube.com/@alpha", from: "corpus" });
+ assert.deepEqual(f.asked, ["https://stub.test/corpus.json"]);
+});
+
+test("an older archive: the platform from the first shard's record, read in order, the lowest page", async () => {
+ const f = fakeFetch({
+ "https://stub.test/corpus.json": () => respond({ ...CORPUS, spec: 5 }),
+ "https://stub.test/transcripts/beta/manifest.json": () => respond({ pageCount: 3, slugToPage: { v9: 2, v1: 1, v2: 1 } }),
+ "https://stub.test/transcripts/beta/page-0001.json": () =>
+ respond([{ id: "v1", title: "no url" }, { id: "v2", webpageUrl: "https://rumble.com/v2-x.html" }]),
+ });
+ const facts = await archiveChannelFacts("https://stub.test", "beta", { fetch: f });
+ assert.deepEqual(facts, { slug: "beta", name: "Beta", platform: "rumble", url: null, from: "record", sampleVideoUrl: "https://rumble.com/v2-x.html" });
+ assert.deepEqual(f.asked, [
+ "https://stub.test/corpus.json",
+ "https://stub.test/transcripts/beta/manifest.json",
+ "https://stub.test/transcripts/beta/page-0001.json",
+ ]);
+});
+
+test("a channel the archive does not list is refused; one with no readable record is unknown", async () => {
+ const f = fakeFetch({ "https://stub.test/corpus.json": () => respond({ ...CORPUS, spec: 5 }) });
+ await assert.rejects(archiveChannelFacts("https://stub.test", "nope", { fetch: f }), (e: unknown) => e instanceof ArchiveChannelError && /lists no channel "nope"/.test((e as Error).message));
+ const facts = await archiveChannelFacts("https://stub.test", "beta", { fetch: f });
+ assert.deepEqual(facts, { slug: "beta", name: "Beta", platform: null, url: null, from: "none" });
+});
diff --git a/common/lib/remoteArchives.ts b/common/lib/remoteArchives.ts
@@ -0,0 +1,288 @@
+// settings.remoteArchives — the PUBLISHED ARCHIVES this machine reads as
+// sources (demo epic D1: "a public archive is a first-class source").
+//
+// A published archive is any origin serving the machine contract at
+// `/corpus.json` (common/lib/corpus.ts): jeralyzer.pages.dev, or a friend's.
+// Connecting one is the operator typing its origin once; from then on the
+// editor's Create form, umtool's Source chip and the MCP all offer it, its
+// sweeps cite it, and its clip windows are fetched for its channels — with no
+// local corpus and no site.json made by hand.
+//
+// THE ONE RESOLVER. This module is the pure half (the shape, the sanitizer, the
+// origin rule, the env default); remoteArchives-server.ts reads corpus.json and
+// a channel's facts over HTTP. The editor (settings + its ops action), umtool's
+// source picker (umtool/lib/research/sources.ts) and the MCP's list_sources all
+// list archives through `connectedArchives`, so the three never disagree about
+// what is connected.
+//
+// NOT `settings.archives`: that key was taken first, by the page-import sources
+// (archive.today, release 37 lane F — lib/archives/settings.ts).
+//
+// Pure, browser-safe: no node:* import.
+
+import type { FieldDocs } from "./fieldDocs";
+
+export type RemoteArchive = {
+ // A slug, unique among the connected archives: the archive's own site id
+ // when its corpus.json names one, else made from its host.
+ id: string;
+ // The archive's origin, normalized (archiveOriginOf): http(s), no trailing
+ // slash, no query or fragment. `<origin>/corpus.json` is its contract.
+ origin: string;
+ // What its corpus.json calls it (site.title) when it was connected.
+ title: string;
+ // When it was connected, ISO-8601.
+ addedAt: string;
+};
+
+// A connected archive as the pickers list it: the stored ones, then the one the
+// environment names (TRANSCRIPT_SITE_URL) when no stored entry has its origin.
+export type ConnectedArchive = RemoteArchive & {
+ // From TRANSCRIPT_SITE_URL, not settings.json: listed, never written, and
+ // gone when the variable is.
+ fromEnv?: true;
+};
+
+export const REMOTE_ARCHIVE_FIELD_DOCS: FieldDocs<RemoteArchive> = {
+ id:
+ "A slug, unique among the connected archives: the archive's own `site.id` from its corpus.json when that is " +
+ "free, else one made from its host. What `pnpm ops archives` removes by.",
+ origin:
+ "The archive's origin: an http(s) URL with no trailing slash, query or fragment, where `/corpus.json` is " +
+ "served. Sweeps over it cite it (`remote:<origin>`), whatever `generation.citationOrigin` says.",
+ title: "The archive's `site.title`, as its corpus.json said when it was connected.",
+ addedAt: "When it was connected (ISO-8601).",
+};
+
+const ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
+
+/** Whether `v` is an archive id (a lowercase slug, at most 64 characters). */
+export function isArchiveId(v: unknown): v is string {
+ return typeof v === "string" && ID_RE.test(v);
+}
+
+/**
+ * An archive origin, normalized — `https://host[/path]` with no trailing
+ * slash — or null when `v` is not one: not http(s), carries credentials, a
+ * query or a fragment, or does not parse. A path is kept (an archive may be
+ * served under one); `/corpus.json` typed on the end is taken off.
+ */
+export function archiveOriginOf(v: unknown): string | null {
+ if (typeof v !== "string") return null;
+ let s = v.trim();
+ if (!s) return null;
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) s = `https://${s}`;
+ let u: URL;
+ try {
+ u = new URL(s);
+ } catch {
+ return null;
+ }
+ if (u.protocol !== "https:" && u.protocol !== "http:") return null;
+ if (u.username || u.password || u.search || u.hash || !u.hostname) return null;
+ const p = u.pathname.replace(/\/corpus\.json$/i, "").replace(/\/+$/, "");
+ return `${u.protocol}//${u.host}${p}`;
+}
+
+/** The source handle a sweep over an archive names (mcp/src/sourceRegistry.ts). */
+export function archiveHandle(origin: string): string {
+ return `remote:${origin}`;
+}
+
+/** The origin a `remote:<origin>` handle names, normalized, or null for any other handle. */
+export function originOfHandle(handle: string | null | undefined): string | null {
+ const m = /^remote:(.+)$/s.exec(handle?.trim() ?? "");
+ return m ? archiveOriginOf(m[1]) : null;
+}
+
+/** A slug for an archive from its host (and path): `jeralyzer.pages.dev` → `jeralyzer-pages-dev`. */
+export function archiveIdFromOrigin(origin: string): string {
+ const bare = origin.replace(/^https?:\/\//, "").toLowerCase();
+ const slug = bare.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64).replace(/-+$/, "");
+ return slug && ID_RE.test(slug) ? slug : "archive";
+}
+
+/**
+ * The id a newly connected archive gets: `preferred` (its corpus.json's site
+ * id) when that is a free slug, else one from its origin, made unique with a
+ * numeric suffix.
+ */
+export function freeArchiveId(origin: string, taken: Iterable<string>, preferred?: string | null): string {
+ const used = new Set(taken);
+ const base = preferred && ID_RE.test(preferred) ? preferred : archiveIdFromOrigin(origin);
+ if (!used.has(base)) return base;
+ for (let n = 2; ; n++) {
+ const id = `${base.slice(0, 60)}-${n}`;
+ if (!used.has(id)) return id;
+ }
+}
+
+/**
+ * settings.json's `remoteArchives`, sanitized: an array of entries each with a
+ * valid id and origin; a later duplicate (same origin or id) is dropped; a
+ * missing title becomes the origin's host, a missing date the epoch. Total over
+ * `unknown` (the settings reader never throws).
+ */
+export function sanitizeRemoteArchives(v: unknown): RemoteArchive[] {
+ if (!Array.isArray(v)) return [];
+ const out: RemoteArchive[] = [];
+ const ids = new Set<string>();
+ const origins = new Set<string>();
+ for (const raw of v) {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
+ const r = raw as Record<string, unknown>;
+ const origin = archiveOriginOf(r.origin);
+ if (!origin || origins.has(origin)) continue;
+ const id = isArchiveId(r.id) ? r.id : null;
+ if (!id || ids.has(id)) continue;
+ const title = typeof r.title === "string" && r.title.trim() ? r.title.trim().slice(0, 200) : origin.replace(/^https?:\/\//, "");
+ const addedAt =
+ typeof r.addedAt === "string" && !Number.isNaN(Date.parse(r.addedAt)) ? new Date(r.addedAt).toISOString() : new Date(0).toISOString();
+ ids.add(id);
+ origins.add(origin);
+ out.push({ id, origin, title, addedAt });
+ }
+ return out;
+}
+
+type Env = Record<string, string | undefined>;
+
+/**
+ * Every connected archive, as the pickers list them: the stored ones in order,
+ * then — when it names an origin no stored entry has — TRANSCRIPT_SITE_URL's
+ * (the MCP's own remote, AGENTS.md "Working this repo with no local corpus"),
+ * marked `fromEnv`. That is the default a fresh clone gets: one archive, from
+ * the variable it was told to set.
+ */
+export function connectedArchives(stored: unknown, env: Env = typeof process !== "undefined" ? (process.env as Env) : {}): ConnectedArchive[] {
+ const list: ConnectedArchive[] = sanitizeRemoteArchives(stored);
+ const fromEnv = archiveOriginOf(env.TRANSCRIPT_SITE_URL);
+ if (fromEnv && !list.some((a) => a.origin === fromEnv)) {
+ list.push({
+ id: freeArchiveId(fromEnv, list.map((a) => a.id)),
+ origin: fromEnv,
+ title: fromEnv.replace(/^https?:\/\//, ""),
+ addedAt: new Date(0).toISOString(),
+ fromEnv: true,
+ });
+ }
+ return list;
+}
+
+/** The connected archive at `origin` (normalized first), or null. */
+export function findConnectedArchive(list: readonly ConnectedArchive[], origin: string | null | undefined): ConnectedArchive | null {
+ const want = archiveOriginOf(origin);
+ return want ? (list.find((a) => a.origin === want) ?? null) : null;
+}
+
+/**
+ * Why a remote-only channel's archive is not read any more, or null: the
+ * origin its config names (`remoteArchive`) is no longer among the connected
+ * archives — removed from settings since the channel was registered. Its
+ * record is not asked for and no window is fetched for it (demo epic D1
+ * re-review, item 6).
+ */
+export function disconnectedArchiveRefusal(origin: string | null | undefined, list: readonly ConnectedArchive[]): string | null {
+ if (!origin) return null;
+ if (findConnectedArchive(list, origin)) return null;
+ return `its archive ${origin} is no longer connected — connect it again (the editor's /sites, "Connected archives") to fetch its windows`;
+}
+
+/**
+ * The marker a remote-only channel's whole-recording refusal starts with
+ * (controller/remoteOnlyChannel.ts wholeRecordingRefusal): umtool's chain
+ * looks for it to offer the one-press override (`allowWholeRecording`).
+ */
+export const WHOLE_RECORDING_REFUSED = "whole recording refused:";
+
+// ─── An archive is untrusted input (demo epic D1 review, blocker 2) ───
+
+// The platforms a clip window of an archive's channel may be fetched from:
+// the video platforms, each recognised by its HOST (lib/detectPlatform.mjs).
+// Never the post platforms, and never xenforo, which is recognised by a
+// thread path on any host.
+export const RECORD_PAGE_PLATFORMS = ["youtube", "rumble", "odysee", "twitch", "kick", "archiveorg", "bitchute"] as const;
+
+// Each platform's own domains, matched EXACTLY or as a parent (`host === d` or
+// `host` ends in `.d`). lib/detectPlatform.mjs answers "which platform is
+// this", loosely (`host.endsWith("youtube.com")` is true of evilyoutube.com);
+// here the question is "may this machine fetch from that host", so the answer
+// it gives is checked against this table (demo epic D1 re-review, must-fix 1).
+export const RECORD_PAGE_HOSTS: Record<(typeof RECORD_PAGE_PLATFORMS)[number], readonly string[]> = {
+ youtube: ["youtube.com", "youtu.be"],
+ rumble: ["rumble.com"],
+ odysee: ["odysee.com"],
+ twitch: ["twitch.tv"],
+ kick: ["kick.com"],
+ archiveorg: ["archive.org"],
+ bitchute: ["bitchute.com"],
+};
+
+/** Whether `host` is one of `platform`'s own domains or a subdomain of one. */
+export function isPlatformHost(platform: string, host: string): boolean {
+ const domains = (RECORD_PAGE_HOSTS as Record<string, readonly string[] | undefined>)[platform];
+ const h = host.toLowerCase().replace(/\.$/, "");
+ return !!domains && domains.some((d) => h === d || h.endsWith(`.${d}`));
+}
+
+// A page URL is refused when it carries a backslash, whitespace or a control
+// character ANYWHERE — before it is parsed. URL parsers disagree about exactly
+// these: Node reads `https://youtube.com\@evil.example/` as host youtube.com
+// (a backslash is a slash to it), Python's urlsplit — what yt-dlp reads it
+// with — as host evil.example; Node drops a tab or newline inside a host and
+// trims the ends. So the host judged here would not be the host fetched
+// (demo epic D1 re-check, the parser differential).
+const UNSAFE_PAGE_CHARS = /[\\\s\u0000-\u001f\u007f-\u009f\u00a0\u1680\u2000-\u200f\u2028-\u202f\u205f-\u2060\u3000\ufeff]/;
+
+export type RecordPage = { href: string; platform: string } | { refused: string };
+
+/**
+ * A remote-only channel's page URL — an archive record's `webpageUrl`, or one
+ * an ask carried for it — judged, and NORMALISED: `{href, platform}` when a
+ * window may be fetched from it, `{refused}` with the sentence when not. The
+ * archive is someone else's JSON: a URL is accepted only when it has no
+ * backslash, whitespace or control character, is http(s) with no credentials,
+ * its host names a known video platform, and that is the channel's own
+ * platform when the channel has one. Refused before any request.
+ *
+ * `href` is what the parser that judged the host wrote back (`new URL().href`:
+ * the host lowercased, a default port dropped, an IDN in punycode), and it is
+ * THE ONLY string a caller hands on — never the one it was given.
+ */
+export function recordPage(url: string | null | undefined, channelPlatform: string | null | undefined, detect: (u: string) => string | null): RecordPage {
+ if (!url) return { refused: "no page URL" };
+ if (UNSAFE_PAGE_CHARS.test(url)) {
+ return { refused: `${JSON.stringify(url)} is not a page URL: it carries a backslash, whitespace or a control character, which URL parsers read differently — the archive's page URL is not fetched` };
+ }
+ let u: URL;
+ try {
+ u = new URL(url);
+ } catch {
+ return { refused: `"${url}" is not a page URL` };
+ }
+ if ((u.protocol !== "https:" && u.protocol !== "http:") || u.username || u.password) return { refused: `${u.protocol}//${u.host} is not a page URL a window is fetched from` };
+ const href = u.href;
+ const platform = detect(href);
+ if (!platform || !(RECORD_PAGE_PLATFORMS as readonly string[]).includes(platform) || !isPlatformHost(platform, u.hostname)) {
+ return { refused: `${u.host} is not a video platform's host (${RECORD_PAGE_PLATFORMS.join(", ")}): the archive's page URL is not fetched` };
+ }
+ if (channelPlatform && channelPlatform !== platform) {
+ return { refused: `${u.host} is ${platform}, and the channel is ${channelPlatform}'s: the archive's page URL is not fetched` };
+ }
+ return { href, platform };
+}
+
+/** Why a remote-only channel's page URL is not fetched, or null when it may be (recordPage's sentence). */
+export function recordPageRefusal(url: string | null | undefined, channelPlatform: string | null | undefined, detect: (u: string) => string | null): string | null {
+ const page = recordPage(url, channelPlatform, detect);
+ return "refused" in page ? page.refused : null;
+}
+
+/** Whether `url` is on `origin`'s own scheme, host and port. */
+export function sameOrigin(url: string, origin: string): boolean {
+ try {
+ return new URL(url).origin === new URL(origin).origin;
+ } catch {
+ return false;
+ }
+}
diff --git a/common/lib/report/draft/refresh/fetch.ts b/common/lib/report/draft/refresh/fetch.ts
@@ -30,7 +30,9 @@ export type RefreshHooks = {
editor: ResearchEditor;
jobOf: JobOf;
// A channel of this editor: what it is and on which platform; null: none.
- channelOf: (slug: string) => Promise<{ kind: "video" | "posts"; platform?: string } | null>;
+ // `localLibrary`: a local media library channel (a library, no URL) —
+ // nothing online to sync, so its sync is a routine skip.
+ channelOf: (slug: string) => Promise<{ kind: "video" | "posts"; platform?: string; localLibrary?: true } | null>;
// Why a fetch on this platform would be refused now (held, cooling down), or null.
platformRefusal?: (platform: string) => Promise<string | null>;
// A channel's "downloaded, not transcribed" recordings (its report's bucket), or null.
@@ -169,6 +171,7 @@ export async function fetchAndBuild(
const fetchChannel = async (slug: string): Promise<FetchStep[]> => {
const ch = await hooks.channelOf(slug).catch(() => null);
if (!ch) return [skip(slug, "sync", "not a channel of this editor")];
+ if (ch.localLibrary) return [skip(slug, "sync", "a local media library: nothing online to sync", true)];
const first = ch.kind === "posts" ? "fetch-posts" : "sync";
if (ch.platform && hooks.platformRefusal) {
const no = await hooks.platformRefusal(ch.platform).catch(() => null);
diff --git a/common/lib/report/draft/refresh/refresh.test.ts b/common/lib/report/draft/refresh/refresh.test.ts
@@ -536,3 +536,21 @@ test("R4.1 fetch: transcription held — transcribe-bucket is skipped and said (
assert.ok(r.warnings.some((w) => /^gone: sync cancelled — the job ended cancelled$/.test(w)), JSON.stringify(r.warnings));
assert.ok(!r.warnings.some((w) => /nothing new to transcribe/.test(w)));
});
+
+// lane/local-media: a local media library channel has nothing online to sync —
+// a routine skip, no job and no warning (it used to be a refused sync).
+test("fetch: a local media library channel's sync is a routine skip, not a refused job", async () => {
+ const calls: Call[] = [];
+ const hooks = {
+ editor: { async run(action: string, args: Record<string, unknown>) { calls.push({ action, args }); return { ok: true, jobId: "j" }; } },
+ jobOf: async () => ({ status: "done", endedAt: Date.now() }),
+ channelOf: async () => ({ kind: "video" as const, localLibrary: true as const }),
+ siteOf: async () => ({ site: null, reason: "no build" }),
+ pollMs: 1,
+ sleep: async () => {},
+ };
+ const r = await fetchAndBuild({ channels: ["library"] }, hooks);
+ assert.deepEqual(calls, []);
+ assert.deepEqual(r.fetch, [{ channel: "library", action: "sync", status: "skipped", reason: "a local media library: nothing online to sync", routine: true }]);
+ assert.deepEqual(r.warnings, []);
+});
diff --git a/common/lib/report/iterations.test.ts b/common/lib/report/iterations.test.ts
@@ -29,6 +29,7 @@ import {
iterationDir,
iterationUsd,
lineage,
+ lineageSource,
listIterations,
makeCurrent,
parseIteration,
@@ -282,3 +283,19 @@ test("an article may not be called `new` (umtool's /articles/new is a page)", as
/reserved/,
);
});
+
+// demo epic D1: a sweep over a published archive records it; its revisions read it.
+test("a sweep's source is kept in its scope and inherited down its lineage", async () => {
+ const paths = store();
+ await createIteration("arc", { kind: "sweep", model: "m", question: "q", scope: { channels: ["alpha"], source: "remote:https://stub.test" } }, paths, NOW);
+ await done(paths, "arc", 1, doc("arc"));
+ await createIteration("arc", { kind: "revise-report", model: "m", parent: 1, feedback: "tighter" }, paths, NOW);
+ assert.equal(await lineageSource("arc", 2, paths), "remote:https://stub.test");
+ assert.equal((await readIteration("arc", 1, paths))?.scope?.source, "remote:https://stub.test");
+ // A sweep of the editor's own build has none.
+ await createIteration("own", { kind: "sweep", model: "m", question: "q", scope: { channels: ["alpha"] } }, paths, NOW);
+ assert.equal(await lineageSource("own", 1, paths), null);
+ assert.equal(await lineageSource("nope", 1, paths), null);
+ // Not a handle: refused at the schema.
+ await assert.rejects(createIteration("bad", { kind: "sweep", model: "m", question: "q", scope: { channels: ["alpha"], source: "https://stub.test" } }, paths, NOW));
+});
diff --git a/common/lib/report/iterations.ts b/common/lib/report/iterations.ts
@@ -141,6 +141,10 @@ export const iterationScopeSchema = z.looseObject({
ids: z.array(z.string().min(1)).optional(),
// The triage run this sweep escalates (umtool R6): reports/.triage/<owner>/<k>/.
triage: z.looseObject({ owner: z.string().min(1), k: z.number().int().positive() }).optional(),
+ // The corpus the sweep read when it was not the editor's own build (demo epic
+ // D1): a handle, `remote:<archive origin>` or `hub:<url>`. Its revisions,
+ // media drafts and video chain read and cite the same one (lineageSource).
+ source: z.string().regex(/^(local|remote|hub):\S+/).optional(),
});
export type IterationScope = z.infer<typeof iterationScopeSchema>;
@@ -377,6 +381,19 @@ export async function lineage(id: string, n: number, paths: StorePaths = getPath
return out;
}
+// The corpus handle an iteration's lineage read (demo epic D1): the newest
+// `scope.source` from n back to its root, or null — the editor's own build.
+export async function lineageSource(id: string, n: number, paths: StorePaths = getPaths()): Promise<string | null> {
+ let at: number | null = n;
+ while (at !== null) {
+ const it: Iteration | null = await readIteration(id, at, paths);
+ if (!it) return null;
+ if (it.scope?.source) return it.scope.source;
+ at = it.parent;
+ }
+ return null;
+}
+
// A file of an iteration as text, or null when it has none.
export async function readIterationFile(
id: string,
diff --git a/common/lib/search/evalTree.test.ts b/common/lib/search/evalTree.test.ts
@@ -393,3 +393,14 @@ test("a transcripts leaf reads the record's alternate tracks; a hit only one hol
],
);
});
+
+// lane/local-media (review B2): an undated record — a local recording with no
+// recording date, uploadDate "" — is outside every bounded date range, from-
+// only and to-only alike, and inside an unbounded one.
+test("passesFilters: an undated record is outside any bounded date range", () => {
+ const rec = { uploadDate: "", isLivestream: false, ageRestricted: false };
+ assert.equal(passesFilters(rec, openFilters(), undefined), true);
+ assert.equal(passesFilters(rec, openFilters({ dateFrom: "20250101" }), undefined), false);
+ assert.equal(passesFilters(rec, openFilters({ dateTo: "20251231" }), undefined), false);
+ assert.equal(passesFilters(rec, openFilters({ dateFrom: "20250101", dateTo: "20251231" }), undefined), false);
+});
diff --git a/common/lib/search/evalTree.ts b/common/lib/search/evalTree.ts
@@ -364,7 +364,10 @@ export function passesFilters(
if (rec.ageRestricted ? !f.restricted : !f.allAges) return false;
// fav — presence on the source platform
if (!f.states.has(avail?.state ?? "available")) return false;
- // fdf / fdt — upload-date range (lexicographic on YYYYMMDD)
+ // fdf / fdt — upload-date range (lexicographic on YYYYMMDD). An undated
+ // record (an undated local recording, "") is outside ANY bounded range — not
+ // only a from-bounded one, which "" < from alone would make it.
+ if ((f.dateFrom || f.dateTo) && !rec.uploadDate) return false;
if (f.dateFrom && rec.uploadDate < f.dateFrom) return false;
if (f.dateTo && rec.uploadDate > f.dateTo) return false;
// tg — curated tags. OR across the selection (a video tagged either
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -15,6 +15,8 @@ import {
ARCHIVES_SETTINGS_FIELD_DOCS,
CLIPS_SETTINGS_FIELD_DOCS,
JOBS_SETTINGS_FIELD_DOCS,
+ LOOKOUTS_SETTINGS_FIELD_DOCS,
+ LOOKOUT_ITEM_FIELD_DOCS,
SERVICE_COOKIES_SETTINGS_FIELD_DOCS,
VOICE_CONVERT_SETTINGS_FIELD_DOCS,
VOICE_ENHANCE_SETTINGS_FIELD_DOCS,
@@ -46,6 +48,7 @@ import {
GENERATION_VERDICT_BAR_FIELD_DOCS,
GENERATION_VERDICT_WINDOW_FIELD_DOCS,
SOCIAL_LINK_FIELD_DOCS,
+ REMOTE_ARCHIVE_FIELD_DOCS,
SOCIAL_SETTINGS_FIELD_DOCS,
X_SOCIAL_SETTINGS_FIELD_DOCS,
XENFORO_SOCIAL_SETTINGS_FIELD_DOCS,
@@ -216,6 +219,7 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
{ path: "social.xenforo", docs: XENFORO_SOCIAL_SETTINGS_FIELD_DOCS },
],
socialLinks: [{ path: "socialLinks[]", docs: SOCIAL_LINK_FIELD_DOCS }],
+ remoteArchives: [{ path: "remoteArchives[]", docs: REMOTE_ARCHIVE_FIELD_DOCS }],
savedVideoBackup: [
{
path: "savedVideoBackup",
@@ -358,6 +362,14 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
defaults: fromObject(d.serviceCookies),
},
],
+ lookouts: [
+ {
+ path: "lookouts",
+ docs: LOOKOUTS_SETTINGS_FIELD_DOCS,
+ defaults: fromObject(d.lookouts),
+ },
+ { path: "lookouts.items[]", docs: LOOKOUT_ITEM_FIELD_DOCS },
+ ],
};
}
diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts
@@ -33,9 +33,11 @@ import type { ArchiveOrgFetchSettings } from "./archiveOrgTorrent";
import type { SeederSettings } from "./seederSettings";
import type { TtsSettings } from "./ttsSettings";
import type { ArchivesSettings } from "./archives/settings";
+import type { RemoteArchive } from "./remoteArchives";
import type { ClipsSettings } from "./clipSettings";
import type { JobsSettings } from "./jobsSettings";
import type { ServiceCookiesSettings } from "./serviceCookieSettings";
+import type { LookoutsSettings } from "./lookoutSettings";
import type { VoiceSettings } from "./voiceSettings";
import type { GenerationSettings } from "./generationSettings";
import type {
@@ -114,6 +116,8 @@ type PreSchemaSiteSettings = {
// How archive.org files are fetched: BitTorrent with seeding, else direct.
archiveOrg: ArchiveOrgFetchSettings;
archives: ArchivesSettings;
+ // The connected published archives (demo epic D1).
+ remoteArchives: RemoteArchive[];
// The publish lane (release 18).
publish: PublishSettings;
// The recurring reports' lane (umtool R5).
@@ -132,13 +136,15 @@ type PreSchemaSiteSettings = {
jobs: JobsSettings;
// The cookie refresh alerts' proactive timer (2026-10-31).
serviceCookies: ServiceCookiesSettings;
+ // Saved lookouts (lane/lookout).
+ lookouts: LookoutsSettings;
};
// Bracketed so the conditional does not distribute (see commit 8c43231).
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true;
-test("SiteSettings keeps its 46 fields, in file order", () => {
+test("SiteSettings keeps its 47 fields, in file order", () => {
assert.equal(shapeUnchanged, true);
assert.deepEqual(Object.keys(siteSettingsSchema.shape), [
"adminTitle",
@@ -178,6 +184,7 @@ test("SiteSettings keeps its 46 fields, in file order", () => {
"attribution",
"archiveOrg",
"archives",
+ "remoteArchives",
"publish",
"reportSchedule",
"seeder",
@@ -187,6 +194,7 @@ test("SiteSettings keeps its 46 fields, in file order", () => {
"clips",
"jobs",
"serviceCookies",
+ "lookouts",
]);
// A parsed object carries every key, in that order — writeSettings writes
// exactly this, so the order is the on-disk order.
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -82,8 +82,10 @@ export { SEEDER_SETTINGS_FIELD_DOCS, type SeederSettings } from "./seederSetting
import { sanitizeTts, type TtsSettings } from "./ttsSettings";
import { sanitizeVoice, type VoiceSettings } from "./voiceSettings";
import { sanitizeArchives, type ArchivesSettings } from "./archives/settings";
+import { sanitizeRemoteArchives, type RemoteArchive } from "./remoteArchives";
import { sanitizeClips, type ClipsSettings } from "./clipSettings";
import { sanitizeJobs, type JobsSettings } from "./jobsSettings";
+import { sanitizeLookouts, type LookoutsSettings } from "./lookoutSettings";
import { sanitizeServiceCookies, type ServiceCookiesSettings } from "./serviceCookieSettings";
import { sanitizeGeneration, type GenerationSettings } from "./generationSettings";
export {
@@ -109,8 +111,10 @@ export {
type VoiceSettings,
} from "./voiceSettings";
export { ARCHIVES_SETTINGS_FIELD_DOCS, type ArchivesSettings } from "./archives/settings";
+export { REMOTE_ARCHIVE_FIELD_DOCS, type RemoteArchive } from "./remoteArchives";
export { CLIPS_SETTINGS_FIELD_DOCS, type ClipsSettings } from "./clipSettings";
export { JOBS_SETTINGS_FIELD_DOCS, type JobsSettings } from "./jobsSettings";
+export { LOOKOUTS_SETTINGS_FIELD_DOCS, LOOKOUT_ITEM_FIELD_DOCS, type LookoutsSettings, type LookoutItem } from "./lookoutSettings";
export { SERVICE_COOKIES_SETTINGS_FIELD_DOCS, type ServiceCookiesSettings } from "./serviceCookieSettings";
import {
DEFAULT_COOKIE_MODE,
@@ -2044,6 +2048,9 @@ export const siteSettingsSchema = z.object({
archives: settingsField((v): ArchivesSettings => sanitizeArchives(v)).describe(
"The archive sources a page import reads besides the Wayback Machine (release 37 lane F, lib/archives/): archive.today's one canonical host, its pace (one request at a time, a long gap, a rest after a 429) and whether a check it answers with is read once more through the archive session's headless browser. The Wayback Machine keeps archive.org's own client and pace. See ArchivesSettings.",
),
+ remoteArchives: settingsField((v): RemoteArchive[] => sanitizeRemoteArchives(v)).describe(
+ "The PUBLISHED ARCHIVES this machine reads as sources (demo epic D1, lib/remoteArchives.ts): each a site serving `/corpus.json`, connected once by its origin (the editor's /sites → Connect an archive, umtool's Source chip, or `pnpm ops archives`). Create, research and the MCP offer each one; a sweep over one cites that origin; a clip window cited from one registers a REMOTE-ONLY channel (CHANNEL.md `remoteOnly`) to fetch it. TRANSCRIPT_SITE_URL, when set and not listed here, is offered too without being written. Empty = none. See RemoteArchive.",
+ ),
publish: settingsField((v): PublishSettings => sanitizePublish(v)).describe(
"The publish LANE (release 18): a runner that, when the index is stale, updates it and then builds — and, where a site's own `publish.auto` (site.json) says so, deploys — what changed, one stage at a time on the `publish` queue. OFF by default; the manual stages (Publish now, Build, Deploy) work either way. See PublishSettings and common/publish/publishRunner.ts.",
),
@@ -2071,6 +2078,9 @@ export const siteSettingsSchema = z.object({
serviceCookies: settingsField((v): ServiceCookiesSettings => sanitizeServiceCookies(v)).describe(
"The cookie refresh alerts' PROACTIVE timer (plans/cookie-refresh-alerts.md): how often the editor rechecks raised alerts, probes Rumble's clearance with no alert up, and re-reads X's cookie jar age, by itself — so the dashboard banner goes up before a sync or a download fails. See ServiceCookiesSettings and common/controller/serviceCookieTimer.ts.",
),
+ lookouts: settingsField((v): LookoutsSettings => sanitizeLookouts(v)).describe(
+ "Saved lookouts (lane/lookout): each names channels, a number of days back and an optional prompt, and a run reads those channels' recent transcripts — by air date, duplicate uploads and stream cut-downs folded in — and answers with video ideas. OFF and empty by default; nothing a lookout writes is published. `pnpm ops get lookouts` is the readout, `pnpm ops lookout-run --json '{\"id\":\"…\",\"dryRun\":true}'` lists what one would read. See LookoutsSettings and common/lib/lookoutSettings.ts.",
+ ),
});
export type SiteSettings = z.infer<typeof siteSettingsSchema>;
diff --git a/common/lib/sidecar-server.test.ts b/common/lib/sidecar-server.test.ts
@@ -6,6 +6,7 @@ import path from "node:path";
import { SIDECAR_FILENAMES, sidecar, sidecarField } from "./sidecar-server";
import { SUB_FILE_RE } from "./videoStatus";
// Every sidecar module, so the enumeration below sees every declaration.
+import "./externalMedia-server";
import "./archiveOrg-server";
import "./audioIntegrity-server";
import "./attribution-server";
@@ -62,6 +63,7 @@ test("every declared sidecar filename escapes SUB_FILE_RE, and all eighteen are
"do-not-clean.json",
"download-outcome.json",
"exclude-truncated-check.json",
+ "external-media.json",
"find-clips.json",
"frame-scan.poker.json",
"metadata.history.json",
diff --git a/common/lib/site.ts b/common/lib/site.ts
@@ -11,7 +11,7 @@ import {
type SocialLink,
} from "./settings";
import { socialLinksForSave } from "./socialLinks";
-import { parseChannelConfig } from "./channelConfig";
+import { isRemoteOnlyChannel, parseChannelConfig } from "./channelConfig";
import { isXSearchChannel } from "./xSearch/config";
import { readJsonFileSync, withJsonFileLock, writeJsonAtomic } from "./jsonFile-server";
import {
@@ -231,6 +231,25 @@ function storedSocialLinks(file: string): SocialLink[] {
export const X_SEARCH_NOT_ON_A_SITE = (slug: string) =>
`${slug} is an X search channel: it is never put on a site.`;
+export const REMOTE_ONLY_NOT_ON_A_SITE = (slug: string) =>
+ `${slug} is a remote-only channel (a connected archive's clip windows): it is never put on a site.`;
+
+// The first member of `site` (or of its cited scope) that is a remote-only
+// channel (demo epic D1), by its config.json — or null.
+export function remoteOnlyChannelOnSite(
+ site: Pick<Site, "channels" | "citedChannels">,
+ paths: Paths,
+): string | null {
+ if (!paths.channelsDir) return null;
+ const slugs = [...site.channels.map((c) => c.slug), ...(site.citedChannels ?? []).map((c) => c.slug)];
+ for (const slug of slugs) {
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug)) continue;
+ const raw = readJsonFileSync(path.join(paths.channelsDir, slug, "config.json"));
+ if (raw.ok && isRemoteOnlyChannel(parseChannelConfig(raw.value))) return slug;
+ }
+ return null;
+}
+
// The first member of `site` (or of its cited scope) that is an X search
// channel, by its config.json — or null. One small read per member.
export function xSearchChannelOnSite(
@@ -278,6 +297,9 @@ export async function writeSite(
// the one writer every site edit goes through.
const searchChannel = xSearchChannelOnSite(site, paths);
if (searchChannel) throw new Error(X_SEARCH_NOT_ON_A_SITE(searchChannel));
+ // Nor a remote-only channel (demo epic D1): it has no corpus to publish.
+ const remoteOnly = remoteOnlyChannelOnSite(site, paths);
+ if (remoteOnly) throw new Error(REMOTE_ONLY_NOT_ON_A_SITE(remoteOnly));
// undefined socialLinks = inherit the global default; only validate/persist a
// key when the site explicitly overrides (an array, even empty).
// A link whose SVG is unchanged from the file on disk is kept as it is; a new
diff --git a/common/lib/siteRemoteOnly.test.ts b/common/lib/siteRemoteOnly.test.ts
@@ -0,0 +1,41 @@
+// demo epic D1: a remote-only channel is never put on a site (writeSite, the
+// one writer every site edit goes through).
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "site-remote-only-"));
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+
+const { getPaths } = await import("./paths");
+const { writeSite, REMOTE_ONLY_NOT_ON_A_SITE } = await import("./site");
+const paths = getPaths();
+
+async function channel(slug: string, config: Record<string, unknown>) {
+ await mkdir(path.join(paths.channelsDir, slug), { recursive: true });
+ await writeFile(path.join(paths.channelsDir, slug, "config.json"), JSON.stringify({ name: slug, handling: "youtube", ...config }));
+}
+
+test("no site may carry a remote-only channel, as a member or a cited channel", async () => {
+ await channel("own", { url: "https://www.youtube.com/@own" });
+ await channel("remote", { platform: "youtube", remoteOnly: true, remoteArchive: "https://stub.test", downloadMode: "manual" });
+ const site = {
+ siteId: "demo-site",
+ siteTitle: "Demo",
+ siteDescription: "",
+ headerTitle: "Demo",
+ homeTagline: "",
+ groups: [{ id: "default", name: "All", selectedByDefault: true }],
+ defaultGroupId: "default",
+ channels: [{ slug: "own", groupId: "default" }],
+ };
+ await writeSite(site as never, paths);
+ await assert.rejects(writeSite({ ...site, channels: [...site.channels, { slug: "remote", groupId: "default" }] } as never, paths), {
+ message: REMOTE_ONLY_NOT_ON_A_SITE("remote"),
+ });
+ await assert.rejects(writeSite({ ...site, citedChannels: [{ slug: "remote" }] } as never, paths), { message: REMOTE_ONLY_NOT_ON_A_SITE("remote") });
+});
diff --git a/common/lib/transcripts-server.ts b/common/lib/transcripts-server.ts
@@ -1,3 +1,4 @@
+import { localRecordingProblem } from "./localRecordingMetadata";
import { readFile } from "node:fs/promises";
import path from "node:path";
import { formatDate, formatDuration } from "./format";
@@ -12,6 +13,8 @@ import type { MediaType, VideoStat, VideoStatus } from "./stats";
import type { VideoState } from "./availability";
export type RawMetadata = {
+ local_recording?: unknown;
+ recorded_date?: string;
id?: string;
title?: string;
upload_date?: string;
@@ -87,7 +90,19 @@ export function loadRawMetadataFromDir(
// been — the generic extractor (a podcast episode imported by its enclosure
// URL) still lands there, and changing that would relabel records already
// published.
+//
+// A LOCAL RECORDING (lib/localRecordingMetadata.ts) carries a `local_recording`
+// marker and is "local" — even when the marker does not validate: relabelling
+// it as a provider would build a YouTube URL from a `local-…` id. Never a
+// throw (a dozen summarize() callers would fall over on one bad file): an
+// invalid marker is warned once per id here, and the index skips the record
+// with a log line (controller/buildIndex.ts, localRecordingProblem).
export function platformFromMetadata(meta: RawMetadata): Platform {
+ if (meta.local_recording !== undefined) {
+ const problem = localRecordingProblem(meta);
+ if (problem) warnInvalidLocalRecording(meta, problem);
+ return "local";
+ }
const key = meta.extractor_key ?? meta.extractor ?? "";
if (/^rumble/i.test(key)) return "rumble";
if (/^lbry/i.test(key)) return "odysee";
@@ -164,7 +179,13 @@ export function summarize(
id,
channelSlug,
title: meta.title ?? id,
- uploadDate: meta.upload_date ?? dateFromDir ?? "",
+ // A LOCAL RECORDING was never published: its one date is the recording
+ // date the operator gave (`recorded_date`), and that is the date it sorts,
+ // filters and shows by (lane/local-media slice 1, review B2). It keeps
+ // `recordedDate` too. With none it is UNDATED (""): indexed all the same,
+ // last in newest-first, outside any date-bounded filter.
+ uploadDate: platform === "local" ? meta.recorded_date ?? "" : meta.upload_date ?? dateFromDir ?? "",
+ ...(platform === "local" && meta.recorded_date ? { recordedDate: meta.recorded_date } : {}),
duration: meta.duration ?? 0,
channel: configName ?? meta.channel ?? meta.uploader ?? "",
description: meta.description ?? "",
@@ -292,3 +313,13 @@ export function toDisplaySummary(
: {}),
};
}
+
+const warnedLocalRecordings = new Set<string>();
+function warnInvalidLocalRecording(meta: RawMetadata, problem: string): void {
+ const key = typeof meta.id === "string" ? meta.id : JSON.stringify(meta.title ?? null);
+ if (warnedLocalRecordings.has(key)) return;
+ // Bounded: a long-lived server warns about at most this many ids.
+ if (warnedLocalRecordings.size >= 1000) return;
+ warnedLocalRecordings.add(key);
+ console.warn(`Invalid local_recording metadata for ${key}: ${problem}; the index skips it.`);
+}
diff --git a/common/lib/voiceApps.ts b/common/lib/voiceApps.ts
@@ -53,8 +53,19 @@ export type VoiceSetup =
importName: string;
code: { repo: string; commit: string };
files: readonly VoiceModelFile[];
+ // Files the engine runs without, in named groups: fetched only when
+ // setup is asked for the group (`--with <id>`), never counted against
+ // "installed" — an install made before a group existed keeps working.
+ optional?: readonly VoiceFileGroup[];
};
+export type VoiceFileGroup = {
+ id: string;
+ // What the group is for, as setup says it.
+ label: string;
+ files: readonly VoiceModelFile[];
+};
+
// A downloaded file, verified by size and sha256 like a TTS model file. `name`
// may hold a subdirectory (`whisper-small/model.safetensors`).
export type VoiceModelFile = TtsModelFile & { executable?: boolean };
@@ -63,6 +74,22 @@ export type VoiceParamSpec =
| { kind: "number"; min: number; max: number; default: number; doc: string }
| { kind: "boolean"; default: boolean; doc: string };
+// THE PITCH A CONVERSION LANDS ON (operator, 11 Nov: both converters threw the
+// read's intonation away — inputs with a median f0 of 128 to 237 Hz all came
+// out at 196-199 Hz, a 152-321 Hz range as 165-240 Hz).
+// target the stock voice's own pitch: the converter is given none of the
+// input's (every engine; what there was before).
+// source the input's f0 as it was read: raise the voice and the output
+// rises with it.
+// contour the input's f0 curve moved as a whole so its median sits on the
+// stock voice's: every rise and fall kept, the register the target's.
+// `semitones` then moves a followed curve (source, contour) up or down.
+export type VoicePitch = "target" | "source" | "contour";
+export const VOICE_PITCH_MODES: readonly VoicePitch[] = ["target", "source", "contour"];
+export const VOICE_SEMITONES_MAX = 12;
+export type VoicePitchChoice = { pitch: VoicePitch; semitones: number };
+export const DEFAULT_VOICE_PITCH: VoicePitchChoice = { pitch: "target", semitones: 0 };
+
export type VoiceBuildInput = {
input: string;
output: string;
@@ -74,6 +101,8 @@ export type VoiceBuildInput = {
// The stock target's reference clip and openvoice's embedding cache (convert).
targetRef?: string;
targetSe?: string;
+ // A followed pitch (an engine with `pitch`); absent = target.
+ pitch?: VoicePitchChoice;
bins: { ffmpegBin: string; voiceModelsDir: string };
};
@@ -93,6 +122,11 @@ export type VoiceEngine = {
// plus swapped — rnnoise 112 MB, deepfilternet 111 MB, openvoice 1625 MB,
// seed-vc 2865 MB; no GPU memory, they are CPU engines) plus a margin.
defaultEstimateMB: number;
+ // A convert engine that can FOLLOW the input's pitch (source, contour): the
+ // optional file group that mode runs on, and the memory ITS run declares
+ // (another, bigger model) — kept in settings.voice.heavyEstimateMB under
+ // `estimateKey`. An engine without it has one pitch: the target's.
+ pitch?: { group: string; estimateKey: string; defaultEstimateMB: number };
// Args to paths.voiceBin (scripts/voice.mjs).
build: (input: VoiceBuildInput) => string[];
};
@@ -232,6 +266,13 @@ const openvoice: VoiceEngine = {
],
};
+// The f0 model's run, declared to the heavy slot: its peak measured 2026-11-11
+// (RSS plus swap of the wrapper and python, sampled twice a second) — 3706 MB
+// over 6.9 s reads, 5781 MB over a 34 s one, whose first window is a full one
+// (30 s less the reference: the 44.1 kHz vocoder's activations grow with the
+// window, and no take makes a longer one) — plus a margin.
+const SEEDVC_F0_ESTIMATE_MB = 6500;
+
const SEEDVC_HF = "https://huggingface.co/Plachta/Seed-VC/resolve/257283f9f41585055e8f858fba4fd044e5caed6e";
const WHISPER_HF = "https://huggingface.co/openai/whisper-small/resolve/973afd24965f72e36ca33b3055d56a652f456b4d";
const BIGVGAN_HF = "https://huggingface.co/nvidia/bigvgan_v2_22khz_80band_256x/resolve/633ff708ed5b74903e86ff1298cf4a98e921c513";
@@ -288,6 +329,52 @@ export const SEEDVC_FILES: readonly VoiceModelFile[] = [
},
];
+// The f0-conditioned model (upstream's `inference.py --f0-condition`): a 44.1
+// kHz DiT, its 128-band BigVGAN, and RMVPE, the pitch tracker whose curve
+// conditions it. Optional (`voice setup --engine seed-vc --with f0`, 1.49 GB):
+// `pitch: source | contour` runs on these, `target` never touches them.
+const RMVPE_HF = "https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d";
+const BIGVGAN_44K_HF = "https://huggingface.co/nvidia/bigvgan_v2_44khz_128band_512x/resolve/95a9d1dcb12906c03edd938d77b9333d6ded7dfb";
+
+export const SEEDVC_F0_FILES: readonly VoiceModelFile[] = [
+ {
+ name: "DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema_v2.pth",
+ url: `${SEEDVC_HF}/DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema_v2.pth`,
+ bytes: 820_865_494,
+ sha256: "42aef93ffe65857c840d270252fa040f7ba04514945ec460f3ac1ac2a96de684",
+ },
+ {
+ name: "config_dit_mel_seed_uvit_whisper_base_f0_44k.yml",
+ url: `${SEEDVC_HF}/config_dit_mel_seed_uvit_whisper_base_f0_44k.yml`,
+ bytes: 2_408,
+ sha256: "ff86f343b08c2def405f075022eeb10dafba23c4eda36d151010f4ca6d7a1a0a",
+ },
+ {
+ name: "rmvpe.pt",
+ url: `${RMVPE_HF}/rmvpe.pt`,
+ bytes: 181_184_272,
+ sha256: "6d62215f4306e3ca278246188607209f09af3dc77ed4232efdd069798c4ec193",
+ },
+ {
+ name: "bigvgan-44k/bigvgan_generator.pt",
+ url: `${BIGVGAN_44K_HF}/bigvgan_generator.pt`,
+ bytes: 489_041_291,
+ sha256: "d9fe7ec6bd0b44ed9d66973d5012d8181c1570b01e5c72df51973e241dccd357",
+ },
+ {
+ name: "bigvgan-44k/config.json",
+ url: `${BIGVGAN_44K_HF}/config.json`,
+ bytes: 1_403,
+ sha256: "65b7f487bfaf15256056a75f6667ef5f640214c981922a111927873705ea4ddb",
+ },
+];
+
+export const SEEDVC_F0_GROUP: VoiceFileGroup = {
+ id: "f0",
+ label: "the f0-conditioned 44.1 kHz model, for a conversion that follows the input's pitch (pitch: source | contour)",
+ files: SEEDVC_F0_FILES,
+};
+
// Seed-VC v1, its 22 kHz speech model (Whisper-small content features, a
// diffusion transformer, BigVGAN v2): zero-shot, the stronger timbre match,
// several times slower than OpenVoice on the CPU. GPL-3.0 code, run as a
@@ -312,6 +399,7 @@ const seedVc: VoiceEngine = {
importName: "transformers",
code: { repo: "https://github.com/Plachtaa/seed-vc", commit: "51383efd921027683c89e5348211d93ff12ac2a8" },
files: SEEDVC_FILES,
+ optional: [SEEDVC_F0_GROUP],
},
params: {
steps: { kind: "number", min: 1, max: 100, default: 10, doc: "diffusion steps: each is one pass of the model over every window, so the time grows with them (upstream: 4-10 fast, 25-30 cleaner; 10 by the 2026-11-03 bake-off)" },
@@ -319,12 +407,14 @@ const seedVc: VoiceEngine = {
refSeconds: { kind: "number", min: 3, max: 25, default: 10, doc: "seconds of the reference the model is prompted with (each window is 30 s less this: less is faster)" },
},
defaultEstimateMB: 3500,
+ pitch: { group: SEEDVC_F0_GROUP.id, estimateKey: "seed-vc-f0", defaultEstimateMB: SEEDVC_F0_ESTIMATE_MB },
build: (i) => [
...common("convert", "seed-vc", i),
"--python", voiceVenvPython(i.installDir),
"--code", voiceCodeDir(i.installDir),
"--install", i.installDir,
"--target-ref", i.targetRef ?? "",
+ ...(i.pitch && i.pitch.pitch !== "target" ? ["--pitch", i.pitch.pitch, "--semitones", String(i.pitch.semitones)] : []),
],
};
@@ -355,6 +445,58 @@ export function voiceInstallDir(home: string, engine: Pick<VoiceEngine, "id">):
type Check<T> = { ok: true; value: T } | { ok: false; error: string };
/**
+ * The pitch a conversion lands on: the request's `pitch` / `semitones` over the
+ * defaults (settings.voice.convert). An engine with one pitch refuses a request
+ * for another (the defaults are not a request: they are for the engines that
+ * can); `semitones` asked of the target's own pitch is refused, since nothing
+ * is followed to move. A request that names a followed `pitch` and no
+ * `semitones` takes the DEFAULT semitones (settings.voice.convert.semitones),
+ * whichever pitch the settings name — say `"semitones": 0` for none. Pure.
+ */
+export function resolveVoicePitch(
+ engine: Pick<VoiceEngine, "id" | "label" | "pitch">,
+ given: { pitch?: unknown; semitones?: unknown },
+ defaults: VoicePitchChoice = DEFAULT_VOICE_PITCH,
+): Check<VoicePitchChoice> {
+ if (given.pitch !== undefined && !VOICE_PITCH_MODES.includes(given.pitch as VoicePitch)) {
+ return { ok: false, error: `"pitch" is one of ${VOICE_PITCH_MODES.join(", ")} (got ${JSON.stringify(given.pitch)})` };
+ }
+ if (given.semitones !== undefined) {
+ const n = given.semitones;
+ if (typeof n !== "number" || !Number.isFinite(n) || Math.abs(n) > VOICE_SEMITONES_MAX) {
+ return { ok: false, error: `"semitones" is a number from -${VOICE_SEMITONES_MAX} to ${VOICE_SEMITONES_MAX} (got ${JSON.stringify(n)})` };
+ }
+ }
+ const askedPitch = given.pitch as VoicePitch | undefined;
+ const askedSemitones = given.semitones as number | undefined;
+ if (!engine.pitch) {
+ if ((askedPitch && askedPitch !== "target") || askedSemitones) {
+ const can = Object.values(VOICE_ENGINES).filter((e) => e.pitch).map((e) => e.id);
+ return {
+ ok: false,
+ error: `${engine.label} has no pitch control — it lands every read on the target's own pitch; "pitch" and "semitones" are ${can.join(", ")}'s (engine: "${can[0]}")`,
+ };
+ }
+ return { ok: true, value: { pitch: "target", semitones: 0 } };
+ }
+ const pitch = askedPitch ?? defaults.pitch;
+ if (pitch === "target") {
+ if (askedSemitones) {
+ return { ok: false, error: `"semitones" moves a followed pitch — give "pitch": "source" or "contour" with it (pitch is "target": the stock voice's own)` };
+ }
+ return { ok: true, value: { pitch, semitones: 0 } };
+ }
+ return { ok: true, value: { pitch, semitones: askedSemitones ?? defaults.semitones } };
+}
+
+/** How a result, a take or a page says a pitch choice: "contour +2 st", "source", "" for the target's own. */
+export function describeVoicePitch(p: Partial<VoicePitchChoice> | undefined): string {
+ if (!p?.pitch || p.pitch === "target") return "";
+ const n = p.semitones ?? 0;
+ return n ? `${p.pitch} ${n > 0 ? "+" : "−"}${Math.abs(n)} st` : p.pitch;
+}
+
+/**
* An engine's knobs from a body's `params`: each key one the engine has, each
* value of its kind and in its range; the rest from the defaults. Pure.
*/
@@ -445,8 +587,8 @@ export function voiceConvertDisclosure(engine: Pick<VoiceEngine, "label">, targe
}
// A client-safe view (no functions).
-export type VoiceEngineDescriptor = { id: string; op: VoiceOp; label: string; license: string; params: Record<string, VoiceParamSpec> };
+export type VoiceEngineDescriptor = { id: string; op: VoiceOp; label: string; license: string; params: Record<string, VoiceParamSpec>; pitch: boolean };
export function listVoiceEngines(): VoiceEngineDescriptor[] {
- return Object.values(VOICE_ENGINES).map((e) => ({ id: e.id, op: e.op, label: e.label, license: e.license, params: { ...e.params } }));
+ return Object.values(VOICE_ENGINES).map((e) => ({ id: e.id, op: e.op, label: e.label, license: e.license, params: { ...e.params }, pitch: Boolean(e.pitch) }));
}
diff --git a/common/lib/voiceInstall.ts b/common/lib/voiceInstall.ts
@@ -7,18 +7,51 @@
// the pinned checkout's marker, each file at its pinned size (an executable
// one executable); setup's `--check` goes further and imports the package and
// reads the checkout's commit. Read-only: never creates anything.
+//
+// An engine's OPTIONAL file groups (seed-vc's `f0`: the model a followed pitch
+// runs on) are reported beside, never counted: `installed` is the required
+// files alone, so an install made before a group existed is still installed.
import fs from "node:fs";
import path from "node:path";
-import { voiceCodeDir, voiceInstallDir, voiceVenvPython, type VoiceEngine } from "./voiceApps";
+import { voiceCodeDir, voiceInstallDir, voiceVenvPython, type VoiceEngine, type VoiceModelFile } from "./voiceApps";
export type VoiceInstallState = {
engine: string;
dir: string;
installed: boolean;
missing: string[];
+ // Each optional group: there whole, or what of it is missing.
+ optional: VoiceGroupState[];
};
+export type VoiceGroupState = { id: string; label: string; installed: boolean; missing: string[] };
+
+function missingFiles(dir: string, files: readonly VoiceModelFile[]): string[] {
+ const missing: string[] = [];
+ for (const f of files) {
+ const p = path.join(dir, f.name);
+ let st: fs.Stats | null = null;
+ try {
+ st = fs.statSync(p);
+ } catch {
+ st = null;
+ }
+ if (!st) missing.push(f.name);
+ else if (st.size !== f.bytes) missing.push(`${f.name} (${st.size} bytes, expected ${f.bytes})`);
+ else if (f.executable && (st.mode & 0o111) === 0) missing.push(`${f.name} (not executable)`);
+ }
+ return missing;
+}
+
+/** One optional group of an engine's install, or undefined when the engine has none by that id. */
+export function voiceGroupState(engine: VoiceEngine, group: string, opts: { home: string }): VoiceGroupState | undefined {
+ const g = engine.setup.kind === "python-venv" ? engine.setup.optional?.find((x) => x.id === group) : undefined;
+ if (!g) return undefined;
+ const missing = missingFiles(voiceInstallDir(opts.home, engine), g.files);
+ return { id: g.id, label: g.label, installed: missing.length === 0, missing };
+}
+
// The file a finished checkout leaves: the commit it is at.
export const VOICE_CODE_MARKER = ".archilyzer-commit";
@@ -30,7 +63,7 @@ export function voiceInstallState(
if (setup.kind === "bundled") {
const model = path.join(opts.voiceModelsDir, "sh.rnnn");
const ok = fs.existsSync(model);
- return { engine: engine.id, dir: opts.voiceModelsDir, installed: ok, missing: ok ? [] : [`${model} (shipped in the repo)`] };
+ return { engine: engine.id, dir: opts.voiceModelsDir, installed: ok, missing: ok ? [] : [`${model} (shipped in the repo)`], optional: [] };
}
const dir = voiceInstallDir(opts.home, engine);
const missing: string[] = [];
@@ -47,17 +80,7 @@ export function voiceInstallState(
missing.push(at ? `the checkout of ${setup.code.repo} is at ${at.slice(0, 10)}, pinned ${setup.code.commit.slice(0, 10)}` : `the checkout of ${setup.code.repo} (${voiceCodeDir(dir)})`);
}
}
- for (const f of setup.files) {
- const p = path.join(dir, f.name);
- let st: fs.Stats | null = null;
- try {
- st = fs.statSync(p);
- } catch {
- st = null;
- }
- if (!st) missing.push(f.name);
- else if (st.size !== f.bytes) missing.push(`${f.name} (${st.size} bytes, expected ${f.bytes})`);
- else if (f.executable && (st.mode & 0o111) === 0) missing.push(`${f.name} (not executable)`);
- }
- return { engine: engine.id, dir, installed: missing.length === 0, missing };
+ missing.push(...missingFiles(dir, setup.files));
+ const optional = (setup.kind === "python-venv" ? setup.optional ?? [] : []).map((g) => voiceGroupState(engine, g.id, opts)!);
+ return { engine: engine.id, dir, installed: missing.length === 0, missing, optional };
}
diff --git a/common/lib/voiceSettings.test.ts b/common/lib/voiceSettings.test.ts
@@ -1,7 +1,7 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { DEFAULT_VOICE_SETTINGS, resolveVoiceHome, sanitizeVoice } from "./voiceSettings";
-import { NO_CLONING, VOICE_ENGINES, listVoiceEngines, parseStockTarget, resolveVoiceParams, voiceEngineIds } from "./voiceApps";
+import { NO_CLONING, VOICE_ENGINES, describeVoicePitch, listVoiceEngines, parseStockTarget, resolveVoiceParams, voiceEngineIds } from "./voiceApps";
// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/voiceSettings.test.ts
@@ -25,7 +25,16 @@ test("settings.voice: defaults, and every field falls back rather than throws",
assert.equal(s.heavyEstimateMB["seed-vc"], 4200);
assert.equal(s.heavyEstimateMB.openvoice, 0);
assert.equal("nope" in s.heavyEstimateMB, false);
- assert.deepEqual(Object.keys(s.heavyEstimateMB).sort(), Object.keys(VOICE_ENGINES).sort());
+ // Every engine, and the f0 run of the one that can follow a pitch.
+ assert.deepEqual(Object.keys(s.heavyEstimateMB).sort(), [...Object.keys(VOICE_ENGINES), "seed-vc-f0"].sort());
+ assert.equal(s.heavyEstimateMB["seed-vc-f0"], VOICE_ENGINES["seed-vc"].pitch!.defaultEstimateMB);
+ assert.equal(sanitizeVoice({ heavyEstimateMB: { "seed-vc-f0": 5000 } }).heavyEstimateMB["seed-vc-f0"], 5000);
+ // The pitch a conversion lands on: the target's own unless said, the semitones clamped.
+ assert.deepEqual([s.convert.pitch, s.convert.semitones], ["target", 0]);
+ const p = sanitizeVoice({ convert: { pitch: "contour", semitones: 40 } }).convert;
+ assert.deepEqual([p.pitch, p.semitones], ["contour", 12]);
+ const q = sanitizeVoice({ convert: { pitch: "higher", semitones: "2" } }).convert;
+ assert.deepEqual([q.pitch, q.semitones], ["target", 0]);
const ok = sanitizeVoice({ home: "~/voice", convert: { engine: "seed-vc", target: "kokoro:bm_george" }, enhance: { engine: "rnnoise" } });
assert.equal(ok.convert.engine, "seed-vc");
assert.equal(ok.convert.target, "kokoro:bm_george");
@@ -62,7 +71,24 @@ test("the registry: two engines per op, every knob has a default in range", () =
}
assert.ok(e.defaultEstimateMB > 0, e.id);
if (e.setup.kind !== "bundled") for (const f of e.setup.files) assert.match(f.sha256, /^[0-9a-f]{64}$/, f.name);
+ // An optional group: pinned by revision, size and sha256 like the rest, and no name of the required set.
+ if (e.setup.kind === "python-venv") {
+ const required = new Set(e.setup.files.map((f) => f.name));
+ for (const g of e.setup.optional ?? []) {
+ for (const f of g.files) {
+ assert.match(f.sha256, /^[0-9a-f]{64}$/, f.name);
+ assert.match(f.url, /\/resolve\/[0-9a-f]{40}\//, f.name);
+ assert.ok(f.bytes > 0 && !required.has(f.name), f.name);
+ }
+ }
+ if (e.pitch) assert.ok(e.setup.optional?.some((g) => g.id === e.pitch!.group), e.id);
+ }
+ assert.equal(Boolean(e.pitch), e.id === "seed-vc", e.id);
}
+ assert.equal(describeVoicePitch({ pitch: "target", semitones: 0 }), "");
+ assert.equal(describeVoicePitch({ pitch: "source", semitones: 0 }), "source");
+ assert.equal(describeVoicePitch({ pitch: "contour", semitones: 2 }), "contour +2 st");
+ assert.equal(describeVoicePitch({ pitch: "source", semitones: -1.5 }), "source −1.5 st");
assert.equal(listVoiceEngines().length, 4);
assert.equal(resolveVoiceParams(VOICE_ENGINES.rnnoise, []).ok, false);
});
diff --git a/common/lib/voiceSettings.ts b/common/lib/voiceSettings.ts
@@ -14,13 +14,17 @@ import {
DEFAULT_VOICE_ENGINE,
DEFAULT_VOICE_TARGET,
VOICE_ENGINES,
+ DEFAULT_VOICE_PITCH,
+ VOICE_PITCH_MODES,
+ VOICE_SEMITONES_MAX,
getVoiceEngine,
parseStockTarget,
type VoiceOp,
+ type VoicePitch,
} from "./voiceApps";
export type VoiceEnhanceSettings = { engine: string };
-export type VoiceConvertSettings = { engine: string; target: string };
+export type VoiceConvertSettings = { engine: string; target: string; pitch: VoicePitch; semitones: number };
export type VoiceSettings = {
home: string;
@@ -31,15 +35,20 @@ export type VoiceSettings = {
heavyEstimateMB: Record<string, number>;
};
+// An engine's own estimate, and — for one that can follow the input's pitch on
+// another model — that run's, under the engine's `pitch.estimateKey`.
export const DEFAULT_VOICE_HEAVY_ESTIMATES: Record<string, number> = Object.fromEntries(
- Object.values(VOICE_ENGINES).map((e) => [e.id, e.defaultEstimateMB]),
+ Object.values(VOICE_ENGINES).flatMap((e) => [
+ [e.id, e.defaultEstimateMB] as const,
+ ...(e.pitch ? [[e.pitch.estimateKey, e.pitch.defaultEstimateMB] as const] : []),
+ ]),
);
export const DEFAULT_VOICE_SETTINGS: VoiceSettings = {
home: "",
threads: 4,
enhance: { engine: DEFAULT_VOICE_ENGINE.enhance },
- convert: { engine: DEFAULT_VOICE_ENGINE.convert, target: DEFAULT_VOICE_TARGET },
+ convert: { engine: DEFAULT_VOICE_ENGINE.convert, target: DEFAULT_VOICE_TARGET, ...DEFAULT_VOICE_PITCH },
heavyEstimateMB: DEFAULT_VOICE_HEAVY_ESTIMATES,
};
@@ -51,11 +60,13 @@ export const VOICE_SETTINGS_FIELD_DOCS: FieldDocs<VoiceSettings> = {
"(`<home>/targets/`). Blank = `~/.local/share/archilyzer/voice`. Absolute, or `~/`-relative.",
threads: "CPU threads a torch engine (openvoice, seed-vc) may use. 1–16.",
enhance: "The enhance op's default engine. See VoiceEnhanceSettings (`voice.enhance` below).",
- convert: "The convert op's default engine and target. See VoiceConvertSettings (`voice.convert` below).",
+ convert: "The convert op's default engine, target and pitch. See VoiceConvertSettings (`voice.convert` below).",
heavyEstimateMB:
"Per engine id: the memory (MB) its job is admitted to the machine's heavy slot with " +
"(`queue-lock --heavy --estimate`) — it runs only when that much is free above the floor. " +
- "The defaults are the 2026-11-03 bake-off's measured peaks plus a margin. An engine left out " +
+ "The defaults are the 2026-11-03 bake-off's measured peaks plus a margin; `seed-vc-f0` is seed-vc's " +
+ "run when it follows the input's pitch (`pitch: source | contour` — another, bigger model; measured " +
+ "2026-11-11 over a take long enough to fill a 30 s window: 5.8 GB). An engine left out " +
"takes its default; 0 declares nothing (the job then runs ALONE in the slot).",
};
@@ -78,6 +89,17 @@ export const VOICE_CONVERT_SETTINGS_FIELD_DOCS: FieldDocs<VoiceConvertSettings>
"`<tts engine>:<stock voice>` (`orpheus:zac`, `orpheus:leah`, `kokoro:am_michael`, …). Never a " +
"file or a recording — no real person's voice is a target. Its reference clip is synthesized " +
"once through the `tts` op and kept under `home`. Anything else falls back to `orpheus:zac`.",
+ pitch:
+ "The pitch a conversion lands on when the request names none — for an engine that can follow the " +
+ "input's (seed-vc, with its optional f0 model: `archilyzer voice setup --engine seed-vc --with f0`; " +
+ "openvoice always lands on the target's). `target`: the stock voice's own pitch — the read's " +
+ "intonation is flattened to it (what there was before). `source`: the pitch the take was read at — " +
+ "raise your voice and the result rises. `contour`: the read's rises and falls, moved as a whole so " +
+ "their median sits on the stock voice's. Anything else falls back to `target`.",
+ semitones:
+ "Semitones a FOLLOWED pitch (`source`, `contour`) is moved by when the request names none: -12 to 12, " +
+ "0 = as followed. Ignored for `target`. It applies to a request that names its own `pitch` too: " +
+ "`{\"pitch\": \"source\"}` with no `semitones` is moved by this many — send `\"semitones\": 0` for none.",
};
// "" (the default), an absolute path, or a `~/` one; anything else is "".
@@ -109,7 +131,15 @@ export function sanitizeVoice(value: unknown): VoiceSettings {
home: dirSetting(r.home),
threads: Math.min(16, Math.max(1, threads)),
enhance: { engine: engineFor("enhance", en.engine) },
- convert: { engine: engineFor("convert", cv.engine), target: target.ok ? target.value.id : DEFAULT_VOICE_TARGET },
+ convert: {
+ engine: engineFor("convert", cv.engine),
+ target: target.ok ? target.value.id : DEFAULT_VOICE_TARGET,
+ pitch: VOICE_PITCH_MODES.includes(cv.pitch as VoicePitch) ? (cv.pitch as VoicePitch) : DEFAULT_VOICE_PITCH.pitch,
+ semitones:
+ typeof cv.semitones === "number" && Number.isFinite(cv.semitones)
+ ? Math.min(VOICE_SEMITONES_MAX, Math.max(-VOICE_SEMITONES_MAX, Math.round(cv.semitones * 100) / 100))
+ : DEFAULT_VOICE_PITCH.semitones,
+ },
heavyEstimateMB,
};
}
diff --git a/common/package.json b/common/package.json
@@ -42,6 +42,7 @@
"./lib/atomicFile.mjs": "./lib/atomicFile.mjs",
"./lib/cueWiden.mjs": "./lib/cueWiden.mjs",
"./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs",
+ "./lib/projectsRoot.mjs": "./lib/projectsRoot.mjs",
"./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs",
"./lib/recordingClock.mjs": "./lib/recordingClock.mjs",
"./lib/recordingClock-read.mjs": "./lib/recordingClock-read.mjs",
diff --git a/common/publish/composeReports.test.ts b/common/publish/composeReports.test.ts
@@ -342,7 +342,7 @@ test("a cited site: exactly its reports, moments, cited media and contract — t
assert.ok(!JSON.stringify(readJson(pub("m", "index.json"))).includes("40.00"));
});
-test("a cited site's contract: site.json without channels, corpus.json scope cited at spec 5, the cited llms.txt and sitemap", () => {
+test("a cited site's contract: site.json without channels, corpus.json scope cited at spec 6, the cited llms.txt and sitemap", () => {
const site = readJson<{ siteId: string; channels: unknown[]; pwa: boolean }>(pub("site.json"));
assert.equal(site.siteId, "cited");
assert.deepEqual(site.channels, []);
@@ -355,7 +355,7 @@ test("a cited site's contract: site.json without channels, corpus.json scope cit
reports?: { index: string; count: number };
}>(pub("corpus.json"));
assert.equal(corpus.spec, CONTRACT.corpusSpec);
- assert.equal(corpus.spec, 5);
+ assert.equal(corpus.spec, 6);
assert.equal(corpus.site.id, "cited");
assert.equal(corpus.site.scope, "cited");
assert.equal(corpus.site.audience, "public");
@@ -640,7 +640,7 @@ test("a full site with reports keeps its corpus and links each moment into it",
const corpus = readJson<{ spec: number; site: { scope?: string; audience?: string }; channels: unknown[]; reports?: { count: number } }>(
pub("corpus.json"),
);
- assert.equal(corpus.spec, 5);
+ assert.equal(corpus.spec, 6);
assert.equal(corpus.site.scope, undefined);
assert.equal(corpus.site.audience, undefined);
assert.equal(corpus.channels.length, 2);
diff --git a/common/publish/composeReports.ts b/common/publish/composeReports.ts
@@ -69,6 +69,7 @@
// thrown together (ComposeReportsError), so a failed compose leaves no half
// set of reports behind.
+import { isLocalRecord } from "../lib/localMedia";
import { pageCaptureView, pageCopyLinks } from "../lib/waybackPages/view";
import { copyFile, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
@@ -646,6 +647,13 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol
problems.push({ kind: "missing-record", citation: ref, report: report.id, message: `no record ${c.channel}/${c.id} (no metadata or transcript in its data dir)` });
continue;
}
+ // A local recording publishes only on a private host (lane/local-media
+ // slice 1 ruling; lib/localMedia.ts isLocalRecord): its quote and cues
+ // never reach a public site or the public articles.
+ if (host.audience !== "private" && isLocalRecord({ id: c.id, platform: (record.summary as { platform?: string } | null)?.platform })) {
+ problems.push({ kind: "not-visible", citation: ref, report: report.id, message: `${carrier} is public and may not carry the local recording ${c.channel}/${c.id} (local media is private until slice 4)` });
+ continue;
+ }
if (record.cues.length === 0) {
problems.push({ kind: "no-cues", citation: ref, report: report.id, message: `${c.channel}/${c.id} has no transcript cues to check the quote against` });
continue;
diff --git a/common/publish/composeReportsArticles.test.ts b/common/publish/composeReportsArticles.test.ts
@@ -262,3 +262,33 @@ test("nothing published: the stage writes nothing and clears the output root's r
assert.deepEqual(composed, { reports: [], moments: [], allowed: [] });
assert.deepEqual(filesUnder(OUT), []);
});
+
+// lane/local-media review fix 3: a local recording publishes only on a private
+// host — a public build refuses a citation of one; a private build carries it.
+test("refused: a local recording cited in a public build; a private build carries it", async () => {
+ const { prepareManualLocalRecordingMetadata } = await import("../lib/localRecordingMetadata");
+ const LOCAL = "local-" + "f".repeat(32);
+ const dir = path.join(paths.channelsDir, LONE, "data", LOCAL);
+ writeJson(path.join(dir, "metadata.info.json"), prepareManualLocalRecordingMetadata({ id: LOCAL, filename: "talk.mp4", title: "A local talk" }));
+ writeFileSync(path.join(dir, "transcript.en.vtt"), readFileSync(path.join(paths.channelsDir, LONE, "data", "abc123", "transcript.en.vtt")));
+ seedArticle("art-local", { c01: { ...SPAN, id: LOCAL } });
+ await configureArticle("art-local", { published: true, audience: "public" }, paths);
+ try {
+ const pub = await articlesReportHost(paths, { audience: "public" });
+ await assert.rejects(composeHostReports({ paths, host: pub, publicDir: OUT, settings: {}, ...quiet }), (e: unknown) => {
+ assert.ok(e instanceof ComposeReportsError);
+ assert.deepEqual(
+ e.problems.filter((p) => p.citation === "art-local#c01").map((p) => [p.kind, p.message]),
+ [["not-visible", `the articles is public and may not carry the local recording ${LONE}/${LOCAL} (local media is private until slice 4)`]],
+ );
+ return true;
+ });
+ const priv = await articlesReportHost(paths, { audience: "private" });
+ const composed = await composeHostReports({ paths, host: priv, publicDir: OUT, settings: {}, ...quiet }).catch((e: unknown) => e);
+ const problems = composed instanceof ComposeReportsError ? composed.problems : [];
+ assert.deepEqual(problems.filter((p) => p.citation === "art-local#c01"), []);
+ } finally {
+ await configureArticle("art-local", { published: false }, paths);
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/publish/inputSig.test.ts b/common/publish/inputSig.test.ts
@@ -250,3 +250,30 @@ test("hubSig: the stamp, homepage.json, and each listed site's id + url + title"
rmSync(s.root, { recursive: true, force: true });
}
});
+
+// Re-review F2 (lane/local-media): a PRIVATE-audience site signs the transcript
+// tree it actually copies — a channel's full tree under shared/private where it
+// has one; a public site keeps signing the shared tree and does not move when
+// only the private tree does.
+test("a private site signs a member's private transcript tree; a public site does not see it", async () => {
+ const s = setup();
+ try {
+ (s.paths as { exportSharedDir: string }).exportSharedDir = path.join(s.root, ".export-index", "shared");
+ const privateTree = path.join(s.root, ".export-index", "shared", "private", "transcripts", "a");
+ s.write(path.join(privateTree, "page-0000.json"), "[1,\"local\"]");
+ const publicBefore = await s.sig();
+ s.write(path.join(privateTree, "page-0001.json"), "[\"another local\"]");
+ assert.equal(await s.sig(), publicBefore, "a public site does not sign the private tree");
+
+ (s.site as { audience?: string }).audience = "private";
+ const privateBefore = await s.sig();
+ s.write(path.join(privateTree, "page-0002.json"), "[\"a third local\"]");
+ assert.notEqual(await s.sig(), privateBefore, "a private site signs the tree it copies");
+ // A member with no private tree is still signed by its shared tree.
+ const before = await s.sig();
+ s.write(path.join(s.paths.exportSharedPostsDir, "x", "page-0009.json"), "[9]");
+ assert.notEqual(await s.sig(), before);
+ } finally {
+ rmSync(s.root, { recursive: true, force: true });
+ }
+});
diff --git a/common/publish/inputSig.ts b/common/publish/inputSig.ts
@@ -34,7 +34,7 @@ import path from "node:path";
import { open } from "lmdb";
import { dirSignature } from "../lib/dirSignature";
import { DUPLICATES_FILENAME, DUPLICATE_OVERRIDES_FILENAME } from "../lib/duplicates";
-import type { Paths } from "../lib/paths";
+import { sharedPrivateTranscriptsDir, type Paths } from "../lib/paths";
import { publishedMemberSlugs } from "../lib/postsVisibility";
import type { SiteSettings } from "../lib/settings";
import {
@@ -46,7 +46,7 @@ import {
siteIndexDir,
type Site,
} from "../lib/site";
-import { isCitedOnlyChannel, isListedSite } from "../lib/siteSchema";
+import { isCitedOnlyChannel, isListedSite, isPrivateSite } from "../lib/siteSchema";
import { INDEX_SCANNED_AT_KEY } from "../lib/stats";
import { readChannelConfig } from "../controller/channels";
import type { ChannelConfig } from "../lib/channelConfig";
@@ -112,9 +112,19 @@ export async function siteInputSig(i: SiteSigInputs): Promise<string> {
const indexDir = siteIndexDir(paths, site.siteId);
lines.push(`site-index\t${await dirSignature(indexDir, CHART_TEMPLATES)}`);
lines.push(`${CHART_TEMPLATES}\t${await fileBytesSig(path.join(indexDir, CHART_TEMPLATES))}`);
+ // The transcript tree a member's copy comes from: for a PRIVATE-audience
+ // site, a channel's full tree (local recordings included) where it has one —
+ // what compose copies (bin/compose-site.ts transcriptsSourceFor; re-review
+ // F2). Every other site, and a channel with none, signs the shared tree, so
+ // their signatures are unchanged.
+ const privateSite = isPrivateSite(site);
+ const transcriptsRoot = (slug: string): string =>
+ privateSite && existsSync(path.join(sharedPrivateTranscriptsDir(paths), slug))
+ ? sharedPrivateTranscriptsDir(paths)
+ : paths.exportSharedTranscriptsDir;
for (const slug of members) {
for (const [tree, root] of [
- ["transcripts", paths.exportSharedTranscriptsDir],
+ ["transcripts", transcriptsRoot(slug)],
["subs", paths.exportSharedSubsDir],
["posts", paths.exportSharedPostsDir],
["digests", paths.exportSharedDigestsDir],
@@ -130,7 +140,7 @@ export async function siteInputSig(i: SiteSigInputs): Promise<string> {
if (citedOnly.length > 0) lines.push(`cited-only\t${citedOnly.join(",")}`);
for (const slug of citedOnly) {
for (const [tree, root] of [
- ["transcripts", paths.exportSharedTranscriptsDir],
+ ["transcripts", transcriptsRoot(slug)],
["posts", paths.exportSharedPostsDir],
] as const) {
lines.push(`cited/${tree}/${slug}\t${await channelTreeSig(root, slug, cache)}`);
diff --git a/common/publish/reportMedia.ts b/common/publish/reportMedia.ts
@@ -42,6 +42,7 @@
// a channel whose media tier is not reachable (lib/channelMedia.ts) is
// reported as unreachable, with the reason, rather than as missing.
+import { localMediaFetchRefusal } from "../lib/localMedia";
import type { Dirent } from "node:fs";
import { readdir, rm } from "node:fs/promises";
import path from "node:path";
@@ -498,7 +499,7 @@ export type EvidenceWindow = {
reason?: string;
};
-export type UnfetchableReason = "not-in-site" | "unreachable" | "gone" | "members-only" | "audio-only" | "too-long";
+export type UnfetchableReason = "not-in-site" | "unreachable" | "gone" | "members-only" | "audio-only" | "too-long" | "local-media";
export type UnfetchableEvidenceWindow = EvidenceWindow & {
why: UnfetchableReason;
@@ -568,6 +569,11 @@ export async function missingEvidenceWindows(
continue;
}
const config = await configOf(slug);
+ const localRefusal = localMediaFetchRefusal(slug, config, id);
+ if (localRefusal) {
+ unfetchable("local-media", localRefusal);
+ continue;
+ }
const audioOnly = isAudioOnlyPlatform(config?.platform);
const source = await resolveEvidenceSource({
channelsDir: paths.channelsDir,
diff --git a/common/publish/reportMediaLocal.test.ts b/common/publish/reportMediaLocal.test.ts
@@ -0,0 +1,67 @@
+// lane/local-media: a site's evidence read lists a cited local recording, and
+// every window of a local media library channel, as UNFETCHABLE ("local-media",
+// lib/localMedia.ts's sentence) — not missing, which a fetch would try to fill.
+// Synthetic ids; nothing is fetched or cut.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test publish/reportMediaLocal.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "report-media-local-"));
+Object.assign(process.env, {
+ TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"),
+ SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"),
+ SITES_DIR: path.join(ROOT, "transcripts", "sites"),
+ SETTINGS_FILE: path.join(ROOT, "settings.json"),
+ EXPORT_PUBLIC_DIR: path.join(ROOT, "public"),
+ EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"),
+ EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"),
+ ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"),
+});
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { missingEvidenceWindows } = await import("./reportMedia");
+
+const paths = getPaths();
+const SITE = "demo-site";
+const LIB = "library";
+const ONLINE = "online";
+const LOCAL_ID = "local-" + "e".repeat(32);
+const writeJson = (file: string, value: unknown) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, JSON.stringify(value, null, 2));
+};
+writeJson(path.join(paths.channelsDir, LIB, "config.json"), {
+ handling: "youtube", name: "Library", localMedia: { sourceId: "library-1", directory: "/mnt/library" },
+});
+writeJson(path.join(paths.channelsDir, ONLINE, "config.json"), {
+ handling: "youtube", name: "Online", url: "https://www.youtube.com/@online",
+});
+for (const [ch, id] of [[LIB, LOCAL_ID], [LIB, "aaaaaaaaaaa"], [ONLINE, "bbbbbbbbbbb"]]) {
+ writeJson(path.join(paths.channelsDir, ch, "data", id, "metadata.info.json"), { id, duration: 600 });
+}
+writeJson(path.join(paths.sitesDir, SITE, "site.json"), {
+ title: "Demo", channels: [{ slug: LIB }, { slug: ONLINE }], search: false, reports: ["r1"],
+});
+writeJson(path.join(paths.sitesDir, SITE, "reports", "r1", "report.json"), {
+ format: "archilyzer-report", version: 1, id: "r1", kind: "sweep", title: "Report r1",
+ citations: {
+ c01: { kind: "video", channel: LIB, id: LOCAL_ID, start: 10, end: 12, quote: "one" },
+ c02: { kind: "video", channel: LIB, id: "aaaaaaaaaaa", start: 10, end: 12, quote: "two" },
+ c03: { kind: "video", channel: ONLINE, id: "bbbbbbbbbbb", start: 10, end: 12, quote: "three" },
+ },
+ sections: [{ id: "s1", title: "One", body: "[c01](cite:c01) [c02](cite:c02) [c03](cite:c03)" }],
+});
+
+test("a local recording and a local library channel's windows are unfetchable, the online one missing", async () => {
+ const r = await missingEvidenceWindows(paths, SITE);
+ assert.deepEqual(r.problems, []);
+ assert.deepEqual(r.unfetchable.map((w) => [w.id, w.why]).sort(), [["aaaaaaaaaaa", "local-media"], [LOCAL_ID, "local-media"]]);
+ for (const w of r.unfetchable) assert.match(w.message, /no online source, so no clip can be fetched for it\./);
+ assert.deepEqual(r.missing.map((w) => w.id), ["bbbbbbbbbbb"]);
+});
diff --git a/common/views/channelRow.test.ts b/common/views/channelRow.test.ts
@@ -181,3 +181,13 @@ test("channelVolumeOf: no mediaDir is internal, a named root wins, else unnamed"
label: "Big disk",
});
});
+
+test("a remote-only channel's row says so, with its archive, and is not 'manual dl' (demo epic D1)", () => {
+ const remote = buildChannelRowView(
+ input({ config: { handling: "youtube", name: "Remote", remoteOnly: true, remoteArchive: "https://stub.test", downloadMode: "manual" } as ChannelConfig }),
+ );
+ assert.equal(remote.remoteOnly, "https://stub.test");
+ assert.equal(remote.manualDownloads, false);
+ assert.equal(remote.hasUrl, false);
+ assert.equal(buildChannelRowView(input()).remoteOnly, null);
+});
diff --git a/common/views/channelRow.ts b/common/views/channelRow.ts
@@ -1,5 +1,5 @@
import { channelDownloadsAreManual } from "../lib/manualDownloads";
-import { isSocialChannel, type ChannelConfig } from "../lib/channelConfig";
+import { isRemoteOnlyChannel, isSocialChannel, type ChannelConfig } from "../lib/channelConfig";
import type { ChannelSnapshot } from "../controller/channelSnapshot";
import type { ChannelMediaLocation } from "../lib/channelMedia";
import { mediaHoldText } from "../lib/channelMediaHold";
@@ -80,6 +80,8 @@ export type ChannelRowView = {
// `config.name`, "" when unset.
name: string;
handling: ChannelConfig["handling"];
+ // Display-only wording; the pipeline handling value remains unchanged.
+ handlingLabel?: string;
// Whether the channel has a URL — Sync and Download need one.
hasUrl: boolean;
// A social (posts) channel: its Sync runs fetch-posts, never the yt-dlp
@@ -120,6 +122,10 @@ export type ChannelRowView = {
// the channel by design and its `work.undownloaded` is 0 — the rack says so,
// so a long, mostly undownloaded listing is not read as a stalled channel.
manualDownloads: boolean;
+ // A REMOTE-ONLY channel (lib/channelConfig.ts isRemoteOnlyChannel, demo epic
+ // D1): the archive it holds clip windows for — its origin — or null for any
+ // other channel. The list says so; nothing syncs or downloads it.
+ remoteOnly: string | null;
// WHICH VOLUME THE MEDIA IS ON, as an id a filter can name: a location id,
// "internal" for the corpus volume, or "" for a mediaDir under a root nobody
// named. (The text is on the corpus volume whatever this says.)
@@ -197,6 +203,7 @@ export function buildChannelRowView(i: ChannelRowInput): ChannelRowView {
slug: i.slug,
name: i.config.name ?? "",
handling: i.config.handling,
+ handlingLabel: i.config.localMedia && !i.config.url?.trim() ? "Local media" : i.config.handling,
hasUrl: Boolean(i.config.url),
social: isSocialChannel(i.config),
excludeFromBuild: i.config.excludeFromBuild === true,
@@ -231,7 +238,8 @@ export function buildChannelRowView(i: ChannelRowInput): ChannelRowView {
}
: null,
mediaHold: i.media ? mediaHoldText(i.media.status) : null,
- manualDownloads: channelDownloadsAreManual(i.config),
+ manualDownloads: channelDownloadsAreManual(i.config) && !isRemoteOnlyChannel(i.config),
+ remoteOnly: isRemoteOnlyChannel(i.config) ? (i.config.remoteArchive ?? "") : null,
volumeId: i.volume.id,
volumeLabel: i.volume.label,
mediaBytes: snap?.totalMediaBytes ?? null,
diff --git a/common/views/pipeline/channelFlow.test.ts b/common/views/pipeline/channelFlow.test.ts
@@ -355,3 +355,25 @@ test("the flow says which corrupt full sources await full audio, and the salvage
assert.ok(plain.some((s) => s.label === "salvaged transcript"));
assert.ok(!plain.some((s) => s.label === "awaiting full audio"));
});
+
+test("local source satisfies configuration without claiming an online sync", () => {
+ const config: ChannelConfig = { handling: "youtube", localMedia: { sourceId: "archive", directory: "/library" } };
+ const stages = computeStageStatuses({ snapshot: snapshotOf(), failedVideoIds: [], config, runningJobs: [] });
+ assert.equal(stages.configure.tone, "neutral");
+ assert.match(stages.configure.summary, /Local archive configured/);
+ assert.match(stages.playlist.summary, /preview the library/);
+});
+
+test("an absent URL alone never implies a local archive", () => {
+ const stages = computeStageStatuses({ snapshot: snapshotOf(), failedVideoIds: [], config: { handling: "youtube" }, runningJobs: [] });
+ assert.equal(stages.configure.tone, "attention");
+ assert.equal(stages.configure.summary, "Channel has no URL — open to configure.");
+ assert.equal(stages.playlist.summary, "Never synced.");
+});
+
+test("adding a library to an online channel preserves all provider stage statuses", () => {
+ const input = { snapshot: snapshotOf(), failedVideoIds: [], config: CONFIG, runningJobs: [{ kind: "sync", status: "running" }] };
+ const online = computeStageStatuses(input);
+ const hybrid = computeStageStatuses({ ...input, config: { ...CONFIG, localMedia: { sourceId: "archive", directory: "/library" } } });
+ assert.deepEqual(hybrid, online);
+});
diff --git a/common/views/pipeline/stageStatus.ts b/common/views/pipeline/stageStatus.ts
@@ -250,6 +250,9 @@ export function computeStageStatuses(
// always reach the buttons; the summary line communicates idle/busy state
// instead of collapsing the controls out of sight. Configure collapses once
// the channel has a URL; Danger zone stays collapsed unless opened.
+ // A local library is a configured source, but does not imply an online sync.
+ // Channels with both retain their provider status and controls.
+ const localOnly = !!config.localMedia && !config.url;
const configure: StageStatus = {
id: "configure",
title: "Configure",
@@ -259,8 +262,10 @@ export function computeStageStatuses(
defaultOpen: true,
summary: config.url
? `${config.handling}${config.platform ? ` · ${config.platform}` : ""}`
- : "Channel has no URL — open to configure.",
- tone: config.url ? "neutral" : "attention",
+ : localOnly
+ ? "Local archive configured — no online URL required."
+ : "Channel has no URL — open to configure.",
+ tone: config.url || localOnly ? "neutral" : "attention",
};
const playlistRunning = runningByStage.has("playlist");
@@ -273,7 +278,9 @@ export function computeStageStatuses(
defaultOpen: true,
summary: playlistRunning
? "Running…"
- : config.lastSyncedAt
+ : localOnly
+ ? "Local archive — preview the library to discover recordings."
+ : config.lastSyncedAt
? `Last sync ${new Date(config.lastSyncedAt).toLocaleString()}`
: "Never synced.",
tone: pickTone({ running: playlistRunning, pending: 0, failed: 0 }),
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,23 @@
# Changelog
## [Unreleased]
+- **A published archive is a source: connect it once, sweep it, and fetch its cited clips with no local corpus.** A fresh clone pointed at jeralyzer.pages.dev could search it through the MCP and do nothing else: Create had no corpus to offer, and every clip of a channel the editor did not archive was a 404 `Channel "<slug>" not found`. An archive is now connected by its origin — `/sites` → **Connected archives**, or `pnpm ops archives --json '{"connect":"https://jeralyzer.pages.dev"}'` (`"dryRun": true` reads it and writes nothing; `pnpm ops get archives` lists them) — and kept in `settings.remoteArchives`. `TRANSCRIPT_SITE_URL`'s archive is offered without being connected, so a clone set up as AGENTS.md says starts with one. Create offers each connected archive as a sweep's source, preselected when this machine has no corpus of its own, the MCP's `list_sources` lists them and `generate` passes the choice. A sweep over an archive cites that archive's origin, whatever `generation.citationOrigin` says, and its revisions, drafts and refreshes inherit it. A clip window cited from one registers its channel **remote-only** on first need (`fetch-windows` and `fetch-window` take `"archive"`, and the MCP's `fetch_clip` names it): a `config.json` and nothing else, shown as "remote only" in the channel list, skipped by every sync, lane, scan and site build, and left out of the site form's channel picker. On a whole-recording platform (Rumble) a window means downloading the whole recording, which nobody planned for a channel that is not archived here: it is refused with the recording's length and estimated size until the ask carries `"allowWholeRecording": true`. The archive's documents are cached on disk by its build (512 MB by default), read one at a time and paced. `corpus.json` is spec 6 (the export's changelog): each channel names its platform and its page there; an older archive's platform is read from a record's `webpageUrl`.
+- **A connected archive is untrusted input.** umtool can connect one and is open on the LAN, and everything an archive serves is someone else's JSON. An archive on this machine or its network — loopback, private, link-local and CGNAT addresses in any spelling (decimal, hex, IPv4 carried inside IPv6), a `.local`/`.internal`/`.lan` name, or a name that resolves to one — is refused at connect, before anything is asked of it, unless the editor runs with `ARCHILYZER_ALLOW_PRIVATE_ARCHIVES=1` or the origin is `TRANSCRIPT_SITE_URL`'s or already in `settings.json`; the check is made once, at connect. Its documents are read on its own origin only: a redirect elsewhere is refused unfollowed, a manifest its `corpus.json` names on another origin is not followed, and no document past 32 MB is read or kept. A record's page URL is fetched only when its host is its channel's video platform's own domain or a subdomain (`evilyoutube.com` and `youtube.com.evil.example` are not YouTube); a URL carrying a backslash, whitespace or a control character is refused unparsed, because Node and yt-dlp's Python read its host differently; and what reaches yt-dlp is the URL the check parsed, never the archive's own string. A remote-only channel whose archive was removed from settings is refused before its record is read.
+- **umtool: the Source chip connects an archive, and an article swept over one is cut from it.** The Source chip takes an archive's address, reads it and connects it through the editor; a connected archive is offered as the source of **Article from a question** and of a new article, first when this machine has no corpus. The chain of an article swept over an archive asks the editor for its windows with the archive named and each record's page URL, so the cited channels are registered remote-only and fetched; a manifest with no sweep naming an origin takes the archive as its QR origin. A Rumble window fails the step with every recording's size, nothing fetched, until **Fetch the whole recordings** (`umtool chain <article> <n> --allow-whole-recording`). `--stop-before-render` ends Draft everything before the voices, and its new `cut-windows` step fetches the drafted cut's windows, asking the editor only for those not on disk. The cue walk, the link check and a source's build identity read an archive under the same rules as the editor (its own origin, 32 MB), and a chain whose archive is no longer connected stops and says to connect it again.
+- **umtool e2e: the Inbox spec waits for the list after a Park, Mute or Undo.** Three runs failed where the list had not changed 5 seconds after Reactivate, Unmute or Undo. In each the write had been saved and the page's refresh had been asked for; the server was slow for those seconds (a neighbouring suite was building) and the check gave up first. The first look at the list after such a write now waits up to 20 seconds. Nothing in the app changed: the lifecycle and the mutes are read from disk on every render, and the rail's count is memoised for 10 seconds by design and cleared by those writes.
+- **umtool: the trail no longer draws a 0 lb point for a row with no number.** A measure event whose value was empty was read as 0 and plotted at the foot of the trail. Such a row is now left off; a real 0 is still drawn.
+- **umtool: `posts attach` finds captures in the archive too.** On a project with its own channels tree (a `.shadow-channels`), `umtool posts attach` and `posts repeats` looked for a post's capture only there, so media captured into the real archive's `channels/<slug>/posts-media/<id>/` was not seen. They now look in the project's tree first and then the archive's, as the other readers do. The archive is only read: the files are copied into the project as before. `--dry-run` prints which tree each file would come from. A capture whose file name is not a plain name (`../../x`, `a/b`, `..`) is refused before any file is read or any folder made.
+- **umtool: an entry's chapter name is set from a terminal.** An entry's `chapter` names it in the chapter list (the YouTube text, `umtool export --format chapters`) in place of its on-screen title, and it could only be written by editing the manifest by hand. `umtool set <p> <entry> chapter='The weigh-in'` writes it for any entry (a clip, a post item, a still), `chapter=` clears it, and `--take <t>` writes it on that take alone. One line, at most 100 characters.
+- **umtool: a windowed take preview no longer fails on an effect that names a clip outside the window.** `umtool take <p> --id <t> --preview --at S --dur S` on a cut with `render.chrome.fx.glitch.clips` or `fx.thenNow.pairs` was refused with "names k06, which is not a clip of the cut". The window's manifest now keeps only the named clips inside it (a glitch's only when a clip stands right before it in the window, a then/now pair only with both ends), as it already did for markers and claim checks; an effect left naming no clip is off in that window. A glitch in another mode (`on: "year"`) does not read its list and is left as it is. The same for `fx.kineticQuote.clips` and `fx.redact.clips`.
+- **umtool: `quote-check` works on a project whose `out/` is on the media drive.** The check asked the editor to write its word files under `<project>/out/quote-check/`; when `out/` is a link onto a media drive, that is inside the corpus and the editor refuses to write there, so every clip failed. The work files now go to `<project>/.quote-check/`, and if the editor refuses that too (the project itself is inside the corpus) to `<reports>/.umtool/quote-check/<project>/`, then `~/.cache/umtool/quote-check/<project>/`. The rows are still the project's `quote-check.json`; the editor's refusal is unchanged. A directory the editor refuses is removed again if the check made it, so no empty `.quote-check/` is left on the media drive.
+- **umtool: the words under the promise clock's REFUNDED stamp can be the record's own.** The stamp always read "by <date> · no video" under REFUNDED or WITHDRAWN, whatever the outcome row said. A `promise_outcome` row may now carry `stampNote` (`umtool ledger <p> set <row> --stampNote "by her account · no receipt"`, `--stampNote null` to take it off): it is the stamp's second line, and the one-line strip over a post's card shows its first clause. Without one the words are as before. `umtool lint` warns when a note is longer than the stamp's line holds (26 characters).
+- **umtool: a loss goal no longer takes its base from a weight said years before.** A goal such as "lose 100" is shown against the latest weight he had given by then, however old: on the weight video that put "(FROM 368)" on a goal set eight years after he said 368. `deck.goals.baseMaxDays` (unset: as before) keeps a base only when its weight was said at most that many days before the goal; an older one is no base, so the note carries no "(FROM …)" and the dial draws no goal weight or tick from it. `umtool look <p> deck.goals.baseMaxDays=365`, and `umtool look` now takes `--take <t>` for the deck's keys, which sets them on that take alone.
+- **umtool: the dial's finale no longer shows the callout's labels over its hub.** With `deck.dial.rememberedAs: "callout"` the finale's dial drew every remembered weight's label box and the ghost needle and never hid them, so the boxes sat on the hub for the whole finale (take rev9-a9). They are hidden there now; the rim's marker and flag for the last remembered weight stay.
+- **umtool: record, filter and listen before anything is kept.** On the record page a recording became a take the moment its last part was in, and hearing it in the character's voice meant importing it on the Voices page and waiting for three takes (operator, 11 Nov: "run the filter and preview it seamlessly in the record UI"). With **Filter before keeping** (on by itself for a post whose character has a stock voice to convert to) the post now waits. **Filter** (`f`) runs the character's recorded preset as one job: clean, cut, convert. Its result is a preview in `narration/.record-preview/<postId>.<label>/`, not a take. The page shows the three stages and the time it has run, and a wait at the editor's queue or the machine's heavy slot reads "waiting for memory … the gate working, not an error". **▶ Raw** and **▶ Filtered** play at one loudness. **Keep** (`Enter`) makes the recorded, cleaned and converted takes from the preview's files, converts nothing again, picks the last and opens the next post not recorded; **Again** (`Backspace` or `r`) drops the preview and records the part again. Each part's waveform carries two **cut marks** at the auto trim's answer; drag one, or press the arrow keys on it, to cut a keyboard click off the start or the end. **Pitch** and **semitones** (a Seed-VC convert) default to the preset's and re-run the convert alone; **Save to character** writes them back, and a post read as the narrator or as nobody offers **Keep in this video only**. Above the record button: the character, its direction line and **▶ <voice> reads it** (its synthetic preset's voice), which plays the read kept from before when there is one and asks the editor only when pressed. Cancel stops the editor's job too. Opened over http from the LAN the page says the microphone is off (a browser opens it only on localhost or https); **Use a sound file…** takes a recording made elsewhere, and Filter, the preview and Keep work there. From a terminal: `umtool posts narrate <p> <item> --recording <file> --preview [--out <file>] [--trim-span 0.4-3.1]` prints the paths and makes no take, `--keep-preview` keeps it, `--discard-preview` drops it. A "start on speech" trigger was not built: it would lose the start of the first word, and the auto trim already cuts the silence before it. ([knobs.md](../umtool/docs/knobs.md#record-filter-preview-on-the-record-page))
+- **umtool: a convert made from a take uses its character's voice, not the editor's default.** On 11 Nov `umtool posts narrate <p> <item> --derive <n> --op convert` with no flags made a take in the wrong voice: it asked the editor with nothing, and the editor used its own default target. A convert now takes its engine, stock voice, pitch and semitones from the recorded preset of the character the read is made as (`--as`, else the item's own, this video's for the author, the cast's, the narrator); a flag overrides its own key. With no character and no `--voice` it is refused in one sentence. The post bench's **run AI on take** does the same on the server.
+- **Lookouts: a saved set of channels and days, and a dry run that lists what it would read.** A lookout (lane/lookout) will read its channels' recent transcripts and answer with video ideas; this first part has no model. `settings.lookouts` holds the lookouts (off and empty by default; nothing in code names a channel), and `pnpm ops lookout-run --json '{"id":"…","dryRun":true}'` lists the week it would read: every video by its AIR date in the lookout's time zone (a stream that starts at 8:20 pm in New York is 3 Nov, not the 4 Nov of its UTC upload date), a recording uploaded twice read once with the other upload named beside it, a stream's cut-downs credited to the stream, the longest 40 read and every one left out listed with why. Over the pilot's week, read-only, it found all 6 of the pilot's duplicate uploads and all 18 of its stream cut-downs. `pnpm ops get lookouts` is the readout. Runs and verdicts will live in `transcripts/.lookouts/`, never published.
+- **umtool: a character is a preset, and a video can have characters of its own.** The operator wanted "a preset of voice and other settings" per character, applied to that author's posts, anonymous characters with their own profile per video, a pool reused across videos, and different presets for synthetic and recorded voices. A cast character now carries two presets. `synthetic` is the stock voice and its speed. `recorded` is what a recording of them is made into: the stock voice it is converted to, the engine, the pitch and semitones, whether it is cleaned first, whether its edges are trimmed and how much room is kept, and a one-line direction for the person reading, which is never sent to a model. An existing `cast.json` (`voice`, `convert`) reads as these presets, and the first write makes it version 2; `umtool cast undo` puts the old file back. A video's own characters live in `<project>/narration/characters.json`, for people who must not enter the pool. An anonymous one goes by a shown name, "Anon 1", "Anon 2" by default, on the Voices page, in `umtool cast project` and in a recording's note, and is refused the pool. `narration/voices.json` keeps working and is not rewritten. A post item can name its own character (`umtool posts character <p> <item> <id>`, `--clear`). One read asks, first hit wins: the command's flags, the item's character, the video's character for the author, the cast's, the narrator's, the default. `umtool cast project <p>` prints the answer and its source for each author. A thread read ignored `--speed`: each part is now asked at its character's speed, and `--speed` sets every part. A recording made a read (`posts narrate --recording`) applies its character's clean and trim settings; `--clean`, `--no-clean`, `--trim` and `--no-trim` override them for one read. The Voices page edits both presets, keeps the video's own characters, and has "Add to the pool" and "Keep in this video only"; none of it needs an agent. New: `umtool cast set <id> --speed --enhance --trim --trim-pad --direction`, `umtool cast project <p> add|set|rm|undo|pool|keep`. A convert target is still always a stock synthetic voice, and the disclosure line is unchanged. Not built yet: the on-screen card is not anonymised (a cut still shows the post's author for an anonymous character), and the record page does not show the direction (umtool/docs/knobs.md, "A character is a preset").
+- **A converted read can follow your pitch.** Converting a recorded read to a stock voice threw the voice acting away. On 11 Nov, reads with a median pitch of 128, 212, 225 and 237 Hz all came out at 196–199 Hz, and a 152–321 Hz range came out as 165–240 Hz: both converters speak at the stock voice's own pitch. `pnpm ops voice-convert` now takes `"pitch"`: `target` (as before), `source` (the pitch you read at: raise your voice and the result rises) or `contour` (your rises and falls, moved as a whole to the stock voice's register), and `"semitones"` (-12 to 12) moves a followed pitch. The same read that came out at 197 Hz now comes out at 211 Hz with a 148–314 Hz range, against 212 Hz and 152–321 Hz read. `source` and `contour` are seed-vc's, on its f0-conditioned model: optional files, fetched by `archilyzer voice setup --engine seed-vc --with f0` (1.49 GB). An install without them converts as before, and a followed pitch is refused naming that command; openvoice refuses a pitch it cannot follow. It takes about 1.7 times as long, and more memory (5.8 GB at its peak on a take of 20 s or more). `settings.voice.convert.pitch` and `.semitones` are the defaults (`target`, 0). In umtool a character keeps its pitch in the cast (`umtool cast set <id> --convert-pitch contour --convert-semitones 2`, shown on Voices), and `--pitch` / `--semitones` on `posts narrate … --recording` or `--derive <n> --op convert` set it for one read; the post bench's **run AI on take** has the same two controls for a convert on seed-vc, starting from the character's. The disclosure line is unchanged.
- **The dashboard says when a media drive is not answering, slow, or not mounted.** A stalled external drive used to show only on `/storage` and in channel badges, so the editor looked broken with nothing on its front page saying why. The dashboard now opens with one card per storage location in trouble: **not answering** (an alert: pages and polls skip the drive, and its channels' jobs wait until it answers), **answering slowly** (everything still runs, just late), or **not mounted** (only when some channel's media is on it). Each card links to `/storage` and to that location's channels. On `/storage` each location has a **Drive** line that says when the drive last answered and how long it took (for example "answering — 12 ms (a read in the editor), last at 11:42"), and a **slow** chip appears next to Available when two reads in a row on it take half the 3-second limit or more (one long read is not enough). `pnpm ops get storage` reports the same for each location under `rows[].drive`: `state` (`ok`, `slow`, `stalled` or `unmounted`), `since`, `lastOkAt`, `latencyMs`, the cause and the one-line text.
- **A transcription or backfill run waits while its channel's media drive is not answering.** Before, a run that started while the drive answered kept going after the drive stalled. Each next video asked the stalled drive for its audio, waited about 30 seconds and failed. Now the run pauses at the next video and says so in its log ("Holding: the media drive "…" is not answering (since 11:35) — no new transcription starts until it answers again"), then resumes by itself when the drive answers. If it has held for 5 minutes, the run checks the drive itself from a separate process, and it logs that it is still holding every 10 minutes. A run also follows a channel that is moved to another drive while it runs. A video that is refused because the drive is not answering is skipped, not added to the channel's failed-transcriptions list, and is transcribed on a later run. A downloaded video is also not moved into a saved-video store on a drive that is not answering. It stays in the video's folder, and a later pass stores it.
- **The drive watch no longer overwrites a tier you change while it is pausing channels.** The five-minute storage watch, which pauses the channels on a drive that went away and restores them when it comes back, could save its change in the middle of yours and undo it. It now waits for the same settings lock that the channel-priority save uses. The editor's `dev` script also gives Node 16 file-access threads, as `start`, the systemd unit and the container already do.
diff --git a/editor/app/api/media/fetch-window/route.remote.test.ts b/editor/app/api/media/fetch-window/route.remote.test.ts
@@ -0,0 +1,147 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/media/fetch-window/route.remote.test.ts"
+//
+// demo epic D1: the single window (the MCP's fetch_clip over a remote source)
+// of a channel this editor does not hold, named with its connected archive —
+// registered remote-only; its Rumble whole recording refused with the size
+// (409, no job). The archive is a fake fetch.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetch-window-remote-"));
+process.env.WORKER_TOKEN = "test-token";
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+delete process.env.TRANSCRIPT_SITE_URL;
+// yt-dlp is a fake that writes down what it was asked for: no test here reaches a platform.
+const ARGS_LOG = path.join(ROOT, "argv.jsonl");
+const YTDLP = path.join(ROOT, "fake-ytdlp.mjs");
+await writeFile(
+ YTDLP,
+ `#!/usr/bin/env node
+import { appendFileSync, writeFileSync } from "node:fs";
+const args = process.argv.slice(2);
+appendFileSync(${JSON.stringify(ARGS_LOG)}, JSON.stringify(args) + "\\n");
+const o = args.indexOf("-o");
+if (o >= 0) writeFileSync(args[o + 1], "mp4");
+`,
+);
+await chmod(YTDLP, 0o755);
+process.env.YTDLP_BIN = YTDLP;
+process.env.E2E_CLIP_WINDOW_GAP_MS = "0";
+const ORIGIN = "https://stub.test";
+await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0, remoteArchives: [{ id: "stub", origin: ORIGIN, title: "Stub", addedAt: "2026-11-11T00:00:00Z" }] }));
+const DOCS: Record<string, unknown> = {
+ [`${ORIGIN}/corpus.json`]: {
+ spec: 6,
+ channels: [
+ { slug: "rb-remote", name: "RB Remote", platform: "rumble", manifests: { transcripts: `${ORIGIN}/transcripts/rb-remote/manifest.json` } },
+ { slug: "yt-evil", name: "Evil", platform: "youtube", manifests: { transcripts: `${ORIGIN}/transcripts/yt-evil/manifest.json` } },
+ ],
+ },
+ [`${ORIGIN}/transcripts/yt-evil/manifest.json`]: { slugToPage: { e1: 0, d1: 0, d2: 0, n1: 0 } },
+ [`${ORIGIN}/transcripts/yt-evil/page-0000.json`]: [
+ { id: "e1", webpageUrl: "http://169.254.169.254/latest/meta-data/" },
+ // Read as youtube.com by Node's URL parser, as another host by Python's (re-check, the parser differential).
+ { id: "d1", webpageUrl: "https://youtube.com\\@evil.example/watch?v=d1" },
+ { id: "d2", webpageUrl: "https://you\ttube.com/watch?v=d2" },
+ // The platform's own page, spelled loudly.
+ { id: "n1", webpageUrl: "HTTPS://WWW.YouTube.com:443/watch?v=n1" },
+ ],
+ [`${ORIGIN}/transcripts/rb-remote/manifest.json`]: { slugToPage: { rb9: 0 } },
+ [`${ORIGIN}/transcripts/rb-remote/page-0000.json`]: [{ id: "rb9", duration: 600, webpageUrl: "https://rumble.com/vrb9-x.html" }],
+};
+const asked: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL) => {
+ const url = String(input);
+ asked.push(url);
+ return url in DOCS ? new Response(JSON.stringify(DOCS[url]), { status: 200 }) : new Response("nope", { status: 404 });
+}) as typeof fetch;
+const { POST } = await import("./route");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const post = async (body: Record<string, unknown>) => {
+ const res = await POST(
+ new Request("http://localhost/api/media/fetch-window", {
+ method: "POST",
+ headers: { authorization: "Bearer test-token", "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+ return { status: res.status, json: (await res.json()) as { error?: string } };
+};
+
+test("a single window of an archive's channel registers it remote-only, and its Rumble whole recording is refused with the size", async () => {
+ const r = await post({ channelSlug: "rb-remote", videoId: "rb9", from: 10, to: 20, requestedBy: "test", reason: "a test", archive: ORIGIN });
+ assert.equal(r.status, 409, r.json.error);
+ assert.match(r.json.error ?? "", /^whole recording refused: Rumble windows are cut from the WHOLE recording, and rb-remote is a remote-only channel: rb-remote\/rb9 is 10:00 long/);
+ const config = JSON.parse(await readFile(path.join(ROOT, "channels", "rb-remote", "config.json"), "utf8"));
+ assert.equal(config.remoteOnly, true);
+ assert.equal(config.remoteArchive, ORIGIN);
+});
+
+test("without its archive named, a channel not held is a 404 as before", async () => {
+ const r = await post({ channelSlug: "nope-remote", videoId: "x1", from: 10, to: 20, requestedBy: "test", reason: "a test" });
+ assert.equal(r.status, 404);
+});
+
+test("a single window whose archive record points at a non-platform host is refused (400), nothing fetched", async () => {
+ const r = await post({ channelSlug: "yt-evil", videoId: "e1", from: 10, to: 20, requestedBy: "test", reason: "a test", archive: ORIGIN });
+ assert.equal(r.status, 400);
+ assert.match(r.json.error ?? "", /^yt-evil\/e1: 169\.254\.169\.254 is not a video platform's host/);
+});
+
+test("a page URL two parsers read differently is refused (400) before any request, from the record or from the ask", async () => {
+ const ask = (videoId: string, webpageUrl?: string) => post({ channelSlug: "yt-evil", videoId, from: 10, to: 20, requestedBy: "test", reason: "a test", archive: ORIGIN, ...(webpageUrl ? { webpageUrl } : {}) });
+ for (const r of [
+ await ask("d1"),
+ await ask("d2"),
+ await ask("a1", "https://youtube.com\\@evil.example/watch?v=x"),
+ await ask("a2", "https://youtube.com\\@127.0.0.1/x"),
+ await ask("a3", "https://rumble.com\\.evil.example/v1"),
+ await ask("a4", "https://you\ttube.com/watch?v=x"),
+ ]) {
+ assert.equal(r.status, 400, r.json.error);
+ assert.match(r.json.error ?? "", /carries a backslash, whitespace or a control character/);
+ }
+ assert.equal(await readFile(ARGS_LOG, "utf8").catch(() => ""), "", "yt-dlp was never run");
+});
+
+test("what reaches yt-dlp is the URL the check parsed, written back — never the record's own string", async () => {
+ const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry");
+ const res = await POST(
+ new Request("http://localhost/api/media/fetch-window", {
+ method: "POST",
+ headers: { authorization: "Bearer test-token", "content-type": "application/json" },
+ body: JSON.stringify({ channelSlug: "yt-evil", videoId: "n1", from: 10, to: 20, requestedBy: "test", reason: "a test", archive: ORIGIN }),
+ }),
+ );
+ const body = (await res.json()) as { jobId?: string; error?: string };
+ assert.equal(res.status, 202, body.error);
+ const reg = getRegistry();
+ for (let i = 0; i < 200; i++) {
+ const s = reg.get(body.jobId!)?.status;
+ if (s !== "queued" && s !== "running") break;
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ const runs = (await readFile(ARGS_LOG, "utf8")).trim().split("\n").map((l) => JSON.parse(l) as string[]);
+ assert.ok(runs.length > 0, "yt-dlp was asked");
+ for (const args of runs) {
+ assert.equal(args.at(-1), "https://www.youtube.com/watch?v=n1");
+ assert.equal(args.some((a) => /YouTube|:443/.test(a)), false, "the record's own spelling is nowhere in the command");
+ }
+});
+
+// LAST: it disconnects the archive for the rest of the file.
+test("a remote-only channel whose archive was removed from settings is refused (400), and the archive is not read", async () => {
+ await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ remoteArchives: [] }));
+ asked.length = 0;
+ const r = await post({ channelSlug: "rb-remote", videoId: "rb9", from: 10, to: 20, requestedBy: "test", reason: "a test" });
+ assert.equal(r.status, 400, r.json.error);
+ assert.match(r.json.error ?? "", /^rb-remote is a remote-only channel, and its archive https:\/\/stub\.test is no longer connected/);
+ assert.deepEqual(asked, [], "nothing asked of an archive that is not connected");
+});
diff --git a/editor/app/api/media/fetch-window/route.ts b/editor/app/api/media/fetch-window/route.ts
@@ -18,6 +18,20 @@ import {
type FetchMediaOutcome,
} from "../../../channels/[slug]/videos/[id]/videoActions";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { detectPlatform } from "yt-dlp-transcript-common/lib/platform";
+import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig";
+import { connectedArchives, disconnectedArchiveRefusal, findConnectedArchive, recordPage } from "yt-dlp-transcript-common/lib/remoteArchives";
+import { cachedArchiveGetJson } from "yt-dlp-transcript-common/lib/archiveCache-server";
+import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
+import { wholeRecordingFor } from "yt-dlp-transcript-common/controller/fetchWindows";
+import {
+ archiveRecordOf,
+ ensureRemoteOnlyChannel,
+ wholeRecordingRefusal,
+} from "yt-dlp-transcript-common/controller/remoteOnlyChannel";
+
export const dynamic = "force-dynamic";
// SOURCE MEDIA FOR ANOTHER TOOL, fetched through the editor's managed download
@@ -59,6 +73,10 @@ type Body = {
full?: unknown;
maxHeight?: unknown;
storedUrl?: unknown;
+ // demo epic D1: the connected archive the clip is cited from, and the
+ // allowance for a remote-only channel's whole recording.
+ archive?: unknown;
+ allowWholeRecording?: unknown;
};
const str = (v: unknown): string | undefined =>
@@ -186,6 +204,62 @@ export async function POST(request: Request) {
);
}
+ // A CONNECTED ARCHIVE'S CLIP (demo epic D1; `archive`, the MCP's fetch_clip
+ // over a remote source): a channel this editor does not hold is registered
+ // remote-only of it (controller/remoteOnlyChannel.ts), as fetch-windows does.
+ // A remote-only channel's page URL is the ask's, else its archive's record;
+ // its whole recording — `full`, or a window on a whole-recording platform —
+ // is refused with the recording's size (409) unless `allowWholeRecording`.
+ let webpageUrl = str(body.webpageUrl);
+ {
+ const paths = getPaths();
+ const getJson = cachedArchiveGetJson();
+ const named = str(body.archive);
+ let config = await readChannelConfig(paths, channelSlug);
+ if (!config && named) {
+ const archive = findConnectedArchive(connectedArchives(getSettings().remoteArchives), named);
+ if (archive) {
+ try {
+ config = (await ensureRemoteOnlyChannel(paths, channelSlug, archive, { getJson })).config;
+ } catch (e) {
+ return NextResponse.json({ error: `Channel "${channelSlug}" not found, and it could not be registered from ${archive.origin}: ${(e as Error).message}` }, { status: 404 });
+ }
+ }
+ }
+ if (config && isRemoteOnlyChannel(config)) {
+ // An archive removed from settings is not read any more, for a channel
+ // registered while it was connected either.
+ const gone = disconnectedArchiveRefusal(config.remoteArchive, connectedArchives(getSettings().remoteArchives));
+ if (gone) return NextResponse.json({ error: `${channelSlug} is a remote-only channel, and ${gone}` }, { status: 400 });
+ const record = config.remoteArchive ? await archiveRecordOf(config.remoteArchive, channelSlug, videoId, { getJson }).catch(() => null) : null;
+ webpageUrl ||= record?.webpageUrl;
+ // An archive is untrusted input (demo epic D1 review): its page URL must
+ // name the channel's own video platform's host, before any request.
+ const page = recordPage(webpageUrl, config.platform ?? null, detectPlatform);
+ if ("refused" in page) return NextResponse.json({ error: `${channelSlug}/${videoId}: ${page.refused}` }, { status: 400 });
+ // From here on the URL is the one the check parsed, written back — never
+ // the string the archive or the ask gave (another parser may read that
+ // one as another host).
+ webpageUrl = page.href;
+ const platform = page.platform;
+ const whole = body.full === true || wholeRecordingFor(getSettings(), platform, {}, undefined);
+ if (whole && body.allowWholeRecording !== true) {
+ return NextResponse.json(
+ {
+ error: wholeRecordingRefusal({
+ platform,
+ slug: channelSlug,
+ id: videoId,
+ ...(record?.duration !== undefined ? { duration: record.duration } : {}),
+ ...(typeof body.maxHeight === "number" ? { maxHeight: body.maxHeight } : {}),
+ }),
+ },
+ { status: 409 },
+ );
+ }
+ }
+ }
+
if (body.full === true) {
// A cap at or under 720 asks for "video_720"; one above it asks for
// "original" in so many words. No cap: the channel's, else the global,
@@ -233,7 +307,7 @@ export async function POST(request: Request) {
await fetchWindowAction({
slug: channelSlug,
videoId,
- webpageUrl: str(body.webpageUrl),
+ webpageUrl,
from,
to,
provenance,
diff --git a/editor/app/api/ops/_localMediaDoors.test.ts b/editor/app/api/ops/_localMediaDoors.test.ts
@@ -0,0 +1,86 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, readdir, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { callPost, setupOpsCorpus } from "./_testCorpus";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_localMediaDoors.test.ts"
+//
+// lane/local-media review fix 5: every door that would fetch, transcribe,
+// persist or write media refuses a local media library channel and a local
+// recording with lib/localMedia.ts's ONE sentence ("... with no online source,
+// so no clip can be fetched for it."), or its sibling for the metadata doors
+// ("... so its metadata cannot be read from one."), never a generic empty-URL
+// failure; and attach-media / import-media refuse a record linked to a library
+// original (external-media.json). Through each ops route; no job is queued and
+// no record changes.
+
+const corpus = await setupOpsCorpus(null);
+test.after(() => corpus.cleanup());
+const route = async (name: string) => (await import(`./${name}/route`)).POST;
+
+const LOCAL = "local-" + "e".repeat(32);
+const lib = { sourceId: "library-1", directory: path.join(corpus.root, "library") };
+await mkdir(lib.directory, { recursive: true });
+await corpus.writeChannelConfig("library", { name: "Library", handling: "youtube", url: undefined, sourceKind: "video", localMedia: lib });
+await corpus.writeChannelConfig("hybrid", { name: "Hybrid", handling: "youtube", url: "https://www.youtube.com/@hybrid", platform: "youtube", localMedia: lib });
+const record = async (slug: string, id: string, meta: unknown, extra: Record<string, string> = {}) => {
+ const dir = path.join(corpus.transcripts, "channels", slug, "data", id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(meta));
+ await writeFile(path.join(dir, "transcript.en.vtt"), "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nA cue\n");
+ for (const [name, body] of Object.entries(extra)) await writeFile(path.join(dir, name), body);
+};
+await record("library", "aaaaaaaaaaa", { id: "aaaaaaaaaaa", title: "Provider", upload_date: "20200101", webpage_url: "https://www.youtube.com/watch?v=aaaaaaaaaaa" });
+await record("hybrid", LOCAL, { id: LOCAL, title: "Talk", local_recording: { version: 1, titleSource: "filename", inspection: "manual", durationSource: "unknown" } });
+await record("hybrid", "linkedrec01", { id: "linkedrec01", title: "Linked", upload_date: "20200101", webpage_url: "https://www.youtube.com/watch?v=linkedrec01" },
+ { "external-media.json": JSON.stringify({ version: 1, kind: "external", sourceId: "library-1", relativePath: "linked.mp4" }) });
+const FILE = path.join(corpus.root, "a-file.mp4");
+await writeFile(FILE, "not really a video");
+
+const FETCH = /with no online source, so no clip can be fetched for it\.$/;
+const METADATA = /with no online source, so its metadata cannot be read from one\.$/;
+const LINKED = /^"hybrid\/linkedrec01" is linked to a local media library original \(external-media\.json\), so no media is written into it\.$/;
+const CHANNEL = /^"library" is a local media library channel /;
+const RECORD = new RegExp(`^"${LOCAL}" is a local recording `);
+
+const DOORS: Array<[string, Record<string, unknown>, RegExp, RegExp]> = [
+ ["transcribe-one", { slug: "library", id: "aaaaaaaaaaa" }, CHANNEL, FETCH],
+ ["transcribe-one", { slug: "hybrid", id: LOCAL }, RECORD, FETCH],
+ ["prepare-playable", { slug: "library" }, CHANNEL, FETCH],
+ ["prepare-playable", { slug: "hybrid", ids: [LOCAL] }, RECORD, FETCH],
+ ["persist-videos", { items: [{ slug: "library", id: "aaaaaaaaaaa" }] }, CHANNEL, FETCH],
+ ["persist-videos", { items: [{ slug: "hybrid", id: LOCAL }] }, RECORD, FETCH],
+ ["refresh-metadata", { slug: "library", id: "aaaaaaaaaaa" }, CHANNEL, METADATA],
+ ["refresh-metadata", { slug: "hybrid", id: LOCAL }, RECORD, METADATA],
+ ["metadata-scan", { slug: "library" }, CHANNEL, METADATA],
+ ["browser-lookup", { slug: "library", listing: true }, CHANNEL, METADATA],
+ ["browser-lookup", { slug: "hybrid", ids: [LOCAL] }, RECORD, METADATA],
+ ["fetch-chat", { slug: "library", id: "aaaaaaaaaaa" }, CHANNEL, FETCH],
+ ["fetch-chat", { slug: "hybrid", id: LOCAL }, RECORD, FETCH],
+ ["live-clip", { slug: "library", id: "aaaaaaaaaaa", start: 1, end: 5 }, CHANNEL, FETCH],
+ ["live-clip", { slug: "hybrid", id: LOCAL, start: 1, end: 5 }, RECORD, FETCH],
+ ["import-media", { slug: "library", path: FILE, id: "aaaaaaaaaaa" }, CHANNEL, FETCH],
+ ["import-media", { slug: "hybrid", path: FILE, id: LOCAL }, RECORD, FETCH],
+ ["import-media", { slug: "hybrid", path: FILE, id: "linkedrec01" }, LINKED, LINKED],
+ ["attach-media", { slug: "library", source: corpus.root }, CHANNEL, FETCH],
+ ["attach-media", { slug: "hybrid", source: corpus.root, items: [{ id: LOCAL, path: "a-file.mp4" }] }, RECORD, FETCH],
+ ["attach-media", { slug: "hybrid", source: corpus.root, items: [{ id: "linkedrec01", path: "a-file.mp4" }] }, LINKED, LINKED],
+];
+
+test("every door refuses a local library channel, a local recording and (writers) a linked record, with the one sentence", async () => {
+ const before = await corpus.listJobIds();
+ const dirs = async () => (await readdir(path.join(corpus.transcripts, "channels", "hybrid", "data", "linkedrec01"))).sort();
+ const linkedBefore = await dirs();
+ for (const [name, body, who, sentence] of DOORS) {
+ const r = await callPost(await route(name), body);
+ const label = `${name} ${JSON.stringify(body)} -> ${r.status} ${JSON.stringify(r.body)}`;
+ assert.equal(r.body.ok, false, label);
+ assert.match(String(r.body.error), who, label);
+ assert.match(String(r.body.error), sentence, label);
+ assert.doesNotMatch(String(r.body.error), /Could not determine the video URL|no `url` configured/, label);
+ }
+ assert.deepEqual(await corpus.listJobIds(), before, "no job was queued");
+ assert.deepEqual(await dirs(), linkedBefore, "the linked record is unchanged");
+});
diff --git a/editor/app/api/ops/_lookouts.test.ts b/editor/app/api/ops/_lookouts.test.ts
@@ -0,0 +1,92 @@
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_lookouts.test.ts"
+//
+// `pnpm ops get lookouts` and `pnpm ops lookout-run` (the dry run, the only
+// one there is yet), against the route handlers over a temp corpus. Every
+// channel and lookout here is invented. Never the live editor's settings.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, readdir, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { callGet, callPost, setupOpsCorpus } from "./_testCorpus";
+
+const corpus = await setupOpsCorpus(null);
+const { GET } = await import("./lookouts/route");
+const { POST } = await import("./lookout-run/route");
+test.after(() => corpus.cleanup());
+
+const LOOKOUTS = {
+ enabled: false,
+ afterSync: false,
+ items: [{ id: "example-week", label: "Example week", channels: ["example-news", "no-such-channel"], days: 3, timeZone: "America/New_York" }],
+};
+
+async function video(slug: string, dir: string, title: string, uploadDate: string, timestamp: number, seconds: number) {
+ const d = path.join(corpus.transcripts, "channels", slug, "data", dir);
+ await mkdir(d, { recursive: true });
+ await writeFile(path.join(d, "metadata.info.json"), JSON.stringify({ id: dir, title, duration: seconds, upload_date: uploadDate, timestamp }));
+ const cues = Array.from({ length: 40 }, (_, i) => ({ start: i * (seconds / 40), end: (i + 1) * (seconds / 40), text: `${title} line ${i} of ${dir}` }));
+ await writeFile(
+ path.join(d, "transcript.cues.json"),
+ JSON.stringify({ version: 2, id: dir, title, uploadDate, duration: seconds, platform: "youtube", webpageUrl: `https://example.invalid/${dir}`, cues }),
+ );
+}
+
+test("get lookouts: the saved lookouts and what the store holds for each; nothing configured is an empty list", async () => {
+ const empty = await callGet(GET!, "http://localhost/api/ops/lookouts");
+ assert.equal(empty.status, 200, JSON.stringify(empty.body));
+ assert.deepEqual(empty.body.lookouts, []);
+ assert.equal(empty.body.enabled, false);
+
+ await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS });
+ const r = await callGet(GET!, "http://localhost/api/ops/lookouts");
+ assert.equal(r.status, 200, JSON.stringify(r.body));
+ const [one] = r.body.lookouts as Record<string, unknown>[];
+ assert.equal(one!.id, "example-week");
+ assert.equal(one!.maxVideos, 40, "the defaults the settings filled");
+ assert.equal(one!.lastRun, null);
+ assert.equal(one!.runs, 0);
+ assert.equal(one!.unruled, 0);
+ assert.equal((await callGet(GET!, "http://localhost/api/ops/lookouts?id=nope")).status, 404);
+ assert.equal((await callGet(GET!, "http://localhost/api/ops/lookouts?lookout=x")).status, 400);
+});
+
+test("lookout-run: the dry run lists what would be read, on air dates, and writes nothing", async () => {
+ await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS });
+ await corpus.writeChannelConfig("example-news", {});
+ // 2026-11-04T01:20:53Z is the evening of 3 Nov in New York.
+ await video("example-news", "Evening0001", "Evening Show", "20261104", 1793755253, 1200);
+ await video("example-news", "Short000001", "A Short", "20261104", 1793790000, 45);
+ const before = await readdir(corpus.transcripts);
+ const r = await callPost(POST!, { id: "example-week", dryRun: true, until: "2026-11-05" });
+ assert.equal(r.status, 200, JSON.stringify(r.body));
+ const plan = r.body.plan as {
+ window: { from: string; to: string };
+ read: { video: string; airDate: string }[];
+ skipped: { video: string; reason: string }[];
+ refused: { channel: string }[];
+ };
+ assert.deepEqual(plan.window, { from: "2026-11-03", to: "2026-11-05", days: 3, timeZone: "America/New_York" });
+ assert.deepEqual(plan.read.map((v) => [v.video, v.airDate]), [["Evening0001", "2026-11-03"]]);
+ assert.deepEqual(plan.skipped.map((v) => [v.video, v.reason]), [["Short000001", "under-min-seconds"]]);
+ assert.deepEqual(plan.refused.map((x) => x.channel), ["no-such-channel"]);
+ assert.deepEqual(await readdir(corpus.transcripts), before, "no store, no job, nothing written");
+ assert.deepEqual(await corpus.listJobIds(), []);
+});
+
+test("lookout-run refuses before reading anything: no dryRun, an unknown lookout or key, bad overrides", async () => {
+ await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS });
+ const run = await callPost(POST!, { id: "example-week" });
+ assert.equal(run.status, 400);
+ assert.match(String(run.body.error), /dryRun/);
+ assert.equal((await callPost(POST!, { id: "example-week", dryRun: false })).status, 400);
+ assert.equal((await callPost(POST!, { id: "nope", dryRun: true })).status, 404);
+ assert.equal((await callPost(POST!, { id: "example-week", dryRun: true, model: "x" })).status, 400);
+ assert.equal((await callPost(POST!, { id: "example-week", dryRun: true, days: 99 })).status, 400);
+ assert.equal((await callPost(POST!, { id: "example-week", dryRun: true, maxVideos: 0 })).status, 400);
+ assert.equal((await callPost(POST!, { id: "example-week", dryRun: true, until: "11/05/2026" })).status, 400);
+ await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: { items: [{ id: "empty", channels: [] }] } });
+ const none = await callPost(POST!, { id: "empty", dryRun: true });
+ assert.equal(none.status, 400);
+ assert.match(String(none.body.error), /names no channels/);
+});
diff --git a/editor/app/api/ops/archives/route.ts b/editor/app/api/ops/archives/route.ts
@@ -0,0 +1,61 @@
+import { NextResponse } from "next/server";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { connectedArchives } from "yt-dlp-transcript-common/lib/remoteArchives";
+import { ArchiveProbeError } from "yt-dlp-transcript-common/lib/remoteArchives-server";
+import {
+ RemoteArchiveError,
+ connectRemoteArchive,
+ removeRemoteArchive,
+ type RemoteArchiveDeps,
+} from "yt-dlp-transcript-common/controller/remoteArchives";
+import { saveSettings } from "../../../settings/saveSettings";
+import { OpsInputError, ops, opsFail, optBool, optString } from "../_lib";
+import { readRoute } from "../_read";
+
+export const dynamic = "force-dynamic";
+
+// THE CONNECTED ARCHIVES (demo epic D1; lib/remoteArchives.ts): the published
+// archives this machine reads as sources — Create, research and the MCP offer
+// each, a sweep over one cites it, and a window it cites registers a
+// remote-only channel to fetch it.
+//
+// GET /api/ops/archives
+// -> { ok, archives: [{ id, origin, title, addedAt, fromEnv? }] }
+// (`fromEnv`: TRANSCRIPT_SITE_URL's, listed and never stored)
+// POST { connect: "<origin>", dryRun? }
+// -> { ok, archive, probe: { origin, siteId, title, spec, generatedAt,
+// totals, channels }, already }
+// reads <origin>/corpus.json once; a hub, a cited-only site, a site with
+// no channels or an origin that does not answer is refused (400/502).
+// dryRun answers the probe and writes nothing (already: null); an origin
+// connected already writes nothing (already: true).
+// POST { remove: "<id or origin>" } -> { ok, removed }
+
+const deps = (): RemoteArchiveDeps => ({
+ stored: () => getSettings().remoteArchives,
+ save: (next) => saveSettings({ remoteArchives: next }),
+});
+
+export async function GET(request: Request) {
+ return readRoute(request, [], async () => ({ archives: connectedArchives(getSettings().remoteArchives) }));
+}
+
+export async function POST(request: Request) {
+ return ops(request, ["connect", "remove", "dryRun"], async (body) => {
+ const connect = optString(body, "connect")?.trim();
+ const remove = optString(body, "remove")?.trim();
+ if (!!connect === !!remove) throw new OpsInputError('send "connect" (an origin) or "remove" (an id or origin)');
+ try {
+ if (connect) {
+ const r = await connectRemoteArchive({ origin: connect, dryRun: optBool(body, "dryRun") === true }, deps());
+ return NextResponse.json({ ok: true, ...r });
+ }
+ if (optBool(body, "dryRun") !== undefined) throw new OpsInputError('"dryRun" goes with "connect"');
+ return NextResponse.json({ ok: true, removed: await removeRemoteArchive(remove!, deps()) });
+ } catch (e) {
+ if (e instanceof ArchiveProbeError) return opsFail(e.message, e.status);
+ if (e instanceof RemoteArchiveError) return opsFail(e.message);
+ throw e;
+ }
+ });
+}
diff --git a/editor/app/api/ops/channels/route.ts b/editor/app/api/ops/channels/route.ts
@@ -1,7 +1,7 @@
import { NextResponse } from "next/server";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels";
-import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig";
+import { isRemoteOnlyChannel, isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig";
import { siteChannelIndex } from "yt-dlp-transcript-common/lib/site";
import { opsAuth } from "../_lib";
@@ -32,13 +32,15 @@ export async function GET(request: Request) {
channels: rows.map(({ slug, config }) => ({
slug,
name: config.name ?? slug,
- kind: isSocialChannel(config) ? "social" : "video",
+ // "remote-only" (demo epic D1): a connected archive's clip windows only.
+ kind: isRemoteOnlyChannel(config) ? "remote-only" : isSocialChannel(config) ? "social" : "video",
platform: config.platform ?? null,
handling: config.handling,
url: config.url ?? null,
sites: sitesOf.get(slug) ?? [],
...(config.excludeFromBuild ? { excludeFromBuild: true } : {}),
...(config.excludeFromCleanup ? { excludeFromCleanup: true } : {}),
+ ...(isRemoteOnlyChannel(config) && config.remoteArchive ? { remoteArchive: config.remoteArchive } : {}),
})),
});
}
diff --git a/editor/app/api/ops/fetch-windows/route.remote.test.ts b/editor/app/api/ops/fetch-windows/route.remote.test.ts
@@ -0,0 +1,178 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/fetch-windows/route.remote.test.ts"
+//
+// demo epic D1 item 5: a window cited from a CONNECTED archive, of a channel
+// this editor does not hold. The archive is a fake fetch (no request leaves
+// the process); no job is queued — every run here ends refused or unresolved.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetch-windows-remote-"));
+process.env.WORKER_TOKEN = "test-token";
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+delete process.env.TRANSCRIPT_SITE_URL;
+const ORIGIN = "https://stub.test";
+await writeFile(
+ process.env.SETTINGS_FILE,
+ JSON.stringify({ remoteArchives: [{ id: "stub", origin: ORIGIN, title: "Stub", addedAt: "2026-11-11T00:00:00Z" }] }),
+);
+
+const DOCS: Record<string, unknown> = {
+ [`${ORIGIN}/corpus.json`]: {
+ spec: 6,
+ site: { id: "stub", title: "Stub" },
+ channels: [
+ { slug: "yt-remote", name: "YT Remote", videoCount: 1, platform: "youtube", url: "https://www.youtube.com/@ytr", manifests: { transcripts: `${ORIGIN}/transcripts/yt-remote/manifest.json` } },
+ { slug: "rb-remote", name: "RB Remote", videoCount: 1, platform: "rumble", manifests: { transcripts: `${ORIGIN}/transcripts/rb-remote/manifest.json` } },
+ { slug: "evil-remote", name: "Evil", videoCount: 1, platform: "youtube", manifests: { transcripts: `${ORIGIN}/transcripts/evil-remote/manifest.json` } },
+ ],
+ },
+ [`${ORIGIN}/transcripts/rb-remote/manifest.json`]: { pageCount: 1, slugToPage: { rb9: 0 } },
+ [`${ORIGIN}/transcripts/rb-remote/page-0000.json`]: [{ id: "rb9", duration: 5400, webpageUrl: "https://rumble.com/vrb9-x.html" }],
+ // An archive pointing the editor at its own API (review of 9fddc3bb, blocker 2).
+ [`${ORIGIN}/transcripts/evil-remote/manifest.json`]: { slugToPage: { e1: 0, e2: 0, e3: 0, d1: 0, d2: 0, d3: 0, n1: 0 } },
+ [`${ORIGIN}/transcripts/evil-remote/page-0000.json`]: [
+ { id: "e1", webpageUrl: "http://127.0.0.1:3001/api/ops/settings" },
+ { id: "e2", webpageUrl: "https://rumble.com/ve2-x.html" },
+ // A look-alike of the channel's platform (re-review, must-fix 1).
+ { id: "e3", webpageUrl: "https://evilyoutube.com/watch?v=e3" },
+ // Read as youtube.com by Node's URL parser, as another host by Python's (re-check, the parser differential).
+ { id: "d1", webpageUrl: "https://youtube.com\\@evil.example/watch?v=d1" },
+ { id: "d2", webpageUrl: "https://youtube.com\\@127.0.0.1/x" },
+ { id: "d3", webpageUrl: "https://you\ttube.com/watch?v=d3" },
+ // The platform's own page, spelled loudly: handed on as the parser wrote it back.
+ { id: "n1", webpageUrl: "HTTPS://WWW.YouTube.com:443/watch?v=n1" },
+ ],
+};
+const asked: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL) => {
+ const url = String(input);
+ asked.push(url);
+ if (!(url in DOCS)) return new Response("not found", { status: 404 });
+ return new Response(JSON.stringify(DOCS[url]), { status: 200 });
+}) as typeof fetch;
+
+const { POST } = await import("./route");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+async function post(body: Record<string, unknown>) {
+ const res = await POST(
+ new Request("http://localhost/api/ops/fetch-windows", {
+ method: "POST",
+ headers: { authorization: "Bearer test-token", "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+ return { status: res.status, json: (await res.json()) as Record<string, unknown> & { error?: string } };
+}
+
+type Unresolved = { item: { slug: string }; error: string }[];
+
+test("a dry run names the channel it would register, and registers nothing", async () => {
+ const r = await post({ requestedBy: "test", archive: ORIGIN, dryRun: true, items: [{ slug: "yt-remote", id: "v1", from: 1, to: 5, webpageUrl: "https://www.youtube.com/watch?v=v1" }] });
+ assert.equal(r.status, 200, r.json.error);
+ assert.deepEqual(r.json.registered, ["yt-remote"]);
+ assert.match((r.json.unresolved as Unresolved)[0].error, /would register it as a remote-only channel of https:\/\/stub\.test/);
+ await assert.rejects(readFile(path.join(ROOT, "channels", "yt-remote", "config.json")));
+ assert.deepEqual(asked, [], "a dry run reads no archive either");
+});
+
+test("an origin not connected registers nothing, and the refusal names the connect", async () => {
+ const r = await post({ requestedBy: "test", archive: "https://elsewhere.test", dryRun: true, items: [{ slug: "yt-remote", id: "v1", from: 1, to: 5 }] });
+ assert.equal(r.status, 200, r.json.error);
+ assert.deepEqual(r.json.registered, []);
+ assert.match((r.json.unresolved as Unresolved)[0].error, /not found — https:\/\/elsewhere\.test is not a connected archive: connect it/);
+});
+
+test("a run registers the remote-only channel from the archive, and refuses its Rumble whole recording with the size", async () => {
+ const r = await post({ requestedBy: "test", archive: ORIGIN, items: [{ slug: "rb-remote", id: "rb9", from: 60, to: 70 }] });
+ assert.equal(r.status, 200, r.json.error);
+ assert.deepEqual(r.json.registered, ["rb-remote"]);
+ assert.deepEqual(r.json.jobIds, [], "nothing queued");
+ const error = (r.json.unresolved as Unresolved)[0].error;
+ assert.match(error, /^whole recording refused: Rumble windows are cut from the WHOLE recording/);
+ assert.match(error, /rb-remote\/rb9 is 1:30:00 long, about 1\.7 GB \(estimated\)/);
+ const config = JSON.parse(await readFile(path.join(ROOT, "channels", "rb-remote", "config.json"), "utf8"));
+ assert.deepEqual(config, { name: "RB Remote", handling: "transcribe", platform: "rumble", remoteOnly: true, remoteArchive: ORIGIN, downloadMode: "manual" });
+ // Its page URL came from the archive's record (the item had none).
+ assert.ok(asked.includes(`${ORIGIN}/transcripts/rb-remote/page-0000.json`));
+ // The allowance, as a dry run: planned on Rumble's download queue, the archive's URL.
+ const allowed = await post({ requestedBy: "test", archive: ORIGIN, allowWholeRecording: true, dryRun: true, items: [{ slug: "rb-remote", id: "rb9", from: 60, to: 70 }] });
+ assert.equal(allowed.status, 200, allowed.json.error);
+ const groups = allowed.json.groups as { platform: string; queueKey: string; items: { webpageUrl: string }[] }[];
+ assert.equal(groups.length, 1);
+ assert.equal(groups[0].platform, "rumble");
+ assert.equal(groups[0].items[0].webpageUrl, "https://rumble.com/vrb9-x.html");
+});
+
+test("an archive's record pointing anywhere but its channel's video platform is refused before any request", async () => {
+ const r = await post({ requestedBy: "test", archive: ORIGIN, items: [{ slug: "evil-remote", id: "e1", from: 1, to: 5 }, { slug: "evil-remote", id: "e2", from: 1, to: 5 }] });
+ assert.equal(r.status, 200, r.json.error);
+ const errors = (r.json.unresolved as Unresolved).map((u) => u.error);
+ assert.match(errors[0], /127\.0\.0\.1:3001 is not a video platform's host/);
+ assert.match(errors[1], /rumble\.com is rumble, and the channel is youtube's/);
+ assert.deepEqual(r.json.jobIds, []);
+ assert.equal(asked.some((u) => u.startsWith("http://127.0.0.1")), false);
+});
+
+test("a look-alike of the channel's platform host is refused before any request", async () => {
+ const r = await post({ requestedBy: "test", archive: ORIGIN, items: [{ slug: "evil-remote", id: "e3", from: 1, to: 5 }, { slug: "evil-remote", id: "e4", from: 1, to: 5, webpageUrl: "https://www.youtube.com.evil.example/watch?v=e4" }] });
+ assert.equal(r.status, 200, r.json.error);
+ const errors = (r.json.unresolved as Unresolved).map((u) => u.error);
+ assert.match(errors[0], /^evilyoutube\.com is not a video platform's host/);
+ assert.match(errors[1], /^www\.youtube\.com\.evil\.example is not a video platform's host/);
+ assert.deepEqual(r.json.jobIds, []);
+});
+
+test("a page URL two parsers read differently is refused before any request, from the record or from the ask", async () => {
+ const r = await post({
+ requestedBy: "test",
+ archive: ORIGIN,
+ items: [
+ { slug: "evil-remote", id: "d1", from: 1, to: 5 },
+ { slug: "evil-remote", id: "d2", from: 1, to: 5 },
+ { slug: "evil-remote", id: "d3", from: 1, to: 5 },
+ { slug: "evil-remote", id: "a1", from: 1, to: 5, webpageUrl: "https://youtube.com\\@evil.example/watch?v=x" },
+ { slug: "evil-remote", id: "a2", from: 1, to: 5, webpageUrl: "https://rumble.com\\.evil.example/v1" },
+ { slug: "evil-remote", id: "a3", from: 1, to: 5, webpageUrl: "https://you\ttube.com/watch?v=x" },
+ { slug: "evil-remote", id: "a4", from: 1, to: 5, webpageUrl: "https://youtube.com/watch?v=x\nhttps://evil.example/" },
+ ],
+ });
+ assert.equal(r.status, 200, r.json.error);
+ const errors = (r.json.unresolved as Unresolved).map((u) => u.error);
+ assert.equal(errors.length, 7);
+ for (const e of errors) assert.match(e, /carries a backslash, whitespace or a control character/);
+ assert.deepEqual(r.json.jobIds, []);
+});
+
+test("what is planned for the fetcher is the URL the check parsed, written back — the record's and the ask's", async () => {
+ const r = await post({
+ requestedBy: "test",
+ archive: ORIGIN,
+ dryRun: true,
+ items: [
+ { slug: "evil-remote", id: "n1", from: 1, to: 5 },
+ { slug: "evil-remote", id: "n2", from: 1, to: 5, webpageUrl: " https:YOUTUBE.com:443/watch?v=n2 " },
+ ],
+ });
+ assert.equal(r.status, 200, r.json.error);
+ assert.deepEqual(r.json.unresolved, []);
+ const urls = (r.json.groups as { items: { id: string; webpageUrl: string }[] }[]).flatMap((g) => g.items).map((i) => i.webpageUrl).sort();
+ assert.deepEqual(urls, ["https://www.youtube.com/watch?v=n1", "https://youtube.com/watch?v=n2"]);
+});
+
+// LAST: it disconnects the archive for the rest of the file.
+test("a remote-only channel whose archive was removed from settings is refused, and the archive is not read", async () => {
+ await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ remoteArchives: [] }));
+ asked.length = 0;
+ const r = await post({ requestedBy: "test", items: [{ slug: "rb-remote", id: "rb9", from: 60, to: 70 }] });
+ assert.equal(r.status, 200, r.json.error);
+ assert.deepEqual(r.json.jobIds, []);
+ assert.match((r.json.unresolved as Unresolved)[0].error, /^rb-remote is a remote-only channel, and its archive https:\/\/stub\.test is no longer connected/);
+ assert.deepEqual(asked, [], "nothing asked of an archive that is not connected");
+});
diff --git a/editor/app/api/ops/fetch-windows/route.ts b/editor/app/api/ops/fetch-windows/route.ts
@@ -35,7 +35,8 @@ export const dynamic = "force-dynamic";
// POST { siteId, maxHeight?, storedUrl?, wholeRecording?, dryRun? }
// | { items: [{ slug, id, from, to, clipId?, reason?, pad?, webpageUrl?, force? }, …],
-// requestedBy, manifest?, maxHeight?, storedUrl?, minGapSeconds?, wholeRecording?, dryRun? }
+// requestedBy, manifest?, maxHeight?, storedUrl?, minGapSeconds?, wholeRecording?,
+// archive?, allowWholeRecording?, dryRun? }
// dryRun -> { ok, dryRun: true, groups: [{ platform, queueKey, items }],
// cached, inFlight, unresolved[, onDisk, unfetchable] }
// else -> { ok, dryRun: false, jobs: [{ platform, queueKey, jobId, items }],
@@ -75,6 +76,16 @@ export const dynamic = "force-dynamic";
// `"wholeRecording": false` fetches every window of this run by a remote seek
// instead, as before.
//
+// `archive` (items only; demo epic D1): the connected archive the items cite
+// (settings.remoteArchives — any other origin is refused). A channel this
+// editor does not hold is then REGISTERED as a remote-only channel of it
+// (config only, no listing; answered in `registered`) and its windows fetched
+// on the paced queue as any other; a remote-only channel's page URL comes
+// from the archive's record when the item has none. A remote-only channel's
+// window on a whole-recording platform (Rumble) is unresolved with the
+// recording's estimated size unless `"allowWholeRecording": true`. A dry run
+// registers nothing (it names who would be).
+//
// A big list goes in a file: `pnpm ops fetch-windows --file list.json`.
const ITEM_KEYS = ["slug", "id", "from", "to", "clipId", "reason", "pad", "webpageUrl", "force"];
@@ -182,7 +193,7 @@ function optMaxHeight(body: OpsBody): number | undefined {
export async function POST(request: Request) {
return ops(
request,
- ["siteId", "items", "requestedBy", "manifest", "maxHeight", "storedUrl", "minGapSeconds", "wholeRecording", "dryRun"],
+ ["siteId", "items", "requestedBy", "manifest", "maxHeight", "storedUrl", "minGapSeconds", "wholeRecording", "archive", "allowWholeRecording", "dryRun"],
async (body) => {
const maxHeight = optMaxHeight(body);
const storedUrl = optStoredUrl(body);
@@ -196,7 +207,7 @@ export async function POST(request: Request) {
let result: Awaited<ReturnType<typeof fetchWindowsAction>>;
if (body.siteId !== undefined) {
// A site's windows say who asked themselves (the reports, by site).
- for (const k of ["requestedBy", "manifest", "minGapSeconds"]) {
+ for (const k of ["requestedBy", "manifest", "minGapSeconds", "archive", "allowWholeRecording"]) {
if (body[k] !== undefined) {
throw new OpsInputError(`"${k}" goes with "items"; a site's windows name the site`);
}
@@ -221,6 +232,8 @@ export async function POST(request: Request) {
storedUrl,
dryRun,
...(minGapSeconds !== undefined ? { minGapSeconds } : {}),
+ ...(optString(body, "archive")?.trim() ? { archive: optString(body, "archive")!.trim() } : {}),
+ ...(optBool(body, "allowWholeRecording") === true ? { allowWholeRecording: true } : {}),
...seek,
});
} else {
diff --git a/editor/app/api/ops/local-media-configure/route.ts b/editor/app/api/ops/local-media-configure/route.ts
@@ -0,0 +1,26 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { configureLocalMedia } from "yt-dlp-transcript-common/controller/configureLocalMedia";
+import { ops, reqSlug, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, sourceId, directory } -> { ok: true, localMedia }
+//
+// A LOCAL MEDIA LIBRARY for a video channel (controller/configureLocalMedia.ts;
+// the Local media page's Save library): `localMedia` = {sourceId, directory}
+// written through patchChannelConfig, the channel config lock and the schema.
+// Initial opt-in only — a channel that already has a library is refused (the
+// same names could identify different recordings), as are a social channel,
+// queued or running channel work, a relocation, a directory that does not
+// exist or overlaps the channel. Playback is never set here. Nothing is
+// scanned or imported. Synchronous; no job.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "sourceId", "directory"], async (body) => {
+ const localMedia = await configureLocalMedia(getPaths(), reqSlug(body, "slug"), {
+ sourceId: reqString(body, "sourceId"),
+ directory: reqString(body, "directory"),
+ });
+ return NextResponse.json({ ok: true, localMedia });
+ });
+}
diff --git a/editor/app/api/ops/local-media-import/route.test.ts b/editor/app/api/ops/local-media-import/route.test.ts
@@ -0,0 +1,147 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/local-media-import/route.test.ts"
+//
+// The Local media page's five ops twins, end to end over a temp corpus and a
+// synthetic library: configure, preview (writes nothing), prepare (writes
+// nothing), import (one job), and link (dry run, then apply). The library's
+// files are never changed.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "local-media-ops-"));
+// Set before the routes (and getPaths, which caches) are first imported.
+process.env.WORKER_TOKEN = "test-token";
+process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts");
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+const routes = {
+ "local-media-configure": (await import("../local-media-configure/route")).POST,
+ "local-media-preview": (await import("../local-media-preview/route")).POST,
+ "local-media-prepare": (await import("../local-media-prepare/route")).POST,
+ "local-media-import": (await import("./route")).POST,
+ "local-media-link": (await import("../local-media-link/route")).POST,
+};
+const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const CH = path.join(ROOT, "transcripts", "channels");
+const LIB = path.join(ROOT, "library");
+const VTT = "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nA library cue\n";
+const info = (id: string) => JSON.stringify({
+ id, title: `Title ${id}`, webpage_url: `https://www.youtube.com/watch?v=${id}`,
+ upload_date: "20200102", duration: 12, extractor_key: "Youtube",
+});
+await mkdir(path.join(CH, "lib"), { recursive: true });
+await writeFile(path.join(CH, "lib", "config.json"), JSON.stringify({ handling: "youtube", name: "lib" }));
+await mkdir(LIB, { recursive: true });
+for (const id of ["aaaaaaaaaaa", "bbbbbbbbbbb"]) {
+ await writeFile(path.join(LIB, `${id}.mp4`), `mp4 ${id}`);
+ await writeFile(path.join(LIB, `${id}.info.json`), info(id));
+ await writeFile(path.join(LIB, `${id}.vtt`), VTT);
+}
+// No .info.json: a recording for Prepare details.
+await writeFile(path.join(LIB, "talk.mp4"), "mp4 talk");
+await writeFile(path.join(LIB, "talk.vtt"), VTT);
+// Held already, with the library's exact bytes: for Verify and link.
+await mkdir(path.join(CH, "lib", "data", "bbbbbbbbbbb"), { recursive: true });
+await writeFile(path.join(CH, "lib", "data", "bbbbbbbbbbb", "metadata.info.json"), info("bbbbbbbbbbb"));
+await writeFile(path.join(CH, "lib", "data", "bbbbbbbbbbb", "transcript.en.vtt"), VTT);
+
+type Json = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
+async function post(action: keyof typeof routes, body: Record<string, unknown>): Promise<{ status: number; json: Json }> {
+ const res = await routes[action](
+ new Request(`http://localhost/api/ops/${action}`, {
+ method: "POST",
+ headers: { authorization: "Bearer test-token", "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+ return { status: res.status, json: (await res.json()) as Json };
+}
+async function waitJob(id: string): Promise<string | undefined> {
+ for (let i = 0; i < 200; i++) {
+ const status = getRegistry().get(id)?.status;
+ if (status === "done" || status === "failed") return status;
+ await new Promise((res) => setTimeout(res, 50));
+ }
+ return getRegistry().get(id)?.status;
+}
+
+test("refusals: unknown keys, a missing slug, no library yet, a bad directory", async () => {
+ assert.match((await post("local-media-preview", { slug: "lib", force: true })).json.error, /unknown key\(s\): force/);
+ assert.match((await post("local-media-configure", { sourceId: "x", directory: LIB })).json.error, /"slug" is required/);
+ assert.match((await post("local-media-preview", { slug: "lib" })).json.error, /no valid local media source/);
+ assert.match((await post("local-media-import", { slug: "lib", allNew: true })).json.error, /no valid local media source/);
+ const rel = await post("local-media-configure", { slug: "lib", sourceId: "library-1", directory: "relative" });
+ assert.equal(rel.json.ok, false);
+ assert.equal(JSON.parse(await readFile(path.join(CH, "lib", "config.json"), "utf8")).localMedia, undefined);
+});
+
+test("configure, preview, prepare, import and link, the library untouched", async () => {
+ const before = (await readdir(LIB)).sort();
+ const configured = await post("local-media-configure", { slug: "lib", sourceId: "library-1", directory: LIB });
+ assert.equal(configured.status, 200, JSON.stringify(configured.json));
+ assert.deepEqual(configured.json.localMedia, { sourceId: "library-1", directory: LIB });
+ assert.match((await post("local-media-configure", { slug: "lib", sourceId: "library-2", directory: LIB })).json.error, /already has a library/);
+
+ const previewed = await post("local-media-preview", { slug: "lib" });
+ assert.equal(previewed.status, 200, JSON.stringify(previewed.json));
+ const { preview } = previewed.json;
+ assert.deepEqual(preview.counts, { discovered: 3, new: 1, existing: 1, issues: 1 });
+ const byMedia = Object.fromEntries(preview.candidates.map((c: Json) => [c.media, c]));
+ assert.equal(byMedia["aaaaaaaaaaa.mp4"].status, "new");
+ assert.equal(byMedia["bbbbbbbbbbb.mp4"].status, "existing");
+ assert.ok(byMedia["talk.mp4"].preparationFingerprint);
+ assert.deepEqual(await readdir(path.join(CH, "lib", "data")), ["bbbbbbbbbbb"]);
+
+ const prepared = await post("local-media-prepare", {
+ slug: "lib", sourceToken: preview.sourceToken, media: "talk.mp4",
+ sourceFingerprint: byMedia["talk.mp4"].preparationFingerprint,
+ details: { mode: "manual", title: "A talk", recordedDate: "2021-03-04" },
+ });
+ assert.equal(prepared.status, 200, JSON.stringify(prepared.json));
+ assert.equal(prepared.json.review.metadata.title, "A talk");
+ assert.equal(prepared.json.review.metadata.recorded_date, "20210304");
+ assert.match((await post("local-media-prepare", { slug: "lib", sourceToken: preview.sourceToken, media: "talk.mp4",
+ sourceFingerprint: "x", details: { mode: "nope" } })).json.error, /"details"/);
+
+ const dry = await post("local-media-link", { slug: "lib", sourceToken: preview.sourceToken, media: "bbbbbbbbbbb.mp4",
+ fingerprint: byMedia["bbbbbbbbbbb.mp4"].fingerprint, dryRun: true });
+ assert.equal(dry.json.status, "ready", JSON.stringify(dry.json));
+ assert.deepEqual((await readdir(path.join(CH, "lib", "data", "bbbbbbbbbbb"))).sort(), ["metadata.info.json", "transcript.en.vtt"]);
+ const linked = await post("local-media-link", { slug: "lib", sourceToken: preview.sourceToken, media: "bbbbbbbbbbb.mp4",
+ fingerprint: byMedia["bbbbbbbbbbb.mp4"].fingerprint });
+ assert.equal(linked.json.status, "attached", JSON.stringify(linked.json));
+ assert.deepEqual(JSON.parse(await readFile(path.join(CH, "lib", "data", "bbbbbbbbbbb", "external-media.json"), "utf8")),
+ { version: 1, kind: "external", sourceId: "library-1", relativePath: "bbbbbbbbbbb.mp4" });
+
+ const started = await post("local-media-import", {
+ slug: "lib", sourceToken: preview.sourceToken,
+ selected: [
+ { media: "aaaaaaaaaaa.mp4", fingerprint: byMedia["aaaaaaaaaaa.mp4"].fingerprint },
+ { media: "talk.mp4", fingerprint: prepared.json.review.fingerprint,
+ preparation: { sourceFingerprint: byMedia["talk.mp4"].preparationFingerprint,
+ details: { mode: "manual", title: "A talk", recordedDate: "2021-03-04" } } },
+ ],
+ });
+ assert.equal(started.status, 200, JSON.stringify(started.json));
+ // Review fix 7: the answer says how many were taken and how many remain.
+ assert.equal(started.json.selected, 2);
+ assert.equal(started.json.remaining, 0);
+ assert.equal(await waitJob(started.json.jobId), "done");
+ const data = (await readdir(path.join(CH, "lib", "data"))).sort();
+ assert.equal(data.length, 3);
+ assert.ok(data.includes("aaaaaaaaaaa"));
+ const local = data.find((d) => d.startsWith("local-"))!;
+ assert.equal(JSON.parse(await readFile(path.join(CH, "lib", "data", local, "metadata.info.json"), "utf8")).title, "A talk");
+ assert.deepEqual((await readdir(path.join(CH, "lib", "data", "aaaaaaaaaaa"))).sort(),
+ ["external-media.json", "metadata.info.json", "transcript.en.vtt"]);
+
+ // Nothing new left: allNew says so rather than starting an empty job.
+ assert.match((await post("local-media-import", { slug: "lib", allNew: true })).json.error, /no new recording/);
+ assert.match((await post("local-media-import", { slug: "lib", allNew: true, selected: [] })).json.error, /takes no/);
+ assert.deepEqual((await readdir(LIB)).sort(), before);
+});
diff --git a/editor/app/api/ops/local-media-import/route.ts b/editor/app/api/ops/local-media-import/route.ts
@@ -0,0 +1,59 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { previewLocalMedia } from "yt-dlp-transcript-common/controller/localMediaImport";
+import { NextResponse } from "next/server";
+import { selectAllNew, startLocalMediaImportJob, type LocalMediaJobRequest } from "yt-dlp-transcript-common/controller/localMediaImportJob";
+import { OpsInputError, jobResponse, ops, optBool, reqSlug } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, sourceToken, selected: [{ media, fingerprint, preparation? }] }
+// | { slug, allNew: true }
+// -> { ok: true, jobId, selected, remaining }
+//
+// LOCAL LIBRARY RECORDINGS IMPORTED (jobs/localMediaImportJob.ts; the Local
+// media page's Import selected): one `import-local-media` job on the channel's
+// queue writes each selected recording's metadata.info.json, transcript.en.vtt
+// (an .srt converted) and external-media.json into data/<id>/. The video file
+// stays where it is and is never copied. `selected` is what a
+// local-media-preview answered (its `sourceToken`, each candidate's `media`
+// and `fingerprint`; a prepared one adds `preparation: {sourceFingerprint,
+// details}` with the prepare's fingerprint). `allNew: true` takes a fresh
+// preview here and selects its "new" candidates — the first 1000 in the scan's
+// order when there are more, with `remaining` the count left for the next run
+// (also said in the job's log). Every selection is
+// re-checked before its record is written: a changed file is "stale", an
+// occupied record is left unchanged. Drainable between recordings. The
+// imported records are searchable after the next index build.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "sourceToken", "selected", "allNew"], async (body) => {
+ const slug = reqSlug(body, "slug");
+ const paths = getPaths();
+ let req: LocalMediaJobRequest;
+ let remaining = 0;
+ if (optBool(body, "allNew") === true) {
+ if (body.sourceToken !== undefined || body.selected !== undefined) {
+ throw new OpsInputError('"allNew" takes no "sourceToken" or "selected"');
+ }
+ const all = selectAllNew(await previewLocalMedia(paths, slug));
+ if (all.request.selected.length === 0) throw new OpsInputError("the library has no new recording to import");
+ req = all.request;
+ remaining = all.remaining;
+ } else {
+ if (typeof body.sourceToken !== "string" || !Array.isArray(body.selected)) {
+ throw new OpsInputError('"sourceToken" and "selected" (from local-media-preview) are required, or "allNew": true');
+ }
+ req = { sourceToken: body.sourceToken, selected: body.selected as LocalMediaJobRequest["selected"] };
+ }
+ let started;
+ try {
+ started = await startLocalMediaImportJob(paths, slug, req);
+ } catch (e) {
+ throw new OpsInputError((e as Error).message);
+ }
+ if (!started.ok) return jobResponse(started);
+ void started.stream.cancel();
+ // `selected` and `remaining`: over LOCAL_MEDIA_IMPORT_MAX new recordings,
+ // allNew takes the first ones and says how many are left for the next run.
+ return NextResponse.json({ ok: true, jobId: started.jobId, selected: req.selected.length, remaining });
+ });
+}
diff --git a/editor/app/api/ops/local-media-link/route.ts b/editor/app/api/ops/local-media-link/route.ts
@@ -0,0 +1,30 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { adoptLocalMediaReference } from "yt-dlp-transcript-common/controller/adoptLocalMediaReference";
+import { ops, optBool, reqSlug, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, sourceToken, media, fingerprint, dryRun? }
+// -> { ok: true, status: "attached" | "already-linked" | "conflict" | "ready" }
+//
+// VERIFY AND LINK one record the channel already holds to its local original
+// (controller/adoptLocalMediaReference.ts; the Local media page's Verify and
+// link): for a preview candidate that is "existing", the library's
+// .info.json and transcript are compared BYTE FOR BYTE with the record's
+// metadata.info.json and transcript.en.vtt (an .srt converted first), and
+// only on a match is external-media.json written beside them — never over one
+// already there ("conflict" keeps it). Nothing else in the record changes;
+// linking grants no playback. `dryRun` verifies and answers "ready" (or
+// "already-linked" / "conflict") without writing. Refused while the channel has
+// queued or running work. Synchronous; no job.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "sourceToken", "media", "fingerprint", "dryRun"], async (body) => {
+ const result = await adoptLocalMediaReference(getPaths(), reqSlug(body, "slug"), {
+ sourceToken: reqString(body, "sourceToken"),
+ media: reqString(body, "media"),
+ fingerprint: reqString(body, "fingerprint"),
+ }, { apply: optBool(body, "dryRun") !== true });
+ return NextResponse.json({ ok: true, ...result });
+ });
+}
diff --git a/editor/app/api/ops/local-media-prepare/route.ts b/editor/app/api/ops/local-media-prepare/route.ts
@@ -0,0 +1,40 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { channelWriters } from "yt-dlp-transcript-common/controller/channelWriters";
+import { prepareLocalMediaRecording } from "yt-dlp-transcript-common/controller/localMediaImport";
+import { parseLocalRecordingDetails } from "yt-dlp-transcript-common/lib/localRecordingDetails";
+import { OpsInputError, ops, opsFail, reqSlug, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, sourceToken, media, sourceFingerprint,
+// details: { mode: "inspect" | "manual", title, recordedDate?, durationSeconds? } }
+// -> { ok: true, review: { metadata, fingerprint } }
+//
+// LOCAL RECORDING DETAILS for a library recording with no .info.json
+// (controller/localMediaImport.ts prepareLocalMediaRecording; the Local media
+// page's Prepare details): a title, an optional recording date (YYYY-MM-DD)
+// and, by "inspect", the duration ffprobe measures, or by "manual" the one
+// given (or none). Writes nothing: the `review.fingerprint` is the
+// `fingerprint` local-media-import takes, with `preparation: {sourceFingerprint,
+// details}`, to import it. `sourceFingerprint` is the preview's
+// `preparationFingerprint`. Refused while the channel has queued or running
+// work. Synchronous; no job.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "sourceToken", "media", "sourceFingerprint", "details"], async (body) => {
+ const slug = reqSlug(body, "slug");
+ let details;
+ try { details = parseLocalRecordingDetails(body.details); }
+ catch (e) { throw new OpsInputError(`"details": ${(e as Error).message}`); }
+ if (channelWriters(slug, { includeQueued: true }).length) {
+ return opsFail("wait for this channel's queued or running work to finish", 409);
+ }
+ const review = await prepareLocalMediaRecording(getPaths(), slug, {
+ sourceToken: reqString(body, "sourceToken"),
+ media: reqString(body, "media"),
+ sourceFingerprint: reqString(body, "sourceFingerprint"),
+ details,
+ });
+ return NextResponse.json({ ok: true, review });
+ });
+}
diff --git a/editor/app/api/ops/local-media-preview/route.ts b/editor/app/api/ops/local-media-preview/route.ts
@@ -0,0 +1,25 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { previewLocalMedia } from "yt-dlp-transcript-common/controller/localMediaImport";
+import { ops, reqSlug } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug } -> { ok: true, preview: { sourceToken, counts, candidates } }
+//
+// The channel's local media library SCANNED, writing nothing
+// (controller/localMediaImport.ts previewLocalMedia; the Local media page's
+// Preview library): every .mp4 directly in `localMedia.directory` (not its
+// subdirectories) with its same-named .info.json and .vtt/.srt, each a
+// candidate "new", "existing" (its record's directory is occupied) or "issue"
+// (with `issues`). A candidate's `fingerprint` (import, link) or
+// `preparationFingerprint` (prepare, for one with no .info.json) and the
+// preview's `sourceToken` are what the other local-media actions take; a
+// changed file or config makes them stale. An unreachable library is an
+// error, never an empty preview. Synchronous; no job.
+export async function POST(request: Request) {
+ return ops(request, ["slug"], async (body) => {
+ const preview = await previewLocalMedia(getPaths(), reqSlug(body, "slug"));
+ return NextResponse.json({ ok: true, preview });
+ });
+}
diff --git a/editor/app/api/ops/lookout-run/route.ts b/editor/app/api/ops/lookout-run/route.ts
@@ -0,0 +1,56 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { isIsoDate } from "yt-dlp-transcript-common/lib/lookout";
+import { LOOKOUT_MAX_DAYS, LOOKOUT_MAX_MAX_VIDEOS, lookoutById } from "yt-dlp-transcript-common/lib/lookoutSettings";
+import { LookoutPlanRefusal, planLookout } from "yt-dlp-transcript-common/controller/lookoutPlan";
+import { OpsInputError, ops, opsFail, optBool, optPositiveInt, optString, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { id, dryRun: true, days?, maxVideos?, until? } -> { ok: true, plan }
+//
+// What a saved lookout (settings.lookouts.items, SETTINGS.md) would read
+// (common/controller/lookoutPlan.ts): every video of its channels whose AIR
+// date — `release_timestamp`, else `timestamp`, in its time zone — falls in
+// the window; duplicate uploads and a stream's cut-downs folded into one
+// recording; the longest `maxVideos` read and the rest listed as skipped for
+// the cap, with why for every video left out; the reading calls and, once a
+// run has been measured, the seconds they would take. `days` and `maxVideos`
+// override the lookout's for this answer; `until` (YYYY-MM-DD) ends the window
+// on another day than today. A local media library channel, or a slug this
+// archive does not hold, is named in `refused`. Reads text only and writes
+// nothing; synchronous, no job, no model, no network.
+//
+// Only the dry run exists in this build: without `dryRun: true` the request is
+// refused, never run.
+export async function POST(request: Request) {
+ return ops(request, ["id", "dryRun", "days", "maxVideos", "until"], async (body) => {
+ const id = reqString(body, "id");
+ if (optBool(body, "dryRun") !== true) {
+ throw new OpsInputError(
+ 'a lookout run reads with a model, which this build does not do yet — send "dryRun": true to list what it would read',
+ );
+ }
+ const days = optPositiveInt(body, "days");
+ if (days !== undefined && days > LOOKOUT_MAX_DAYS) throw new OpsInputError(`"days" is at most ${LOOKOUT_MAX_DAYS}`);
+ const maxVideos = optPositiveInt(body, "maxVideos");
+ if (maxVideos !== undefined && maxVideos > LOOKOUT_MAX_MAX_VIDEOS) {
+ throw new OpsInputError(`"maxVideos" is at most ${LOOKOUT_MAX_MAX_VIDEOS}`);
+ }
+ const until = optString(body, "until");
+ if (until !== undefined && !isIsoDate(until)) throw new OpsInputError('"until" is a date, YYYY-MM-DD');
+ const lookouts = getSettings().lookouts;
+ const item = lookoutById(lookouts, id);
+ if (!item) {
+ return opsFail(`no lookout "${id}" — settings.lookouts.items names ${lookouts.items.map((i) => i.id).join(", ") || "none"}`, 404);
+ }
+ try {
+ const plan = await planLookout(getPaths(), item, { days, maxVideos, until });
+ return NextResponse.json({ ok: true, plan });
+ } catch (err) {
+ if (err instanceof LookoutPlanRefusal) throw new OpsInputError(err.message);
+ throw err;
+ }
+ });
+}
diff --git a/editor/app/api/ops/lookouts/route.ts b/editor/app/api/ops/lookouts/route.ts
@@ -0,0 +1,29 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { lookoutReadout } from "yt-dlp-transcript-common/lib/lookoutStore";
+import { opsFail } from "../_lib";
+import { readRoute } from "../_read";
+
+export const dynamic = "force-dynamic";
+
+// GET /api/ops/lookouts[?id=<lookout>] — `pnpm ops get lookouts`
+//
+// The saved lookouts (settings.lookouts, SETTINGS.md) and what the store holds
+// for each (common/lib/lookoutStore.ts, `transcripts/.lookouts/<id>/`): its
+// runs, the latest one summarised (when, window, model, calls, seconds,
+// ideas), how many of that run's ideas have no verdict yet, and the verdicts
+// given. Reads settings and the store only — never a channel's videos, so it
+// is cheap to poll; what a lookout would read is `lookout-run` with dryRun.
+export async function GET(request: Request) {
+ return readRoute(request, ["id"], async (q) => {
+ const { enabled, afterSync, items } = getSettings().lookouts;
+ const id = q.get("id");
+ const chosen = id === null ? items : items.filter((i) => i.id === id);
+ if (id !== null && chosen.length === 0) {
+ return opsFail(`no lookout "${id}" — settings.lookouts.items names ${items.map((i) => i.id).join(", ") || "none"}`, 404);
+ }
+ const paths = getPaths();
+ const lookouts = await Promise.all(chosen.map(async (item) => ({ ...item, ...(await lookoutReadout(paths, item.id)) })));
+ return { enabled, afterSync, lookouts };
+ });
+}
diff --git a/editor/app/api/ops/settings/patch.ts b/editor/app/api/ops/settings/patch.ts
@@ -8,6 +8,7 @@
// - autoQueue: a lane's tree is its policy editor's, or compiled from the
// channel priorities — and the editor refuses a tree edit while they rule.
// - workers: /workers validates each worker (templates, URLs) on save.
+// - remoteArchives: an archive's corpus.json is read when it is connected.
// - storage: a location is probed and its volume recorded when added or
// re-pointed (/storage); a raw root would skip both.
export const OWNED_KEYS: Readonly<Record<string, string>> = {
@@ -15,6 +16,7 @@ export const OWNED_KEYS: Readonly<Record<string, string>> = {
autoQueue:
"a lane's switch, hold and runner are `pnpm ops lane`; its tree is the policy editor's on /operations, or compiled from channel priorities",
workers: "workers are saved on /workers; `pnpm ops workers` enables and disables them",
+ remoteArchives: "an archive is probed (its corpus.json read) when it is connected — use `pnpm ops archives` or /sites → Connect an archive",
storage: "locations are added and re-pointed on /storage, which probes them; a channel's media moves with `pnpm ops relocate`",
};
diff --git a/editor/app/api/ops/voice-convert/route.ts b/editor/app/api/ops/voice-convert/route.ts
@@ -7,7 +7,7 @@ import { jobResponse, ops } from "../_lib";
export const dynamic = "force-dynamic";
-// POST { file, out, voice?, engine?, params?, parts? } -> { ok: true, jobId }
+// POST { file, out, voice?, engine?, pitch?, semitones?, params?, parts? } -> { ok: true, jobId }
//
// Keep a recording's PERFORMANCE — its timing, pitch contour and emphasis —
// and give it a STOCK synthetic voice's timbre, as a job on /jobs
@@ -22,7 +22,12 @@ export const dynamic = "force-dynamic";
// `engine` is `openvoice` (OpenVoice v2's converter) or `seed-vc` (Seed-VC v1),
// default settings.voice.convert.engine — `archilyzer voice setup --engine
// <id>` installs one; `file`/`path`, `out`, `params` and `parts` as for
-// voice-enhance. umtool's derived takes (`umtool posts narrate … --derive <n>
+// voice-enhance. `pitch` says where the result's pitch comes from — `target`
+// (the stock voice's own: the read's intonation is flattened to it), `source`
+// (the pitch the take was read at) or `contour` (the read's rises and falls at
+// the stock voice's register) — and `semitones` (-12 to 12) moves a followed
+// one; defaults settings.voice.convert. source and contour are seed-vc's, on
+// its optional f0 model (`archilyzer voice setup --engine seed-vc --with f0`). umtool's derived takes (`umtool posts narrate … --derive <n>
// --op convert`) are the caller.
//
// The job's log ends with `@@voice-result {json}` — voice-enhance's shape plus
diff --git a/editor/app/channels/[slug]/attachMediaActions.ts b/editor/app/channels/[slug]/attachMediaActions.ts
@@ -1,5 +1,6 @@
"use server";
+import { localMediaWriteRefusal } from "yt-dlp-transcript-common/controller/localMediaDoors";
import path from "node:path";
import { safeRevalidate } from "../../lib/safeRevalidate";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
@@ -41,6 +42,13 @@ export async function attachMediaAction(
if (!channelConfig) {
return { ok: false, error: `Channel "${slug}" not found` };
}
+ // A local media library channel, or a named item that is a local recording or
+ // linked to a library original (review fix 5); a walk's ids are refused in
+ // the job (controller/attachMedia.ts, class "local-media").
+ for (const id of [undefined, ...(opts.items ?? []).map((i) => i.id)]) {
+ const localRefusal = await localMediaWriteRefusal(paths, slug, channelConfig, id);
+ if (localRefusal) return { ok: false, error: localRefusal };
+ }
const source = opts.source.trim();
if (!path.isAbsolute(source)) {
return { ok: false, error: `"source" must be an absolute path (a directory, a .zip or a .7z)` };
diff --git a/editor/app/channels/[slug]/components/flow/AttentionStrip.tsx b/editor/app/channels/[slug]/components/flow/AttentionStrip.tsx
@@ -36,6 +36,8 @@ export type AttentionInput = {
failedVideoIds: string[];
generatedAt: string;
lastSyncedAt?: string;
+ // Local-only libraries are scanned explicitly, not synced from a provider.
+ onlineSyncApplicable?: boolean;
};
function ageInDays(iso: string | undefined): number | null {
@@ -93,16 +95,18 @@ export function collectAttention(input: AttentionInput): Chip[] {
});
}
}
- if (!input.lastSyncedAt) {
- chips.push({ label: "never synced", stage: "playlist", tone: "warning" });
- } else {
- const days = ageInDays(input.lastSyncedAt);
- if (days != null && days > STALE_SYNC_DAYS) {
- chips.push({
- label: `last synced ${Math.floor(days)} days ago`,
- stage: "playlist",
- tone: "warning",
- });
+ if (input.onlineSyncApplicable !== false) {
+ if (!input.lastSyncedAt) {
+ chips.push({ label: "never synced", stage: "playlist", tone: "warning" });
+ } else {
+ const days = ageInDays(input.lastSyncedAt);
+ if (days != null && days > STALE_SYNC_DAYS) {
+ chips.push({
+ label: `last synced ${Math.floor(days)} days ago`,
+ stage: "playlist",
+ tone: "warning",
+ });
+ }
}
}
diff --git a/editor/app/channels/[slug]/components/flow/OverviewPanel.tsx b/editor/app/channels/[slug]/components/flow/OverviewPanel.tsx
@@ -25,6 +25,7 @@ const TONE_DOT: Record<StageStatus["tone"], string> = {
};
export type ChannelEssentials = {
+ localArchive?: boolean;
handling: string;
platform?: string;
url?: string;
@@ -125,11 +126,14 @@ export function OverviewPanel({
aria-label="channel essentials"
className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-1 text-sm"
>
- <Field label="Handling" value={essentials.handling} />
+ {essentials.localArchive && (
+ <Field label="Source" value={essentials.url ? "Online source and local library" : "Local archive"} />
+ )}
+ <Field label="Handling" value={essentials.localArchive && !essentials.url ? "Local media" : essentials.handling} />
<Field label="Platform" value={essentials.platform ?? "—"} />
<Field
label="URL"
- value={essentials.url ?? "no URL configured"}
+ value={essentials.url ?? (essentials.localArchive ? "Not required for a local archive" : "no URL configured")}
mono
/>
<Field
@@ -155,7 +159,9 @@ export function OverviewPanel({
) : (
"No report has been generated for this channel yet."
)}{" "}
- {lastSyncedAt
+ {essentials.localArchive && !essentials.url
+ ? "Local library scans are started from Local library."
+ : lastSyncedAt
? `Last synced ${formatTimestamp(lastSyncedAt)}.`
: "Never synced."}
</p>
diff --git a/editor/app/channels/[slug]/components/flow/StageSwitcher.tsx b/editor/app/channels/[slug]/components/flow/StageSwitcher.tsx
@@ -24,11 +24,13 @@ export function StageSwitcher({
stageOrder,
stages,
selected,
+ showLocalLibrary = false,
}: {
slug: string;
stageOrder: StageId[];
stages: Record<StageId, StageStatus>;
selected: StageId | null;
+ showLocalLibrary?: boolean;
}) {
return (
<nav
@@ -36,6 +38,9 @@ export function StageSwitcher({
className="flex flex-wrap items-center gap-1 border-b border-border pb-2"
>
<Tab href={`/channels/${slug}`} active={selected === null} label="Overview" />
+ {showLocalLibrary && (
+ <Tab href={`/channels/${slug}/local-media`} active={false} label="Local library" />
+ )}
{stageOrder.map((id) => {
const status = stages[id];
return (
diff --git a/editor/app/channels/[slug]/liveMediaActions.ts b/editor/app/channels/[slug]/liveMediaActions.ts
@@ -22,6 +22,8 @@
//
// NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use server" file).
+import { localMediaWriteRefusal } from "yt-dlp-transcript-common/controller/localMediaDoors";
+import { localMediaFetchRefusal } from "yt-dlp-transcript-common/lib/localMedia";
import { stat } from "node:fs/promises";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
@@ -62,6 +64,10 @@ export async function importMediaAction(body: Record<string, unknown>): Promise<
const paths = getPaths();
const config = await readChannelConfig(paths, req.slug);
if (!config) return { ok: false, error: `Channel "${req.slug}" not found` };
+ // Both branches (one file, or attach-media's walk): a local media library
+ // channel, a local recording, or a record linked to a library original.
+ const localRefusal = await localMediaWriteRefusal(paths, req.slug, config, req.id);
+ if (localRefusal) return { ok: false, error: localRefusal };
const st = await stat(req.path).catch(() => null);
if (!st) return { ok: false, error: `${req.path} is not there` };
if (isArchivePath(req.path, st.isDirectory())) {
@@ -150,7 +156,11 @@ export async function liveClipAction(body: Record<string, unknown>): Promise<Str
if (!parsed.ok) return parsed;
if (!isValidChannelSlug(parsed.value.slug)) return { ok: false, error: `"${parsed.value.slug}" is not a channel slug` };
const paths = getPaths();
- if (!(await readChannelConfig(paths, parsed.value.slug))) return { ok: false, error: `Channel "${parsed.value.slug}" not found` };
+ const config = await readChannelConfig(paths, parsed.value.slug);
+ if (!config) return { ok: false, error: `Channel "${parsed.value.slug}" not found` };
+ // Before the umtool checks: a local media record has no live source (review fix 5).
+ const localRefusal = localMediaFetchRefusal(parsed.value.slug, config, parsed.value.id);
+ if (localRefusal) return { ok: false, error: localRefusal };
return runLiveClipJob({ paths, request: parsed.value });
}
diff --git a/editor/app/channels/[slug]/local-media/LocalMediaPanel.tsx b/editor/app/channels/[slug]/local-media/LocalMediaPanel.tsx
@@ -0,0 +1,151 @@
+"use client";
+
+import Link from "next/link";
+import { LocalRecordingDetailsForm, type ReviewedLocalRecording } from "./LocalRecordingDetailsForm";
+import { useState, useTransition } from "react";
+import type { LocalMediaConfig } from "yt-dlp-transcript-common/lib/localMedia";
+import type { LocalMediaPreview } from "yt-dlp-transcript-common/controller/localMediaImport";
+import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
+import { cancelJobAction, drainJobAction } from "../../../jobs/actions";
+import { previewLibraryAction, importLibraryAction, linkExistingLibraryRecordingAction } from "./actions";
+
+const button = "rounded border border-border px-3 py-2 disabled:opacity-50";
+export function LocalMediaPanel({ slug, initialConfig }: { slug: string; initialConfig: LocalMediaConfig | null }) {
+ const config = initialConfig;
+ const [preview, setPreview] = useState<LocalMediaPreview | null>(null);
+ const [selected, setSelected] = useState<Set<string>>(new Set());
+ const [error, setError] = useState<string | null>(null);
+ const [pending, start] = useTransition();
+ const [running, setRunning] = useState(false);
+ const [jobId, setJobId] = useState<string | null>(null);
+ const [stopping, setStopping] = useState(false);
+ const [linkResults, setLinkResults] = useState<Record<string, string>>({});
+ const [linking, setLinking] = useState<string | null>(null);
+ const [detailsOpenRequest, setDetailsOpenRequest] = useState(0);
+ const [detailsMedia, setDetailsMedia] = useState<string | null>(null);
+ const [preparing, setPreparing] = useState(false);
+ const [prepared, setPrepared] = useState<Record<string, ReviewedLocalRecording>>({});
+ const busy = pending || running || linking !== null || preparing;
+ const detailsRow = preview?.candidates.find(row => row.media === detailsMedia && row.preparationFingerprint);
+ function canSelect(row: LocalMediaPreview["candidates"][number]) {
+ return row.status === "new" && !!row.fingerprint || !!row.preparationFingerprint && !!prepared[row.media];
+ }
+
+
+ // Results describe this explicit attempt, not a permanent guarantee that a
+ // file remains present. A fresh preview clears them and rechecks eligibility.
+ async function linkExisting(media: string, fingerprint: string) {
+ if (!preview || busy) return;
+ setLinking(media); setError(null);
+ try {
+ const response = await linkExistingLibraryRecordingAction(slug,
+ {sourceToken: preview.sourceToken, media, fingerprint});
+ const message = !response.ok ? response.error
+ : response.result.status === "conflict" ? "Conflict: the existing reference was preserved. Review it before continuing."
+ : response.result.status === "attached" || response.result.status === "already-linked"
+ ? (response.result.status === "attached" ? "Linked to local original." : "Already linked to this local original.")
+ + (response.result.stagingCleanupFailed ? " Temporary reference cleanup needs review." : "")
+ : "Not linked. Preview again before retrying.";
+ setLinkResults(previous => ({...previous, [media]: message}));
+ } catch {
+ // A lost response does not prove publication failed. Retrying is safe:
+ // the controller recognizes an identical already-published reference.
+ setLinkResults(previous => ({...previous, [media]: "No response from the editor. The link may have been saved; preview and retry to verify."}));
+ } finally { setLinking(null); }
+ }
+
+ return <section className="[&_button:enabled]:cursor-pointer [&_button:enabled:hover]:brightness-125 [&_button:disabled]:cursor-not-allowed space-y-4 rounded border border-border p-4">
+ {/* A library is added through the New channel form (Local Archive) or
+ `pnpm ops local-media-configure` (review fix 8); this route stays
+ reachable by URL for a channel without one, and says how. */}
+ {!config ? <div role="status" className="space-y-2">
+ <p>This channel has no local media library.</p>
+ <p className="text-sm text-muted-foreground">Add one with the New channel form (Local Archive) for a new channel, or for this one:</p>
+ <pre className="whitespace-pre-wrap break-all rounded bg-muted p-2 text-xs">{`pnpm ops local-media-configure --json '{"slug":"${slug}","sourceId":"library-1","directory":"/absolute/path/to/recordings"}'`}</pre>
+ </div> : <>
+ <p><strong>{config.sourceId}</strong> · <code className="break-all">{config.directory}</code></p>
+ <p className="text-sm text-muted-foreground">Each .mp4 directly in this directory, with a same-named .info.json and .vtt (or .srt). Subdirectories are not scanned.</p>
+ <button className={button} disabled={busy} onClick={() => {
+ setError(null); setPreview(null); setSelected(new Set()); setLinkResults({}); setPrepared({}); setDetailsMedia(null);
+ start(async () => {
+ try {
+ const result = await previewLibraryAction(slug);
+ if (result.ok) setPreview(result.preview); else setError(result.error);
+ } catch { setError("Could not contact the editor. Try again."); }
+ });
+ }}>{pending ? "Working…" : "Preview library"}</button>
+ </>}
+ {error && <p role="alert" className="text-destructive">{error}</p>}
+ {preview && <>
+ <p role="status">{preview.counts.discovered} discovered · {preview.counts.new} new · {preview.counts.existing} occupied · {preview.counts.issues} need review</p>
+ <div className="overflow-x-auto"><table className="w-full text-sm text-left">
+ <thead><tr><th>Select</th><th>Recording</th><th>Status</th><th>Cues / notes</th><th>Details / local reference</th></tr></thead>
+ <tbody>{preview.candidates.map(row => <tr key={row.media} className="border-t border-border">
+ <td><input type="checkbox" aria-label={`Import ${row.media}`} disabled={busy || !canSelect(row) || (!selected.has(row.media) && selected.size >= 1000)} checked={selected.has(row.media)} onChange={e => {
+ const next = new Set(selected); if (e.target.checked) next.add(row.media); else next.delete(row.media); setSelected(next);
+ }} /></td>
+ <td className="p-2"><span>{row.title ?? row.media}</span><br /><span className="text-xs text-muted-foreground break-all">{row.media}</span></td>
+ <td>{prepared[row.media] ? "Ready to import" : row.preparationFingerprint ? "Needs details" : row.status === "existing" ? "Occupied" : row.status === "issue" ? "Needs review" : "New"}</td>
+ <td className="p-2">{row.cueCount ?? "—"}{[...(prepared[row.media] ? ["Local recording details reviewed"] : row.issues), ...row.warnings].map((note, index) => <p key={index}>{note}</p>)}</td>
+ <td className="p-2">
+ {row.savedRecordAvailable && row.status !== "existing" && row.directoryId && <div>
+ <Link className={button + " inline-block"} href={"/channels/" + encodeURIComponent(slug) + "/videos/" + encodeURIComponent(row.directoryId)}>Open saved record</Link>
+ <p className="text-sm text-muted-foreground mt-2">Already held; not reverified.</p>
+ </div>}
+ {row.preparationFingerprint && <button type="button" className={button} disabled={busy}
+ aria-label={`Prepare details for ${row.media}`} onClick={() => {
+ setDetailsMedia(row.media); setDetailsOpenRequest(value => value + 1);
+ setSelected(previous => {const next = new Set(previous); next.delete(row.media); return next;});
+ }}>{prepared[row.media] ? "Edit details" : "Prepare details"}</button>}
+ {row.status === "existing" && row.fingerprint && <button type="button" className={button}
+ disabled={busy} aria-label={`Verify and link ${row.media}`}
+ onClick={() => { void linkExisting(row.media, row.fingerprint!); }}>
+ {linking === row.media ? "Verifying…" : "Verify and link"}
+ </button>}
+ {row.status === "existing" && row.generatedMetadata && row.directoryId && <div>
+ <Link className={button + " inline-block"} href={"/channels/" + encodeURIComponent(slug) + "/videos/" + encodeURIComponent(row.directoryId)}
+ aria-label={"Open saved record for " + row.media}>Open saved record</Link>
+ <p className="text-sm text-muted-foreground mt-2">Imported with prepared details; not reverified.</p>
+ </div>}
+ {linkResults[row.media] && <p role="status" className="mt-2">{linkResults[row.media]}</p>}
+ </td>
+ </tr>)}</tbody>
+ </table></div>
+ </>}
+ {detailsRow?.preparationFingerprint && preview && <LocalRecordingDetailsForm
+ key={preview.sourceToken + detailsRow.media + detailsRow.preparationFingerprint}
+ slug={slug} media={detailsRow.media} sourceToken={preview.sourceToken} sourceFingerprint={detailsRow.preparationFingerprint}
+ openRequest={detailsOpenRequest}
+ initialDetails={prepared[detailsRow.media]?.details}
+ disabled={busy} onBusy={setPreparing} onClose={() => setDetailsMedia(null)} onUse={review => {
+ setPrepared(previous => ({...previous, [detailsRow.media]: review}));
+ setSelected(previous => previous.size < 1000 ? new Set([...previous, detailsRow.media]) : previous);
+ setDetailsMedia(null);
+ }} />}
+ {config && <StreamActionLog
+ label="Import local media" buttonLabel={`Import selected (${selected.size})`} runningLabel="Importing…"
+ disabled={busy || detailsMedia !== null || !preview || selected.size === 0}
+ cancelAction={cancelJobAction}
+ extraControls={running && jobId ? <button className={button} disabled={stopping} onClick={async () => {
+ setStopping(true);
+ try { const result = await drainJobAction(jobId); if (!result.ok) { setStopping(false); setError("Could not request a stop. Check the job page."); } }
+ catch { setStopping(false); setError("Could not contact the editor."); }
+ }}>{stopping ? "Stop requested" : "Finish recording and stop"}</button> : undefined}
+ trigger={async () => {
+ if (!preview) return {ok: false as const, error: "Preview the library first"};
+ setRunning(true); setStopping(false); setError(null);
+ try {
+ const result = await importLibraryAction(slug, {sourceToken: preview.sourceToken, selected: preview.candidates.filter(row => selected.has(row.media) && canSelect(row)).map(row => {
+ const review = prepared[row.media];
+ return review && row.preparationFingerprint ? {media: row.media, fingerprint: review.fingerprint,
+ preparation: {sourceFingerprint: row.preparationFingerprint, details: review.details}}
+ : {media: row.media, fingerprint: row.fingerprint!};
+ })});
+ if (result.ok) setJobId(result.jobId); else setRunning(false);
+ return result;
+ } catch { setRunning(false); return {ok: false as const, error: "Could not contact the editor"}; }
+ }}
+ onSettled={() => { setRunning(false); setJobId(null); setPreview(null); setSelected(new Set()); setLinkResults({}); setPrepared({}); setDetailsMedia(null); }}
+ />}
+ </section>;
+}
diff --git a/editor/app/channels/[slug]/local-media/LocalRecordingDetailsForm.tsx b/editor/app/channels/[slug]/local-media/LocalRecordingDetailsForm.tsx
@@ -0,0 +1,78 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import type { LocalRecordingDetails } from "yt-dlp-transcript-common/lib/localRecordingDetails";
+import type { LocalRecordingMetadata } from "yt-dlp-transcript-common/lib/localRecordingMetadata";
+import { prepareLibraryRecordingAction } from "./actions";
+
+export type ReviewedLocalRecording = {fingerprint: string; details: LocalRecordingDetails};
+const input = "block w-full rounded border border-border bg-background p-2";
+const button = "rounded border border-border px-3 py-2 disabled:opacity-50";
+
+export function LocalRecordingDetailsForm({slug, media, sourceToken, sourceFingerprint, initialDetails, openRequest, disabled, onBusy, onUse, onClose}: {
+ slug: string; media: string; sourceToken: string; sourceFingerprint: string; disabled: boolean;
+ initialDetails?: LocalRecordingDetails;
+ openRequest: number;
+ onBusy: (value: boolean) => void; onUse: (review: ReviewedLocalRecording) => void; onClose: () => void;
+}) {
+ const headingRef = useRef<HTMLHeadingElement>(null);
+ useEffect(() => {
+ const heading = headingRef.current;
+ if (!heading) return;
+ heading.focus({preventScroll: true});
+ heading.scrollIntoView({block: "start", behavior: "instant"});
+ }, [openRequest]);
+ const [mode, setMode] = useState<"inspect" | "manual">(initialDetails?.mode ?? "inspect");
+ const [title, setTitle] = useState(initialDetails?.title ?? media.slice(0, -4));
+ const [date, setDate] = useState(initialDetails?.recordedDate ?? "");
+ const [duration, setDuration] = useState(initialDetails?.durationSeconds?.toString() ?? "");
+ const [error, setError] = useState<string | null>(null);
+ const [review, setReview] = useState<{metadata: LocalRecordingMetadata; fingerprint: string; details: LocalRecordingDetails} | null>(null);
+ function changed() { setReview(null); setError(null); }
+ return <form aria-label={`Prepare details for ${media}`} className="space-y-3 rounded border border-border p-4" onSubmit={async event => {
+ event.preventDefault();
+ if (disabled) return;
+ changed();
+ const details: LocalRecordingDetails = {mode, title,
+ ...(date ? {recordedDate: date} : {}),
+ ...(mode === "manual" && duration.trim() ? {durationSeconds: Number(duration)} : {})};
+ if (details.durationSeconds !== undefined && (!Number.isFinite(details.durationSeconds) || details.durationSeconds <= 0)) {
+ setError("Enter a positive duration in seconds or leave it unknown."); return;
+ }
+ onBusy(true);
+ try {
+ const result = await prepareLibraryRecordingAction(slug, {media, sourceToken, sourceFingerprint, details});
+ if (result.ok) setReview({...result.review, details}); else setError(result.error);
+ } catch { setError("Could not contact the editor. No import was requested; try preparing again."); }
+ finally { onBusy(false); }
+ }}>
+ <h3 ref={headingRef} tabIndex={-1} className="scroll-mt-32 font-semibold">Prepare recording details</h3>
+ <p className="break-all text-sm">{media}</p>
+ <fieldset disabled={disabled} className="space-y-3">
+ <legend className="sr-only">Recording details</legend>
+ <label className="block">Method
+ <select className={input} value={mode} onChange={e => {changed(); setMode(e.target.value as "inspect" | "manual");}}>
+ <option value="inspect">Inspect video with ffprobe</option>
+ <option value="manual">Enter details manually</option>
+ </select>
+ </label>
+ <p className="text-sm text-muted-foreground">{mode === "inspect"
+ ? "Reads video properties to measure duration. Requires ffprobe on the editor server; the Docker image includes it with FFmpeg."
+ : "Video properties will not be inspected. Duration and recording date may remain unknown. File size alone cannot establish either."}</p>
+ <label className="block">Title<input className={input} required maxLength={1000} value={title} onChange={e => {changed(); setTitle(e.target.value);}} /></label>
+ <label className="block">Recording date (optional)<input className={input} type="date" value={date} onChange={e => {changed(); setDate(e.target.value);}} /></label>
+ <p className="text-sm text-muted-foreground">The record sorts and filters by this date. Leave it empty if unknown: a file's dates often say when it was copied.</p>
+ {mode === "manual" && <label className="block">Duration in seconds (optional)<input className={input} type="number" min="0.001" step="any" value={duration} onChange={e => {changed(); setDuration(e.target.value);}} /></label>}
+ <button type="submit" className={button}>Review details</button>
+ <button type="button" className={`${button} ml-2`} onClick={onClose}>Cancel</button>
+ </fieldset>
+ {error && <p role="alert" className="text-destructive">{error}</p>}
+ {review && <section aria-label="Prepared recording details" className="space-y-2 border-t border-border pt-3">
+ <p><strong>{review.metadata.title}</strong></p>
+ <p>Duration: {review.metadata.duration === undefined ? "Unknown" : `${review.metadata.duration} seconds (${mode === "inspect" ? "measured" : "entered manually"})`}</p>
+ <p>Recording date: {review.metadata.recorded_date ? `${review.metadata.recorded_date.slice(0,4)}-${review.metadata.recorded_date.slice(4,6)}-${review.metadata.recorded_date.slice(6)} (entered manually)` : "Unknown"}</p>
+ {review.metadata.filesize !== undefined && <p>File size: {review.metadata.filesize.toLocaleString()} bytes</p>}
+ <button type="button" className={button} disabled={disabled} onClick={() => onUse({fingerprint: review.fingerprint, details: review.details})}>Use details for import</button>
+ </section>}
+ </form>;
+}
diff --git a/editor/app/channels/[slug]/local-media/actions.ts b/editor/app/channels/[slug]/local-media/actions.ts
@@ -0,0 +1,54 @@
+"use server";
+import { channelWriters } from "yt-dlp-transcript-common/controller/channelWriters";
+import { adoptLocalMediaReference } from "yt-dlp-transcript-common/controller/adoptLocalMediaReference";
+import { revalidatePath } from "next/cache";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { prepareLocalMediaRecording, type LocalRecordingPreparationRequest, previewLocalMedia } from "yt-dlp-transcript-common/controller/localMediaImport";
+import { startLocalMediaImportJob, type LocalMediaJobRequest } from "yt-dlp-transcript-common/controller/localMediaImportJob";
+
+// These are private editor actions, behind the same deployment access boundary
+// as the channel's existing actions. Do not expose them through the public export.
+// Client input is validated again by the controllers. No absolute source paths
+// are accepted for import; selections refer to the stored source and preview.
+export async function previewLibraryAction(slug: string) {
+ try { return { ok: true as const, preview: await previewLocalMedia(getPaths(), slug) }; }
+ catch (e) {
+ const message = (e as Error).message ?? "";
+ if (message.startsWith("The library directory is inside")) return { ok: false as const, error: message };
+ return { ok: false as const, error: "Could not scan the library. Check its mount, channel settings, and relocation status." };
+ }
+}
+
+export async function importLibraryAction(slug: string, request: LocalMediaJobRequest) {
+ try { return await startLocalMediaImportJob(getPaths(), slug, request); }
+ catch { return { ok: false as const, error: "Could not start the import. Preview the library again and check channel availability." }; }
+}
+
+// One occupied recording per explicit click, not a silent merge during preview.
+// The controller revalidates all client tokens and exact companion bytes, refuses
+// active channel writers, and publishes without replacing an existing reference.
+// This uses the same private editor access boundary as library configuration.
+export async function linkExistingLibraryRecordingAction(slug: string,
+ selection: {sourceToken: string; media: string; fingerprint: string}) {
+ let result;
+ try {
+ result = await adoptLocalMediaReference(getPaths(), slug, selection, {apply: true});
+ } catch {
+ return {ok: false as const, error: "Could not verify and link this recording. Preview again and check that source and archived metadata/transcript files match and the channel is idle."};
+ }
+ // Publication already happened. Cache invalidation failure must not turn a
+ // successful attachment into an apparent failure or encourage blind retries.
+ try { revalidatePath(`/channels/${slug}/local-media`); } catch { /* A manual refresh is sufficient. */ }
+ return {ok: true as const, result};
+}
+
+export async function prepareLibraryRecordingAction(slug: string, request: LocalRecordingPreparationRequest) {
+ try {
+ if (channelWriters(slug, {includeQueued: true}).length) {
+ return {ok: false as const, error: "Wait for channel work to finish before preparing details."};
+ }
+ return {ok: true as const, review: await prepareLocalMediaRecording(getPaths(), slug, request)};
+ } catch {
+ return {ok: false as const, error: "Could not prepare details. Check the title, date and duration, then preview again if the recording changed. Inspection requires ffprobe on the editor server; you can explicitly choose manual entry instead."};
+ }
+}
diff --git a/editor/app/channels/[slug]/local-media/page.tsx b/editor/app/channels/[slug]/local-media/page.tsx
@@ -0,0 +1,18 @@
+import Link from "next/link";
+import { notFound } from "next/navigation";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
+import { LocalMediaPanel } from "./LocalMediaPanel";
+
+export const dynamic = "force-dynamic";
+export default async function LocalMediaPage({ params }: { params: Promise<{ slug: string }> }) {
+ const { slug } = await params;
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug) || slug.endsWith(".")) notFound();
+ const config = await readChannelConfig(getPaths(), slug);
+ if (!config || config.sourceKind === "social") notFound();
+ return <div className="flex flex-col gap-4">
+ <Link href={`/channels/${slug}`} className="underline">Back to channel</Link>
+ <h1 className="text-2xl font-semibold">Local media library</h1>
+ <LocalMediaPanel slug={slug} initialConfig={config.localMedia ?? null} />
+ </div>;
+}
diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx
@@ -996,6 +996,7 @@ export default async function ChannelDetailPage({
failedVideoIds={failedVideoIds}
generatedAt={snapshot.generatedAt}
lastSyncedAt={config.lastSyncedAt}
+ onlineSyncApplicable={!config.localMedia || !!config.url}
/>
<RunningJobsList jobs={runningJobs} hideChannelSlug />
@@ -1006,6 +1007,7 @@ export default async function ChannelDetailPage({
stageOrder={stageOrder}
stages={stages}
selected={selectedStage}
+ showLocalLibrary={!isSocialChannel(config) && !!config.localMedia}
/>
{selectedStage ? (
<section
@@ -1036,6 +1038,7 @@ export default async function ChannelDetailPage({
stageOrder={stageOrder}
stages={stages}
essentials={{
+ localArchive: !!config.localMedia,
handling: config.handling,
platform: config.platform,
url: config.url,
diff --git a/editor/app/channels/[slug]/persistActions.ts b/editor/app/channels/[slug]/persistActions.ts
@@ -1,5 +1,6 @@
"use server";
+import { localMediaWriteRefusal } from "yt-dlp-transcript-common/controller/localMediaDoors";
import { safeRevalidate } from "../../lib/safeRevalidate";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
@@ -161,6 +162,12 @@ export async function persistVideosAction(
const { items, dryRun, ...opts } = input;
if (items.length === 0) return { ok: false, error: "No videos to persist." };
const paths = getPaths();
+ // A local media library channel, a local recording, or a record linked to a
+ // library original has nothing to persist from a source (review fix 5).
+ for (const item of items) {
+ const localRefusal = await localMediaWriteRefusal(paths, item.slug, await readChannelConfig(paths, item.slug).catch(() => null), item.id);
+ if (localRefusal) return { ok: false, error: localRefusal };
+ }
const planned = await persistVideos({
paths,
items,
diff --git a/editor/app/channels/[slug]/pipelineActions.ts b/editor/app/channels/[slug]/pipelineActions.ts
@@ -1,7 +1,8 @@
"use server";
+import { localMediaMetadataRefusal } from "yt-dlp-transcript-common/lib/localMedia";
import { manualDownloadsRefusal } from "yt-dlp-transcript-common/lib/manualDownloads";
-import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig";
+import { isSocialChannel, remoteOnlyRefusal } from "yt-dlp-transcript-common/lib/channelConfig";
import { fetchPostsAction } from "./socialActions";
import path from "node:path";
import { safeRevalidate } from "../../lib/safeRevalidate";
@@ -154,6 +155,9 @@ async function runPipelineAction(
if (!channelConfig) {
return { ok: false, error: `Channel "${slug}" not found` };
}
+ // A REMOTE-ONLY channel (demo epic D1) is never listed, synced or downloaded.
+ const remoteOnly = remoteOnlyRefusal(slug, channelConfig);
+ if (remoteOnly) return { ok: false, info: true, error: remoteOnly };
if (!channelConfig.url) {
return { ok: false, error: "Channel has no `url` configured" };
}
@@ -445,6 +449,10 @@ export async function runMetadataScanAction(
if (!channelConfig) {
return { ok: false, error: `Channel "${slug}" not found` };
}
+ const remoteOnly = remoteOnlyRefusal(slug, channelConfig);
+ if (remoteOnly) return { ok: false, info: true, error: remoteOnly };
+ const localRefusal = localMediaMetadataRefusal(slug, channelConfig);
+ if (localRefusal) return { ok: false, error: localRefusal };
if (!channelConfig.url) {
return { ok: false, error: "Channel has no `url` configured" };
}
diff --git a/editor/app/channels/[slug]/playableActions.ts b/editor/app/channels/[slug]/playableActions.ts
@@ -1,5 +1,6 @@
"use server";
+import { localMediaFetchRefusal } from "yt-dlp-transcript-common/lib/localMedia";
import path from "node:path";
import { safeRevalidate } from "../../lib/safeRevalidate";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
@@ -27,6 +28,11 @@ export async function preparePlayableAction(
if (!channelConfig) {
return { ok: false, error: `Channel "${slug}" not found` };
}
+ // A local media library channel, or a local recording among the ids.
+ for (const id of [undefined, ...(opts.ids ?? [])]) {
+ const localRefusal = localMediaFetchRefusal(slug, channelConfig, id);
+ if (localRefusal) return { ok: false, error: localRefusal };
+ }
if (opts.root !== undefined && !path.isAbsolute(opts.root)) {
return { ok: false, error: `"root" must be an absolute path` };
}
diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx
@@ -1,5 +1,7 @@
"use client";
+import Link from "next/link";
+
// THE ASSEMBLY, not the cards. Each chore card's body — its state, its server
// action, its copy — is its own module under ./cards/ (enumerated, with why each
// is a chore and not an operation, in ../lib/videoChoreCards.ts). What stays here
@@ -56,6 +58,7 @@ import {
export type { FetchedWindow, VideoFile };
type Props = {
+ localRecording?: boolean;
slug: string;
videoId: string;
files: VideoFile[];
@@ -117,6 +120,7 @@ type Props = {
};
export function VideoPanel({
+ localRecording = false,
slug,
videoId,
files,
@@ -189,7 +193,9 @@ export function VideoPanel({
: hasTranscript
? "Transcript present."
: noAudio
- ? "No audio yet — run the download pipeline (or use Audio + Whisper) to produce a transcript."
+ ? localRecording
+ ? "No imported transcript. Review this recording in the Local media library."
+ : "No audio yet — run the download pipeline (or use Audio + Whisper) to produce a transcript."
: "Audio ready, no transcript.";
const transcodeSummary =
transcodeSources.length > 0
@@ -220,11 +226,11 @@ export function VideoPanel({
<span className="text-muted-foreground"> — this recording's life cycle: its windows, every cut that uses it, what was checked, rendered and published</span>
</div>
)}
- <PipelineStatusStrip
+ {!localRecording && <PipelineStatusStrip
downloaded={!noAudio}
transcribed={hasTranscript}
downloadFailed={downloadFailed}
- />
+ />}
{downloadOutcome && <DownloadOutcomeBadge outcome={downloadOutcome} />}
{salvageShown && salvaged && (
<SalvagedTranscriptNotice
@@ -251,7 +257,7 @@ export function VideoPanel({
<IncompleteTranscriptBanner
slug={slug}
videoId={videoId}
- coverage={incompleteTranscript ? coverage : null}
+ coverage={!localRecording && incompleteTranscript ? coverage : null}
defaultQueueKey={defaultQueueKey}
existingQueues={existingQueues}
/>
@@ -259,7 +265,7 @@ export function VideoPanel({
slug={slug}
videoId={videoId}
flagged={
- downloadOutcome?.status === "failed-short-audio" &&
+ !localRecording && downloadOutcome?.status === "failed-short-audio" &&
!excludedFromTruncatedCheck
}
shortAudio={downloadOutcome?.shortAudio}
@@ -288,7 +294,14 @@ export function VideoPanel({
Media archived — cleanup will skip this video.
</div>
)}
- <PipelineStageCard
+ {localRecording ? (
+ <section aria-label="Local recording" className="rounded border p-4 flex flex-col gap-2">
+ <h3 className="font-semibold">Local recording</h3>
+ <p>This record was imported from your local library and has no online download source. The original video stays in your library.</p>
+ <Link className="underline" href={"/channels/" + encodeURIComponent(slug) + "/local-media"}>Open local media library</Link>
+ {incompleteTranscript && <p role="status">The imported transcript may not cover the full recording. Review the original subtitles; an online re-download is not available for this record.</p>}
+ </section>
+ ) : <PipelineStageCard
id="download"
title={noAudio ? "Download audio" : "Redownload audio"}
summary={downloadSummary}
@@ -313,7 +326,7 @@ export function VideoPanel({
storedMediaHost={storedMediaHost}
channelStoredUrl={channelStoredUrl}
/>
- </PipelineStageCard>
+ </PipelineStageCard>}
{transcodeSources.length > 0 && (
<PipelineStageCard
@@ -370,7 +383,7 @@ export function VideoPanel({
</div>
</PipelineStageCard>
- <SubtitleDeferralLine slug={slug} videoId={videoId} />
+ {!localRecording && <SubtitleDeferralLine slug={slug} videoId={videoId} />}
{hasTranscript && (
<PipelineStageCard
@@ -415,7 +428,7 @@ export function VideoPanel({
</PipelineStageCard>
)}
- {!hasTranscript && (
+ {!localRecording && !hasTranscript && (
<PipelineStageCard
id="mark-untranscribable"
title="Mark untranscribable"
@@ -427,7 +440,7 @@ export function VideoPanel({
</PipelineStageCard>
)}
- <PipelineStageCard
+ {!localRecording && <PipelineStageCard
id="source-video-persistence"
title="Source video"
summary={
@@ -447,7 +460,7 @@ export function VideoPanel({
savedVideo={savedVideo}
defaultQuality={sourceVideoQuality}
/>
- </PipelineStageCard>
+ </PipelineStageCard>}
{clipWindows.length > 0 && (
<PipelineStageCard
diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx
@@ -397,7 +397,7 @@ export default async function VideoDetailPage({
none, and the action refuses it rather than create one), and not
for an archive.org record or a Wayback copy: their metadata is not
yt-dlp's, and the action refuses them too. */}
- {dirData.files.length > 0 && !archiveOrg && !wayback && (
+ {!meta.localRecording && dirData.files.length > 0 && !archiveOrg && !wayback && (
<RefreshMetadataControl
slug={slug}
videoId={id}
@@ -407,7 +407,7 @@ export default async function VideoDetailPage({
)}
{/* Release 32 R9: an Odysee channel's record read from its page in a
headless browser, for when yt-dlp's lookup is refused. */}
- {BROWSER_LOOKUP_PLATFORMS.includes(config.platform ?? detectPagePlatform(config.url ?? null) ?? "") && (
+ {!meta.localRecording && BROWSER_LOOKUP_PLATFORMS.includes(config.platform ?? detectPagePlatform(config.url ?? null) ?? "") && (
<BrowserLookupControl slug={slug} videoId={id} />
)}
</header>
@@ -415,6 +415,7 @@ export default async function VideoDetailPage({
<RunningJobsList jobs={activeJobs} hideChannelSlug hideVideoId />
<VideoPanel
+ localRecording={meta.localRecording}
slug={slug}
videoId={id}
files={dirData.files}
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -1,5 +1,6 @@
"use server";
+import { localMediaFetchRefusal } from "yt-dlp-transcript-common/lib/localMedia";
import path from "node:path";
import { lstat, readdir, readFile, rm, stat } from "node:fs/promises";
import { revalidatePath } from "next/cache";
@@ -261,6 +262,9 @@ export async function transcribeOneAction(
): Promise<StreamActionResult> {
const r = await loadConfigOrError(slug);
if (!r.ok) return r;
+ // A local media record: nothing to transcribe from a source (slice 3's drafts).
+ const localRefusal = localMediaFetchRefusal(slug, r.config, videoId);
+ if (localRefusal) return { ok: false, error: localRefusal };
return queueTranscribeOne({
slug,
videoId,
@@ -722,6 +726,8 @@ export async function whisperVideoAction(
): Promise<WhisperVideoResult> {
const r = await loadConfigOrError(slug);
if (!r.ok) return r;
+ const localRefusal = localMediaFetchRefusal(slug, r.config, videoId);
+ if (localRefusal) return { ok: false, error: localRefusal };
const paths = getPaths();
const videoDir = videoDirOf(slug, videoId);
const audioFormat = r.config.audioFormat ?? "mp3";
@@ -1609,6 +1615,9 @@ export async function fetchWindowAction(req: {
}
const r = await loadConfigOrError(slug);
if (!r.ok) return { ok: false, status: 404, error: r.error };
+ // Before the cache: a local library's recording has no window to hold.
+ const localRefusal = localMediaFetchRefusal(slug, r.config, req.videoId);
+ if (localRefusal) return { ok: false, status: 409, error: localRefusal };
const paths = getPaths();
// From here on the video is named by its directory: the cache, the job, the
// page revalidated (a Twitch record's v<n> is data/<n>/).
@@ -1969,6 +1978,8 @@ export async function fetchFullSourceAction(req: {
const { slug } = req;
const r = await loadConfigOrError(slug);
if (!r.ok) return { ok: false, status: 404, error: r.error };
+ const localRefusal = localMediaFetchRefusal(slug, r.config, req.videoId);
+ if (localRefusal) return { ok: false, status: 409, error: localRefusal };
const paths = getPaths();
const videoId = await recordDirIdOf(slug, req.videoId, r.config);
const videoDir = videoDirOf(slug, videoId);
diff --git a/editor/app/channels/[slug]/videos/fetchWindowLocalMedia.test.ts b/editor/app/channels/[slug]/videos/fetchWindowLocalMedia.test.ts
@@ -0,0 +1,70 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/channels/*/videos/fetchWindowLocalMedia.test.ts"
+//
+// The editor's fetch doors refuse a local media library channel and a local
+// recording with one sentence (lib/localMedia.ts localMediaFetchRefusal), before
+// the window cache and before any job: fetch-window, full source, and the
+// fetch-windows planner. Nothing reaches the network.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetch-window-local-"));
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 }));
+const LOCAL_ID = "local-" + "a".repeat(32);
+async function channel(slug: string, config: Record<string, unknown>, ids: string[]) {
+ await mkdir(path.join(ROOT, "channels", slug), { recursive: true });
+ await writeFile(path.join(ROOT, "channels", slug, "config.json"), JSON.stringify(config));
+ for (const id of ids) {
+ await mkdir(path.join(ROOT, "channels", slug, "data", id), { recursive: true });
+ await writeFile(path.join(ROOT, "channels", slug, "data", id, "metadata.info.json"),
+ JSON.stringify({ id, title: id, webpage_url: `https://www.youtube.com/watch?v=${id}` }));
+ }
+}
+// A Local Archive channel (no URL), holding a provider-metadata record too.
+await channel("library", { name: "Library", handling: "youtube", sourceKind: "video",
+ localMedia: { sourceId: "library-1", directory: "/mnt/library" } }, [LOCAL_ID, "aaaaaaaaaaa"]);
+// An online channel with a library: its online records fetch as before, its local one does not.
+await channel("hybrid", { name: "Hybrid", handling: "youtube", url: "https://www.youtube.com/@hybrid",
+ localMedia: { sourceId: "library-1", directory: "/mnt/library" } }, [LOCAL_ID]);
+
+const { fetchWindowAction, fetchFullSourceAction } = await import("./[id]/videoActions");
+const { fetchWindowsAction } = await import("./fetchWindowsAction");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const SENTENCE = /with no online source, so no clip can be fetched for it\./;
+
+test("fetch-window and full source refuse a local library channel and a local recording", async () => {
+ for (const [slug, videoId, who] of [["library", "aaaaaaaaaaa", /"library" is a local media library channel/],
+ ["library", LOCAL_ID, /is a local recording/], ["hybrid", LOCAL_ID, /is a local recording/]] as const) {
+ const w = await fetchWindowAction({ slug, videoId, from: 5, to: 15, provenance: { requestedBy: "test" } });
+ assert.equal(w.ok, false, JSON.stringify(w));
+ if (w.ok) continue;
+ assert.equal(w.status, 409);
+ assert.match(w.error, SENTENCE);
+ assert.match(w.error, who);
+ const f = await fetchFullSourceAction({ slug, videoId, provenance: { requestedBy: "test" } });
+ assert.equal(f.ok, false);
+ if (!f.ok) assert.match(f.error, SENTENCE);
+ }
+ // Nothing was made: no clips/ dir, no job.
+ assert.deepEqual(await readdir(path.join(ROOT, "channels", "library", "data", LOCAL_ID)), ["metadata.info.json"]);
+});
+
+test("the fetch-windows planner puts a local item in unresolved with the sentence", async () => {
+ const r = await fetchWindowsAction({
+ items: [{ slug: "library", id: "aaaaaaaaaaa", from: 5, to: 15 }, { slug: "hybrid", id: LOCAL_ID, from: 5, to: 15 }],
+ requestedBy: "test",
+ dryRun: true,
+ });
+ assert.ok(r.ok, JSON.stringify(r));
+ if (!r.ok) return;
+ assert.equal(r.unresolved.length, 2);
+ for (const u of r.unresolved) assert.match(u.error, SENTENCE);
+ assert.deepEqual(r.groups, []);
+});
diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts
@@ -1,5 +1,6 @@
"use server";
+import { localMediaFetchRefusal } from "yt-dlp-transcript-common/lib/localMedia";
import path from "node:path";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
@@ -61,6 +62,14 @@ import {
type StreamActionResult,
} from "yt-dlp-transcript-common/jobs/streamCommand";
import { safeRevalidate } from "../../../lib/safeRevalidate";
+import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig";
+import { connectedArchives, disconnectedArchiveRefusal, findConnectedArchive, recordPage, type ConnectedArchive } from "yt-dlp-transcript-common/lib/remoteArchives";
+import {
+ archiveRecordOf,
+ ensureRemoteOnlyChannel,
+ wholeRecordingRefusal,
+} from "yt-dlp-transcript-common/controller/remoteOnlyChannel";
+import { cachedArchiveGetJson } from "yt-dlp-transcript-common/lib/archiveCache-server";
// FETCH A LIST OF CLIP WINDOWS through the managed path, as ONE JOB PER
// PLATFORM QUEUE (controller/fetchWindows.ts walks each one, paced).
@@ -122,6 +131,15 @@ export type FetchWindowsRequest = {
minGapSeconds?: number;
// false: every window by a remote seek, the whole-recording platforms' too.
wholeRecording?: boolean;
+ // THE ARCHIVE THE ITEMS CITE (demo epic D1): a connected archive's origin
+ // (settings.remoteArchives). A channel this editor does not hold is then
+ // registered as a REMOTE-ONLY channel of it (controller/remoteOnlyChannel.ts)
+ // instead of refused, and a remote-only channel's page URL comes from the
+ // archive's record. A dry run registers nothing.
+ archive?: string;
+ // A remote-only channel's window on a whole-recording platform (Rumble) is
+ // refused with the recording's size unless this is true.
+ allowWholeRecording?: boolean;
};
export type FetchWindowsUnresolved = { item: FetchWindowsItem; error: string };
@@ -152,6 +170,9 @@ export type FetchWindowsActionResult =
// Windows a queued or running job will already write, and that job.
inFlight: FetchWindowsInFlight[];
unresolved: FetchWindowsUnresolved[];
+ // Channels registered as remote-only for these windows (a dry run: the
+ // ones that would be), each once.
+ registered: string[];
};
export type FetchWindowsInFlight = { item: FetchWindowsItem; jobId: string };
@@ -185,11 +206,13 @@ async function planFetchWindows(
maxHeight: number | undefined,
storedMode: StoredUrlMode,
wholeRecording?: boolean,
+ remote: { archive?: ConnectedArchive | null; unconnected?: string; allowWholeRecording?: boolean; dryRun?: boolean } = {},
): Promise<{
groups: FetchWindowsGroup[];
cached: FetchWindowsItem[];
inFlight: FetchWindowsInFlight[];
unresolved: FetchWindowsUnresolved[];
+ registered: string[];
// The planned items (as grouped) whose record stores a trusted media URL.
stored: Set<FetchWindowsItem>;
}> {
@@ -201,6 +224,10 @@ async function planFetchWindows(
const inFlight: FetchWindowsInFlight[] = [];
const unresolved: FetchWindowsUnresolved[] = [];
const stored = new Set<FetchWindowsItem>();
+ const registered: string[] = [];
+ // A slug the archive could not register, with why (asked once per run).
+ const unregistrable = new Map<string, string>();
+ const getJson = cachedArchiveGetJson();
const live = getRegistry().list();
for (const item of dedupeFetchWindowsItems(items)) {
const problem = itemProblem(item);
@@ -211,9 +238,41 @@ async function planFetchWindows(
if (!configs.has(item.slug)) {
configs.set(item.slug, await readChannelConfig(paths, item.slug));
}
- const config = configs.get(item.slug);
+ let config = configs.get(item.slug);
+ // NOT HELD HERE, CITED FROM A CONNECTED ARCHIVE (demo epic D1): registered
+ // as a remote-only channel of it, config only — or, in a dry run, said.
+ if (!config && remote.archive && !unregistrable.has(item.slug)) {
+ if (remote.dryRun) {
+ if (!registered.includes(item.slug)) registered.push(item.slug);
+ unresolved.push({ item, error: `Channel "${item.slug}" is not held here: the run would register it as a remote-only channel of ${remote.archive.origin}` });
+ continue;
+ }
+ try {
+ const r = await ensureRemoteOnlyChannel(paths, item.slug, remote.archive, { getJson });
+ config = r.config;
+ configs.set(item.slug, config);
+ if (r.registered && !registered.includes(item.slug)) registered.push(item.slug);
+ } catch (e) {
+ unregistrable.set(item.slug, (e as Error).message);
+ }
+ }
if (!config) {
- unresolved.push({ item, error: `Channel "${item.slug}" not found` });
+ const why = unregistrable.get(item.slug);
+ unresolved.push({
+ item,
+ error:
+ `Channel "${item.slug}" not found` +
+ (why
+ ? `, and it could not be registered from its archive: ${why}`
+ : remote.unconnected
+ ? ` — ${remote.unconnected} is not a connected archive: connect it (/sites → Connected archives, or pnpm ops archives {"connect": …}) to fetch its windows here`
+ : ""),
+ });
+ continue;
+ }
+ const localRefusal = localMediaFetchRefusal(item.slug, config, item.id);
+ if (localRefusal) {
+ unresolved.push({ item, error: localRefusal });
continue;
}
// The item names a RECORD; its directory may be another id — a Twitch
@@ -292,9 +351,40 @@ async function planFetchWindows(
continue;
}
}
- const url =
+ // An archive removed from settings is not read any more, for a channel
+ // registered while it was connected either: nothing is asked of it.
+ if (isRemoteOnlyChannel(config)) {
+ const gone = disconnectedArchiveRefusal(config.remoteArchive, connectedArchives(settings.remoteArchives));
+ if (gone) {
+ unresolved.push({ item, error: `${item.slug} is a remote-only channel, and ${gone}` });
+ continue;
+ }
+ }
+ // A REMOTE-ONLY channel has no metadata or playlist of its own: the page
+ // URL is the ask's, else its archive's record.
+ const record =
+ isRemoteOnlyChannel(config) && config.remoteArchive
+ ? await archiveRecordOf(config.remoteArchive, item.slug, item.id, { getJson }).catch(() => null)
+ : null;
+ let url =
item.webpageUrl?.trim() ||
- (await findVideoSourceUrl(paths, item.slug, dirId, config));
+ record?.webpageUrl ||
+ (isRemoteOnlyChannel(config) ? null : await findVideoSourceUrl(paths, item.slug, dirId, config));
+ // An archive is untrusted input (demo epic D1 review): a remote-only
+ // channel's page URL must name its own video platform's host, or nothing
+ // is asked of it. What goes on is the URL the check parsed, written back
+ // — never the string the archive or the ask gave.
+ if (isRemoteOnlyChannel(config)) {
+ const raw = item.webpageUrl?.trim() || record?.webpageUrl;
+ if (raw) {
+ const page = recordPage(raw, config.platform ?? null, detectPlatform);
+ if ("refused" in page) {
+ unresolved.push({ item, error: page.refused });
+ continue;
+ }
+ url = page.href;
+ }
+ }
if (!url) {
unresolved.push({
item,
@@ -310,6 +400,15 @@ async function planFetchWindows(
// only itself.
const platform = detectPlatform(url) ?? "unknown";
const whole = wholeRecordingFor(settings, platform, item, wholeRecording);
+ // A remote-only channel's whole recording is a download nobody planned:
+ // refused with its size until the ask allows it (one press in umtool).
+ if (whole && isRemoteOnlyChannel(config) && !remote.allowWholeRecording) {
+ unresolved.push({
+ item,
+ error: wholeRecordingRefusal({ platform, slug: item.slug, id: item.id, ...(record?.duration !== undefined ? { duration: record.duration } : {}), ...(maxHeight ? { maxHeight } : {}) }),
+ });
+ continue;
+ }
const queueKey = resolveQueueKey(
whole ? queueKeyForUrl(url) : clipWindowQueueKey(queueKeyForUrl(url)),
queueOverride,
@@ -328,7 +427,7 @@ async function planFetchWindows(
}
groups.set(queueKey, group);
}
- return { groups: [...groups.values()], cached, inFlight, unresolved, stored };
+ return { groups: [...groups.values()], cached, inFlight, unresolved, stored, registered };
}
// The door each group passes before its job is queued: the platform's hold,
@@ -455,14 +554,28 @@ export async function fetchWindowsAction(
};
}
const storedMode = req.storedUrl ?? "never";
- const { groups, cached, inFlight, unresolved, stored } = await planFetchWindows(
+ // The archive the items cite: only a CONNECTED one registers anything. Any
+ // other origin (a site's own, an archive not connected) registers nothing —
+ // a channel held here is fetched as always, one not held is refused, naming
+ // the connect that would register it.
+ const archive: ConnectedArchive | null = req.archive?.trim()
+ ? findConnectedArchive(connectedArchives(getSettings().remoteArchives), req.archive)
+ : null;
+ const { groups, cached, inFlight, unresolved, stored, registered } = await planFetchWindows(
req.items,
req.queueKey,
req.maxHeight,
storedMode,
req.wholeRecording,
+ {
+ archive,
+ ...(req.archive?.trim() && !archive ? { unconnected: req.archive.trim() } : {}),
+ allowWholeRecording: req.allowWholeRecording === true,
+ dryRun: req.dryRun === true,
+ },
);
- const base = { groups, cached, inFlight, unresolved, jobs: [], refused: [] };
+ if (registered.length && !req.dryRun) safeRevalidate(["/channels"]);
+ const base = { groups, cached, inFlight, unresolved, registered, jobs: [], refused: [] };
if (req.dryRun) return { ok: true, dryRun: true, ...base };
if (groups.length === 0) return { ok: true, dryRun: false, ...base };
@@ -536,7 +649,7 @@ export async function fetchWindowsAction(
error: refused.map((r) => `${r.platform}: ${r.error}`).join("; "),
};
}
- return { ok: true, dryRun: false, groups, cached, inFlight, unresolved, jobs, refused };
+ return { ok: true, dryRun: false, groups, cached, inFlight, unresolved, registered, jobs, refused };
}
export type FetchMissingEvidenceResult =
@@ -600,6 +713,7 @@ async function fetchMissingFor(
cached: [],
inFlight: [],
unresolved: [],
+ registered: [],
...extra,
};
}
diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts
@@ -1,5 +1,7 @@
"use server";
+import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig";
+import { prepareLocalArchiveChannel } from "./lib/prepareLocalArchiveChannel";
import { withRumbleDefaults } from "yt-dlp-transcript-common/lib/rumbleDefaults";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
@@ -231,7 +233,9 @@ export async function createChannelAction(
): Promise<ActionResult> {
const result = await createChannelFromForm(formData);
if (!result.ok) return { error: result.error, values: result.values };
- redirect(`/channels/${result.slug}`);
+ redirect(formData.get("localArchive") === "on"
+ ? `/channels/${result.slug}/local-media`
+ : `/channels/${result.slug}`);
}
export async function createChannelFromForm(
@@ -242,7 +246,11 @@ export async function createChannelFromForm(
const jobIds: string[] = [];
let parsed;
try {
- parsed = parseChannelForm(formData);
+ // Build local configuration from an allowlist before any channel/site writes.
+ // Hidden or stale online fields must not accidentally schedule network work.
+ parsed = formData.get("localArchive") === "on"
+ ? await prepareLocalArchiveChannel(getPaths(), formData)
+ : parseChannelForm(formData);
} catch (e) {
return fail((e as Error).message);
}
@@ -638,6 +646,7 @@ export async function syncAllChannelsAction(
skip: async (slug) => {
const config = bySlug.get(slug);
if (!config?.url) return "no url";
+ if (isRemoteOnlyChannel(config)) return "remote-only";
if (isChannelPaused(priority, slug, "sync")) return "paused for sync";
if (active.has(slug)) return "already running";
const media = await inspectChannelMedia(paths, slug, config);
diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx
@@ -168,6 +168,10 @@ export function ChannelForm({
}: Props) {
const isEdit = !!initial;
const c = initial?.config;
+ // Creation choice only: existing channels can combine online and local media.
+ // Never infer a conversion or erase their online settings from this toggle.
+ const [localArchive, setLocalArchive] = useState(seedChecked(state, "localArchive", false));
+ const creatingLocal = !isEdit && localArchive;
// Edit mode's handling radios are uncontrolled: a radio group seeds from the
// VALUE it posted, not from whether its name was there.
const editHandling = seedValue(
@@ -225,7 +229,7 @@ export function ChannelForm({
isWaybackPagesUrl(url) ||
platform === "x-search";
// An X search channel (release 38): a query across accounts, never on a site.
- const isXSearch = isEdit ? Boolean(c?.xSearch) : platform === "x-search";
+ const isXSearch = isEdit ? Boolean(c?.xSearch) : !creatingLocal && platform === "x-search";
// A Wayback pages channel (release 37): captures of pages, no fetcher; its
// scope is its targets.
const isWaybackPages = isEdit ? c?.platform === "webpage" : platform === "webpage";
@@ -385,6 +389,37 @@ export function ChannelForm({
)}
</Section>
<Section title="Source">
+ {!isEdit && (
+ <label className="flex items-center gap-2 text-sm font-medium">
+ <input type="checkbox" name="localArchive" checked={localArchive}
+ disabled={probe.state === "loading"}
+ onChange={(event) => {
+ setLocalArchive(event.target.checked);
+ if (event.target.checked && !slugTouched) setSlug("");
+ }} />
+ Local Archive
+ </label>
+ )}
+ {creatingLocal ? (
+ <>
+ <p className="text-sm text-muted-foreground">
+ Use existing recordings and transcripts from a directory. No URL,
+ online fetching, download format or transcription settings are needed.
+ </p>
+ <Field label="Directory on the editor server" name="localDirectory"
+ state={state} required placeholder="/mnt/archives/creator"
+ hint="Docker: enter the path inside the container, using a read-only archive mount. Without Docker: enter an absolute directory the editor can read, such as /home/you/videos/creator. The directory must already exist." />
+ <Field label="Library ID" name="localSourceId" state={state}
+ required defaultValue="library-1"
+ hint="A stable identifier within this channel: lowercase letters, numbers, hyphens or underscores; start with a letter or number (up to 64 characters)." />
+ <p className="text-xs text-muted-foreground">
+ After creation, preview matching MP4, .info.json and .vtt files and
+ select recordings to import. Subdirectories are not scanned. Originals
+ stay in place.
+ </p>
+ </>
+ ) : (
+ <>
{isEdit ? (
<>
<fieldset className="flex flex-col gap-2">
@@ -687,11 +722,13 @@ export function ChannelForm({
value={c?.syncIntervalMinutes}
fullSweepValue={c?.fullSweepIntervalMinutes}
/>
+ </>
+ )}
</Section>
{/* Video-only sections. A social account has no audio, no download
format and no source video to retain, so they are hidden entirely
rather than shown as inert controls. */}
- {!isSocial && (
+ {!creatingLocal && !isSocial && (
<>
<Section title="Transcription">
<label className="flex flex-col gap-1 text-sm">
@@ -955,6 +992,7 @@ export function ChannelForm({
</Section>
</>
)}
+ {!creatingLocal && (
<CollapsibleSection title="Advanced">
<Fragment key={`args-${rumbleKey}`}>
<label className="flex flex-col gap-1 text-sm">
@@ -1156,6 +1194,7 @@ export function ChannelForm({
</span>
</label>
</CollapsibleSection>
+ )}
<div className="flex gap-2">
<button
type="submit"
diff --git a/editor/app/channels/components/ChannelTierSelect.tsx b/editor/app/channels/components/ChannelTierSelect.tsx
@@ -67,6 +67,8 @@ export type ChannelTierSelectProps = {
// A manual-downloads channel (lib/manualDownloads.ts): the download lane
// skips it by design, so its rack row says so rather than looking stalled.
manualDownloads?: boolean;
+ // A remote-only channel's archive origin (demo epic D1), else null/undefined.
+ remoteOnly?: string | null;
disabled?: boolean;
};
@@ -98,6 +100,7 @@ export default function ChannelTierSelect({
autoPausedReason = null,
mediaHold = null,
manualDownloads = false,
+ remoteOnly = null,
disabled = false,
}: ChannelTierSelectProps): React.ReactNode {
const [pending, startTransition] = useTransition();
@@ -213,6 +216,17 @@ export default function ChannelTierSelect({
<span className="sr-only"> — {mediaHold}</span>
</span>
)}
+ {remoteOnly !== null && remoteOnly !== undefined && (
+ <span
+ role="note"
+ aria-label={`remote-only channel ${slug}`}
+ title={`Remote-only: holds clip windows of ${remoteOnly || "a connected archive"}; never listed, synced or downloaded here.`}
+ className="rounded-full border border-border px-1.5 text-[10px] uppercase tracking-wide text-muted-foreground"
+ >
+ remote only
+ <span className="sr-only"> — holds clip windows of {remoteOnly || "a connected archive"}</span>
+ </span>
+ )}
{manualDownloads && (
<span
role="note"
diff --git a/editor/app/channels/components/ChannelsTable.tsx b/editor/app/channels/components/ChannelsTable.tsx
@@ -126,7 +126,7 @@ function cmp(a: ChannelRowView, b: ChannelRowView, key: ChannelSortKey): number
case "name":
return compareStrings(a.name, b.name);
case "handling":
- return compareStrings(a.handling, b.handling);
+ return compareStrings(a.handlingLabel ?? a.handling, b.handlingLabel ?? b.handling);
case "build":
return compareBools(a.excludeFromBuild, b.excludeFromBuild);
case "tier":
diff --git a/editor/app/channels/components/channelColumns.tsx b/editor/app/channels/components/channelColumns.tsx
@@ -149,7 +149,7 @@ export const CHANNEL_COLUMNS: Record<
sortKey: "handling",
cell: (c) => ({
className: "font-mono text-[11px] text-muted-foreground",
- content: c.handling,
+ content: c.handlingLabel ?? c.handling,
}),
},
build: {
@@ -180,6 +180,7 @@ export const CHANNEL_COLUMNS: Record<
autoPausedReason={c.priority.autoPausedReason}
mediaHold={c.mediaHold}
manualDownloads={c.manualDownloads}
+ remoteOnly={c.remoteOnly}
/>
),
}),
diff --git a/editor/app/channels/lib/prepareLocalArchiveChannel.test.ts b/editor/app/channels/lib/prepareLocalArchiveChannel.test.ts
@@ -0,0 +1,74 @@
+import test, { type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, readdir, readFile, writeFile, rm, symlink } from "node:fs/promises";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import type { Paths } from "yt-dlp-transcript-common/lib/paths";
+import { prepareLocalArchiveChannel } from "./prepareLocalArchiveChannel";
+
+async function fixture(t: TestContext) {
+ const root = await mkdtemp(path.join(tmpdir(), "local-channel-setup-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const directory = path.join(root, "library");
+ await mkdir(directory);
+ const paths = { transcriptsDir: path.join(root, "corpus") } as Paths;
+ const form = new FormData();
+ for (const [key, value] of Object.entries({ name: " Example ", localSourceId: "library-1", localDirectory: directory })) form.set(key, value);
+ return { root, directory, paths, form };
+}
+
+test("local creation leaves playback off and ignores stale online fields; preparation writes nothing", async t => {
+ const f = await fixture(t);
+ await writeFile(path.join(f.directory, "original.mp4"), "original bytes");
+ for (const [key,value] of Object.entries({url:"https://example.com/account", platform:"twitter", sourceKind:"social", handling:"transcribe", fetchPostsNow:"on", fetchPlaylist:"on", prioritizeDownload:"on", syncIntervalMinutes:"1"})) f.form.set(key,value);
+ const result = await prepareLocalArchiveChannel(f.paths, f.form);
+ assert.deepEqual(result, { name:"Example", slug:"", config:{name:"Example", handling:"youtube", sourceKind:"video", localMedia:{sourceId:"library-1",directory:f.directory}, syncIntervalMinutes:0,fullSweepIntervalMinutes:0}, warnings:[] });
+ assert.equal("playback" in result.config.localMedia!, false);
+ assert.deepEqual(await readdir(f.root), ["library"]);
+ assert.equal(await readFile(path.join(f.directory,"original.mp4"),"utf8"),"original bytes");
+});
+
+test("invalid identity, relative path, missing directory and regular file fail before writes", async t => {
+ const f = await fixture(t);
+ await writeFile(path.join(f.root,"file"),"not a directory");
+ for (const directory of ["relative",path.join(f.root,"missing"),path.join(f.root,"file")]) {
+ f.form.set("localDirectory",directory);
+ await assert.rejects(prepareLocalArchiveChannel(f.paths,f.form));
+ }
+ f.form.set("localDirectory",f.directory);
+ f.form.set("localSourceId","../bad");
+ await assert.rejects(prepareLocalArchiveChannel(f.paths,f.form));
+ f.form.set("localSourceId","library-1");
+ f.form.set("name"," ");
+ await assert.rejects(prepareLocalArchiveChannel(f.paths,f.form),/Name is required/);
+ assert.deepEqual((await readdir(f.root)).sort(),["file","library"]);
+});
+
+test("corpus overlap is refused in either direction, including linked ancestors", async t => {
+ const f = await fixture(t);
+ await mkdir(f.paths.transcriptsDir);
+ await mkdir(path.join(f.paths.transcriptsDir,"nested"));
+ const alias = path.join(f.root,"alias");
+ await symlink(f.paths.transcriptsDir,alias,"dir");
+ for (const directory of [f.root,f.paths.transcriptsDir,path.join(f.paths.transcriptsDir,"nested"),alias]) {
+ f.form.set("localDirectory",directory);
+ await assert.rejects(prepareLocalArchiveChannel(f.paths,f.form),/must be separate|The library directory (is inside|contains) the corpus/);
+ }
+ const absentCorpus = {...f.paths,transcriptsDir:path.join(alias,"not-created")};
+ f.form.set("localDirectory",f.paths.transcriptsDir);
+ await assert.rejects(prepareLocalArchiveChannel(absentCorpus,f.form),/must be separate|The library directory is inside the corpus/);
+});
+
+test("operator-selected directory link and sibling-prefix paths are allowed", async t => {
+ const f = await fixture(t);
+ const alias = path.join(f.root,"library-link");
+ await symlink(f.directory,alias,"dir");
+ f.form.set("localDirectory",alias);
+ f.form.set("slug","explicit-slug");
+ assert.equal((await prepareLocalArchiveChannel(f.paths,f.form)).config.localMedia?.directory,alias);
+ assert.equal((await prepareLocalArchiveChannel(f.paths,f.form)).slug,"explicit-slug");
+ const sibling = path.join(f.root,"corpus-extra");
+ await mkdir(sibling);
+ f.form.set("localDirectory",sibling);
+ await prepareLocalArchiveChannel(f.paths,f.form);
+});
diff --git a/editor/app/channels/lib/prepareLocalArchiveChannel.ts b/editor/app/channels/lib/prepareLocalArchiveChannel.ts
@@ -0,0 +1,64 @@
+import path from "node:path";
+import { libraryLocationProblem } from "yt-dlp-transcript-common/controller/localMediaLocation";
+import { access, realpath, stat } from "node:fs/promises";
+import { constants } from "node:fs";
+import type { Paths } from "yt-dlp-transcript-common/lib/paths";
+import { coerceLocalMediaConfig } from "yt-dlp-transcript-common/lib/localMedia";
+import type { ParsedChannelForm } from "../components/parseChannelForm";
+
+function contains(parent: string, child: string): boolean {
+ const relative = path.relative(parent, child);
+ return !relative || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
+}
+
+// First-run installs may not have a corpus yet. Resolve its existing ancestors
+// without creating anything, including when a parent is a directory symlink.
+async function prospectiveRealpath(directory: string): Promise<string> {
+ try { return await realpath(directory); }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ const parent = path.dirname(directory);
+ if (parent === directory) throw error;
+ return path.join(await prospectiveRealpath(parent), path.basename(directory));
+ }
+}
+
+// Create-only preparation. Reuse the normal channel/site creation action after
+// validating the directory, rather than creating a half-configured channel and
+// asking the operator to retry a second setup action. This function writes nothing.
+export async function prepareLocalArchiveChannel(paths: Paths, form: FormData): Promise<ParsedChannelForm> {
+ const name = String(form.get("name") ?? "").trim();
+ if (!name) throw new Error("Name is required");
+ const slug = String(form.get("slug") ?? "").trim();
+ const localMedia = coerceLocalMediaConfig({
+ sourceId: String(form.get("localSourceId") ?? "").trim(),
+ directory: String(form.get("localDirectory") ?? "").trim(),
+ // Playback is never on by default: serving originals is its own opt-in.
+ });
+ if (!localMedia || !path.isAbsolute(localMedia.directory)) {
+ throw new Error("Enter a valid library ID and an absolute directory on the editor server");
+ }
+ let source: string;
+ try {
+ source = await realpath(localMedia.directory);
+ if (!(await stat(source)).isDirectory()) throw new Error("Not a directory");
+ await access(source, constants.R_OK | constants.X_OK);
+ } catch {
+ throw new Error("Library directory is unavailable or unreadable. In Docker, use the mounted path inside the container.");
+ }
+ const corpus = await prospectiveRealpath(path.resolve(paths.transcriptsDir));
+ const misplaced = await libraryLocationProblem(paths, source);
+ if (misplaced) throw new Error(misplaced);
+ if (contains(source, corpus) || contains(corpus, source)) {
+ throw new Error("Library and corpus directories must be separate");
+ }
+ return {
+ name, slug,
+ // Handling remains required by the video schema. With no URL and sync off,
+ // this compatibility value does not select an online source or start work.
+
+ config: { name, handling: "youtube", sourceKind: "video", localMedia,
+ syncIntervalMinutes: 0, fullSweepIntervalMinutes: 0 },
+ warnings: [],
+ };
+}
diff --git a/editor/app/cleanup/lib/loadCleanup.ts b/editor/app/cleanup/lib/loadCleanup.ts
@@ -1,3 +1,4 @@
+import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig";
import type { Paths } from "yt-dlp-transcript-common/lib/paths";
import type { ChannelBrief } from "yt-dlp-transcript-common/controller/channels";
import { getChannelBriefs } from "../../lib/requestCache";
@@ -247,6 +248,8 @@ export async function cleanableChannels(
const channels = await getChannelBriefs(paths);
const rows = channels.map((channel) => {
if (channel.config.excludeFromCleanup) return null;
+ // A remote-only channel (demo epic D1) has nothing a cleanup sweeps.
+ if (isRemoteOnlyChannel(channel.config)) return null;
const snap = channel.snapshot;
const bytes = transcribedBytesOf(snap);
const count = snap?.buckets.transcribedWithAudio?.length ?? 0;
diff --git a/editor/app/sites/[siteId]/page.tsx b/editor/app/sites/[siteId]/page.tsx
@@ -1,6 +1,6 @@
import { notFound } from "next/navigation";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
-import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels";
+import { siteChannelOptions } from "../lib/channelOptions";
import { listSites } from "yt-dlp-transcript-common/lib/site";
import {
SiteForm,
@@ -21,10 +21,7 @@ export default async function EditSitePage({
const paths = getPaths();
const site = getSiteCached(siteId);
if (!site) notFound();
- const channels: ChannelOption[] = (await listChannelConfigs(paths)).map((c) => ({
- slug: c.slug,
- name: c.config.name ?? c.slug,
- }));
+ const channels: ChannelOption[] = await siteChannelOptions(paths);
const allSites: SiteOption[] = listSites(paths)
.filter((s) => s.siteId !== siteId)
.map((s) => ({ siteId: s.siteId, siteTitle: s.siteTitle }));
diff --git a/editor/app/sites/actions.ts b/editor/app/sites/actions.ts
@@ -10,6 +10,14 @@ import {
siteDeleteBlocked,
type SiteDeletePlan,
} from "yt-dlp-transcript-common/publish/siteDelete";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import {
+ connectRemoteArchive,
+ removeRemoteArchive,
+ type ConnectResult,
+ type RemoteArchiveDeps,
+} from "yt-dlp-transcript-common/controller/remoteArchives";
+import { saveSettings } from "../settings/saveSettings";
import { saveSiteFromForm, type SaveResult } from "./lib/saveSiteForm";
export type { SaveResult } from "./lib/saveSiteForm";
@@ -81,3 +89,36 @@ export async function migrateToSitesAction(): Promise<DeleteResult> {
// /settings is dynamic, rendered afresh on the next visit.
return { ok: true };
}
+
+// CONNECT AN ARCHIVE (demo epic D1): the /sites panel's two presses — Read it
+// (a dry run: corpus.json read, nothing written) and Connect — and Remove, all
+// through the one controller `pnpm ops archives` uses.
+export type ArchiveActionResult =
+ | { ok: true; result: ConnectResult }
+ | { ok: false; error: string };
+
+const archiveDeps = (): RemoteArchiveDeps => ({
+ stored: () => getSettings().remoteArchives,
+ save: (next) => saveSettings({ remoteArchives: next }),
+});
+
+export async function connectArchiveAction(origin: string, dryRun: boolean): Promise<ArchiveActionResult> {
+ try {
+ const result = await connectRemoteArchive(
+ { origin, dryRun },
+ archiveDeps(),
+ );
+ return { ok: true, result };
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+}
+
+export async function removeArchiveAction(id: string): Promise<{ ok: true } | { ok: false; error: string }> {
+ try {
+ await removeRemoteArchive(id, archiveDeps());
+ return { ok: true };
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+}
diff --git a/editor/app/sites/components/ConnectArchive.tsx b/editor/app/sites/components/ConnectArchive.tsx
@@ -0,0 +1,142 @@
+"use client";
+
+import { useState, useTransition } from "react";
+import { useRouter } from "next/navigation";
+import type { ConnectedArchive } from "yt-dlp-transcript-common/lib/remoteArchives";
+import type { ArchiveProbe } from "yt-dlp-transcript-common/lib/remoteArchives-server";
+import { connectArchiveAction, removeArchiveAction } from "../actions";
+
+// CONNECTED ARCHIVES (demo epic D1): the published archives this machine reads
+// as sources. Type an origin → Read it (its corpus.json: title, channels,
+// videos, nothing saved) → Connect. Each row's Remove drops it; the one
+// TRANSCRIPT_SITE_URL names is listed and cannot be removed here.
+
+const nf = new Intl.NumberFormat("en-US");
+
+export function ConnectArchive({ archives }: { archives: ConnectedArchive[] }) {
+ const router = useRouter();
+ const [pending, start] = useTransition();
+ const [origin, setOrigin] = useState("");
+ const [probe, setProbe] = useState<ArchiveProbe | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [said, setSaid] = useState<string | null>(null);
+
+ const read = () =>
+ start(async () => {
+ setError(null);
+ setSaid(null);
+ setProbe(null);
+ const r = await connectArchiveAction(origin, true);
+ if (r.ok) setProbe(r.result.probe);
+ else setError(r.error);
+ });
+ const connect = () =>
+ start(async () => {
+ setError(null);
+ const r = await connectArchiveAction(probe?.origin ?? origin, false);
+ if (!r.ok) return setError(r.error);
+ setSaid(r.result.already ? `${r.result.archive.title} was connected already.` : `Connected ${r.result.archive.title}.`);
+ setProbe(null);
+ setOrigin("");
+ router.refresh();
+ });
+ const remove = (id: string) =>
+ start(async () => {
+ setError(null);
+ const r = await removeArchiveAction(id);
+ if (!r.ok) setError(r.error);
+ else router.refresh();
+ });
+
+ return (
+ <div className="flex flex-col gap-3" data-connected-archives="">
+ {archives.length > 0 ? (
+ <ul className="flex flex-col divide-y divide-border" aria-label="connected archives">
+ {archives.map((a) => (
+ <li key={a.origin} className="flex items-center justify-between gap-3 py-2" data-archive={a.id}>
+ <div className="min-w-0">
+ <div className="font-medium">{a.title}</div>
+ <div className="text-xs text-muted-foreground">
+ <code>{a.origin}</code>
+ {a.fromEnv ? " · from TRANSCRIPT_SITE_URL" : ` · connected ${a.addedAt.slice(0, 10)}`}
+ </div>
+ </div>
+ {!a.fromEnv && (
+ <button
+ type="button"
+ disabled={pending}
+ onClick={() => remove(a.id)}
+ aria-label={`remove ${a.title}`}
+ className="px-2 py-1 rounded border border-border text-xs disabled:opacity-50"
+ >
+ Remove
+ </button>
+ )}
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="text-sm italic text-muted-foreground">No archive connected.</p>
+ )}
+ <form
+ className="flex flex-wrap items-center gap-2"
+ aria-label="connect an archive"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (probe && probe.origin) connect();
+ else read();
+ }}
+ >
+ <input
+ type="text"
+ aria-label="archive origin"
+ placeholder="https://jeralyzer.pages.dev"
+ value={origin}
+ onChange={(e) => {
+ setOrigin(e.target.value);
+ setProbe(null);
+ }}
+ className="w-80 rounded-md border border-border bg-background px-2 py-1 text-sm"
+ />
+ <button
+ type="button"
+ disabled={pending || !origin.trim()}
+ onClick={read}
+ className="px-3 py-1 rounded-md border border-border text-sm disabled:opacity-50"
+ >
+ {pending && !probe ? "Reading…" : "Read it"}
+ </button>
+ {probe && (
+ <button type="button" disabled={pending} onClick={connect} className="px-3 py-1 rounded-md bg-primary text-primary-foreground text-sm disabled:opacity-50">
+ Connect
+ </button>
+ )}
+ </form>
+ {probe && (
+ <div className="rounded-md border border-border px-3 py-2 text-sm" data-archive-probe={probe.origin}>
+ <div className="font-medium">{probe.title}</div>
+ <div className="text-xs text-muted-foreground">
+ {nf.format(probe.totals.channels)} channel{probe.totals.channels === 1 ? "" : "s"} · {nf.format(probe.totals.videos)} videos
+ {probe.generatedAt ? ` · built ${probe.generatedAt.slice(0, 10)}` : ""}
+ {probe.spec !== null ? ` · corpus spec ${probe.spec}` : ""}
+ </div>
+ <ul className="mt-1 flex flex-wrap gap-x-3 text-xs" aria-label="its channels">
+ {probe.channels.slice(0, 40).map((c) => (
+ <li key={c.slug}>
+ {c.name}
+ {c.videoCount !== null ? <span className="text-muted-foreground"> {nf.format(c.videoCount)}</span> : null}
+ </li>
+ ))}
+ {probe.channels.length > 40 && <li className="text-muted-foreground">…and {probe.channels.length - 40} more</li>}
+ </ul>
+ </div>
+ )}
+ {said && <p className="text-sm text-muted-foreground">{said}</p>}
+ {error && (
+ <p role="alert" className="text-sm text-destructive">
+ {error}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/editor/app/sites/lib/channelOptions.test.ts b/editor/app/sites/lib/channelOptions.test.ts
@@ -0,0 +1,24 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { Paths } from "yt-dlp-transcript-common/lib/paths";
+import { siteChannelOptions } from "./channelOptions";
+
+// Run with: pnpm -C editor exec tsx --test "app/sites/lib/channelOptions.test.ts"
+
+test("the site form's channel picker leaves remote-only channels out", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "site-channel-options-"));
+ try {
+ const put = async (slug: string, config: Record<string, unknown>) => {
+ await mkdir(path.join(root, slug), { recursive: true });
+ await writeFile(path.join(root, slug, "config.json"), JSON.stringify({ handling: "youtube", ...config }));
+ };
+ await put("own", { name: "Own", url: "https://www.youtube.com/@own" });
+ await put("remote", { name: "Remote", platform: "youtube", remoteOnly: true, remoteArchive: "https://stub.test", downloadMode: "manual" });
+ assert.deepEqual(await siteChannelOptions({ channelsDir: root } as unknown as Paths), [{ slug: "own", name: "Own" }]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/editor/app/sites/lib/channelOptions.ts b/editor/app/sites/lib/channelOptions.ts
@@ -0,0 +1,13 @@
+import type { Paths } from "yt-dlp-transcript-common/lib/paths";
+import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig";
+import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels";
+import type { ChannelOption } from "../components/SiteForm";
+
+// The channels a site form offers: every channel but a REMOTE-ONLY one (demo
+// epic D1) — it holds a connected archive's clip windows, has no corpus to
+// publish, and the site writer refuses it anyway (lib/site.ts).
+export async function siteChannelOptions(paths: Paths): Promise<ChannelOption[]> {
+ return (await listChannelConfigs(paths))
+ .filter((c) => !isRemoteOnlyChannel(c.config))
+ .map((c) => ({ slug: c.slug, name: c.config.name ?? c.slug }));
+}
diff --git a/editor/app/sites/new/page.tsx b/editor/app/sites/new/page.tsx
@@ -1,7 +1,7 @@
import type { Metadata } from "next";
import Link from "next/link";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
-import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels";
+import { siteChannelOptions } from "../lib/channelOptions";
import {
DEFAULT_GROUP_FALLBACK_ID,
FALLBACK_GROUP,
@@ -18,10 +18,7 @@ export const metadata: Metadata = { title: "New site — Sites" };
export default async function NewSitePage() {
const paths = getPaths();
- const channels: ChannelOption[] = (await listChannelConfigs(paths)).map((c) => ({
- slug: c.slug,
- name: c.config.name ?? c.slug,
- }));
+ const channels: ChannelOption[] = await siteChannelOptions(paths);
const allSites: SiteOption[] = listSites(paths).map((s) => ({
siteId: s.siteId,
siteTitle: s.siteTitle,
diff --git a/editor/app/sites/page.tsx b/editor/app/sites/page.tsx
@@ -22,6 +22,9 @@ import { AmendReleaseForm } from "./components/AmendReleaseForm";
import { HomepageConfigForm } from "./components/HomepageConfigForm";
import { PublishPanel, type PanelRow } from "./components/PublishPanel";
import { DeleteSiteButton, MigrateButton } from "./components/SiteListActions";
+import { ConnectArchive } from "./components/ConnectArchive";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { connectedArchives } from "yt-dlp-transcript-common/lib/remoteArchives";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Sites" };
@@ -129,6 +132,19 @@ export default async function SitesPage() {
</ul>
</section>
+ {/* Connected archives (demo epic D1): published archives read as
+ sources — Create, research and the MCP offer each one. */}
+ <section className="flex flex-col gap-3 border-t border-border pt-6" aria-labelledby="archives-heading">
+ <div>
+ <h2 id="archives-heading" className="text-lg font-semibold">Connected archives</h2>
+ <p className="text-sm text-muted-foreground">
+ Published archives this machine reads as sources: a sweep over one
+ cites it, and a clip it cites is fetched as a remote-only channel.
+ </p>
+ </div>
+ <ConnectArchive archives={connectedArchives(getSettings().remoteArchives)} />
+ </section>
+
{/* Release: stage the changelog before shipping anything. */}
<section className="flex flex-col gap-3 border-t border-border pt-6">
<div>
diff --git a/editor/e2e/local-media.spec.ts b/editor/e2e/local-media.spec.ts
@@ -0,0 +1,100 @@
+// LOCAL MEDIA LIBRARY, slice 1 (lane/local-media): a Local Archive channel made
+// from the New channel form, its library previewed, one recording with
+// provider metadata and one prepared by hand imported, and the local record's
+// page — all through the UI, against a synthetic library of a few bytes the
+// spec writes in the OS temp dir: a library may not lie inside the corpus or the
+// checkout (controller/localMediaLocation.ts).
+// Nothing is fetched; the library's files are never changed.
+
+import { test, expect } from "@playwright/test";
+import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { resetData, testPaths, writeChannelConfig } from "./helpers";
+
+const VTT = "WEBVTT\n\n00:00:01.000 --> 00:00:03.000\nA synthetic library cue\n";
+
+test("a Local Archive channel imports a library recording and a prepared one, playback left off", async ({ page }) => {
+ await resetData("empty");
+ const library = join(tmpdir(), `archilyzer-e2e-local-library-${process.env.TEST_PARALLEL_INDEX ?? "0"}`);
+ await rm(library, { recursive: true, force: true });
+ await mkdir(library, { recursive: true });
+ await writeFile(join(library, "aaaaaaaaaaa.mp4"), "synthetic mp4 a");
+ await writeFile(join(library, "aaaaaaaaaaa.info.json"), JSON.stringify({
+ id: "aaaaaaaaaaa", title: "Library episode", webpage_url: "https://www.youtube.com/watch?v=aaaaaaaaaaa",
+ upload_date: "20200102", duration: 12, extractor_key: "Youtube",
+ }));
+ await writeFile(join(library, "aaaaaaaaaaa.vtt"), VTT);
+ await writeFile(join(library, "talk.mp4"), "synthetic mp4 talk");
+ await writeFile(join(library, "talk.vtt"), VTT);
+ const before = (await readdir(library)).sort();
+
+ await page.goto("/channels/new");
+ await page.getByLabel("Local Archive").check();
+ await page.locator('input[name="name"]').fill("Local Spec Library");
+ await page.locator('input[name="localDirectory"]').fill(library);
+ await page.getByRole("button", { name: "Create channel" }).click();
+ await expect(page).toHaveURL(/\/channels\/local-spec-library\/local-media$/);
+
+ const config = JSON.parse(await readFile(join(testPaths().transcriptsDir, "channels", "local-spec-library", "config.json"), "utf8"));
+ expect(config.localMedia).toEqual({ sourceId: "library-1", directory: library });
+ expect(config.url).toBeUndefined();
+
+ await page.getByRole("button", { name: "Preview library" }).click();
+ await expect(page.getByRole("status").filter({ hasText: "discovered" })).toHaveText(
+ "2 discovered · 1 new · 0 occupied · 1 need review",
+ );
+ await page.getByLabel("Import aaaaaaaaaaa.mp4").check();
+
+ await page.getByRole("button", { name: "Prepare details for talk.mp4" }).click();
+ const form = page.getByRole("form", { name: "Prepare details for talk.mp4" });
+ await form.getByLabel("Method").selectOption("manual");
+ await form.getByLabel("Title").fill("A prepared talk");
+ await form.getByLabel("Recording date (optional)").fill("2021-03-04");
+ await form.getByRole("button", { name: "Review details" }).click();
+ await expect(form.getByLabel("Prepared recording details")).toContainText("Recording date: 2021-03-04");
+ await form.getByRole("button", { name: "Use details for import" }).click();
+ await expect(page.getByLabel("Import talk.mp4")).toBeChecked();
+
+ await page.getByRole("button", { name: "Import selected (2)" }).click();
+ await expect(page.getByText(/Imported 2; already occupied 0; rejected 0/)).toBeVisible({ timeout: 30_000 });
+
+ const data = join(testPaths().transcriptsDir, "channels", "local-spec-library", "data");
+ const ids = (await readdir(data)).sort();
+ expect(ids).toHaveLength(2);
+ expect(ids).toContain("aaaaaaaaaaa");
+ const local = ids.find((id) => id.startsWith("local-"))!;
+ expect((await readdir(join(data, local))).sort()).toEqual(["external-media.json", "metadata.info.json", "transcript.en.vtt"]);
+ expect(JSON.parse(await readFile(join(data, local, "metadata.info.json"), "utf8")).title).toBe("A prepared talk");
+
+ // A local record's page names it a local recording, with no download card.
+ await page.goto(`/channels/local-spec-library/videos/${local}`);
+ await expect(page.getByLabel("Local recording")).toBeVisible();
+ await expect(page.getByRole("link", { name: "Open local media library" })).toBeVisible();
+ await expect(page.getByText("Download audio")).toHaveCount(0);
+
+ // The channel page offers its Local library tab (it has a library).
+ await page.goto("/channels/local-spec-library");
+ await expect(page.getByLabel("Local library stage tab")).toBeVisible();
+
+ // Playback stayed off, and the library was never touched.
+ const after = JSON.parse(await readFile(join(testPaths().transcriptsDir, "channels", "local-spec-library", "config.json"), "utf8"));
+ expect(after.localMedia.playback).toBeUndefined();
+ expect((await readdir(library)).sort()).toEqual(before);
+ await rm(library, { recursive: true, force: true });
+});
+
+// Review fix 8: the tab is only on a channel that has a library; a library is
+// added through the New channel form or `pnpm ops local-media-configure`, and
+// the route, reachable by URL, says so for a channel without one.
+test("a channel without a library has no Local library tab, and its route names the command", async ({ page }) => {
+ await resetData("empty");
+ await writeChannelConfig("plain-channel", { name: "Plain", url: "https://www.youtube.com/@plain" });
+ await page.goto("/channels/plain-channel");
+ await expect(page.getByLabel("Overview stage tab")).toBeVisible();
+ await expect(page.getByLabel("Local library stage tab")).toHaveCount(0);
+ await page.goto("/channels/plain-channel/local-media");
+ await expect(page.getByText("This channel has no local media library.")).toBeVisible();
+ await expect(page.getByText(/pnpm ops local-media-configure --json '\{"slug":"plain-channel"/)).toBeVisible();
+ await expect(page.getByRole("button", { name: "Save library" })).toHaveCount(0);
+});
diff --git a/editor/e2e/remote-archive.spec.ts b/editor/e2e/remote-archive.spec.ts
@@ -0,0 +1,213 @@
+import { test, expect, type APIRequestContext } from "@playwright/test";
+import { spawnSync } from "node:child_process";
+import { createServer, type Server } from "node:http";
+import { mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import { dirname, extname, join, normalize, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { startFakeOllama, type FakeOllama } from "../../common/testing/llm/fakeOllama.mjs";
+import { writeDraftCorpus } from "../../common/testing/draft/corpus.mjs";
+import { baseUrl } from "./baseUrl";
+import { resetData, testPaths } from "./helpers";
+
+// A PUBLIC ARCHIVE IS A FIRST-CLASS SOURCE (demo epic D1, item 7): a fresh
+// editor with NO channels of its own, a STUB ARCHIVE (the synthetic draft
+// corpus served over loopback HTTP as a published site serves it — an older
+// corpus.json, no per-channel platform, so the resolver's record fallback is
+// what names the platform), and nothing fetched from the network:
+//
+// connect /sites → Connected archives: Read it (the probe), Connect
+// sweep a question over the archive on the local model (the fake ollama,
+// the recorded pipeline run): its links on the STUB's origin
+// project umtool's chain, step by step as its job runs them (current,
+// windows, manifest): the editor registers the cited channel
+// REMOTE-ONLY and fetches its windows (the fake yt-dlp); the
+// project's QR origin is the stub
+// link a citation's link opens on the stub at its second
+//
+// The stub's own page at `/` says which moment it was asked for.
+
+const AUTH = { authorization: "Bearer test-worker-token" };
+const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
+const RUNS = join(REPO, "common", "testing", "draft", "runs");
+const CHAIN_RUN = join(REPO, "umtool", "lib", "report", "chain-run.mjs");
+
+const TYPES: Record<string, string> = { ".json": "application/json", ".html": "text/html" };
+
+async function startStubArchive(dir: string): Promise<{ url: string; asked: string[]; close: () => Promise<void> }> {
+ const asked: string[] = [];
+ const server: Server = createServer(async (req, res) => {
+ const u = new URL(req.url ?? "/", "http://stub");
+ asked.push(u.pathname);
+ if (u.pathname === "/" || u.pathname === "/index.html") {
+ // The archive's viewer, as far as a link needs it: which moment.
+ const v = u.searchParams.get("v") ?? "";
+ const t = u.searchParams.get("t") ?? "";
+ res.writeHead(200, { "content-type": "text/html" });
+ res.end(`<!doctype html><title>stub archive</title><p id="moment" data-v="${v.replace(/"/g, "")}" data-t="${t.replace(/"/g, "")}">v=${v} t=${t}</p>`);
+ return;
+ }
+ const file = normalize(join(dir, decodeURIComponent(u.pathname)));
+ if (!file.startsWith(dir)) {
+ res.writeHead(403).end();
+ return;
+ }
+ try {
+ const body = await readFile(file);
+ res.writeHead(200, { "content-type": TYPES[extname(file)] ?? "application/octet-stream", "access-control-allow-origin": "*" });
+ res.end(body);
+ } catch {
+ res.writeHead(404).end("not found");
+ }
+ });
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r()));
+ const port = (server.address() as { port: number }).port;
+ return { url: `http://127.0.0.1:${port}`, asked, close: () => new Promise((r) => server.close(() => r())) };
+}
+
+async function jobUntil(request: APIRequestContext, id: string, ms = 120_000) {
+ const t0 = Date.now();
+ let last = "";
+ while (Date.now() - t0 < ms) {
+ const res = await request.get(`${baseUrl}/api/ops/job/${id}?tail=60`, { headers: AUTH });
+ const body = (await res.json()) as { job?: { status?: string }; status?: string; tail?: string[] };
+ last = body.job?.status ?? body.status ?? "";
+ if (["done", "failed", "cancelled"].includes(last)) return body;
+ await new Promise((r) => setTimeout(r, 400));
+ }
+ throw new Error(`job ${id} is still ${last}`);
+}
+
+test.describe.configure({ mode: "serial" });
+
+let stub: Awaited<ReturnType<typeof startStubArchive>>;
+let ol: FakeOllama;
+let scratch: string;
+
+test.beforeAll(async () => {
+ scratch = await mkdtemp(join(os.tmpdir(), "e2e-remote-archive-"));
+ const dir = join(scratch, "archive");
+ await writeDraftCorpus(dir);
+ // A build of its own, so no other run's cached copy answers for it.
+ const corpus = JSON.parse(await readFile(join(dir, "corpus.json"), "utf8"));
+ await writeFile(join(dir, "corpus.json"), JSON.stringify({ ...corpus, spec: 5, generatedAt: new Date().toISOString() }));
+ // A record's page is a video platform's (an archive's own URL is refused
+ // otherwise): YouTube's watch pages, which the fake yt-dlp answers.
+ for (const c of corpus.channels as { slug: string }[]) {
+ const page = join(dir, "transcripts", c.slug, "page-0000.json");
+ const records = JSON.parse(await readFile(page, "utf8")) as { id: string; webpageUrl?: string }[];
+ await writeFile(page, JSON.stringify(records.map((r) => ({ ...r, webpageUrl: `https://www.youtube.com/watch?v=${r.id}` }))));
+ }
+ stub = await startStubArchive(dir);
+ ol = await startFakeOllama();
+});
+
+test.afterAll(async () => {
+ await stub?.close();
+ await ol?.close();
+ await rm(scratch, { recursive: true, force: true });
+});
+
+test("a fresh editor with no channels: connect the stub archive, sweep it on the local model, fetch the cut's windows as a remote-only channel, open a link at its second", async ({ page, request }) => {
+ test.setTimeout(300_000);
+ await resetData(null);
+ const paths = testPaths();
+ expect(await readdir(join(paths.transcriptsDir, "channels"))).toEqual([]);
+ const settings = JSON.parse(await readFile(paths.settingsFile, "utf8"));
+ const projects = join(scratch, "projects");
+ await writeFile(paths.settingsFile, JSON.stringify({ ...settings, minFreeDiskGB: 0, generation: { ...(settings.generation ?? {}), ollamaUrl: ol.url, projectsRoot: projects } }, null, 2));
+ await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
+
+ // ─── connect, in the UI ───
+ await page.goto(`${baseUrl}/sites`);
+ const panel = page.locator("[data-connected-archives]");
+ await expect(panel.getByText("No archive connected.")).toBeVisible();
+ await panel.getByLabel("archive origin").fill(`${stub.url}/`);
+ await panel.getByRole("button", { name: "Read it" }).click();
+ const probe = panel.locator(`[data-archive-probe="${stub.url}"]`);
+ await expect(probe).toContainText("Synth Kitchen");
+ await expect(probe).toContainText(/2 channels · \d+ videos/);
+ await panel.getByRole("button", { name: "Connect" }).click();
+ await expect(panel.getByRole("list", { name: "connected archives" }).locator("li")).toHaveCount(1);
+ const listed = await (await request.get(`${baseUrl}/api/ops/archives`, { headers: AUTH })).json();
+ expect(listed.archives).toEqual([expect.objectContaining({ origin: stub.url })]);
+
+ // ─── a question, swept over the archive on the local model ───
+ const run = JSON.parse(await readFile(join(RUNS, "sweep-pipeline.json"), "utf8"));
+ for (const turn of run.turns) ol.push(turn);
+ const draft = await request.post(`${baseUrl}/api/ops/report-draft`, {
+ headers: AUTH,
+ data: { task: "sweep", article: "remote-e2e", model: run.model, question: run.question, channels: run.channels, source: `remote:${stub.url}` },
+ });
+ const started = (await draft.json()) as { ok?: boolean; error?: string; jobId?: string };
+ expect(draft.status(), started.error).toBe(200);
+ const job = await jobUntil(request, started.jobId!);
+ expect(job.job?.status ?? job.status, (job.tail ?? []).join("\n")).toBe("done");
+ const itDir = join(paths.transcriptsDir, "reports", "remote-e2e", "iterations", "1");
+ const iteration = JSON.parse(await readFile(join(itDir, "iteration.json"), "utf8"));
+ expect(iteration.scope.source).toBe(`remote:${stub.url}`);
+ const report = JSON.parse(await readFile(join(itDir, "report.json"), "utf8"));
+ const cited = Object.values(report.citations as Record<string, { kind: string; channel: string; id: string; start: number }>).filter((c) => c.kind === "video");
+ expect(cited.length).toBeGreaterThan(0);
+ const sweep = await readFile(join(itDir, "sweep.md"), "utf8");
+ const links = [...sweep.matchAll(/\((https?:\/\/[^)\s]+\?v=[^)\s]+)\)/g)].map((m) => m[1]);
+ expect(links.length).toBeGreaterThan(0);
+ for (const l of links) expect(l.startsWith(`${stub.url}/?v=`), l).toBe(true);
+ // Nothing was asked of the editor's own corpus (it has none), and the stub was read.
+ expect(stub.asked).toContain("/corpus.json");
+ expect(stub.asked.some((p) => p.startsWith("/transcripts/synth-kitchen/"))).toBe(true);
+
+ // ─── the project: the chain's steps as its job runs them ───
+ const env: Record<string, string> = {
+ ...(process.env as Record<string, string>),
+ TRANSCRIPTS_DIR: paths.transcriptsDir,
+ SETTINGS_FILE: paths.settingsFile,
+ EXPORT_PUBLIC_DIR: join(scratch, "public"),
+ EXPORT_INDEX_DIR: join(scratch, ".export-index"),
+ EXPORT_BUILDS_DIR: join(scratch, ".export-builds"),
+ ARCHIVE_CACHE_DIR: join(scratch, ".archive-cache"),
+ ARCHILYZER_EDITOR_URL: baseUrl,
+ WORKER_TOKEN: "test-worker-token",
+ };
+ delete env.ARTICLES_DIR;
+ const step = (name: string) => {
+ const r = spawnSync(process.execPath, ["--import", "tsx", CHAIN_RUN, "step", "remote-e2e", "1", name, "--projects-root", projects], {
+ cwd: REPO,
+ env: env as NodeJS.ProcessEnv,
+ encoding: "utf8",
+ timeout: 180_000,
+ });
+ return { code: r.status, out: `${r.stdout}\n${r.stderr}` };
+ };
+ for (const name of ["current", "windows", "manifest"]) {
+ const r = step(name);
+ expect(r.code, `${name}: ${r.out}`).toBe(0);
+ }
+ // The cited channel is registered REMOTE-ONLY: config only, its platform from the archive's record.
+ const config = JSON.parse(await readFile(join(paths.transcriptsDir, "channels", "synth-kitchen", "config.json"), "utf8"));
+ expect(config).toMatchObject({ remoteOnly: true, remoteArchive: stub.url, platform: "youtube", downloadMode: "manual" });
+ expect(config.url).toBeUndefined();
+ // Every cited window is on disk under it.
+ for (const c of cited) {
+ const clips = await readdir(join(paths.transcriptsDir, "channels", c.channel, "data", c.id, "clips")).catch(() => [] as string[]);
+ expect(clips.filter((f) => f.endsWith(".mp4")).length, `${c.channel}/${c.id}`).toBeGreaterThan(0);
+ }
+ const manifest = JSON.parse(await readFile(join(projects, "remote-e2e", "i1", "video.manifest.json"), "utf8"));
+ expect(manifest.provenance.siteOrigin).toBe(stub.url);
+
+ // The channel list says what it is.
+ await page.goto(`${baseUrl}/channels`);
+ await expect(page.getByRole("note", { name: "remote-only channel synth-kitchen" })).toBeVisible();
+
+ // ─── a citation's link opens on the stub at its second ───
+ const link = links[0];
+ const at = new URL(link);
+ const t = at.searchParams.get("t");
+ expect(t, link).not.toBeNull();
+ const [channel, id] = (at.searchParams.get("v") ?? "").split("/");
+ // The second is the cited moment's: a citation of that recording starts there.
+ expect(cited.some((c) => c.channel === channel && c.id === id && Math.floor(c.start) === Number(t)), `${link} against ${JSON.stringify(cited)}`).toBe(true);
+ await page.goto(link);
+ await expect(page.locator("#moment")).toHaveAttribute("data-t", t!);
+ await expect(page.locator("#moment")).toHaveAttribute("data-v", `${channel}/${id}`);
+});
diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts
@@ -40,6 +40,9 @@ export const E2E_SERVER_ENV: Record<string, string> = {
E2E_AUDIO_CHECK_RECOVER_AFTER: "2",
E2E_BACKOFF_BASE_MS: "20000",
E2E_CLIP_WINDOW_GAP_MS: "2000",
+ // remote-archive.spec's stub archive is on loopback (demo epic D1): the
+ // editor connects a local archive only when told so on its own machine.
+ ARCHILYZER_ALLOW_PRIVATE_ARCHIVES: "1",
E2E_AVAILABILITY_PROBE_GAP_MS: "0",
// The pacing guard's BUILT-IN defaults (plans/pacing-guard.md) are off on
// the test server — a spec's two fake X fetches would otherwise sit five
diff --git a/export/CHANGELOG.md b/export/CHANGELOG.md
@@ -1,5 +1,8 @@
# Changelog
+## [Unreleased]
+- **`corpus.json` is spec 6: each channel says where it is.** A channel's entry adds `platform` (youtube, rumble, …) and `url`, its page on that platform, when the archive's operator configured them, and `llms.txt` shows them beside the channel's name — what a machine with no copy of the channel needs to fetch a cited moment's media (a fresh Archilyzer clone pointed at the archive). Additive: a reader that does not know spec 6 reads the archive as before, and a reader of an older archive takes the platform from a transcript record's `webpageUrl`. Needs a rebuild and deploy of each site.
+
## [0.11.2] - 2026-10-21
- **A link to a moment of a removed YouTube video opens the transcript at that moment.** `?v=…&t=<seconds>` for a video YouTube no longer plays used to open its transcript at the start: the reader followed only the player, which never got there. The transcript now starts at the linked moment on every platform, and a player that cannot play leaves it there. Needs a rebuild and deploy of each site.
- **A report can keep a timeline, and a reader can subscribe to it.** `report.json` `entries` (each `{ "id", "date", "title", "body" }`, optionally `updated`) shows as **Timeline** after In brief: dated entries, newest first, each date linking to the entry's own place on the page (`#<id>`), each body citing as a section's does. The report counts as updated at its newest entry, in its header and the report list. Each entry is a slide too, and the HTML, PDF and Markdown downloads carry the Timeline. On a site with a public URL, the report publishes its timeline as feeds — `feed.xml` (RSS) and `feed.json` (JSON Feed) beside its page — and its header reads **Subscribe: RSS · JSON**; a feed reader finds them from the page too. A site with no public URL publishes no feed. The MCP's `get_report` reads the timeline, and its `section` may name an entry. Needs a rebuild and deploy of each site with reports.
diff --git a/mcp/src/connectedArchives.test.ts b/mcp/src/connectedArchives.test.ts
@@ -0,0 +1,27 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { connectedArchivesHere } from "./sources";
+
+// list_sources offers the archives the editor connected (demo epic D1): read
+// from settings.json through the one resolver, TRANSCRIPT_SITE_URL's added.
+test("the MCP lists the connected archives from settings.json, the environment's after them", async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "mcp-archives-"));
+ try {
+ const file = path.join(dir, "settings.json");
+ await writeFile(file, JSON.stringify({ remoteArchives: [{ id: "stub", origin: "https://stub.test/", title: "Stub", addedAt: "2026-11-11T00:00:00Z" }] }));
+ const list = connectedArchivesHere(file, { TRANSCRIPT_SITE_URL: "https://other.test" });
+ assert.deepEqual(
+ list.map((a) => [a.id, a.origin, a.fromEnv ?? false]),
+ [
+ ["stub", "https://stub.test", false],
+ ["other-test", "https://other.test", true],
+ ],
+ );
+ assert.deepEqual(connectedArchivesHere(path.join(dir, "missing.json"), {}), []);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/mcp/src/fetchClip.ts b/mcp/src/fetchClip.ts
@@ -178,6 +178,10 @@ export type FetchClipRequest =
reason: string;
report?: string;
waitSeconds: number;
+ // The published archive the clip is cited from (demo epic D1): the
+ // editor registers a channel it does not hold as remote-only of it, when
+ // it is a connected archive. Set by the server from a remote source.
+ archive?: string;
};
const trimmed = (v: unknown): string =>
@@ -549,6 +553,7 @@ export async function fetchClip(
pad: target.pad,
...capped,
...(target.storedUrl ? { storedUrl: target.storedUrl } : {}),
+ ...(request.archive ? { archive: request.archive } : {}),
...provenance,
};
const res = await call(`${editor.url}/api/media/fetch-window`, {
diff --git a/mcp/src/generation.test.ts b/mcp/src/generation.test.ts
@@ -571,3 +571,21 @@ test("generate propose-groups: a project (words optional); routed to code, the p
assert.match(b.text, /Project: \/r\/p · 1 proposed, 0 refused/);
assert.match(b.text, /Nothing in the cut changed/);
});
+
+// demo epic D1: a sweep over a published archive names it to the editor.
+test("generate carries source for a sweep or research run, refuses it elsewhere", async () => {
+ const { generateArgsWithSource } = await import("./server");
+ const ok = validateGenerateArgs({ task: "sweep", article: "a", question: "q", channels: ["c"], source: "remote:https://stub.test" });
+ assert.equal(ok.ok, true);
+ assert.equal((ok as { request: { body: Record<string, unknown> } }).request.body.source, "remote:https://stub.test");
+ const bad = validateGenerateArgs({ task: "revise-report", article: "a", iteration: 1, feedback: "x", source: "remote:https://stub.test" });
+ assert.match(String((bad as { error: string }).error), /source is a sweep's or a research run's/);
+ assert.match(String((validateGenerateArgs({ task: "sweep", article: "a", question: "q", channels: ["c"], source: "nope" }) as { error: string }).error), /corpus handle/);
+ // The server's resolution: the canonical handle of a remote or hub, never a local dir; only sweep and research.
+ const remote = { handle: "remote:https://stub.test", spec: { kind: "remote" as const, url: "https://stub.test" } };
+ assert.equal(generateArgsWithSource({ task: "sweep", source: "https://stub.test/" }, remote).source, "remote:https://stub.test");
+ assert.equal(generateArgsWithSource({ task: "research" }, remote).source, "remote:https://stub.test");
+ assert.equal("source" in generateArgsWithSource({ task: "narrate", source: "x" }, remote), false);
+ const local = { handle: "local:/x", spec: { kind: "local" as const, dir: "/x" } };
+ assert.equal("source" in generateArgsWithSource({ task: "sweep" }, local), false);
+});
diff --git a/mcp/src/generation.ts b/mcp/src/generation.ts
@@ -249,6 +249,12 @@ export function validateGenerateArgs(args: Record<string, unknown>): { ok: true;
if (n === null) return bad(`${k} is an iteration number (1, 2, …)`);
if (n !== undefined) body[k] = n;
}
+ if (args.source !== undefined && args.source !== null) {
+ const src = trimmed(args.source);
+ if (!/^(local|remote|hub):\S+/.test(src)) return bad("source is a corpus handle: remote:<url>, hub:<url> or local:<dir>");
+ if (task !== "sweep" && task !== "research") return bad("source is a sweep's or a research run's (the corpus it reads)");
+ body.source = src;
+ }
for (const k of ["model", "extractorModel", "feedback", "question", "from", "to"] as const) {
if (args[k] === undefined) continue;
const v = trimmed(args[k]);
@@ -955,6 +961,12 @@ export const GENERATION_TOOLS = [
},
question: { type: "string", description: "sweep / research: the question, in words." },
channels: { type: "array", items: { type: "string" }, description: "sweep / research: the channel slugs to read." },
+ source: {
+ type: "string",
+ description:
+ "sweep / research: the corpus the editor reads and the sweep cites — a handle (remote:<archive origin>, hub:<url>). " +
+ "Omitted: this server's default corpus when it is a published archive or a hub, else the editor's own build holding the channels.",
+ },
from: { type: "string", description: "sweep: only videos on or after this date (YYYY-MM-DD)." },
to: { type: "string", description: "sweep: only videos on or before this date (YYYY-MM-DD)." },
feedback: { type: "string", description: "A revision's feedback: what to change, concretely." },
diff --git a/mcp/src/instructions.ts b/mcp/src/instructions.ts
@@ -369,7 +369,9 @@ function generateSweepStep(req: PromptRequest, r: { route: GenerationRoute; mode
`${r.route === "code" ? "Claude Code" : ROUTE_WORDS[r.route]}${r.model ? ` (${r.model})` : ""} by ${r.by}. ` +
`Call \`generate\` with task: "sweep", ${article}, ${question}, ${channels}${model}, ` +
`wait: true (add from/to, YYYY-MM-DD, when I named a period). The editor runs ` +
- `it as a report-draft job on its own corpus build and caps; the article's ` +
+ `it as a report-draft job, under its caps, over the corpus the call names in \`source\` — ` +
+ `omitted, this server's default when that is a published archive (remote:<origin>) or a hub, ` +
+ `else the editor's own build holding the channels — and the sweep cites that archive; the article's ` +
`iteration is what it makes, never its published report. If the answer ` +
`says it is still running, call \`generate\` again with the job, article ` +
`and iteration it names and wait: true — never enqueue the same sweep ` +
diff --git a/mcp/src/server.ts b/mcp/src/server.ts
@@ -9,6 +9,13 @@ import { salvageCaveat } from "yt-dlp-transcript-common/lib/salvageMark";
import { COPIES_NOT_AVAILABLE, describeCopies, loadMirrorScans, onlyHereIds } from "./mirrorCopies";
import { transcriptToMarkdown } from "yt-dlp-transcript-common/lib/transcriptToMarkdown";
import { formatDate, formatDuration } from "yt-dlp-transcript-common/lib/format";
+
+// A record's date as these listings print it. An undated record (a local
+// recording with no recording date has uploadDate "") says so, rather than
+// leaving an empty field a reader takes for a parse error.
+export function dateOrUndated(uploadDate: string): string {
+ return uploadDate ? formatDate(uploadDate) : "undated";
+}
import { manifestHasDigest } from "yt-dlp-transcript-common/lib/digests";
import type { VideoStat } from "yt-dlp-transcript-common/lib/stats";
import { momentUrl, momentBaseUrl, viewerPostUrl } from "yt-dlp-transcript-common/lib/momentUrl";
@@ -38,7 +45,7 @@ import {
type HubSite,
type ShardSource,
} from "./source";
-import type { SourceSpec } from "./sources";
+import { connectedArchivesHere, type SourceSpec } from "./sources";
import { SourceRegistry, type ResolvedSource } from "./sourceRegistry";
import type { Post } from "yt-dlp-transcript-common/lib/posts";
import {
@@ -1203,7 +1210,10 @@ async function handleFetchClip(
const { note, ctx } = await resolveClipTarget(source, resolved.handle, request);
- const outcome = await fetchClip(request, deps, { onPoll });
+ // A clip cited from a published archive names it (demo epic D1): the editor
+ // registers its channel remote-only when the archive is connected there.
+ const archived = "target" in request && resolved.spec.kind === "remote" ? { ...request, archive: resolved.spec.url } : request;
+ const outcome = await fetchClip(archived, deps, { onPoll });
const rendered = renderFetchClip(outcome, ctx);
const body = `${note}${rendered.text}`;
return rendered.isError ? errorText(body) : text(body);
@@ -1347,7 +1357,7 @@ export function createServer(
case "generate":
return fromAnswer(
await generateTool(
- args,
+ generateArgsWithSource(args, resolved),
fetchClipDeps,
progressNotifier(ctx.mcpReq._meta?.progressToken, ctx.mcpReq.notify),
),
@@ -1717,7 +1727,7 @@ async function handleSearch(
`### ${h.title}\n` +
`- video_id: ${h.videoId} | channel: ${h.channelName}` +
(h.siteTitle ? ` | site: ${h.siteTitle}` : "") +
- ` | uploaded: ${formatDate(h.uploadDate)} | matches: ${h.matches}` +
+ ` | uploaded: ${dateOrUndated(h.uploadDate)} | matches: ${h.matches}` +
(includeSnippets && h.webpageUrl ? `\n- source: ${h.webpageUrl}` : "") +
(baseUrl ? `\n- moment_base: ${baseUrl}` : "") +
(h.mirrors && h.mirrors.length > 0
@@ -1861,7 +1871,7 @@ async function handleEnumerateMatches(
: "";
return (
`- ${h.videoId} | ${kind} | ${h.channelName} | ` +
- `${formatDate(h.uploadDate)} | ${h.matches} match(es) | ${h.title}${mirrors}`
+ `${dateOrUndated(h.uploadDate)} | ${h.matches} match(es) | ${h.title}${mirrors}`
);
});
@@ -2129,7 +2139,7 @@ async function handleGetTranscripts(
`## ${record.title || id}\n` +
`- video_id: ${id} | channel: ${ch.name}` +
(ch.siteTitle ? ` | site: ${ch.siteTitle}` : "") +
- ` | uploaded: ${formatDate(record.uploadDate)}` +
+ ` | uploaded: ${dateOrUndated(record.uploadDate)}` +
(record.webpageUrl ? `\n- source: ${record.webpageUrl}` : "") +
(baseUrl ? `\n- moment_base: ${baseUrl}` : "") +
// A salvage transcript (release 30, lane Q) is marked here too (release 32 R8).
@@ -2560,7 +2570,7 @@ async function describeOtherCopies(
`open it at 0:00 and locate the moment again`;
return (
`- ${s.id} (${s.channel}, ${s.platform}, ${formatDuration(s.duration)}, ` +
- `uploaded ${formatDate(s.uploadDate)}` +
+ `uploaded ${dateOrUndated(s.uploadDate)}` +
`${s.hasTranscript ? "" : ", NO transcript"}) — ${timing}`
);
});
@@ -2655,6 +2665,21 @@ async function describeDigest(
return out.length > 1 ? out.join("\n") : "";
}
+// generate's `source` (demo epic D1): the corpus a sweep or a research run
+// reads and cites. The call's own `source`, resolved to its canonical handle,
+// when it names a published archive or a hub — and, when it names none, this
+// server's default if that is one: an MCP pointed at jeralyzer.pages.dev asks
+// the editor to sweep jeralyzer.pages.dev, not whatever build it holds. A
+// LOCAL corpus is not sent: the editor picks its own build holding the
+// channels, as before. Only a sweep or a research run carries it.
+export function generateArgsWithSource(args: Record<string, unknown>, resolved: Pick<ResolvedSource, "handle" | "spec">): Record<string, unknown> {
+ const { source: _asked, ...rest } = args;
+ const task = typeof args.task === "string" ? args.task.trim() : "";
+ if (task !== "sweep" && task !== "research") return rest;
+ if (resolved.spec.kind === "local") return rest;
+ return { ...rest, source: resolved.handle };
+}
+
// ─── Source discovery: list_sources / resolve_source ───
// A one-line human description of a source spec's target (kind + where it
@@ -2733,6 +2758,18 @@ async function handleListSources(
);
}
+ // The archives this machine's editor connected (demo epic D1): each a
+ // handle to pass, offered beside the default.
+ const connected = connectedArchivesHere();
+ if (connected.length > 0) {
+ lines.push(
+ `\nArchives connected on this machine (${connected.length}):\n` +
+ connected
+ .map((a) => ` - ${a.title} · ${a.origin}${a.fromEnv ? " (TRANSCRIPT_SITE_URL)" : ""}\n source: remote:${a.origin}`)
+ .join("\n"),
+ );
+ }
+
lines.push(
`\nPass a corpus per call, in each tool's own \`source\` argument — ` +
`'default', 'local:<dir>', 'remote:<url>', 'hub:<url>', or ` +
@@ -2987,7 +3024,7 @@ function renderSpecResults(source: ShardSource, hits: SpecHit[]): string {
`### ${h.title}\n` +
`- video_id: ${h.videoId} | channel: ${h.channelName}` +
(h.siteTitle ? ` | site: ${h.siteTitle}` : "") +
- ` | uploaded: ${formatDate(h.uploadDate)} | matches: ${h.matches}` +
+ ` | uploaded: ${dateOrUndated(h.uploadDate)} | matches: ${h.matches}` +
(h.webpageUrl ? `\n- source: ${h.webpageUrl}` : "");
const snips = h.snippets
.map((s) => renderScopedSnippet(source, h, s))
diff --git a/mcp/src/sources.ts b/mcp/src/sources.ts
@@ -1,3 +1,7 @@
+import { readFileSync } from "node:fs";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { connectedArchives, type ConnectedArchive } from "yt-dlp-transcript-common/lib/remoteArchives";
+import { archiveCache, archiveCacheEnabled } from "yt-dlp-transcript-common/lib/archiveCache-server";
import {
LocalSource,
RemoteSource,
@@ -54,7 +58,9 @@ export function buildSource(spec: SourceSpec): ShardSource {
case "hub":
return new HubSource(spec.url, spec.sites);
case "remote":
- return new RemoteSource(spec.url);
+ // Its shards cached on disk while the archive's build is unchanged, read
+ // one at a time, paced (demo epic D1: common/lib/archiveCache-server.ts).
+ return archiveCacheEnabled() ? new RemoteSource(spec.url, undefined, { fetch: archiveCache().fetch as typeof fetch }) : new RemoteSource(spec.url);
case "local":
return new LocalSource(spec.dir);
}
@@ -64,3 +70,21 @@ export function buildSource(spec: SourceSpec): ShardSource {
export function resolveSource(argv: string[]): ShardSource {
return buildSource(resolveSourceSpec(argv));
}
+
+// The archives this machine's editor has CONNECTED (settings.remoteArchives,
+// plus TRANSCRIPT_SITE_URL's — the one resolver, common/lib/remoteArchives.ts),
+// for list_sources: each one a `remote:<origin>` handle a call can pass. Read
+// from settings.json (SETTINGS_FILE, else the checkout's); a clone with none, or
+// no readable file, has only the environment's.
+export function connectedArchivesHere(
+ settingsFile: string = getPaths().settingsFile,
+ env: Record<string, string | undefined> = process.env,
+): ConnectedArchive[] {
+ let stored: unknown = [];
+ try {
+ stored = (JSON.parse(readFileSync(settingsFile, "utf8")) as { remoteArchives?: unknown })?.remoteArchives ?? [];
+ } catch {
+ stored = [];
+ }
+ return connectedArchives(stored, env);
+}
diff --git a/mcp/src/undatedRecord.test.ts b/mcp/src/undatedRecord.test.ts
@@ -0,0 +1,11 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { dateOrUndated } from "./server";
+
+// lane/local-media (review B2): a local recording with no recording date has
+// uploadDate "", and the listings say "undated" rather than print an empty
+// field; a dated record prints exactly as before.
+test("dateOrUndated: an empty date is named, a real one formatted as before", () => {
+ assert.equal(dateOrUndated(""), "undated");
+ assert.equal(dateOrUndated("20240229"), "2024-02-29");
+});
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -144,6 +144,15 @@ An ARTICLE's "workspace files" are something else: the files of its research wor
Article tab's `source` view (`umtool/lib/pieces/tabs.mjs` ARTICLE_SECTION_TAB `source`,
`umtool/components/articles/WorkspacePanel.tsx`). Say which.
+**"Local media" means three things.** In umtool, `umtool/report-to-video/local-media.mjs`
+(`createLocalMedia`, `hasLocalMedia`, `validateLocalMedia`) is a report-video clip whose media is a
+FILE BESIDE THE MANIFEST (`src`, `cues`), nothing to do with the corpus; and
+`umtool/lib/research/media.ts` `localMediaFor` is the files on disk a research view can play for a
+corpus record (its clip windows, its saved video). In the corpus, a channel's `localMedia` config key (`common/lib/localMedia.ts`, CHANNEL.md) is
+a LOCAL MEDIA LIBRARY — a directory of recordings the archive imports text from and never owns —
+whose records are platform `"local"`, id `local-<32 hex>`, with `external-media.json`; umtool's guard
+for those is `umtool/report-to-video/local-recording.mjs`. Say which.
+
**Never name a sidecar `transcript.<x>.<y>`.** `common/lib/videoStatus.ts:88` —
`export const SUB_FILE_RE = /^transcript\.([^.]+)\.([^.]+)$/;` treats any such file as a
subtitle track. The exclusion list in `readSubTracks` is hardcoded. Use `ai-digest.json`,
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -53,6 +53,11 @@
// pnpm ops import-media --json '{"slug":"demo-rumble","path":"/abs/stream.mp4.part","url":"https://rumble.com/v1abcde-title.html","move":true}' --wait
// pnpm ops import-media --json '{"slug":"demo-archive","path":"/abs/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"},"dryRun":true}' --wait
// pnpm ops attach-media --json '{"slug":"demo-yt","source":"/abs/YouTube.zip","match":"aaaaaaaaaaa|bbbbbbbbbbb","fillDates":true,"dryRun":true}' --wait
+// pnpm ops local-media-configure --json '{"slug":"demo-local","sourceId":"library-1","directory":"/mnt/recordings"}'
+// pnpm ops local-media-preview --json '{"slug":"demo-local"}'
+// pnpm ops local-media-prepare --json '{"slug":"demo-local","sourceToken":"<token>","media":"talk.mp4","sourceFingerprint":"<fp>","details":{"mode":"inspect","title":"A talk"}}'
+// pnpm ops local-media-import --json '{"slug":"demo-local","allNew":true}' --wait
+// pnpm ops local-media-link --json '{"slug":"demo-local","sourceToken":"<token>","media":"talk.mp4","fingerprint":"<fp>","dryRun":true}'
// pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'
// pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'
// pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}'
@@ -130,6 +135,8 @@
// tag exists on, absent = every site — included)
// pnpm ops tag-videos --file ids.json
// pnpm ops persist-videos --file list.json --wait
+// pnpm ops archives --json '{"connect":"https://jeralyzer.pages.dev","dryRun":true}'
+// pnpm ops get archives
// pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'
// pnpm ops fetch-windows --file windows.json --wait
// pnpm ops get tags eva-collab
@@ -204,6 +211,9 @@
// pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'
// pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'
// pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'
+// pnpm ops get lookouts
+// pnpm ops lookout-run --json '{"id":"example-week","dryRun":true}'
+// pnpm ops lookout-run --json '{"id":"example-week","dryRun":true,"days":3,"until":"2026-11-10"}'
//
// --file reads the BODY from a JSON file, which is how a big one gets sent: a
// four-thousand-id tag-videos body is written by a script, not typed by a model
@@ -282,6 +292,9 @@ const GETTERS = {
slug ? `/api/ops/saved-alternates?slug=${encodeURIComponent(slug)}` : "/api/ops/saved-alternates",
// Every site: id, title, siteUrl, Pages project, audience, policy, channels.
sites: () => "/api/ops/sites",
+ // The connected archives (settings.remoteArchives, plus TRANSCRIPT_SITE_URL's,
+ // marked fromEnv): the published archives this machine reads as sources.
+ archives: () => "/api/ops/archives",
// The transcription workers and what each is running.
workers: () => "/api/ops/workers",
// The four lanes: runner, policy, cooldowns, picks, pending.
@@ -308,6 +321,9 @@ const GETTERS = {
cleanup: (slug) => `/api/ops/cleanup/${encodeURIComponent(slug)}`,
// The speakers readout: waiting, freed this run, rate, days left, per channel.
speakers: () => "/api/ops/speakers",
+ // The saved lookouts (settings.lookouts) and what the store holds for each:
+ // the latest run, how many of its ideas wait for a verdict.
+ lookouts: (id) => (id ? `/api/ops/lookouts?id=${encodeURIComponent(id)}` : "/api/ops/lookouts"),
// What a channel holds, by date, and its gaps (release 19 A9): each video
// dated by its recorded date when the channel has a title rule, else upload.
coverage: (slug) => `/api/ops/coverage?slug=${encodeURIComponent(slug)}`,
@@ -351,6 +367,7 @@ const GET_ARG_OPTIONAL = new Set([
"storage",
"saved-alternates",
"sites",
+ "archives",
"workers",
"auto-queue",
"scheduler",
@@ -360,6 +377,7 @@ const GET_ARG_OPTIONAL = new Set([
"generation-usage",
"render-mode",
"speakers",
+ "lookouts",
]);
// The flags each noun takes beyond the shared ones; any other is refused.
@@ -408,6 +426,10 @@ const ACTIONS = [
// Delete a site ({id, force?, dryRun?}): the plan, then sites/<id>/, its
// publish state and its staging. Channel data is never touched. Synchronous.
"delete-site",
+ // Connect a published archive as a source ({connect: "<origin>", dryRun?}:
+ // its corpus.json read once, then saved) or remove one ({remove: "<id>"}).
+ // Synchronous; no job.
+ "archives",
// The channel's lifecycle: the New channel form, and the channel page's
// Danger → Rename and Danger → Delete. Synchronous; no job.
"create-channel",
@@ -442,6 +464,16 @@ const ACTIONS = [
// job; both land through the same code.
"import-media",
"record-live",
+ // A LOCAL MEDIA LIBRARY (controller/localMediaImport.ts): a directory of
+ // recordings that stay where they are, the channel's `localMedia`. Its
+ // config ({slug, sourceId, directory}), a scan writing nothing ({slug}),
+ // details for a recording with no .info.json, the import job, and the link
+ // of a record already held to its original. The local media page's twins.
+ "local-media-configure",
+ "local-media-preview",
+ "local-media-prepare",
+ "local-media-import",
+ "local-media-link",
// LIVE PRE-CLIP (plans/live-preclip.md): a recording in progress transcribed
// and mined while it records ({slug, id, action?: start | stop | status |
// finalize, everyMinutes?, maxChunkMinutes?, overlapSeconds?, scan?, mine?,
@@ -544,7 +576,8 @@ const ACTIONS = [
"tts",
// Run an engine over a speech RECORDING ({file, out, engine?, params?,
// parts?}; convert also takes voice — a stock synthetic voice
- // `<tts engine>:<voice>`, never a recording), as a job on the `voice` queue
+ // `<tts engine>:<voice>`, never a recording — and pitch / semitones, the
+ // pitch the result lands on), as a job on the `voice` queue
// behind the heavy slot. With --wait the result JSON is what stdout carries.
"voice-enhance",
"voice-convert",
@@ -690,6 +723,11 @@ const ACTIONS = [
// X's queue, the jar checked before each ({channels: [...], limit?} or
// {resume: <run id>}); a stale jar defers the rest.
"x-run",
+ // What a saved lookout would read ({id, dryRun: true, days?, maxVideos?,
+ // until?}): its channels' videos by air date, duplicate uploads and stream
+ // cut-downs folded in, the cap. Synchronous; no job, nothing written. Only
+ // the dry run exists yet.
+ "lookout-run",
];
// The log line a transcribe job ends with: this marker, then the result as
@@ -1069,6 +1107,7 @@ export function usage() {
" pnpm ops get x-run [<run id>]",
" pnpm ops get cleanup <slug>",
" pnpm ops get speakers",
+ " pnpm ops get lookouts [<id>]",
" pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]",
" pnpm ops get transcript <videoId> [--slug <slug>]",
" pnpm ops get coverage <slug>",
@@ -1123,6 +1162,8 @@ export function usage() {
"get sites lists every site: id, title, siteUrl, Pages project, audience,",
" listed, search, publish policy, channels, citedChannels. (`get publish`",
" is the status.)",
+ "get archives lists the connected archives: id, origin, title, addedAt;",
+ " TRANSCRIPT_SITE_URL's, when set and not stored, is listed with fromEnv.",
"get workers, get auto-queue and get scheduler are /workers, the four lanes",
" of /operations, and /operations/sync — the payloads those pages poll.",
"get services is the dashboard's cookie refresh alerts: each service",
@@ -1162,6 +1203,11 @@ export function usage() {
" noFingerprintPossible (diarized, audio already gone), per channel with",
" corpus-disk channels first; and the lane: armed, held, the operations",
" it dispatches, its order, cleanAfterCapture and requireVoiceprints.",
+ "get lookouts [<id>] is the saved lookouts (settings.lookouts, SETTINGS.md):",
+ " each one's channels, days, cap and zone, its runs (transcripts/.lookouts/",
+ " <id>/), the latest run (when, window, model, calls, seconds, ideas), how",
+ " many of that run's ideas have no verdict yet, and the verdicts given.",
+ " Reads settings and the store only, never a channel's videos.",
"get cleanup <slug> is one channel's /cleanup row: what each sweep would",
" reclaim (they overlap — never add them), what holds the rest, and the",
" failed-transcriptions count. measured: false means unknown, not zero.",
@@ -1247,6 +1293,20 @@ export function usage() {
' "speakers": "work" (the deck\'s Work through speakers: arm, lift the hold,',
' start a run) | "pause" (hold; stays armed).',
"",
+ 'lookout-run lists what a saved lookout (settings.lookouts) would read:',
+ ' {"id", "dryRun": true, "days"?, "maxVideos"?, "until"?: "YYYY-MM-DD"}.',
+ " Every video of its channels whose AIR date (release_timestamp, else",
+ " timestamp, in the lookout's timeZone — not the UTC upload_date) falls in",
+ " the window; a duplicate upload of one recording, and a stream's cut-down,",
+ " folded into it (each named, with why and its score); the longest",
+ " maxVideos recordings read and the rest listed as skipped for the cap;",
+ " under minSeconds and no transcript yet listed too. A local media library",
+ " channel or a slug this archive does not hold is named in \"refused\".",
+ " Answers {plan: {window, counts, read, skipped, refused, estimate}}:",
+ " readCalls is one per transcript chunk, priced once a run has been",
+ " measured. Synchronous, reads text only, writes nothing; without",
+ ' "dryRun": true it is refused (the model run is not in this build).',
+ "",
'render-mode gives a render the operator is waiting for the machine:',
' {"on": true, "for"?: "90m" | <minutes>, "note"?} opens a window (default',
' 2h) in which every other heavy job — e2e suites, next builds, the publish',
@@ -1531,6 +1591,14 @@ export function usage() {
" own. Refused, force or not: no such site (404), a site dir that is a link,",
" a publish stage running.",
"",
+ 'archives connects a published archive as a source: {"connect": "<origin>"}',
+ " reads <origin>/corpus.json once (its title, totals and channels) and saves",
+ ' it in settings.remoteArchives; "dryRun"? answers the probe and writes',
+ " nothing; an origin connected already writes nothing. A federation hub, a",
+ " cited-only site, one with no channels or one that does not answer is",
+ ' refused. {"remove": "<id or origin>"} drops one. Create, research and the',
+ " MCP offer each connected archive; a sweep over it cites it.",
+ "",
'create-channel is the New channel form: {"fields": {"name", "handling":',
' "youtube"|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?,',
' "socialHandle"?, …}} with channel-config\'s patch keys; "slug"? (else',
@@ -1773,6 +1841,49 @@ export function usage() {
' "dryRun": true says what it would do and writes nothing. A directory, a',
' .zip or a .7z goes to attach-media ("id", "replace", "dryRun" only).',
"",
+ "local-media-configure gives a video channel a LOCAL MEDIA LIBRARY: {\"slug\",",
+ " \"sourceId\", \"directory\"} — a stable lowercase id and an absolute directory",
+ " on the editor server whose recordings stay where they are (never copied,",
+ " moved or deleted). Written through the channel config; a channel that",
+ " already has one is refused, and so is queued or running channel work.",
+ " Playback is not set. Synchronous.",
+ "",
+ "local-media-preview scans the library and writes nothing: {\"slug\"} ->",
+ " {preview: {sourceToken, counts, candidates}}. Each .mp4 directly in the",
+ " directory (not its subdirectories) with its same-named .info.json and",
+ " .vtt (or .srt) is \"new\", \"existing\" (its record is held) or \"issue\" (with",
+ " issues). The sourceToken and a candidate's fingerprint (or",
+ " preparationFingerprint, when it has no .info.json) are what the other",
+ " local-media actions take. An unreachable library is an error, never an",
+ " empty preview.",
+ "",
+ "local-media-prepare reviews details for a recording with no .info.json and",
+ " writes nothing: {\"slug\", \"sourceToken\", \"media\", \"sourceFingerprint\"",
+ " (the candidate's preparationFingerprint), \"details\": {\"mode\": \"inspect\"",
+ " | \"manual\", \"title\", \"recordedDate\"? (YYYY-MM-DD), \"durationSeconds\"?",
+ " (manual)}} -> {review: {metadata, fingerprint}}. \"inspect\" measures the",
+ " duration with ffprobe. Import it with local-media-import, the review's",
+ " fingerprint and \"preparation\": {\"sourceFingerprint\", \"details\"}.",
+ "",
+ "local-media-import imports library recordings as one job on the channel's",
+ " queue: {\"slug\", \"sourceToken\", \"selected\": [{\"media\", \"fingerprint\",",
+ " \"preparation\"?}]} from a preview, or {\"slug\", \"allNew\": true} for every",
+ " \"new\" candidate of a fresh preview (the first 1000 in the scan's order,",
+ " with \"remaining\" in the answer and the log when there are more). Each",
+ " record gets metadata.info.json,",
+ " transcript.en.vtt and external-media.json; the video stays in the",
+ " library. Every selection is re-checked first (a changed file is stale; a",
+ " held record is left unchanged). Drainable between recordings; searchable",
+ " after the next index build.",
+ "",
+ "local-media-link links a record the channel already holds to its library",
+ " original: {\"slug\", \"sourceToken\", \"media\", \"fingerprint\", \"dryRun\"?} for",
+ " an \"existing\" candidate. Only when the library's .info.json and",
+ " transcript match the record's byte for byte is external-media.json",
+ " written (\"attached\"; \"already-linked\"; \"conflict\" keeps a different one).",
+ " Nothing else changes, and no playback is granted. \"dryRun\" answers",
+ " \"ready\" without writing.",
+ "",
'record-live records a live stream until it ends, then lands it as',
' import-media lands a file: {"slug", "url"} (or "id" of a record here),',
' "fromStart"? (true: yt-dlp --live-from-start — Rumble\'s DVR playlist',
@@ -1852,6 +1963,15 @@ export function usage() {
" fetches in place of the platform's floor (Rumble's 120 s); still jittered",
" up to half again. Shorter than the default risks Rumble's IP-wide",
" Cloudflare challenge; a Retry keeps it.",
+ ' "archive" (items only) names the CONNECTED archive the items cite',
+ " (settings.remoteArchives): a channel this editor does not hold is",
+ ' registered as a remote-only channel of it (config only, no listing;',
+ ' answered in "registered"; a dry run registers nothing), and a remote-only',
+ " channel's page URL comes from the archive's record. Its window on a",
+ " whole-recording platform is refused with the recording's estimated size",
+ ' unless "allowWholeRecording": true. Another origin registers nothing.',
+ " A media URL's transient 403 (googlevideo's) is asked once more after a",
+ " pause before it counts toward the two-403 stop.",
' A window on a whole-recording platform (settings.clips',
' .wholeRecordingPlatforms, default Rumble) is not seeked: the video is',
' saved whole once, as "Persist source video" saves it, on the platform\'s',
@@ -1947,8 +2067,17 @@ export function usage() {
" kokoro:am_michael, ...; settings.voice.convert.target); a file, a path or a",
" recording is REFUSED as a target (no real person's voice) — and \"engine\"",
" (openvoice | seed-vc, each installed by `archilyzer voice setup --engine <id>`).",
+ ' "pitch" is where the result\'s pitch comes from (settings.voice.convert.pitch):',
+ ' "target" — the stock voice\'s own, the read\'s intonation flattened to it;',
+ ' "source" — the pitch the take was read at (raise your voice and it rises);',
+ ' "contour" — the read\'s rises and falls, moved as a whole to the stock voice\'s',
+ ' register. "semitones" (-12 to 12) then moves a followed pitch; left out, a',
+ " followed pitch takes settings.voice.convert.semitones (0 unless set). source and",
+ " contour are seed-vc's, on its optional f0 model (`archilyzer voice setup",
+ " --engine seed-vc --with f0`; slower, 44.1 kHz); openvoice refuses them.",
" The target's reference is synthesized once through the tts op and kept. The",
- " result adds target, voice, synthetic: true and the disclosure line.",
+ " result adds target, voice, pitch (semitones and f0 — the medians heard and the",
+ " move applied — when followed), synthetic: true and the disclosure line.",
"",
'web-search searches the web (DuckDuckGo\'s HTML page) and answers the',
' results: {"query", "n"?: 6 (at most 20)} -> {results: [{title, url,',
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -1084,3 +1084,17 @@ test("archive-lookup is a POST to its route; import-page passes source through;
assert.match(usage(), /archive-lookup answers the copies of a page each archive source holds/);
assert.match(usage(), /excluded from the Wayback Machine \(cause/);
});
+
+// Local media libraries (lane/local-media slice 1): the Local media page's
+// five twins are POSTs to their own routes, each named in the usage.
+test("the local-media actions are POSTs to their routes, named in the usage", () => {
+ for (const action of ["local-media-configure", "local-media-preview", "local-media-prepare", "local-media-import", "local-media-link"]) {
+ const p = parseArgs([action, "--json", '{"slug":"demo-local"}']);
+ assert.equal(p.method, "POST");
+ assert.equal(p.path, `/api/ops/${action}`);
+ assert.deepEqual(p.body, { slug: "demo-local" });
+ assert.match(usage(), new RegExp(`\\n${action} `));
+ }
+ assert.equal(parseArgs(["local-media-import", "--json", '{"slug":"demo-local","allNew":true}', "--wait"]).wait, true);
+ assert.match(usage(), /Actions:.*record-live, local-media-configure, local-media-preview, local-media-prepare, local-media-import, local-media-link/);
+});
diff --git a/scripts/voice.mjs b/scripts/voice.mjs
@@ -15,7 +15,9 @@
// its delay compensated (-D) so the timing holds.
// convert openvoice OpenVoice v2's tone-colour converter
// (scripts/voice_openvoice.py, torch on the CPU).
-// seed-vc Seed-VC v1's 22 kHz speech model
+// seed-vc Seed-VC v1's 22 kHz speech model, or with
+// --pitch source|contour its 44.1 kHz f0-conditioned
+// one, whose output follows the input's pitch
// (scripts/voice_seedvc.py, torch on the CPU).
// A convert engine is given --target-ref: a STOCK voice's reference clip,
// made by our own TTS engines (the controller refuses anything else).
@@ -27,7 +29,8 @@
// limiter, which would move the timing): to --lufs for enhance, to the
// input's own loudness for convert, either capped at -1 dBTP. Moved into
// place atomically. On stdout, one JSON line: {op, engine, sampleRate,
-// seconds, samples, engineMs, gainDb, inputLufs, outputLufs, more?}.
+// seconds, samples, engineMs, gainDb, inputLufs, outputLufs, more?}, and for
+// a followed pitch {pitch, semitones, f0: {targetHz, sourceHz, shiftSemitones}}.
//
// SCRATCH lives beside --output (`<output>.voice-<pid>/`), never in the OS
// temp dir (a RAM tmpfs on this machine), and is removed on every way out.
@@ -45,6 +48,10 @@
// --code <dir> the engine's pinned checkout [openvoice, seed-vc]
// --target-ref <wav> the stock target's reference clip [convert]
// --target-se <pt> where openvoice caches the target's embedding
+// --pitch <mode> target (default: the stock voice's own pitch), source
+// (the input's pitch) or contour (the input's intonation
+// at the stock voice's register) [seed-vc]
+// --semitones <n> moves a followed pitch, -12 to 12 [seed-vc, with --pitch source|contour]
// --model <f> the rnnoise model [rnnoise]
// --threads <n> CPU threads for torch (default 4)
// --lufs <x> enhance's level when params has no `lufs` (default -20)
@@ -101,6 +108,14 @@ if (!Array.isArray(extra) || !extra.every((x) => x && typeof x.input === "string
}
const ffmpeg = arg("--ffmpeg", process.env.FFMPEG_BIN ?? "ffmpeg");
const threads = String(Math.max(1, Number(arg("--threads", "4")) || 4));
+// The pitch a conversion lands on (seed-vc; scripts/voice_seedvc.py's header).
+const PITCH_MODES = ["target", "source", "contour"];
+const pitch = arg("--pitch", "target");
+const semitones = Number(arg("--semitones", "0"));
+if (!PITCH_MODES.includes(pitch)) fail(`--pitch is one of ${PITCH_MODES.join(", ")} (got '${pitch}')`);
+if (!Number.isFinite(semitones) || semitones < -12 || semitones > 12) fail(`--semitones is a number from -12 to 12 (got '${arg("--semitones", "")}')`);
+if (pitch !== "target" && kind !== "seed-vc") fail(`--pitch ${pitch} is seed-vc's: ${kind} has no pitch control`);
+if (semitones !== 0 && pitch === "target") fail("--semitones moves a followed pitch: it needs --pitch source or contour");
const lufs = typeof params.lufs === "number" ? params.lufs : Number(arg("--lufs", "-20"));
const out = path.resolve(output);
@@ -247,13 +262,27 @@ async function convertAll(items) {
"--threads", threads,
], { env });
} else {
- await run(python, [
+ const { stdout } = await run(python, [
path.join(import.meta.dirname, "voice_seedvc.py"),
"--code", code,
- "--dit", path.join(install, "DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth"),
- "--config", path.join(install, "config_dit_mel_seed_uvit_whisper_small_wavenet.yml"),
+ // A followed pitch is the f0-conditioned model's (44.1 kHz, its own
+ // vocoder, RMVPE): the optional files `voice setup --engine seed-vc
+ // --with f0` fetches (common/lib/voiceApps.ts SEEDVC_F0_FILES).
+ ...(pitch === "target"
+ ? [
+ "--dit", path.join(install, "DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth"),
+ "--config", path.join(install, "config_dit_mel_seed_uvit_whisper_small_wavenet.yml"),
+ "--bigvgan", path.join(install, "bigvgan"),
+ ]
+ : [
+ "--dit", path.join(install, "DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema_v2.pth"),
+ "--config", path.join(install, "config_dit_mel_seed_uvit_whisper_base_f0_44k.yml"),
+ "--bigvgan", path.join(install, "bigvgan-44k"),
+ "--rmvpe", path.join(install, "rmvpe.pt"),
+ "--pitch", pitch,
+ "--semitones", String(semitones),
+ ]),
"--whisper", path.join(install, "whisper-small"),
- "--bigvgan", path.join(install, "bigvgan"),
"--campplus", path.join(install, "campplus_cn_common.bin"),
"--batch", batch, "--target-ref", ref,
"--steps", String(Math.round(Math.min(100, Math.max(1, num(params.steps, 10))))),
@@ -261,7 +290,15 @@ async function convertAll(items) {
"--ref-seconds", String(Math.min(25, Math.max(3, num(params.refSeconds, 10)))),
"--threads", threads,
], { env });
+ // A followed pitch: what the tracker heard and how far the curve was moved.
+ try {
+ const said = JSON.parse(stdout.trim().split("\n").pop() ?? "{}");
+ if (pitch !== "target" && said.f0 && typeof said.f0 === "object") return { pitch, semitones, f0: said.f0 };
+ } catch {
+ /* the result line is the wrapper's own */
+ }
}
+ return {};
}
// One static gain (enhance to --lufs, convert to the input's own loudness;
@@ -302,8 +339,9 @@ try {
const items = [];
for (const [k, item] of [{ input, output }, ...extra].entries()) items.push(await prepare(item, k));
const started = Date.now();
+ const engineSaid = {};
if (op === "enhance") for (const it of items) await enhanceOne(it);
- else await convertAll(items);
+ else Object.assign(engineSaid, await convertAll(items));
const engineMs = Date.now() - started;
const done = [];
for (const it of items) done.push(await finish(it));
@@ -319,6 +357,7 @@ try {
gainDb: first.gainDb,
inputLufs: first.inputLufs,
outputLufs: first.outputLufs,
+ ...engineSaid,
...(rest.length ? { more: rest } : {}),
};
process.stdout.write(JSON.stringify(result) + "\n");
diff --git a/scripts/voice.test.mjs b/scripts/voice.test.mjs
@@ -31,6 +31,13 @@ test("the argv is checked before anything runs", () => {
assert.match(run(["--op", "enhance", "--engine-kind", "seed-vc"]).stderr, /--engine-kind for enhance is one of rnnoise, deepfilternet/);
assert.match(run(["--op", "enhance", "--engine-kind", "rnnoise"]).stderr, /--input and --output are required/);
assert.match(run(["--op", "enhance", "--engine-kind", "rnnoise", "--input", "/a", "--output", "/b", "--params", "{"]).stderr, /--params must be JSON/);
+ // The pitch a conversion lands on is seed-vc's to follow, and semitones move a followed one.
+ const conv = (kind, ...more) => run(["--op", "convert", "--engine-kind", kind, "--input", "/a", "--output", "/b", ...more]);
+ assert.match(conv("seed-vc", "--pitch", "higher").stderr, /--pitch is one of target, source, contour \(got 'higher'\)/);
+ assert.match(conv("seed-vc", "--pitch", "source", "--semitones", "13").stderr, /--semitones is a number from -12 to 12 \(got '13'\)/);
+ assert.match(conv("seed-vc", "--semitones", "2").stderr, /--semitones moves a followed pitch: it needs --pitch source or contour/);
+ assert.match(conv("openvoice", "--pitch", "contour").stderr, /--pitch contour is seed-vc's: openvoice has no pitch control/);
+ for (const r of [conv("seed-vc", "--pitch", "higher"), conv("openvoice", "--pitch", "contour")]) assert.equal(r.status, 2);
});
test("rnnoise: 48 kHz mono, the input's exact length, aligned, the same every run", { skip: !ffmpeg && "ffmpeg absent" }, () => {
@@ -90,3 +97,43 @@ test("--more runs further files the same way, in the same run", { skip: !ffmpeg
assert.equal(readFileSync(outB).readUInt32LE(40), 48000);
assert.match(run(["--op", "enhance", "--engine-kind", "rnnoise", "--input", a, "--output", "/x.wav", "--more", '[{"input":1}]']).stderr, /--more is a list of \{input, output\}/);
});
+
+// scripts/voice_seedvc.py's contour shift over a batch (a take and its parts): measured once, on the first file with
+// a voiced frame. The function is stdlib-only (torch and the model are imported inside main).
+let python = true;
+try {
+ execFileSync("python3", ["-c", "import math"], { stdio: "ignore" });
+} catch {
+ python = false;
+}
+
+test("seed-vc's contour shift: set by the first file with a voiced frame, never locked at 0 by a silent one", { skip: !python && "python3 absent" }, () => {
+ const code = `
+import json, math, sys
+sys.path.insert(0, ${JSON.stringify(import.meta.dirname)})
+from voice_seedvc import pitch_move
+ref, src = math.log(200.0), math.log(100.0)
+out = {}
+# A silent first file: nothing measured, a factor of the semitones alone.
+m, hz, f = pitch_move(None, None, None, ref, "contour", 0)
+out["silent"] = [m, hz, f]
+# The next, voiced: an octave up to the reference's median, and it is kept.
+m, hz, f = pitch_move(m, hz, src, ref, "contour", 0)
+out["voiced"] = [round(m, 6), hz, round(f, 6)]
+m2, hz2, f2 = pitch_move(m, hz, math.log(150.0), ref, "contour", 0)
+out["later"] = [round(m2, 6), hz2, round(f2, 6)]
+# Source: no move, the semitones alone; contour with semitones: both.
+out["source"] = [round(x, 6) if isinstance(x, float) else x for x in pitch_move(None, None, src, ref, "source", 12)]
+out["both"] = round(pitch_move(None, None, src, ref, "contour", -12)[2], 6)
+# A silent file after the move is set does not unset it.
+out["after"] = round(pitch_move(m, hz, None, ref, "contour", 0)[0], 6)
+print(json.dumps(out))
+`;
+ const out = JSON.parse(execFileSync("python3", ["-c", code], { encoding: "utf8", env: { ...process.env, PYTHONDONTWRITEBYTECODE: "1" } }));
+ assert.deepEqual(out.silent, [null, null, 1]);
+ assert.deepEqual(out.voiced, [0.693147, 100, 2]);
+ assert.deepEqual(out.later, [0.693147, 100, 2]);
+ assert.deepEqual(out.source, [0, 100, 2]);
+ assert.equal(out.both, 1);
+ assert.equal(out.after, 0.693147);
+});
diff --git a/scripts/voice_seedvc.py b/scripts/voice_seedvc.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-# SEED-VC (v1, the 22 kHz speech model), files in, files out — run by
+# SEED-VC (v1: the 22 kHz speech model, or the 44.1 kHz f0-conditioned one), files in, files out — run by
# scripts/voice.mjs (--engine-kind seed-vc) in the venv `archilyzer voice
# setup --engine seed-vc` built. Never run by hand: the editor's
# `voice-convert` op is the way in (common/controller/voiceFile.ts).
@@ -17,19 +17,56 @@
# quantizer this model does not use; it is stubbed rather than installed (it
# pulls in a training stack).
#
+# PITCH (--pitch). The 22 kHz model is given no pitch at all: it speaks every
+# input at the TARGET's own pitch and narrows the range (measured 2026-11-11:
+# inputs with a median f0 of 128 to 237 Hz all came out at 196-199 Hz) — the
+# read's intonation is thrown away. `--pitch target` is that, unchanged. The
+# other two run upstream's f0-conditioned model (`inference.py --f0-condition`:
+# 44.1 kHz, a 128-band BigVGAN, RMVPE as the pitch tracker — voice.mjs passes
+# those files as --dit/--config/--bigvgan and --rmvpe): the input's f0 curve
+# conditions the content, so the output's pitch FOLLOWS the read.
+# source the input's f0 as it is: the output is at the pitch it was read at.
+# contour the input's curve moved, as a whole, so its median lands on the
+# target reference's median (upstream's --auto-f0-adjust): every rise
+# and fall is kept, the register is the stock voice's.
+# --semitones then moves the followed curve up or down (2^(n/12)). In a batch
+# the contour's move is measured ONCE, on the first file (the take), and used
+# for the rest (its parts): a part must sit where it sits in the whole. A file
+# with no voiced frame (silence, a breath) has no median to measure: it leaves
+# the move unset, and the first file that has one sets it.
+#
# Several files (--batch) are converted one after another, the model and the
# target's features made once.
#
-# stdout: one JSON line {engine, sampleRate, seconds, files, engineMs}.
+# stdout: one JSON line {engine, sampleRate, seconds, files, engineMs, pitch,
+# semitones, f0?: {targetHz, sourceHz, shiftSemitones}} — f0 is the medians
+# RMVPE heard in the reference and the first file, and the whole move applied.
import argparse
import json
+import math
import os
import sys
import time
import types
+def pitch_move(move, source_hz, median, ref_median, pitch, semitones):
+ """The followed curve's factor for one file, and the batch's state after it.
+
+ `move` is the batch's shift in log-f0 (None: not measured yet), `median` this
+ file's median log-f0 (None: no voiced frame), `ref_median` the reference's.
+ The shift is measured ONCE, on the first file with a voiced frame — contour:
+ the reference's median less the file's; source: 0 — and a file before it
+ (unvoiced: nothing in it is multiplied anyway) leaves it unset rather than
+ locking it at 0. Returns (move, source_hz, factor).
+ """
+ if move is None and median is not None:
+ source_hz = round(math.exp(median), 1)
+ move = (ref_median - median) if pitch == "contour" and ref_median is not None else 0.0
+ return move, source_hz, math.exp(move or 0.0) * 2 ** (semitones / 12)
+
+
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--code", required=True, help="the seed-vc checkout")
@@ -46,11 +83,22 @@ def main() -> int:
ap.add_argument("--cfg-rate", type=float, default=0.7)
ap.add_argument("--ref-seconds", type=float, default=10.0,
help="how much of the reference prompts the model: each window is 30 s less this, so less is faster")
+ ap.add_argument("--pitch", choices=["target", "source", "contour"], default="target",
+ help="target: the stock voice's own pitch (the 22 kHz model); source / contour: the input's f0 conditions the 44.1 kHz f0 model")
+ ap.add_argument("--semitones", type=float, default=0.0, help="moves the followed f0 (source, contour); -12 to 12")
+ ap.add_argument("--rmvpe", default="", help="rmvpe.pt, the pitch tracker (source, contour)")
ap.add_argument("--threads", type=int, default=4)
a = ap.parse_args()
items = json.load(open(a.batch)) if a.batch else [{"input": a.input, "output": a.output}]
if not items or not all(i.get("input") and i.get("output") for i in items):
ap.error("--input and --output, or --batch")
+ follow = a.pitch != "target"
+ if follow and not a.rmvpe:
+ ap.error("--pitch source|contour needs --rmvpe")
+ if not follow and a.semitones != 0:
+ ap.error("--semitones moves a followed pitch: it needs --pitch source or contour")
+ if not -12 <= a.semitones <= 12:
+ ap.error("--semitones is between -12 and 12")
os.environ.setdefault("HF_HUB_OFFLINE", "1")
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
@@ -106,6 +154,34 @@ def main() -> int:
whisper.eval()
feat = AutoFeatureExtractor.from_pretrained(a.whisper, local_files_only=True)
+ # The pitch tracker (source, contour): f0 in Hz per 10 ms of 16 kHz audio,
+ # 0 where unvoiced. A long input goes in 30 s pieces, each heard with a
+ # second of context either side — RMVPE over half an hour at once is GBs.
+ f0_of = None
+ if follow:
+ from modules.rmvpe import RMVPE
+
+ rmvpe = RMVPE(a.rmvpe, is_half=False, device=device)
+ PIECE, CTX, HOP16 = 16000 * 30, 16000, 160
+
+ def f0_of(w16):
+ w16 = w16.squeeze(0).cpu().numpy()
+ n = len(w16)
+ if n <= PIECE + 2 * CTX:
+ return rmvpe.infer_from_audio(w16, thred=0.03)
+ out, at = [], 0
+ while at < n:
+ lo, end = max(0, at - CTX), min(n, at + PIECE)
+ f = rmvpe.infer_from_audio(w16[lo : min(n, end + CTX)], thred=0.03)
+ first = (at - lo) // HOP16
+ out.append(f[first:] if end == n else f[first : first + (end - at) // HOP16])
+ at = end
+ return np.concatenate(out)
+
+ def median_log(f0):
+ v = f0[f0 > 1]
+ return float(np.median(np.log(v))) if len(v) else None
+
def semantic(w16):
inputs = feat([w16.squeeze(0).cpu().numpy()], return_tensors="pt", return_attention_mask=True, sampling_rate=16000)
x = whisper._mask_input_features(inputs.input_features, attention_mask=inputs.attention_mask)
@@ -148,8 +224,23 @@ def main() -> int:
fb = torchaudio.compliance.kaldi.fbank(ref16, num_mel_bins=80, dither=0, sample_frequency=16000)
fb = fb - fb.mean(dim=0, keepdim=True)
style = campplus(fb.unsqueeze(0))
- prompt, *_ = model.length_regulator(s_ori, ylens=target2_len, n_quantizers=3, f0=None)
+ f0_ref = f0_of(ref16) if follow else None
+ prompt, *_ = model.length_regulator(s_ori, ylens=target2_len, n_quantizers=3,
+ f0=torch.from_numpy(f0_ref)[None] if follow else None)
window = max_context - mel2.size(2)
+ ref_median = median_log(f0_ref) if follow else None
+ # What was heard and done, for the result line; `move` is the contour's
+ # shift in log-f0, measured on the first file that has a voiced frame and
+ # kept for the rest (None until then: a file with none has nothing to move).
+ heard = {"move": None, "sourceHz": None}
+
+ def followed_f0(src16):
+ f0 = f0_of(src16)
+ heard["move"], heard["sourceHz"], factor = pitch_move(heard["move"], heard["sourceHz"], median_log(f0), ref_median, a.pitch, a.semitones)
+ voiced = f0 > 1
+ out = f0.copy()
+ out[voiced] = f0[voiced] * factor
+ return torch.from_numpy(out.astype(np.float32))[None]
def convert(src):
with torch.no_grad():
@@ -172,7 +263,8 @@ def main() -> int:
s_alt = torch.cat(parts, dim=1)
mel = to_mel(source)
# The input's own frame count: the timing is the input's.
- cond, *_ = model.length_regulator(s_alt, ylens=torch.LongTensor([mel.size(2)]), n_quantizers=3, f0=None)
+ cond, *_ = model.length_regulator(s_alt, ylens=torch.LongTensor([mel.size(2)]), n_quantizers=3,
+ f0=followed_f0(src16) if follow else None)
done, chunks, prev = 0, [], None
while done < cond.size(1):
c = cond[:, done : done + window]
@@ -208,6 +300,13 @@ def main() -> int:
"seconds": round(total, 3),
"files": len(items),
"engineMs": int((time.time() - t0) * 1000),
+ "pitch": a.pitch,
+ "semitones": a.semitones,
+ **({"f0": {
+ "targetHz": round(float(np.exp(ref_median)), 1) if ref_median is not None else None,
+ "sourceHz": heard["sourceHz"],
+ "shiftSemitones": round(12 * (heard["move"] or 0.0) / float(np.log(2)) + a.semitones, 2),
+ }} if follow else {}),
}))
return 0
diff --git a/settings.json.example b/settings.json.example
@@ -217,6 +217,7 @@
"archiveTodayCooldownMinutes": 30,
"archiveTodayBrowser": true
},
+ "remoteArchives": [],
"publish": {
"enabled": false,
"held": false,
@@ -268,13 +269,16 @@
},
"convert": {
"engine": "openvoice",
- "target": "orpheus:zac"
+ "target": "orpheus:zac",
+ "pitch": "target",
+ "semitones": 0
},
"heavyEstimateMB": {
"deepfilternet": 400,
"rnnoise": 300,
"openvoice": 2000,
- "seed-vc": 3500
+ "seed-vc": 3500,
+ "seed-vc-f0": 6500
}
},
"generation": {
@@ -370,5 +374,10 @@
"probeServices": [
"rumble"
]
+ },
+ "lookouts": {
+ "enabled": false,
+ "afterSync": false,
+ "items": []
}
}
diff --git a/umtool/app/api/articles/chain/route.ts b/umtool/app/api/articles/chain/route.ts
@@ -13,7 +13,7 @@ export const dynamic = "force-dynamic";
// `from`. The projects root is the editor's policy's (generation.projectsRoot).
//
// GET ?article=<id>&n=<n>[&mode=draft-all][&deck=1] -> { chain } the steps, where it resumes, its job
-// POST { article, n, from?, draftAll?, model?, deck? } -> { ok, job } started
+// POST { article, n, from?, draftAll?, model?, deck?, stopBeforeRender?, allowWholeRecording? } -> { ok, job } started
// POST { cancel: <jobId> } -> { cancelled }
//
// `draftAll` is Draft everything (release 28 M9): the chain with its
@@ -21,6 +21,10 @@ export const dynamic = "force-dynamic";
// route) — and the fast build; a job of its own kind, resumed as the chain is.
// `deck` (release 29 G1, Draft everything's option, off by default) adds the
// deck step before the flips: the minimal on-screen deck on a cut with none.
+// `stopBeforeRender` (demo epic D1) ends the run before the voices: nothing
+// voiced or built; the next run resumes there. `allowWholeRecording` (the
+// windows step's one press) lets a remote-only channel's Rumble windows
+// download their whole recording, refused with its size otherwise.
function parse(article: unknown, n: unknown): { article: string; n: number } | string {
const a = String(article ?? "");
const k = Number(n);
@@ -52,7 +56,17 @@ export async function GET(request: Request) {
}
export async function POST(request: Request) {
- const body = (await request.json().catch(() => ({}))) as { article?: unknown; n?: unknown; from?: unknown; cancel?: unknown; draftAll?: unknown; model?: unknown; deck?: unknown };
+ const body = (await request.json().catch(() => ({}))) as {
+ article?: unknown;
+ n?: unknown;
+ from?: unknown;
+ cancel?: unknown;
+ draftAll?: unknown;
+ model?: unknown;
+ deck?: unknown;
+ stopBeforeRender?: unknown;
+ allowWholeRecording?: unknown;
+ };
if (body.cancel !== undefined) {
const id = String(body.cancel);
if (!getJob(id)) return Response.json({ error: "no such job" }, { status: 404 });
@@ -73,7 +87,18 @@ export async function POST(request: Request) {
if (model && mode !== "draft-all") return Response.json({ error: "a model is Draft everything's (draftAll): the model its drafts run on" }, { status: 400 });
const deck = body.deck === true;
if (deck && mode !== "draft-all") return Response.json({ error: "the deck is Draft everything's option (draftAll)" }, { status: 400 });
- const plan = planChain({ articlesDir: ARTICLES_DIR, article: p.article, n: p.n, from, mode, ...(deck ? { deck } : {}), ...(model ? { model } : {}), ...(projectsRoot ? { projectsRoot } : {}) });
+ const plan = planChain({
+ articlesDir: ARTICLES_DIR,
+ article: p.article,
+ n: p.n,
+ from,
+ mode,
+ ...(deck ? { deck } : {}),
+ ...(model ? { model } : {}),
+ ...(projectsRoot ? { projectsRoot } : {}),
+ ...(body.stopBeforeRender === true ? { stopBeforeRender: true } : {}),
+ ...(body.allowWholeRecording === true ? { allowWholeRecording: true } : {}),
+ });
if (plan.steps.length === 0) return Response.json({ error: `every step of ${mode === "draft-all" ? "Draft everything" : "the chain"} is done — pick a step to run from` }, { status: 400 });
const job = startJob(chainKind(p.article, p.n, mode), plan.steps);
return Response.json({ ok: true, job: { id: job.id }, chain: await chainOf(p.article, p.n, mode, deck) });
diff --git a/umtool/app/api/articles/channels/route.ts b/umtool/app/api/articles/channels/route.ts
@@ -1,12 +1,28 @@
-import { errorResponse, listEditorChannels } from "@/lib/articles/generation";
+import { errorResponse, listEditorChannels, type EditorChannel } from "@/lib/articles/generation";
+import { SourceError, openSource } from "@/lib/research/sources";
export const dynamic = "force-dynamic";
-// The editor's channels, for /articles/new's picker (GET /api/ops/channels).
-export async function GET() {
+// The channels /articles/new's picker offers (GET /api/ops/channels): the
+// editor's own, or — `?source=remote:<origin>` (demo epic D1 item 2) — that
+// published archive's, from its corpus.json. Only an offered source opens
+// (lib/research/sources.ts openSource refuses any other handle). A remote-only
+// channel is not offered as the editor's own: it holds no transcripts.
+export async function GET(request: Request) {
try {
- return Response.json({ channels: await listEditorChannels() }, { headers: { "cache-control": "no-store" } });
+ const source = new URL(request.url).searchParams.get("source")?.trim();
+ if (!source) {
+ const channels = (await listEditorChannels()).filter((c) => c.kind !== "remote-only");
+ return Response.json({ channels }, { headers: { "cache-control": "no-store" } });
+ }
+ const opened = await openSource(source);
+ const refs = await opened.source.listChannels();
+ const channels: EditorChannel[] = refs
+ .map((c) => ({ slug: c.slug, name: c.name ?? c.slug, kind: "video", platform: c.platform ?? null, sites: [] }))
+ .sort((a, b) => a.name.localeCompare(b.name));
+ return Response.json({ channels, source: opened.option.handle }, { headers: { "cache-control": "no-store" } });
} catch (err) {
+ if (err instanceof SourceError) return Response.json({ error: err.message }, { status: err.status });
return errorResponse(err);
}
}
diff --git a/umtool/app/api/articles/sources/route.ts b/umtool/app/api/articles/sources/route.ts
@@ -0,0 +1,21 @@
+import { errorResponse, listEditorChannels } from "@/lib/articles/generation";
+import { createSourcesOf } from "@/lib/articles/createSources";
+import { listSources } from "@/lib/research/sources";
+
+export const dynamic = "force-dynamic";
+
+// The corpora "Article from a question" may sweep (demo epic D1 item 2): the
+// editor's own (its channels and the build holding them; handle "") and every
+// published archive the source picker offers (connected archives first). With
+// no local corpus — the editor holds no channel of its own — and an archive to
+// offer, the first archive is preselected.
+//
+// GET -> { sources: [{ handle, label, detail? }], preselect }
+export async function GET() {
+ try {
+ const [sources, channels] = await Promise.all([listSources(), listEditorChannels().catch(() => null)]);
+ return Response.json(createSourcesOf(sources, channels), { headers: { "cache-control": "no-store" } });
+ } catch (err) {
+ return errorResponse(err);
+ }
+}
diff --git a/umtool/app/api/report/post-narration/record/route.ts b/umtool/app/api/report/post-narration/record/route.ts
@@ -1,9 +1,20 @@
-import { readFile, stat } from "node:fs/promises";
+import { mkdir, readFile, rename, stat } from "node:fs/promises";
+import path from "node:path";
import { resolveReport } from "@/lib/report/serve.mjs";
import { refuseCaller } from "@/lib/report/caller";
import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
import { StaleToken, StructureRefused } from "@/lib/report/manifest.mjs";
-import { discardPart, finishSession, partFile, readSession, savePart } from "@/lib/report/recordSession.mjs";
+import { clearSession, discardPart, finishSession, partFile, readSession, savePart, sessionParts } from "@/lib/report/recordSession.mjs";
+import { discardPreview, keepPreview, preparePreview, previewFile, previewView, readPreview } from "@/lib/report/recordPreview.mjs";
+import { readLayers } from "@/lib/report/characterLayers.mjs";
+import { derivePitchOf } from "@/lib/report/derivePitch.mjs";
+import { UMTOOL_DIR } from "@/lib/report/driver.mjs";
+import { PARTS_CACHE, partKey } from "@/lib/report/postThreadRead.mjs";
+import { projectRedaction } from "@/lib/report/postRedaction.mjs";
+import { cancelJob, getJob, jobView, recentJobs, runningJob, startJob, type Job } from "@/lib/jobs";
+import { editorCall, jobState, startJob as startEditorJob } from "@/lib/research/case-editor";
+import { CAST_PITCH_ENGINES, characterSpeed, characterVoice, projectCharactersOf, recordedPresetOf, shownNameOf, voiceRefOf } from "umtool-report-to-video/cast";
+import { spokenRead } from "umtool-report-to-video/post-redact";
export const dynamic = "force-dynamic";
@@ -12,10 +23,40 @@ export const dynamic = "force-dynamic";
//
// GET ?project&id[&label] the session: the parts kept so far (a reload resumes)
// GET ?project&id&n[&label] one kept part's audio (play it back)
-// POST multipart {project, id, n, count, text, para, label?, part} keep part n of count
+// POST multipart {project, id, n, count, text, para, label?, part} keep part n of count (a recording, or a
+// sound file chosen for it)
// POST {project, op: "discard", id, n, label?} drop part n (redo it)
-// POST {project, op: "finish", id, label?, script?} every part in: one recorded
-// take, trimmed, joined, levelled, PICKED
+// POST {project, op: "finish", id, label?, script?, spans?} every part in: one recorded take, cut at the
+// marks (`spans`, per part) else trimmed, joined,
+// levelled, PICKED
+//
+// RECORD -> FILTER -> PREVIEW (lib/report/recordPreview.mjs): the session's parts run through the character's
+// recorded preset into a SCRATCH DIR (narration/.record-preview/<postId>.<label>/), no take made, listened to beside
+// the raw read, then kept or recorded again.
+//
+// GET ?project&id&preview[&label] who it is read as (its direction, convert, clean, trim), the preview as
+// it stands (each part's waveform and marks, what was made), the Filter
+// job running or last run
+// GET ?project&id&preview&file=raw|clean|filtered|part[&n] one of its sounds
+// GET ?project&id&job=<id> the Filter job: its state, the stage it is at (and whether it WAITS --
+// queued, or at the heavy slot for memory: the gate, not an error)
+// GET ?project&id&stock&job=<id>&key a stock read asked for: running | done {file} | failed
+// POST {project, op: "prepare", id} the parts decoded: lengths, waveforms, the auto trim's marks (no editor)
+// POST {project, op: "filter", id, spans?, pitch?, semitones?} THE CHAIN as one job (`umtool posts narrate <p>
+// <item> --preview --events`): clean, cut, convert -- a step whose inputs
+// stand is not run again (another pitch: the convert alone)
+// POST {project, op: "cancel", id, job} stop that job AND the editor's job it waits on (its engine holds the
+// heavy slot otherwise); `editor.note` when that one was not known yet
+// keep, again, discard-preview, finish, discard and a part's upload answer 409 while the item's Filter runs
+// POST {project, op: "keep", id, filtered, spans?, script?} filtered: the preview's files made the takes
+// (recorded, cleaned, converted; the last picked) -- nothing converted
+// again; else the recorded take alone (finish). The session and the
+// scratch dir are cleared.
+// POST {project, op: "again", id, n?} the preview dropped (and part n, to record it again)
+// POST {project, op: "discard-preview", id} the scratch dir removed (the page is left; a beacon)
+// POST {project, op: "stock", id, text} the character's SYNTHETIC preset voice reading the line: the cached read when there
+// is one (narration/parts-cache/, a thread read's), else asked of the
+// editor's tts op (a job) -- only when a person asks
const noStore = { "cache-control": "no-store" };
type Entry = Record<string, unknown> & { id: string; type?: string };
@@ -32,7 +73,75 @@ function itemOf(manifest: Record<string, unknown>, id: string): Entry | null {
return tl.find((e) => e?.type === "post" && e.id === id) ?? null;
}
-const TYPES: Record<string, string> = { webm: "audio/webm", ogg: "audio/ogg", wav: "audio/wav", m4a: "audio/mp4" };
+const TYPES: Record<string, string> = { webm: "audio/webm", ogg: "audio/ogg", wav: "audio/wav", m4a: "audio/mp4", mp3: "audio/mpeg", flac: "audio/flac" };
+
+/** The Filter job of one post item (lib/jobs.ts: one job at a time, its log, Cancel). */
+const filterKind = (project: string, id: string) => `record-filter ${project} ${id}`;
+/** Is that item's Filter running now? Its scratch dir and its session are the job's until it ends. */
+const filterRunning = (project: string, id: string) => runningJob()?.kind === filterKind(project, id);
+const busy = () => Response.json({ error: "its Filter is still running: wait for it, or Cancel it", busy: true }, { status: 409 });
+
+type Stage = { stage?: string; state?: string; message?: string; line?: string; job?: string };
+const WAITS = ["queued", "memory", "slot"];
+/**
+ * The Filter job as the record page reads it: its state, the STAGE it is at (the chain's last `stage` event:
+ * recordPreview.mjs runPreview), every stage's last word, and whether it is WAITING -- `queued` behind the editor's
+ * other jobs, `memory` / `slot` at the machine's heavy slot. A wait is the gate working: it is never an error here.
+ */
+function filterJobView(job: Job) {
+ const stages = (job.events as Array<Stage & { ev?: string }>).filter((x) => x.ev === "stage");
+ const at = stages.at(-1) ?? null;
+ const last: Record<string, Stage> = {};
+ for (const x of stages) if (x.stage) last[x.stage] = { state: x.state, message: x.message };
+ const failed = job.state === "failed";
+ return {
+ id: job.id, state: job.state, startedAt: job.startedAt, endedAt: job.endedAt,
+ stage: at?.stage ?? null, stageState: at?.state ?? null, message: at?.message ?? null,
+ waiting: at && job.state === "running" && WAITS.includes(String(at.state)) ? at.state : null,
+ // Every wait it went through, in order (said after the fact too: "waited for memory").
+ waited: [...new Set(stages.filter((x) => WAITS.includes(String(x.state))).map((x) => String(x.state)))],
+ stages: last,
+ // The editor's job it waits on now (the clean, the convert): what Cancel stops there too. null: none known yet.
+ editorJob: job.state === "running" ? (stages.filter((x) => typeof x.job === "string").at(-1)?.job ?? null) : null,
+ // A failure in the CLI's own words (its last line), not "exited 1".
+ error: failed ? (job.log.filter((l) => !l.startsWith("**") && !l.startsWith("$ ") && !l.startsWith("---")).at(-1) ?? job.error) : null,
+ };
+}
+
+/** Who a recording of `e` is read as, and that character's recorded preset (cast.mjs characterForRead, recordedPresetOf). */
+async function whoOf(dir: string, e: Entry) {
+ const layers = await readLayers(dir);
+ const who = layers.characterForRead(e);
+ const c = who?.character ?? null;
+ const preset = c ? recordedPresetOf(c) : null;
+ // Where a change to it is written: this video's own characters, else the cast.
+ const own = c ? projectCharactersOf(layers.project).some((x: { id: string }) => x.id === c.id) : false;
+ return {
+ character: c ? { id: c.id as string, name: shownNameOf(c) as string, layer: who.layer as string, scope: own ? "project" : "cast" } : null,
+ convert: preset ? preset.convert : null,
+ recorded: preset ? { enhance: preset.enhance, trim: preset.trim, direction: preset.direction } : null,
+ // The voice it reads in when it is SYNTHESIZED (the synthetic preset: the cheap one to hear the line in).
+ synthetic: c && characterVoice(c) ? { voice: String(characterVoice(c)), speed: characterSpeed(c) as number | null } : null,
+ pitchEngines: CAST_PITCH_ENGINES,
+ };
+}
+
+/** The file a stock read of `text` is cached at (a thread read's part: postThreadRead.mjs partKey), project-relative. */
+const stockRel = (key: string) => `${PARTS_CACHE}/${key}.wav`;
+const isKey = (k: string) => /^[0-9a-f]{40}$/.test(k);
+
+/** A stock read asked of the editor: where its job is; done, its file is put in the cache. */
+async function stockPoll(dir: string, job: string, key: string) {
+ if (!isKey(key)) return Response.json({ error: "which read?" }, { status: 400 });
+ const abs = path.join(dir, ...stockRel(key).split("/"));
+ const st = await jobState(job);
+ if (!st.done) return Response.json({ state: "running", status: st.status }, { headers: noStore });
+ if (st.status !== "done") return Response.json({ state: "failed", error: st.tail.slice(-3).join(" / ") }, { headers: noStore });
+ const tmp = `${abs}.pending.tmp.wav`;
+ if (await stat(tmp).catch(() => null)) await rename(tmp, abs);
+ if (!(await stat(abs).catch(() => null))?.isFile()) return Response.json({ state: "failed", error: "the job is done but its read is not there" }, { headers: noStore });
+ return Response.json({ state: "done", file: stockRel(key) }, { headers: noStore });
+}
export async function GET(request: Request) {
const q = new URL(request.url).searchParams;
@@ -42,6 +151,22 @@ export async function GET(request: Request) {
if (!e) return Response.json({ error: `no post item ${q.get("id")}` }, { status: 404 });
const label = q.get("label") ?? "operator";
try {
+ if (q.get("stock") !== null) return await stockPoll(r.project.dir, String(q.get("job") ?? ""), String(q.get("key") ?? ""));
+ if (q.get("job") !== null) {
+ const job = getJob(String(q.get("job")));
+ if (!job || job.kind !== filterKind(r.project.id, e.id)) return Response.json({ error: "no such job" }, { status: 404 });
+ return Response.json({ ok: true, job: filterJobView(job), ...(job.state === "done" ? { preview: previewView(await readPreview(r.project.dir, e, label)) } : {}) }, { headers: noStore });
+ }
+ if (q.get("preview") !== null) {
+ const which = q.get("file");
+ if (which !== null) {
+ const f = await previewFile(r.project.dir, e, which, { label, n: q.get("n") === null ? null : Number(q.get("n")) });
+ if (!f) return new Response("no such sound", { status: 404 });
+ return new Response(new Uint8Array(await readFile(f)), { headers: { "content-type": "audio/wav", ...noStore } });
+ }
+ const mine = [runningJob(), ...recentJobs(20)].find((j) => j && j.kind === filterKind(r.project.id, e.id)) ?? null;
+ return Response.json({ ok: true, ...(await whoOf(r.project.dir, e)), preview: previewView(await readPreview(r.project.dir, e, label)), job: mine ? filterJobView(mine) : null }, { headers: noStore });
+ }
const n = q.get("n");
if (n !== null) {
const f = await partFile(r.project.dir, e, Number(n), label);
@@ -76,11 +201,14 @@ export async function POST(request: Request) {
if (!e) return Response.json({ error: `no post item ${String(form.get("id"))}` }, { status: 404 });
const blob = form.get("part");
if (!blob || typeof blob === "string") return Response.json({ error: "no part" }, { status: 400 });
+ if (filterRunning(r.project.id, e.id)) return busy();
try {
const session = await savePart(r.project.dir, e, {
n: Number(form.get("n")), count: Number(form.get("count")), text: String(form.get("text") ?? ""), para: Number(form.get("para")),
bytes: new Uint8Array(await blob.arrayBuffer()), type: blob.type || "audio/webm", label: String(form.get("label") ?? "operator").toLowerCase(),
});
+ // Another recording than the one a preview was made from: that preview goes (it must never be kept for this one).
+ await discardPreview(r.project.dir, e, String(form.get("label") ?? "operator").toLowerCase());
return Response.json({ ok: true, session }, { headers: noStore });
} catch (err) {
return fail(err);
@@ -99,12 +227,109 @@ export async function POST(request: Request) {
const label = String(body.label ?? "operator").toLowerCase();
try {
if (body.op === "discard") return Response.json({ ok: true, session: await discardPart(r.project.dir, e, Number(body.n), label) }, { headers: noStore });
+ const script = typeof body.script === "string" ? body.script : null;
+ const spans = spansOf(body.spans);
if (body.op === "finish") {
- const kept = await finishSession(r.project, e, { label, manifest: r.manifest as Record<string, unknown>, script: typeof body.script === "string" ? body.script : null });
+ const kept = await finishSession(r.project, e, { label, manifest: r.manifest as Record<string, unknown>, script, spans });
+ await discardPreview(r.project.dir, e, label);
return Response.json({ ok: true, take: kept.take, gain: kept.gain, entry: kept.result.entry, token: kept.result.token }, { headers: noStore });
}
- return Response.json({ error: "op is discard or finish" }, { status: 400 });
+ if (body.op === "prepare") {
+ // The parts decoded into the scratch dir: their waveforms and the auto trim's marks. No editor, no take.
+ const who = await whoOf(r.project.dir, e);
+ const doc = await preparePreview(r.project, e, await sessionParts(r.project.dir, e, label), { label, trim: who.recorded?.trim ?? null });
+ return Response.json({ ok: true, ...who, preview: previewView(doc) }, { headers: noStore });
+ }
+ if (body.op === "filter") {
+ // THE CHAIN, as one job of umtool's (its log, Cancel): the CLI's own command over the session's parts.
+ const running = runningJob();
+ if (running) return Response.json({ error: `umtool is running another job (${running.kind}): Filter when it is done`, busy: true }, { status: 409 });
+ await sessionParts(r.project.dir, e, label);
+ const checked = derivePitchOf({ pitch: body.pitch, semitones: body.semitones });
+ if (!checked.ok) return Response.json({ error: checked.error }, { status: 400 });
+ const pitched: { pitch?: string; semitones?: number } = checked.value ?? {};
+ const cliPath = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs");
+ const argv = [
+ process.execPath, cliPath, "posts", "narrate", r.project.id, e.id, "--preview", "--events", "--label", label,
+ ...(spans ?? []).flatMap((sp, k) => (sp ? ["--trim-span", `${k + 1}=${sp.from}-${sp.to}`] : [])),
+ ...(pitched.pitch ? ["--pitch", pitched.pitch] : []),
+ ...(typeof pitched.semitones === "number" && pitched.pitch !== "target" ? ["--semitones", String(pitched.semitones)] : []),
+ ];
+ const job = startJob(filterKind(r.project.id, e.id), [{ label: `${e.id}: its recording cleaned, cut, converted (a preview: no take)`, argv, cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, timeoutMs: 45 * 60 * 1000, ndjson: true }], { project: r.project.id });
+ return Response.json({ ok: true, job: filterJobView(job) }, { headers: noStore });
+ }
+ if (body.op === "cancel") {
+ const job = getJob(String(body.job ?? ""));
+ if (!job || job.kind !== filterKind(r.project.id, e.id)) return Response.json({ error: "no such job" }, { status: 404 });
+ // The editor's job too: its engine holds (or waits at) the heavy slot whether or not umtool still follows it.
+ const editorJob = filterJobView(job).editorJob;
+ const cancelled = cancelJob(job.id);
+ let editor: { job: string | null; cancelled: boolean; note?: string } = { job: editorJob, cancelled: false };
+ if (editorJob) {
+ const a = await editorCall("/api/ops/job", { method: "POST", body: { verb: "cancel", ids: [editorJob] } }).catch((err: Error) => ({ ok: false, status: 502, body: { error: err.message } as Record<string, unknown> }));
+ editor = a.ok ? { job: editorJob, cancelled: true } : { job: editorJob, cancelled: false, note: `the editor's job ${editorJob} was not cancelled (${String(a.body.error ?? `HTTP ${a.status}`)}): cancel it on the editor's /jobs` };
+ } else if (cancelled) editor = { job: null, cancelled: false, note: "the editor's job was not known yet: if one started, cancel it on the editor's /jobs" };
+ return Response.json({ ok: true, cancelled, editor }, { headers: noStore });
+ }
+ if (["keep", "again", "discard-preview", "finish", "discard"].includes(String(body.op)) && filterRunning(r.project.id, e.id)) return busy();
+ if (body.op === "keep") {
+ if (body.filtered === true) {
+ // The preview's files made the takes: it must be OF this recording and these marks (nothing is converted here).
+ const doc = await readPreview(r.project.dir, e, label);
+ const view = previewView(doc);
+ if (!view?.raw) return Response.json({ error: "there is no preview to keep: Filter it first" }, { status: 409 });
+ if (spans && view.parts.some((p: { span: { from: number; to: number } | null }, k: number) => spans[k] && p.span && (Math.abs(p.span.from - spans[k]!.from) > 0.002 || Math.abs(p.span.to - spans[k]!.to) > 0.002))) {
+ return Response.json({ error: "the cut marks moved since the Filter: Filter again, or keep the recording alone" }, { status: 409 });
+ }
+ // Of the session as it is NOW: a part recorded again since the Filter is another recording (409, nothing kept).
+ const kept = await keepPreview(r.project, e, { label, script, parts: doc?.session ? await sessionParts(r.project.dir, e, label) : null });
+ if (kept.session) await clearSession(r.project.dir, e, label);
+ return Response.json({ ok: true, takes: kept.takes, picked: kept.picked, notes: kept.notes, disclosure: kept.disclosure, entry: kept.entry, token: kept.token }, { headers: noStore });
+ }
+ const kept = await finishSession(r.project, e, { label, manifest: r.manifest as Record<string, unknown>, script, spans });
+ await discardPreview(r.project.dir, e, label);
+ return Response.json({ ok: true, takes: [{ step: "recorded", file: kept.take.file }], picked: kept.take.file, notes: [], entry: kept.result.entry, token: kept.result.token }, { headers: noStore });
+ }
+ if (body.op === "again") {
+ await discardPreview(r.project.dir, e, label);
+ const session = body.n === undefined || body.n === null ? await readSession(r.project.dir, e, label) : await discardPart(r.project.dir, e, Number(body.n), label);
+ return Response.json({ ok: true, session }, { headers: noStore });
+ }
+ if (body.op === "discard-preview") {
+ await discardPreview(r.project.dir, e, label);
+ return Response.json({ ok: true }, { headers: noStore });
+ }
+ if (body.op === "stock") {
+ // The character's stock voice reading the line -- what the redaction, the slur filter and the lexicon leave of it.
+ const who = await whoOf(r.project.dir, e);
+ const ref = voiceRefOf(who.synthetic?.voice ?? "") as { engine: string | null; voice: string } | null;
+ const speed = ref?.engine && ref.engine !== "orpheus" && typeof who.synthetic?.speed === "number" ? who.synthetic.speed : null;
+ if (!ref?.engine) return Response.json({ error: "this post's character has no synthetic voice to hear" }, { status: 400 });
+ const text = String(body.text ?? "").trim();
+ if (!text) return Response.json({ error: "no line to read" }, { status: 400 });
+ const red = await projectRedaction(r.project.dir, r.manifest as Record<string, unknown>);
+ const spoken = String(spokenRead(text, e, red, { voice: red?.slurs?.voice === "beep" ? "skip" : undefined }).text);
+ const key = partKey(ref.engine, ref.voice, spoken, speed) as string;
+ const abs = path.join(r.project.dir, ...stockRel(key).split("/"));
+ if ((await stat(abs).catch(() => null))?.isFile()) return Response.json({ ok: true, cached: true, file: stockRel(key), voice: who.synthetic?.voice }, { headers: noStore });
+ if (body.cachedOnly === true) return Response.json({ ok: true, cached: false, voice: who.synthetic?.voice }, { headers: noStore });
+ await mkdir(path.dirname(abs), { recursive: true });
+ // The job writes BESIDE the cache; its poll renames it in (a half-written read is never a cached part).
+ const jobId = await startEditorJob("/api/ops/tts", { text: spoken, engine: ref.engine, voice: ref.voice, out: `${abs}.pending.tmp.wav`, ...(speed ? { speed } : {}) });
+ return Response.json({ ok: true, cached: false, jobId, key, voice: who.synthetic?.voice }, { headers: noStore });
+ }
+ return Response.json({ error: "op is discard, finish, prepare, filter, cancel, keep, again, discard-preview or stock" }, { status: 400 });
} catch (err) {
return fail(err);
}
}
+
+/** A body's `spans` as cut marks per part: `[{from, to} | null]`, or null when it gives none. */
+function spansOf(v: unknown): Array<{ from: number; to: number } | null> | null {
+ if (!Array.isArray(v) || !v.length || v.length > 200) return null;
+ const out = v.map((x) => {
+ const sp = x as { from?: unknown; to?: unknown } | null;
+ return sp && typeof sp.from === "number" && typeof sp.to === "number" && Number.isFinite(sp.from) && Number.isFinite(sp.to) && sp.to - sp.from >= 0.2 && sp.from >= 0 ? { from: Math.round(sp.from * 1000) / 1000, to: Math.round(sp.to * 1000) / 1000 } : null;
+ });
+ return out.some(Boolean) ? out : null;
+}
diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts
@@ -21,6 +21,9 @@ import { fitPostItem } from "@/lib/report/postFit.mjs";
import { itemReadVoice } from "@/lib/report/readVoice.mjs";
import { projectRedaction } from "@/lib/report/postRedaction.mjs";
import { spokenRead } from "umtool-report-to-video/post-redact";
+import { recordedPresetOf, shownNameOf } from "umtool-report-to-video/cast";
+import { readLayers, recordedTrimFor } from "@/lib/report/characterLayers.mjs";
+import { convertAskOf, derivePitchOf, deriveRefusalOf, stepPitchOf } from "@/lib/report/derivePitch.mjs";
export const dynamic = "force-dynamic";
@@ -41,10 +44,18 @@ const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => (red?.
// POST {project, op: "take", id, note?, voice?, engine?, speed?, script?}
// a new take asked of the EDITOR's tts op (a job)
// POST {project, op: "fit", id, linger?} the attachment's best part for the read (posts fit)
-// POST {project, op: "derive", id, from, op2: enhance|convert, engine?, voice?}
-// a NEW take made from take `from` by the editor's voice op
-// (a job; kept by GET ?job&derive=<from>); `installed: false`
-// when the editor has no engine for it
+// GET ?project&id&convert=1 what a convert of this post defaults to: its author's character in
+// the cast (else the narrator) and that character's convert
+// target -- {character, convert: {engine, voice, pitch?, semitones?}}
+// POST {project, op: "derive", id, from, op2: enhance|convert, engine?, voice?, pitch?, semitones?, as?}
+// a NEW take made from take `from` by the editor's voice op; a
+// convert's engine, voice, pitch and semitones default to the
+// CHARACTER's recorded preset (`as`, else the post's), and with
+// none and no voice it is refused -- the answer names what was asked
+// (a job; kept by GET ?job&derive=<from>[&pitch&semitones]);
+// `installed: false` when the editor has no engine for it. A
+// convert's `pitch` (target | source | contour) and `semitones`
+// are the pitch the read lands on (lib/report/derivePitch.mjs)
// POST {project, op: "delete", id, take} a take out of the list, its file to .trash/ (soft)
// POST {project, op: "reread", id, without?, dropParts?, dropUrls?} the picked take RE-JOINED without a piece
// POST {project, op: "reread", id, tempo: "4-16=1.35", stretch?} its parts RE-TIMED (no TTS); {…, yell: true, yellGain?, yellStyle?}: its caps raised
@@ -77,6 +88,17 @@ export async function GET(request: Request) {
const render = (m.render ?? {}) as Record<string, unknown>;
const id = q.get("id");
const job = q.get("job");
+ if (id && !job && q.get("convert") !== null) {
+ // What a convert of this post defaults to (`posts narrate --recording`'s rule: the author's character, else the narrator).
+ const e = postsOf(m).find((x) => x.id === id);
+ if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 });
+ // The chain a recording asks (cast.mjs characterForRead): the item's own character, this video's for the author, the
+ // cast's, the narrator -- and its recorded preset (what the record page will read: the direction, clean, trim).
+ const who = (await readLayers(r.project.dir)).characterForRead(e);
+ const c = who?.character ?? null;
+ const preset = c ? recordedPresetOf(c) : null;
+ return Response.json({ character: c ? { id: c.id, name: shownNameOf(c), layer: who.layer } : null, convert: preset ? preset.convert : null, ...(preset ? { recorded: { enhance: preset.enhance, trim: preset.trim, direction: preset.direction } } : {}) }, { headers: noStore });
+ }
if (id && job) {
// A GET that WRITES the manifest (a job followed to done): the proxy passes reads, so an <img> on another site
// could ask it; refused cross-site here (lib/report/sameOrigin.mjs).
@@ -109,13 +131,16 @@ export async function GET(request: Request) {
if (!from) return Response.json({ state: "failed", error: `no take ${derive}` }, { headers: noStore });
const op = String(q.get("op") ?? "");
// The editor's defaults, when the ask named none (its `@@voice-result` line).
- const vr = resultLine<{ engine?: string; voice?: string }>(st.tail, "@@voice-result ") ?? {};
+ const vr = resultLine<{ engine?: string; voice?: string; pitch?: string; semitones?: number }>(st.tail, "@@voice-result ") ?? {};
+ // The pitch it landed on, as the editor ran it (else as it was asked); the target's own is not recorded.
+ const asked = derivePitchOf({ pitch: q.get("pitch"), semitones: q.get("semitones") });
+ const pitched = op === "convert" ? stepPitchOf(asked.ok ? asked.value : {}, vr) : {};
const engine = q.get("engine") ?? vr.engine ?? null;
const voice = op === "convert" ? (q.get("voice") ?? vr.voice ?? null) : null;
const partsRel = rel.replace(/\.wav$/, ".parts");
const derived = {
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 } : {}), ranAt: new Date().toISOString(), job }],
+ 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 } : {}),
...(Array.isArray(from.parts) ? { parts: from.parts.map((p) => ({ ...p, file: `${partsRel}/p${String(p.n).padStart(2, "0")}.wav` })) } : {}),
};
@@ -220,7 +245,8 @@ async function postHere(request: Request) {
const k = postNarrationKnobs(e, (m.render ?? {}) as Record<string, unknown>);
const script = String(body.script ?? e.narration?.script ?? "").trim();
if (!script) return Response.json({ error: `${id} has no script to read` }, { status: 400 });
- // The voice: the one asked for, the project's voice map, the CAST, the narrator's -- a single read's rule (readVoice.mjs).
+ // The voice: the one asked for, the item's own character, the project's characters and voice map, the CAST, the
+ // narrator's -- a single read's rule (readVoice.mjs).
const said = await itemReadVoice(r.project, e, {
render: (m.render ?? {}) as Record<string, unknown>,
engine: typeof body.engine === "string" && body.engine ? body.engine : null,
@@ -232,7 +258,10 @@ async function postHere(request: Request) {
const dir = path.join(r.project.dir, ...takesDirOf(pid).split("/"));
await mkdir(dir, { recursive: true });
const rel = takeFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), engine, voice);
- const speed = body.speed === undefined || body.speed === null || engine === "orpheus" ? undefined : Number(body.speed);
+ // Its speed: the one asked for, else the item's own (`narration.speed`), else its character's (the synthetic
+ // preset's that answered for the voice) -- makeTake's order.
+ const askedSpeed = body.speed === undefined || body.speed === null ? (e.narration as { speed?: number } | undefined)?.speed ?? (said as { speed?: number }).speed : Number(body.speed);
+ const speed = askedSpeed === undefined || askedSpeed === null || engine === "orpheus" ? undefined : Number(askedSpeed);
// What the voice SAYS: the script with every redacted term left out (post-redact.mjs), each slur as the cut's
// filter has it (post-slurs.mjs) and the project's pronunciation lexicon applied (post-say.mjs); the script is kept as written. The bench cannot word-time a take as it is made,
// so a beep falls back to skip here (the CLI's --take times it and beeps).
@@ -248,8 +277,24 @@ async function postHere(request: Request) {
if (!t) return Response.json({ error: `${id} has no take ${from + 1}` }, { status: 404 });
const op = String(body.op2 ?? "");
if (!(POST_DERIVE_OPS as readonly string[]).includes(op)) return Response.json({ error: `op2 is one of ${POST_DERIVE_OPS.join(", ")}` }, { status: 400 });
- const engine = body.engine ? String(body.engine) : null;
- const voice = body.voice ? String(body.voice) : null;
+ let engine = body.engine ? String(body.engine) : null;
+ let voice = body.voice ? String(body.voice) : null;
+ // A convert's pitch (target | source | contour) and semitones, checked here; the editor refuses what its engine cannot do.
+ const checked = derivePitchOf({ pitch: body.pitch, semitones: body.semitones }, op);
+ if (!checked.ok) return Response.json({ error: checked.error }, { status: 400 });
+ let pitch: { pitch?: string; semitones?: number } = checked.value ?? {};
+ if (op === "convert") {
+ // A convert is the CHARACTER's (the CLI's rule, derivePitch.mjs convertAskOf): what the body does not name is
+ // its recorded preset's -- engine, stock voice, pitch, semitones -- and with no character and no voice it is
+ // refused: the editor's default voice is never asked for.
+ const who = (await readLayers(r.project.dir)).characterForRead(e, typeof body.as === "string" && body.as ? body.as : null);
+ if (typeof body.as === "string" && body.as && !who?.character) return Response.json({ error: `no such character: ${body.as}` }, { status: 400 });
+ const d = convertAskOf({ engine, voice, ...pitch }, who?.character ? recordedPresetOf(who.character).convert : null, who?.character?.id ?? null);
+ if (!d.ok) return Response.json({ error: `${d.error}: name a stock voice here, or give the character one on the Voices page` }, { status: 400 });
+ engine = d.value.engine ?? null;
+ voice = d.value.voice;
+ pitch = { ...(d.value.pitch !== undefined ? { pitch: d.value.pitch } : {}), ...(d.value.semitones !== undefined ? { semitones: d.value.semitones } : {}) };
+ }
const pid = postIdOf(e);
const dir = path.join(r.project.dir, ...takesDirOf(pid).split("/"));
await mkdir(dir, { recursive: true });
@@ -261,15 +306,15 @@ async function postHere(request: Request) {
: null;
try {
// `voice` is the convert op's stock target; enhance takes none.
- const jobId = await startJob(POST_DERIVE_ROUTES[op as keyof typeof POST_DERIVE_ROUTES], { file: abs(t.file), out: abs(rel), ...(engine ? { engine } : {}), ...(voice && op === "convert" ? { voice } : {}), ...(parts ? { parts } : {}) });
- return Response.json({ ok: true, jobId, file: rel, from, op: op, engine, voice }, { headers: noStore });
+ const jobId = await startJob(POST_DERIVE_ROUTES[op as keyof typeof POST_DERIVE_ROUTES], { file: abs(t.file), out: abs(rel), ...(engine ? { engine } : {}), ...(voice && op === "convert" ? { voice } : {}), ...pitch, ...(parts ? { parts } : {}) });
+ return Response.json({ ok: true, jobId, file: rel, from, op: op, engine, voice, ...pitch }, { headers: noStore });
} catch (err) {
const status = (err as { status?: number }).status ?? 502;
const msg = err instanceof Error ? err.message : String(err);
// The editor has no engine for it (an older editor has no route; a newer one names the setup to run): say so, plainly, with its words.
- if (status === 404 || /not installed|no engine|unknown|not found|404/i.test(msg)) {
- return Response.json({ ok: false, installed: false, error: `the editor has no ${op} engine installed (not installed: ${msg.replace(/^the editor refused it: /, "")})` }, { status: 200, headers: noStore });
- }
+ // A missing optional model (`… --with f0`) is passed through in the editor's words (derivePitch.mjs deriveRefusalOf).
+ const refusal = deriveRefusalOf(op, status, msg);
+ if (refusal) return Response.json({ ok: false, ...refusal }, { status: 200, headers: noStore });
return Response.json({ error: msg }, { status });
}
}
@@ -372,7 +417,8 @@ async function record(request: Request) {
}
const script = form.get("script");
const note = form.get("note");
- const kept = await keepRecording(r.project, e, parts, { label, manifest: m, note: note ? String(note) : null, script: script === null ? null : String(script) });
+ // Its character's recorded preset says whether its edges are trimmed, and the room kept (characterLayers.mjs).
+ const kept = await keepRecording(r.project, e, parts, { label, manifest: m, note: note ? String(note) : null, script: script === null ? null : String(script), trim: await recordedTrimFor(r.project.dir, e) });
return Response.json({ ok: true, take: kept.take, gain: kept.gain, target: kept.target, token: kept.result.token, entry: kept.result.entry }, { headers: noStore });
} catch (err) {
return fail(err);
diff --git a/umtool/app/api/report/voices/route.ts b/umtool/app/api/report/voices/route.ts
@@ -32,7 +32,15 @@ export const dynamic = "force-dynamic";
// POST { project, op: "use", who, voice, scope: "project" | "cast" } umtool cast use <p> <who> <voice> [--everywhere]
// POST { project, op: "reread", who } QUEUED: one `posts narrate … --take [--thread …]` step per item
// whose picked read says them in another voice (the argv built here)
-// POST { project, op: "cast-rm", id } | { op: "cast-undo" } | { op: "cast-set", id, convertEngine?, narrator? }
+// POST { project, op: "cast-rm", id } | { op: "cast-undo" } | { op: "cast-set", id, convertEngine?, convertPitch?, convertSemitones?, narrator?, …the preset fields }
+// POST { project, op: "character-set", scope: "cast" | "project", id, name?, voice?, speed?, convertEngine?, convertVoice?, convertPitch?,
+// convertSemitones?, enhance?, trim?, trimPad?, direction?, handles?, anonymous?, shown? } a character's PRESETS (umtool cast set /
+// cast project <p> set): "" or null for a field puts its default back
+// POST { project, op: "character-add", id, name?, voice?, handles?, anonymous?, shown? } one of THIS VIDEO's own (cast project <p> add)
+// POST { project, op: "character-rm", id } | { op: "characters-undo" } cast project <p> rm | undo
+// POST { project, op: "character-pool", id } "Add to the pool": cast project <p> pool <id>
+// POST { project, op: "character-keep", who, anonymous? } "Keep in this video only": cast project <p> keep <character|@handle>
+// POST { project, op: "item-character", item, character: <id> | null } umtool posts character <p> <item> <id> | --clear
// POST multipart { project, op: "recording", item, as?, clean?, convert?, file } a JOB: posts narrate <p> <item>
// --recording <file> (kept, cleaned, converted to a STOCK voice)
const headers = { "cache-control": "no-store" };
@@ -50,6 +58,51 @@ async function cli(args: string[]) {
return { code, json, error: code === 0 ? null : (json?.error as string | undefined) ?? (err.join("\n") || "refused") };
}
+/** `umtool posts character …`, run here (its JSON, or its refusal in its words). */
+async function postsCli(args: string[]) {
+ const { postsCommand } = await import("@/lib/report/postsCli.mjs");
+ const said: string[] = [];
+ const errs: string[] = [];
+ const code = await postsCommand([...args, "--json"], { root: REPORTS_ROOT, out: (x: string) => said.push(x), err: (x: string) => errs.push(x) });
+ let json: Record<string, unknown> | null = null;
+ try {
+ json = JSON.parse(said.join("\n") || "null");
+ } catch {
+ json = null;
+ }
+ return { code, json, error: code === 0 ? null : (errs.join("\n") || said.join("\n") || "refused").replace(/^umtool posts: /, "") };
+}
+
+/**
+ * A character's preset fields as the CLI's flags (castCli.mjs fieldsOf: it refuses what makes no sense). A field
+ * that is "" or null puts its default back; one that is absent is left as it is.
+ */
+function presetArgs(b: Record<string, unknown>): string[] {
+ const args: string[] = [];
+ const has = (k: string) => b[k] !== undefined;
+ const blank = (k: string) => b[k] === null || b[k] === "";
+ const val = (k: string) => String(b[k]).trim();
+ if (has("name") && !blank("name")) args.push("--name", val("name"));
+ if (has("handles")) args.push("--handles", (Array.isArray(b.handles) ? b.handles.map(String) : String(b.handles ?? "").split(",")).map((h) => h.trim()).filter(Boolean).join(","));
+ if (has("voice")) args.push(...(blank("voice") ? ["--no-voice"] : ["--voice", val("voice")]));
+ if (has("speed")) args.push(...(blank("speed") ? ["--no-speed"] : ["--speed", val("speed")]));
+ if (has("convertEngine")) args.push("--convert-engine", blank("convertEngine") ? "default" : val("convertEngine"));
+ if (has("convertVoice")) args.push("--convert-voice", blank("convertVoice") ? "default" : val("convertVoice"));
+ if (has("convertPitch")) args.push("--convert-pitch", blank("convertPitch") ? "default" : val("convertPitch"));
+ if (has("convertSemitones")) args.push("--convert-semitones", blank("convertSemitones") ? "0" : val("convertSemitones"));
+ const onOff = (k: string) => (blank(k) ? "default" : b[k] === true || b[k] === "on" ? "on" : b[k] === false || b[k] === "off" ? "off" : val(k));
+ if (has("enhance")) args.push("--enhance", onOff("enhance"));
+ if (has("trim")) args.push("--trim", onOff("trim"));
+ if (has("trimPad")) args.push("--trim-pad", blank("trimPad") ? "default" : val("trimPad"));
+ if (has("direction")) args.push("--direction", blank("direction") ? "" : val("direction"));
+ if (b.anonymous === true || b.anonymous === "on") args.push("--anonymous");
+ if (b.anonymous === false || b.anonymous === "off") args.push("--no-anonymous");
+ if (has("shown") && !blank("shown")) args.push("--shown", val("shown"));
+ if (b.narrator === true || b.narrator === "on") args.push("--narrator");
+ if (b.narrator === false || b.narrator === "off") args.push("--no-narrator");
+ return args;
+}
+
/** The checkout's heavy-slot CLI, when this umtool sits in the checkout (speakerCheck.mjs's rule). */
function queueLockScript() {
const file = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "..", "scripts", "queue-lock.mjs");
@@ -166,14 +219,47 @@ export async function POST(request: Request) {
const r = await cli(["undo"]);
return Response.json(r.code === 0 ? r.json : { error: r.error }, { status: r.code === 0 ? 200 : 400, headers });
}
+ const answer = (r: { code: number; json: Record<string, unknown> | null; error: string | null }) => Response.json(r.code === 0 ? r.json : { error: r.error }, { status: r.code === 0 ? 200 : 400, headers });
+ const idOk = (v: string) => /^[a-z0-9][a-z0-9_-]{0,47}$/.test(v);
if (op === "cast-set") {
const args = ["set", s("id")];
if (s("convertEngine")) args.push("--convert-engine", s("convertEngine"));
+ // The pitch a converted read lands on (castCli.mjs refuses what makes no sense).
+ if (s("convertPitch")) args.push("--convert-pitch", s("convertPitch"));
+ if (typeof b.convertSemitones === "number" || s("convertSemitones")) args.push("--convert-semitones", String(b.convertSemitones ?? s("convertSemitones")));
if (b.narrator === true || s("narrator") === "on") args.push("--narrator");
if (b.narrator === false || s("narrator") === "off") args.push("--no-narrator");
if (s("name")) args.push("--name", s("name"));
- const r = await cli(args);
- return Response.json(r.code === 0 ? r.json : { error: r.error }, { status: r.code === 0 ? 200 : 400, headers });
+ return answer(await cli(args));
+ }
+ // A CHARACTER's PRESETS, the cast's or this video's own -- each the CLI's own command (castCli.mjs).
+ if (op === "character-set" || op === "character-add") {
+ const id = s("id");
+ if (!idOk(id)) return Response.json({ error: "a character's id is lower case letters, digits, - and _" }, { status: 400 });
+ const own = op === "character-add" || s("scope") === "project";
+ const head = own ? ["project", project.id, op === "character-add" ? "add" : "set", id] : ["set", id];
+ return answer(await cli([...head, ...presetArgs(b)]));
+ }
+ if (op === "character-rm") {
+ if (!idOk(s("id"))) return Response.json({ error: "which character?" }, { status: 400 });
+ return answer(await cli(["project", project.id, "rm", s("id")]));
+ }
+ if (op === "characters-undo") return answer(await cli(["project", project.id, "undo"]));
+ if (op === "character-pool") {
+ if (!idOk(s("id"))) return Response.json({ error: "which character?" }, { status: 400 });
+ return answer(await cli(["project", project.id, "pool", s("id")]));
+ }
+ if (op === "character-keep") {
+ const who = s("who");
+ if (!/^@?[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/.test(who)) return Response.json({ error: "keep takes a cast character's id, or an author (@handle)" }, { status: 400 });
+ return answer(await cli(["project", project.id, "keep", who, ...(b.anonymous === true ? ["--anonymous"] : []), ...(s("shown") ? ["--shown", s("shown")] : [])]));
+ }
+ if (op === "item-character") {
+ const item = s("item");
+ if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(item)) return Response.json({ error: "which post item?" }, { status: 400 });
+ const id = s("character");
+ if (id && !idOk(id)) return Response.json({ error: "which character?" }, { status: 400 });
+ return answer(await postsCli(["character", project.id, item, id || "--clear"]));
}
if (op === "recording") {
const file = form?.get("file");
@@ -192,7 +278,7 @@ export async function POST(request: Request) {
const job = startJob(`cast-recording ${project.id}`, [{ label: `${item}: the recording kept, cleaned, converted`, argv, cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, timeoutMs: 45 * 60 * 1000 }], { project: project.id });
return Response.json({ ok: true, job: jobView(job), file: path.relative(project.dir, abs) }, { headers });
}
- return Response.json({ error: "op must be audition, use, reread, cast-rm, cast-undo, cast-set or recording" }, { status: 400 });
+ return Response.json({ error: "op must be audition, use, reread, cast-rm, cast-undo, cast-set, character-set, character-add, character-rm, characters-undo, character-pool, character-keep, item-character or recording" }, { status: 400 });
} catch (e) {
const status = (e as { status?: number }).status ?? 400;
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
diff --git a/umtool/app/api/research/archives/route.ts b/umtool/app/api/research/archives/route.ts
@@ -0,0 +1,21 @@
+import { askEditor } from "@/lib/articles/generation";
+import { fail, ok } from "../_respond";
+
+export const dynamic = "force-dynamic";
+
+// CONNECT AN ARCHIVE from the Source chip (demo epic D1): forwarded to the
+// editor's `archives` action, which reads the archive's corpus.json and — unless
+// `dryRun` — saves it in settings.remoteArchives (the one writer). The chip then
+// lists it (lib/research/sources.ts reads the same list).
+//
+// POST { origin, dryRun? } -> the editor's { ok, archive, probe, already }
+export async function POST(request: Request) {
+ try {
+ const body = (await request.json().catch(() => null)) as { origin?: unknown; dryRun?: unknown } | null;
+ if (!body || typeof body.origin !== "string" || !body.origin.trim()) return Response.json({ error: "send { origin }: the archive's address" }, { status: 400 });
+ const answer = await askEditor("/api/ops/archives", { method: "POST", body: { connect: body.origin.trim(), ...(body.dryRun === true ? { dryRun: true } : {}) } });
+ return ok(answer);
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -46,11 +46,15 @@
// umtool build <project> [--preset preview|fast|final] [--only ID] [--dry]
// [--run [--url URL] [--replace]] run it as the app's job, follow it, Ctrl-C cancels
// umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL]
-// [--draft-all [--model M] [--deck]]
+// [--draft-all [--model M] [--deck]] [--stop-before-render] [--allow-whole-recording]
// an iteration's pipeline: current, windows, prepare, posts, manifest,
// voices, video, podcast, attach, dedupe (resumes at the first step not done);
-// --draft-all is Draft everything: the drafts between manifest and the fast build;
-// --deck adds the on-screen deck to a cut with none before the flips
+// --draft-all is Draft everything: the drafts between manifest and the fast build,
+// the cut's windows after the cut is drafted (cut-windows);
+// --deck adds the on-screen deck to a cut with none before the flips;
+// --stop-before-render ends it before the voices (nothing voiced or built);
+// --allow-whole-recording lets a remote-only channel's windows download
+// their whole recording (Rumble), which is refused with its size otherwise
// umtool index [--rebuild] [--prune] [--since MS] [--json]
// umtool new <slug> | <folder>/<slug> [--folder <folder>] [--kind report-video] [--from <report.md>|<share URL>|<channel>/<id>]
// [--site-origin URL] [--seed chapters|frames [--target S]] [--brand archilyzer-media]
@@ -1426,7 +1430,7 @@ async function cmdChain() {
const article = positional[0];
const n = Number(positional[1]);
if (!article || !Number.isInteger(n) || n < 1) {
- die("usage: umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]]");
+ die("usage: umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]] [--stop-before-render] [--allow-whole-recording]");
}
const draftAll = has("--draft-all");
if (val("--model") && !draftAll) die("--model is Draft everything's (--draft-all): the model its drafts run on");
@@ -1444,12 +1448,14 @@ async function cmdChain() {
...(val("--site-origin") ? { siteOrigin: val("--site-origin") } : {}),
final: has("--final"),
...(draftAll ? { mode: "draft-all", ...(val("--model") ? { model: val("--model") } : {}), ...(deck ? { deck: true } : {}) } : {}),
+ ...(has("--stop-before-render") ? { stopBeforeRender: true } : {}),
+ ...(has("--allow-whole-recording") ? { allowWholeRecording: true } : {}),
});
} catch (err) {
die(err.message);
}
const { start, steps } = plan;
- const again = `umtool chain ${article} ${n}${draftAll ? ` --draft-all${deck ? " --deck" : ""}` : ""}`;
+ const again = `umtool chain ${article} ${n}${draftAll ? ` --draft-all${deck ? " --deck" : ""}` : ""}${has("--stop-before-render") ? " --stop-before-render" : ""}`;
if (json && has("--dry")) return out({ article, n, start, steps });
if (steps.length === 0) {
console.log(`${article} i${n}: every step of the ${draftAll ? "Draft everything chain" : "chain"} is done (--from <step> runs one again)`);
diff --git a/umtool/components/articles/ChainPanel.tsx b/umtool/components/articles/ChainPanel.tsx
@@ -5,6 +5,7 @@ import { Button } from "@/components/ui/button";
import { JobProgress, type JobStep, type JobStepState } from "@/components/ui/job-progress";
import type { ChainMode, ChainView } from "@/lib/articles/generation";
import { spendFromLog } from "@/lib/running.mjs";
+import { WHOLE_RECORDING_REFUSED } from "yt-dlp-transcript-common/lib/remoteArchives";
// MAKE THE VIDEO for one iteration (release 27 S8): the pipeline chain's ten
// steps (lib/report/chain.mjs) as a umtool job — what each step last did, where
@@ -36,6 +37,8 @@ export default function ChainPanel({
const [from, setFrom] = useState<string>("");
const [error, setError] = useState("");
const [sending, setSending] = useState(false);
+ // Stop before render (demo epic D1): this run ends before the voices.
+ const [stopBefore, setStopBefore] = useState(false);
const load = useCallback(async () => {
const r = await fetch(`/api/articles/chain?article=${encodeURIComponent(article)}&n=${n}${draftAll ? `&mode=draft-all${deck ? "&deck=1" : ""}` : ""}`, { cache: "no-store" });
@@ -58,13 +61,21 @@ export default function ChainPanel({
return () => clearInterval(t);
}, [running, load]);
- const start = useCallback(async () => {
+ const start = useCallback(async (extra: { from?: string; allowWholeRecording?: boolean } = {}) => {
setError("");
setSending(true);
try {
+ const at = extra.from ?? from;
const r = await fetch("/api/articles/chain", {
method: "POST",
- body: JSON.stringify({ article, n, ...(from ? { from } : {}), ...(draftAll ? { draftAll: true, ...(model ? { model } : {}), ...(deck ? { deck: true } : {}) } : {}) }),
+ body: JSON.stringify({
+ article,
+ n,
+ ...(at ? { from: at } : {}),
+ ...(draftAll ? { draftAll: true, ...(model ? { model } : {}), ...(deck ? { deck: true } : {}) } : {}),
+ ...(stopBefore ? { stopBeforeRender: true } : {}),
+ ...(extra.allowWholeRecording ? { allowWholeRecording: true } : {}),
+ }),
});
const b = await r.json();
if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`);
@@ -75,7 +86,7 @@ export default function ChainPanel({
} finally {
setSending(false);
}
- }, [article, n, from, draftAll, model, deck, load]);
+ }, [article, n, from, draftAll, model, deck, stopBefore, load]);
useEffect(() => {
if (!autoStart || started.current) return;
@@ -102,6 +113,9 @@ export default function ChainPanel({
attrs: { "data-chain-step": s.name, "data-step-status": s.status },
}));
const job = chain?.job ?? null;
+ // A windows step a remote-only channel's whole recording refused, with its
+ // size (demo epic D1): one press fetches them and goes on from there.
+ const wholeRefused = chain?.steps.find((s) => s.status === "failed" && (s.detail ?? "").startsWith(WHOLE_RECORDING_REFUSED)) ?? null;
const done = job ? chain!.steps.filter((s) => s.status === "done" || s.status === "skipped" || s.status === "failed").length : 0;
return (
<section
@@ -143,6 +157,14 @@ export default function ChainPanel({
)}
</JobProgress>
)}
+ {!running && wholeRefused && (
+ <div className="flex flex-wrap items-center gap-2 rounded-[3px] border border-seam-2 p-2" data-whole-recording-refused={wholeRefused.name}>
+ <p className="min-w-0 flex-1 text-text-2">{wholeRefused.detail}</p>
+ <Button size="sm" variant="outline" disabled={sending} onClick={() => void start({ from: wholeRefused.name, allowWholeRecording: true })}>
+ Fetch the whole recordings
+ </Button>
+ </div>
+ )}
{!running && (
<div className="flex flex-wrap items-center gap-2">
<label className="flex items-center gap-1">
@@ -161,6 +183,10 @@ export default function ChainPanel({
))}
</select>
</label>
+ <label className="flex items-center gap-1 text-muted" title="end this run before the voices: nothing voiced or built; the next run resumes there">
+ <input type="checkbox" aria-label={`${label} stop before render`} checked={stopBefore} onChange={(e) => setStopBefore(e.target.checked)} />
+ stop before render
+ </label>
<Button size="sm" variant="outline" disabled={sending || (!from && !chain?.resumeAt)} onClick={() => void start()}>
{draftAll ? "Run Draft everything" : "Run the chain"}
</Button>
diff --git a/umtool/components/articles/NewArticleForm.tsx b/umtool/components/articles/NewArticleForm.tsx
@@ -43,19 +43,23 @@ const AUTONOMY_SAYS: Record<Autonomy, string> = {
};
// Exported for Create's recurring form (R5): the same picker, the same channels.
-export function ChannelPicker({ value, onChange }: { value: string[]; onChange: (v: string[]) => void }) {
+// `source` (demo epic D1): a published archive's handle lists ITS channels
+// (its corpus.json); none, the editor's own.
+export function ChannelPicker({ value, onChange, source = "" }: { value: string[]; onChange: (v: string[]) => void; source?: string }) {
const [all, setAll] = useState<EditorChannel[] | null>(null);
const [error, setError] = useState("");
const [q, setQ] = useState("");
useEffect(() => {
- fetch("/api/articles/channels", { cache: "no-store" })
+ setAll(null);
+ setError("");
+ fetch(source ? `/api/articles/channels?source=${encodeURIComponent(source)}` : "/api/articles/channels", { cache: "no-store" })
.then(async (r) => {
const b = await r.json();
if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`);
setAll(b.channels);
})
.catch((e) => setError((e as Error).message));
- }, []);
+ }, [source]);
const shown = useMemo(() => {
const k = q.trim().toLowerCase();
return (all ?? []).filter((c) => !k || c.slug.includes(k) || c.name.toLowerCase().includes(k)).slice(0, 80);
@@ -97,7 +101,7 @@ export function ChannelPicker({ value, onChange }: { value: string[]; onChange:
<button
type="button"
aria-pressed={value.includes(c.slug)}
- title={`${c.slug}${c.sites.length ? ` · on ${c.sites.join(", ")}` : " · on no site"}`}
+ title={`${c.slug}${source ? "" : c.sites.length ? ` · on ${c.sites.join(", ")}` : " · on no site"}`}
className={`rounded border px-1.5 py-0.5 text-[12px] hover:bg-[var(--color-panel-2)] ${value.includes(c.slug) ? "border-[var(--color-muted)] bg-[var(--color-panel-2)] text-[var(--color-text)]" : "border-[var(--color-line)]"}`}
onClick={() => toggle(c.slug)}
>
@@ -157,6 +161,21 @@ export default function NewArticleForm({
const [id, setId] = useState("");
const [question, setQuestion] = useState("");
const [channels, setChannels] = useState<string[]>([]);
+ // The corpus the sweep reads and cites (demo epic D1): "" the editor's own,
+ // else a published archive's handle. Preselected when the editor holds no
+ // channel and an archive is connected (/api/articles/sources).
+ const [sources, setSources] = useState<{ handle: string; label: string; detail?: string }[] | null>(null);
+ const [source, setSource] = useState("");
+ useEffect(() => {
+ fetch("/api/articles/sources", { cache: "no-store" })
+ .then(async (r) => {
+ const b = await r.json();
+ if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`);
+ setSources(b.sources);
+ if (b.preselect) setSource(b.preselect);
+ })
+ .catch(() => setSources([]));
+ }, []);
const [from, setFrom] = useState("");
const [to, setTo] = useState("");
const [title, setTitle] = useState("");
@@ -205,6 +224,7 @@ export default function NewArticleForm({
article: id,
question,
...(channels.length ? { channels } : {}),
+ ...(source ? { source } : {}),
model,
...(begin === "sweep" ? extractorBody(model, extractor, policy?.generation.models.extractor) : {}),
...(from ? { from } : {}),
@@ -288,10 +308,33 @@ export default function NewArticleForm({
</div>
</fieldset>
) : (
- <div className="flex flex-col gap-1">
- <span className="micro">channels{begin === "research" ? " (optional)" : ""}</span>
- <ChannelPicker value={channels} onChange={setChannels} />
- </div>
+ <>
+ {sources && sources.length > 1 && (
+ <label className="flex flex-col gap-1">
+ <span className="micro">source</span>
+ <select
+ className={`${field} max-w-md`}
+ aria-label="source"
+ value={source}
+ onChange={(e) => {
+ setSource(e.target.value);
+ setChannels([]);
+ }}
+ >
+ {sources.map((s) => (
+ <option key={s.handle || "local"} value={s.handle}>
+ {s.label}
+ {s.detail ? ` · ${s.detail}` : ""}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+ <div className="flex flex-col gap-1">
+ <span className="micro">channels{begin === "research" ? " (optional)" : ""}</span>
+ <ChannelPicker value={channels} onChange={setChannels} source={source} />
+ </div>
+ </>
)}
<div className="flex flex-wrap items-end gap-4">
diff --git a/umtool/components/create/forms.tsx b/umtool/components/create/forms.tsx
@@ -214,6 +214,7 @@ export function ArticleVideoForm({
const [chain, setChain] = useState<ChainView | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
+ const [stopBefore, setStopBefore] = useState(false);
// The article's iterations: those with a report (done) are what a chain runs over.
useEffect(() => {
@@ -255,10 +256,17 @@ export function ArticleVideoForm({
const start = async () => {
if (!article || n === null) return;
+ // stopBefore (demo epic D1): the run ends before the voices.
setBusy(true);
setError(null);
try {
- await json(await fetch("/api/articles/chain", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ article, n }) }));
+ await json(
+ await fetch("/api/articles/chain", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ article, n, ...(stopBefore ? { stopBeforeRender: true } : {}) }),
+ }),
+ );
router.push(articleHref({ site: "articles", id: article }, { tab: "iterations" }));
} catch (e) {
setError((e as Error).message);
@@ -303,6 +311,10 @@ export function ArticleVideoForm({
))}
</Select>
</Field>
+ <label className="flex items-center gap-1 self-center text-[12px] text-text-2" title="end the run before the voices: nothing voiced or built; the next run resumes there">
+ <input type="checkbox" aria-label="stop before render" checked={stopBefore} onChange={(e) => setStopBefore(e.target.checked)} />
+ stop before render
+ </label>
<Actions error={error}>
<Button type="submit" variant="go" disabled={busy || n === null || !chain || chain.resumeAt === null || chain.job?.state === "running"}>
{busy ? "Starting…" : "Make the video"}
diff --git a/umtool/components/projects/CharacterPresets.tsx b/umtool/components/projects/CharacterPresets.tsx
@@ -0,0 +1,379 @@
+"use client";
+
+import { useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+
+// ---------------------------------------------------------------------------
+// A CHARACTER IS A PRESET (components/projects/VoicesPanel.tsx; /api/report/voices; the CLI is `umtool cast set`,
+// `umtool cast project <p> add|set|rm|undo|pool|keep`, `umtool posts character`). Works with the operator alone:
+// every field is a form field, every write the CLI's own command -- nothing here needs an agent.
+//
+// PresetEditor one character's two presets: SYNTHETIC (the stock voice, its speed) and RECORDED (what a
+// recording of them is made into: the stock voice it is converted to, the engine, the pitch
+// and semitones, cleaned or not, its edges trimmed or not and the room kept, and a DIRECTION
+// -- one line for the person reading, never sent to a model) -- the cast's or this video's own
+// ProjectCharacters THIS VIDEO's OWN characters (narration/characters.json): people who must not enter the pool
+// (anonymous ones go by "Anon 1" … here and in recording notes; the cut's card is not anonymised yet), add one, remove one, undo, "Add to the
+// pool"; and the post items that name a character of their own
+// ---------------------------------------------------------------------------
+
+export type Convert = { engine?: string; voice?: string; pitch?: "target" | "source" | "contour"; semitones?: number };
+export type Synthetic = { voice?: string; speed?: number };
+export type Recorded = { convert?: Convert; enhance?: boolean; trim?: { on?: boolean; padMs?: number }; direction?: string };
+export type PresetCharacter = {
+ id: string; name: string; handles?: string[]; voice?: string; convert?: Convert; synthetic?: Synthetic; recorded?: Recorded;
+ speakers?: string[]; note?: string; narrator?: boolean; anonymous?: boolean; shown?: string; layer?: "cast" | "project";
+};
+export type Engine = { id: string; label: string; voices: string[]; defaultVoice: string; weight: string };
+export type ItemCharacter = { id: string; handle: string | null; character: string; found: boolean; layer: "cast" | "project" | null; name?: string; voice: { spec: string; from: string; speed?: number } };
+type Post = { id: string; handle: string; author: string; text: string };
+type PostFn = (body: Record<string, unknown>) => Promise<Record<string, unknown> | null>;
+
+const input = "rounded-[3px] border border-seam-2 bg-ground px-1.5 py-[3px] text-[11.5px] text-text outline-none focus:border-signal";
+const pretty = (spec: string) => spec.replace(":", " · ");
+
+/** A recorded preset in words: "a recording → kokoro · am_michael (seed-vc), pitch contour +2 st · not cleaned · …". */
+export function recordedWords(c: PresetCharacter): string {
+ const rec = c.recorded;
+ if (!rec) return "";
+ const bits: string[] = [];
+ const cv = rec.convert;
+ if (cv) {
+ const n = Number(cv.semitones) || 0;
+ const pitch = cv.pitch && cv.pitch !== "target" ? `, pitch ${cv.pitch}${n ? ` ${n > 0 ? "+" : "−"}${Math.abs(n)} st` : ""}` : "";
+ bits.push(`a recording → ${pretty(cv.voice ?? c.voice ?? "?")}${cv.engine ? ` (${cv.engine})` : ""}${pitch}`);
+ }
+ if (rec.enhance === false) bits.push("not cleaned");
+ if (rec.trim?.on === false) bits.push("edges not trimmed");
+ else if (typeof rec.trim?.padMs === "number") bits.push(`trim pad ${rec.trim.padMs} ms`);
+ if (rec.direction) bits.push(`direction: “${rec.direction}”`);
+ return bits.join(" · ");
+}
+
+/** A stock voice picked as engine + voice; `none` (a label) offers "no voice of its own". */
+function VoicePick({ value, onChange, engines, none = null, name }: { value: string; onChange: (v: string) => void; engines: Engine[]; none?: string | null; name: string }) {
+ const at = value.indexOf(":");
+ const eng = at > 0 ? value.slice(0, at) : "";
+ const voice = at > 0 ? value.slice(at + 1) : "";
+ const engine = engines.find((e) => e.id === eng) ?? null;
+ // A voice the editor's list does not carry (an older cast entry) stays selectable as it is.
+ const voices = engine ? (engine.voices.includes(voice) || !voice ? engine.voices : [voice, ...engine.voices]) : [];
+ return (
+ <span className="inline-flex items-center gap-1">
+ <select
+ data-preset-engine={name}
+ aria-label={`${name}: the engine`}
+ value={eng}
+ onChange={(e) => {
+ const next = engines.find((x) => x.id === e.target.value);
+ onChange(next ? `${next.id}:${next.defaultVoice || next.voices[0] || ""}` : "");
+ }}
+ className={input}
+ >
+ {none !== null && <option value="">{none}</option>}
+ {none === null && !engine && <option value="">an engine…</option>}
+ {engines.map((e) => (
+ <option key={e.id} value={e.id}>
+ {e.label}
+ </option>
+ ))}
+ </select>
+ {engine && (
+ <select data-preset-voice={name} aria-label={`${name}: the voice`} value={voice} onChange={(e) => onChange(`${engine.id}:${e.target.value}`)} className={input}>
+ {voices.map((v) => (
+ <option key={v} value={v}>
+ {v}
+ </option>
+ ))}
+ </select>
+ )}
+ </span>
+ );
+}
+
+type Form = {
+ name: string; shown: string; voice: string; speed: string; convertVoice: string; convertEngine: string; convertPitch: string; convertSemitones: string;
+ enhance: boolean; trim: boolean; trimPad: string; direction: string;
+};
+const formOf = (c: PresetCharacter): Form => ({
+ name: c.name ?? "",
+ shown: c.shown ?? "",
+ voice: c.synthetic?.voice ?? c.voice ?? "",
+ speed: typeof c.synthetic?.speed === "number" ? String(c.synthetic.speed) : "",
+ convertVoice: c.recorded?.convert?.voice ?? "",
+ convertEngine: c.recorded?.convert?.engine ?? "",
+ convertPitch: c.recorded?.convert?.pitch ?? "",
+ convertSemitones: typeof c.recorded?.convert?.semitones === "number" ? String(c.recorded.convert.semitones) : "",
+ enhance: c.recorded?.enhance !== false,
+ trim: c.recorded?.trim?.on !== false,
+ trimPad: typeof c.recorded?.trim?.padMs === "number" ? String(c.recorded.trim.padMs) : "",
+ direction: c.recorded?.direction ?? "",
+});
+
+/**
+ * ONE CHARACTER's PRESETS, editable: Save is `umtool cast set <id> …` (scope "cast": every project) or `umtool cast
+ * project <p> set <id> …` (scope "project": this video only). A field left empty is its default again.
+ */
+export function PresetEditor({
+ c, scope, engines, convertEngines, busy, post, onSaved, onClose,
+}: {
+ c: PresetCharacter; scope: "cast" | "project"; engines: Engine[]; convertEngines: string[]; busy: boolean; post: PostFn; onSaved: (what: string) => void; onClose: () => void;
+}) {
+ // (The panel keys this editor by the character as it is stored: another one opened, or this one saved, is a new form.)
+ const [f, setF] = useState<Form>(() => formOf(c));
+ const set = <K extends keyof Form>(k: K, v: Form[K]) => setF((x) => ({ ...x, [k]: v }));
+ const follows = f.convertPitch === "source" || f.convertPitch === "contour";
+ const save = async () => {
+ const j = await post({
+ op: "character-set", scope, id: c.id,
+ ...(f.name.trim() && f.name.trim() !== c.name ? { name: f.name.trim() } : {}),
+ ...(c.anonymous && f.shown.trim() && f.shown.trim() !== (c.shown ?? "") ? { shown: f.shown.trim() } : {}),
+ voice: f.voice, speed: f.voice ? f.speed : "",
+ convertVoice: f.convertVoice, convertEngine: f.convertEngine, convertPitch: f.convertPitch, convertSemitones: follows ? f.convertSemitones : "",
+ // On is the default: said only when it is off, so a preset nobody touched stays as short as it was.
+ enhance: f.enhance ? "" : "off", trim: f.trim ? (f.trimPad.trim() ? "on" : "") : "off", trimPad: f.trim ? f.trimPad.trim() : "",
+ direction: f.direction.trim(),
+ });
+ if (j) onSaved(`${c.name}: its presets saved ${scope === "cast" ? "in the cast (every project)" : "for this video only"}`);
+ };
+ const row = "flex flex-wrap items-center gap-x-3 gap-y-1.5";
+ const lab = "inline-flex items-center gap-1.5";
+ return (
+ <section className="rounded-[4px] border border-seam-2 p-3" data-preset-editor={c.id} data-preset-scope={scope}>
+ <h2 className="micro mb-2">
+ presets · {c.anonymous ? `${c.shown} (anonymous)` : c.name}
+ <span className="ml-2 normal-case tracking-normal text-muted">{scope === "cast" ? "the cast: the same in every project" : "this video only"}</span>
+ </h2>
+ <div className={row}>
+ <label className={lab}>
+ <span className="text-muted">name</span>
+ <input data-preset-name="" value={f.name} onChange={(e) => set("name", e.target.value)} maxLength={80} className={cn(input, "w-44")} />
+ </label>
+ {c.anonymous && (
+ <label className={lab} title="the name it goes by on this page, in `umtool cast project` and in a recording's note — the cut's on-screen card is not anonymised yet: it still shows the post's author">
+ <span className="text-muted">shown as</span>
+ <input data-preset-shown="" value={f.shown} onChange={(e) => set("shown", e.target.value)} maxLength={80} className={cn(input, "w-32")} />
+ </label>
+ )}
+ </div>
+ <h3 className="micro mb-1 mt-3">synthetic · a read the editor synthesizes</h3>
+ <div className={row}>
+ <span className={lab}>
+ <span className="text-muted">voice</span>
+ <VoicePick name="voice" value={f.voice} onChange={(v) => set("voice", v)} engines={engines} none={scope === "project" ? "none of its own (the cast's, the narrator's…)" : null} />
+ </span>
+ <label className={lab} title="the tts op's speed, 0.5–2 (empty: 1). Orpheus has no speed: it is not asked one.">
+ <span className="text-muted">speed</span>
+ <input data-preset-speed="" type="number" min={0.5} max={2} step={0.05} value={f.speed} disabled={!f.voice} onChange={(e) => set("speed", e.target.value)} placeholder="1" className={cn(input, "w-16")} />
+ {f.voice.startsWith("orpheus:") && f.speed && <span className="text-[11px] text-doubt-text">Orpheus has no speed</span>}
+ </label>
+ </div>
+ <h3 className="micro mb-1 mt-3">recorded · a recording of them, made their read</h3>
+ <div className={row}>
+ <span className={lab} title="always a STOCK synthetic voice: a file or a recording is never a target">
+ <span className="text-muted">converted to</span>
+ <VoicePick name="convert" value={f.convertVoice} onChange={(v) => set("convertVoice", v)} engines={engines} none={f.voice ? `its own voice (${pretty(f.voice)})` : "its own voice"} />
+ </span>
+ <label className={lab}>
+ <span className="text-muted">by</span>
+ <select data-preset-convert-engine="" value={f.convertEngine} onChange={(e) => set("convertEngine", e.target.value)} className={input}>
+ <option value="">the editor's default</option>
+ {convertEngines.map((e) => (
+ <option key={e} value={e}>
+ {e}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className={lab} title="where the converted read's pitch comes from: the stock voice's own, the pitch you read at, or your rises and falls at the stock voice's register (source and contour are seed-vc's)">
+ <span className="text-muted">pitch</span>
+ <select data-preset-pitch="" value={f.convertPitch} onChange={(e) => set("convertPitch", e.target.value)} className={input}>
+ <option value="">the editor's default</option>
+ <option value="target">target — the stock voice's own</option>
+ <option value="source">source — the pitch you read at</option>
+ <option value="contour">contour — your intonation, its register</option>
+ </select>
+ </label>
+ <label className={lab} title="moves a followed pitch (source, contour), −12…12">
+ <span className="text-muted">semitones</span>
+ <input data-preset-semitones="" type="number" min={-12} max={12} step={0.5} value={follows ? f.convertSemitones : ""} disabled={!follows} onChange={(e) => set("convertSemitones", e.target.value)} placeholder="0" className={cn(input, "w-14")} />
+ </label>
+ </div>
+ <div className={cn(row, "mt-1.5")}>
+ <label className="inline-flex items-center gap-1" title="the editor's voice-enhance (DeepFilterNet), before the convert">
+ <input type="checkbox" data-preset-enhance="" checked={f.enhance} onChange={(e) => set("enhance", e.target.checked)} /> clean it first
+ </label>
+ <label className="inline-flex items-center gap-1" title="the silence (and a key click) before and after the words cut away">
+ <input type="checkbox" data-preset-trim="" checked={f.trim} onChange={(e) => set("trim", e.target.checked)} /> trim its edges to speech
+ </label>
+ <label className={lab} title="the room kept either side of the words, milliseconds (empty: the recorder's own, 80 before and 150 after)">
+ <span className="text-muted">pad</span>
+ <input data-preset-trim-pad="" type="number" min={0} max={2000} step={10} value={f.trim ? f.trimPad : ""} disabled={!f.trim} onChange={(e) => set("trimPad", e.target.value)} placeholder="default" className={cn(input, "w-20")} />
+ <span className="text-muted">ms</span>
+ </label>
+ </div>
+ <label className="mt-1.5 flex flex-wrap items-center gap-1.5">
+ <span className="text-muted">direction</span>
+ <input data-preset-direction="" value={f.direction} onChange={(e) => set("direction", e.target.value)} maxLength={200} placeholder="higher, brisk, amused" className={cn(input, "w-[26rem] max-w-full")} />
+ <span className="text-[11px] text-muted">one line for the person reading — never sent to a model</span>
+ </label>
+ <div className="mt-2.5 flex flex-wrap gap-1.5">
+ <button type="button" data-preset-save="" disabled={busy || !f.name.trim() || (scope === "cast" && !f.voice)} onClick={() => void save()} className={buttonVariants({ variant: "go", size: "sm" })}>
+ Save presets
+ </button>
+ <button type="button" data-preset-close="" onClick={onClose} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Close
+ </button>
+ </div>
+ </section>
+ );
+}
+
+/** THIS VIDEO's OWN characters, and the items that name a character of their own. */
+export function ProjectCharacters({
+ own, cast, itemCharacters, posts, charactersError, busy, post, onChanged, onOpen, open,
+}: {
+ own: PresetCharacter[]; cast: PresetCharacter[]; itemCharacters: ItemCharacter[]; posts: Post[]; charactersError?: string; busy: boolean; post: PostFn;
+ onChanged: (what: string) => void; onOpen: (id: string) => void; open: string | null;
+}) {
+ const [add, setAdd] = useState({ id: "", name: "", handles: "", anonymous: false, shown: "" });
+ const [item, setItem] = useState({ item: posts[0]?.id ?? "", character: "" });
+ const cell = "border-t border-seam px-2 py-1 align-top";
+ const idOk = /^[a-z0-9][a-z0-9_-]{0,47}$/.test(add.id);
+ const send = async (body: Record<string, unknown>, what: string) => {
+ const j = await post(body);
+ if (j) onChanged(what);
+ return j;
+ };
+ return (
+ <section data-project-characters={own.length}>
+ <h2 className="micro mb-1.5">
+ this video's own characters · {own.length}
+ <span className="ml-2 normal-case tracking-normal text-muted">people who stay out of the pool — an anonymous one goes by its shown name here and in recording notes; the cut's on-screen card is not anonymised yet</span>
+ </h2>
+ {charactersError && <p className="m-0 mb-1 text-doubt-text" data-project-characters-error="">this video's characters are not read: {charactersError}</p>}
+ {own.length > 0 && (
+ <table className="w-full border-collapse">
+ <tbody>
+ {own.map((c) => (
+ <tr key={c.id} data-project-character={c.id} className={cn(open === c.id && "bg-panel-2")}>
+ <td className={cell}>
+ <span className="font-medium">{c.anonymous ? c.shown : c.name}</span>
+ {c.anonymous && <span className="ml-1.5 rounded-[3px] border border-seam-2 px-1 text-[10.5px] text-doubt-text" title={`anonymous: “${c.shown}” on this page, in cast project and in recording notes (your own label: ${c.name}) — the cut's on-screen card still shows the post's author`}>anonymous</span>}
+ <span className="ml-1.5 font-mono text-[11px] text-muted">{(c.handles ?? []).map((h) => `@${h}`).join(" ")}</span>
+ </td>
+ <td className={cn(cell, "font-mono")}>
+ {c.voice ? pretty(c.voice) : <span className="font-sans text-muted">no voice of its own</span>}
+ {typeof c.synthetic?.speed === "number" ? ` ×${c.synthetic.speed}` : ""}
+ </td>
+ <td className={cn(cell, "text-[11px] text-text-2")}>{recordedWords(c)}</td>
+ <td className={cn(cell, "whitespace-nowrap text-right")}>
+ <button type="button" data-project-character-preset={c.id} onClick={() => onOpen(c.id)} className={buttonVariants({ variant: open === c.id ? "pressed" : "outline", size: "sm" })}>
+ Presets
+ </button>{" "}
+ {!c.anonymous && (
+ <button
+ type="button"
+ data-character-pool={c.id}
+ disabled={busy || !c.voice}
+ title={c.voice ? "into the cast: the same presets in every project" : "a cast character has a stock voice: give it one first"}
+ onClick={() => void send({ op: "character-pool", id: c.id }, `${c.name} is in the pool now, for every project`)}
+ className={buttonVariants({ variant: "outline", size: "sm" })}
+ >
+ Add to the pool
+ </button>
+ )}{" "}
+ <button type="button" data-project-character-remove={c.id} disabled={busy} onClick={() => void send({ op: "character-rm", id: c.id }, `${c.anonymous ? c.shown : c.name} removed from this video's characters`)} className={buttonVariants({ variant: "quiet", size: "sm" })} aria-label={`remove ${c.anonymous ? c.shown : c.name} from this video's characters`}>
+ ✕
+ </button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ <div className="mt-1.5 flex flex-wrap items-center gap-1.5" data-project-character-add="">
+ <input data-project-character-id="" value={add.id} onChange={(e) => setAdd({ ...add, id: e.target.value.toLowerCase() })} placeholder="id (anon-1)" className={cn(input, "w-28")} aria-label="the new character's id" />
+ <input data-project-character-name="" value={add.name} onChange={(e) => setAdd({ ...add, name: e.target.value })} placeholder={add.anonymous ? "your label for them (optional)" : "name"} className={cn(input, "w-44")} aria-label="the new character's name" />
+ <input data-project-character-handles="" value={add.handles} onChange={(e) => setAdd({ ...add, handles: e.target.value })} placeholder="handles: a,b" className={cn(input, "w-40")} aria-label="the handles it covers" />
+ <label className="inline-flex items-center gap-1">
+ <input type="checkbox" data-project-character-anonymous="" checked={add.anonymous} onChange={(e) => setAdd({ ...add, anonymous: e.target.checked })} /> anonymous
+ </label>
+ {add.anonymous && <input data-project-character-shown="" value={add.shown} onChange={(e) => setAdd({ ...add, shown: e.target.value })} placeholder="shown as (Anon 1, Anon 2 …)" className={cn(input, "w-44")} aria-label="the name it is shown under" />}
+ <button
+ type="button"
+ data-project-character-add-go=""
+ disabled={busy || !idOk || (!add.anonymous && !add.name.trim())}
+ onClick={() =>
+ void send({ op: "character-add", id: add.id, ...(add.name.trim() ? { name: add.name.trim() } : {}), ...(add.handles.trim() ? { handles: add.handles } : {}), ...(add.anonymous ? { anonymous: true, ...(add.shown.trim() ? { shown: add.shown.trim() } : {}) } : {}) }, `${add.id} is one of this video's characters`).then((j) => {
+ if (!j) return;
+ onOpen(add.id);
+ setAdd({ id: "", name: "", handles: "", anonymous: false, shown: "" });
+ })
+ }
+ className={buttonVariants({ variant: "outline", size: "sm" })}
+ >
+ Add a character
+ </button>
+ <button type="button" data-project-characters-undo="" disabled={busy} onClick={() => void send({ op: "characters-undo" }, "undone: the last change to this video's characters")} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Undo the last change
+ </button>
+ </div>
+
+ <h3 className="micro mb-1 mt-3">
+ an item read as a character of its own · {itemCharacters.length}
+ <span className="ml-2 normal-case tracking-normal text-muted">its presets answer for that item before its author's handle does</span>
+ </h3>
+ {itemCharacters.length > 0 && (
+ <ul className="m-0 mb-1.5 list-none p-0 text-[11.5px] text-text-2" data-item-characters={itemCharacters.length}>
+ {itemCharacters.map((it) => (
+ <li key={it.id} data-item-character={it.id} data-item-character-found={it.found ? "yes" : "no"}>
+ <span className="font-mono">{it.id}</span>
+ {it.handle ? ` @${it.handle}` : ""} — read as <b>{it.name ?? it.character}</b>
+ {it.found ? (
+ <>
+ {" "}
+ ({it.layer === "project" ? "this video's" : "the cast's"}): <span className="font-mono">{pretty(it.voice.spec)}</span>
+ {typeof it.voice.speed === "number" ? ` ×${it.voice.speed}` : ""}
+ </>
+ ) : (
+ <span className="text-doubt-text"> — no such character: it reads as its author does ({pretty(it.voice.spec)})</span>
+ )}{" "}
+ <button type="button" data-item-character-clear={it.id} disabled={busy} onClick={() => void send({ op: "item-character", item: it.id, character: "" }, `${it.id}: read by its author's handle again`)} className="ink-link">
+ clear
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ {posts.length > 0 && (
+ <div className="flex flex-wrap items-center gap-1.5">
+ <select data-item-character-item="" value={item.item} onChange={(e) => setItem({ ...item, item: e.target.value })} className={cn(input, "max-w-[22rem]")} aria-label="the post item">
+ {posts.map((p) => (
+ <option key={p.id} value={p.id}>
+ {p.id} @{p.handle}: {p.text}
+ </option>
+ ))}
+ </select>
+ <select data-item-character-pick="" value={item.character} onChange={(e) => setItem({ ...item, character: e.target.value })} className={input} aria-label="the character it is read as">
+ <option value="">read as…</option>
+ {own.map((c) => (
+ <option key={`p:${c.id}`} value={c.id}>
+ {c.anonymous ? c.shown : c.name} (this video)
+ </option>
+ ))}
+ {cast.filter((c) => !own.some((o) => o.id === c.id)).map((c) => (
+ <option key={`c:${c.id}`} value={c.id}>
+ {c.name} (the cast)
+ </option>
+ ))}
+ </select>
+ <button type="button" data-item-character-set="" disabled={busy || !item.item || !item.character} onClick={() => void send({ op: "item-character", item: item.item, character: item.character }, `${item.item}: read as ${item.character}`)} className={buttonVariants({ variant: "outline", size: "sm" })}>
+ Set
+ </button>
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx
@@ -7,6 +7,7 @@ import Waveform from "@/components/Waveform";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { postBenchHref } from "@/lib/hrefs";
+import { CAST_CONVERT_ENGINES, CAST_CONVERT_PITCH, CAST_PITCH_ENGINES, CAST_SEMITONES_MAX, convertPitchLabel } from "umtool-report-to-video/cast";
import { POST_DERIVE_OPS, POST_NARRATION_DEFAULTS, mixPhaseAt, pickedTake, postNarrationKnobs, scriptParts, takeIdOf, takeSourceOf } from "umtool-report-to-video/post-narration";
import { projectFileMedia } from "./bench/benchMedia";
import { usePeaks } from "./bench/usePeaks";
@@ -37,7 +38,15 @@ import PostAttachmentLane from "./PostAttachmentLane";
// `umtool posts narrate` runs; the bench takes the entry it returns.
// ---------------------------------------------------------------------------
-type Step = { op: string; engine?: string; voice?: string };
+// A derived take's step. A convert's `pitch` / `semitones`: the pitch the converted read lands on (knobs.md, "The
+// pitch a converted read lands on") -- absent for the stock voice's own.
+type Step = { op: string; engine?: string; voice?: string; pitch?: string; semitones?: number };
+// The engines whose convert can FOLLOW the read's pitch (cast.mjs CAST_PITCH_ENGINES), and the modes in plain words.
+const PITCH_WORDS: Record<string, string> = {
+ target: "the stock voice's own pitch",
+ source: "follow my pitch",
+ contour: "my intonation, at the voice's register",
+};
type Take = { file: string; engine?: string; voice?: string; seconds: number; note?: string; script?: string; label?: string; source?: { kind: string; from?: string; voice?: string; engine?: string }; steps?: Step[]; parts?: Array<{ n: number; para?: number; text?: string; start: number; seconds: number; file?: string }>; words?: Array<{ w: string; start: number; end: number }> };
type Narration = { script?: string; takes?: Take[]; pick?: number; approved?: boolean; off?: boolean; window?: { media: number; start: number; end: number; score?: number; reason?: string } } & Record<string, unknown>;
type Entry = Record<string, unknown> & { id: string; narration?: Narration; media?: Array<Record<string, unknown> & { src: string; kind: string; seconds?: number; start?: number; end?: number }> };
@@ -212,20 +221,22 @@ export default function PostNarrationPanel({
// ---- a re-take with direction (the editor's tts op) --------------------------
const [dir, setDir] = useState({ note: "", voice: "", speed: "" });
- const [job, setJob] = useState<{ id: string; file: string; note: string; script: string; state: string; error?: string; polls?: number; derive?: { from: number; op: string; engine?: string | null; voice?: string | null } } | null>(null);
+ const [job, setJob] = useState<{ id: string; file: string; note: string; script: string; state: string; error?: string; polls?: number; derive?: { from: number; op: string; engine?: string | null; voice?: string | null; pitch?: string | null; semitones?: number | null } } | null>(null);
// Derived takes still to make after a re-record ("re-run the chain"), from the new take.
const [chain, setChain] = useState<Array<{ from: number; step: Step }>>([]);
const [rerunChain, setRerunChain] = useState(true);
const [notInstalled, setNotInstalled] = useState<string | null>(null);
const derive = async (from: number, step: Step) => {
setNotInstalled(null);
- const j = (await post({ op: "derive", from, op2: step.op, engine: step.engine || undefined, voice: step.voice || undefined })) as ({ jobId?: string; file?: string; installed?: boolean; error?: string } & Record<string, unknown>) | null;
+ const j = (await post({ op: "derive", from, op2: step.op, engine: step.engine || undefined, voice: step.voice || undefined, ...(step.op === "convert" && step.pitch ? { pitch: step.pitch, ...(typeof step.semitones === "number" ? { semitones: step.semitones } : {}) } : {}) })) as ({ jobId?: string; file?: string; installed?: boolean; error?: string } & Record<string, unknown>) | null;
if (j && j.installed === false) {
setNotInstalled(j.error ?? `the editor has no ${step.op} engine yet`);
setChain([]);
return;
}
- if (j?.jobId && j.file) setJob({ id: j.jobId, file: j.file, note: "", script, state: "running", derive: { from, op: step.op, engine: step.engine ?? null, voice: step.voice ?? null } });
+ // What the server asked the editor with (a convert's defaults are its character's): the keeper records those.
+ const asked = (k: string) => (typeof j?.[k] === "string" && j[k] ? (j[k] as string) : null);
+ if (j?.jobId && j.file) setJob({ id: j.jobId, file: j.file, note: "", script, state: "running", derive: { from, op: step.op, engine: asked("engine") ?? step.engine ?? null, voice: asked("voice") ?? step.voice ?? null, pitch: asked("pitch") ?? step.pitch ?? null, semitones: typeof j.semitones === "number" ? j.semitones : step.semitones ?? null } });
};
const retake = async () => {
const j = await post({ op: "take", note: dir.note || undefined, voice: dir.voice || undefined, speed: dir.speed ? Number(dir.speed) : undefined, script });
@@ -236,7 +247,7 @@ export default function PostNarrationPanel({
const t = setTimeout(async () => {
const q = new URLSearchParams({
project, id: entry.id, job: job.id, file: job.file, script: job.script, ...(job.note ? { note: job.note } : {}),
- ...(job.derive ? { derive: String(job.derive.from), op: job.derive.op, ...(job.derive.engine ? { engine: job.derive.engine } : {}), ...(job.derive.voice ? { voice: job.derive.voice } : {}) } : {}),
+ ...(job.derive ? { derive: String(job.derive.from), op: job.derive.op, ...(job.derive.engine ? { engine: job.derive.engine } : {}), ...(job.derive.voice ? { voice: job.derive.voice } : {}), ...(job.derive.pitch ? { pitch: job.derive.pitch } : {}), ...(typeof job.derive.semitones === "number" ? { semitones: String(job.derive.semitones) } : {}) } : {}),
});
const r = await fetch(`/api/report/post-narration?${q}`, { cache: "no-store" });
const j = (await r.json().catch(() => ({}))) as { state?: string; error?: string; entry?: Entry; token?: string };
@@ -279,7 +290,47 @@ export default function PostNarrationPanel({
roots.forEach((i) => walk(i, 0));
return { rows: out, kids };
}, [takes]);
- const [deriveDraft, setDeriveDraft] = useState<{ op: string; engine: string; voice: string }>({ op: "enhance", engine: "", voice: "" });
+ const [deriveDraft, setDeriveDraft] = useState<{ op: string; engine: string; voice: string; pitch: string; semitones: string }>({ op: "enhance", engine: "", voice: "", pitch: "target", semitones: "" });
+ // What a convert of THIS post defaults to: its author's character in the cast (else the narrator) -- the engine, the
+ // stock voice and the pitch every recording made that character's lands on (`umtool cast set <id> --convert-pitch …`).
+ const [castConvert, setCastConvert] = useState<{ name: string; engine?: string | null; voice?: string | null; pitch?: string; semitones?: number } | null>(null);
+ useEffect(() => {
+ let live = true;
+ setCastConvert(null);
+ fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&convert=1`, { cache: "no-store" })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((j: { character?: { name: string } | null; convert?: { engine?: string | null; voice?: string | null; pitch?: string; semitones?: number } | null } | null) => {
+ if (live && j?.character && j.convert) setCastConvert({ name: j.character.name, ...j.convert });
+ })
+ .catch(() => {});
+ return () => {
+ live = false;
+ };
+ }, [project, entry.id]);
+ // Choosing the op: a convert starts from the character's entry (its engine and voice only where the field is
+ // empty); an enhance drops a convert engine left in the field.
+ const chooseDeriveOp = (op: string) =>
+ setDeriveDraft((d) =>
+ op !== "convert"
+ ? { ...d, op, engine: (CAST_CONVERT_ENGINES as readonly string[]).includes(d.engine.trim()) ? "" : d.engine }
+ : {
+ op,
+ engine: d.engine || castConvert?.engine || "",
+ voice: d.voice || castConvert?.voice || "",
+ pitch: castConvert?.pitch ?? "target",
+ semitones: castConvert?.semitones ? String(castConvert.semitones) : "",
+ },
+ );
+ // The pitch controls are an engine's that can follow one; without it the convert lands on the stock voice's own.
+ const derivePitched = deriveDraft.op === "convert" && (CAST_PITCH_ENGINES as readonly string[]).includes(deriveDraft.engine.trim());
+ const deriveSemitones = Number(deriveDraft.semitones || 0);
+ const deriveSemitonesBad = derivePitched && deriveDraft.pitch !== "target" && !(Number.isFinite(deriveSemitones) && Math.abs(deriveSemitones) <= CAST_SEMITONES_MAX);
+ const deriveStep = (): Step => ({
+ op: deriveDraft.op,
+ ...(deriveDraft.engine.trim() ? { engine: deriveDraft.engine.trim() } : {}),
+ ...(deriveDraft.op === "convert" && deriveDraft.voice.trim() ? { voice: deriveDraft.voice.trim() } : {}),
+ ...(derivePitched ? { pitch: deriveDraft.pitch, ...(deriveDraft.pitch !== "target" ? { semitones: deriveSemitones } : {}) } : {}),
+ });
// ---- the lanes ------------------------------------------------------------------
// One lane per timed attachment (a video, a GIF), its in and out the bench's draft (onTrim).
@@ -589,7 +640,7 @@ export default function PostNarrationPanel({
<div className="flex flex-wrap items-center gap-2">
<span className="font-mono">{depth ? "└ " : ""}#{i + 1}</span>
<span>
- {src.kind === "recorded" ? `recorded · ${src.voice ?? t.voice ?? "?"}` : src.kind === "take" ? `${step?.op ?? "derived"}${step?.engine ? ` · ${step.engine}` : ""}${step?.voice ? ` → ${step.voice}` : ""}` : `${t.engine ?? "?"} · ${t.voice ?? "?"}`}
+ {src.kind === "recorded" ? `recorded · ${src.voice ?? t.voice ?? "?"}` : src.kind === "take" ? `${step?.op ?? "derived"}${step?.engine ? ` · ${step.engine}` : ""}${step?.voice ? ` → ${step.voice}` : ""}${convertPitchLabel(step) ? ` · pitch: ${convertPitchLabel(step)}` : ""}` : `${t.engine ?? "?"} · ${t.voice ?? "?"}`}
</span>
<span className="tabular-nums">{Number(t.seconds).toFixed(1)} s</span>
{/* eslint-disable-next-line jsx-a11y/media-has-caption */}
@@ -642,7 +693,7 @@ export default function PostNarrationPanel({
{picked && (
<div className="flex flex-wrap items-center gap-1.5" data-post-derive="">
<span className="micro">run AI on take #{picked.index + 1}</span>
- <select value={deriveDraft.op} onChange={(e) => setDeriveDraft({ ...deriveDraft, op: e.target.value })} data-post-derive-op="">
+ <select value={deriveDraft.op} onChange={(e) => chooseDeriveOp(e.target.value)} data-post-derive-op="">
{POST_DERIVE_OPS.map((o) => (
<option key={o} value={o}>
{o === "enhance" ? "enhance (denoise, level)" : "convert (to a stock synthetic voice)"}
@@ -653,7 +704,30 @@ export default function PostNarrationPanel({
{deriveDraft.op === "convert" && (
<input value={deriveDraft.voice} onChange={(e) => setDeriveDraft({ ...deriveDraft, voice: e.target.value })} placeholder="stock voice" className="w-24 rounded border border-seam bg-ground px-1 py-0.5" data-post-derive-voice="" />
)}
- <button type="button" className={btn} disabled={job?.state === "running"} onClick={() => void derive(picked.index, { op: deriveDraft.op, ...(deriveDraft.engine ? { engine: deriveDraft.engine } : {}), ...(deriveDraft.voice ? { voice: deriveDraft.voice } : {}) })} data-post-derive-run="">
+ {derivePitched && (
+ <label className="flex items-center gap-1" title="where the converted read's pitch comes from: the stock voice's own (your intonation is flattened to it), the pitch you read at, or your rises and falls moved to the stock voice's register">
+ <span className="micro">pitch</span>
+ <select value={deriveDraft.pitch} onChange={(e) => setDeriveDraft({ ...deriveDraft, pitch: e.target.value })} aria-label="the pitch the converted read lands on" data-post-derive-pitch="">
+ {CAST_CONVERT_PITCH.map((p) => (
+ <option key={p} value={p}>
+ {PITCH_WORDS[p] ?? p}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+ {derivePitched && deriveDraft.pitch !== "target" && (
+ <label className="flex items-center gap-1" title={`moves the followed pitch up or down, in semitones (-${CAST_SEMITONES_MAX} to ${CAST_SEMITONES_MAX}); 0: as followed`}>
+ <input type="number" min={-CAST_SEMITONES_MAX} max={CAST_SEMITONES_MAX} step={0.5} value={deriveDraft.semitones} onChange={(e) => setDeriveDraft({ ...deriveDraft, semitones: e.target.value })} placeholder="0" aria-label="semitones the followed pitch is moved by" aria-invalid={deriveSemitonesBad || undefined} className="w-14 rounded border border-seam bg-ground px-1 py-0.5" data-post-derive-semitones="" />
+ <span className="micro">semitones</span>
+ </label>
+ )}
+ {deriveDraft.op === "convert" && castConvert && (
+ <span className="micro text-text-2" data-post-derive-cast="">
+ {castConvert.name}'s in the cast: {[castConvert.engine, castConvert.voice, convertPitchLabel(castConvert) ? `pitch ${convertPitchLabel(castConvert)}` : null].filter(Boolean).join(" · ")}
+ </span>
+ )}
+ <button type="button" className={btn} disabled={job?.state === "running" || deriveSemitonesBad} onClick={() => void derive(picked.index, deriveStep())} data-post-derive-run="">
Run → a new take
</button>
{notInstalled && (
diff --git a/umtool/components/projects/RecordFilter.tsx b/umtool/components/projects/RecordFilter.tsx
@@ -0,0 +1,206 @@
+"use client";
+
+import { useCallback, useRef, useState, type PointerEvent as RPointerEvent } from "react";
+import { cn } from "@/lib/utils";
+
+// ---------------------------------------------------------------------------
+// RECORD -> FILTER -> PREVIEW, the record page's pieces (RecordSession.tsx; the
+// chain is lib/report/recordPreview.mjs, its route app/api/report/post-narration/
+// record): the types the page and the route share, a part's WAVEFORM with its
+// two CUT MARKS (draggable; the arrow keys move one 0.05 s), and the Filter
+// job's progress -- each stage's state, and a wait at the editor's queue or the
+// machine's heavy slot said as what it is: the gate working, not an error.
+// ---------------------------------------------------------------------------
+
+export type Span = { from: number; to: number };
+export type PreviewPart = { n: number; text: string; seconds: number; auto: Span; peaks: number[]; span: Span | null };
+export type Made = { seconds: number | null; lufs: number | null };
+export type Preview = {
+ id: string;
+ source: string;
+ trim: { on: boolean; padMs: number | null };
+ parts: PreviewPart[];
+ cleaned: "done" | "skipped" | "off" | null;
+ raw: Made | null;
+ clean: Made | null;
+ filtered: (Made & { engine: string | null; voice: string; pitch: string; semitones: number; asked: { pitch?: string; semitones?: number } | null }) | null;
+ notes: string[];
+};
+export type Who = {
+ character: { id: string; name: string; layer: string; scope: "project" | "cast" } | null;
+ convert: { engine: string | null; voice: string | null; pitch?: string; semitones?: number } | null;
+ recorded: { enhance: boolean; trim: { on: boolean; padMs: number | null }; direction: string | null } | null;
+ synthetic: { voice: string; speed: number | null } | null;
+ pitchEngines: string[];
+};
+export type FilterJob = {
+ id: string;
+ state: "running" | "done" | "failed";
+ startedAt: number;
+ endedAt: number | null;
+ stage: string | null;
+ stageState: string | null;
+ message: string | null;
+ waiting: "queued" | "memory" | "slot" | null;
+ waited: string[];
+ editorJob?: string | null;
+ stages: Record<string, { state?: string; message?: string }>;
+ error: string | null;
+};
+
+const r3 = (v: number) => Math.round(v * 1000) / 1000;
+export const sameSpan = (a: Span | null | undefined, b: Span | null | undefined) => !!a && !!b && Math.abs(a.from - b.from) < 0.002 && Math.abs(a.to - b.to) < 0.002;
+
+/** The least a cut may keep, and one press of an arrow key. */
+const MIN_KEPT = 0.2;
+const NUDGE = 0.05;
+
+/**
+ * A part's waveform with its cut marks: what is outside them is dimmed (it is cut), the dashed lines are the auto
+ * trim's answer. Drag a mark, or focus it and press the arrow keys (Shift: 0.25 s).
+ */
+export function TrimWave({ part, span, onChange, disabled = false }: { part: PreviewPart; span: Span; onChange: (s: Span) => void; disabled?: boolean }) {
+ const box = useRef<HTMLDivElement | null>(null);
+ const [drag, setDrag] = useState<"from" | "to" | null>(null);
+ const secs = Math.max(part.seconds, 0.001);
+ const pct = (t: number) => `${Math.max(0, Math.min(100, (t / secs) * 100))}%`;
+ const set = useCallback(
+ (edge: "from" | "to", t: number) => {
+ const v = edge === "from" ? Math.max(0, Math.min(span.to - MIN_KEPT, t)) : Math.min(secs, Math.max(span.from + MIN_KEPT, t));
+ onChange(edge === "from" ? { from: r3(v), to: span.to } : { from: span.from, to: r3(v) });
+ },
+ [span, secs, onChange],
+ );
+ const at = (ev: RPointerEvent) => {
+ const r = box.current?.getBoundingClientRect();
+ return r && r.width > 0 ? ((ev.clientX - r.left) / r.width) * secs : 0;
+ };
+ const mark = (edge: "from" | "to") => (
+ <button
+ type="button"
+ role="slider"
+ aria-label={edge === "from" ? `part ${part.n}: cut in` : `part ${part.n}: cut out`}
+ aria-valuemin={0}
+ aria-valuemax={r3(secs)}
+ aria-valuenow={span[edge]}
+ aria-valuetext={`${span[edge].toFixed(2)} s`}
+ disabled={disabled}
+ className={cn("absolute top-0 z-10 h-full w-3 -translate-x-1/2 cursor-ew-resize touch-none border-0 bg-transparent p-0", disabled && "cursor-default")}
+ style={{ left: pct(span[edge]) }}
+ onPointerDown={(ev) => {
+ if (disabled) return;
+ ev.currentTarget.setPointerCapture(ev.pointerId);
+ setDrag(edge);
+ }}
+ onPointerMove={(ev) => drag === edge && set(edge, at(ev))}
+ onPointerUp={() => setDrag(null)}
+ onPointerCancel={() => setDrag(null)}
+ onKeyDown={(ev) => {
+ const step = (ev.shiftKey ? 5 : 1) * NUDGE;
+ if (ev.key === "ArrowLeft" || ev.key === "ArrowDown") set(edge, span[edge] - step);
+ else if (ev.key === "ArrowRight" || ev.key === "ArrowUp") set(edge, span[edge] + step);
+ else return;
+ ev.preventDefault();
+ ev.stopPropagation();
+ }}
+ data-record-mark={edge}
+ data-record-mark-at={span[edge]}
+ >
+ <span className="mx-auto block h-full w-0.5 bg-amber-400" />
+ <span className={cn("absolute h-2 w-2 -translate-x-1/2 rounded-full bg-amber-400", edge === "from" ? "left-1/2 top-0" : "bottom-0 left-1/2")} />
+ </button>
+ );
+ const n = part.peaks.length || 1;
+ return (
+ <div className="space-y-1" data-record-wave={part.n} data-record-wave-auto={`${part.auto.from}-${part.auto.to}`}>
+ <div ref={box} className="relative h-14 w-full overflow-visible rounded bg-black/40">
+ <svg viewBox={`0 0 ${n} 100`} preserveAspectRatio="none" className="absolute inset-0 h-full w-full text-emerald-500" aria-hidden="true">
+ {part.peaks.map((v, i) => {
+ const h = Math.max(1.5, Math.min(100, v * 100));
+ return <rect key={i} x={i + 0.15} y={50 - h / 2} width={0.7} height={h} fill="currentColor" />;
+ })}
+ </svg>
+ {/* What the marks cut away. */}
+ <div className="absolute inset-y-0 left-0 bg-black/65" style={{ width: pct(span.from) }} />
+ <div className="absolute inset-y-0 right-0 bg-black/65" style={{ width: `${Math.max(0, 100 - (span.to / secs) * 100)}%` }} />
+ {/* The auto trim's answer. */}
+ <div className="absolute inset-y-0 w-px border-l border-dashed border-white/40" style={{ left: pct(part.auto.from) }} />
+ <div className="absolute inset-y-0 w-px border-l border-dashed border-white/40" style={{ left: pct(part.auto.to) }} />
+ {mark("from")}
+ {mark("to")}
+ </div>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px] text-text-2">
+ <span className="font-mono tabular-nums" data-record-span={`${span.from}-${span.to}`}>
+ cut in {span.from.toFixed(2)} s · out {span.to.toFixed(2)} s · keeps {(span.to - span.from).toFixed(2)} of {part.seconds.toFixed(2)} s
+ </span>
+ {!sameSpan(span, part.auto) && (
+ <button type="button" className="ink-link" disabled={disabled} onClick={() => onChange(part.auto)} data-record-span-auto="">
+ back to the auto trim
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+const STAGES: Array<[string, string]> = [["clean", "Clean"], ["trim", "Cut"], ["convert", "Convert"]];
+const mmss = (ms: number) => `${Math.floor(ms / 60000)}:${String(Math.floor((ms % 60000) / 1000)).padStart(2, "0")}`;
+
+/** What a wait is, in a sentence: the gate working. */
+export const waitText = (w: FilterJob["waiting"]) =>
+ w === "memory" ? "waiting for memory — the machine's heavy slot lets it in when there is room. This is the gate working, not an error."
+ : w === "slot" ? "waiting for the heavy slot — another heavy job (a render, a build, a test run) holds it. This is the gate working, not an error."
+ : w === "queued" ? "queued at the editor behind its other voice jobs."
+ : "";
+
+/** The Filter job as it runs: the three stages, the wait when it waits, how long it has run. */
+export function FilterProgress({ job, now, onCancel }: { job: FilterJob; now: number; onCancel: () => void }) {
+ const running = job.state === "running";
+ return (
+ <div className="space-y-1 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-2 text-[12.5px]" data-record-filter-job={job.state} data-record-filter-stage={job.stage ?? ""} data-record-filter-waiting={job.waiting ?? ""} data-record-filter-waited={(job.waited ?? []).join(" ")}>
+ <div className="flex flex-wrap items-center gap-2">
+ {STAGES.map(([key, label]) => {
+ const st = job.stages[key]?.state;
+ const here = running && job.stage === key;
+ const wait = here && job.waiting;
+ return (
+ <span
+ key={key}
+ className={cn(
+ "rounded px-1.5 py-0.5",
+ wait ? "bg-amber-400/25" : here ? "bg-[var(--color-sel)]/25" : st === "done" || st === "cached" ? "bg-emerald-500/20" : st === "skipped" ? "bg-white/10 text-text-2" : "text-text-2",
+ )}
+ data-record-filter-step={key}
+ data-record-filter-step-state={st ?? ""}
+ >
+ {label}
+ {wait ? ": waiting" : here ? "…" : st === "done" ? " ✓" : st === "cached" ? " ✓ (kept from before)" : st === "skipped" ? " — skipped" : ""}
+ </span>
+ );
+ })}
+ <span className="font-mono tabular-nums text-text-2" data-record-filter-elapsed="">
+ {mmss((job.endedAt ?? now) - job.startedAt)}
+ </span>
+ {running && (
+ <button type="button" className="ink-link" onClick={onCancel} data-record-filter-cancel="">
+ Cancel
+ </button>
+ )}
+ </div>
+ {running && job.waiting && (
+ <div className="text-amber-300" data-record-filter-wait={job.waiting}>
+ {waitText(job.waiting)}
+ </div>
+ )}
+ {running && !job.waiting && <div className="text-text-2">{job.message ?? "starting…"} — a short read takes two or three minutes here.</div>}
+ {job.state === "done" && (job.waited ?? []).some((w) => w !== "queued") && (
+ <div className="text-text-2">it waited at the heavy slot ({(job.waited ?? []).filter((w) => w !== "queued").map((w) => (w === "memory" ? "for memory" : "for another heavy job")).join(", ")}) on the way: the gate, not a fault</div>
+ )}
+ {job.state === "failed" && (
+ <div className="text-[var(--color-blocking,#c33)]" data-record-filter-error="">
+ the Filter did not finish: {job.error ?? "it failed"}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/umtool/components/projects/RecordSession.tsx b/umtool/components/projects/RecordSession.tsx
@@ -3,10 +3,11 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
-import { postBenchHref } from "@/lib/hrefs";
+import { postBenchHref, voicesHref } from "@/lib/hrefs";
import { scriptParts } from "umtool-report-to-video/post-narration";
import { redactText } from "umtool-report-to-video/post-redact";
import { MIC_KEY, ls, useMic } from "./useMic";
+import { FilterProgress, TrimWave, sameSpan, type FilterJob, type Preview, type Span, type Who } from "./RecordFilter";
// ---------------------------------------------------------------------------
// THE RECORDING SESSION, the client half (RecordPage.tsx): one post at a time,
@@ -23,6 +24,23 @@ import { MIC_KEY, ls, useMic } from "./useMic";
// and a reload resumes; when the last part is in, the post's recorded take is
// made (trimmed, joined with the parts' pauses, levelled to the placeholder's)
// and PICKED.
+//
+// RECORD -> FILTER -> PREVIEW ("Filter before keeping": on when the post's
+// character has a stock voice to convert to; lib/report/recordPreview.mjs): the
+// last part in, the post WAITS -- each part's waveform with its cut marks (the
+// auto trim's answer, draggable), the pitch the converted read lands on, and
+//
+// f Filter: the character's recorded preset as ONE job (clean,
+// cut, convert), into a scratch dir -- no take -- then the raw
+// read and the filtered one play at one loudness
+// Enter Keep: the takes made from the preview's files (nothing is
+// converted again), picked, awaiting approval; the next post
+// not recorded yet is opened
+// Backspace / r Again: the preview dropped, the part recorded again
+//
+// The scratch dir (<project>/narration/.record-preview/<postId>.operator/) is
+// removed on Keep, on Again, and when the post or the page is left (unless its
+// Filter is still running: it is there when you come back).
// ---------------------------------------------------------------------------
type Part = { n: number; para: number; text: string; start?: number; seconds?: number; file?: string };
@@ -64,6 +82,12 @@ function SkipMarked({ text, skip }: { text: string; skip?: RecordItem["skip"] })
type Session = { count: number | null; parts: Record<string, { file: string; text: string; at: string }> };
const COUNT_KEY = "umtool.record.count-in";
+/** "Filter before keeping", when a person set it ("1" / "0"); unset: on for a post whose character converts. */
+const REVIEW_KEY = "umtool.record.filter-first";
+const RECORD_API = "/api/report/post-narration/record";
+/** The gain that plays a sound of `lufs` at the level of the quieter of the two (an <audio> can only turn down). */
+const levelFor = (lufs: number | null | undefined, other: number | null | undefined) =>
+ typeof lufs === "number" && typeof other === "number" && Number.isFinite(lufs) && Number.isFinite(other) ? Math.min(1, 10 ** ((Math.min(lufs, other) - lufs) / 20)) : 1;
const enc = encodeURIComponent;
const fileUrl = (project: string, rel: string) => `/api/report/file?project=${enc(project)}&path=${enc(rel)}`;
const postFileUrl = (project: string, rel: string) => `/api/report/post-item?project=${enc(project)}&file=${enc(rel)}`;
@@ -87,8 +111,113 @@ export default function RecordSession({ project, items: initial, start, box }: {
const [error, setError] = useState<string | null>(null);
const mic = useMic();
const kept = (n: number) => !!session.parts[String(n)] && session.count === parts.length;
+ // RECORD -> FILTER -> PREVIEW: who the post is read as, the preview as it stands, the marks and the pitch asked.
+ const [who, setWho] = useState<Who | null>(null);
+ const [reviewSet, setReviewSet] = useState<boolean | null>(null);
+ const [preview, setPreview] = useState<Preview | null>(null);
+ const [spans, setSpans] = useState<Span[]>([]);
+ const [pitch, setPitch] = useState("target");
+ const [semitones, setSemitones] = useState("0");
+ const [fjob, setFjob] = useState<FilterJob | null>(null);
+ const [now, setNow] = useState(0);
+ const [busy, setBusy] = useState<string | null>(null);
+ const [saved, setSaved] = useState<string | null>(null);
+ const [lastKept, setLastKept] = useState<string | null>(null);
+ const [stock, setStock] = useState<{ state: "idle" | "cached" | "asking" | "failed"; file?: string; error?: string }>({ state: "idle" });
+ // The microphone needs a secure context (localhost, https): a page opened from the LAN over http has none.
+ const [micOk, setMicOk] = useState(true);
+ useEffect(() => setMicOk(typeof window !== "undefined" && window.isSecureContext && !!navigator.mediaDevices?.getUserMedia), []);
+ useEffect(() => {
+ const v = ls.get(REVIEW_KEY);
+ setReviewSet(v === "1" ? true : v === "0" ? false : null);
+ }, []);
+ const converts = !!who?.convert?.voice;
+ // On by itself for a post whose character converts; while the next post's character loads it stays as it was.
+ const autoReview = useRef(false);
+ if (who) autoReview.current = converts;
+ const review = reviewSet ?? (who ? converts : autoReview.current);
+ const pitched = !!who?.convert?.engine && (who.pitchEngines ?? []).includes(who.convert.engine);
+ const semis = Number(semitones || 0);
+ const semisBad = pitched && pitch !== "target" && !(Number.isFinite(semis) && Math.abs(semis) <= 12);
+ const asked = pitched ? { pitch, semitones: pitch === "target" ? 0 : semis } : null;
useEffect(() => setCountIn(ls.get(COUNT_KEY) !== "0"), []);
+ const postOp = useCallback(
+ async (body: Record<string, unknown>) => {
+ const r = await fetch(RECORD_API, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, id: item.id, ...body }) });
+ const j = (await r.json().catch(() => ({}))) as Record<string, unknown>;
+ return { ok: r.ok, status: r.status, j };
+ },
+ [project, item.id],
+ );
+ // Who this post is read as (its direction, its convert), the preview a Filter left, the Filter still running.
+ const spanSource = useRef<string | null>(null);
+ const takePreview = useCallback((p: Preview | null) => {
+ setPreview(p);
+ if (!p) return;
+ setSpans(p.parts.map((x) => x.span ?? x.auto));
+ spanSource.current = p.source;
+ }, []);
+ const dropPreview = useCallback(() => {
+ setPreview(null);
+ spanSource.current = null;
+ setFjob(null);
+ }, []);
+ const loadWho = useCallback(async () => {
+ const r = await fetch(`${RECORD_API}?project=${enc(project)}&id=${enc(item.id)}&preview`, { cache: "no-store" });
+ const j = (await r.json().catch(() => ({}))) as Partial<Who> & { preview?: Preview | null; job?: FilterJob | null };
+ const w: Who = { character: j.character ?? null, convert: j.convert ?? null, recorded: j.recorded ?? null, synthetic: j.synthetic ?? null, pitchEngines: j.pitchEngines ?? [] };
+ setWho(w);
+ setPitch(j.preview?.filtered?.asked?.pitch ?? w.convert?.pitch ?? "target");
+ setSemitones(String(j.preview?.filtered?.asked?.semitones ?? w.convert?.semitones ?? 0));
+ takePreview(j.preview ?? null);
+ setFjob(j.job && j.job.state === "running" ? j.job : null);
+ return w;
+ }, [project, item.id, takePreview]);
+ // Whether the last part in WAITS (Filter before keeping), asked when it lands: what a person set, else whether the
+ // post's character converts -- the character awaited, so a part that lands before it has loaded is not kept at once.
+ const whoReady = useRef<Promise<Who | null>>(Promise.resolve(null));
+ const reviewAsked = useRef<boolean | null>(null);
+ reviewAsked.current = reviewSet;
+ const waits = useCallback(async () => reviewAsked.current ?? !!(await whoReady.current.catch(() => null))?.convert?.voice, []);
+ useEffect(() => {
+ setWho(null);
+ setPreview(null);
+ setSpans([]);
+ spanSource.current = null;
+ setFjob(null);
+ setSaved(null);
+ setStock({ state: "idle" });
+ whoReady.current = loadWho();
+ void whoReady.current.catch(() => {});
+ }, [loadWho]);
+ // LEAVING the post (another one, the page closed): its scratch dir goes -- unless its Filter is still running.
+ const running = useRef(false);
+ running.current = fjob?.state === "running";
+ const leaving = useRef<{ id: string; timer: ReturnType<typeof setTimeout> } | null>(null);
+ useEffect(() => {
+ // The same post again at once (a development build mounts an effect twice): it was not left.
+ if (leaving.current?.id === item.id) clearTimeout(leaving.current.timer);
+ leaving.current = null;
+ const id = item.id;
+ const wasRunning = () => running.current;
+ const drop = () => {
+ try {
+ navigator.sendBeacon(RECORD_API, new Blob([JSON.stringify({ project, id, op: "discard-preview" })], { type: "application/json" }));
+ } catch {
+ // no beacon here: the scratch dir is removed a day later (recordPreview.mjs)
+ }
+ };
+ const onHide = () => {
+ if (!wasRunning()) drop();
+ };
+ window.addEventListener("pagehide", onHide);
+ return () => {
+ window.removeEventListener("pagehide", onHide);
+ if (wasRunning()) return;
+ leaving.current = { id, timer: setTimeout(drop, 150) };
+ };
+ }, [project, item.id]);
// The post's session: what was kept before (a reload resumes at the first part not kept).
const loadSession = useCallback(async () => {
const r = await fetch(`/api/report/post-narration/record?project=${enc(project)}&id=${enc(item.id)}`, { cache: "no-store" });
@@ -110,6 +239,53 @@ export default function RecordSession({ project, items: initial, start, box }: {
}, [loadSession, item.id]);
const done = parts.length > 0 && parts.every((p) => kept(p.n));
+ // The post waits to be filtered and kept: every part in, "Filter before keeping" on.
+ const reviewing = review && done;
+ // The marks and the pitch the filtered read was made with: moved since, it is not what Keep would keep.
+ const filtered = preview?.filtered ?? (preview?.cleaned === "done" && preview.clean ? preview.clean : null);
+ const current =
+ !!preview?.raw && !!filtered && preview.parts.length === spans.length && preview.parts.every((p, k) => sameSpan(p.span, spans[k])) &&
+ (!preview.filtered || !asked || ((preview.filtered.asked?.pitch ?? "target") === asked.pitch && (preview.filtered.asked?.semitones ?? 0) === asked.semitones));
+
+ // The parts decoded once the last one is in: their waveforms and the auto trim's marks (no editor, no take).
+ const sessionAt = Object.values(session.parts).map((p) => p.at).join("|");
+ useEffect(() => {
+ if (!reviewing) return;
+ let live = true;
+ void (async () => {
+ const { ok, j } = await postOp({ op: "prepare" });
+ if (!live) return;
+ if (!ok) return setError(String(j.error ?? "the recording could not be read"));
+ const p = j.preview as Preview;
+ // Marks a person set stand for the same recording; a new recording starts from the auto trim's.
+ if (spanSource.current === p.source) setPreview(p);
+ else takePreview(p);
+ })();
+ return () => {
+ live = false;
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [reviewing, sessionAt, postOp, takePreview]);
+
+ // The Filter job, followed to its end.
+ useEffect(() => {
+ if (fjob?.state !== "running") return;
+ setNow(Date.now());
+ const clock = setInterval(() => setNow(Date.now()), 1000);
+ let live = true;
+ const poll = setInterval(async () => {
+ const r = await fetch(`${RECORD_API}?project=${enc(project)}&id=${enc(item.id)}&job=${enc(fjob.id)}`, { cache: "no-store" }).catch(() => null);
+ const j = (await r?.json().catch(() => null)) as { job?: FilterJob; preview?: Preview | null } | null;
+ if (!live || !j?.job) return;
+ setFjob(j.job);
+ if (j.job.state === "done" && j.preview) takePreview(j.preview);
+ }, 1000);
+ return () => {
+ live = false;
+ clearInterval(clock);
+ clearInterval(poll);
+ };
+ }, [fjob?.state, fjob?.id, project, item.id, takePreview]);
const finish = useCallback(async () => {
setPhase("finishing");
@@ -168,12 +344,123 @@ export default function RecordSession({ project, items: initial, start, box }: {
setError(`part ${p.n} was NOT saved: ${j.error ?? `HTTP ${r.status}`} — record it again`);
return;
}
+ // Another recording than the one a preview was made from: that preview is gone (the server dropped it too).
+ dropPreview();
setSession(j.session);
const s = j.session;
const next = parts.findIndex((q) => !(s.parts[String(q.n)] && s.count === parts.length));
- if (next < 0) await finish();
- else setCur(next);
- }, [phase, mic, parts, cur, project, item.id, finish]);
+ // The last part in: the take is made -- or, with "Filter before keeping", the post waits to be filtered and kept.
+ if (next >= 0) setCur(next);
+ else if (!(await waits())) await finish();
+ }, [phase, mic, parts, cur, project, item.id, finish, waits, dropPreview]);
+
+ // A sound file for the current part (a recording made elsewhere: a phone's recorder, the LAN where the mic is off).
+ const takeFile = useCallback(
+ async (file: File) => {
+ if (phase !== "idle" || !parts[cur]) return;
+ setError(null);
+ setPhase("saving");
+ const p = parts[cur];
+ const fd = new FormData();
+ fd.set("project", project);
+ fd.set("id", item.id);
+ fd.set("n", String(p.n));
+ fd.set("count", String(parts.length));
+ fd.set("text", p.text);
+ fd.set("para", String(p.para));
+ fd.set("part", file, file.name || `p${p.n}.wav`);
+ const r = await fetch(RECORD_API, { method: "POST", body: fd });
+ const j = (await r.json().catch(() => ({}))) as { session?: Session; error?: string };
+ setPhase("idle");
+ if (!r.ok || !j.session) return setError(`part ${p.n} was NOT saved: ${j.error ?? `HTTP ${r.status}`}`);
+ dropPreview();
+ setSession(j.session);
+ const sdoc = j.session;
+ const next = parts.findIndex((q) => !(sdoc.parts[String(q.n)] && sdoc.count === parts.length));
+ if (next >= 0) setCur(next);
+ else if (!(await waits())) await finish();
+ },
+ [phase, parts, cur, project, item.id, finish, waits, dropPreview],
+ );
+
+ // FILTER: the character's recorded preset as one job -- clean, cut at the marks, convert -- into the scratch dir.
+ const filter = useCallback(async () => {
+ if (!reviewing || phase !== "idle" || fjob?.state === "running" || semisBad) return;
+ setError(null);
+ setStatus(null);
+ const { ok, j } = await postOp({ op: "filter", spans, ...(asked ? { pitch: asked.pitch, ...(asked.pitch !== "target" ? { semitones: asked.semitones } : {}) } : {}) });
+ if (!ok || !j.job) return setError(String(j.error ?? "the Filter did not start"));
+ setFjob(j.job as FilterJob);
+ }, [reviewing, phase, fjob?.state, semisBad, postOp, spans, asked]);
+
+ // KEEP: the preview's files made the takes (when it is of these marks and this pitch), else the recording alone.
+ const keep = useCallback(async () => {
+ // No preview: the recording is still being read (a part just landed) -- there is nothing to judge or keep yet.
+ if (!reviewing || phase !== "idle" || fjob?.state === "running" || !preview) return;
+ setError(null);
+ setPhase("finishing");
+ const { ok, j } = await postOp({ op: "keep", filtered: current, spans, script: item.script });
+ setPhase("idle");
+ if (!ok || !j.picked) return setError(String(j.error ?? "it was not kept"));
+ const takes = (j.takes ?? []) as Array<{ step: string; file: string }>;
+ setItems((xs) => xs.map((x) => (x.id === item.id ? { ...x, recorded: true, plays: "recorded" } : x)));
+ setSession({ count: null, parts: {} });
+ setPreview(null);
+ spanSource.current = null;
+ const said = `kept post ${item.n}: ${takes.map((t) => `${t.step} (${t.file.split("/").pop()})`).join(", ")} — picked, awaiting approval`;
+ setLastKept(said);
+ // The next post not recorded yet (after this one, else before it); none: this one stays, and says so.
+ const order = [...items.keys()].filter((i) => i !== at);
+ const next = order.find((i) => i > at && !items[i].recorded) ?? order.find((i) => !items[i].recorded);
+ if (next === undefined) setStatus(`${said}. Every post is recorded.`);
+ else setAt(next);
+ }, [reviewing, phase, fjob?.state, preview, postOp, current, spans, item.script, item.id, item.n, items, at]);
+
+ // The pitch asked here, written back to the character (the Voices page's own write: POST /api/report/voices).
+ const voices = useCallback(
+ async (body: Record<string, unknown>) => {
+ const r = await fetch("/api/report/voices", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, ...body }) });
+ const j = (await r.json().catch(() => ({}))) as { error?: string; character?: { id?: string } };
+ return { ok: r.ok, j };
+ },
+ [project],
+ );
+ const saveToCharacter = useCallback(async () => {
+ const c = who?.character;
+ if (!c || !asked || semisBad) return;
+ setBusy("save");
+ setSaved(null);
+ const { ok, j } = await voices({ op: "character-set", scope: c.scope, id: c.id, convertPitch: asked.pitch, convertSemitones: String(asked.semitones) });
+ setBusy(null);
+ if (!ok) return setError(String(j.error ?? "the character was not changed"));
+ setSaved(`saved to ${c.name}${c.scope === "cast" ? " (the cast: every project)" : " (this video's own)"}`);
+ setWho((w) => (w ? { ...w, convert: w.convert ? { ...w.convert, pitch: asked.pitch, semitones: asked.semitones } : w.convert } : w));
+ }, [who, asked, semisBad, voices]);
+ // "Keep in this video only": the post's author given a character of this video's own (the narrator's convert with
+ // it, at the pitch asked here) -- the cast, and every other project, stay as they are.
+ const keepInVideo = useCallback(async () => {
+ if (!item.handle) return;
+ setBusy("keep-in-video");
+ setSaved(null);
+ const made = await voices({ op: "character-keep", who: `@${item.handle}` });
+ const id = made.j.character?.id;
+ if (!made.ok || !id) {
+ setBusy(null);
+ return setError(String(made.j.error ?? "the character was not made"));
+ }
+ const cv = who?.convert;
+ if (cv?.voice) {
+ const set = await voices({
+ op: "character-set", scope: "project", id, convertVoice: cv.voice, ...(cv.engine ? { convertEngine: cv.engine } : {}),
+ ...(asked ? { convertPitch: asked.pitch, convertSemitones: String(asked.semitones) } : {}),
+ });
+ if (!set.ok) setError(String(set.j.error ?? "its convert was not set"));
+ }
+ setBusy(null);
+ whoReady.current = loadWho();
+ await whoReady.current.catch(() => null);
+ setSaved(`${id} is this video's own character for @${item.handle} now`);
+ }, [item.handle, voices, who, asked, loadWho]);
const redo = useCallback(async () => {
if (phase !== "idle") return;
@@ -187,6 +474,19 @@ export default function RecordSession({ project, items: initial, start, box }: {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [phase, parts, cur, project, item.id, record, session]);
+ // AGAIN: the preview dropped, the current part recorded again.
+ const again = useCallback(async () => {
+ if (phase !== "idle" || fjob?.state === "running") return;
+ const p = parts[cur];
+ const { j } = await postOp({ op: "again", ...(p && kept(p.n) ? { n: p.n } : {}) });
+ if (j.session) setSession(j.session as Session);
+ setPreview(null);
+ spanSource.current = null;
+ setFjob(null);
+ if (micOk) await record();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [phase, fjob?.state, parts, cur, postOp, record, session, micOk]);
+
const go = useCallback((k: number) => {
if (phase !== "idle") return;
setAt((x) => Math.max(0, Math.min(items.length - 1, x + k)));
@@ -199,31 +499,56 @@ export default function RecordSession({ project, items: initial, start, box }: {
// A text box or a select keeps its keys; a checkbox (the count-in) does not -- Space still records.
if (tgt?.closest("textarea, select, input:not([type=checkbox])")) return;
if (ev.metaKey || ev.ctrlKey || ev.altKey) return;
+ // A key held down is one press: a held Space must not stop the recording it started, nor a held Enter keep twice.
+ if (ev.repeat) {
+ if ([" ", "Enter", "Backspace"].includes(ev.key) && !tgt?.closest("button, a, [role=slider]")) ev.preventDefault();
+ return;
+ }
+ // A button keeps its own Enter and Space (a cut mark keeps its arrows): the page's keys are for hands off it.
+ const onButton = !!tgt?.closest("button, a, [role=slider]");
+ // While the Filter runs the recording it reads is not recorded over: the keys wait for it (n / p still walk).
+ const filtering = fjob?.state === "running";
+ if (filtering && (ev.key === " " || ev.key === "r" || ev.key === "Backspace" || ev.key === "Enter" || ev.key === "f")) {
+ if (!onButton) ev.preventDefault();
+ return;
+ }
if (ev.key === " ") {
+ if (onButton) return;
ev.preventDefault();
if (phase === "recording") void stop();
- else void record();
- } else if (ev.key === "r") {
+ else if (micOk) void record();
+ } else if (ev.key === "r" || (ev.key === "Backspace" && reviewing)) {
ev.preventDefault();
- void redo();
+ if (reviewing) void again();
+ else if (micOk) void redo();
+ } else if (ev.key === "f" && reviewing) {
+ ev.preventDefault();
+ void filter();
} else if (ev.key === "Enter") {
+ if (onButton) return;
ev.preventDefault();
- if (done || item.recorded && !Object.keys(session.parts).length) go(1);
+ if (reviewing) void keep();
+ else if (done || item.recorded && !Object.keys(session.parts).length) go(1);
else if (phase === "idle") setCur((c) => Math.min(parts.length - 1, c + 1));
} else if (ev.key === "n") go(1);
else if (ev.key === "p") go(-1);
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
- }, [phase, stop, record, redo, done, item.recorded, session.parts, go, parts.length]);
+ }, [phase, stop, record, redo, done, item.recorded, session.parts, go, parts.length, reviewing, again, filter, keep, micOk, fjob?.state]);
// Play a kept part back, or the placeholder's part for reference.
const player = useRef<HTMLAudioElement | null>(null);
const stopAt = useRef<number | null>(null);
- const play = (src: string, from = 0, seconds: number | null = null) => {
+ const then = useRef<(() => void) | null>(null);
+ const [playing, setPlaying] = useState<string | null>(null);
+ const play = (src: string, from = 0, seconds: number | null = null, { volume = 1, what = null, after = null }: { volume?: number; what?: string | null; after?: (() => void) | null } = {}) => {
const a = player.current;
if (!a) return;
a.src = src;
+ a.volume = volume;
+ then.current = after;
+ setPlaying(what);
a.currentTime = 0;
const go2 = () => {
try {
@@ -245,6 +570,30 @@ export default function RecordSession({ project, items: initial, start, box }: {
else play(fileUrl(project, ph.file));
};
+ // The raw read and the filtered one, at ONE loudness: the louder of the two turned down to the other's.
+ const previewUrl = (which: string, n?: number) => `${RECORD_API}?project=${enc(project)}&id=${enc(item.id)}&preview&file=${which}${n ? `&n=${n}` : ""}&v=${enc(`${preview?.source ?? ""}.${fjob?.id ?? ""}.${spans.map((x) => `${x.from}-${x.to}`).join(",")}`)}`;
+ const playRaw = (after: (() => void) | null = null) => play(previewUrl("raw"), 0, null, { volume: levelFor(preview?.raw?.lufs, filtered?.lufs), what: "raw", after });
+ const playFiltered = () => play(previewUrl(preview?.filtered ? "filtered" : "clean"), 0, null, { volume: levelFor(filtered?.lufs, preview?.raw?.lufs), what: "filtered" });
+ // The character's stock voice reading the line: the cached read when there is one, else asked of the editor.
+ const playStock = async () => {
+ const text = parts[cur]?.text;
+ if (!text || stock.state === "asking") return;
+ setStock({ state: "asking" });
+ const { ok, j } = await postOp({ op: "stock", text });
+ if (!ok) return setStock({ state: "failed", error: String(j.error ?? "it could not be asked") });
+ let file = typeof j.file === "string" ? j.file : null;
+ for (let i = 0; !file && typeof j.jobId === "string" && i < 600; i += 1) {
+ await new Promise((res) => setTimeout(res, 1000));
+ const r = await fetch(`${RECORD_API}?project=${enc(project)}&id=${enc(item.id)}&stock&job=${enc(j.jobId)}&key=${enc(String(j.key))}`, { cache: "no-store" }).catch(() => null);
+ const st = (await r?.json().catch(() => null)) as { state?: string; file?: string; error?: string } | null;
+ if (st?.state === "failed") return setStock({ state: "failed", error: st.error ?? "the editor's read failed" });
+ if (st?.state === "done" && st.file) file = st.file;
+ }
+ if (!file) return setStock({ state: "failed", error: "the editor's read did not come" });
+ setStock({ state: "cached", file });
+ play(fileUrl(project, file), 0, null, { what: "stock" });
+ };
+
const recordedCount = items.filter((x) => x.recorded).length;
const btn = cn(buttonVariants({ variant: "outline", size: "sm" }));
const scale = 0.42;
@@ -342,8 +691,30 @@ export default function RecordSession({ project, items: initial, start, box }: {
/>
count-in
</label>
- <span className="text-text-2">Space record / stop · r redo the part · Enter next part · n / p next / previous post</span>
+ <label className="flex items-center gap-1" title="The last part in, the post waits: Filter runs its character's recorded preset (clean, cut, convert) into a preview, and Keep makes the takes. Off: the last part makes the recorded take at once.">
+ <input
+ type="checkbox"
+ checked={review}
+ disabled={phase !== "idle" || fjob?.state === "running"}
+ onChange={(e) => {
+ setReviewSet(e.target.checked);
+ ls.set(REVIEW_KEY, e.target.checked ? "1" : "0");
+ }}
+ data-record-review=""
+ />
+ Filter before keeping
+ </label>
+ <span className="text-text-2">
+ {reviewing ? "f Filter · Enter Keep · Backspace / r Again · n / p next / previous post" : "Space record / stop · r redo the part · Enter next part · n / p next / previous post"}
+ </span>
</div>
+ {!micOk && (
+ <div className="rounded border border-amber-400/50 bg-amber-400/10 px-3 py-2 text-[13px]" role="note" data-record-no-mic="">
+ <b>The microphone is off on this page.</b> A browser opens it only on <code>localhost</code> or over https, and this page was opened over plain http from another machine. Record on
+ the machine umtool runs on (<code>http://localhost:…</code>), or choose a sound file for a part below. Everything else works here: Filter a recording already made, listen to the
+ preview, move the cut marks, Keep.
+ </div>
+ )}
{/* The teleprompter: every part, the current one large. */}
<ol className="m-0 list-none space-y-2 p-0" data-record-teleprompter="">
@@ -381,6 +752,186 @@ export default function RecordSession({ project, items: initial, start, box }: {
{!parts.length && <li className="text-text-2">no script yet — write one on its bench</li>}
</ol>
+ {/* Who it is read as: the character, its direction (for the person reading: never sent to a model), its stock voice. */}
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2 text-[13px]" data-record-character={who?.character?.id ?? ""} data-record-character-layer={who?.character?.layer ?? ""}>
+ {who?.character ? (
+ <>
+ <span>
+ read as <b data-record-character-name="">{who.character.name}</b>
+ <span className="text-text-2">
+ {" "}
+ ({who.character.layer === "narrator" ? "the cast's narrator: this author has no character" : who.character.scope === "project" ? "this video's own" : "the cast"})
+ </span>
+ </span>
+ {who.recorded?.direction && (
+ <span className="text-[15px] italic text-amber-300" data-record-direction="">
+ “{who.recorded.direction}”
+ </span>
+ )}
+ {who.synthetic?.voice ? (
+ <button
+ type="button"
+ className={btn}
+ disabled={stock.state === "asking" || !parts.length}
+ onClick={() => void playStock()}
+ title="The character's synthetic voice reading this line (its synthetic preset; a recording is converted to its convert voice, which may be another): the read kept from before when there is one, else the editor is asked to synthesize it (Kokoro is quick; Orpheus is slow and takes the heavy slot)."
+ data-record-stock={stock.state}
+ >
+ {stock.state === "asking" ? "asking the editor…" : `▶ ${who.synthetic.voice} reads it`}
+ </button>
+ ) : (
+ <span className="text-text-2">no synthetic voice to hear it in</span>
+ )}
+ {stock.state === "failed" && <span className="text-[var(--color-blocking,#c33)]" data-record-stock-error="">{stock.error}</span>}
+ </>
+ ) : (
+ <span className="text-text-2" data-record-no-character="">
+ {who ? `no character reads @${item.handle || "this author"}: a recording is cleaned and kept in your own voice` : "…"}
+ </span>
+ )}
+ {who && (!who.character || who.character.layer === "narrator") && item.handle && (
+ <button type="button" className={btn} disabled={busy !== null} onClick={() => void keepInVideo()} title={`Give @${item.handle} a character of this video's own${who.convert?.voice ? ", converted as here" : ""}; the cast and every other project stay as they are.`} data-record-keep-in-video="">
+ Keep in this video only
+ </button>
+ )}
+ <a href={voicesHref(project, { who: who?.character?.id ?? (item.handle ? `@${item.handle}` : null) })} className="ink-link ml-auto" data-record-voices-link="">
+ Voices ›
+ </a>
+ </div>
+
+ {/* RECORD -> FILTER -> PREVIEW: the post waits -- its cut marks, the pitch, the Filter, the two reads, Keep / Again. */}
+ {reviewing && (
+ <div className="space-y-3 rounded border border-amber-400/40 p-3" data-record-review-panel="" data-record-preview-current={current ? "1" : "0"}>
+ {preview ? (
+ preview.parts.map((p, k) => (
+ <div key={p.n} className="space-y-1">
+ {preview.parts.length > 1 && <div className="micro">part {p.n}</div>}
+ <TrimWave part={p} span={spans[k] ?? p.auto} disabled={fjob?.state === "running"} onChange={(sp) => setSpans((xs) => xs.map((x, i) => (i === k ? sp : x)))} />
+ <button
+ type="button"
+ className="ink-link text-[12px]"
+ onClick={() => play(previewUrl("part", p.n), (spans[k] ?? p.auto).from, (spans[k] ?? p.auto).to - (spans[k] ?? p.auto).from, { what: `part-${p.n}` })}
+ data-record-play-cut={p.n}
+ >
+ ▶ what the marks keep
+ </button>
+ </div>
+ ))
+ ) : (
+ <div className="text-[12.5px] text-text-2">reading the recording…</div>
+ )}
+ {preview && !preview.trim.on && <div className="text-[12px] text-text-2" data-record-trim-off="">its edges are kept as recorded (the character's preset: trim off) — the marks still cut where you put them</div>}
+ {pitched && (
+ <div className="flex flex-wrap items-center gap-2 text-[12.5px]" data-record-pitch-row="">
+ <label className="flex items-center gap-1">
+ pitch
+ <select value={pitch} onChange={(e) => setPitch(e.target.value)} disabled={fjob?.state === "running"} aria-label="the pitch the converted read lands on" data-record-pitch="">
+ <option value="target">target — the stock voice's own</option>
+ <option value="source">source — the pitch you read it at</option>
+ <option value="contour">contour — your rises and falls, at its register</option>
+ </select>
+ </label>
+ <label className="flex items-center gap-1">
+ semitones
+ <input
+ type="number"
+ min={-12}
+ max={12}
+ step={0.5}
+ value={pitch === "target" ? "" : semitones}
+ disabled={pitch === "target" || fjob?.state === "running"}
+ onChange={(e) => setSemitones(e.target.value)}
+ placeholder="0"
+ className="w-16"
+ aria-label="semitones"
+ data-record-semitones=""
+ />
+ </label>
+ {semisBad && <span className="text-[var(--color-blocking,#c33)]">semitones is a number from -12 to 12</span>}
+ {who?.character && who.character.layer !== "narrator" && (
+ <button
+ type="button"
+ className={btn}
+ disabled={busy !== null || semisBad || ((who.convert?.pitch ?? "target") === asked?.pitch && (who.convert?.semitones ?? 0) === asked?.semitones)}
+ onClick={() => void saveToCharacter()}
+ title={`Write this pitch and these semitones to ${who.character.name}'s recorded preset${who.character.scope === "cast" ? " in the cast (every project)" : " (this video's own character)"}.`}
+ data-record-save-character=""
+ >
+ Save to character
+ </button>
+ )}
+ {saved && <span className="text-emerald-500" data-record-saved="">{saved}</span>}
+ </div>
+ )}
+ {!pitched && saved && <div className="text-[12.5px] text-emerald-500" data-record-saved="">{saved}</div>}
+ <div className="flex flex-wrap items-center gap-2">
+ <button
+ type="button"
+ className={cn(buttonVariants({ variant: current ? "outline" : "go", size: "sm" }))}
+ disabled={phase !== "idle" || fjob?.state === "running" || !preview || semisBad}
+ onClick={() => void filter()}
+ title="Run the character's recorded preset on this recording — clean, cut at the marks, convert — as one job. No take is made: the result is a preview."
+ data-record-filter=""
+ >
+ {current ? "Filtered ✓" : preview?.raw ? "Filter again (f)" : "Filter (f)"}
+ </button>
+ <button
+ type="button"
+ className={cn(buttonVariants({ variant: current ? "go" : "outline", size: "sm" }))}
+ disabled={phase !== "idle" || fjob?.state === "running" || !preview}
+ onClick={() => void keep()}
+ title={current ? "Make the takes from the preview's files (nothing is converted again): the recording, the cleaned one, the converted one — the last picked, awaiting approval." : "Keep the recording alone, cut at the marks: one recorded take, picked."}
+ data-record-keep=""
+ data-record-keep-what={current ? "filtered" : "recording"}
+ >
+ {current ? "Keep (Enter)" : "Keep the recording alone (Enter)"}
+ </button>
+ <button type="button" className={btn} disabled={phase !== "idle" || fjob?.state === "running"} onClick={() => void again()} title="Drop the preview and record the part again." data-record-again="">
+ Again (Backspace)
+ </button>
+ </div>
+ {!current && preview?.raw && filtered && fjob?.state !== "running" && <div className="text-[12.5px] text-amber-300" data-record-preview-stale="">the marks or the pitch moved since the Filter: Filter again to hear and keep them</div>}
+ {fjob && (
+ <FilterProgress
+ job={fjob}
+ now={now}
+ onCancel={() =>
+ void postOp({ op: "cancel", job: fjob.id }).then(({ j }) => {
+ const note = (j.editor as { note?: string } | undefined)?.note;
+ if (note) setError(note);
+ })
+ }
+ />
+ )}
+ {preview?.raw && filtered && fjob?.state !== "running" && (
+ <div className="flex flex-wrap items-center gap-2 text-[12.5px]" data-record-compare="">
+ <button type="button" className={btn} onClick={() => playRaw()} data-record-play-raw="" data-record-playing={playing === "raw" ? "1" : undefined}>
+ ▶ Raw
+ </button>
+ <button type="button" className={btn} onClick={() => playFiltered()} data-record-play-filtered="" data-record-playing={playing === "filtered" ? "1" : undefined}>
+ ▶ Filtered
+ </button>
+ <button type="button" className={btn} onClick={() => playRaw(() => playFiltered())} data-record-play-both="">
+ ▶ Raw, then filtered
+ </button>
+ <span className="text-text-2" data-record-compare-what="">
+ {preview.cleaned === "done" ? "cleaned" : "not cleaned"}
+ {preview.filtered ? ` · converted to ${preview.filtered.voice}${preview.filtered.engine ? ` by ${preview.filtered.engine}` : ""}${preview.filtered.pitch !== "target" ? ` · pitch ${preview.filtered.pitch}${preview.filtered.semitones ? ` ${preview.filtered.semitones > 0 ? "+" : "−"}${Math.abs(preview.filtered.semitones)} st` : ""}` : ""}` : " · not converted"}
+ {" · both at one loudness"}
+ </span>
+ </div>
+ )}
+ {preview?.raw && !filtered && fjob?.state !== "running" && (
+ <div className="text-[12.5px] text-text-2" data-record-nothing-filtered="">nothing filtered it: no clean engine answered and no character converts it — Keep keeps the recording alone</div>
+ )}
+ {(preview?.notes ?? []).map((n) => (
+ <div key={n} className="text-[12px] text-text-2" data-record-preview-note="">
+ {n}
+ </div>
+ ))}
+ </div>
+ )}
+
<div className="flex flex-wrap items-center gap-2">
{phase === "count" && (
<span className="text-[28px] font-bold tabular-nums" data-record-count={count}>
@@ -390,24 +941,44 @@ export default function RecordSession({ project, items: initial, start, box }: {
<button
type="button"
className={cn(buttonVariants({ variant: phase === "recording" ? "outline" : "go", size: "sm" }))}
- disabled={(phase !== "idle" && phase !== "recording") || !parts.length}
+ disabled={(phase !== "idle" && phase !== "recording") || !parts.length || !micOk || fjob?.state === "running"}
onClick={() => void (phase === "recording" ? stop() : record())}
data-record-toggle=""
>
{phase === "recording" ? "Stop (Space)" : `Record part ${parts[cur]?.n ?? 1} (Space)`}
</button>
- <button type="button" className={btn} disabled={phase !== "idle" || !parts.length} onClick={() => void redo()} data-record-redo="">
+ <button type="button" className={btn} disabled={phase !== "idle" || !parts.length || !micOk || fjob?.state === "running"} onClick={() => void redo()} data-record-redo="">
Redo part (r)
</button>
<button type="button" className={btn} disabled={phase !== "idle" || cur >= parts.length - 1} onClick={() => setCur((c) => c + 1)} data-record-next-part="">
Next part (Enter)
</button>
+ <label className={cn(btn, "cursor-pointer")} title="A sound file for this part instead of the microphone: a recording made elsewhere (any sound ffmpeg reads).">
+ Use a sound file…
+ <input
+ type="file"
+ accept="audio/*,video/webm,video/mp4"
+ className="sr-only"
+ disabled={phase !== "idle" || !parts.length || fjob?.state === "running"}
+ onChange={(e) => {
+ const f = e.target.files?.[0];
+ e.target.value = "";
+ if (f) void takeFile(f);
+ }}
+ data-record-file=""
+ />
+ </label>
{phase === "recording" && <span className="text-red-400" data-record-recording="">● recording part {parts[cur]?.n}</span>}
{phase === "saving" && <span className="text-text-2">saving the part…</span>}
- {phase === "finishing" && <span className="text-text-2">joining the parts into the take…</span>}
+ {phase === "finishing" && <span className="text-text-2">{reviewing ? "making the takes…" : "joining the parts into the take…"}</span>}
{status && <span className="text-emerald-500" data-record-status="">{status}</span>}
{error && <span className="text-[var(--color-blocking,#c33)]" data-record-error="">{error}</span>}
</div>
+ {lastKept && (
+ <div className="text-[12.5px] text-emerald-500" data-record-last-kept="">
+ {lastKept}
+ </div>
+ )}
{/* eslint-disable-next-line jsx-a11y/media-has-caption */}
<audio
ref={player}
@@ -415,6 +986,12 @@ export default function RecordSession({ project, items: initial, start, box }: {
onTimeUpdate={(e) => {
if (stopAt.current !== null && e.currentTarget.currentTime >= stopAt.current) e.currentTarget.pause();
}}
+ onEnded={() => {
+ const next = then.current;
+ then.current = null;
+ setPlaying(null);
+ next?.();
+ }}
data-record-player=""
/>
</section>
diff --git a/umtool/components/projects/VoicesPanel.tsx b/umtool/components/projects/VoicesPanel.tsx
@@ -4,14 +4,19 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { jobsHref, postBenchHref } from "@/lib/hrefs";
+import { PresetEditor, ProjectCharacters, recordedWords, type ItemCharacter, type PresetCharacter } from "./CharacterPresets";
// ---------------------------------------------------------------------------
// THE VOICES PANEL (components/projects/VoicesPage.tsx; /api/report/voices; the CLI is `umtool cast`). Works with
// the operator alone: nothing here needs an agent.
//
// the characters every author the project's reads use, the voice each reads in NOW and where it comes from
-// (cast · project · narrator · default), how many items it reads, its picked reads in another
-// voice (drift), its real voice (speakers.json) -- Audition opens the box below for it
+// (the item's own character · this video's · the cast · narrator · default), how many items it
+// reads, its picked reads in another voice (drift), its real voice (speakers.json) -- Audition
+// opens the box below for it; Presets opens its two presets (CharacterPresets.tsx); an author
+// with no character: "Add to the pool" / "Keep in this video only"
+// this video's own the characters that live in this video only (anonymous ones under a shown name), and the items
+// read as a character of their own
// the audition a line (its own words in this project, a stock line, or typed), 2-6 candidate stock voices
// (Kokoro fast, Orpheus heavy), Render: a job (the editor's tts; then the closeness to the real
// voice through the heavy slot), each candidate played side by side at ONE loudness, with its
@@ -22,23 +27,36 @@ import { jobsHref, postBenchHref } from "@/lib/hrefs";
// a recording a person's read of an item made a character's: kept, cleaned, converted to its stock voice
// ---------------------------------------------------------------------------
-type Voice = { engine: string; voice: string; spec: string; from: string };
+type Voice = { engine: string; voice: string; spec: string; from: string; speed?: number; character?: string };
type Drift = { id: string; handle: string; role: string; reads: string; want: string; from: string | null; kind: string; thread: boolean };
type Character = {
key: string; name: string; handles: string[];
- character: { id: string; name: string; voice: string; convert?: { engine?: string; voice?: string }; note?: string; narrator?: boolean } | null;
+ character: (PresetCharacter & { layer: "cast" | "project" }) | null;
items: number; context: number; itemIds: string[]; contextIds: string[];
voice: Voice; contextVoice?: Voice; weight: string;
reads: { id: string; role: string; spec: string; kind: string }[];
drift: Drift[]; speaker: string | null; lines: { item: string; text: string; own: boolean }[];
};
-type CastChar = { id: string; name: string; handles?: string[]; voice: string; convert?: { engine?: string; voice?: string }; speakers?: string[]; note?: string; narrator?: boolean };
+// What a recording of the character is made into: the stock voice, the engine, and the pitch the converted read
+// lands on (`umtool cast set <id> --convert-pitch source|contour|target --convert-semitones n`).
+type Convert = { engine?: string; voice?: string; pitch?: "target" | "source" | "contour"; semitones?: number };
+type CastChar = PresetCharacter & { voice: string };
+
+/** A convert entry's pitch in words — "follows your pitch", "your intonation at the voice's register +2 st" — "" for the stock voice's own. */
+function pitchWords(cv?: Convert): string {
+ if (!cv?.pitch || cv.pitch === "target") return "";
+ const n = Number(cv.semitones) || 0;
+ const st = n ? ` ${n > 0 ? "+" : "−"}${Math.abs(n)} st` : "";
+ return cv.pitch === "source" ? `follows your pitch${st}` : `your intonation at the voice's register${st}`;
+}
type Engine = { id: string; label: string; voices: string[]; defaultVoice: string; weight: string };
type View = {
project: string; castFile: string | null; castError?: string; map: Record<string, string>;
narrator: { engine: string; voice: string; spec: string; from: string; character: { id: string; name: string; voice: string } | null; recorded: { id: string; kind: string; voice: string }[] };
characters: Character[]; overrides: { handle: string; character: string; cast: string; project: string }[];
cast: CastChar[]; engines: Engine[]; convertEngines: string[]; running: { id: string; state: string; kind: string } | null;
+ // This video's own characters (narration/characters.json) and the items that name a character of their own.
+ own?: PresetCharacter[]; itemCharacters?: ItemCharacter[]; charactersError?: string;
};
type Candidate = { spec: string; engine: string; voice: string; weight: string; key: string; rel: string; cached: boolean; seconds: number | null; lufs: number | null; score: number | null };
type Audition = { character: { id: string; name: string; handles: string[]; voice: string | null }; text: string; from: string; speaker: string | null; reference: string | null; candidates: Candidate[] };
@@ -47,7 +65,7 @@ type Post = { id: string; handle: string; author: string; text: string };
const whoOf = (c: Character) => (c.character ? c.character.id : `@${c.handles[0]}`);
const pretty = (spec: string) => spec.replace(":", " · ");
-const FROM: Record<string, string> = { cast: "the cast", project: "this project", narrator: "the narrator's", default: "the default", override: "a read's own" };
+const FROM: Record<string, string> = { cast: "the cast", project: "this project", narrator: "the narrator's", default: "the default", override: "a read's own", item: "the item's own character" };
const fileUrl = (project: string, rel: string, v?: string | number | null) => `/api/report/file?project=${encodeURIComponent(project)}&path=${encodeURIComponent(rel)}${v ? `&v=${v}` : ""}`;
export default function VoicesPanel({ project, posts, initialWho = null }: { project: string; posts: Post[]; initialWho?: string | null }) {
@@ -67,6 +85,8 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro
const [queued, setQueued] = useState<string[] | null>(null);
const [rec, setRec] = useState<{ item: string; as: string; clean: boolean; convert: boolean; file: File | null }>({ item: posts[0]?.id ?? "", as: "", clean: true, convert: true, file: null });
const [drag, setDrag] = useState(false);
+ // The character whose presets are open: the cast's, or one of this video's own.
+ const [preset, setPreset] = useState<{ scope: "cast" | "project"; id: string } | null>(null);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const audios = useRef<Map<string, HTMLAudioElement>>(new Map());
@@ -219,6 +239,23 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro
});
};
+ const changed = (what: string) => {
+ setStatus(what);
+ void load();
+ void loadAudition();
+ };
+ // An author with no character: into the pool (the cast: the voice they read in now, everywhere) or this video only.
+ const poolAuthor = async (c: Character) => {
+ const j = await post({ op: "use", who: whoOf(c), voice: c.voice.spec, scope: "cast" });
+ if (j) changed(`${c.name} is in the pool now (${pretty(c.voice.spec)}), for every project`);
+ };
+ const keepHere = async (who: string, name: string) => {
+ const j = (await post({ op: "character-keep", who })) as { character?: { id: string } } | null;
+ if (!j) return;
+ changed(`${name} is a character of this video only`);
+ if (j.character?.id) setPreset({ scope: "project", id: j.character.id });
+ };
+
if (!view) return error ? <p role="alert" className="text-[12px] text-reject-text">{error}</p> : <p className="text-[12px] text-muted">reading the voices…</p>;
const input = "rounded-[3px] border border-seam-2 bg-ground px-1.5 py-[3px] text-[11.5px] text-text outline-none focus:border-signal";
@@ -230,6 +267,8 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro
const best = scored.length > 1 && scored[0] > scored[1] ? scored[0] : null;
const missing = (audition?.candidates ?? []).filter((c) => !c.cached).length;
const heavy = (audition?.candidates ?? []).some((c) => !c.cached && c.weight === "heavy");
+ const own = view.own ?? [];
+ const presetOf = preset ? (preset.scope === "project" ? own.find((c) => c.id === preset.id) : view.cast.find((c) => c.id === preset.id)) ?? null : null;
return (
<div className="space-y-5 text-[12.5px]" data-voices-panel={project}>
@@ -238,7 +277,7 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro
<h2 className="micro mb-1.5">
the characters · {view.characters.length}
<span className="ml-2 normal-case tracking-normal text-muted">
- a voice comes from a read's own choice, this project's map, the cast (every project), the narrator's, or the default — in that order
+ a voice comes from a read's own choice, the item's own character, this video's characters and map, the cast (every project), the narrator's, or the default — in that order
</span>
</h2>
{view.castError && <p className="m-0 mb-1 text-doubt-text" data-cast-error="">the cast is not read: {view.castError}</p>}
@@ -261,10 +300,13 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro
<td className={cell}>
<span className="font-medium text-text">{c.name}</span>
<span className="ml-1.5 font-mono text-[11px] text-muted">{c.handles.map((h) => `@${h}`).join(" ")}</span>
- {c.character && <span className="ml-1.5 rounded-[3px] border border-seam-2 px-1 text-[10.5px] text-signal-text" title="in the cast: the same voice in every project">cast</span>}
+ {c.character && c.character.layer !== "project" && <span className="ml-1.5 rounded-[3px] border border-seam-2 px-1 text-[10.5px] text-signal-text" title="in the cast: the same voice in every project">cast</span>}
+ {c.character?.layer === "project" && <span className="ml-1.5 rounded-[3px] border border-seam-2 px-1 text-[10.5px] text-text-2" data-voices-layer="project" title="a character of this video only">this video</span>}
+ {c.character?.anonymous && <span className="ml-1.5 rounded-[3px] border border-seam-2 px-1 text-[10.5px] text-doubt-text" title={`anonymous: “${c.character.shown}” on this page, in cast project and in recording notes — the cut's on-screen card is not anonymised yet: it still shows the post's author`}>anonymous</span>}
</td>
<td className={cell}>
<span className="font-mono text-[12px]" data-voice-now={c.voice.spec}>{pretty(c.voice.spec)}</span>
+ {typeof c.voice.speed === "number" && <span className="ml-1 font-mono text-[11px] text-text-2" data-voice-speed={c.voice.speed} title="its preset's speed">×{c.voice.speed}</span>}
{c.weight === "heavy" && <span className="ml-1 text-[10.5px] text-doubt-text" title="Orpheus pins ~8.5 GB while it reads">heavy</span>}
<div className="text-[11px] text-muted">from {FROM[c.voice.from] ?? c.voice.from}{c.contextVoice ? ` · as a context post: ${pretty(c.contextVoice.spec)} (${FROM[c.contextVoice.from] ?? c.contextVoice.from})` : ""}</div>
</td>
@@ -286,7 +328,27 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro
<td className={cn(cell, "text-text-2")} data-voice-speaker={c.speaker ?? ""}>
{c.speaker ?? <span className="text-muted" title="name it in speakers.json (the walk's Add to a voice) to score candidates against it">—</span>}
</td>
- <td className={cn(cell, "text-right")}>
+ <td className={cn(cell, "whitespace-nowrap text-right")}>
+ {c.character ? (
+ <button
+ type="button"
+ data-voices-preset-open={k}
+ onClick={() => setPreset({ scope: c.character!.layer, id: c.character!.id })}
+ className={buttonVariants({ variant: preset?.id === c.character.id && preset.scope === c.character.layer ? "pressed" : "outline", size: "sm" })}
+ title="its two presets: the synthetic voice and speed, and what a recording of them is made into"
+ >
+ Presets
+ </button>
+ ) : (
+ <>
+ <button type="button" data-character-pool-author={k} disabled={busy} onClick={() => void poolAuthor(c)} className={buttonVariants({ variant: "outline", size: "sm" })} title={`a cast character, reading in ${pretty(c.voice.spec)} in every project`}>
+ Add to the pool
+ </button>{" "}
+ <button type="button" data-character-keep={k} disabled={busy} onClick={() => void keepHere(k, c.name)} className={buttonVariants({ variant: "outline", size: "sm" })} title="a character of this video only — for someone who must not enter the pool">
+ Keep in this video only
+ </button>
+ </>
+ )}{" "}
<button
type="button"
data-voices-audition-open={k}
@@ -331,6 +393,35 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro
)}
</section>
+ {/* --- one character's presets --------------------------------------------------- */}
+ {preset && presetOf && (
+ <>
+ <PresetEditor key={`${preset.scope}:${preset.id}:${JSON.stringify([presetOf.name, presetOf.shown, presetOf.synthetic, presetOf.recorded])}`} c={presetOf} scope={preset.scope} engines={view.engines} convertEngines={view.convertEngines} busy={busy} post={post} onSaved={changed} onClose={() => setPreset(null)} />
+ {preset.scope === "cast" && !own.some((c) => c.id === preset.id) && (
+ <p className="m-0 -mt-3 text-[11.5px] text-text-2">
+ <button type="button" data-character-keep={preset.id} disabled={busy} onClick={() => void keepHere(preset.id, presetOf.name)} className="ink-link">
+ Keep in this video only
+ </button>{" "}
+ — a copy of {presetOf.name} for this video: change its presets here and the pool's stay as they are
+ </p>
+ )}
+ </>
+ )}
+
+ {/* --- this video's own characters ------------------------------------------------ */}
+ <ProjectCharacters
+ own={own}
+ cast={view.cast}
+ itemCharacters={view.itemCharacters ?? []}
+ posts={posts}
+ charactersError={view.charactersError}
+ busy={busy}
+ post={post}
+ onChanged={changed}
+ onOpen={(id) => setPreset({ scope: "project", id })}
+ open={preset?.scope === "project" ? preset.id : null}
+ />
+
{/* --- the audition ------------------------------------------------------------- */}
{chosen && (
<section className="rounded-[4px] border border-seam-2 p-3" data-audition-panel={whoOf(chosen)}>
@@ -455,7 +546,7 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro
<button type="button" data-audition-use="project" disabled={busy} onClick={() => void use(c.spec, "project")} className={buttonVariants({ variant: "outline", size: "sm" })}>
Use for this project
</button>
- <button type="button" data-audition-use="cast" disabled={busy} onClick={() => void use(c.spec, "cast")} className={buttonVariants({ variant: "outline", size: "sm" })} title="the cast: this character reads in it in every project">
+ <button type="button" data-audition-use="cast" disabled={busy || !!chosen.character?.anonymous} onClick={() => void use(c.spec, "cast")} className={buttonVariants({ variant: "outline", size: "sm" })} title={chosen.character?.anonymous ? "an anonymous character stays in this video: it never enters the pool" : "the cast: this character reads in it in every project"}>
Use everywhere
</button>
</div>
@@ -524,10 +615,15 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro
))}
</select>
<select data-recording-as="" value={rec.as} onChange={(e) => setRec({ ...rec, as: e.target.value })} className={input}>
- <option value="">as: the post's author (else the narrator)</option>
- {view.cast.map((c) => (
+ <option value="">as: the item's character, else the post's author (else the narrator)</option>
+ {own.filter((c) => c.voice || c.recorded).map((c) => (
+ <option key={`own:${c.id}`} value={c.id}>
+ as {c.anonymous ? c.shown : c.name} (this video{c.recorded?.convert?.voice ?? c.voice ? `: ${pretty(c.recorded?.convert?.voice ?? c.voice ?? "")}` : ""})
+ </option>
+ ))}
+ {view.cast.filter((c) => !own.some((o) => o.id === c.id)).map((c) => (
<option key={c.id} value={c.id}>
- as {c.name} ({pretty(c.convert?.voice ?? c.voice)})
+ as {c.name} ({pretty(c.convert?.voice ?? c.voice)}{pitchWords(c.convert) ? `, ${pitchWords(c.convert)}` : ""})
</option>
))}
</select>
@@ -577,13 +673,25 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro
<span className="ml-1.5 font-mono text-[11px] text-muted">{(c.handles ?? []).map((h) => `@${h}`).join(" ")}</span>
{c.narrator && <span className="ml-1.5 text-[11px] text-muted">the narrator</span>}
</td>
- <td className={cn(cell, "font-mono")}>{pretty(c.voice)}</td>
+ <td className={cn(cell, "font-mono")}>
+ {pretty(c.voice)}
+ {typeof c.synthetic?.speed === "number" ? ` ×${c.synthetic.speed}` : ""}
+ </td>
<td className={cn(cell, "text-[11px] text-text-2")}>
{c.convert ? `a recording → ${pretty(c.convert.voice ?? c.voice)}${c.convert.engine ? ` (${c.convert.engine})` : ""}` : ""}
+ {pitchWords(c.convert) && (
+ <span data-cast-pitch={c.id} title={`the pitch a converted read lands on: ${c.convert?.pitch}${c.convert?.semitones ? `, ${c.convert.semitones} semitones` : ""} — umtool cast set ${c.id} --convert-pitch target|source|contour --convert-semitones <n>`}>
+ {` · pitch: ${pitchWords(c.convert)}`}
+ </span>
+ )}
+ {recordedWords({ ...c, recorded: { ...c.recorded, convert: undefined } }) ? ` · ${recordedWords({ ...c, recorded: { ...c.recorded, convert: undefined } })}` : ""}
{c.speakers?.length ? ` · real voice: ${c.speakers.join(", ")}` : ""}
{c.note ? ` · ${c.note}` : ""}
</td>
- <td className={cn(cell, "text-right")}>
+ <td className={cn(cell, "whitespace-nowrap text-right")}>
+ <button type="button" data-cast-preset={c.id} onClick={() => setPreset({ scope: "cast", id: c.id })} className={buttonVariants({ variant: preset?.scope === "cast" && preset.id === c.id ? "pressed" : "outline", size: "sm" })}>
+ Presets
+ </button>{" "}
<button type="button" data-cast-remove={c.id} disabled={busy} onClick={() => void post({ op: "cast-rm", id: c.id }).then((j) => j && load())} className={buttonVariants({ variant: "quiet", size: "sm" })} aria-label={`remove ${c.name} from the cast`}>
✕
</button>
diff --git a/umtool/components/research/ConnectArchive.tsx b/umtool/components/research/ConnectArchive.tsx
@@ -0,0 +1,100 @@
+"use client";
+
+import { useState } from "react";
+import { useRouter } from "next/navigation";
+import { Button } from "@/components/ui/button";
+import { controlClass } from "@/components/ui/field";
+import { cn } from "@/lib/utils";
+
+// CONNECT AN ARCHIVE (demo epic D1), from the Source chip: type an origin, Read
+// it (its corpus.json: title, channels, videos — nothing saved), Connect. The
+// editor's `archives` action does both (POST /api/research/archives forwards),
+// so a connect here is the one /sites and `pnpm ops archives` make. Connected,
+// the page reloads its sources and the scope moves to the new one.
+
+type Probe = { origin: string; title: string; totals: { channels: number; videos: number }; channels: { slug: string; name: string; videoCount: number | null }[] };
+
+const nf = new Intl.NumberFormat("en-US");
+
+export default function ConnectArchive({ onConnected, onCancel }: { onConnected: (handle: string) => void; onCancel: () => void }) {
+ const router = useRouter();
+ const [origin, setOrigin] = useState("");
+ const [probe, setProbe] = useState<Probe | null>(null);
+ const [error, setError] = useState("");
+ const [busy, setBusy] = useState(false);
+
+ async function ask(dryRun: boolean) {
+ setBusy(true);
+ setError("");
+ try {
+ const r = await fetch("/api/research/archives", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ origin: probe?.origin ?? origin, dryRun }),
+ });
+ const b = await r.json();
+ if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`);
+ if (dryRun) setProbe(b.probe);
+ else {
+ router.refresh();
+ onConnected(`remote:${b.archive.origin}`);
+ }
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+ <form
+ aria-label="connect an archive"
+ className="flex basis-full flex-col gap-1.5 rounded-[3px] border border-seam-2 bg-panel p-2.5 text-[12.5px]"
+ onSubmit={(e) => {
+ e.preventDefault();
+ void ask(!probe);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ onCancel();
+ }
+ }}
+ >
+ <div className="flex flex-wrap items-center gap-2">
+ <input
+ autoFocus
+ aria-label="archive origin"
+ placeholder="https://jeralyzer.pages.dev"
+ value={origin}
+ onChange={(e) => {
+ setOrigin(e.target.value);
+ setProbe(null);
+ }}
+ className={cn(controlClass, "w-72 py-[3px] text-[12px]")}
+ />
+ <Button type="submit" size="sm" variant={probe ? "go" : "outline"} disabled={busy || !origin.trim()}>
+ {busy ? "Reading…" : probe ? "Connect" : "Read it"}
+ </Button>
+ <Button type="button" size="sm" variant="quiet" onClick={onCancel}>
+ Cancel
+ </Button>
+ </div>
+ {probe && (
+ <p data-archive-probe={probe.origin} className="text-text-2">
+ <span className="font-medium text-text">{probe.title}</span> · {nf.format(probe.totals.channels)} channels · {nf.format(probe.totals.videos)} videos
+ <span className="text-muted">
+ {" "}
+ — {probe.channels.slice(0, 8).map((c) => c.name).join(", ")}
+ {probe.channels.length > 8 ? `, and ${probe.channels.length - 8} more` : ""}
+ </span>
+ </p>
+ )}
+ {error && (
+ <p role="alert" className="text-bad">
+ {error}
+ </p>
+ )}
+ </form>
+ );
+}
diff --git a/umtool/components/research/ScopeBar.tsx b/umtool/components/research/ScopeBar.tsx
@@ -1,11 +1,15 @@
"use client";
-import { useEffect, useRef } from "react";
+import { useEffect, useRef, useState } from "react";
import { VIDEO_STATES, VIDEO_STATE_LABELS, type VideoState } from "yt-dlp-transcript-common/lib/availability";
import { badgeVariants } from "@/components/ui/badge";
import { controlClass } from "@/components/ui/field";
import { cn } from "@/lib/utils";
import type { Scope, ScopeSummary, SourceOption } from "@/lib/research/types";
+import ConnectArchive from "./ConnectArchive";
+
+// The Source select's last option: not a source, the Connect form (demo epic D1).
+const CONNECT = "connect:";
// ---------------------------------------------------------------------------
// The scope chips and the "holds …" line under them (canvas `.scope`): which
@@ -58,6 +62,7 @@ export default function ScopeBar({
onChange: (next: Scope) => void;
}) {
const ref = useRef<HTMLDivElement>(null);
+ const [connecting, setConnecting] = useState(false);
// One click outside closes an open chip.
useEffect(() => {
const close = (e: MouseEvent) => {
@@ -92,7 +97,10 @@ export default function ScopeBar({
aria-label="Source"
disabled={disabled}
value={source?.handle ?? ""}
- onChange={(e) => onChange({ source: e.target.value })}
+ onChange={(e) => {
+ if (e.target.value === CONNECT) setConnecting(true);
+ else onChange({ source: e.target.value });
+ }}
className={cn(controlClass, "max-w-[260px] py-[3px] text-[12px]")}
>
{sources.map((s) => (
@@ -101,6 +109,7 @@ export default function ScopeBar({
{s.detail ? ` · ${s.detail}` : ""}
</option>
))}
+ <option value={CONNECT}>Connect an archive…</option>
</select>
<Pop
@@ -207,6 +216,15 @@ export default function ScopeBar({
</>
)}
</div>
+ {connecting && (
+ <ConnectArchive
+ onCancel={() => setConnecting(false)}
+ onConnected={(handle) => {
+ setConnecting(false);
+ onChange({ source: handle });
+ }}
+ />
+ )}
</div>
);
}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -22,11 +22,12 @@ Inbox cannot disagree about what is wrong with one.
| `check [<project>] [--json]` | **exit 1 on anything blocking** — including an `out/`, `clips/` or `share-*/` link whose drive is not there (`storage-unreachable`) |
| `links <project> --embed-ids [--clips a,b] [--dry-run] [--json]` | the **published embed id**: every clip citing a Rumble URL-slug folder the archive does not serve gets `siteVideo` (the folder's `metadata.info.json` id, shareLine.mjs `siteVideoFor`), a citeUrl naming the folder moved with it; no network, one write, one undo point. The Cut tab's Project › Rumble cites ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) |
| `links <project> [--json] [--fix]` | do the clip QRs open on their sites? `corpus.json` → the channel's manifest → `slugToPage` → the shard's record, one request at a time, shards from the cue cache; recorded in `out/links.json`, which `check` reads (`link-dead` blocking, `links-unverified`, `links-unchecked`); `--fix` rewrites a Twitch id the site serves as `v<id>`, and a Rumble folder id (the URL slug) as the embed id the site serves (the clip gets `siteVideo`); **exit 1** when a link is dead ([knobs.md](knobs.md#do-the-qr-links-open)). The same record dates each site's deploy: a cited video newer than it is `site-deploy-behind` ([knobs.md](knobs.md#the-sites-the-links-depend-on)) |
-| `cast [ls] \| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--convert-engine e] [--convert-voice v] [--narrator] \| set <id> … \| rm <id> \| undo [--json]` | **THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects and their STOCK voices, a layer under each project's voice map; one writer, an undo point a write |
-| `cast project <project> [--json]` · `cast use <project> <character\|@handle> <voice> [--everywhere]` · `cast reread <project> <character> [--dry-run]` | a project's characters (each voice now, where it comes from, its stale reads), the voice for this project or everywhere, and the re-reads that asks for |
+| `cast [ls] \| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--speed s] [--convert-engine e] [--convert-voice v] [--convert-pitch target\|source\|contour] [--convert-semitones n] [--enhance on\|off] [--trim on\|off] [--trim-pad ms] [--direction "…"] [--narrator] \| set <id> … \| rm <id> \| undo [--json]` | **THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects, one writer, an undo point a write. **A character is a PRESET**, two of them ([knobs.md](knobs.md#a-character-is-a-preset)): `synthetic` -- the STOCK voice it reads in (`--voice`) and its speed (`--speed` 0.5–2; Orpheus has none) -- and `recorded` -- what a recording of them is made into: the stock voice (`--convert-voice`; a file or a recording is refused), the engine, the **pitch** the converted read lands on (`--convert-pitch`: `target` the stock voice's own, `source` the pitch it was read at, `contour` the read's rises and falls at the stock voice's register; `--convert-semitones` -12…12 moves a followed one), whether it is cleaned first (`--enhance`), its edges trimmed to speech (`--trim`, `--trim-pad` the ms kept either side) and a `--direction` (one line for the person reading, never sent to a model). `set` lays the flags given over the presets; `default` for one takes that key off; `--no-convert`, `--no-speed`. A version 1 file (`voice`, `convert` at a character's top) reads as these presets and the first write makes it version 2 (`undo` puts the old file back). A followed pitch on an engine that has none, semitones with nothing followed, a speed or a pad out of range: **exit 1** |
+| `cast project <project> [--json]` · `cast use <project> <character\|@handle> <voice> [--everywhere]` · `cast reread <project> <character> [--dry-run]` | a project's characters: each one's voice now (and speed) and **where it comes from** -- the chain one read asks, first hit wins: the command's flags, the item's own character (`posts character`), this video's character for the author (then its voice map), the cast's, the narrator's, the default -- what a recording of them is made into, its stale reads; this video's own characters; the items that name their own. `use`: the voice for this project (its own character's when it has one for them, else the voice map) or everywhere, and the re-reads that asks for |
+| `cast project <project> add <id> [--name "…"] [--voice <engine:voice>] [--handles a,b] [--anonymous [--shown "…"]] [the preset flags]` · `set <id> … [--no-voice] [--no-anonymous]` · `rm <id>` · `undo` · `pool <id>` · `keep <character\|@handle> [--anonymous]` `[--json]` | **THIS VIDEO's OWN CHARACTERS** (`<project>/narration/characters.json`, [knobs.md](knobs.md#this-videos-own-characters-and-an-items-own)): the cast's shape and the cast's writer (a token, an undo point a write, atomic, a broken file never overwritten), for people who must not enter the pool. `--anonymous`: it goes by a **shown name** (`--shown`; default the next of `Anon 1`, `Anon 2` …) on the Voices page, in `cast project` and in a recording's note, and never enters the pool; **the on-screen card is not anonymised yet** (it still shows the post's author). `--voice` is optional here: a character with none leaves the voice to the layers under it. `narration/voices.json` keeps working under it (a handle in it reads as a character with only a synthetic voice) and is never rewritten by these. `pool <id>` (**Add to the pool**) moves one into the cast -- an anonymous one, or an id the cast has, is refused; `keep` (**Keep in this video only**) copies a cast character here (its presets changed for this video alone), or gives an author with no character one, in the voice they read in now. A refusal: **exit 1**, nothing written |
| `cast audition <character\|@handle> --voices a,b,… [--project <p>] [--text "…" \| --item <id> \| --line <n> \| --stock] [--no-score \| --score-only] [--json] [--progress ndjson]` | **AN AUDITION**: one line read by 2-6 stock voices through the editor's tts op, levelled to -20 LUFS in `<p>/narration/auditions/` (cached), scored for closeness to the character's real voice (`speakers.json`; TitaNet, local) |
| `speaker-check <project> [--clip <id> …] [--json] [--progress ndjson]` · `--set 'Name=<clip>,<channel>/<id>,channel:<slug>'` · `--remove <name>` · `--list` | which of the project's **named voices** (`speakers.json`) each clip is: TitaNet-small, local, against each voice's robust centroid → `<project>/speaker-check.json` (merged); the walk's **Speaker:** badge and **Check speaker** ([report-video.md](report-video.md#the-speaker-check-on-the-walk-which-of-several-voices)) |
-| `quote-check <project> [--clips a,b] [--pad S] [--json]` · `quote-check <project> --status` | **is each clip's quote in the seconds it plays?** The cut ±15 s of the source the render would cut it from, transcribed by the editor (`pnpm ops transcribe`, words on — its transcription lane), the quote found in those words and in the cues: `ok`, `moved` (heard more than 0.5 s from where the cues have it), `not-found`; rows in `quote-check.json`, stale when the cut or the quote changes; `check` blocks on `moved`/`not-found` (`clip-quote-moved`, `clip-quote-missing`), a take refuses them, `prep --status` counts them ([knobs.md](knobs.md#the-quote-check-is-the-quote-where-the-clip-plays)) |
+| `quote-check <project> [--clips a,b] [--pad S] [--json]` · `quote-check <project> --status` | **is each clip's quote in the seconds it plays?** The cut ±15 s of the source the render would cut it from, transcribed by the editor (`pnpm ops transcribe`, words on — its transcription lane), the quote found in those words and in the cues: `ok`, `moved` (heard more than 0.5 s from where the cues have it), `not-found`; rows in `quote-check.json`, stale when the cut or the quote changes; the editor's work files go to `<project>/.quote-check/`, never under `out/` (a link onto a media drive the editor will not write in); `check` blocks on `moved`/`not-found` (`clip-quote-moved`, `clip-quote-missing`), a take refuses them, `prep --status` counts them ([knobs.md](knobs.md#the-quote-check-is-the-quote-where-the-clip-plays)) |
| `check-joins <project> --take <id> [--json] [--all] [--limit <n>]` | do a rendered take's **post joins carry on**: every boundary of its master where the next post item draws a post the one before showed, its planned join, the SSIM across it and the largest frame-to-frame step (read-only, ffmpeg) -- worst first ([report-video.md](report-video.md#thread-scenes-whole-threads-the-join-manual-threads-wide-attachments-context-media-link-visits-the-branch-map)) |
| `link-policy <project> [--via <site id \| https://…>] [--direct <slug,…>] [--clear] [--fix] [--json]` | the project's **link policy** (`provenance.linkPolicy`): cite via site X, these channels direct. With no flag, prints it and every clip whose QR breaks it; `--fix` rewrites each one that has a fix through the window writer; new clips are written by it. **Exit 1** when a clip still breaks it ([knobs.md](knobs.md#the-link-policy)) |
| `patch-markers <project> [<file>.patch.json] [--fix] [--json]` | take patches whose deck markers name a clip not in the cut (a take made with one is refused); `--fix` gives each the `after` of the cut's marker of the same label; **exit 1** when one is left ([knobs.md](knobs.md#take-patches-follow-a-removal)) |
@@ -45,14 +46,14 @@ Inbox cannot disagree about what is wrong with one.
| `review-pass <project> [ls] [--json]` · `review-pass <project> mark <block> keep\|fix\|clear [--note T]` | the workspace's **review pass** (`?mode=review`): every block but the intro and a clip rejected for a cut reason, its answer and the block the pass resumes on; a Fix ("needs work", saying what) is a mark in `<project>/review-pass.json` on any block, a clip too — never a clip's verdict (`incorrect` is the bench's fact-error ruling, never written or overwritten here); a clip's Keep is its walk verdict (`window --verdict confirmed`), a post's or a card's a mark — `mark` writes one (a Fix needs `--note`; a clip takes `fix` and `clear`) ([knobs.md](knobs.md#the-review-pass)) |
| `review-pass <project> verdict like\|maybe\|no\|clear [--note T] [--json]` | the pass's **verdict on the draft**, one locked call: a draft that differs from its parent version only by what the walk and the review pass write (verdict, correction, reason, reject note, walk note, ★) judges the PARENT and saves nothing; otherwise the draft is saved as the next version and that is judged (`takes/verdicts.json`) |
| `present <project> [--take <take> \| --cut] [--json] [--public] [--open] [--url <origin>]` | **present mode**: the cut as slides, navigated like a deck (`/projects/<p>/present`) — prints the address and every slide (its kind, id — a post's `<channel>/<id>`, a clip's id, `section-<n>`, `day-<YYYY-MM-DD>` — date, words and censor counts); `--json` the payload (each post's card as Play draws it and its censor data by kind, each clip's spans, the dividers); `--public` the payload a public page would carry (censored, no reveal data); `--open` opens it; `<address>#<slide id>` opens a slide ([knobs.md](knobs.md#present-mode-the-cut-as-slides-navigated-like-a-deck)) |
-| `set <project> <clip> key=value …` | a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)); `key=` clears one ([knobs.md](knobs.md#marks)) |
+| `set <project> <clip> key=value …` | a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)); on ANY entry (a post item, a still, a clip) `hideModules=diet,streak`, `shelfNote='…'` and `chapter='…'` (its name in the chapter list, one line of at most 100 characters; `chapter=` none); `--take <t>` writes the entry knobs into that take's patch; `key=` clears one ([knobs.md](knobs.md#marks)) |
| `intro <project> [key=value …] [--off] [--json]` · `intro <project> --take <take> --off\|--on` | **the intro** the cut opens on (`render.intro`): with no key, prints it as written, what the cut opens with (a `title-card`'s words resolved) and each version's on/off; `key=value` writes it through the look writer (`style` `seconds` 3.5–8 `mark` `ground` `sound` (`false` silent) `site` `title` `lines` (`a\|b`, ≤ 3) and the brand's keys; `key=` clears one; a new intro starts as `boot-dark`); `--off` takes it off the cut; `--take <t> --off` that version opens on no intro (its patch's `render.intro: null`), `--on` on the cut's again. **Exit 1** on a value the build refuses ([knobs.md](knobs.md#the-intro-played-and-edited)) |
-| `look <project> key=value … [--unset render.<key>]…` | the cut's **knobs**: `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\|label\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys — `mode=basic\|deck` (the footage alone, [knobs.md](knobs.md#basic-output-the-footage-alone)) and `basic=<json>` (its fades) among them ([knobs.md](knobs.md)) **The deck on, legacy keys off** (`updateRenderKeys`, one write, an undo point `revisions/…auto-render-keys…` first): `chrome.layout=deck` turns the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck), `--unset render.<key>` (repeatable) drops a legacy render key -- only `rail` `chromeEngine` `railEngine` `chromeRegions` `claimSchedule` `wordmark` `title` `finale` `cut`; the deck beside the old rail is refused in the build's words unless the same command drops it; deck.* keys in the same command land after the chrome exists. Another key named: **exit 2** |
+| `look <project> key=value … [--unset render.<key>]… [--take <t>]` | the cut's **knobs** (`--take <t>`: the `deck.*` keys given are set on that take -- its patch, an undo point of its own, the project's manifest untouched; the other knobs are the project's): `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\|label\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys — `mode=basic\|deck` (the footage alone, [knobs.md](knobs.md#basic-output-the-footage-alone)) and `basic=<json>` (its fades) among them ([knobs.md](knobs.md)) **The deck on, legacy keys off** (`updateRenderKeys`, one write, an undo point `revisions/…auto-render-keys…` first): `chrome.layout=deck` turns the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck), `--unset render.<key>` (repeatable) drops a legacy render key -- only `rail` `chromeEngine` `railEngine` `chromeRegions` `claimSchedule` `wordmark` `title` `finale` `cut`; the deck beside the old rail is refused in the build's words unless the same command drops it; deck.* keys in the same command land after the chrome exists. Another key named: **exit 2** |
| `variants <project> [--take <t>] [--list] [--json]` | **Make variants**: the encode ladder of the build (or of a take's); `--list` what was made and the build's sync report, each clip's lag (past a frame flagged) ([knobs.md](knobs.md)) |
| `corrections <project>` | what the report got wrong (the clip bench's sixth field) and the walk's coverage, as markdown for the next pass |
| `build <project> [--preset preview\|fast\|final] [--only ID]` | **prints** the chain |
| `build <project> --run [--url URL] [--replace] [--preset P] [--only ID] [--skip-fetch]` | **runs** it as the app's build job (POST `/api/report/build` on `--url`, else `UMTOOL_URL`, else `http://localhost:3050`), prints its log as it grows, **Ctrl-C** cancels the job (twice leaves it running); `--replace` stamps a deliverable newer than the manifest aside; exit 1 unless the job is done (release 36) |
-| `chain <article> <n> [--from <step>] [--dry] [--final] [--draft-all [--model M]]` | an iteration to a video: the Iterations tab's **Make the video** (`--draft-all`: Draft everything) |
+| `chain <article> <n> [--from <step>] [--dry] [--final] [--draft-all [--model M]] [--stop-before-render] [--allow-whole-recording]` | an iteration to a video: the Iterations tab's **Make the video** (`--draft-all`: Draft everything, which fetches the windows of the clips the drafted cut kept, `cut-windows`); `--stop-before-render` is **Stop before render** (it ends before the voices); `--allow-whole-recording` is **Fetch the whole recordings** (a remote-only channel's Rumble windows, refused with their size otherwise) |
| `index [--rebuild] [--prune] [--since MS] [--json]` | the cache |
| `new <slug> [--from <report.md>\|<share URL>\|<channel>/<id>] [--site-origin URL] [--seed chapters\|frames [--target S]]` · `new <folder>/<slug> …` · `new <slug> --folder <folder> …` · `new <slug> --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]` · `new <slug> --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO\|auto [--segment sN]] [--no-analyze]` | scaffold; `<folder>/<slug>` (or `--folder`) makes it in a folder of the reports tree — its id `<folder>/<slug>`, routed `/projects/<folder>/<slug>` (a spin-off beside its parent); a folder that is itself a project, the reserved `at`, or one past the walk's four levels is refused |
| `new <slug> --from-posts <channel> [--channel <more>…] [--since D] [--until D] [--own] [--with-media] [--replies …] [--order …] [--limit N]` | a **posts reel**: the scaffold with the deck on (no `siteOrigin`: each post's QR opens the post, `deck.qr.links: "original"`), then `posts reel` with the same filters |
@@ -90,7 +91,7 @@ Inbox cannot disagree about what is wrong with one.
| `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s) and its start back into the one before, so the crossfade lands in quiet, each move said (`--no-snap`: the edges as written), crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) · `--reel <name> [--take <t>]`: a **beat reel** -- its own beats file (`promo/<name>-beats.json`), crossfade, intro (one rendered for the reel when the master has none, or the reel's own) and outro card (the title, the call to action, an image, the site's name; faded in from the last beat, held to the end), written to `<slug>.<name>.mp4`; no `--take`: its pinned take, else the one it was last cut from, else the latest finished master ([report-video.md](report-video.md#beat-reels)) |
| `trailer-beats <project> [ls] [--json]` · `add <clip> [<from>-<to>] [--at N] [--label L]` · `add-raw <at> <dur>` · `set <n> <from>-<to>` · `remove <n>` · `move <n> --to <m>` · `order` · `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok>` · `xfade <s>` · `intro on\|off\|'<render.intro JSON>'` · `outro on\|off\|none\|'{title,text,image,seconds}'` · `candidates [--add]` · `verdict <n> confirmed\|note\|clear` · `title <text>\|none` · `take <t>\|none` · `undo` · `reels [--json]` · `new-reel <name> [--from <reel>] [--title T]` · `gap <n> add <from>-<to>\|remove <s>\|clear` · `status [--take <t>] [--json]` · `anchor [<n>…] --take <t>` · `clamp <n>` · `repoint <n> <clip>` · `history [--json]` · `--take <t>` on an edit · `--reel <name>` on any | **the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads) or another **beat reel's** (`--reel`: `promo/<name>-beats.json`): each beat's length, the running length against the platform limit (X 2:20 by default), beats outside their clip's window, the cut's order, the walk's ★ clips; the reel's own intro and its outro card (`ls`: `· outro 3.5 s`, counted in the length); every write an undo point and a history entry; a beat's gaps (two moments of one clip as one beat of jump cuts); each beat read against the take now -- what it was cut against, what changed (`status`), and the fixes ([knobs.md](knobs.md#the-trailers-beats), [reels track their source](knobs.md#reels-track-their-source)) |
| `tighten <project> [--json] [--all] [--no-measure]` · `tighten <project> --apply <clip>[,<clip>…]` | the Cut tab's **Propose tight windows**: each clip to its sentence (the sentences its cut touches, else the whole ones inside its window) and each edge into its pause (the build's measured silences and the gaps between the recording's timed words, ≤ 1 s, inside the cached window) — before → after with the seconds, the clips that would change (`--all`: every clip); prints only. `--apply` writes the named rows through the window writer (the token, the cite that follows the edge); a lock is kept (it is against `resolve-windows`, not a person) ([knobs.md](knobs.md#tighten-to-the-sentence-snap-to-a-pause)) |
-| `ledger <project> [ls] [--scope S] [--population P] [--json]` · `ledger <project> add <id> --date D --scope S --population P [--value V] --scopeBasis "…" [--<key> V …] [--row '{…}']` · `ledger <project> set <id> --<key> V … [--unset k,k]` · `ledger <project> rm <id>` | a **measure ledger's rows** (`ledgerSchema.kind "measure"`), the only writer of them: each row is checked against the schema -- a track, a form (and the promise forms `promise` / `promise_check`), a number in its unit or a declared regime with an event, the six adjudication fields (a new row defaults `scopeConfidence` read, `valueKind` uttered, `flags` []; `--scopeBasis` is never defaulted), the declared fields, and the instruments' own keys: `run` (a loss claim's run), `retro` (a loss told in the past with no `asOf`: off the odometer), `promise`, `kept`, `due`, `speaker` (another party's key: her rows move none of his numbers), `paidOn`, `outcome` (a `promise_outcome`'s: kept, refunded, withdrawn); the promise forms are `promise`, `promise_check`, `promise_claim`, `promise_outcome`. `rm` refuses a row an entry pins or another row names ([knobs.md](knobs.md#the-measure-slice-the-weight-instruments)) |
+| `ledger <project> [ls] [--scope S] [--population P] [--json]` · `ledger <project> add <id> --date D --scope S --population P [--value V] --scopeBasis "…" [--<key> V …] [--row '{…}']` · `ledger <project> set <id> --<key> V … [--unset k,k]` · `ledger <project> rm <id>` | a **measure ledger's rows** (`ledgerSchema.kind "measure"`), the only writer of them: each row is checked against the schema -- a track, a form (and the promise forms `promise` / `promise_check`), a number in its unit or a declared regime with an event, the six adjudication fields (a new row defaults `scopeConfidence` read, `valueKind` uttered, `flags` []; `--scopeBasis` is never defaulted), the declared fields, and the instruments' own keys: `run` (a loss claim's run), `retro` (a loss told in the past with no `asOf`: off the odometer), `promise`, `kept`, `due`, `speaker` (another party's key: her rows move none of his numbers), `paidOn`, `outcome` (a `promise_outcome`'s: kept, refunded, withdrawn), `stampNote` (a `promise_outcome`'s: the words under its stamp on the promise clock in place of "by <date> · no video" -- `ledger <p> set <row> --stampNote "…"`, `--stampNote null` for the clock's own words again; one line, the strip over a post's card shows its first clause, and `umtool lint` warns past 26 characters); the promise forms are `promise`, `promise_check`, `promise_claim`, `promise_outcome`. `rm` refuses a row an entry pins or another row names ([knobs.md](knobs.md#the-measure-slice-the-weight-instruments)) |
| `measure <project> [--take <t>] [--scopes a,b] [--scale MIN-MAX] [--as-of YYYY-MM-DD] [--json]` | the **measure slice** the instruments draw from (`render.chrome.deck.measure`; the flags override it): each row in scope the cut shows at the cut second its figure is said, the hidden rows, and the totals -- the odometer's runs, NET, the goals, the diets, the promises. The take's built `schedule.json` with `--take`, else an estimate; `--json` prints the slice. Reads only ([knobs.md](knobs.md#the-measure-slice-the-weight-instruments)) |
| `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) |
| `fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` · `… --refetch <clipId>[,…]` · `… --refetch-video <slug>/<id>` · `… --take <take>` | **Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. `--refetch <clipId>[,<clipId>…]` evicts the cached windows that OVERLAP those clips' fetch spans first (the editor's `evict-clips` `{slug, id, covering}`, one job per video, waited for), then fetches as usual — for windows known bad (cut from a corrupt saved video); `--refetch-video <slug>/<id>` does it for every window the project asks of that video; with `--dry-run` the eviction is a dry run too and names what it would remove. `--take <take>` asks for a TAKE's clips instead — its manifest as its walk reads it (the project's now with the take's patches; a draft's too, nothing rendered), so a clip only the take has is fetched; the run is recorded with `take`, and `--status --take` follows the take's last run (the cut's never reads a take's). Every run is recorded in `<project>/fetch-runs.json` (a refetch's evictions under `refetch`). Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins)) |
@@ -130,10 +131,11 @@ Inbox cannot disagree about what is wrong with one.
| `posts progress <project> [auto\|on\|off\|default] [--json]` | the cut's **progress bar** default (`render.posts.progress`, `updatePostProgressRender`; [report-video.md](report-video.md#the-progress-bar)); bare, which items draw it |
| `posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]` | a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**) |
| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs= pace=fast\|normal]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said "at <handle>", the lexicon first; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans. |
-| `posts narrate <project> <item> --take --thread [--parents 0\|all\|none\|<n>] [--skip-parent <id\|parent:i>]… [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--note "…"] [--force] [--no-hold] [--dry-run] [--json]` | a **THREAD READ** as one command ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read), `lib/report/postThreadRead.mjs`): the post it answers (`--parents all`: every ancestor; `<n>`: parents 0..n; `none`), the post it quotes and the posts it links to, then his words, in DATE order, each in its author's voice (`--voice-for`, then the project's voice map, `posts voices`; his own: the narrator's), the redaction, the slur filter (a beep is skipped: a joined read is not word-timed) and the lexicon (`posts say`) applied. A parent or quoted post the item before already shows is not read again (`--read-seen`: it is). Each part is synthesized ONCE by the editor's tts op into `narration/parts-cache/<sha1(voice\|text)>.wav` (the transcription lane held meanwhile, only if it was not; `--no-hold`: left alone), joined (0.8 s between pieces, 0.6 between paragraphs, 0.25 inside one) into `take-<n>.<engine>-thread.wav` with `take-<n>.parts.json`, saved with its parts' roles, its lexicon and how it was asked (`read`) and PICKED — one write (one undo point). `--dry-run`: the pieces, voices and parts (cached or not), nothing asked. Already up to date (same words and voices): nothing done, **exit 0** (`--force`: again). A part not synthesized: **exit 1** (the parts made stay cached; run it again); `--json` prints `{ok: false, error}` too. A usage error: **exit 2** |
+| `posts narrate <project> <item> --take --thread [--parents 0\|all\|none\|<n>] [--skip-parent <id\|parent:i>]… [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--speed s] [--note "…"] [--force] [--no-hold] [--dry-run] [--json]` | a **THREAD READ** as one command ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read), `lib/report/postThreadRead.mjs`): the post it answers (`--parents all`: every ancestor; `<n>`: parents 0..n; `none`), the post it quotes and the posts it links to, then his words, in DATE order, each in its author's voice (`--voice-for`, then the item's own character, this video's characters and voice map, the cast: `cast project`; his own: the narrator's) and at its character's speed (its synthetic preset's; `--speed`: every part at that one; Orpheus has none; a part at another speed is another cached part), the redaction, the slur filter (a beep is skipped: a joined read is not word-timed) and the lexicon (`posts say`) applied. A parent or quoted post the item before already shows is not read again (`--read-seen`: it is). Each part is synthesized ONCE by the editor's tts op into `narration/parts-cache/<sha1(voice\|text)>.wav` (the transcription lane held meanwhile, only if it was not; `--no-hold`: left alone), joined (0.8 s between pieces, 0.6 between paragraphs, 0.25 inside one) into `take-<n>.<engine>-thread.wav` with `take-<n>.parts.json`, saved with its parts' roles, its lexicon and how it was asked (`read`) and PICKED — one write (one undo point). `--dry-run`: the pieces, voices and parts (cached or not), nothing asked. Already up to date (same words and voices): nothing done, **exit 0** (`--force`: again). A part not synthesized: **exit 1** (the parts made stay cached; run it again); `--json` prints `{ok: false, error}` too. A usage error: **exit 2** |
| `posts say <project> [ls] [--item <id>]` · `add <word\|phrase> "<spoken>" [--case] [--item <id>] [--note "…"]` · `remove <word\|n> [--item <id>]` · `try "<text>" [--item <id>]` · `stale` `[--json]` | **THE PRONUNCIATION LEXICON** ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)): `narration/lexicon.json` in the project, a word or phrase said differently in EVERY synthesized read (a script's `--take`, each piece of a thread read, the bench's re-take); the scripts and cards keep their words. Whole words, without case unless `--case`, a phrase across any spaces, regex characters literal; `--item` for one item's reads (it wins over the project's). A masked slur and a redacted word are never replaced. `add` of a word already listed changes what is said. `try` prints what a voice would be asked to say. `stale` lists every picked read that still says an entry the old way, with the command that re-reads it. A bad entry or an unknown item: **exit 2** |
+| `posts character <project> <item> [<character> \| --clear] [--json]` | **THE CHARACTER ONE ITEM's OWN READ IS MADE WITH** (`narration.character`, [knobs.md](knobs.md#this-videos-own-characters-and-an-items-own)): the id of one of this video's own characters, else of the cast's -- its presets answer for that item before its author's handle does (the synthetic one for `--take` and a thread read, the recorded one for `--recording`). No character: the one it names and what its read resolves to now; `--clear`: by its handle again. One undoable write; no take is made. An id nobody has: **exit 2** |
| `posts voices <project> [ls] \| set <handle\|*> <voice> \| remove <handle\|*> [--json]` | **THE VOICE MAP** (`narration/voices.json`): the stock voice a thread read gives each author (`*`: everyone it does not name; default `leo` on Orpheus); `ls` lists the map and every author the cut's items carry with the voice each would get. A bad handle or voice: **exit 2** |
-| `posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert] [--label l]` | **a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked |
+| `posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean\|--clean] [--no-trim\|--trim] [--no-convert] [--pitch target\|source\|contour] [--semitones n] [--label l]` · `<item> [--recording <file>] --preview [--as <character>] [--out <file>] [--trim-span [<part>=]<from>-<to>]… [--engine e] [--voice v] [--events]` · `<item> --keep-preview` · `<item> --discard-preview` · `<item> --derive <n> --op convert [--as <character>] [--engine e] [--voice v] [--pitch …] [--semitones n]` | **a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked. The character is `--as` (this video's own first, then the cast's), else the item's own, this video's for the author, the cast's, the narrator; its **recorded preset** says whether it is cleaned and its edges trimmed (and the room kept) -- `--no-clean`/`--clean`, `--no-trim`/`--trim` say otherwise for this read. **`--pitch`** is the pitch the converted read lands on ([knobs.md](knobs.md#the-pitch-a-converted-read-lands-on)): `target` the stock voice's own (the read's intonation flattened to it), `source` the pitch it was read at, `contour` the read's rises and falls moved to the stock voice's register; `--semitones` (-12…12) moves a followed one. Default: the character's `convert` entry, else the editor's `settings.voice.convert`. `source` and `contour` are seed-vc's, with its f0 model (`archilyzer voice setup --engine seed-vc --with f0`); what the editor cannot do it refuses in a sentence (**exit 1**); a value outside these, or a pitch on `--op enhance`: **exit 1**. **`--preview`** runs the same chain with NO TAKE made ([knobs.md](knobs.md#record-filter-preview-on-the-record-page); the record page's Filter): cleaned whole, cut (`--trim-span`: at these seconds of the recording instead of the auto trim's), converted, into the scratch dir `narration/.record-preview/<postId>.<label>/` -- its paths printed, `--out <file>` a copy of the filtered read; without `--recording` it is the record page's session of the item. A step whose inputs stand is not run again (another `--pitch`: the convert alone). `--keep-preview` makes its takes from those files (nothing converted again), `--discard-preview` removes it. **`--derive <n> --op convert`** is the character's too: its recorded preset's engine, stock voice, pitch and semitones, each unless its flag says otherwise (`--as` names another character); no character and no `--voice`: refused (**exit 2**) -- the editor's default voice is never asked for |
| `posts fx <project> <item> add caption --match "…" --text "…" [--target post\|quoted\|parent:<i>] [--occurrence n] [--at s] [--lead s] [--hold s] [--place below\|above\|side]` · `add clock [--rewind auto\|on\|off] [--off]` · `set <n> [--text …] [--place …] [--rewind …]` | a post item's **caption** ([report-video.md](report-video.md#a-caption), [knobs.md](knobs.md#a-caption-a-chip-explaining-a-phrase-as-it-is-read)): a chip explaining a phrase (any script: CJK drawn), up as it is read -- `--at`, else the take's word timings, else the reading estimate -- held `--hold` s, by the phrase and never over a word read while it is up; it waits for a word zoom. Its **clock** ([knobs.md](knobs.md#the-clock-each-posts-own-time-on-its-card-run-between-items)): the post's own time on the card, run from the clock item before it (forward; a REWIND when earlier: `--rewind`), `--off` not on this item. Through `updatePostFx`, refused in the build's words (**exit 1**); a zoom's knob on a caption, or a caption's on a zoom (**exit 1**) |
| `posts clock <project> [on\|off\|default] [--zone <IANA zone>] [--json]` | the cut's **clock** default (`render.posts.clock`, `updatePostClock`); bare, which items show it and their times |
| `posts fx <project> <item> add slam --text "不動心" [--match "…" \| --at s] [--whole \| --per-glyph] [--gap s] [--hold s] [--from-scale x] [--color #rrggbb] [--outline #rrggbb] [--outline-width px] [--place over-match\|center] [--size px] [--face jp\|sc\|tc\|kr] [--sfx trailer-hit\|off] [--volume x] [--swell \| --no-swell] [--bar "…" [--bar-style dark\|gold\|plain]]` · `set <n> [those flags; --bar off clears it]` | a post item's **slam** ([report-video.md](report-video.md#a-slam), [knobs.md](knobs.md#a-slam-a-trailer-style-title-slam-over-a-word-as-it-is-read)): a corny trailer title slam -- each glyph huge, shrinking onto the card just above the matched words' line and HITTING (a flash, dust, the frame's punch, a trailer hit's boom: the teaser's generator, `trailer-hits.mjs`), gold with a black outline; the hits spread evenly over the words' spoken span (`--gap` spaces them, `--at` moves the first), held `--hold` s; `--bar` lands the glyphs on a translation bar (rising in at the first hit, faded with them); a caption up with it waits for it. Through `updatePostFx`, refused in the build's words (**exit 1**); a slam's knob on another effect, or another's on a slam (**exit 2**) |
@@ -145,7 +147,7 @@ Inbox cannot disagree about what is wrong with one.
| `posts context <project> [--dry-run] [--json]` | every **post item's context from its capture** (`postContext.mjs`): the post it quotes and the post it answers, as its page showed them (`capture.json`'s `context`, read by the editor's `capture-posts` -- `"contextOnly": true` reads it alone), filled where the archive row lacks them -- `quoted` where the entry has none (or a named one with no words, the same post), `parents` where it has none (a thread shot stays on the entry; the card draws the parents). An x.com/twitter.com **status link** in its words (or its row's links) is a quote: the post it names, from any channel's archive, fills `quoted` (`via: "link"`) when it has none; the row's `threadId` is snapshotted as the item's `conversation` (the thread walk reads it). What the archive gave is never replaced. ONE write for every entry (`setPostItemsContext`: one undo point, refused whole in the build's words); a re-run with nothing new writes nothing. A post whose capture read no context is listed with the call that reads it (`pnpm ops capture-posts --json '{"slug":…,"ids":[…],"contextOnly":true}' --wait`). The card's blur of other authors is unchanged ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)) |
| `posts picture-reply <project> [on=on\|off] [image=<s>] [min=<s>] [max=<s>] [maxSound=<s>] [--in-take <take>] [--json]` | the cut's **PICTURE-ONLY RULE** ([knobs.md](knobs.md#picture-only-posts-a-reply-that-is-its-picture)): `render.posts.pictureReply` (`updatePostPictureReplyRender`, one undo point) -- `on` the rule at all; a beat's length: an image `image` s (2), a GIF's or a silent video's own length clamped to `min`–`max` (1.5–4 s), a video with its sound its whole length up to `maxSound` (8 s). `k=` the default again; none: the rule as it stands. `--in-take` writes it into a take's patch. Refused in the build's words (**exit 1**) |
| `posts repeats <project> [--match id\|file\|audio] [--json]` | the **combo counter**'s repeats ([report-video.md](report-video.md#the-combo-counter)): every attachment the cut's post items play more than once -- the same X media id (the capture's url), else the same file (the capture's sha256 when its bytes agree, else hashed; cached by path, size and mtime), else (`--match audio`) the same sound (fpcalc, else a coarse ffmpeg hash) -- its posts in the cut's ORDER with their dates, the tier that matched and the badge each draws (`×2` from the second use, `(×n)` counted but not drawn); a post whose CAPTURE holds the same file but whose entry carries no attachment is listed too, `NOT ATTACHED`, with the `posts attach` that brings it in. Reads only |
-| `posts attach <project> [<item> … \| --all] [--dry-run] [--json]` | a post item with **no attachment whose capture holds one** (captured after it went in -- `posts repeats` marks them `NOT ATTACHED`): the capture's media (its own channel's `posts-media/<postId>/`, else any channel the cut's posts come from) copied into the project's `posts-media/<slug>/<postId>/` and measured, set as the entry's `media` as `posts reel` would have made it -- nothing else of the entry changes (its paraphrases, narration, knobs kept); an item that has an attachment is never touched. ONE write (one undo point: `timeline <p> undo`), refused whole in the build's words |
+| `posts attach <project> [<item> … \| --all] [--dry-run] [--json]` | a post item with **no attachment whose capture holds one** (captured after it went in -- `posts repeats` marks them `NOT ATTACHED`): the capture's media (its own channel's `posts-media/<postId>/`, else any channel the cut's posts come from -- looked for in the project's channels tree first, a `.shadow-channels` or `provenance.channelsDir`, then the archive's `CHANNELS_DIR` behind it, read only; `--dry-run` says which tree each file comes from) copied into the project's `posts-media/<slug>/<postId>/` and measured, set as the entry's `media` as `posts reel` would have made it -- nothing else of the entry changes (its paraphrases, narration, knobs kept); an item that has an attachment is never touched. ONE write (one undo point: `timeline <p> undo`), refused whole in the build's words |
| `posts combo <project> [on=on\|off] [label=L] [position=top-right\|top-left\|bottom-right\|bottom-left\|center] [color=#rrggbb] [scale=0.4-2.5] [sfx=off\|hit\|coin] [minCount=2-20] [match=id\|file\|audio] [--json]` · `posts combo <project> <item> off\|on\|auto\|label=…\|position=…\|color=…\|scale=…\|sfx=… [--json]` | the **combo badge's knobs** ([knobs.md](knobs.md#the-combo-counter)): the cut's (`render.posts.combo`, `updatePostComboRender`; no knobs prints them; `k=` the default again) or one post item's (`combo`, `updatePostCombo`): `off` draws no badge on it -- it still counts -- `on`/`auto` the cut's again. Refused in the build's words (**exit 1**) |
| `candidates <project> [ls] [--all] [--json]` · `candidates <project> import <sweep.md> [--dry-run] [--json]` · `candidates <project> add <json\|@file> [--json]` | the **candidates inbox** (`<project>/candidates.json`): proposals only — `import` reads a sweep's bullets (`- [verdict] [title @ time](link) (date) "quote" — why`, under their headings; a Top N section marks what it restates; a bullet with no verdict or link is skipped and said), `add` an agent's (`{channel?, video, t, quote?, why?, verdict?, score?, section?}` or `{link, …}`); the same moment again changes nothing it holds. Insert and Not this are the Cut tab's Candidates panel's ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press)) |
| `ingredient <channel>/<video> [--window <from>-<to>] [--used-in] [--json]` | **one recording's life cycle**, the twin of `/ingredients/<channel>/<video>` ([knobs.md](knobs.md#an-ingredients-life-cycle-the-rail)): nine stages — found, downloaded, transcribed, clock, windows, used in, checked, rendered, published — each **✓**, a count, **!** or **—**, and its line, then every project clip that cuts from it (the draft and each saved version, from the usage index `<REPORTS_ROOT>/.umtool/usage-index.json`). A Rumble recording answers to its folder slug or its embed id; both are printed. `--window`: one clip window, the stages after it narrowed to the clips it plays. `--used-in`: the clips alone. `--json`: the page's object. Read-only over the corpus. **Exit 0 · 1 failed · 2 usage** |
@@ -170,11 +172,17 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `still <project> <clip> --at N [--take TAKE]` | one frame of a clip's fetched window at a source second, into shots/ | form · *project* |
| `still <project> ls` | the pictures in the project's shots/ | form · *project* |
| `cast ls` | the characters' voices across projects | form · *corpus* |
-| `cast add <id> --name NAME --voice VOICE [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--note NOTE] [--narrator]` | a character: name, stock voice, handles | form · *corpus* |
-| `cast set <id> [--name NAME] [--voice VOICE] [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--note NOTE] [--add-handle ADD-HANDLE] [--remove-handle REMOVE-HANDLE] [--no-convert] [--narrator] [--no-narrator]` | change a character | form · *corpus* |
+| `cast add <id> --name NAME --voice VOICE [--handles HANDLES] [--speakers SPEAKERS] [--speed N] [--convert-engine openvoice\|seed-vc\|default] [--convert-voice CONVERT-VOICE] [--convert-pitch target\|source\|contour\|default] [--convert-semitones N] [--enhance on\|off\|default] [--trim on\|off\|default] [--trim-pad TRIM-PAD] [--direction DIRECTION] [--note NOTE] [--narrator]` | a character: name, stock voice, handles, its two presets | form · *corpus* |
+| `cast set <id> [--name NAME] [--voice VOICE] [--handles HANDLES] [--speakers SPEAKERS] [--speed N] [--convert-engine openvoice\|seed-vc\|default] [--convert-voice CONVERT-VOICE] [--convert-pitch target\|source\|contour\|default] [--convert-semitones N] [--enhance on\|off\|default] [--trim on\|off\|default] [--trim-pad TRIM-PAD] [--direction DIRECTION] [--note NOTE] [--add-handle ADD-HANDLE] [--remove-handle REMOVE-HANDLE] [--no-convert] [--no-speed] [--narrator] [--no-narrator]` | change a character: its name, handles, presets | form · *corpus* |
| `cast rm <id>` | a character out of the cast (an undo point) | form · *corpus* |
| `cast undo` | the cast as it was before its last write | form · *corpus* |
-| `cast project <project>` | the project's characters, their voices and drift | form · *project* |
+| `cast project <project>` | the project's characters: each one's voice, where it comes from, its drift; this video's own | form · *project* |
+| `cast project <project> add <id> [--name NAME] [--voice VOICE] [--handles HANDLES] [--anonymous] [--shown SHOWN] [--speed N] [--convert-engine openvoice\|seed-vc\|default] [--convert-voice CONVERT-VOICE] [--convert-pitch target\|source\|contour\|default] [--convert-semitones N] [--enhance on\|off\|default] [--trim on\|off\|default] [--trim-pad TRIM-PAD] [--direction DIRECTION] [--note NOTE]` | a character of this video only (anonymous: shown under Anon 1 …) | form · *project* |
+| `cast project <project> set <id> [--name NAME] [--voice VOICE] [--handles HANDLES] [--shown SHOWN] [--speed N] [--convert-engine openvoice\|seed-vc\|default] [--convert-voice CONVERT-VOICE] [--convert-pitch target\|source\|contour\|default] [--convert-semitones N] [--enhance on\|off\|default] [--trim on\|off\|default] [--trim-pad TRIM-PAD] [--direction DIRECTION] [--note NOTE] [--add-handle ADD-HANDLE] [--remove-handle REMOVE-HANDLE] [--no-voice] [--no-convert] [--no-speed] [--anonymous] [--no-anonymous]` | change a character of this video's | form · *project* |
+| `cast project <project> rm <id>` | a character out of this video's (an undo point) | form · *project* |
+| `cast project <project> undo` | this video's characters as they were before their last write | form · *project* |
+| `cast project <project> pool <id>` | Add to the pool: this video's character into the cast | form · *corpus* |
+| `cast project <project> keep <character> [--anonymous] [--shown SHOWN]` | Keep in this video only: a cast character copied here, or an author given one | form · *project* |
| `cast audition <character> --voices VOICES [--project PROJECT] [--text TEXT] [--item ITEM] [--line N] [--stock] [--no-score] [--score-only]` | one line read by 2-6 candidate voices, scored against the real voice | form · queued · *project* |
| `cast use <project> <character> <voice> [--everywhere]` | the voice a character reads in, here or everywhere | form · *draft* |
| `cast reread <project> <character> [--dry-run]` | the items that say a character in another voice, read again | form · queued · *project* |
@@ -203,7 +211,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `variants <project> [--take TAKE] [--list]` | make the encode ladder of a build | form · queued · *project* |
| `corrections <project>` | what the report got wrong, as markdown | form · *project* |
| `build <project> [--preset preview\|fast\|final] [--only ONLY] [--dry]` | the build's chain, printed (the Cut tab's Build runs it) | form · *project* |
-| `chain <article> <n> [--from FROM] [--dry] [--final] [--site-origin SITE-ORIGIN] [--draft-all] [--model MODEL] [--deck]` | an article iteration's pipeline to a video | form · queued · *corpus* |
+| `chain <article> <n> [--from FROM] [--dry] [--final] [--site-origin SITE-ORIGIN] [--draft-all] [--model MODEL] [--deck] [--stop-before-render] [--allow-whole-recording]` | an article iteration's pipeline to a video | form · queued · *corpus* |
| `index [--rebuild] [--prune] [--since N]` | the project index (the cache) | form · *corpus* |
| `new <slug> [--folder FOLDER] [--from FROM] [--site-origin SITE-ORIGIN] [--seed chapters\|frames\|phrase\|reactions] [--target N] [--phrase PHRASE] [--channels CHANNELS] [--prefer PREFER] [--exclude EXCLUDE] [--max N] [--from-posts FROM-POSTS] [--brand BRAND]` | a new project (scaffold) | form · *corpus* |
| `doctor` | the tools and the roots on this machine | form · *corpus* |
@@ -349,8 +357,9 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `posts set <project> <post> key=value…` | the Posts table's writer: thread, hide, attach, crop | form · *draft* |
| `posts reel <project> --channel CHANNEL… [--since SINCE] [--until UNTIL] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after AFTER] [--dry-run]` | post items from posts channels, in one write | form · *draft* |
| `posts set-item <project> <item> key=value… [--in-take IN-TAKE]` | a post item's knobs | form · *draft* |
-| `posts narrate <project> [<item>] [key=value…] [--script SCRIPT] [--take] [--note NOTE] [--voice VOICE] [--engine ENGINE] [--speed N] [--pick N] [--approve] [--unapprove] [--off] [--on] [--thread] [--parents PARENTS] [--words] [--import] [--list] [--all] [--draft-scripts] [--limit N] [--force] [--recording RECORDING] [--as AS] [--dry-run] [--in-take IN-TAKE]` | a post item's narration: script, takes, pick, approve, mix | form · queued · *draft* |
+| `posts narrate <project> [<item>] [key=value…] [--script SCRIPT] [--take] [--note NOTE] [--voice VOICE] [--engine ENGINE] [--speed N] [--pick N] [--approve] [--unapprove] [--off] [--on] [--thread] [--parents PARENTS] [--words] [--import] [--list] [--all] [--draft-scripts] [--limit N] [--force] [--recording RECORDING] [--as AS] [--pitch target\|source\|contour] [--semitones N] [--dry-run] [--in-take IN-TAKE]` | a post item's narration: script, takes, pick, approve, mix | form · queued · *draft* |
| `posts say <project> ls\|add\|remove\|try\|stale [<word>] [<spoken>] [--case] [--item ITEM] [--note NOTE]` | the pronunciation lexicon | form · *draft* |
+| `posts character <project> <item> [<character>] [--clear]` | the character one post item's own read is made with | form · *draft* |
| `posts voices <project> ls\|set\|remove [<handle>] [<voice>]` | the voice map a thread read uses | form · *draft* |
| `posts fit <project> [<items>…] [--all] [--linger N] [--dry-run]` | narrated posts' videos cut to their best part | form · queued · *draft* |
| `posts fx <project> <item> ls\|add\|set\|remove [<what>] [--key value…] [--in-take IN-TAKE]` | a post item's word zooms, captions, clock, slams | form · *draft* |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -37,6 +37,7 @@ that generates it ([notes.md](notes.md)).
| `chat` — `on`: the clip's live chat (its video's `live_chat.cues.json`, for the clip's source span, timed through its gaps) in a column beside the footage; `off` or `chat=` (the default): none. A video with no chat draws nothing and the build log says so ([Live chat](#live-chat)) | — | `umtool set <p> <clip> chat=on` (`chat=` clears it) | — |
| `hideModules` — `["diet","streak",…]`: the measure extras (`goals` `peak` `promise` `diet` `streak`) hidden over THIS entry's span, each with its own fade, whatever it would otherwise do there -- for text in the footage no dodge can know of (a DM screenshot's refund email under the diet badge). Any entry, a post item too; an id no entry can hide is refused | — | `umtool set <p> <entry> hideModules=diet,streak` (`hideModules=` clears it; `--take <t>` writes the take's patch, the project's manifest untouched) | — |
| `shelfNote` — one line of at most 80 characters on the shelf (`render.chrome.deck.shelf`, its `note` slot) over THIS entry's span, coming and going with it -- a short fact beside the footage for any video, with or without a measure slice ([Shelf](#shelf)). Any entry, a post item too | — | `umtool set <p> <entry> shelfNote='Weighed in on camera'` (`shelfNote=` clears it; `--take <t>` writes the take's patch) | — |
+| `chapter` — the entry's name in the chapter list (`out/…chapters`, `youtube.txt`, `umtool export --format chapters`): one line of at most 100 characters. An authored `chapter` wins over the entry's on-screen title (under the deck) and the line derived from its record; without one the list is as before. Any entry, a post item too | — | `umtool set <p> <entry> chapter='The weigh-in'` (`chapter=` clears it; `--take <t>` writes the take's patch, the project's manifest untouched) | — |
| `fx.zoom` — `{shot, focus, at?, hold?}`: a screenshot (a file in the project; a bare name under its `shots/` is written as `shots/<name>`) that comes up over the footage and pushes in on `focus` (`[left, top, right, bottom]`, fractions of the shot) — drawn once `render.chrome.fx.zoom` is on ([Effects](#effects)). **How long it stays**: up 0.2 s into the clip's clean span (rising in over 0.38 s), its focus box drawn 0.55 s later, the push at `at` (seconds into the clip; default as soon as the box has drawn) over 1 s, then a slow drift on the detail; it leaves with a 0.3 s fade 0.3 s before the clip's clean span ends — or, with `hold` (0.5–10 s), that long after the push lands (never past the clip's own leave) | — | `umtool set <p> <clip> fx.zoom='{"shot":"shots/x.png","focus":[0.1,0.2,0.9,0.4],"at":5.9,"hold":4}'` (`fx.zoom=` clears it) | `PUT /api/report/window {project, clip, "fx.zoom": {…} \| null}` |
| `fx.receipts`, `fx.punch`, `fx.quote`, `fx.punchIn`, `fx.speakers` — the clip's other effect fields (`[{shot, mark?, at?, hold?, label?}]` 1–4, `at` the source second a receipt flies in at (default: as the clip comes up), `hold` 0.5–10 s it stays once landed (on every one: they leave then, not with the clip), `label` a line of at most 80 characters in a band under the screenshot (when it was taken, what it is); the words to punch; `false`: no line; 1–8 source seconds inside the clip; `[{at, who: 0\|1}]`), each inert until its effect is on; `fx` is all of them at once. Checked by the build's own `validateFxEntries` | — | `fx.punch="the words"` `fx.punchIn='[231.4]'` · `fx='{…}'` sets them all, `fx=` clears every one | `PUT /api/report/window {project, clip, fx}` (or one `"fx.<field>"`) |
| `gaps` — `[{from, to}]`, SOURCE seconds cut out of the clip's middle: it renders as ONE segment of jump cuts (one pip, one card), not two clips with a crossfade ([below](#gaps-inside-a-clip)) | clip bench (Edit this clip), the waveform: **Select a gap** (`g`) or Alt + drag a span, **Cut gap** (`g`), **Hear it**; a click on a gap's band puts it back (`G`: the one at the playhead); **Undo** | `umtool window <p> <clip> --gap 12.3-15.1` (repeatable) · `--gap-remove 12.3` · `--gaps '12.3-15.1,20-20.6'` (`--gaps ''` clears) · `umtool set <p> <clip> gap.add=12.3-15.1 gap.remove=12.3 gaps=` | `PUT /api/report/window {project, clip, token, gapAdd \| gapRemove \| gaps}` |
@@ -107,7 +108,10 @@ misclip), and only listening caught it. `umtool quote-check <p> [--clips a,b]` l
clip's cut ±15 s (`--pad`) of the source the render would use is transcribed by the editor (its
transcription lane, words on), and the quote is found in those words — numbers one token however they
are written, a word one letter off still a match, an ellipsis splitting it into fragments found in
-order — and in the recording's cues. The rows (`quote-check.json`, one per clip, with the cut, the
+order — and in the recording's cues. The editor's work files (`<clip>.words.json`) go to
+`<project>/.quote-check/` — never under `out/`, which may be a link onto a media drive, where the editor
+refuses to write (inside the corpus); refused there too, `<reports>/.umtool/quote-check/<project>/`, then
+`~/.cache/umtool/quote-check/<project>/`. The rows (`quote-check.json`, one per clip, with the cut, the
quote and the source judged):
| row | means | what settles it |
@@ -1164,11 +1168,11 @@ the shape, the mix, recordings, parts, the best part). One writer for a post's n
| Knob | In umtool | From a terminal | Route |
|---|---|---|---|
| `narration.script` — what is read: the post, verbatim; Orpheus's tags for emotion | post bench, **script**, **Save script** | `umtool posts narrate <p> <item> --script "…"` · every post's drafted: `--all --draft-scripts [--force]` | `op: "set", patch: {script}` |
-| **the recording session** — the cut's posts read aloud in order, part by part, each part on disk as soon as it is kept (a reload resumes), the post's recorded take made and picked when its last part is in | `/projects/<p>/narration/record` (the Cut tab's **Record the narration**): the jump list (recorded / placeholder, n of N), the post's card and attachment, the teleprompter in its parts (the placeholder's `parts.json`, else the script split), the mic, the level, count-in; **Space** record / stop, **r** redo the part, **Enter** the next part (the post done: the next post), **n** / **p** posts; **Play it back**, **Play the placeholder** | — | `GET /api/report/post-narration/record?project&id[&n]` · `POST` multipart `{project, id, n, count, text, para, part}` · `POST {op: "discard", id, n}` · `POST {op: "finish", id}` |
+| **the recording session** — the cut's posts read aloud in order, part by part, each part on disk as soon as it is kept (a reload resumes), the post's recorded take made and picked when its last part is in -- or, with **Filter before keeping**, the post waits: [filter, preview, Keep](#record-filter-preview-on-the-record-page) | `/projects/<p>/narration/record` (the Cut tab's **Record the narration**): the jump list (recorded / placeholder, n of N), the post's card and attachment, the teleprompter in its parts (the placeholder's `parts.json`, else the script split), the mic, the level, count-in; **Space** record / stop, **r** redo the part, **Enter** the next part (the post done: the next post), **n** / **p** posts; **Play it back**, **Play the placeholder**; **Use a sound file…** (a recording made elsewhere, for the part); the character it is read as, its direction, **▶ <voice> reads it** | — | `GET /api/report/post-narration/record?project&id[&n]` · `POST` multipart `{project, id, n, count, text, para, part}` · `POST {op: "discard", id, n}` · `POST {op: "finish", id, spans?}` |
| a recorded take — your own read, part by part, kept as `take-<n>.recorded-<label>.wav`, picked | post bench, **record your read**: the mic, the level, **Record** (R) / **Stop** (S) / **Redo part** / **Next part**, **Keep** / **Discard**, **voice** (the label, default `operator`) | — | `POST` multipart `{project, id, label, script?, part[], text[], para[]}` |
| a synthesized take — the editor's tts op, with direction | post bench, **Re-take with direction** (a note, a voice) | `umtool posts narrate <p> <item> --take [--note "…"] [--voice v] [--engine e] [--speed s]` · every missing one: `--all --take` | `op: "take"` → `{jobId, file}` · `GET ?project&id&job&file` keeps it when done |
| a THREAD READ — the post it answers (or every ancestor), the post it quotes, the linked posts and his words, each in its author's voice, parts cached, one take picked ([below](#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)) | — | `umtool posts narrate <p> <item> --take --thread [--parents 0\|all] [--skip-parent <id>]… [--voice-for <handle>=<voice>]… [--dry-run] [--json]` | — |
-| a derived take — a take run through the editor's `enhance` or `convert` (a stock synthetic voice: `zac`, `leah`, `orpheus:zac`, never a recording) into a NEW take, the original kept; enhance engines `deepfilternet` · `rnnoise`, convert `openvoice` · `seed-vc` (unnamed: the editor's settings.voice, recorded on the take); "not installed" until `archilyzer voice setup --engine <id>` | post bench, **run AI on take #n** (the op, an engine, a stock voice) → **Run → a new take**; a derived take's **Re-run**; a recording's **Re-record** with **then re-run the chain** | `umtool posts narrate <p> <item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` | `op: "derive", from, op2, engine?, voice?` → `{jobId, file}` (or `{installed: false}`) · `GET ?project&id&job&file&derive=<from>&op=…` keeps it |
+| a derived take — a take run through the editor's `enhance` or `convert` (a stock synthetic voice: `zac`, `leah`, `orpheus:zac`, never a recording) into a NEW take, the original kept; enhance engines `deepfilternet` · `rnnoise`, convert `openvoice` · `seed-vc` (unnamed: the editor's settings.voice, recorded on the take); "not installed" until `archilyzer voice setup --engine <id>`; a convert's **pitch** ([below](#the-pitch-a-converted-read-lands-on)) | post bench, **run AI on take #n** (the op, an engine, a stock voice; for a convert on `seed-vc`, **pitch** and **semitones**) → **Run → a new take**; a derived take's **Re-run**; a recording's **Re-record** with **then re-run the chain** | `umtool posts narrate <p> <item> --derive <n> --op enhance\|convert [--engine e] [--voice v] [--pitch target\|source\|contour] [--semitones n]` | `op: "derive", from, op2, engine?, voice?, pitch?, semitones?` → `{jobId, file}` (or `{installed: false}`) · `GET ?project&id&job&file&derive=<from>&op=…` keeps it |
| delete a take (soft: its file to the post's `.trash/`) | post bench, the take's **Delete** | `--delete <n>` | `op: "delete", take` (an index) |
| `narration.pick` — the take that plays | post bench, the take's **Pick** | `--pick <n>` (1 = the first, as `--list` shows) | `patch: {pick}` (an index) |
| `narration.approved` — the picked take on this script, approved (a new script or pick takes it away) | post bench, **approved** | `--approve` · `--unapprove` | `patch: {approved: true \| null}` |
@@ -1275,16 +1279,21 @@ not the manifest: changing it never re-renders a card, it makes new takes. Beep
still word-timed against its script as written (the replaced words are placed between the words heard).
**The voice map** (`narration/voices.json`, `updateVoiceMap`): `{"<handle>": "<voice>", "*": "<voice>"}` -- the
-project's override of THE CAST (below, "The cast"); the stock voice a read gives each author (handles without `@`, any case; `*` everyone it does not name, default `leo` on
+project's override of THE CAST (below, "The cast"; a handle in it reads as one of this video's own characters with
+only a synthetic voice, and the project's `narration/characters.json` answers before it); the stock voice a read gives each author (handles without `@`, any case; `*` everyone it does not name, default `leo` on
Orpheus). The item's own author reads in the item's narrator voice (`narration.voice`, else the cut's) unless the map
names them; `--voice-for <handle>=<voice>` overrides it for one read, `--voice` sets his post's.
**A thread read** (`lib/report/postThreadRead.mjs`): `posts narrate <p> <item> --take --thread` reads the post it
answers, the post it quotes, the posts its words link to and his words, in DATE order (`post-thread.mjs`
`chronoPieces`), each piece cleaned to be spoken (a context post's paraphrase when it has one), each in its author's
-voice. Each part (a paragraph; a long one split at a sentence end) is synthesized ONCE through the editor's tts op (a
-job on its queue, paced; the GPU and the heavy slot are the editor's) into `narration/parts-cache/<sha1(voice|text)>.wav`
-and reused by every read after -- a re-read after one word changed asks for that part alone. The transcription lane is
+voice and **at its character's speed** (its synthetic preset's, [below](#a-character-is-a-preset); `--speed <s>`: every
+part at that one, recorded on the take's `read`; his own words at the item's `narration.speed` when it has one -- the
+flag, then the item's own, then the character's; Orpheus has no speed and is asked none). Each part (a paragraph; a long one split at a sentence end) is synthesized ONCE through
+the editor's tts op (a job on its queue, paced; the GPU and the heavy slot are the editor's) into
+`narration/parts-cache/<sha1(voice|text)>.wav` (a part at a speed: `…|x<speed>`, so the same words at another speed are
+another part; `parts[i].speed` says it) and reused by every read after -- a re-read after one word changed asks for
+that part alone. The transcription lane is
held while parts are asked (only if it was not held; released after, on a failure, on Ctrl-C). The parts are joined
(0.8 s between pieces, 0.6 between paragraphs, 0.25 inside one) into `take-<n>.<engine>-thread.wav` with
`take-<n>.parts.json`, kept with each part's ROLE stored, and PICKED -- one write, one undo point
@@ -1297,7 +1306,7 @@ was not synthesized (the parts made stay cached: run it again), 2 a usage error;
| what a voice would be asked to say (the lexicon, the redaction, the slur filter) | **Reads and voices** → **Try it** | `umtool posts say <p> try "tbh @grok atm" [--item <id>]` | — |
| the picked reads that say an entry the old way, each with the command that re-reads it | **Reads and voices** names them | `umtool posts say <p> stale [--json]` | — |
| the voice map | **Reads and voices**: the map, **Set** a handle (or `*`) and a voice, ✕ removes; the cut's authors with the voice each gets | `umtool posts voices <p> set kirscheverstahl tara` · `set '*' leo` · `remove <handle>` · `ls` (each author the cut carries, and the voice each gets) | — |
-| a thread read -- `takes[i].read: {kind: "thread", parents, skip?, quoted?, linked?, seen?, voiceFor?, voice?}` | the post bench plays and picks it like any take | `umtool posts narrate <p> <item> --take --thread` (parent 0) · `--parents all` (every ancestor) · `--parents none` · `--skip-parent <id>` (repeat) · `--no-quoted` · `--no-linked` · `--read-seen` · `--voice-for Movail2=leah` · `--voice leo` · `--force` · `--dry-run` · `--json` | — |
+| a thread read -- `takes[i].read: {kind: "thread", parents, skip?, quoted?, linked?, seen?, voiceFor?, voice?}` | the post bench plays and picks it like any take | `umtool posts narrate <p> <item> --take --thread` (parent 0) · `--parents all` (every ancestor) · `--parents none` · `--skip-parent <id>` (repeat) · `--no-quoted` · `--no-linked` · `--read-seen` · `--voice-for Movail2=leah` · `--voice leo` · `--speed 1.1` · `--force` · `--dry-run` · `--json` | — |
Recipes (copy them; `<p>` is the project, `<item>` the post item's id or its post's id):
@@ -1318,19 +1327,31 @@ different ones to compare … and try to maintain consistent voices for differen
**The cast** (`report-to-video/cast.mjs`; `<reports>/.umtool/cast.json`, one writer `lib/report/castStore.mjs`
`castWrite` -- a token, an undo point a write, a broken file never overwritten): the CHARACTERS that recur across
-projects -- `{id, name, handles, voice, convert?, speakers?, avatar?, note?, narrator?}`. `voice` is a STOCK voice
-with its engine (`kokoro:am_michael`, `orpheus:zac`); `convert` the voice (and engine, openvoice | seed-vc) a
-recording of them is converted to (default: `voice`); `speakers` the names their REAL voice goes by in a project's
-`speakers.json` -- a reference to compare a candidate with, never a target (the editor's convert op refuses a file;
-the cast holds no path). One character may be the `narrator` (a recording's default character).
-
-**Every read asks one function** (`post-say.mjs` `voiceSourceOf` / `resolvePieceVoice`): the read's own voice
-(`--voice-for`, `--voice`, the bench's voice field), the project's voice map (`narration/voices.json` -- the
-project's OVERRIDE LAYER; a value may name its engine too), **the cast**, the narrator's (the item's own author),
-the map's `*`, the default. A single post's take (`posts narrate --take`, the bench's Re-take: `readVoice.mjs`) and
-each piece of a thread read agree. A voice that names another engine than the read's is synthesized by it: a
-thread read may join Orpheus and Kokoro parts (each part records its `engine`; the disclosure names both). Projects
-without a cast read as before.
+projects -- `{id, name, handles, synthetic, recorded, speakers?, avatar?, note?, narrator?}` (version 2). **A
+character is a preset**, two of them ([below](#a-character-is-a-preset)): `synthetic.voice` is a STOCK voice with its
+engine (`kokoro:am_michael`, `orpheus:zac`) and `synthetic.speed` its speed; `recorded.convert` the voice (and engine,
+openvoice | seed-vc) a recording of them is converted to (default: the synthetic voice) and the **pitch** that
+converted read lands on (`pitch`, `semitones`: [below](#the-pitch-a-converted-read-lands-on)); `speakers` the names
+their REAL voice goes by in a project's `speakers.json` -- a reference to compare a candidate with, never a target
+(the editor's convert op refuses a file; the cast holds no path). One character may be the `narrator` (a recording's
+default character). **A version 1 file** kept the voice in `voice` and the convert entry in `convert` at the
+character's top: those keys are READ as the presets (`upgradeCharacter`), a reader is handed a view that still says
+`voice` and `convert` (`charactersOf`), and the first write makes the file version 2 -- whose undo point is the
+version 1 text, so `umtool cast undo` puts the old file back as it was. **Before rolling umtool back**, undo the
+cast change: `cast.json` becomes version 2 at the first write, and an older umtool build then reads the cast as empty
+(and refuses to write it).
+
+**Every read asks one chain, first hit wins** (`post-say.mjs` `voiceSourceOf` / `resolvePieceVoice` for a synthesized
+read; `cast.mjs` `characterForRead` for a recording): **the command's flags** (`--voice-for`, `--voice`, `--speed`,
+the bench's voice field; `--as`, `--pitch`), **the item's own character** (`narration.character`), **this video's
+character** for the author (`narration/characters.json`, then `narration/voices.json` -- the project's OVERRIDE
+LAYER; a value may name its engine too), **the cast's**, **the narrator's** (the item's own author), the map's `*`,
+the default. A layer answers for a preset it HAS: a project character with no synthetic voice leaves the voice to
+the layers under it, and its recorded preset still answers for a recording. A single post's take (`posts narrate
+--take`, the bench's Re-take: `readVoice.mjs`) and each piece of a thread read agree, and `umtool cast project <p>`
+prints the answer and its source (`item`, `project`, `cast`, `narrator`, `default`) for every author. A voice that
+names another engine than the read's is synthesized by it: a thread read may join Orpheus and Kokoro parts (each part
+records its `engine`; the disclosure names both). Projects without a cast read as before.
**The guard**: `umtool lint <p>` warns for each picked read that says a cast character in another voice than now
(`umtool cast reread`), and notes each cast voice the project's map overrides on purpose.
@@ -1345,16 +1366,25 @@ with an excerpt of the real voice (`ref-<speaker>.wav`) to listen to beside them
**A recording made a character's read**: `posts narrate <p> <item> --recording <file> [--as <character>]` keeps it as
a recorded take (the original), cleans it (the editor's voice-enhance, when installed) and converts it (its
-voice-convert) to the character's stock voice -- each a new take, the last picked, the disclosure line said.
+voice-convert) to the character's stock voice -- each a new take, the last picked, the disclosure line said. The
+character is the chain's (`--as`, the item's own, this video's for the author, the cast's, the narrator), and its
+**recorded preset** is applied: `enhance: false` skips the clean, `trim.on: false` keeps its edges as recorded,
+`trim.padMs` is the room kept either side of the words (`--clean` / `--no-clean`, `--trim` / `--no-trim` say otherwise
+for one read).
| Knob | In umtool | From a terminal | Route |
|---|---|---|---|
-| the cast -- `<reports>/.umtool/cast.json` | **Voices** (`/projects/<p>/voices`, from the Cut tab's Reads and voices): **the cast** list, ✕ removes, **Undo the last cast change**; an audition's **Use everywhere** adds or changes a character | `umtool cast ls` · `add <id> --name … --voice kokoro:am_michael --handles a,b [--speakers Jeremy] [--convert-engine seed-vc] [--convert-voice …] [--narrator]` · `set <id> …` (`--add-handle`, `--remove-handle`, `--no-convert`) · `rm <id>` · `undo` | `POST /api/report/voices {op: "cast-rm" \| "cast-undo" \| "cast-set"}` |
-| a project's characters -- each one's voice now and where it comes from, its reads, its drift, its real voice | **Voices**: the characters table | `umtool cast project <p> [--json]` | `GET /api/report/voices?project` |
+| the cast -- `<reports>/.umtool/cast.json` | **Voices** (`/projects/<p>/voices`, from the Cut tab's Reads and voices): **the cast** list, **Presets**, ✕ removes, **Undo the last cast change**; an audition's **Use everywhere** (or an author's **Add to the pool**) adds or changes a character | `umtool cast ls` · `add <id> --name … --voice kokoro:am_michael --handles a,b [--speakers Jeremy] [the preset flags] [--narrator]` · `set <id> …` (`--add-handle`, `--remove-handle`, `--no-convert`, `--no-speed`) · `rm <id>` · `undo` | `POST /api/report/voices {op: "cast-rm" \| "cast-undo" \| "cast-set"}` |
+| a character's presets -- `synthetic: {voice, speed}`, `recorded: {convert: {engine, voice, pitch, semitones}, enhance, trim: {on, padMs}, direction}` | **Voices** → a character's **Presets**: the voice and speed; converted to, by, pitch, semitones; clean it first; trim its edges and the pad; the direction; **Save presets** | `umtool cast set <id> [--voice kokoro:am_michael] [--speed 1.1] [--convert-engine seed-vc] [--convert-voice …] [--convert-pitch source\|contour\|target] [--convert-semitones n] [--enhance on\|off] [--trim on\|off] [--trim-pad 120] [--direction "higher, brisk, amused"]` (`default` for one takes it off) · this video's own: `umtool cast project <p> set <id> …` | `POST … {op: "character-set", scope: "cast" \| "project", id, voice?, speed?, convertEngine?, convertVoice?, convertPitch?, convertSemitones?, enhance?, trim?, trimPad?, direction?}` |
+| a project's characters -- each one's voice now (and speed) and where it comes from, what a recording of them is made into, its reads, its drift, its real voice | **Voices**: the characters table | `umtool cast project <p> [--json]` | `GET /api/report/voices?project` |
+| this video's own characters -- `<p>/narration/characters.json` | **Voices** → *this video's own characters*: **Add a character** (id, name, handles, anonymous and its shown name), **Presets**, ✕, **Undo the last change**; an author's **Keep in this video only**; a character's **Add to the pool** | `umtool cast project <p> add <id> --name … [--voice …] [--handles a,b] [--anonymous [--shown "Anon 1"]]` · `set <id> …` (`--no-voice`, `--no-anonymous`) · `rm <id>` · `undo` · `pool <id>` · `keep <character\|@handle> [--anonymous]` | `POST … {op: "character-add" \| "character-set" \| "character-rm" \| "characters-undo" \| "character-pool" \| "character-keep"}` |
+| the character one post item's own read is made with -- `narration.character` | **Voices** → *an item read as a character of its own*: the item, **read as…**, **Set**; **clear** | `umtool posts character <p> <item> <character>` · `--clear` · none: print it | `POST … {op: "item-character", item, character}` |
| an audition | **Voices** → a character's **Audition**: the line, the candidates (engine, voice, Add), **Render** (a job: the editor's tts, then the closeness through the heavy slot), each played at one loudness, **▶ Play each in turn** (the real voice first) | `umtool cast audition <character\|@handle> --project <p> --voices kokoro:am_michael,kokoro:am_onyx,orpheus:zac [--text "…" \| --item <id> \| --line <n> \| --stock] [--no-score \| --score-only] [--json]` | `POST /api/report/voices {op: "audition", who, voices, text?, item?}` |
| the voice a character reads in -- this project, or everywhere | an audition's **Use for this project** / **Use everywhere** | `umtool cast use <p> <character\|@handle> <voice> [--everywhere]` (the project's own override goes with `--everywhere`) | `POST … {op: "use", who, voice, scope}` |
| the re-reads a voice change asks for | the confirm under the audition: the items, **Queue N re-reads** (steps of the queue: /jobs; each a new take, picked, awaiting approval) | `umtool cast reread <p> <character> [--dry-run]` | `POST … {op: "reread", who}` |
-| a recording made a character's read | **Voices** → *a recording*: the item, as whom, drop a file, clean / convert, **Import** (a job) | `umtool posts narrate <p> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert]` | `POST … multipart {op: "recording", item, as?, file}` |
+| a recording made a character's read | **Voices** → *a recording*: the item, as whom (this video's own, the cast's), drop a file, clean / convert, **Import** (a job) | `umtool posts narrate <p> <item> --recording <file> [--as <character>] [--no-clean\|--clean] [--no-trim\|--trim] [--no-convert] [--pitch …] [--semitones n]` | `POST … multipart {op: "recording", item, as?, file}` |
+| the same chain with NO TAKE made -- a preview in the scratch dir `narration/.record-preview/<postId>.<label>/`, then kept or dropped ([below](#record-filter-preview-on-the-record-page)) | the record page's **Filter**, **Keep**, **Again** | `umtool posts narrate <p> <item> [--recording <file>] --preview [--as <character>] [--out <file>] [--trim-span [<part>=]<from>-<to>]… [--no-clean\|--clean] [--no-trim\|--trim] [--no-convert] [--engine e] [--voice v] [--pitch …] [--semitones n]` · `--keep-preview` · `--discard-preview` | `POST /api/report/post-narration/record {op: "prepare" \| "filter" \| "keep" \| "again" \| "discard-preview"}` |
+| a convert made from a take -- its engine, stock voice, pitch and semitones are the CHARACTER's recorded preset, each unless said; no character and no voice: refused (the editor's default voice is never asked for) | post bench, **run AI on take** → convert | `umtool posts narrate <p> <item> --derive <n> --op convert [--as <character>] [--engine e] [--voice v] [--pitch …] [--semitones n]` | `POST /api/report/post-narration {op: "derive", op2: "convert", as?, engine?, voice?, pitch?, semitones?}` |
```sh
umtool cast add thequartering --name TheQuartering --voice kokoro:am_michael --handles thequartering --speakers Jeremy
@@ -1363,8 +1393,158 @@ umtool cast audition thequartering --project quartering-diet --voices kokoro:am_
umtool cast use quartering-diet thequartering kokoro:am_michael --everywhere # then:
umtool cast reread quartering-diet thequartering # each stale read made again (a take each, picked)
umtool posts narrate quartering-diet <item> --recording my-read.wav --as thequartering
+umtool cast set thequartering --speed 1.1 --convert-engine seed-vc --convert-pitch contour --direction "higher, brisk, amused"
+umtool cast project quartering-diet add anon-1 --anonymous --handles somereplyguy --voice kokoro:am_puck # shown as "Anon 1"
+umtool cast project quartering-diet keep @madamsavvy # a character of this video only, in the voice she reads in now
+umtool posts character quartering-diet <item> anon-1 # this one item read as that character (--clear: by its handle)
```
+### Record, filter, preview on the record page
+
+The operator, 11 Nov 2026: "run the filter and preview it seamlessly in the record UI". On
+`/projects/<p>/narration/record`, above the record button: **who the post is read as** (the chain's character and
+where it comes from), its **direction** line, and **▶ <voice> reads it** -- the character's SYNTHETIC preset voice
+(`synthetic.voice`, at its speed: the cheap one to hear the line in -- the voice a recording is CONVERTED to is
+`recorded.convert.voice`, which may be another) reading the part: the read kept from before when there is one
+(`narration/parts-cache/`, a thread read's), else asked of the editor's tts op when the button is pressed, never before.
+
+**Filter before keeping** (a checkbox; on by itself for a post whose character has a stock voice to convert to, off
+otherwise -- the last part then makes the recorded take at once, as before): the last part in, the post WAITS.
+
+- **The cut marks**: each part's waveform with its trim in and out -- the auto trim's answer (the preset's
+ `trim.padMs` either side of the speech; `trim.on: false`: the whole part), draggable, or focus one and press the
+ arrow keys (0.05 s; Shift 0.25 s); **▶ what the marks keep**; **back to the auto trim**. They are what a keyboard
+ click at the start or the end of a recording is cut off with. `keepRecording` takes them as `spans` (`[{from, to}]`
+ per part, the part's own seconds), whatever the trim says.
+- **Filter** (**f**): the character's recorded preset as ONE job of umtool's (`umtool posts narrate <p> <item>
+ --preview --events`; its three stages on the page, the time it has run, Cancel) -- **clean** (the editor's
+ voice-enhance over the parts whole), **cut** at the marks and joined, **convert** (its voice-convert to the stock
+ voice) -- into the SCRATCH DIR `<project>/narration/.record-preview/<postId>.<label>/` (`preview.json`, `raw.wav`,
+ `clean.wav`, `filtered.wav` and their parts). **No take is made.** A stage whose inputs stand is not run again: a
+ mark moved re-cuts the cleaned sound and converts; another pitch converts alone. **A wait is a state, not an
+ error**: *queued* behind the editor's other voice jobs, *waiting for memory* or *for the heavy slot* at the machine's
+ gate (the last line of the editor's job, `scripts/queue-lock.mjs`'s own) -- a short read takes two or three minutes.
+ umtool runs one job at a time: while another runs, Filter says so. **Cancel** stops umtool's job AND the editor's
+ job it waits on (its engine holds, or waits at, the heavy slot otherwise); pressed before the editor's job is known,
+ the page says so. While a post's Filter runs, Keep, Again, a part's upload and dropping the preview answer 409.
+- **▶ Raw**, **▶ Filtered**, **▶ Raw, then filtered**: the two reads at ONE loudness (the louder turned down to the
+ other's measured LUFS). With no clean engine and no character to convert to, it says nothing filtered it.
+- **Pitch** and **semitones** (a Seed-VC convert): default the preset's; **Save to character** writes them to the
+ character (`character-set`: this video's own, or the cast's -- it says which). A post read as the cast's narrator, or
+ as nobody: **Keep in this video only** (`character-keep`) gives its author a character of this video's own, converted
+ as here.
+- **Keep** (**Enter**): the takes `posts narrate --recording` makes -- the recording (cut, joined, levelled), the
+ cleaned one, the converted one, the last PICKED and awaiting approval -- made FROM THE PREVIEW's FILES, nothing
+ converted again; the page opens the next post not recorded yet. When the marks or the pitch moved since the Filter
+ the button says **Keep the recording alone** and keeps one recorded take, cut at the marks.
+- **Again** (**Backspace** or **r**): the preview dropped, the part recorded again. A part recorded over with Space
+ drops the preview too (page and server), and a filtered Keep is refused (409) unless the preview was made from the
+ session's recording as it is now -- the filtered read of an earlier recording is never kept. A held key is one press.
+- A sound file chosen for a part (and `--recording <file>`) is an upload: one that is text (a playlist, a concat
+ script) is refused before ffmpeg opens it, and ffmpeg may open local files only (`-protocol_whitelist file`).
+- Keep writes its takes one after another (an undo point each, as `--recording` does): a failure between them leaves
+ the takes already written, and the preview's files that were moved stay takes.
+- The scratch dir is removed on Keep, on Again, when the post or the page is left (unless its Filter is still running:
+ it is there when you come back), when the recording it was made from changes, and a day after a crash left one.
+- **The microphone is a secure context's** (localhost, https): opened over http from the LAN the page says so and
+ the Record button is off; **Use a sound file…** takes a recording made elsewhere for the part, and Filter, the
+ preview, the marks and Keep work as anywhere.
+- Not built: a "start on speech" level trigger. A recorder that starts at the first sound loses the start of the first
+ word, and the auto trim already cuts the silence before it; Space and the count-in start a read.
+
+| Knob | In umtool | From a terminal | Route |
+|---|---|---|---|
+| the preview -- the chain into the scratch dir, no take | **Filter** (f) | `umtool posts narrate <p> <item> --preview` (the page's session) · `--recording <file> --preview [--out <file>]` (a file; the filtered read copied to `--out`) · `--json` · `--events` (its progress, one JSON object a line) | `POST /api/report/post-narration/record {op: "filter", id, spans?, pitch?, semitones?}` → `{job}`; `GET ?project&id&job=<id>` → `{job: {state, stage, waiting, waited, stages, error}, preview?}`; `POST {op: "cancel", id, job}` → `{cancelled, editor: {job, cancelled, note?}}` |
+| the cut marks -- `[{from, to}]` per part | the waveform's two marks | `--trim-span 0.4-3.1` (the first part) · `--trim-span 2=0.2-4` | `spans` on `filter`, `keep`, `finish`; `POST {op: "prepare", id}` → each part's `seconds`, `peaks`, `auto` |
+| the pitch of this read | **pitch**, **semitones** | `--pitch target\|source\|contour` · `--semitones n` | `pitch`, `semitones` on `filter` |
+| the pitch kept on the character | **Save to character** · **Keep in this video only** | `umtool cast set <id> --convert-pitch … --convert-semitones n` · `umtool cast project <p> set <id> …` · `umtool cast project <p> keep @<handle>` | `POST /api/report/voices {op: "character-set" \| "character-keep"}` |
+| keep the preview -- its takes, the last picked | **Keep** (Enter) | `umtool posts narrate <p> <item> --keep-preview` | `POST … {op: "keep", id, filtered: true, spans?, script?}` (`filtered: false`: the recording alone) |
+| drop it | **Again** (Backspace, r), leaving the post | `umtool posts narrate <p> <item> --discard-preview` | `POST … {op: "again", id, n?}` · `{op: "discard-preview", id}` |
+| the character's synthetic voice reading the line | **▶ <voice> reads it** | — | `POST … {op: "stock", id, text}` → `{file}` or `{jobId, key}`; `GET ?project&id&stock&job&key` |
+| the preview's sounds | **▶ Raw**, **▶ Filtered**, **▶ what the marks keep** | the paths `--preview` prints | `GET ?project&id&preview&file=raw\|clean\|filtered\|part[&n]` · `GET ?project&id&preview` (who it is read as, the preview, the job) |
+
+```sh
+umtool posts narrate <p> <item> --recording savvy.wav --preview # clean, cut, convert: the paths, no take
+umtool posts narrate <p> <item> --recording savvy.wav --preview --semitones 3 # another nudge: the convert alone
+umtool posts narrate <p> <item> --recording savvy.wav --preview --trim-span 0.35-4.1 --out /tmp/savvy.wav
+umtool posts narrate <p> <item> --keep-preview # its takes, the last picked
+umtool posts narrate <p> <item> --derive 1 --op convert # take 1 converted as its character says
+```
+
+### A character is a preset
+
+The operator, 11 Nov 2026: "a preset of voice and other settings … different presets for synthetic and
+human-filtered voices". A character carries two, picked by how the read is made:
+
+- **`synthetic`** -- a read the editor synthesizes: `voice` (`<engine>:<voice>`, a stock voice) and `speed` (0.5–2,
+ 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`.
+- **`recorded`** -- a recording of them made their read: `convert` `{engine, voice, pitch, semitones}` (the target is
+ ALWAYS a stock synthetic voice: validation refuses a file, a path or a recording, in the cast and in a project's
+ own characters), `enhance` (cleaned first by the editor's voice-enhance; absent: yes), `trim` `{on, padMs}` (its
+ edges trimmed to speech -- the silence, a key click -- and the milliseconds of room kept either side; absent: on,
+ 80 ms before and 150 after) and `direction` -- ONE LINE FOR THE PERSON READING ("higher, brisk, amused"), shown to
+ them, **never sent to a model** (at most 200 characters).
+
+The disclosure line a cut carries is unchanged: it is made from the takes (a synthetic voice, a voice converted to a
+synthetic voice), never from a preset.
+
+### This video's own characters, and an item's own
+
+**A project's own characters** (`<project>/narration/characters.json`, format `umtool-project-characters`; the cast's
+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. **The on-screen card is NOT anonymised yet**: a cut
+still shows the post's author, so an anonymous character keeps someone out of the pool and off umtool's own surfaces,
+not off the video. 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.
+
+**Add to the pool** (`umtool cast project <p> pool <id>`) moves a project's character into the cast -- refused for an
+anonymous one, and for an id the cast already has. **Keep in this video only** (`… keep <character|@handle>`) copies
+a cast character into the project (its presets changed for this video alone; the pool's stay as they are), or gives
+an author with no character one here, in the voice they read in now.
+
+**A post item's own character** (`narration.character`, `umtool posts character <p> <item> <id>`): the id of one of
+the project's own characters, else of the cast's. Its presets answer for THAT item's own words before its author's
+handle does -- a reply read as "Anon 2" while the same handle elsewhere reads as itself. An id nobody has is refused
+by the command; one that stops existing later (the character removed) reads as its author does, and `umtool cast
+project <p>` says so.
+
+### The pitch a converted read lands on
+
+A converter given no pitch speaks every read at the STOCK voice's own: measured 11 Nov, reads with a median pitch of
+128 to 237 Hz all came out at 196-199 Hz and a 152-321 Hz range came out as 165-240 Hz -- raising your voice for a
+character, and most of your intonation, was thrown away. A convert's **pitch** says where the result's pitch comes
+from (the editor's `voice-convert`: `pitch`, `semitones`):
+
+- **`target`** -- the stock voice's own pitch, as before. Either engine; the default until a character or
+ `settings.voice.convert.pitch` says otherwise.
+- **`source`** -- the pitch you read at, as you read it: raise your voice and the result rises, drop it and it drops.
+ For a read ACTED at the character's pitch.
+- **`contour`** -- your rises and falls, moved as a whole so their median sits on the stock voice's median: read in
+ your ordinary voice, and the character speaks in its own register with your intonation.
+- **`semitones`** (-12 to 12) then moves a followed pitch (`source`, `contour`) up or down. With `target` it is
+ refused: nothing is followed to move. A convert that names a followed pitch and no semitones takes
+ `settings.voice.convert.semitones` (0 unless set).
+
+`source` and `contour` are **seed-vc's**, on its f0-conditioned model -- optional files, `archilyzer voice setup
+--engine seed-vc --with f0` (1.49 GB); it takes about 1.7 times as long as seed-vc at the target's pitch. openvoice has one
+pitch and refuses another; a followed pitch without the f0 files is refused naming that command. A parted take's
+`contour` is measured once, on the whole take, and used for every part.
+
+| Knob | In umtool | From a terminal | Route |
+|---|---|---|---|
+| a character's convert pitch -- `convert.pitch`, `convert.semitones` in the cast: what every recording made that character's lands on | **Voices**: the cast row says it ("pitch: follows your pitch +2 st"), and the recording form's *as …* choice | `umtool cast set <id> --convert-engine seed-vc --convert-pitch source\|contour\|target [--convert-semitones n]` (the flags given are laid over the entry; `--no-convert` clears it) | `POST /api/report/voices {op: "cast-set", id, convertPitch?, convertSemitones?}` |
+| one read's pitch -- this conversion only, over the character's | post bench, **run AI on take #n** → *convert*, engine `seed-vc`: **pitch** (the stock voice's own pitch · follow my pitch · my intonation, at the voice's register) and **semitones**, starting from the post author's character in the cast (else the narrator), which the row names; a converted take's row says its pitch, and **Re-run** keeps it | `umtool posts narrate <p> <item> --recording <file> [--as <character>] --pitch source\|contour\|target [--semitones n]` · `--derive <n> --op convert --engine seed-vc [--voice v] --pitch … [--semitones n]` | `POST /api/report/post-narration {op: "derive", …, pitch?, semitones?}` · `GET …?project&id&convert=1` (the character's default) · the editor's `POST /api/ops/voice-convert {…, pitch?, semitones?}` |
+| the default for every conversion that names none | — | `settings.voice.convert.pitch`, `.semitones` ([SETTINGS.md](../../SETTINGS.md)) | — |
+
+A converted take's step keeps the pitch it was run at (`steps: [{op: "convert", engine, voice, pitch, semitones}]`),
+so `--list` and a re-run say it; the target's own pitch is not recorded.
+
## A caption (a chip explaining a phrase as it is read)
`fx: [{kind: "caption", match, text, …}]` on a post item ([report-video.md](report-video.md#a-caption): the shape,
@@ -1571,7 +1751,7 @@ in the build's words (`validatePostCombos`). `k=` (empty) takes the default (the
| | In umtool | From a terminal | Route |
|---|---|---|---|
| the repeats: each attachment played more than once, its posts in the cut's order with their dates, the tier that matched (`X media id`, `same file`, `same sound`) and the badge each draws; a post whose capture holds the same file but whose entry carries none, marked | the post bench's **combo** block (this item's group) | `umtool posts repeats <p> [--match id\|file\|audio] [--json]` | `GET /api/report/post-combo?project` |
-| attach what a capture holds to a post item that carries none (captured after it went in): its media copied in and set, nothing else of the entry changed; then it plays and counts | — | `umtool posts attach <p> <item>… \| --all [--dry-run]` | — |
+| attach what a capture holds to a post item that carries none (captured after it went in): its media copied in and set, nothing else of the entry changed; then it plays and counts. The capture is looked for in the project's channels tree (a `.shadow-channels`, `provenance.channelsDir`), then the archive's behind it -- read only, the files are copied into the project; `--dry-run` says which tree each file comes from | — | `umtool posts attach <p> <item>… \| --all [--dry-run]` | — |
| the badge on the item's clock | Play the cut, the post bench (the player) | the build: `segments/<id>.mp4` (the plain one `<id>.plain.mp4`, the record `<id>.combo.json`) | — |
## Media scenes (one attachment, several messages)
@@ -2368,6 +2548,7 @@ The diet he names as a rubber stamp in a corner of the footage box (`render.chro
| `deck.diet.overlap` | 0–0.8, the share of each older tag hidden behind the one in front · default 0 (side by side, the slam and the dim). Above 0 the tags FAN sideways the way the goal stack's notes pile: the newest in front at the left, landing from above like a goal note, each older one a place to the right behind it with its own small turn, keeping its colours (the depth is the overlap and the shadow), showing its regime word and date in the strip beside the one in front; the one past `tags` slides off the back. The fan is narrower by what hides. An older tag's word and date need 110 design px of it, so it is refused past 0.5 (0.63 with `days`) | `umtool look <p> deck.diet.overlap=0.5` |
| `deck.diet.days` | `true` · `false`: the front tag's running count of days on its diet (to the in-record date at the playhead, the streak chain's "Day N"), in a column of its own -- the tag 300 design px wide · default `false` | `umtool look <p> deck.diet.days=true` |
| `deck.diet.colors`, `.labels` | `{<regime>: #hex}` · `{<regime>: words ≤40}` · default the regimes' inks and names | `umtool look <p> deck.diet.labels='{"glp1":"Ozempic"}'` |
+| `deck.diet.flash` | bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): with `form: "tags"`: the new front tag lights, in its ink, at a new diet or new words for it -- never the running day count, never the first tag; the stamp form does not flash; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away | `umtool look <p> deck.diet.flash=false` |
| `deck.diet.onPosts`, `.onChapters` | `dodge` `hide` `show` · default `dodge`: while a post item's card (its card, slot and strip as postLayout lays them: the schedule's `covers`) or a chapter band is up where it stands, it moves to a free anchor of the footage box -- a size down to half if it must, never onto another measure extra that is up -- and hides when none fits; `hide` hides, `show` stays over it | `umtool look <p> deck.diet.onPosts=hide` |
| `deck.diet.position=shelf` | in its own slot on the shelf (`deck.shelf`: under or over the footage), scaled to the shelf's height, left to right in `deck.shelf.items` order -- nothing covers it there, so it never dodges (`onPosts`, `onChapters`, `x`/`y`, `scale` and `avoid` do not apply), and it is over the finale as the shelf is (`deck.shelf.finale`) | `umtool look <p> deck.shelf=true deck.diet.position=shelf` |
| a timeline entry's `hideModules` | `["diet", …]` on an entry hides it over that entry's span, with its own fade, whatever it would otherwise do there (text in the footage no dodge can know of) · any entry, a post item too | `umtool set <p> <entry> hideModules=diet` (`--take <t>` for a take) |
@@ -2392,11 +2573,14 @@ A sticky note per goal on a pile in a corner of the footage box, read off the sc
| Knob | Range · default | From a terminal |
|---|---|---|
-| `deck.goals` | `true` · `false` · `{show, position, x, y, scale, hold, finale, max, color, countdown}` · default on with a measure slice | `umtool look <p> deck.goals=false` |
+| `deck.goals` | `true` · `false` · `{show, position, x, y, scale, hold, finale, max, color, countdown, base, baseMaxDays}` · default on with a measure slice | `umtool look <p> deck.goals=false` |
| `deck.goals.position`, `.x`/`.y`, `.scale` | `top-left` `top-right` `bottom-left` `bottom-right` `top-center` `bottom-center` · design px · 0.5–2 · default `bottom-right`, unset, 1 | `umtool look <p> deck.goals.position=bottom-left` |
| `deck.goals.position=shelf` | its shelf form (`deck.shelf`): the count of goals set in a column, then the notes fanned sideways like the diet's tags -- ordered by the dial's goal board (measure-goals.mjs `goalsAt(goalBoard(schedule.measure), t)`, so the shelf and the dial always agree): its headline -- the closest goal in force -- in front with "+N more" for the others in force, the rest by recency; a goal the board misses struck in red, MISSED on it, for the dial's 6 s; with no goal in force, the newest in front; a new goal landing from above as on the pile; each older one showing its goal's words in the strip beside it (all of each when there is room); a repeat comes to the front with its ×n. The fan takes the shelf's spare width (shelfLayout), up to its notes side by side. On the shelf it stays up from the first goal (`hold` unset). What the dial draws of the goal stays on the dial | `umtool look <p> deck.shelf.items='["diet","goals"]' deck.goals.position=shelf` |
| `deck.goals.max`, `.color`, `.countdown` | 1–8 notes · #hex paper · bool · default 4, the palette's amber, `true` | `umtool look <p> deck.goals.max=6` |
+| `deck.goals.base` | bool · default `false`: each note also says the weight he had stated when he set the goal -- "LOSE 100 (FROM 346.7)", its qualifier kept ("(FROM ≈390)") -- the slice's own base for that goal, the one the gauge reckons its target from (measure-slice.mjs `goalBase`: the start of the run open when he set it, else the latest weight he gave by the goal's date, stated or remembered). A goal with no base (no weight by then, a target goal such as "250 LB", a base the scale's foot refuses) shows none -- never one made up. On a back card it is a line of its own, right-aligned like the label | `umtool look <p> deck.goals.base=true` |
+| `deck.goals.baseMaxDays` | whole days 0–36500 · unset (default): every base counts. A loss goal's base is a weight he gave by the goal's date, however long before; with this set, a base counts only when its weight was SAID (its row's date, never a remembered weight's as-of) at most that many days before the goal's date. A staler one is no base: the note carries no "(FROM …)", and the slice resolves no target from it -- the dial draws no goal weight and no tick for that goal, his words ("LOSE 100") stay. It is the slice's rule (measure-slice.mjs `goalBaseMaxDays`), so the notes, the shelf and the dial agree; it needs `deck.goals` as settings (`deck.goals.base=true deck.goals.baseMaxDays=365`), and `baseMaxDays=null` takes it off | `umtool look <p> deck.goals.baseMaxDays=365` (`--take <t>` for a take) |
| `deck.goals.hold`, `.finale` | 0 (up from the first goal on) or 2–600 s after each · `hide` `show` · default 20, `hide` | `umtool look <p> deck.goals.hold=0` |
+| `deck.goals.flash` | bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): the note that lands lights as a goal is set -- not the first note (the stack coming up), not the board's own changes; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away | `umtool look <p> deck.goals.flash=false` |
| `deck.goals.onPosts`, `.onChapters` | `dodge` `hide` `show` · default `dodge`: while a post item's card (its card, slot and strip as postLayout lays them: the schedule's `covers`) or a chapter band is up where it stands, it moves to a free anchor of the footage box -- a size down to half if it must, never onto another measure extra that is up -- and hides when none fits; `hide` hides, `show` stays over it | `umtool look <p> deck.goals.onPosts=hide` |
| `deck.goals.position=shelf` | in its own slot on the shelf (`deck.shelf`: under or over the footage), scaled to the shelf's height, left to right in `deck.shelf.items` order -- nothing covers it there, so it never dodges (`onPosts`, `onChapters`, `x`/`y`, `scale` and `avoid` do not apply), and it is over the finale as the shelf is (`deck.shelf.finale`) | `umtool look <p> deck.shelf=true deck.goals.position=shelf` |
| a timeline entry's `hideModules` | `["goals", …]` on an entry hides it over that entry's span, with its own fade, whatever it would otherwise do there (text in the footage no dodge can know of) · any entry, a post item too | `umtool set <p> <entry> hideModules=goals` (`--take <t>` for a take) |
@@ -2419,6 +2603,8 @@ A bathroom-scale face at the top of the instruments' column (the right of the fr
| `deck.dial.mark` | a weight, or `null` · default `300` (its tick and label in the accent) | `umtool look <p> deck.dial.mark=300` |
| `deck.dial.ghosts`, `.goal` | bool · default `true` each (`.goal`: every goal in force, the closest headlined) | `umtool look <p> deck.dial.ghosts=false` |
| `deck.measure.ghosts` | `true` · `{opacity, tolerance, ramp, pulse}` · `false` / absent: off (the default). CLAIM GHOSTS (measure-ghosts.mjs), not `deck.dial.ghosts`: every weight he has claimed so far -- each stated weight the needle goes to and each remembered one, his own, in cut order -- leaves a thin faint tick across the dial's rim at its value, under everything else on the face; a value claimed again (within `tolerance` lb of the tick's first value; an `≈` value as its rounded number; `>300` and `<300` at 300) steps that tick along the `ramp` -- 1× faint, 2× warm, 3× and up hot, a little thicker each step -- and it pulses once as the repeat lands (`pulse`). In the finale every tick stays at its count at the cut's end. Seek-safe: a frame at t draws the claims before t | `umtool look <p> deck.measure.ghosts=true` |
+| `deck.dial.rememberedAs` | `needle` · `rim` · `readout` · `callout` · default `needle` (as it was: a long grey second needle from the hub to the value, its words -- "≈390 / AS OF 24 FEB 2023" -- along it). `rim`: no long needle; a bold marker across the rim at the value and a flag inside it -- "HEAVIEST ≈390 / AS OF FEB 2023 · HE SAYS" -- placed clear of the scale's figures, the hub and the readout. `readout`: a line in the readout under the date -- "HEAVIEST HE'S SAID: ≈390 (FEB 2023)", the goal under it -- and the rim marker. `callout`: as he says it a ghost needle sweeps from where the needle stands to the value and a label ("HEAVIEST HE'S SAID / ≈390 / AS OF FEB 2023") holds 2.2 s, then the rim's flag. The words are the ledger's: its qualifier, its asOf's month; HEAVIEST only for the record's highest remembered weight above every weight he stated (the peak extra's `totals.peakDrift`), else "HE SAYS HE WAS". Each is up while it is the latest remembered; the thin rim ticks of every remembered weight stay as they are | `umtool look <p> deck.dial.rememberedAs=rim` |
+| `deck.measure.flash` | bool · default `false` (off: every cut renders as before) -- THE UPDATE FLASH for every measure widget at once (update-flash.mjs): at the moment a widget's shown value changes its outline lights in its own colour and decays (0.15 s up, 0.7 s down) -- the dial on a weight stated or remembered or a goal change, the odometer on the pounds lost or NET, the trail on each weight landing, the goal stack on a goal set, the diet tags on a new diet; widgets that change on one event flash together; never on frame 0, while the deck is away (the intro, a card) or on a widget's first appearance. A widget's own `flash` overrides it | `umtool look <p> deck.measure.flash=true` |
| `deck.measure.ghosts.opacity`, `.tolerance` | 0.15–0.9 (the 1× tick's; +0.2 a step, at most 0.95) · 0–5 lb · default `0.5`, `0.5` | `umtool look <p> deck.measure.ghosts='{"tolerance":1}'` |
| `deck.measure.ghosts.ramp`, `.pulse` | 2–4 #hex, 1× first (the last for every count from there up), or `null`: the palette's muted, amber, and amber half way to the needle's red · bool · default `null`, `true` | `umtool look <p> deck.measure.ghosts='{"ramp":["#98a29b","#e8a33f","#f37e47"],"pulse":false}'` |
| `deck.dial.needle` | a #hex · default `#ff5a4e` | `umtool look <p> deck.dial.needle='"#ff5a4e"'` |
@@ -2429,6 +2615,7 @@ A bathroom-scale face at the top of the instruments' column (the right of the fr
| `deck.dial.corner` | `bottom-right` `bottom-left` `top-right` `top-left` · default `bottom-right` (the corner only): the dial in that corner, the odometer and the trail up the same side. The measure extras stand at their own anchors in the footage (goals bottom-right, peak top-right, promise top-centre, diet bottom-left, streak bottom-centre): a corner instrument over one that is on is REFUSED by the build, naming it -- move one (`deck.goals.position`, …) or the corner; `top-left` is clear of all five | `umtool look <p> deck.dial.corner=top-left` |
| `deck.dial.motion` | `spring` `ease` · default `spring`. A VARIANT: the needle's `back.out` overshoot and settle, or a plain `power2.inOut` (the finale's drop too) | `umtool look <p> deck.dial.motion=ease` |
| `deck.dial.finaleEnd` | `auto` `odometer` `promise` · default `auto` (`promise` when a promise is on camera, else `odometer`): `promise` hands the finale's last beat to the promise clock (module `promise`) -- the instruments fade out once NET has held (`dialFinaleHandoff`) and the clock takes their place in the finale's lower column, clear of the rail; with no promise module on the cut it ends on the odometer | `umtool look <p> deck.dial.finaleEnd=promise` |
+| `deck.dial.flash` | bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): the bezel lights as a weight is stated or remembered, or the goal in force changes; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away | `umtool look <p> deck.dial.flash=false` |
### Lost odometer
@@ -2439,10 +2626,11 @@ Under the dial: the measure's `state.lost.total` (the highest real-time loss cla
| `deck.odometer` | `true` · an object of the knobs below · `false` off · absent: ON when the cut draws a measure (`deck.measure` set), else off | `umtool look <p> deck.odometer=false` |
| `deck.odometer.label` | words over the wheels, ≤ 40 · default `POUNDS HE SAYS HE'S LOST` | `umtool look <p> deck.odometer.label='"…"'` |
| `deck.odometer.net`, `.runs` | bool · default `true` each | `umtool look <p> deck.odometer.net=false` |
+| `deck.odometer.flash` | bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): the card lights as the pounds lost go up (or the runs change) and as NET changes; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away | `umtool look <p> deck.odometer.flash=false` |
### Weight trail
-At the foot of the instruments' column: every STATED weight the cut shows, placed by the date he was weighed (its `asOf`, else its date) across the span of them, a dot appearing at its event's `t` and the line between two neighbours drawn once both are said; a red ring on the latest said. The `mark` line (300) dashed across; with `count` and the mark at 300, `UNDER 300 · SAID n×` counts the measure's `totals.under300` rows as the cut reaches each.
+At the foot of the instruments' column: every weight the cut shows -- the STATED ones and (`remembered`) the remembered ones, "≈390, as of Feb 2023" -- placed by the date he was that weight (its `asOf`, else its date), a dot appearing at its event's `t`; the line joins neighbours by date among the stated ones once both are said (a remembered one is a hollow grey dot, never joined; a qualified one hollow). The axes FIT what has been said so far (trail-plan.mjs): each new weight outside them reflows the chart over 0.4 s -- the years, the bounds, every dot -- so the time axis advances with the story; a stretch with no statement longer than `gap` is a break in the time axis (a narrow dashed band, `//` at its foot, each side with its own years) and the line across it dotted, so a decade of nothing does not take the width from the dense run after it. A red ring on the latest said. The `mark` line (300) dashed across; with `count` and the mark at 300, `UNDER 300 · SAID n×` counts the measure's `totals.under300` rows as the cut reaches each.
| Knob | Range · default | From a terminal |
|---|---|---|
@@ -2450,6 +2638,10 @@ At the foot of the instruments' column: every STATED weight the cut shows, place
| `deck.trail.mark` | a weight, or `null` · default `300` | `umtool look <p> deck.trail.mark=300` |
| `deck.trail.count` | bool · default `true` | `umtool look <p> deck.trail.count=false` |
| `deck.trail.label` | its title, ≤ 40 · default `WHAT HE SAYS HE WEIGHS, BY DATE` | `umtool look <p> deck.trail.label='"…"'` |
+| `deck.trail.bounds` | `fit` · `fixed` · default `fit`: the axes fit the weights said so far and reflow as each lands; `fixed` lays every moment on the axes of all the cut's weights | `umtool look <p> deck.trail.bounds=fixed` |
+| `deck.trail.remembered` | bool · default `true`: his remembered weights are points too, hollow and grey, not joined into the line | `umtool look <p> deck.trail.remembered=false` |
+| `deck.trail.gap` | `auto` · days 30–3650 · `0` none · default `auto`: a stretch with no statement longer than a year (or 8× the median spacing, if longer) is a break in the time axis | `umtool look <p> deck.trail.gap=540` |
+| `deck.trail.flash` | bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): the card lights as each weight lands on it; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away | `umtool look <p> deck.trail.flash=false` |
### Flips
@@ -2507,6 +2699,7 @@ A days-since counter for a promise (`render.chrome.deck.promise`, measure-extras
| `deck.promise.position`, `.x`/`.y`, `.scale` | an anchor in the footage box · design px · 0.5–2 · default `top-center`, unset, 1 | `umtool look <p> deck.promise.position=bottom-center` |
| `deck.promise.hold`, `.finale` | 0 (stays up) or 2–600 s · `hide` `show` · default 0, `show` | `umtool look <p> deck.promise.finale=hide` |
| `deck.promise.label`, `.verb`, `.kept`, `.broken`, `.checks` | ≤40 each · `label` `quote` · default the row's display, "offered", "Posted", "None posted", `label` | `umtool look <p> deck.promise.label='scale video'` |
+| a `promise_outcome` row's `stampNote` | one line, 1–80 characters · unset (default): the clock's own words under the stamp, "by <date> · no video". The row's note is that second line instead (REFUNDED / "by her account · no receipt"); the strip over a post's card, which has one line for everything, shows its first clause (to its first `·`, `;`, `—`, `, ` or ` -- `: "refunded · by her account"). It is the ledger row's, so every take of the project reads it. `umtool lint` warns past 26 characters (the stamp's line is never wrapped: a longer one runs past its border) | `umtool ledger <p> set <row> --stampNote "by her account · no receipt"` · off again: `--stampNote null` |
| `deck.promise.speakers`, `.claimVerb`, `.claimColor` | `{<speaker>: {handle, color}}` · ≤40 · #hex · default `{}` (the postAvatars handle), "paid", #E37AB8 | `umtool look <p> deck.promise.speakers='{"madamsavvy":{"handle":"MadamSavvy"}}'` |
| `deck.promise.onPosts`, `.onChapters` | `dodge` `hide` `show` · default `dodge`: while a post item's card (its card, slot and strip as postLayout lays them: the schedule's `covers`) or a chapter band is up where it stands, it moves to a free anchor of the footage box -- a size down to half if it must, never onto another measure extra that is up -- and hides when none fits; `hide` hides, `show` stays over it | `umtool look <p> deck.promise.onPosts=hide` |
| a timeline entry's `hideModules` | `["promise", …]` on an entry hides it over that entry's span, with its own fade, whatever it would otherwise do there (text in the footage no dodge can know of) · any entry, a post item too | `umtool set <p> <entry> hideModules=promise` (`--take <t>` for a take) |
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -667,7 +667,13 @@ part is written to `narration/posts/<postId>/.recording-<label>/` the moment it
(`lib/report/recordSession.mjs`: a crash loses at most the part being read, a reload
resumes at the first part not kept); when the last part is in, the parts become the post's
recorded take (below) and it is picked. Chromium and Firefox (webm or ogg opus), no network
-beyond localhost.
+beyond localhost. With **Filter before keeping** (on by itself for a post whose character has
+a stock voice to convert to) the post waits instead: its cut marks on a waveform, **Filter**
+(the character's recorded preset as one job, into a preview — no take), the raw and filtered
+reads side by side, **Keep** / **Again**
+([knobs.md](knobs.md#record-filter-preview-on-the-record-page)). The microphone needs
+localhost or https: opened over http from the LAN the page says so, and a sound file can be
+chosen for a part.
**Recorded takes** — the post bench's recording session: the mic (remembered per
browser), a level meter, a 3-2-1 count-in, the script as a teleprompter with the part
diff --git a/umtool/e2e/fixtures/editor-stub-archives.mjs b/umtool/e2e/fixtures/editor-stub-archives.mjs
@@ -0,0 +1,109 @@
+// demo epic D1: a published archive served by the stub editor's own port,
+// under /archive-stub (the synthetic draft corpus — common/testing/draft — as
+// a site serves it), and the editor's `archives` action (POST
+// /api/ops/archives): `connect` reads the origin's corpus.json and, unless
+// `dryRun`, writes settings.remoteArchives into E2E_UMTOOL_SETTINGS_FILE (the
+// fixture's copy, which umtool's source picker reads); `remove` drops one.
+// Nothing leaves loopback.
+
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs";
+
+export const ARCHIVE_PREFIX = "/archive-stub";
+
+/** Write the stub archive's files under `dir` (once, at the stub's start). */
+export async function prepareArchiveStub(dir) {
+ mkdirSync(dir, { recursive: true });
+ await writeDraftCorpus(dir);
+ const corpus = JSON.parse(readFileSync(path.join(dir, "corpus.json"), "utf8"));
+ writeFileSync(
+ path.join(dir, "corpus.json"),
+ JSON.stringify({ ...corpus, spec: 6, generatedAt: new Date().toISOString(), site: { id: "stubalyzer", title: "Stubalyzer" } }),
+ );
+}
+
+/**
+ * GET /archive-stub/<file>: the archive's static files, written on the first
+ * ask (make-fixture.mjs empties the fixture root while the stub starts, so
+ * nothing is written before a spec asks). True when answered.
+ */
+export function archiveStubRoute(req, res, url, { dir }) {
+ if (req.method !== "GET" || !url.pathname.startsWith(`${ARCHIVE_PREFIX}/`)) return false;
+ const rel = decodeURIComponent(url.pathname.slice(ARCHIVE_PREFIX.length));
+ const file = path.normalize(path.join(dir, rel));
+ if (!file.startsWith(dir)) {
+ res.writeHead(403).end();
+ return true;
+ }
+ const ready = existsSync(path.join(dir, "corpus.json")) ? Promise.resolve() : prepareArchiveStub(dir);
+ ready.then(
+ () => {
+ try {
+ const body = readFileSync(file);
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(body);
+ } catch {
+ res.writeHead(404).end("not found");
+ }
+ },
+ (e) => res.writeHead(500).end(String(e?.message ?? e)),
+ );
+ return true;
+}
+
+const settingsOf = (file) => {
+ try {
+ return JSON.parse(readFileSync(file, "utf8"));
+ } catch {
+ return {};
+ }
+};
+
+/** POST /api/ops/archives. True when answered. */
+export function archivesRoute(req, res, url, { json, readBody, settingsFile }) {
+ if (url.pathname !== "/api/ops/archives") return false;
+ if (req.method === "GET") {
+ json(res, 200, { ok: true, archives: settingsOf(settingsFile).remoteArchives ?? [] });
+ return true;
+ }
+ if (req.method !== "POST") return false;
+ readBody(req, async (body) => {
+ const settings = settingsOf(settingsFile);
+ const list = Array.isArray(settings.remoteArchives) ? settings.remoteArchives : [];
+ if (typeof body?.remove === "string") {
+ const next = list.filter((a) => a.id !== body.remove && a.origin !== body.remove);
+ writeFileSync(settingsFile, JSON.stringify({ ...settings, remoteArchives: next }, null, 2));
+ return json(res, 200, { ok: true, removed: list.find((a) => !next.includes(a)) ?? null });
+ }
+ const origin = String(body?.connect ?? "").trim().replace(/\/+$/, "");
+ if (!/^https?:\/\//.test(origin)) return json(res, 400, { ok: false, error: `"${origin}" is not an archive's address` });
+ let corpus;
+ try {
+ const r = await fetch(`${origin}/corpus.json`);
+ if (!r.ok) return json(res, 502, { ok: false, error: `${origin}/corpus.json answered HTTP ${r.status}` });
+ corpus = await r.json();
+ } catch (e) {
+ return json(res, 502, { ok: false, error: `${origin}/corpus.json did not answer: ${e.message}` });
+ }
+ const channels = (corpus.channels ?? []).map((c) => ({ slug: c.slug, name: c.name ?? c.slug, videoCount: c.videoCount ?? null }));
+ const probe = {
+ origin,
+ siteId: corpus.site?.id ?? null,
+ title: corpus.site?.title ?? origin,
+ description: "",
+ spec: corpus.spec ?? null,
+ generatedAt: corpus.generatedAt ?? null,
+ totals: { channels: channels.length, videos: channels.reduce((n, c) => n + (c.videoCount ?? 0), 0) },
+ channels,
+ };
+ const have = list.find((a) => a.origin === origin);
+ const archive = have ?? { id: probe.siteId ?? "archive", origin, title: probe.title, addedAt: new Date().toISOString() };
+ if (!have && body?.dryRun !== true) {
+ mkdirSync(path.dirname(settingsFile), { recursive: true });
+ writeFileSync(settingsFile, JSON.stringify({ ...settings, remoteArchives: [...list, archive] }, null, 2));
+ }
+ return json(res, 200, { ok: true, probe, archive, already: have ? true : body?.dryRun === true ? null : false });
+ });
+ return true;
+}
diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs
@@ -27,6 +27,7 @@ import { fileURLToPath } from "node:url";
import { fetchWindowsRoute } from "./editor-stub-fetch-windows.mjs";
import { importPageRoute } from "./editor-stub-import-page.mjs";
import { caseStagesRoute } from "./editor-stub-case-stages.mjs";
+import { archiveStubRoute, archivesRoute } from "./editor-stub-archives.mjs";
import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
import { readSuggestions, suggestionsDocOf, writeSuggestions } from "yt-dlp-transcript-common/lib/clips/suggest.mjs";
import { checkAssistOps } from "yt-dlp-transcript-common/lib/report/videoAssistOps.mjs";
@@ -36,6 +37,11 @@ import { checkGroupProposals, cutSections, groupProposalsDocOf, writeGroupPropos
const PORT = portFor("EDITOR_STUB_PORT");
const CHANNELS = process.env.CHANNELS_DIR ?? "";
const TOKEN = process.env.WORKER_TOKEN ?? "";
+// demo epic D1: the published archive this stub serves (/archive-stub) and the
+// settings file its `archives` action writes — the fixture's, which umtool's
+// source picker reads (playwright.config.ts E2E_UMTOOL_SETTINGS_FILE).
+const ARCHIVE_STUB_DIR = path.join(path.dirname(CHANNELS || process.cwd()), "archive-stub");
+const SETTINGS = process.env.E2E_UMTOOL_SETTINGS_FILE ?? path.join(path.dirname(CHANNELS || process.cwd()), "settings.json");
// Where the spec reads what was asked for.
const LOG = process.env.E2E_EDITOR_STUB_LOG ?? path.join(process.cwd(), "editor-stub.requests.json");
@@ -1223,6 +1229,8 @@ const server = http.createServer((req, res) => {
const url = new URL(req.url ?? "/", `http://127.0.0.1:${PORT}`);
if (url.pathname === "/health") return json(res, 200, { ok: true });
+ // A published archive's files (demo epic D1): public, like a site's.
+ if (archiveStubRoute(req, res, url, { dir: ARCHIVE_STUB_DIR })) return;
// A job's log is ungated on the editor (GET /api/jobs/<id>/log).
if (url.pathname.startsWith("/api/jobs/") && fetchWindowsRoute(req, res, url, fwCtx)) return;
@@ -1265,6 +1273,8 @@ const server = http.createServer((req, res) => {
// Release 37 S4: Import this capture (editor-stub-import-page.mjs).
if (importPageRoute(req, res, url, { channels: CHANNELS, json, readBody, push: (r) => (requests.push(r), record()) })) return;
if ((url.pathname === "/api/ops/fetch-windows" || url.pathname.startsWith("/api/ops/job/")) && fetchWindowsRoute(req, res, url, fwCtx)) return;
+ // demo epic D1: Connect an archive (the Source chip).
+ if (archivesRoute(req, res, url, { json, readBody, settingsFile: SETTINGS })) return;
if (url.pathname.startsWith("/api/ops/") && generationRoute(req, res, url, auth) !== null) return;
// THE OPS DOOR, stubbed alongside the media one.
@@ -1441,7 +1451,9 @@ const server = http.createServer((req, res) => {
return json(res, 200, {
ok: true,
job: { id: opsJob[1], kind: j.kind ?? "tts-file", status },
- ...(tail ? { tail: ["tts: synthesizing (stub)", `${j.marker ?? "@@tts-result "}${JSON.stringify(j.result)}`] } : {}),
+ // A voice-convert that is still running is at the machine's heavy slot, and says so as the editor's job does
+ // (scripts/queue-lock.mjs): the record page's Filter shows it as a wait, not an error.
+ ...(tail ? { tail: status === "running" && j.kind === "voice-convert" ? ["heavy: waiting for memory — 4100 MB available, the floor is 6000 MB", " (HEAVY_MIN_FREE_MB=<MB> to change it; 0, or HEAVY=0, to skip it)"] : ["tts: synthesizing (stub)", `${j.marker ?? "@@tts-result "}${JSON.stringify(j.result)}`] } : {}),
});
}
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -21,6 +21,7 @@ import {
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import path from "node:path";
+import { fileURLToPath } from "node:url";
import { SONG_DATA } from "../../song/paths.mjs";
import { songCapabilities } from "./song-capabilities.mjs";
import { makeSitesFixture } from "./sites-fixture.mjs";
@@ -38,6 +39,7 @@ import { makeTakeWalkFixture } from "./take-walk-fixture.mjs";
import { makeCutIntegrityFixture } from "./cut-integrity-fixture.mjs";
import { makeUiOpsFixture } from "./ui-ops-fixture.mjs";
import { makeVoicesFixture } from "./voices-fixture.mjs";
+import { makeRecordFilterFixture } from "./record-filter-fixture.mjs";
import { makeYoutubeFixture } from "./youtube-fixture.mjs";
import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs";
import { makeCaseStagesFixture } from "./case-stages-fixture.mjs";
@@ -1922,6 +1924,8 @@ makeCutIntegrityFixture({ reports, manifest, cachedWindow: path.join(REPORT, "ou
makeUiOpsFixture({ reports, channels: CHANNELS, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), ff });
// The Voices page (voices.spec.ts): Host's clips (the real voice) and post items by @hostman and @guest.
makeVoicesFixture({ reports, channels: CHANNELS, manifest, ff });
+// Record -> filter -> preview on the record page (record-filter.spec.ts): three one-part post items, no cast.
+makeRecordFilterFixture({ reports, manifest });
// Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts).
makeYoutubeFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Release 36 lane D: the assistant's labels, Suggest, Ask and Apply in the clip editor (clips-suggest.spec.ts).
@@ -2608,6 +2612,14 @@ makeDeleteFixture({ dest, articles: ARTICLES, reports });
// R1: Research's local corpus (research-public/, TRANSCRIPT_LOCAL_DIR) and the
// held channels its inventory reads on disk.
const { pub: RESEARCH_PUBLIC } = makeResearchFixture({ dest, channels: CHANNELS });
+// demo epic D1: the settings file the app and the editor stub read
+// (playwright.config.ts SETTINGS_FILE) -- a copy of the checkout's, so every
+// spec reads what it read before, and Connect an archive (remote-archive.spec)
+// writes the fixture's, never the checkout's. A clone with none: {}.
+{
+ const checkout = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "settings.json");
+ writeFileSync(path.join(dest, "settings.json"), existsSync(checkout) ? readFileSync(checkout, "utf8") : "{}\n");
+}
// Two channel context notes to review (digest-context.spec.ts), on channels already made above.
makeDigestContextFixture({ dest, channels: CHANNELS });
// R2: a research board with a drifted quote and an `en`-track one (REPORTS_ROOT is dest).
diff --git a/umtool/e2e/fixtures/record-filter-fixture.mjs b/umtool/e2e/fixtures/record-filter-fixture.mjs
@@ -0,0 +1,32 @@
+// RECORD -> FILTER -> PREVIEW (record-filter.spec.ts; components/projects/RecordSession.tsx, lib/report/
+// recordPreview.mjs): a posts cut of three items, each a one-part read --
+//
+// reports/record-filter-fixture/
+// p-1 @savvy "Savvy's first line, read aloud." the spec gives @savvy a character of this video's own
+// p-2 @savvy "Savvy's second line." (narration/characters.json: seed-vc, contour +2, a direction)
+// p-3 @stranger "A stranger says a thing." nobody's: no character, and the fixture has no cast
+//
+// No take, no character and no cast of its own: the spec writes this video's characters and removes what it made. The
+// editor is the suite's stub (voice-enhance: not installed; voice-convert: copies, after one poll at the heavy slot).
+// Synthetic, like every fixture.
+import { mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+export const RECORD_FILTER = "record-filter-fixture";
+
+/** @param {{ reports: string, manifest: Function }} o */
+export function makeRecordFilterFixture({ reports, manifest }) {
+ const dir = path.join(reports, RECORD_FILTER);
+ mkdirSync(dir, { recursive: true });
+ const post = (id, handle, author, text) => ({
+ type: "post", id: `p-${id}`, post: `recordfilter-x/${id}`, platform: "x", author, handle, date: `2026-11-0${id}T10:00:00.000Z`, text,
+ url: `https://x.com/${handle}/status/${id}`, engagement: { likes: 1 }, section: 0, narration: { script: text },
+ });
+ const timeline = [
+ post("1", "savvy", "Madam Savvy", "Savvy's first line, read aloud."),
+ post("2", "savvy", "Madam Savvy", "Savvy's second line."),
+ post("3", "stranger", "A Stranger", "A stranger says a thing."),
+ ];
+ writeFileSync(path.join(dir, "video.manifest.json"), `${JSON.stringify(manifest(RECORD_FILTER, "The Record Filter Fixture", { siteOrigin: "https://archive.example", channelSlug: "recordfilter" }, timeline), null, 2)}\n`);
+ return dir;
+}
diff --git a/umtool/e2e/inbox.spec.ts b/umtool/e2e/inbox.spec.ts
@@ -32,6 +32,15 @@ const setLife = (request: APIRequestContext, piece: string, state: string) =>
request.post("/api/pieces/lifecycle", { data: { piece, state } });
const card = (page: Page, piece: string, kind: string) => page.locator(`[data-lit-line][data-piece='${piece}'][data-card='${kind}']`);
+// A WRITE, THEN THE LIST AGAIN. Park, Mark done, Reactivate, Mute, Unmute and Undo POST, then router.refresh(): the
+// list changes when the refreshed page has been rendered and streamed whole. Three failures of this spec (11 Nov:
+// :122 Reactivate, :178 Unmute, and Undo after Mark done) were all that step late, not wrong: the POST had answered
+// 200 and the refresh's request had gone out and been answered, the lifecycle and the mutes are read from disk on
+// every render (never memoised), and in the one trace that shows it a HEAD of the same page, sent in the same
+// second, took 5.8 s to answer -- the server was that slow for those seconds (another suite's build beside it) and
+// the default 5 s expect gave up first. So the FIRST look at the list after such a write waits this long.
+const SETTLES = { timeout: 20_000 };
+
test.beforeAll(async ({ playwright }) => {
test.setTimeout(WARM_TIMEOUT);
await warm(playwright, ["/", "/?hidden=1", "/api/browse/decisions", "/api/rail", "/settings/system", "/projects"]);
@@ -46,7 +55,15 @@ test("the big count is the cards in the five call groups; the groups come in the
// cards too; on the fixture with nothing probed there are none to count on.
const machine = await page.locator("[data-card^='machine-']").count();
await expect(page.locator("[data-inbox-count]")).toHaveAttribute("data-inbox-count", String(calls + machine));
- await expect(page.locator("[data-rail-count=inbox]")).toHaveText(String(calls + machine));
+ // The rail's count is memoised for a few seconds (lib/rail.ts) and asked once per page load: one
+ // filled before the fixture's last write (the warm-up asks /api/rail) is that much behind, so a
+ // rail that disagrees is asked again once the memo has lapsed.
+ const rail = page.locator("[data-rail-count=inbox]");
+ await expect(async () => {
+ await expect(rail).toHaveText(/^\d+$/);
+ if ((await rail.textContent()) !== String(calls + machine)) await page.reload();
+ await expect(rail).toHaveText(String(calls + machine), { timeout: 2_000 });
+ }).toPass({ timeout: 25_000 });
await expect(page.locator("[data-inbox-note]")).toContainText("quiet");
const shown = await page.locator("[data-lit-list] [data-group]").evaluateAll((els) => els.map((e) => e.getAttribute("data-group")));
@@ -87,6 +104,7 @@ test("j lights the next card, and only the lit card's action wears Signal", asyn
});
test("Park hides a piece's calls, Undo brings them back; Show hidden lists them with Reactivate", async ({ page, request }) => {
+ test.slow(); // room for SETTLES on a loaded machine
try {
await page.goto(urls.homeHref());
const ready = card(page, ZETA, "iteration-ready");
@@ -96,12 +114,12 @@ test("Park hides a piece's calls, Undo brings them back; Show hidden lists them
await ready.click();
await ready.locator("[data-lifecycle-to=parked]").click();
await expect(page.locator(`[data-undo='${ZETA}']`)).toContainText("Parked");
- await expect(page.locator(`[data-lit-line][data-piece='${ZETA}']`)).toHaveCount(0);
+ await expect(page.locator(`[data-lit-line][data-piece='${ZETA}']`)).toHaveCount(0, SETTLES);
await expect(page.locator("[data-inbox-count]")).not.toHaveAttribute("data-inbox-count", String(before));
await expect(page.locator("[data-show-hidden]")).toContainText(/^Show hidden \d+$/);
await page.locator(`[data-undo='${ZETA}']`).getByRole("button", { name: "Undo" }).click();
- await expect(ready).toBeVisible();
+ await expect(ready).toBeVisible(SETTLES);
await expect(page.locator("[data-inbox-count]")).toHaveAttribute("data-inbox-count", String(before));
// Parked again, it is listed under Hidden, and Reactivate is its action.
@@ -111,7 +129,7 @@ test("Park hides a piece's calls, Undo brings them back; Show hidden lists them
await expect(hidden).toBeVisible();
await hidden.click();
await hidden.locator("[data-lifecycle-to=active]").click();
- await expect(page.locator(`[data-group=hidden] [data-lit-line][data-piece='${ZETA}']`)).toHaveCount(0);
+ await expect(page.locator(`[data-group=hidden] [data-lit-line][data-piece='${ZETA}']`)).toHaveCount(0, SETTLES);
await expect(card(page, ZETA, "iteration-ready")).toBeVisible();
} finally {
await setLife(request, ZETA, "active");
@@ -119,6 +137,7 @@ test("Park hides a piece's calls, Undo brings them back; Show hidden lists them
});
test("Mark done on a piece that looks done takes it off the Inbox; Undo puts it back", async ({ page, request }) => {
+ test.slow(); // room for SETTLES on a loaded machine
try {
await page.goto(urls.homeHref());
const done = page.locator(`[data-group=ready-to-finish] [data-piece='${ALPHA}'][data-card='looks-done']`);
@@ -126,15 +145,16 @@ test("Mark done on a piece that looks done takes it off the Inbox; Undo puts it
await done.click();
await done.locator("[data-lifecycle-to=done]").click();
await expect(page.locator(`[data-undo='${ALPHA}']`)).toContainText("Marked done");
- await expect(done).toHaveCount(0);
+ await expect(done).toHaveCount(0, SETTLES);
await page.locator(`[data-undo='${ALPHA}']`).getByRole("button", { name: "Undo" }).click();
- await expect(done).toBeVisible();
+ await expect(done).toBeVisible(SETTLES);
} finally {
await setLife(request, ALPHA, "active");
}
});
test("Mute is the server's: the card leaves, its rows stay hidden-by-muted, Muted N lists it with Unmute", async ({ page, request }) => {
+ test.slow(); // room for SETTLES on a loaded machine
const rows = async () =>
((await (await request.get("/api/browse/decisions")).json()) as { items: { piece?: string; kind: string; hidden: boolean; hiddenBy?: string }[]; muted: number })
try {
@@ -145,7 +165,7 @@ test("Mute is the server's: the card leaves, its rows stay hidden-by-muted, Mute
await ready.click();
await ready.locator("[data-mute=mute]").click();
await expect(page.locator(`[data-undo='${ZETA}']`)).toContainText("Muted");
- await expect(ready).toHaveCount(0);
+ await expect(ready).toHaveCount(0, SETTLES);
// Never dropped: every row is still in the API, hidden, and says why.
const after = await rows();
@@ -167,7 +187,7 @@ test("Mute is the server's: the card leaves, its rows stay hidden-by-muted, Mute
await expect(muted).toHaveAttribute("data-muted", "");
await muted.click();
await muted.locator("[data-mute=unmute]").click();
- await expect(muted).toHaveCount(0);
+ await expect(muted).toHaveCount(0, SETTLES);
await expect(page.locator(`[data-group=review] [data-lit-line][data-piece='${ZETA}'][data-card='iteration-ready']`)).toBeVisible();
expect((await rows()).items.filter((d) => d.piece === ZETA && d.kind === "iteration-ready").every((d) => !d.hidden)).toBe(true);
} finally {
diff --git a/umtool/e2e/instruments.spec.ts b/umtool/e2e/instruments.spec.ts
@@ -158,7 +158,10 @@ test("the odometer and the trail post ready and seek: the wheels only roll up, t
await trail.seek(0.3);
await expect.poll(shown).toBe(0);
await trail.seek(tEnd());
- await expect.poll(shown).toBe(3);
+ // Every weight said so far: the three stated (>240, <300, 291.5) and the remembered ≈390, hollow, at its as-of date.
+ await expect.poll(shown).toBe(4);
+ const remembered = () => trail.frame.locator(".pt.rem").evaluateAll((ps) => ps.filter((p) => Number(getComputedStyle(p).opacity) > 0.5).length);
+ await expect.poll(remembered).toBe(1);
await expect(trail.frame.locator('[data-k="uc1"]')).toContainText("UNDER 300 · SAID 2×");
await expect(trail.frame.locator('[data-k="uc1"]')).toBeVisible();
});
diff --git a/umtool/e2e/record-filter.spec.ts b/umtool/e2e/record-filter.spec.ts
@@ -0,0 +1,326 @@
+import { test, expect, type Page } from "@playwright/test";
+import { execFileSync } from "node:child_process";
+import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// RECORD -> FILTER -> PREVIEW on the record page (components/projects/RecordSession.tsx, RecordFilter.tsx;
+// /api/report/post-narration/record; lib/report/recordPreview.mjs). Fixture: e2e/fixtures/record-filter-fixture.mjs
+// -- p-1 and p-2 by @savvy (the spec gives her a character of this video's own: seed-vc, contour +2, a direction),
+// p-3 by @stranger (nobody's). The editor is the suite's stub: voice-enhance is not installed, voice-convert copies
+// after one poll at the heavy slot ("waiting for memory").
+//
+// Filter -> the preview (no take), the wait at the heavy slot a state, raw and filtered side by side -> another
+// pitch asks for the convert again -> Save to character -> Keep: the takes from the preview's files, the next post
+// Again; nobody's post: nothing to convert, Keep in this video only, the recording kept alone
+// the microphone off (a page opened over http from the LAN): said, and a sound file filtered and kept all the same
+//
+// RECORD_FILTER_SHOTS=<dir> screenshots there
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const P = "reports/record-filter-fixture";
+const DIR = path.join(FIXTURE, "reports", "record-filter-fixture");
+const MANIFEST = path.join(DIR, "video.manifest.json");
+const NARRATION = path.join(DIR, "narration");
+const CHARACTERS = path.join(NARRATION, "characters.json");
+const SCRATCH = (post: string) => path.join(NARRATION, ".record-preview", `${post}.operator`);
+const REQUESTS = path.join(FIXTURE, "editor-stub.requests.json");
+const SHOTS = process.env.RECORD_FILTER_SHOTS ?? null;
+/** A voice for the fake microphone (and the file chosen where there is none): a 1 kHz tone, two seconds. */
+const MIC_WAV = path.join(FIXTURE, "record-filter-mic.wav");
+
+type Take = { file: string; engine?: string; voice?: string; note?: string; seconds: number; source?: { kind: string; from?: string }; steps?: { op: string; engine?: string; voice?: string; pitch?: string; semitones?: number }[] };
+type Entry = { id: string; narration?: { script?: string; takes?: Take[]; pick?: number; approved?: boolean } };
+const narr = (id: string) => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[] }).timeline.find((e) => e.id === id)!.narration!;
+const converts = () => (JSON.parse(readFileSync(REQUESTS, "utf8")) as { route?: string; engine?: string; voice?: string; pitch?: string; semitones?: number; file?: string; out?: string }[]).filter((r) => r.route === "voice-convert");
+const characters = () => (JSON.parse(readFileSync(CHARACTERS, "utf8")) as { characters: { id: string; handles?: string[]; recorded?: { convert?: { engine?: string; voice?: string; pitch?: string; semitones?: number } } }[] }).characters;
+const shot = async (page: Page, name: string) => {
+ if (!SHOTS) return;
+ mkdirSync(SHOTS, { recursive: true });
+ await page.screenshot({ path: path.join(SHOTS, `${name}.png`), fullPage: true });
+};
+
+if (!existsSync(MIC_WAV)) {
+ mkdirSync(FIXTURE, { recursive: true });
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=1000:sample_rate=48000:duration=2", "-ac", "1", MIC_WAV]);
+}
+
+// A fake microphone and audio that may start without a gesture, for the whole file.
+test.use({ launchOptions: { args: ["--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream", `--use-file-for-fake-audio-capture=${MIC_WAV}`, "--autoplay-policy=no-user-gesture-required"] } });
+
+test.beforeAll(() => {
+ if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`);
+});
+const reset = () => {
+ copyFileSync(`${MANIFEST}.pristine`, MANIFEST);
+ rmSync(NARRATION, { recursive: true, force: true });
+ rmSync(path.join(DIR, "revisions"), { recursive: true, force: true });
+};
+/** @savvy's character of this video's own: converted by seed-vc to a stock voice, contour +2, a direction to read by. */
+const giveSavvy = () => {
+ mkdirSync(NARRATION, { recursive: true });
+ writeFileSync(CHARACTERS, `${JSON.stringify({
+ format: "umtool-project-characters", version: 1,
+ characters: [{ id: "madam-savvy", name: "Madam Savvy", handles: ["savvy"], synthetic: { voice: "kokoro:af_bella" }, recorded: { convert: { engine: "seed-vc", pitch: "contour", semitones: 2 }, direction: "higher, brisk, amused" } }],
+ }, null, 2)}\n`);
+};
+test.beforeEach(async ({ page }) => {
+ test.setTimeout(180_000);
+ reset();
+ // "Filter before keeping" as the page decides it (on for a post whose character converts), whatever a test before left.
+ await page.addInitScript(() => {
+ try {
+ window.localStorage.removeItem("umtool.record.filter-first");
+ window.localStorage.setItem("umtool.record.count-in", "0");
+ } catch {
+ // no storage here
+ }
+ });
+});
+test.afterAll(reset);
+
+const s = (page: Page) => page.locator("[data-record-session]");
+/** Space, a second of the fake microphone, Space: the part is on disk. */
+const recordPart = async (page: Page) => {
+ await page.keyboard.press("Space");
+ await expect(s(page)).toHaveAttribute("data-record-phase", "recording", { timeout: 15_000 });
+ await page.waitForTimeout(1200);
+ await page.keyboard.press("Space");
+ await expect(s(page)).toHaveAttribute("data-record-phase", "idle", { timeout: 15_000 });
+};
+const filterDone = async (page: Page) => {
+ await expect(page.locator("[data-record-filter-job]")).toHaveAttribute("data-record-filter-job", "done", { timeout: 90_000 });
+};
+
+test("Filter runs the character's recorded preset as one job into a preview (no take); raw and filtered side by side; another pitch; Save to character; Keep makes the takes and opens the next post", async ({ page }) => {
+ giveSavvy();
+ await page.setViewportSize({ width: 1366, height: 1100 });
+ await page.goto(urls.narrationRecordHref(P, { post: "p-1" }));
+ await expect(s(page)).toHaveAttribute("data-record-session", "p-1");
+ // Who it is read as, above the record button: the character, its direction, its stock voice to hear.
+ const who = page.locator("[data-record-character]");
+ await expect(who).toHaveAttribute("data-record-character", "madam-savvy");
+ await expect(who).toHaveAttribute("data-record-character-layer", "project");
+ await expect(page.locator("[data-record-character-name]")).toHaveText("Madam Savvy");
+ await expect(page.locator("[data-record-direction]")).toContainText("higher, brisk, amused");
+ await expect(page.locator("[data-record-stock]")).toContainText("kokoro:af_bella reads it");
+ // Her character converts: the post waits to be filtered. The microphone is here (localhost): no note.
+ await expect(page.locator("[data-record-review]")).toBeChecked();
+ await expect(page.locator("[data-record-no-mic]")).toHaveCount(0);
+ await expect(page.locator("[data-record-review-panel]")).toHaveCount(0);
+
+ // Record it: NO take is made -- the waveform with its two cut marks, the pitch from the preset.
+ await recordPart(page);
+ const panel = page.locator("[data-record-review-panel]");
+ await expect(panel).toBeVisible();
+ await expect(page.locator('[data-record-wave="1"]')).toBeVisible({ timeout: 20_000 });
+ expect(narr("p-1").takes ?? []).toHaveLength(0);
+ await expect(page.locator("[data-record-pitch]")).toHaveValue("contour");
+ await expect(page.locator("[data-record-semitones]")).toHaveValue("2");
+ await expect(page.locator("[data-record-keep]")).toHaveAttribute("data-record-keep-what", "recording");
+ // A cut mark moved (a keyboard click at the start): four presses of the arrow, 0.2 s in.
+ const from = page.locator('[data-record-mark="from"]');
+ const markAt = async () => Number(await from.getAttribute("data-record-mark-at"));
+ const auto = await markAt();
+ await from.focus();
+ for (let i = 0; i < 4; i += 1) await page.keyboard.press("ArrowRight");
+ await expect.poll(markAt).toBeCloseTo(auto + 0.2, 2);
+ await expect(page.locator("[data-record-span-auto]")).toBeVisible();
+ await shot(page, "record-filter-marks");
+
+ // FILTER (f): one job -- the clean skipped (the stub has no enhance engine), cut, converted; its wait at the heavy
+ // slot was a state on the way, and nothing failed.
+ await page.locator("[data-record-teleprompter]").click({ position: { x: 2, y: 2 } });
+ await page.keyboard.press("f");
+ await expect(page.locator("[data-record-filter-job]")).toBeVisible({ timeout: 15_000 });
+ await filterDone(page);
+ const job = page.locator("[data-record-filter-job]");
+ await expect(job).toHaveAttribute("data-record-filter-waited", /memory/);
+ await expect(job.locator('[data-record-filter-step="clean"]')).toHaveAttribute("data-record-filter-step-state", "skipped");
+ await expect(job.locator('[data-record-filter-step="trim"]')).toHaveAttribute("data-record-filter-step-state", "done");
+ await expect(job.locator('[data-record-filter-step="convert"]')).toHaveAttribute("data-record-filter-step-state", "done");
+ await expect(page.locator("[data-record-filter-error]")).toHaveCount(0);
+ // The preview, in the scratch dir; still no take.
+ expect(existsSync(path.join(SCRATCH("1"), "raw.wav"))).toBe(true);
+ expect(existsSync(path.join(SCRATCH("1"), "filtered.wav"))).toBe(true);
+ expect(narr("p-1").takes ?? []).toHaveLength(0);
+ const asked = converts().at(-1)!;
+ expect(asked).toMatchObject({ engine: "seed-vc", voice: "kokoro:af_bella", pitch: "contour", semitones: 2 });
+ expect(asked.file).toMatch(/narration\/\.record-preview\/1\.operator\/raw\.wav$/);
+ await expect(panel).toHaveAttribute("data-record-preview-current", "1");
+ await expect(page.locator("[data-record-preview-note]").first()).toContainText("not cleaned");
+ // Raw and filtered, side by side.
+ await expect(page.locator("[data-record-compare-what]")).toContainText("converted to kokoro:af_bella by seed-vc · pitch contour +2 st · both at one loudness");
+ const player = page.locator("[data-record-player]");
+ await page.locator("[data-record-play-raw]").click();
+ await expect(player).toHaveAttribute("src", /preview&file=raw/);
+ await page.locator("[data-record-play-filtered]").click();
+ await expect(player).toHaveAttribute("src", /preview&file=filtered/);
+ await shot(page, "record-filter-preview");
+
+ // Another pitch: the preview is not of it any more; Filter again asks for the convert, at that pitch.
+ const before = converts().length;
+ await page.locator("[data-record-pitch]").selectOption("source");
+ await expect(panel).toHaveAttribute("data-record-preview-current", "0");
+ await expect(page.locator("[data-record-preview-stale]")).toBeVisible();
+ await page.locator("[data-record-filter]").click();
+ await expect(panel).toHaveAttribute("data-record-preview-current", "1", { timeout: 90_000 });
+ expect(converts()).toHaveLength(before + 1);
+ expect(converts().at(-1)).toMatchObject({ pitch: "source", semitones: 2, voice: "kokoro:af_bella" });
+ await expect(page.locator('[data-record-filter-step="trim"]')).toHaveAttribute("data-record-filter-step-state", "cached");
+ // Save to character: this video's own character keeps the pitch.
+ await page.locator("[data-record-save-character]").click();
+ await expect(page.locator("[data-record-saved]")).toContainText("saved to Madam Savvy (this video's own)");
+ expect(characters().find((c) => c.id === "madam-savvy")!.recorded!.convert).toMatchObject({ engine: "seed-vc", pitch: "source", semitones: 2 });
+ await expect(page.locator("[data-record-save-character]")).toBeDisabled();
+
+ // KEEP (Enter): the takes from the preview's files -- nothing converted again -- the last picked, awaiting approval;
+ // the scratch dir and the session are gone; the next post not recorded is open.
+ const convertsBefore = converts().length;
+ await page.locator("[data-record-teleprompter]").click({ position: { x: 2, y: 2 } });
+ await page.keyboard.press("Enter");
+ await expect(s(page)).toHaveAttribute("data-record-session", "p-2", { timeout: 30_000 });
+ await expect(page.locator("[data-record-last-kept]")).toContainText("kept post 1: recorded (take-1.recorded-operator.wav), converted to kokoro:af_bella (pitch: source +2 st) (take-2.convert-seed-vc.wav)");
+ const n = narr("p-1");
+ expect(n.takes).toHaveLength(2);
+ expect(n.pick).toBe(1);
+ expect(n.approved).not.toBe(true);
+ expect(n.takes![0]).toMatchObject({ file: "narration/posts/1/take-1.recorded-operator.wav", engine: "recorded", voice: "operator", note: "recorded for Madam Savvy" });
+ expect(n.takes![1]).toMatchObject({ file: "narration/posts/1/take-2.convert-seed-vc.wav", engine: "derived", voice: "af_bella", source: { kind: "take", from: "take-1.recorded-operator" } });
+ expect(n.takes![1].steps![0]).toMatchObject({ op: "convert", engine: "seed-vc", voice: "kokoro:af_bella", pitch: "source", semitones: 2 });
+ for (const t of n.takes!) expect(existsSync(path.join(DIR, t.file))).toBe(true);
+ expect(converts()).toHaveLength(convertsBefore);
+ expect(existsSync(SCRATCH("1"))).toBe(false);
+ expect(existsSync(path.join(NARRATION, "posts", "1", ".recording-operator"))).toBe(false);
+ await expect(page.locator('[data-record-jump="p-1"]')).toHaveAttribute("data-record-state", "recorded");
+ await expect(page.locator("[data-record-progress]")).toHaveAttribute("data-record-progress", "1");
+ // The next post reads as her too, at the pitch just saved.
+ await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character", "madam-savvy");
+ await shot(page, "record-filter-kept");
+});
+
+test("Again drops the preview and records the part again; nobody's post has nothing to convert: Keep in this video only, and the recording kept alone", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 1100 });
+ await page.goto(urls.narrationRecordHref(P, { post: "p-3" }));
+ await expect(s(page)).toHaveAttribute("data-record-session", "p-3");
+ await expect(page.locator("[data-record-no-character]")).toContainText("no character reads @stranger");
+ // Nobody converts it: the last part would make the take at once -- until a person asks to filter first.
+ await expect(page.locator("[data-record-review]")).not.toBeChecked();
+ await page.locator("[data-record-review]").check();
+ await page.locator("[data-record-teleprompter]").click({ position: { x: 2, y: 2 } });
+ await recordPart(page);
+ const panel = page.locator("[data-record-review-panel]");
+ await expect(page.locator('[data-record-wave="1"]')).toBeVisible({ timeout: 20_000 });
+ await expect(page.locator("[data-record-pitch-row]")).toHaveCount(0);
+ expect(existsSync(path.join(SCRATCH("3"), "p01.raw.wav"))).toBe(true);
+ // Filter: no clean engine, no character -- it says so, and nothing failed.
+ await page.locator("[data-record-filter]").click();
+ await filterDone(page);
+ await expect(page.locator('[data-record-filter-step="convert"]')).toHaveAttribute("data-record-filter-step-state", "skipped");
+ await expect(page.locator("[data-record-nothing-filtered]")).toBeVisible();
+ await expect(page.locator("[data-record-filter-error]")).toHaveCount(0);
+ const first = readFileSync(path.join(NARRATION, "posts", "3", ".recording-operator", "session.json"), "utf8");
+
+ // AGAIN (Backspace): the preview dropped, the part recorded again -- still no take.
+ await page.keyboard.press("Backspace");
+ await expect(s(page)).toHaveAttribute("data-record-phase", "recording", { timeout: 15_000 });
+ expect(existsSync(SCRATCH("3"))).toBe(false);
+ await page.waitForTimeout(1200);
+ await page.keyboard.press("Space");
+ await expect(s(page)).toHaveAttribute("data-record-phase", "idle", { timeout: 15_000 });
+ await expect(page.locator('[data-record-wave="1"]')).toBeVisible({ timeout: 20_000 });
+ await expect(page.locator("[data-record-filter-job]")).toHaveCount(0);
+ expect(readFileSync(path.join(NARRATION, "posts", "3", ".recording-operator", "session.json"), "utf8")).not.toBe(first);
+ expect(narr("p-3").takes ?? []).toHaveLength(0);
+
+ // Keep in this video only: @stranger gets a character of this video's own.
+ await page.locator("[data-record-keep-in-video]").click();
+ await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character-layer", "project", { timeout: 20_000 });
+ const made = characters().find((c) => (c.handles ?? []).includes("stranger"));
+ expect(made).toBeTruthy();
+ await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character", made!.id);
+ await expect(page.locator("[data-record-keep-in-video]")).toHaveCount(0);
+
+ // Not filtered: Keep keeps the recording alone -- one recorded take, picked -- and moves on.
+ await expect(panel).toHaveAttribute("data-record-preview-current", "0");
+ await expect(page.locator("[data-record-keep]")).toHaveAttribute("data-record-keep-what", "recording");
+ await page.locator("[data-record-keep]").click();
+ await expect(s(page)).toHaveAttribute("data-record-session", "p-1", { timeout: 30_000 });
+ const n = narr("p-3");
+ expect(n.takes).toHaveLength(1);
+ expect(n.takes![0]).toMatchObject({ file: "narration/posts/3/take-1.recorded-operator.wav", engine: "recorded" });
+ expect(n.pick).toBe(0);
+ expect(existsSync(SCRATCH("3"))).toBe(false);
+ expect(existsSync(path.join(NARRATION, "posts", "3", ".recording-operator"))).toBe(false);
+});
+
+test("opened over http from the LAN the microphone is off, and the page says so; a sound file is filtered and kept all the same; with the filter off the last part makes the take at once", async ({ page }) => {
+ giveSavvy();
+ // What a browser gives a page opened over plain http from another machine: no secure context, no microphone.
+ await page.addInitScript(() => Object.defineProperty(window, "isSecureContext", { get: () => false }));
+ await page.setViewportSize({ width: 1366, height: 1100 });
+ await page.goto(urls.narrationRecordHref(P, { post: "p-1" }));
+ await expect(page.locator("[data-record-no-mic]")).toContainText("The microphone is off on this page");
+ await expect(page.locator("[data-record-no-mic]")).toContainText("localhost");
+ await expect(page.locator("[data-record-toggle]")).toBeDisabled();
+ // Space does not try the microphone.
+ await page.keyboard.press("Space");
+ await expect(s(page)).toHaveAttribute("data-record-phase", "idle");
+ await expect(page.locator("[data-record-error]")).toHaveCount(0);
+ // A sound file for the part: filtered, previewed and kept as a recording made here would be.
+ await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character", "madam-savvy");
+ await page.locator("[data-record-file]").setInputFiles(MIC_WAV);
+ await expect(page.locator('[data-record-wave="1"]')).toBeVisible({ timeout: 20_000 });
+ await page.locator("[data-record-filter]").click();
+ await filterDone(page);
+ await expect(page.locator("[data-record-review-panel]")).toHaveAttribute("data-record-preview-current", "1");
+ await page.locator("[data-record-play-filtered]").click();
+ await expect(page.locator("[data-record-player]")).toHaveAttribute("src", /preview&file=filtered/);
+ await page.locator("[data-record-keep]").click();
+ await expect(s(page)).toHaveAttribute("data-record-session", "p-2", { timeout: 30_000 });
+ expect(narr("p-1").takes!.map((t) => t.engine)).toEqual(["recorded", "derived"]);
+ await shot(page, "record-filter-lan");
+
+ // "Filter before keeping" off: the last part makes the recorded take at once, as before.
+ await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character", "madam-savvy");
+ await expect(page.locator("[data-record-review]")).toBeChecked();
+ await page.locator("[data-record-review]").uncheck();
+ await page.locator("[data-record-file]").setInputFiles(MIC_WAV);
+ await expect(page.locator("[data-record-status]")).toContainText("take-1.recorded-operator.wav", { timeout: 30_000 });
+ await expect(page.locator("[data-record-review-panel]")).toHaveCount(0);
+ expect(narr("p-2").takes).toHaveLength(1);
+ expect(existsSync(path.join(NARRATION, ".record-preview", "2.operator"))).toBe(false);
+});
+
+test("a part recorded again with Space (no Again) and Enter at once: the filtered read of the EARLIER recording is never kept", async ({ page }) => {
+ giveSavvy();
+ await page.setViewportSize({ width: 1366, height: 1100 });
+ await page.goto(urls.narrationRecordHref(P, { post: "p-1" }));
+ await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character", "madam-savvy");
+ await recordPart(page);
+ await expect(page.locator('[data-record-wave="1"]')).toBeVisible({ timeout: 20_000 });
+ await page.locator("[data-record-filter]").click();
+ await filterDone(page);
+ await expect(page.locator("[data-record-review-panel]")).toHaveAttribute("data-record-preview-current", "1");
+ const before = converts().length;
+ // Space records over the part; Enter the moment it has landed.
+ await page.locator("[data-record-teleprompter]").click({ position: { x: 2, y: 2 } });
+ await page.keyboard.press("Space");
+ await expect(s(page)).toHaveAttribute("data-record-phase", "recording", { timeout: 15_000 });
+ await page.waitForTimeout(1200);
+ await page.keyboard.press("Space");
+ await page.keyboard.press("Enter");
+ await expect(s(page)).toHaveAttribute("data-record-phase", "idle", { timeout: 15_000 });
+ // The earlier preview is gone, on the page and on disk; whatever Enter did, no converted take was made.
+ await expect(page.locator("[data-record-compare]")).toHaveCount(0);
+ expect(existsSync(path.join(SCRATCH("1"), "filtered.wav"))).toBe(false);
+ expect((narr("p-1").takes ?? []).filter((t) => t.engine === "derived")).toHaveLength(0);
+ expect(converts()).toHaveLength(before);
+ // The server holds the line too: a filtered Keep with no preview of this recording is refused.
+ const r = await page.request.post("/api/report/post-narration/record", { data: { project: P, id: "p-1", op: "keep", filtered: true } });
+ if ((narr("p-1").takes ?? []).length === 0) expect(r.status()).toBe(409);
+});
diff --git a/umtool/e2e/remote-archive.spec.ts b/umtool/e2e/remote-archive.spec.ts
@@ -0,0 +1,79 @@
+import { test, expect } from "@playwright/test";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs";
+import { WARM_TIMEOUT, warm } from "./warm";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// A PUBLIC ARCHIVE IS A FIRST-CLASS SOURCE (demo epic D1), umtool's half: the
+// Source chip's "Connect an archive…" (Read it → Connect, through the editor's
+// `archives` action — the stub's, which writes the fixture's settings) and
+// "Article from a question"'s Source field, which lists the archive's own
+// channels. The archive is the editor stub's /archive-stub (the synthetic
+// draft corpus, served as a published site serves it); nothing leaves
+// loopback. The engine — the sweep over it, the remote-only channel, the
+// links — is the editor suite's remote-archive.spec.ts.
+//
+// WRITES the fixture's settings.json remoteArchives (removed after)
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const STUB = `http://127.0.0.1:${portFor("EDITOR_STUB_PORT")}`;
+const ORIGIN = `${STUB}/archive-stub`;
+const HANDLE = `remote:${ORIGIN}`;
+
+test.beforeAll(async ({ playwright }) => {
+ test.setTimeout(WARM_TIMEOUT);
+ await warm(playwright, ["/research", urls.newArticleHref(), "/api/articles/sources"]);
+});
+
+test.afterAll(async () => {
+ await fetch(`${STUB}/api/ops/archives`, {
+ method: "POST",
+ headers: { authorization: "Bearer umtool-e2e-token", "content-type": "application/json" },
+ body: JSON.stringify({ remove: ORIGIN }),
+ }).catch(() => {});
+});
+
+test("the Source chip connects an archive by its address: read it, connect, and the scope is that archive's", async ({ page }) => {
+ await page.goto("/research");
+ const source = page.getByRole("combobox", { name: "Source" });
+ await expect(source.locator("option", { hasText: "Connect an archive…" })).toHaveCount(1);
+ await source.selectOption({ label: "Connect an archive…" });
+ const form = page.getByRole("form", { name: "connect an archive" });
+ await form.getByRole("textbox", { name: "archive origin" }).fill(`${ORIGIN}/`);
+ await form.getByRole("button", { name: "Read it" }).click();
+ const probe = form.locator(`[data-archive-probe="${ORIGIN}"]`);
+ await expect(probe).toContainText("Stubalyzer");
+ await expect(probe).toContainText("2 channels");
+ await expect(probe).toContainText("Synth Kitchen");
+ // Read, not saved.
+ expect(JSON.parse(readFileSync(path.join(FIXTURE, "settings.json"), "utf8")).remoteArchives ?? []).toEqual([]);
+
+ await form.getByRole("button", { name: "Connect" }).click();
+ await expect(form).toHaveCount(0);
+ await expect(source).toHaveValue(HANDLE);
+ await expect(source.locator("option:checked")).toContainText("Stubalyzer · connected");
+ // The scope is the archive's: its two channels.
+ await expect(page.locator("[data-scope]")).toContainText("All 2 channels");
+ const saved = JSON.parse(readFileSync(path.join(FIXTURE, "settings.json"), "utf8")).remoteArchives;
+ expect(saved).toEqual([expect.objectContaining({ id: "stubalyzer", origin: ORIGIN, title: "Stubalyzer" })]);
+});
+
+test("Article from a question offers the connected archive as its source, and lists that archive's channels", async ({ page }) => {
+ await page.goto(urls.newArticleHref());
+ const form = page.getByRole("form", { name: "new article" });
+ const source = form.getByRole("combobox", { name: "source" });
+ await expect(source.locator(`option[value="${HANDLE}"]`)).toHaveCount(1);
+ // The fixture's editor holds channels of its own: the local corpus stays the default.
+ await expect(source).toHaveValue("");
+ await source.selectOption(HANDLE);
+ await form.getByRole("textbox", { name: "find a channel" }).fill("synth");
+ await expect(form.getByRole("button", { name: /^Synth Kitchen/ })).toBeVisible();
+ await expect(form.getByRole("button", { name: /^Synth Other Kitchen/ })).toBeVisible();
+ await form.getByRole("button", { name: /^Synth Kitchen/ }).click();
+ await expect(form.locator("[data-picked='synth-kitchen']")).toBeVisible();
+});
diff --git a/umtool/e2e/takes.spec.ts b/umtool/e2e/takes.spec.ts
@@ -278,8 +278,9 @@ test("Give renders the machine: the take runs with --priority, holds the lane it
await expect
.poll(async () => ((await (await request.get(`/api/report/takes/make?job=${job.id}`)).json()) as { state: string }).state, { timeout: 180_000 })
.toBe("done");
- // The stub's download lane was held already: left alone, never released.
- expect(laneAsks().slice(before)).toEqual(["transcription:true", "transcription:false"]);
+ // The stub's download lane was held already: left alone, never released. Transcription and the
+ // Speakers (backfill) lane were free: held for the take, and let go (RENDER_MODE_LANES).
+ expect(laneAsks().slice(before)).toEqual(["transcription:true", "backfill:true", "transcription:false", "backfill:false"]);
expect(existsSync(STATE)).toBe(false);
// While a render holds it, the panel says so (this process is the holder: alive).
diff --git a/umtool/e2e/voices.spec.ts b/umtool/e2e/voices.spec.ts
@@ -19,6 +19,9 @@ import * as urls from "./urls";
// Use for this project -> the project's voice map; the lint's override note
// a recording dropped on an item -> kept, converted to the character's stock voice
// the cast: remove, undo
+// a character's presets (CharacterPresets.tsx): Keep in this video only -> its voice, speed, clean, direction saved;
+// an anonymous character of this video ("Anon 1"), never offered -- and refused -- the pool; an item read as a
+// character of its own, and cleared
// ---------------------------------------------------------------------------
const HERE = path.dirname(fileURLToPath(import.meta.url));
@@ -27,6 +30,8 @@ const P = "reports/voices-fixture";
const DIR = path.join(FIXTURE, "reports", "voices-fixture");
const MANIFEST = path.join(DIR, "video.manifest.json");
const CAST = path.join(FIXTURE, ".umtool", "cast.json");
+// This video's own characters (lib/report/castStore.mjs projectCharactersWrite).
+const CHARACTERS = path.join(DIR, "narration", "characters.json");
const SHOTS = process.env.E2E_VOICES_SHOTS ?? null;
const REC = path.join(FIXTURE, "voices-recording.wav");
@@ -50,7 +55,7 @@ test.beforeAll(() => {
});
const reset = () => {
copyFileSync(`${MANIFEST}.pristine`, MANIFEST);
- for (const f of [CAST, CAST.replace(/\.json$/, ".undo.json"), path.join(DIR, "narration", "voices.json")]) rmSync(f, { force: true });
+ for (const f of [CAST, CAST.replace(/\.json$/, ".undo.json"), path.join(DIR, "narration", "voices.json"), CHARACTERS, CHARACTERS.replace(/\.json$/, ".undo.json")]) rmSync(f, { force: true });
for (const d of ["auditions", "uploads", "parts-cache"]) rmSync(path.join(DIR, "narration", d), { recursive: true, force: true });
for (const id of ["1", "2", "3"]) {
const dir = path.join(DIR, "narration", "posts", id);
@@ -124,8 +129,10 @@ test("each character's voice and where it comes from; an audition side by side w
const confirm = box.locator("[data-reread-confirm]");
await expect(confirm).toHaveAttribute("data-reread-confirm", "1");
await expect(confirm.locator('[data-reread-item="p-1"]')).toContainText("post orpheus · zac → kokoro · am_michael");
- const cast = JSON.parse(readFileSync(CAST, "utf8")) as { characters: { id: string; voice: string; handles: string[] }[] };
- expect(cast.characters).toEqual([{ id: "hostman", name: "Host Man", handles: ["hostman"], voice: "kokoro:am_michael" }]);
+ // The cast on disk is version 2: the voice is the character's synthetic preset.
+ const cast = JSON.parse(readFileSync(CAST, "utf8")) as { version: number; characters: { id: string; synthetic: { voice: string }; handles: string[] }[] };
+ expect(cast.version).toBe(2);
+ expect(cast.characters).toEqual([{ id: "hostman", name: "Host Man", handles: ["hostman"], synthetic: { voice: "kokoro:am_michael" } }]);
await expect(page.locator('[data-voices-character="hostman"]')).toHaveAttribute("data-voice-from", "cast");
await expect(page.locator('[data-voices-character="hostman"] [data-voice-drift]')).toHaveAttribute("data-voice-drift", "1");
await shot(page, "3-reread-confirm", confirm);
@@ -202,6 +209,74 @@ test("a recording dropped on an item: kept as recorded, converted to the charact
expect(conv.voice).toBe("orpheus:zac");
});
+test("a character's presets; this video's own characters -- an anonymous one is Anon 1 and never enters the pool; an item's own character", async ({ page }) => {
+ type Own = { id: string; name: string; anonymous?: boolean; shown?: string; handles?: string[]; synthetic?: { voice?: string; speed?: number }; recorded?: { enhance?: boolean; direction?: string } };
+ const own = () => (JSON.parse(readFileSync(CHARACTERS, "utf8")) as { format: string; characters: Own[] }).characters;
+ const itemCharacter = (id: string) => (entry(id).narration as { character?: string } | undefined)?.character ?? null;
+ await page.goto(urls.voicesHref(P));
+ const host = page.locator('[data-voices-character="@hostman"]');
+ await expect(host).toBeVisible({ timeout: 30_000 });
+ // Keep in this video only: an author with no character gets one here, in the voice they read in now; its presets open.
+ await host.locator("[data-character-keep]").click();
+ const ed = page.locator('[data-preset-editor="hostman"]');
+ await expect(ed).toHaveAttribute("data-preset-scope", "project");
+ expect(own().map((c) => [c.id, c.handles, c.synthetic?.voice])).toEqual([["hostman", ["hostman"], "orpheus:zac"]]);
+ const row = page.locator('[data-voices-character="hostman"]');
+ await expect(row).toHaveAttribute("data-voice-from", "project");
+ await expect(row.locator('[data-voices-layer="project"]')).toBeVisible();
+ // Both presets, edited by hand: a Kokoro voice at 1.1, not cleaned, a direction for the reader.
+ await ed.locator('[data-preset-engine="voice"]').selectOption("kokoro");
+ await ed.locator("[data-preset-speed]").fill("1.1");
+ await ed.locator("[data-preset-enhance]").uncheck();
+ await ed.locator("[data-preset-direction]").fill("higher, brisk, amused");
+ await ed.locator("[data-preset-save]").click();
+ await expect(page.locator("[data-voices-status]")).toContainText("its presets saved for this video only");
+ const saved = own()[0];
+ expect(saved.synthetic?.voice).toMatch(/^kokoro:/);
+ expect(saved.synthetic?.speed).toBe(1.1);
+ expect(saved.recorded).toEqual({ enhance: false, direction: "higher, brisk, amused" });
+ await expect(row.locator("[data-voice-speed]")).toHaveAttribute("data-voice-speed", "1.1");
+ await expect(page.locator('[data-project-character="hostman"]')).toContainText("not cleaned");
+ await shot(page, "7-presets", ed);
+ // An anonymous character of this video's, for the guest: shown as Anon 1.
+ const mine = page.locator("[data-project-characters]");
+ await mine.locator("[data-project-character-id]").fill("anon-a");
+ await mine.locator("[data-project-character-handles]").fill("guest");
+ await mine.locator("[data-project-character-anonymous]").check();
+ await mine.locator("[data-project-character-add-go]").click();
+ const anon = page.locator('[data-project-character="anon-a"]');
+ await expect(anon).toContainText("Anon 1");
+ await expect(anon).toContainText("anonymous");
+ expect(own().find((c) => c.id === "anon-a")).toMatchObject({ anonymous: true, shown: "Anon 1", handles: ["guest"] });
+ await expect(page.locator('[data-voices-character="anon-a"]')).toContainText("Anon 1");
+ // It is never offered the pool -- and the route refuses it (the CLI's words), the cast untouched.
+ await expect(anon.locator("[data-character-pool]")).toHaveCount(0);
+ await expect(page.locator('[data-project-character="hostman"] [data-character-pool]')).toBeVisible();
+ const refused = await page.evaluate(async (project) => {
+ const r = await fetch("/api/report/voices", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "character-pool", id: "anon-a" }) });
+ return { status: r.status, error: ((await r.json()) as { error?: string }).error ?? "" };
+ }, P);
+ expect(refused.status).toBe(400);
+ expect(refused.error).toContain("anon-a is anonymous: it stays in this video");
+ expect(existsSync(CAST)).toBe(false);
+ await shot(page, "8-own-characters", mine);
+ // An item read as a character of its own, then by its author's handle again.
+ await mine.locator("[data-item-character-item]").selectOption("p-3");
+ await mine.locator("[data-item-character-pick]").selectOption("hostman");
+ await mine.locator("[data-item-character-set]").click();
+ const it = mine.locator('[data-item-character="p-3"]');
+ await expect(it).toHaveAttribute("data-item-character-found", "yes");
+ await expect(it).toContainText("this video's");
+ expect(itemCharacter("p-3")).toBe("hostman");
+ await it.locator("[data-item-character-clear]").click();
+ await expect(it).toHaveCount(0);
+ expect(itemCharacter("p-3")).toBe(null);
+ // Undo: the last change to this video's characters (the anonymous one added) is taken back.
+ await mine.locator("[data-project-characters-undo]").click();
+ await expect(anon).toHaveCount(0);
+ expect(own().map((c) => c.id)).toEqual(["hostman"]);
+});
+
test("the Cut tab's Reads and voices reaches the Voices page", async ({ page }) => {
await page.goto(urls.projectHref(P, { tab: "cut" }));
const { openPanel } = await import("./panels");
diff --git a/umtool/lib/articles/createSources.test.ts b/umtool/lib/articles/createSources.test.ts
@@ -0,0 +1,26 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createSourcesOf } from "./createSources";
+import type { SourceOption } from "../research/types";
+
+const SOURCES: SourceOption[] = [
+ { handle: "local:/x/export/public", kind: "local", label: "Local corpus" },
+ { handle: "remote:https://stub.test", kind: "remote", label: "Stubalyzer", detail: "connected · stub.test" },
+ { handle: "hub:https://hub.test", kind: "hub", label: "Hub" },
+];
+const ch = (slug: string, kind = "video") => ({ slug, name: slug, kind, platform: null, sites: [] });
+
+test("Create offers the editor's corpus and each published archive, hubs aside", () => {
+ const r = createSourcesOf(SOURCES, [ch("alpha")]);
+ assert.deepEqual(r.sources.map((s) => s.handle), ["", "remote:https://stub.test"]);
+ assert.equal(r.preselect, "");
+});
+
+test("with no local corpus the first archive is preselected; a remote-only channel is not a corpus", () => {
+ assert.equal(createSourcesOf(SOURCES, []).preselect, "remote:https://stub.test");
+ assert.equal(createSourcesOf(SOURCES, [ch("stub-alpha", "remote-only")]).preselect, "remote:https://stub.test");
+ // The editor did not answer: nothing is assumed.
+ assert.equal(createSourcesOf(SOURCES, null).preselect, "");
+ // No archive to offer: the local corpus, empty or not.
+ assert.equal(createSourcesOf(SOURCES.slice(0, 1), []).preselect, "");
+});
diff --git a/umtool/lib/articles/createSources.ts b/umtool/lib/articles/createSources.ts
@@ -0,0 +1,20 @@
+import type { SourceOption } from "@/lib/research/types";
+import type { EditorChannel } from "./generation";
+
+// THE CREATE FORM'S SOURCES (demo epic D1 item 2), pure so it is tested
+// without an editor: the editor's own corpus (handle "") first, then each
+// published archive (`remote:<origin>`) the source picker offers. The first
+// archive is preselected when the editor holds no channel of its own — a
+// fresh clone with an archive connected sweeps that archive by default. A
+// remote-only channel (held only to fetch an archive's clips) is not a local
+// corpus. An editor that did not answer (null) preselects nothing: the form
+// says it is down.
+export type CreateSource = { handle: string; label: string; detail?: string };
+
+export function createSourcesOf(sources: SourceOption[], editorChannels: EditorChannel[] | null): { sources: CreateSource[]; preselect: string } {
+ const local: CreateSource = { handle: "", label: "Local corpus", detail: "the editor's channels" };
+ const remote = sources.filter((s) => s.kind === "remote").map((s) => ({ handle: s.handle, label: s.label, ...(s.detail ? { detail: s.detail } : {}) }));
+ const ownChannels = editorChannels?.filter((c) => c.kind !== "remote-only").length ?? null;
+ const preselect = ownChannels === 0 && remote.length > 0 ? remote[0].handle : "";
+ return { sources: [local, ...remote], preselect };
+}
diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs
@@ -67,15 +67,19 @@ export const GROUPS = [
cmd: "cast",
usage: [
" umtool cast [ls] | add <id> --name … --voice <engine:voice> [--handles a,b] | set <id> … | rm <id> | undo",
- " | project <p> | audition <character> --voices a,b,c [--project <p>] [--text …] | use <p> <character> <voice>",
- " [--everywhere] | reread <p> <character> the CAST: characters' stock voices across projects (cast.json), a",
- " project's characters and their drift, an audition of candidate voices (scored against the real voice)",
+ " | project <p> [add <id> … | set <id> … | rm <id> | undo | pool <id> | keep <character|@handle>]",
+ " | audition <character> --voices a,b,c [--project <p>] [--text …] | use <p> <character> <voice>",
+ " [--everywhere] | reread <p> <character> the CAST: characters across projects (cast.json), each a",
+ " PRESET -- synthetic (voice, speed) and recorded (convert, clean, trim, a direction) -- a project's",
+ " characters, its OWN (characters.json: anonymous ones), their drift, an audition of candidate voices",
],
docs: [
- ["`cast [ls] \\| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--convert-engine e] [--convert-voice v] [--narrator] \\| set <id> … \\| rm <id> \\| undo [--json]`",
- "**THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects and their STOCK voices, a layer under each project's voice map; one writer, an undo point a write"],
+ ["`cast [ls] \\| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--speed s] [--convert-engine e] [--convert-voice v] [--convert-pitch target\\|source\\|contour] [--convert-semitones n] [--enhance on\\|off] [--trim on\\|off] [--trim-pad ms] [--direction \"…\"] [--narrator] \\| set <id> … \\| rm <id> \\| undo [--json]`",
+ "**THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects, one writer, an undo point a write. **A character is a PRESET**, two of them ([knobs.md](knobs.md#a-character-is-a-preset)): `synthetic` -- the STOCK voice it reads in (`--voice`) and its speed (`--speed` 0.5–2; Orpheus has none) -- and `recorded` -- what a recording of them is made into: the stock voice (`--convert-voice`; a file or a recording is refused), the engine, the **pitch** the converted read lands on (`--convert-pitch`: `target` the stock voice's own, `source` the pitch it was read at, `contour` the read's rises and falls at the stock voice's register; `--convert-semitones` -12…12 moves a followed one), whether it is cleaned first (`--enhance`), its edges trimmed to speech (`--trim`, `--trim-pad` the ms kept either side) and a `--direction` (one line for the person reading, never sent to a model). `set` lays the flags given over the presets; `default` for one takes that key off; `--no-convert`, `--no-speed`. A version 1 file (`voice`, `convert` at a character's top) reads as these presets and the first write makes it version 2 (`undo` puts the old file back). A followed pitch on an engine that has none, semitones with nothing followed, a speed or a pad out of range: **exit 1**"],
["`cast project <project> [--json]` · `cast use <project> <character\\|@handle> <voice> [--everywhere]` · `cast reread <project> <character> [--dry-run]`",
- "a project's characters (each voice now, where it comes from, its stale reads), the voice for this project or everywhere, and the re-reads that asks for"],
+ "a project's characters: each one's voice now (and speed) and **where it comes from** -- the chain one read asks, first hit wins: the command's flags, the item's own character (`posts character`), this video's character for the author (then its voice map), the cast's, the narrator's, the default -- what a recording of them is made into, its stale reads; this video's own characters; the items that name their own. `use`: the voice for this project (its own character's when it has one for them, else the voice map) or everywhere, and the re-reads that asks for"],
+ ["`cast project <project> add <id> [--name \"…\"] [--voice <engine:voice>] [--handles a,b] [--anonymous [--shown \"…\"]] [the preset flags]` · `set <id> … [--no-voice] [--no-anonymous]` · `rm <id>` · `undo` · `pool <id>` · `keep <character\\|@handle> [--anonymous]` `[--json]`",
+ "**THIS VIDEO's OWN CHARACTERS** (`<project>/narration/characters.json`, [knobs.md](knobs.md#this-videos-own-characters-and-an-items-own)): the cast's shape and the cast's writer (a token, an undo point a write, atomic, a broken file never overwritten), for people who must not enter the pool. `--anonymous`: it goes by a **shown name** (`--shown`; default the next of `Anon 1`, `Anon 2` …) on the Voices page, in `cast project` and in a recording's note, and never enters the pool; **the on-screen card is not anonymised yet** (it still shows the post's author). `--voice` is optional here: a character with none leaves the voice to the layers under it. `narration/voices.json` keeps working under it (a handle in it reads as a character with only a synthetic voice) and is never rewritten by these. `pool <id>` (**Add to the pool**) moves one into the cast -- an anonymous one, or an id the cast has, is refused; `keep` (**Keep in this video only**) copies a cast character here (its presets changed for this video alone), or gives an author with no character one, in the voice they read in now. A refusal: **exit 1**, nothing written"],
["`cast audition <character\\|@handle> --voices a,b,… [--project <p>] [--text \"…\" \\| --item <id> \\| --line <n> \\| --stock] [--no-score \\| --score-only] [--json] [--progress ndjson]`",
"**AN AUDITION**: one line read by 2-6 stock voices through the editor's tts op, levelled to -20 LUFS in `<p>/narration/auditions/` (cached), scored for closeness to the character's real voice (`speakers.json`; TitaNet, local)"],
],
@@ -101,7 +105,7 @@ export const GROUPS = [
],
docs: [
["`quote-check <project> [--clips a,b] [--pad S] [--json]` · `quote-check <project> --status`",
- "**is each clip's quote in the seconds it plays?** The cut ±15 s of the source the render would cut it from, transcribed by the editor (`pnpm ops transcribe`, words on — its transcription lane), the quote found in those words and in the cues: `ok`, `moved` (heard more than 0.5 s from where the cues have it), `not-found`; rows in `quote-check.json`, stale when the cut or the quote changes; `check` blocks on `moved`/`not-found` (`clip-quote-moved`, `clip-quote-missing`), a take refuses them, `prep --status` counts them ([knobs.md](knobs.md#the-quote-check-is-the-quote-where-the-clip-plays))"],
+ "**is each clip's quote in the seconds it plays?** The cut ±15 s of the source the render would cut it from, transcribed by the editor (`pnpm ops transcribe`, words on — its transcription lane), the quote found in those words and in the cues: `ok`, `moved` (heard more than 0.5 s from where the cues have it), `not-found`; rows in `quote-check.json`, stale when the cut or the quote changes; the editor's work files go to `<project>/.quote-check/`, never under `out/` (a link onto a media drive the editor will not write in); `check` blocks on `moved`/`not-found` (`clip-quote-moved`, `clip-quote-missing`), a take refuses them, `prep --status` counts them ([knobs.md](knobs.md#the-quote-check-is-the-quote-where-the-clip-plays))"],
],
},
{
@@ -297,7 +301,7 @@ export const GROUPS = [
],
docs: [
["`set <project> <clip> key=value …`",
- "a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)); `key=` clears one ([knobs.md](knobs.md#marks))"],
+ "a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)); on ANY entry (a post item, a still, a clip) `hideModules=diet,streak`, `shelfNote='…'` and `chapter='…'` (its name in the chapter list, one line of at most 100 characters; `chapter=` none); `--take <t>` writes the entry knobs into that take's patch; `key=` clears one ([knobs.md](knobs.md#marks))"],
],
},
{
@@ -321,8 +325,8 @@ export const GROUPS = [
" variants=<json>, and the look's keys (transition=0.3, …)",
],
docs: [
- ["`look <project> key=value … [--unset render.<key>]…`",
- "the cut's **knobs**: `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\\|label\\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys — `mode=basic\\|deck` (the footage alone, [knobs.md](knobs.md#basic-output-the-footage-alone)) and `basic=<json>` (its fades) among them ([knobs.md](knobs.md)) **The deck on, legacy keys off** (`updateRenderKeys`, one write, an undo point `revisions/…auto-render-keys…` first): `chrome.layout=deck` turns the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck), `--unset render.<key>` (repeatable) drops a legacy render key -- only `rail` `chromeEngine` `railEngine` `chromeRegions` `claimSchedule` `wordmark` `title` `finale` `cut`; the deck beside the old rail is refused in the build's words unless the same command drops it; deck.* keys in the same command land after the chrome exists. Another key named: **exit 2**"],
+ ["`look <project> key=value … [--unset render.<key>]… [--take <t>]`",
+ "the cut's **knobs** (`--take <t>`: the `deck.*` keys given are set on that take -- its patch, an undo point of its own, the project's manifest untouched; the other knobs are the project's): `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\\|label\\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys — `mode=basic\\|deck` (the footage alone, [knobs.md](knobs.md#basic-output-the-footage-alone)) and `basic=<json>` (its fades) among them ([knobs.md](knobs.md)) **The deck on, legacy keys off** (`updateRenderKeys`, one write, an undo point `revisions/…auto-render-keys…` first): `chrome.layout=deck` turns the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck), `--unset render.<key>` (repeatable) drops a legacy render key -- only `rail` `chromeEngine` `railEngine` `chromeRegions` `claimSchedule` `wordmark` `title` `finale` `cut`; the deck beside the old rail is refused in the build's words unless the same command drops it; deck.* keys in the same command land after the chrome exists. Another key named: **exit 2**"],
],
},
{
@@ -372,16 +376,19 @@ export const GROUPS = [
{
cmd: "chain",
usage: [
- " umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]]",
+ " umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]] [--stop-before-render] [--allow-whole-recording]",
" an article iteration's pipeline, one step a process: {chainSteps}",
" (resumes at the first step not done; --dry prints it; the project is <root>/<article>/i<n>/)",
" --draft-all (Draft everything): {draftAllSteps} —",
" each draft a report-draft job on --model (else its route); a draft that fails does not stop it;",
" --deck adds a step before the flips: the minimal on-screen deck on a cut with none",
+ " --stop-before-render ends it before the voices: nothing voiced or built",
+ " --allow-whole-recording: a remote-only channel's Rumble windows may download",
+ " their whole recording (refused with its size otherwise)",
],
docs: [
- ["`chain <article> <n> [--from <step>] [--dry] [--final] [--draft-all [--model M]]`",
- "an iteration to a video: the Iterations tab's **Make the video** (`--draft-all`: Draft everything)"],
+ ["`chain <article> <n> [--from <step>] [--dry] [--final] [--draft-all [--model M]] [--stop-before-render] [--allow-whole-recording]`",
+ "an iteration to a video: the Iterations tab's **Make the video** (`--draft-all`: Draft everything, which fetches the windows of the clips the drafted cut kept, `cut-windows`); `--stop-before-render` is **Stop before render** (it ends before the voices); `--allow-whole-recording` is **Fetch the whole recordings** (a remote-only channel's Rumble windows, refused with their size otherwise)"],
],
},
{
@@ -722,7 +729,7 @@ export const GROUPS = [
],
docs: [
["`ledger <project> [ls] [--scope S] [--population P] [--json]` · `ledger <project> add <id> --date D --scope S --population P [--value V] --scopeBasis \"…\" [--<key> V …] [--row '{…}']` · `ledger <project> set <id> --<key> V … [--unset k,k]` · `ledger <project> rm <id>`",
- "a **measure ledger's rows** (`ledgerSchema.kind \"measure\"`), the only writer of them: each row is checked against the schema -- a track, a form (and the promise forms `promise` / `promise_check`), a number in its unit or a declared regime with an event, the six adjudication fields (a new row defaults `scopeConfidence` read, `valueKind` uttered, `flags` []; `--scopeBasis` is never defaulted), the declared fields, and the instruments' own keys: `run` (a loss claim's run), `retro` (a loss told in the past with no `asOf`: off the odometer), `promise`, `kept`, `due`, `speaker` (another party's key: her rows move none of his numbers), `paidOn`, `outcome` (a `promise_outcome`'s: kept, refunded, withdrawn); the promise forms are `promise`, `promise_check`, `promise_claim`, `promise_outcome`. `rm` refuses a row an entry pins or another row names ([knobs.md](knobs.md#the-measure-slice-the-weight-instruments))"],
+ "a **measure ledger's rows** (`ledgerSchema.kind \"measure\"`), the only writer of them: each row is checked against the schema -- a track, a form (and the promise forms `promise` / `promise_check`), a number in its unit or a declared regime with an event, the six adjudication fields (a new row defaults `scopeConfidence` read, `valueKind` uttered, `flags` []; `--scopeBasis` is never defaulted), the declared fields, and the instruments' own keys: `run` (a loss claim's run), `retro` (a loss told in the past with no `asOf`: off the odometer), `promise`, `kept`, `due`, `speaker` (another party's key: her rows move none of his numbers), `paidOn`, `outcome` (a `promise_outcome`'s: kept, refunded, withdrawn), `stampNote` (a `promise_outcome`'s: the words under its stamp on the promise clock in place of \"by <date> · no video\" -- `ledger <p> set <row> --stampNote \"…\"`, `--stampNote null` for the clock's own words again; one line, the strip over a post's card shows its first clause, and `umtool lint` warns past 26 characters); the promise forms are `promise`, `promise_check`, `promise_claim`, `promise_outcome`. `rm` refuses a row an entry pins or another row names ([knobs.md](knobs.md#the-measure-slice-the-weight-instruments))"],
],
},
{
@@ -1020,14 +1027,16 @@ export const GROUPS = [
"a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**)"],
["`posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script \"…\"] [--pick <n>] [--approve\\|--unapprove] [--off\\|--on] [lead= tail= ramp= linger= clip=read\\|full wet= lowpass= duck=on\\|off short=hold\\|loop attach=under\\|after lufs= pace=fast\\|normal]` · `<item> --take [--note \"…\"] [--voice v] [--engine e] [--speed s] [--script \"…\"]` · `<item> --derive <n> --op enhance\\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…`",
"a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; \"not installed\" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said \"at <handle>\", the lexicon first; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans."],
- ["`posts narrate <project> <item> --take --thread [--parents 0\\|all\\|none\\|<n>] [--skip-parent <id\\|parent:i>]… [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--note \"…\"] [--force] [--no-hold] [--dry-run] [--json]`",
- "a **THREAD READ** as one command ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read), `lib/report/postThreadRead.mjs`): the post it answers (`--parents all`: every ancestor; `<n>`: parents 0..n; `none`), the post it quotes and the posts it links to, then his words, in DATE order, each in its author's voice (`--voice-for`, then the project's voice map, `posts voices`; his own: the narrator's), the redaction, the slur filter (a beep is skipped: a joined read is not word-timed) and the lexicon (`posts say`) applied. A parent or quoted post the item before already shows is not read again (`--read-seen`: it is). Each part is synthesized ONCE by the editor's tts op into `narration/parts-cache/<sha1(voice\\|text)>.wav` (the transcription lane held meanwhile, only if it was not; `--no-hold`: left alone), joined (0.8 s between pieces, 0.6 between paragraphs, 0.25 inside one) into `take-<n>.<engine>-thread.wav` with `take-<n>.parts.json`, saved with its parts' roles, its lexicon and how it was asked (`read`) and PICKED — one write (one undo point). `--dry-run`: the pieces, voices and parts (cached or not), nothing asked. Already up to date (same words and voices): nothing done, **exit 0** (`--force`: again). A part not synthesized: **exit 1** (the parts made stay cached; run it again); `--json` prints `{ok: false, error}` too. A usage error: **exit 2**"],
+ ["`posts narrate <project> <item> --take --thread [--parents 0\\|all\\|none\\|<n>] [--skip-parent <id\\|parent:i>]… [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--speed s] [--note \"…\"] [--force] [--no-hold] [--dry-run] [--json]`",
+ "a **THREAD READ** as one command ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read), `lib/report/postThreadRead.mjs`): the post it answers (`--parents all`: every ancestor; `<n>`: parents 0..n; `none`), the post it quotes and the posts it links to, then his words, in DATE order, each in its author's voice (`--voice-for`, then the item's own character, this video's characters and voice map, the cast: `cast project`; his own: the narrator's) and at its character's speed (its synthetic preset's; `--speed`: every part at that one; Orpheus has none; a part at another speed is another cached part), the redaction, the slur filter (a beep is skipped: a joined read is not word-timed) and the lexicon (`posts say`) applied. A parent or quoted post the item before already shows is not read again (`--read-seen`: it is). Each part is synthesized ONCE by the editor's tts op into `narration/parts-cache/<sha1(voice\\|text)>.wav` (the transcription lane held meanwhile, only if it was not; `--no-hold`: left alone), joined (0.8 s between pieces, 0.6 between paragraphs, 0.25 inside one) into `take-<n>.<engine>-thread.wav` with `take-<n>.parts.json`, saved with its parts' roles, its lexicon and how it was asked (`read`) and PICKED — one write (one undo point). `--dry-run`: the pieces, voices and parts (cached or not), nothing asked. Already up to date (same words and voices): nothing done, **exit 0** (`--force`: again). A part not synthesized: **exit 1** (the parts made stay cached; run it again); `--json` prints `{ok: false, error}` too. A usage error: **exit 2**"],
["`posts say <project> [ls] [--item <id>]` · `add <word\\|phrase> \"<spoken>\" [--case] [--item <id>] [--note \"…\"]` · `remove <word\\|n> [--item <id>]` · `try \"<text>\" [--item <id>]` · `stale` `[--json]`",
"**THE PRONUNCIATION LEXICON** ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)): `narration/lexicon.json` in the project, a word or phrase said differently in EVERY synthesized read (a script's `--take`, each piece of a thread read, the bench's re-take); the scripts and cards keep their words. Whole words, without case unless `--case`, a phrase across any spaces, regex characters literal; `--item` for one item's reads (it wins over the project's). A masked slur and a redacted word are never replaced. `add` of a word already listed changes what is said. `try` prints what a voice would be asked to say. `stale` lists every picked read that still says an entry the old way, with the command that re-reads it. A bad entry or an unknown item: **exit 2**"],
+ ["`posts character <project> <item> [<character> \\| --clear] [--json]`",
+ "**THE CHARACTER ONE ITEM's OWN READ IS MADE WITH** (`narration.character`, [knobs.md](knobs.md#this-videos-own-characters-and-an-items-own)): the id of one of this video's own characters, else of the cast's -- its presets answer for that item before its author's handle does (the synthetic one for `--take` and a thread read, the recorded one for `--recording`). No character: the one it names and what its read resolves to now; `--clear`: by its handle again. One undoable write; no take is made. An id nobody has: **exit 2**"],
["`posts voices <project> [ls] \\| set <handle\\|*> <voice> \\| remove <handle\\|*> [--json]`",
"**THE VOICE MAP** (`narration/voices.json`): the stock voice a thread read gives each author (`*`: everyone it does not name; default `leo` on Orpheus); `ls` lists the map and every author the cut's items carry with the voice each would get. A bad handle or voice: **exit 2**"],
- ["`posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert] [--label l]`",
- "**a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked"],
+ ["`posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean\\|--clean] [--no-trim\\|--trim] [--no-convert] [--pitch target\\|source\\|contour] [--semitones n] [--label l]` · `<item> [--recording <file>] --preview [--as <character>] [--out <file>] [--trim-span [<part>=]<from>-<to>]… [--engine e] [--voice v] [--events]` · `<item> --keep-preview` · `<item> --discard-preview` · `<item> --derive <n> --op convert [--as <character>] [--engine e] [--voice v] [--pitch …] [--semitones n]`",
+ "**a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked. The character is `--as` (this video's own first, then the cast's), else the item's own, this video's for the author, the cast's, the narrator; its **recorded preset** says whether it is cleaned and its edges trimmed (and the room kept) -- `--no-clean`/`--clean`, `--no-trim`/`--trim` say otherwise for this read. **`--pitch`** is the pitch the converted read lands on ([knobs.md](knobs.md#the-pitch-a-converted-read-lands-on)): `target` the stock voice's own (the read's intonation flattened to it), `source` the pitch it was read at, `contour` the read's rises and falls moved to the stock voice's register; `--semitones` (-12…12) moves a followed one. Default: the character's `convert` entry, else the editor's `settings.voice.convert`. `source` and `contour` are seed-vc's, with its f0 model (`archilyzer voice setup --engine seed-vc --with f0`); what the editor cannot do it refuses in a sentence (**exit 1**); a value outside these, or a pitch on `--op enhance`: **exit 1**. **`--preview`** runs the same chain with NO TAKE made ([knobs.md](knobs.md#record-filter-preview-on-the-record-page); the record page's Filter): cleaned whole, cut (`--trim-span`: at these seconds of the recording instead of the auto trim's), converted, into the scratch dir `narration/.record-preview/<postId>.<label>/` -- its paths printed, `--out <file>` a copy of the filtered read; without `--recording` it is the record page's session of the item. A step whose inputs stand is not run again (another `--pitch`: the convert alone). `--keep-preview` makes its takes from those files (nothing converted again), `--discard-preview` removes it. **`--derive <n> --op convert`** is the character's too: its recorded preset's engine, stock voice, pitch and semitones, each unless its flag says otherwise (`--as` names another character); no character and no `--voice`: refused (**exit 2**) -- the editor's default voice is never asked for"],
["`posts fx <project> <item> add caption --match \"…\" --text \"…\" [--target post\\|quoted\\|parent:<i>] [--occurrence n] [--at s] [--lead s] [--hold s] [--place below\\|above\\|side]` · `add clock [--rewind auto\\|on\\|off] [--off]` · `set <n> [--text …] [--place …] [--rewind …]`",
"a post item's **caption** ([report-video.md](report-video.md#a-caption), [knobs.md](knobs.md#a-caption-a-chip-explaining-a-phrase-as-it-is-read)): a chip explaining a phrase (any script: CJK drawn), up as it is read -- `--at`, else the take's word timings, else the reading estimate -- held `--hold` s, by the phrase and never over a word read while it is up; it waits for a word zoom. Its **clock** ([knobs.md](knobs.md#the-clock-each-posts-own-time-on-its-card-run-between-items)): the post's own time on the card, run from the clock item before it (forward; a REWIND when earlier: `--rewind`), `--off` not on this item. Through `updatePostFx`, refused in the build's words (**exit 1**); a zoom's knob on a caption, or a caption's on a zoom (**exit 1**)"],
["`posts clock <project> [on\\|off\\|default] [--zone <IANA zone>] [--json]`",
@@ -1051,7 +1060,7 @@ export const GROUPS = [
["`posts repeats <project> [--match id\\|file\\|audio] [--json]`",
"the **combo counter**'s repeats ([report-video.md](report-video.md#the-combo-counter)): every attachment the cut's post items play more than once -- the same X media id (the capture's url), else the same file (the capture's sha256 when its bytes agree, else hashed; cached by path, size and mtime), else (`--match audio`) the same sound (fpcalc, else a coarse ffmpeg hash) -- its posts in the cut's ORDER with their dates, the tier that matched and the badge each draws (`×2` from the second use, `(×n)` counted but not drawn); a post whose CAPTURE holds the same file but whose entry carries no attachment is listed too, `NOT ATTACHED`, with the `posts attach` that brings it in. Reads only"],
["`posts attach <project> [<item> … \\| --all] [--dry-run] [--json]`",
- "a post item with **no attachment whose capture holds one** (captured after it went in -- `posts repeats` marks them `NOT ATTACHED`): the capture's media (its own channel's `posts-media/<postId>/`, else any channel the cut's posts come from) copied into the project's `posts-media/<slug>/<postId>/` and measured, set as the entry's `media` as `posts reel` would have made it -- nothing else of the entry changes (its paraphrases, narration, knobs kept); an item that has an attachment is never touched. ONE write (one undo point: `timeline <p> undo`), refused whole in the build's words"],
+ "a post item with **no attachment whose capture holds one** (captured after it went in -- `posts repeats` marks them `NOT ATTACHED`): the capture's media (its own channel's `posts-media/<postId>/`, else any channel the cut's posts come from -- looked for in the project's channels tree first, a `.shadow-channels` or `provenance.channelsDir`, then the archive's `CHANNELS_DIR` behind it, read only; `--dry-run` says which tree each file comes from) copied into the project's `posts-media/<slug>/<postId>/` and measured, set as the entry's `media` as `posts reel` would have made it -- nothing else of the entry changes (its paraphrases, narration, knobs kept); an item that has an attachment is never touched. ONE write (one undo point: `timeline <p> undo`), refused whole in the build's words"],
["`posts combo <project> [on=on\\|off] [label=L] [position=top-right\\|top-left\\|bottom-right\\|bottom-left\\|center] [color=#rrggbb] [scale=0.4-2.5] [sfx=off\\|hit\\|coin] [minCount=2-20] [match=id\\|file\\|audio] [--json]` · `posts combo <project> <item> off\\|on\\|auto\\|label=…\\|position=…\\|color=…\\|scale=…\\|sfx=… [--json]`",
"the **combo badge's knobs** ([knobs.md](knobs.md#the-combo-counter)): the cut's (`render.posts.combo`, `updatePostComboRender`; no knobs prints them; `k=` the default again) or one post item's (`combo`, `updatePostCombo`): `off` draws no badge on it -- it still counts -- `on`/`auto` the cut's again. Refused in the build's words (**exit 1**)"],
],
diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs
@@ -87,6 +87,14 @@ const window_ = () => [num("--at", { help: "the window's start, s" }), num("--du
// ---- the rows -------------------------------------------------------------------
const form = (verb, target, summary, args, extra = {}) => ({ verb, summary, target, ui: "form", args, ...extra });
+/** A character's preset flags (`umtool cast add|set`, `cast project <p> add|set`: castCli.mjs fieldsOf). */
+const presetArgs = () => [
+ num("--speed", { help: "its voice's speed, 0.5–2 (Orpheus has none)" }),
+ pick("--convert-engine", ["openvoice", "seed-vc", "default"]), opt("--convert-voice", { help: "engine:voice -- a STOCK voice, never a file" }),
+ pick("--convert-pitch", ["target", "source", "contour", "default"], { help: "the pitch a converted read lands on" }), num("--convert-semitones", { help: "-12…12, moves a followed pitch" }),
+ pick("--enhance", ["on", "off", "default"], { help: "a recording is cleaned first" }), pick("--trim", ["on", "off", "default"], { help: "a recording's edges trimmed to speech" }),
+ opt("--trim-pad", { help: "ms kept either side, 0–2000 (or default)" }), opt("--direction", { help: "one line for the person reading (never sent to a model)" }),
+];
/** A row's block menu (lane block-menus L8b): the block kinds that offer it, and what each fills in. */
const B = (blocks, fromBlock, more = {}) => ({ blocks, fromBlock, ...more });
const none = (verb, target, summary, reason, extra = {}) => ({ verb, summary, target, ui: "none", reason, args: [], ...extra });
@@ -128,17 +136,32 @@ export const VERBS = Object.freeze([
// ---- the cast ----
form("cast ls", "corpus", "the characters' voices across projects", [], { shape: "cast ls" }),
- form("cast add", "corpus", "a character: name, stock voice, handles", [
+ form("cast add", "corpus", "a character: name, stock voice, handles, its two presets", [
arg("id"), opt("--name", { required: true }), opt("--voice", { required: true, help: "engine:voice" }), opt("--handles", { help: "a,b" }), opt("--speakers", { help: "Name,…" }),
- pick("--convert-engine", ["openvoice", "seed-vc"]), opt("--convert-voice", { help: "engine:voice" }), opt("--note"), bool("--narrator", "the recordings' default character"),
+ ...presetArgs(), opt("--note"), bool("--narrator", "the recordings' default character"),
]),
- form("cast set", "corpus", "change a character", [
- arg("id"), opt("--name"), opt("--voice", { help: "engine:voice" }), opt("--handles"), opt("--speakers"), pick("--convert-engine", ["openvoice", "seed-vc"]), opt("--convert-voice"),
- opt("--note"), opt("--add-handle"), opt("--remove-handle"), bool("--no-convert"), bool("--narrator"), bool("--no-narrator"),
+ form("cast set", "corpus", "change a character: its name, handles, presets", [
+ arg("id"), opt("--name"), opt("--voice", { help: "engine:voice" }), opt("--handles"), opt("--speakers"), ...presetArgs(),
+ opt("--note"), opt("--add-handle"), opt("--remove-handle"), bool("--no-convert"), bool("--no-speed"), bool("--narrator"), bool("--no-narrator"),
]),
form("cast rm", "corpus", "a character out of the cast (an undo point)", [arg("id")]),
form("cast undo", "corpus", "the cast as it was before its last write", []),
- form("cast project", "project", "the project's characters, their voices and drift", [project()]),
+ form("cast project", "project", "the project's characters: each one's voice, where it comes from, its drift; this video's own", [project()]),
+ // This video's OWN characters (<project>/narration/characters.json; castStore.mjs: one writer, an undo point a write).
+ form("cast project add", "project", "a character of this video only (anonymous: shown under Anon 1 …)", [
+ project(), arg("id"), opt("--name", { help: "required unless --anonymous" }), opt("--voice", { help: "engine:voice (none: the layers under it)" }), opt("--handles", { help: "a,b" }),
+ bool("--anonymous", "goes by a shown name on umtool's pages; never enters the pool (the cut's card is not anonymised yet)"), opt("--shown", { help: "the shown name (default: the next Anon n)" }), ...presetArgs(), opt("--note"),
+ ], { shape: "cast project <project> add <id>" }),
+ form("cast project set", "project", "change a character of this video's", [
+ project(), arg("id"), opt("--name"), opt("--voice", { help: "engine:voice" }), opt("--handles"), opt("--shown"), ...presetArgs(), opt("--note"), opt("--add-handle"), opt("--remove-handle"),
+ bool("--no-voice", "no voice of its own: the layers under it"), bool("--no-convert"), bool("--no-speed"), bool("--anonymous"), bool("--no-anonymous"),
+ ], { shape: "cast project <project> set <id>" }),
+ form("cast project rm", "project", "a character out of this video's (an undo point)", [project(), arg("id")], { shape: "cast project <project> rm <id>" }),
+ form("cast project undo", "project", "this video's characters as they were before their last write", [project()], { shape: "cast project <project> undo" }),
+ form("cast project pool", "corpus", "Add to the pool: this video's character into the cast", [project(), arg("id")], { shape: "cast project <project> pool <id>" }),
+ form("cast project keep", "project", "Keep in this video only: a cast character copied here, or an author given one", [
+ project(), arg("character", { allowAt: true, help: "a cast character's id, or @handle" }), bool("--anonymous"), opt("--shown"),
+ ], { shape: "cast project <project> keep <character>" }),
form("cast audition", "project", "one line read by 2-6 candidate voices, scored against the real voice", [
arg("character", { allowAt: true, help: "a character id or @handle" }), opt("--voices", { required: true, help: "engine:voice,engine:voice,…" }), project({ name: "--project", required: false }),
opt("--text", { type: "text" }), opt("--item"), num("--line"), bool("--stock"), bool("--no-score"), bool("--score-only"),
@@ -197,6 +220,8 @@ export const VERBS = Object.freeze([
form("chain", "corpus", "an article iteration's pipeline to a video", [
arg("article"), num("n", { required: true, help: "the iteration" }), opt("--from", { help: "the step to start at" }), bool("--dry", "print it"), bool("--final"),
opt("--site-origin"), bool("--draft-all", "Draft everything"), opt("--model"), bool("--deck"),
+ bool("--stop-before-render", "end before the voices: nothing voiced or built"),
+ bool("--allow-whole-recording", "a remote-only channel's windows may download their whole recording (Rumble)"),
], Q),
form("index", "corpus", "the project index (the cache)", [bool("--rebuild"), bool("--prune"), num("--since", { help: "ms" })], { confirm: { what: "prune the index's rows of projects no longer on disk", when: ["--prune"] } }),
form("new", "corpus", "a new project (scaffold)", [
@@ -460,10 +485,12 @@ function posts() {
item({ required: false, help: "the post item (none: --list, --import, --all or --cut)" }), opt("--script", { type: "text" }), bool("--take", "a new read (the editor's tts)"), opt("--note"),
opt("--voice"), opt("--engine"), num("--speed"), num("--pick"), bool("--approve"), bool("--unapprove"), bool("--off"), bool("--on"),
bool("--thread", "with --take: a thread read"), opt("--parents"), bool("--words", "the picked take's word timings"), bool("--import"), bool("--list"), bool("--all"), bool("--draft-scripts"),
- num("--limit"), bool("--force"), file("--recording", { help: "a person's recording (a file of the project) made the read" }), opt("--as"), dry(),
+ num("--limit"), bool("--force"), file("--recording", { help: "a person's recording (a file of the project) made the read" }), opt("--as"),
+ pick("--pitch", ["target", "source", "contour"], { help: "a convert's pitch (--recording, --derive)" }), num("--semitones", { help: "-12…12, moves a followed pitch" }), dry(),
pairs({ required: false, help: "the mix: lead= tail= linger= rate= …, one per line" }), inTake(),
], { ...Q, ...POST_ITEM }),
p("say", "draft", "the pronunciation lexicon", [pick("op", ["ls", "add", "remove", "try", "stale"], { required: true }), arg("word", { required: false, allowAt: true, help: "the word or phrase (try: the text)" }), arg("spoken", { required: false }), bool("--case"), opt("--item"), opt("--note")], { shape: "posts say <project> <op>" }),
+ p("character", "draft", "the character one post item's own read is made with", [item(), arg("character", { required: false, help: "a character's id (this video's own, else the cast's); none: print it" }), bool("--clear", "by its author's handle again")], POST_ITEM),
p("voices", "draft", "the voice map a thread read uses", [pick("op", ["ls", "set", "remove"], { required: true }), arg("handle", { required: false, help: "a handle, or *" }), arg("voice", { required: false })], { shape: "posts voices <project> <op>" }),
p("fit", "draft", "narrated posts' videos cut to their best part", [items(), bool("--all"), num("--linger"), dry()], { ...Q, ...POST_ITEMS }),
p("fx", "draft", "a post item's word zooms, captions, clock, slams", [
diff --git a/umtool/lib/report/cast.test.mjs b/umtool/lib/report/cast.test.mjs
@@ -108,7 +108,8 @@ test("the store: one writer, a stale token refused, undo points, a broken file n
test("umtool cast ls/add/set/rm/undo: the characters across projects", async () => {
let r = await cast(["add", "hostman", "--name", "Host Man", "--voice", "orpheus:zac", "--handles", "@HostMan", "--speakers", "Host", "--json"]);
assert.equal(r.code, 0, r.text());
- assert.deepEqual(r.json().character, { id: "hostman", name: "Host Man", handles: ["hostman"], voice: "orpheus:zac", speakers: ["Host"] });
+ // A character as the CLI says it: version 2's presets, and the `voice` (and `convert`) they answer to.
+ assert.deepEqual(r.json().character, { id: "hostman", name: "Host Man", handles: ["hostman"], synthetic: { voice: "orpheus:zac" }, speakers: ["Host"], voice: "orpheus:zac" });
r = await cast(["add", "hostman", "--name", "Again", "--voice", "orpheus:zac"]);
assert.equal(r.code, 1);
assert.match(r.text(), /in the cast already/);
@@ -122,6 +123,30 @@ test("umtool cast ls/add/set/rm/undo: the characters across projects", async ()
r = await cast(["ls", "--json"]);
assert.deepEqual(r.json().characters.map((c) => [c.id, c.voice, c.handles.join(",")]), [["hostman", "orpheus:zac", "hostman"], ["me", "kokoro:bm_george", "operator"]]);
assert.equal(r.json().characters[1].narrator, true);
+ // The pitch a converted read lands on: laid over the convert entry, what makes no sense refused.
+ r = await cast(["set", "me", "--convert-pitch", "contour", "--convert-semitones", "2", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual(r.json().character.convert, { engine: "seed-vc", pitch: "contour", semitones: 2 });
+ r = await cast(["set", "me", "--convert-voice", "kokoro:af_bella", "--json"]);
+ assert.deepEqual(r.json().character.convert, { engine: "seed-vc", pitch: "contour", semitones: 2, voice: "kokoro:af_bella" }, "the other keys kept");
+ r = await cast(["ls"]);
+ assert.match(r.text(), /convert: seed-vc -> kokoro:af_bella, pitch contour \+2 st/);
+ r = await cast(["set", "me", "--convert-pitch", "target", "--json"]);
+ assert.deepEqual(r.json().character.convert, { engine: "seed-vc", pitch: "target", voice: "kokoro:af_bella" }, "the target's own pitch drops the semitones");
+ for (const [args, re] of [
+ [["--convert-pitch", "high"], /--convert-pitch is one of target, source, contour/],
+ [["--convert-semitones", "13"], /--convert-semitones is a number from -12 to 12/],
+ [["--convert-semitones", "2"], /semitones moves a followed pitch/],
+ [["--convert-engine", "openvoice", "--convert-pitch", "source"], /pitch "source" is seed-vc's: openvoice lands every read on the target's own pitch/],
+ ]) {
+ r = await cast(["set", "me", ...args]);
+ assert.equal(r.code, 1, args.join(" "));
+ assert.match(r.text(), re);
+ }
+ assert.deepEqual((await readCast(ROOT)).cast.characters[1].convert, { engine: "seed-vc", pitch: "target", voice: "kokoro:af_bella" }, "a refusal writes nothing");
+ r = await cast(["set", "me", "--no-convert"]);
+ r = await cast(["set", "me", "--convert-engine", "seed-vc"]);
+ assert.equal(r.code, 0, r.text());
r = await cast(["rm", "me"]);
assert.equal(r.code, 0);
r = await cast(["undo"]);
@@ -202,7 +227,7 @@ test("cast project: each character's voice now and where it comes from, its drif
// --everywhere for an author the cast does not know: a new character from the handle.
r = await cast(["use", "voices", "@guest", "kokoro:af_heart", "--everywhere", "--json"]);
assert.equal(r.code, 0, r.text());
- assert.deepEqual((await readCast(ROOT)).cast.characters.find((c) => c.id === "guest"), { id: "guest", name: "The Guest", handles: ["guest"], voice: "kokoro:af_heart" });
+ assert.deepEqual((await readCast(ROOT)).cast.characters.find((c) => c.id === "guest"), { id: "guest", name: "The Guest", handles: ["guest"], synthetic: { voice: "kokoro:af_heart" }, voice: "kokoro:af_heart" });
// reread --dry-run lists; reread makes them (the stub editor is not here: the plan alone).
r = await cast(["reread", "voices", "hostman", "--dry-run", "--json"]);
assert.deepEqual(r.json().items.map((x) => x.argv.join(" ")), ["posts narrate voices p-1 --take"]);
@@ -278,4 +303,36 @@ test("a recording made a character's read: kept, cleaned (when the editor can),
assert.equal(after.narration.takes[0].engine, "recorded", "the original kept");
assert.equal(r.disclosure, "Narration: voice converted to a synthetic voice (openvoice · kokoro:af_heart)");
await assert.rejects(importRecording(project, e, rec, { as: "nobody", ask: askOp }), /no such character/);
+ assert.equal("pitch" in picked.steps[0], false, "no pitch asked, none recorded");
+ // THE PITCH: the character's own (its convert entry) goes to the editor, a flag for this read beats it, and the
+ // step keeps what the editor says it ran.
+ const bodies = [];
+ const askPitch = async (route, body) => {
+ if (route.endsWith("voice-enhance")) return askOp(route, body);
+ bodies.push(body);
+ await wavOf(body.out, VOICE_A, 2);
+ return { jobId: `conv-${bodies.length + 1}`, result: { engine: body.engine ?? "openvoice", voice: body.voice, pitch: body.pitch ?? "target", ...(body.pitch && body.pitch !== "target" ? { semitones: body.semitones ?? 0 } : {}) } };
+ };
+ await castWrite(castFile(ROOT), (chars) => {
+ const g = chars.find((c) => c.id === "guest");
+ g.convert = { ...(g.convert ?? {}), engine: "seed-vc", pitch: "contour", semitones: 2 };
+ return { changed: "updated" };
+ }, { what: "set guest's convert pitch" });
+ const own = await importRecording(project, (await manifest()).timeline.find((x) => x.id === "p-3"), rec, { ask: askPitch });
+ assert.deepEqual([bodies[0].engine, bodies[0].pitch, bodies[0].semitones], ["seed-vc", "contour", 2]);
+ assert.equal(own.takes.at(-1).step, "converted to kokoro:af_heart (pitch: contour +2 st)");
+ let now = (await manifest()).timeline.find((x) => x.id === "p-3");
+ let step = now.narration.takes[now.narration.pick].steps[0];
+ assert.deepEqual([step.pitch, step.semitones], ["contour", 2]);
+ await importRecording(project, now, rec, { pitch: "source", semitones: -1, ask: askPitch });
+ assert.deepEqual([bodies[1].pitch, bodies[1].semitones], ["source", -1]);
+ // This read at the stock voice's own pitch: the character's semitones go with its pitch.
+ const flat = await importRecording(project, (await manifest()).timeline.find((x) => x.id === "p-3"), rec, { pitch: "target", ask: askPitch });
+ assert.equal(bodies[2].pitch, "target");
+ assert.equal("semitones" in bodies[2], false);
+ assert.equal(flat.takes.at(-1).step, "converted to kokoro:af_heart");
+ now = (await manifest()).timeline.find((x) => x.id === "p-3");
+ step = now.narration.takes[now.narration.pick].steps[0];
+ assert.equal("pitch" in step, false);
+ assert.equal(own.disclosure, "Narration: voice converted to a synthetic voice (seed-vc · kokoro:af_heart)", "the disclosure line is what it was");
});
diff --git a/umtool/lib/report/castAudition.mjs b/umtool/lib/report/castAudition.mjs
@@ -104,18 +104,25 @@ export function characterLines(manifest, handles) {
}
/**
- * The character `who` names for an audition: a cast character (its id, a handle, its name), else an AUTHOR of the
+ * The character `who` names for an audition: one of the project's own characters (its id, a handle), a cast character (its id, a handle, its name), else an AUTHOR of the
* project by @handle (`{ id, name, handles, voice: null }`). Throws AuditionError naming what is missing.
*/
export async function auditionCharacter(cast, who, { project = null, manifest = null } = {}) {
- const { characterOf, findCharacter } = await import("umtool-report-to-video/cast");
+ const { characterOf, findCharacter, projectCharactersOf, shownNameOf } = await import("umtool-report-to-video/cast");
const w = String(who ?? "").trim();
if (!w) throw new AuditionError("an audition is of a character (its id, or @handle)");
+ // This video's own characters first (narration/characters.json): by id, then by a handle -- named as it is shown.
+ const own = project ? projectCharactersOf((await (await import("./castStore.mjs")).readProjectCharacters(project.dir)).doc) : [];
+ const mine = (c) => ({ ...c, name: shownNameOf(c), handles: c.handles ?? [], voice: c.voice ?? null });
if (!w.startsWith("@")) {
+ const p = own.find((x) => x.id === w.toLowerCase());
+ if (p) return mine(p);
const c = findCharacter(cast, w);
if (c) return c;
}
const h = handleKey(w);
+ const p = own.find((x) => (x.handles ?? []).includes(h));
+ if (p) return mine(p);
const c = characterOf(cast, h);
if (c) return c;
if (!project) throw new AuditionError(`${w} is not in the cast (umtool cast ls), and no --project names it`);
diff --git a/umtool/lib/report/castCli.mjs b/umtool/lib/report/castCli.mjs
@@ -1,13 +1,17 @@
// `umtool cast` (umtool-report-to-video/cast.mjs; umtool/docs/knobs.md, "The cast"): the CHARACTERS across projects
-// and their voices, a project's characters, an AUDITION of candidate voices, and the voice a character reads in --
-// for a project (its voice map) or everywhere (the cast) -- with the re-reads that asks for.
+// and their presets, a project's characters (the chain's answer for each author, and the project's OWN characters),
+// an AUDITION of candidate voices, and the voice a character reads in -- for a project or everywhere (the cast) --
+// with the re-reads that asks for.
//
// umtool cast [ls] [--json]
-// umtool cast add <id> --name "…" --voice <engine:voice> [--handles a,b] [--speakers Name,…] [--convert-engine e]
-// [--convert-voice <engine:voice>] [--avatar …] [--note "…"] [--narrator] [--json]
-// umtool cast set <id> [the same flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-narrator] [--json]
+// umtool cast add <id> --name "…" --voice <engine:voice> [the preset flags] [--handles a,b] [--speakers Name,…] [--avatar …] [--note "…"] [--narrator] [--json]
+// umtool cast set <id> [the same flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-speed] [--no-narrator] [--json]
// umtool cast rm <id> [--json] · umtool cast undo [--json]
// umtool cast project <p> [--json]
+// umtool cast project <p> add <id> [--name "…"] [--voice <engine:voice>] [the preset flags] [--handles a,b] [--anonymous [--shown "…"]] [--json]
+// umtool cast project <p> set <id> [the same flags] [--no-voice] [--no-anonymous] … · rm <id> · undo
+// umtool cast project <p> pool <id> its character into the cast ("Add to the pool")
+// umtool cast project <p> keep <character|@handle> [--anonymous [--shown "…"]] a character of this video only
// umtool cast audition <character|@handle> --voices a,b,… [--project <p>] [--text "…" | --item <id> | --line <n>]
// [--no-score | --score-only] [--no-hold] [--json] [--progress ndjson]
// umtool cast use <p> <character|@handle> <voice> [--everywhere] [--json]
@@ -15,45 +19,74 @@
//
// Plain ESM: the CLI runs under bare node.
import path from "node:path";
-import { CAST_CONVERT_ENGINES, characterOf, charactersOf, findCharacter, isQualifiedVoice } from "umtool-report-to-video/cast";
-import { handleKey, voiceRefOf } from "umtool-report-to-video/post-say";
+import {
+ ANON_NAME_PATTERN, CAST_CONVERT_ENGINES, CAST_CONVERT_PITCH, CAST_SEMITONES_MAX, CAST_SPEED, DIRECTION_MAX, TRIM_PAD_MAX_MS, characterOf, characterView, convertPitchErrors, convertPitchLabel,
+ charactersOf, findCharacter, isQualifiedVoice, nextAnonName, projectCharactersOf, shownNameOf, upgradeCharacter,
+} from "umtool-report-to-video/cast";
+import { handleKey, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say";
import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
import { readManifest } from "../projects/report.mjs";
-import { CastError, castFile, castForProject, castWrite, readCast, undoCast } from "./castStore.mjs";
+import { CastError, castFile, castForProject, castWrite, projectCharactersWrite, readCast, readProjectCharacters, undoCast, undoProjectCharacters } from "./castStore.mjs";
+
+const PRESET_FLAGS = "[--speed <s>] [--convert-engine openvoice|seed-vc] [--convert-voice <engine:voice>] [--convert-pitch target|source|contour] [--convert-semitones <n>] [--enhance on|off|default] [--trim on|off|default] [--trim-pad <ms>|default] [--direction \"…\"]";
export const CAST_USAGE = [
"usage: umtool cast [ls] [--json]",
- " umtool cast add <id> --name \"…\" --voice <engine:voice> [--handles a,b] [--speakers Name,…] [--convert-engine openvoice|seed-vc]",
- " [--convert-voice <engine:voice>] [--avatar …] [--note \"…\"] [--narrator] [--json]",
- " umtool cast set <id> [those flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-narrator] [--json]",
+ " umtool cast add <id> --name \"…\" --voice <engine:voice> [--handles a,b] [--speakers Name,…]",
+ ` ${PRESET_FLAGS}`,
+ " [--avatar …] [--note \"…\"] [--narrator] [--json]",
+ " umtool cast set <id> [those flags] [--add-handle h] [--remove-handle h] [--no-convert] [--no-speed] [--no-narrator] [--json]",
" umtool cast rm <id> [--json]",
" umtool cast undo [--json]",
" umtool cast project <project> [--json]",
+ " umtool cast project <project> add <id> [--name \"…\"] [--voice <engine:voice>] [--handles a,b] [--anonymous [--shown \"…\"]] [the preset flags] [--json]",
+ " umtool cast project <project> set <id> [those flags] [--add-handle h] [--remove-handle h] [--no-voice] [--no-convert] [--no-speed] [--no-anonymous] [--json]",
+ " umtool cast project <project> rm <id> | undo | pool <id> | keep <character|@handle> [--anonymous [--shown \"…\"]] [--json]",
" umtool cast audition <character|@handle> --voices kokoro:am_michael,kokoro:am_onyx,orpheus:zac [--project <p>]",
" [--text \"…\" | --item <id> | --line <n> | --stock] [--no-score | --score-only] [--no-hold] [--json] [--progress ndjson]",
" umtool cast use <project> <character|@handle> <engine:voice> [--everywhere] [--json]",
" umtool cast reread <project> <character|@handle> [--dry-run] [--json]",
"",
" THE CAST (<reports>/.umtool/cast.json, one writer, an undo point per write): the characters that recur across",
- " projects -- an id, a name, their handles (X handles / channel slugs), the STOCK voice they read in (engine:voice),",
- " optionally the voice a recording of them is converted to (--convert-voice, its engine --convert-engine), the",
- " names their REAL voice goes by in a project's speakers.json (--speakers: a reference to compare with, never a",
- " target), and one --narrator (a recording's default character). A project's narration/voices.json overrides it",
- " (umtool posts voices); every read asks the same function: the read's own voice, the project's map, the cast, the",
- " narrator's, the default.",
- " project: every character the project's reads use, the voice each reads in now and where it comes from, its",
- " picked reads in another voice (drift: re-read them), the cast voices the project overrides, its reference.",
+ " projects -- an id, a name, their handles (X handles / channel slugs) and TWO PRESETS, picked by how a read is made:",
+ " SYNTHETIC: the STOCK voice they read in (--voice engine:voice) and its speed (--speed 0.5-2; Orpheus has none).",
+ " RECORDED (a recording of them made their read): the voice it is converted to (--convert-voice, its engine",
+ " --convert-engine) and the PITCH that read lands on (--convert-pitch: target = the stock voice's own, the read's",
+ " intonation flattened to it; source = the pitch it was read at; contour = the read's rises and falls at the stock",
+ " voice's register; --convert-semitones -12…12 moves a followed one; source and contour are seed-vc's, with its f0",
+ " model), whether it is cleaned first (--enhance on|off; default on), whether its edges are trimmed to speech",
+ " (--trim on|off; default on) and the room kept either side (--trim-pad <ms>), and a DIRECTION (--direction: one",
+ " line for the person reading -- \"higher, brisk, amused\" -- never sent to a model; \"\" removes it). A convert",
+ " target is always a STOCK synthetic voice: a file or a recording is refused. `default` for a convert flag, --enhance,",
+ " --trim or --trim-pad takes that key off (the default again). Also the names their REAL voice goes",
+ " by in a project's speakers.json (--speakers: a reference to compare with, never a target), and one --narrator (a",
+ " recording's default character). A version 1 file (voice, convert at a character's top) reads as these presets;",
+ " the first write after makes it version 2 (undo puts the old file back).",
+ " ONE READ's PRESET, first hit wins: the command's flags (--voice-for, --voice, --speed, --as, --pitch), the item's",
+ " own character (umtool posts character), this video's character for the author (project add; then its voice map,",
+ " umtool posts voices), the cast's, the narrator's, the default.",
+ " project: every character the project's reads use, the voice each reads in now and WHERE IT COMES FROM (item,",
+ " project, cast, narrator, default), its speed, its picked reads in another voice (drift: re-read them), the cast",
+ " voices the project overrides, its reference; this video's own characters; the items that name their own.",
+ " project <p> add|set|rm|undo: THIS VIDEO's OWN characters (<p>/narration/characters.json, one writer, an undo",
+ " point per write) -- the same shape, for people who must not enter the pool. --anonymous: it goes by a SHOWN NAME",
+ ` (--shown; default the next of "${ANON_NAME_PATTERN.replace("{n}", "1")}", "${ANON_NAME_PATTERN.replace("{n}", "2")}" …) on the Voices page, in cast project and in a recording's note, and never`,
+ " enters the pool. The cut's ON-SCREEN CARD IS NOT ANONYMISED YET: it still shows the post's author. --voice is optional",
+ " here: a character with none leaves the voice to the layers under it. pool <id>: it moves into the cast (an",
+ " anonymous one is refused). keep <character|@handle>: a cast character copied here (its presets changed for this",
+ " video only), or an author with no character given one here, in the voice they read in now.",
" audition: one line (--text; --item: the character's line from that item; --line n: its n-th line; default its",
" first, else a stock line) read by each candidate (2-6) through the editor's tts op (a job; Orpheus is heavy,",
" Kokoro fast), kept at one loudness in <p>/narration/auditions/ (a re-audition is a cache hit), and with --project",
" scored for closeness to the character's real voice (TitaNet-small, local; speakers.json). --no-score: synthesize",
" only; --score-only: score what is kept.",
- " use: the voice for this project (its voice map) or --everywhere (the cast; the project's own override of it is",
- " removed); then the items whose picked reads say the character in another voice -- reread makes them (a new take",
- " each, picked, awaiting approval). Exit 0 done · 1 refused or failed · 2 usage.",
+ " use: the voice for this project (its own character's when it has one for them, else its voice map) or",
+ " --everywhere (the cast; the project's own override of it is removed); then the items whose picked reads say the",
+ " character in another voice -- reread makes them (a new take each, picked, awaiting approval).",
+ " Exit 0 done · 1 refused or failed · 2 usage.",
].join("\n");
-const VALUED = new Set(["--name", "--voice", "--handles", "--speakers", "--convert-engine", "--convert-voice", "--avatar", "--note", "--add-handle", "--remove-handle", "--voices", "--project", "--text", "--item", "--line", "--progress"]);
+const VALUED = new Set(["--name", "--voice", "--handles", "--speakers", "--convert-engine", "--convert-voice", "--convert-pitch", "--convert-semitones", "--avatar", "--note", "--add-handle", "--remove-handle", "--voices", "--project", "--text", "--item", "--line", "--progress", "--speed", "--enhance", "--trim", "--trim-pad", "--direction", "--shown"]);
const splitList = (v) => String(v ?? "").split(",").map((x) => x.trim()).filter(Boolean);
function parse(args) {
@@ -71,6 +104,20 @@ function parse(args) {
return { words, flags, str: (k) => flags.get(k)?.at(-1) ?? null, has: (k) => flags.has(k), all: (k) => flags.get(k) ?? [] };
}
+/** `on` / `off` / `default` as true / false / null (null: the key removed -- the default again). */
+function onOff(flag, v) {
+ const x = String(v).trim().toLowerCase();
+ if (x === "on" || x === "true" || x === "yes") return true;
+ if (x === "off" || x === "false" || x === "no") return false;
+ if (x === "default") return null;
+ throw new CastError(`${flag} is on, off or default (got ${v || "nothing"})`);
+}
+const numberOf = (flag, v, lo, hi, what) => {
+ const n = Number(v);
+ if (String(v).trim() === "" || !Number.isFinite(n) || n < lo || n > hi) throw new CastError(`${flag} is ${what} from ${lo} to ${hi} (got ${v || "nothing"})`);
+ return n;
+};
+
/** The fields `add`/`set` take from the flags (only those given). */
function fieldsOf(p) {
const f = {};
@@ -80,19 +127,157 @@ function fieldsOf(p) {
if (!isQualifiedVoice(v)) throw new CastError(`--voice is a STOCK voice with its engine: kokoro:am_michael, orpheus:zac (got ${v})`);
f.voice = v;
}
+ if (p.str("--speed") !== null) f.speed = numberOf("--speed", p.str("--speed"), CAST_SPEED[0], CAST_SPEED[1], "a number");
if (p.str("--handles") !== null) f.handles = splitList(p.str("--handles")).map(handleKey);
if (p.str("--speakers") !== null) f.speakers = splitList(p.str("--speakers"));
if (p.str("--avatar") !== null) f.avatar = p.str("--avatar");
if (p.str("--note") !== null) f.note = p.str("--note");
- if (p.str("--convert-engine") !== null || p.str("--convert-voice") !== null) {
- const ce = p.str("--convert-engine");
- if (ce !== null && !CAST_CONVERT_ENGINES.includes(ce)) throw new CastError(`--convert-engine is ${CAST_CONVERT_ENGINES.join(" or ")}`);
- f.convert = { ...(ce ? { engine: ce } : {}), ...(p.str("--convert-voice") ? { voice: p.str("--convert-voice") } : {}) };
+ if (["--convert-engine", "--convert-voice", "--convert-pitch", "--convert-semitones"].some((k) => p.str(k) !== null)) {
+ // `default` for one of them takes that key off the entry (the editor's engine, the character's own voice, no pitch said).
+ const given = (k) => (p.str(k) !== null && p.str(k).trim().toLowerCase() !== "default" ? p.str(k).trim() : null);
+ const dropped = (k) => p.str(k) !== null && p.str(k).trim().toLowerCase() === "default";
+ const ce = given("--convert-engine");
+ if (ce !== null && !CAST_CONVERT_ENGINES.includes(ce)) throw new CastError(`--convert-engine is ${CAST_CONVERT_ENGINES.join(" or ")} (or default)`);
+ const cp = given("--convert-pitch");
+ if (cp !== null && !CAST_CONVERT_PITCH.includes(cp)) throw new CastError(`--convert-pitch is one of ${CAST_CONVERT_PITCH.join(", ")} (or default)`);
+ const cs = p.str("--convert-semitones") === null ? null : Number(p.str("--convert-semitones"));
+ if (cs !== null && !(p.str("--convert-semitones").trim() !== "" && Number.isFinite(cs) && Math.abs(cs) <= CAST_SEMITONES_MAX)) throw new CastError(`--convert-semitones is a number from -${CAST_SEMITONES_MAX} to ${CAST_SEMITONES_MAX}`);
+ const cvv = given("--convert-voice");
+ if (cvv && !isQualifiedVoice(cvv)) throw new CastError(`--convert-voice is a STOCK voice with its engine, kokoro:am_michael -- never a file or a recording (got ${cvv})`);
+ // Only the keys given: `set` lays them over the character's entry (convertOver), `add` takes them as they are.
+ f.convert = {
+ ...(ce ? { engine: ce } : dropped("--convert-engine") ? { engine: null } : {}), ...(cvv ? { voice: cvv } : dropped("--convert-voice") ? { voice: null } : {}),
+ ...(cp ? { pitch: cp } : dropped("--convert-pitch") ? { pitch: null } : {}), ...(cs !== null ? { semitones: cs } : {}),
+ };
}
+ if (p.str("--enhance") !== null) f.enhance = onOff("--enhance", p.str("--enhance"));
+ if (p.str("--trim") !== null) f.trimOn = onOff("--trim", p.str("--trim"));
+ if (p.str("--trim-pad") !== null) f.trimPad = p.str("--trim-pad").trim().toLowerCase() === "default" ? null : numberOf("--trim-pad", p.str("--trim-pad"), 0, TRIM_PAD_MAX_MS, "a number of milliseconds");
+ if (p.str("--direction") !== null) {
+ const d = p.str("--direction").replace(/\s+/g, " ").trim();
+ if (d.length > DIRECTION_MAX) throw new CastError(`--direction is one line for the person reading (at most ${DIRECTION_MAX} characters)`);
+ f.direction = d;
+ }
+ if (p.str("--shown") !== null) f.shown = p.str("--shown").trim();
return f;
}
-const line = (c) => `${c.id.padEnd(16)} ${c.voice.padEnd(20)} ${c.name}${c.handles?.length ? ` ${c.handles.map((h) => `@${h}`).join(" ")}` : ""}${c.convert ? ` convert: ${c.convert.engine ?? "default"} -> ${c.convert.voice ?? c.voice}` : ""}${c.speakers?.length ? ` real voice: ${c.speakers.join(", ")}` : ""}${c.narrator ? " (the narrator)" : ""}${c.note ? ` -- ${c.note}` : ""}`;
+/**
+ * A convert entry with the flags' keys laid over it, and what makes no sense together refused in a sentence: the
+ * target's own pitch drops the semitones (nothing is followed to move), 0 semitones is no entry.
+ */
+function convertOver(before, given) {
+ const cv = { ...(before ?? {}), ...given };
+ for (const k of Object.keys(cv)) if (cv[k] === null) delete cv[k];
+ if ((given.pitch === "target" || given.pitch === null) && given.semitones === undefined) delete cv.semitones;
+ if (cv.semitones === 0) delete cv.semitones;
+ const wrong = convertPitchErrors(cv);
+ if (wrong.length) throw new CastError(`convert: ${wrong[0]} (--convert-engine seed-vc --convert-pitch source|contour)`);
+ return cv;
+}
+
+/**
+ * THE CHARACTER the flags make, pure: `before` (version 2's shape; null: a new one, `id`) with the fields given laid
+ * over its presets -- `layer` "cast" (it may be the narrator: the caller clears the others') or "project" (it may be
+ * anonymous, shown under `anon()`'s name when none is given; its voice may be removed). Refused in a sentence.
+ */
+export function characterFrom(before, id, f, p, { layer = "cast", anon = () => ANON_NAME_PATTERN.replace("{n}", "1") } = {}) {
+ const c = before ? JSON.parse(JSON.stringify(upgradeCharacter(before))) : { id, name: "", handles: [] };
+ if (f.name !== undefined) c.name = f.name;
+ if (f.handles) c.handles = f.handles;
+ if (!Array.isArray(c.handles)) c.handles = [];
+ for (const h of p.all("--add-handle").map(handleKey)) if (h && !c.handles.includes(h)) c.handles = [...c.handles, h];
+ for (const h of p.all("--remove-handle").map(handleKey)) c.handles = c.handles.filter((x) => x !== h);
+ // The synthetic preset.
+ const syn = { ...(c.synthetic ?? {}) };
+ if (f.voice) syn.voice = f.voice;
+ if (f.speed !== undefined) syn.speed = f.speed;
+ if (p.has("--no-speed") || syn.speed === 1) delete syn.speed;
+ if (p.has("--no-voice")) {
+ if (layer !== "project") throw new CastError("--no-voice is for a character of one video (umtool cast project <p> set …): a cast character has a stock voice");
+ delete syn.voice;
+ delete syn.speed;
+ }
+ if (syn.speed !== undefined && !syn.voice) throw new CastError("--speed is its voice's: give the character a voice too (--voice <engine:voice>)");
+ if (Object.keys(syn).length) c.synthetic = syn;
+ else delete c.synthetic;
+ // The recorded preset.
+ const rec = { ...(c.recorded ?? {}) };
+ if (f.convert) rec.convert = convertOver(rec.convert, f.convert);
+ if (p.has("--no-convert")) delete rec.convert;
+ if (rec.convert && !Object.keys(rec.convert).length) delete rec.convert;
+ if (f.enhance !== undefined) {
+ if (f.enhance === null) delete rec.enhance;
+ else rec.enhance = f.enhance;
+ }
+ if (f.trimOn !== undefined || f.trimPad !== undefined) {
+ const t = { ...(rec.trim ?? {}) };
+ if (f.trimOn === null) delete t.on;
+ else if (f.trimOn !== undefined) t.on = f.trimOn;
+ if (f.trimPad === null) delete t.padMs;
+ else if (f.trimPad !== undefined) t.padMs = f.trimPad;
+ if (f.trimOn === null && f.trimPad === undefined) delete t.padMs;
+ if (Object.keys(t).length) rec.trim = t;
+ else delete rec.trim;
+ }
+ if (f.direction !== undefined) {
+ if (f.direction) rec.direction = f.direction;
+ else delete rec.direction;
+ }
+ if (Object.keys(rec).length) c.recorded = rec;
+ else delete c.recorded;
+ if (f.speakers) c.speakers = f.speakers;
+ for (const k of ["avatar", "note"]) {
+ if (f[k] !== undefined) c[k] = f[k];
+ if (c[k] === "") delete c[k];
+ }
+ if (c.speakers && !c.speakers.length) delete c.speakers;
+ if (layer === "cast") {
+ if (p.has("--anonymous") || f.shown !== undefined) throw new CastError("an anonymous character is one video's, never the pool's: umtool cast project <p> add <id> --anonymous");
+ if (p.has("--narrator")) c.narrator = true;
+ if (p.has("--no-narrator")) delete c.narrator;
+ } else {
+ if (p.has("--narrator")) throw new CastError("the narrator is a cast character (umtool cast set <id> --narrator)");
+ if (p.has("--anonymous")) c.anonymous = true;
+ if (p.has("--no-anonymous")) {
+ delete c.anonymous;
+ delete c.shown;
+ }
+ if (f.shown !== undefined) {
+ if (!c.anonymous) throw new CastError("--shown is an anonymous character's shown name (--anonymous)");
+ if (f.shown) c.shown = f.shown;
+ else delete c.shown;
+ }
+ if (c.anonymous && !c.shown) c.shown = anon();
+ if (c.anonymous && !c.name) c.name = c.shown;
+ }
+ return upgradeCharacter(c);
+}
+
+/** A character's recorded preset as words: "convert: seed-vc -> kokoro:am_michael, pitch contour +2 st; not cleaned; …". */
+function recordedWords(c) {
+ const rec = c.recorded;
+ if (!rec) return "";
+ const cv = rec.convert;
+ const bits = [];
+ if (cv) bits.push(`convert: ${cv.engine ?? "default"} -> ${cv.voice ?? c.voice ?? "?"}${convertPitchLabel(cv) ? `, pitch ${convertPitchLabel(cv)}` : ""}`);
+ if (rec.enhance === false) bits.push("not cleaned");
+ if (rec.trim?.on === false) bits.push("edges not trimmed");
+ else if (typeof rec.trim?.padMs === "number") bits.push(`trim pad ${rec.trim.padMs} ms`);
+ if (rec.direction) bits.push(`direction: "${rec.direction}"`);
+ return bits.join("; ");
+}
+
+/** A character as a line (a view: cast.mjs characterView). */
+const line = (c0) => {
+ const c = characterView(c0);
+ const speed = c.synthetic?.speed;
+ const voice = `${c.voice ?? "(no voice of its own)"}${typeof speed === "number" ? ` ×${speed}` : ""}`;
+ return `${c.id.padEnd(16)} ${voice.padEnd(20)} ${c.anonymous ? `${shownNameOf(c)} (anonymous; ${c.name})` : c.name}${c.handles?.length ? ` ${c.handles.map((h) => `@${h}`).join(" ")}` : ""}${recordedWords(c) ? ` ${recordedWords(c)}` : ""}${c.speakers?.length ? ` real voice: ${c.speakers.join(", ")}` : ""}${c.narrator ? " (the narrator)" : ""}${c.note ? ` -- ${c.note}` : ""}`;
+};
+
+/** An id for a handle's new character ("kirsche.verstahl" -> "kirsche-verstahl"). */
+const idOfHandle = (h) => h.replace(/[^a-z0-9_-]/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 48) || "character";
async function projectOf(ref, reportsRoot) {
const r = await resolveProject(ref, reportsRoot);
@@ -109,19 +294,127 @@ export async function projectView(project, { reportsRoot = REPORTS_ROOT } = {})
const { readSpeakers } = await import("./speakerCheck.mjs");
const { projectCharacters } = await import("./castProject.mjs");
const castRead = await castForProject(project.dir, reportsRoot);
+ const ownRead = await readProjectCharacters(project.dir);
const map = await readVoiceMap(project.dir).catch(() => ({}));
const speakers = await readSpeakers(project.dir).catch(() => []);
- const view = projectCharacters(manifest, { map, cast: castRead.cast, speakers });
- return { manifest, map, castRead, speakers, view };
+ const view = projectCharacters(manifest, { map, cast: castRead.cast, project: ownRead.doc, speakers });
+ return { manifest, map, castRead, ownRead, speakers, view };
}
-/** The handles `ref` names in a project: a character's (the cast's), or one @handle. */
-function handlesOf(ref, castRead, view) {
- const c = findCharacter(castRead.cast, String(ref).replace(/^@+/, ""));
- if (c && !String(ref).startsWith("@")) return { character: c, handles: [...(c.handles ?? [])] };
+/** The handles `ref` names in a project: a character's (the project's own, else the cast's), or one @handle. */
+function handlesOf(ref, castRead, view, ownRead = null) {
+ const bare = String(ref).replace(/^@+/, "");
+ const at = String(ref).startsWith("@");
+ const own = projectCharactersOf(ownRead?.doc);
+ const mine = at ? null : own.find((c) => c.id === bare.toLowerCase()) ?? null;
+ if (mine) return { character: mine, layer: "project", handles: [...(mine.handles ?? [])] };
+ const c = findCharacter(castRead.cast, bare);
+ if (c && !at) return { character: c, layer: "cast", handles: [...(c.handles ?? [])] };
const h = handleKey(ref);
const row = view?.characters?.find((r) => r.handles.includes(h)) ?? null;
- return { character: characterOf(castRead.cast, h), handles: [h], row };
+ const ownByHandle = own.find((x) => (x.handles ?? []).includes(h)) ?? null;
+ return { character: ownByHandle ?? characterOf(castRead.cast, h), layer: ownByHandle ? "project" : characterOf(castRead.cast, h) ? "cast" : null, handles: [h], row };
+}
+
+/**
+ * `umtool cast project <p> add|set|rm|undo|pool|keep …`: THIS VIDEO's OWN characters (castStore.mjs
+ * projectCharactersWrite: one writer, an undo point a write), and the two ways between them and the pool.
+ */
+async function projectCharactersCommand(project, op, rest, p, { reportsRoot, out, file }) {
+ const what = (w) => `${w} (${project.id})`;
+ if (op === "add" || op === "set") {
+ const [id] = rest;
+ if (!id) throw new CastError(`cast project ${op} takes the character's id`);
+ const f = fieldsOf(p);
+ const r = await projectCharactersWrite(project.dir, (chars) => {
+ const at = chars.findIndex((c) => c.id === id);
+ if (op === "add") {
+ if (at >= 0) throw new CastError(`${id} is one of ${project.id}'s characters already (umtool cast project ${project.id} set ${id} …)`);
+ if (!f.name && !p.has("--anonymous")) throw new CastError('cast project add takes --name "…" (or --anonymous: its shown name)');
+ const c = characterFrom(null, id, f, p, { layer: "project", anon: () => nextAnonName(chars) });
+ chars.push(c);
+ return { changed: "added", character: c };
+ }
+ if (at < 0) throw new CastError(`no ${id} among ${project.id}'s characters (umtool cast project ${project.id})`);
+ const c = characterFrom(chars[at], id, f, p, { layer: "project", anon: () => nextAnonName(chars.filter((_, i) => i !== at)) });
+ chars[at] = c;
+ return { changed: "updated", character: c };
+ }, { what: what(`${op} ${id}`) });
+ out({ ok: true, scope: "project", changed: r.changed, character: characterView(r.character), token: r.token }, `${r.changed} in ${project.id}: ${line(r.character)}`);
+ return 0;
+ }
+ if (op === "rm" || op === "remove") {
+ const [id] = rest;
+ if (!id) throw new CastError("cast project rm takes the character's id");
+ const r = await projectCharactersWrite(project.dir, (chars) => {
+ const at = chars.findIndex((c) => c.id === id);
+ if (at < 0) throw new CastError(`no ${id} among ${project.id}'s characters`);
+ const [gone] = chars.splice(at, 1);
+ return { removed: gone };
+ }, { what: what(`rm ${id}`) });
+ out({ ok: true, scope: "project", removed: characterView(r.removed), token: r.token }, `removed ${id} from ${project.id}'s characters (umtool cast project ${project.id} undo puts it back)`);
+ return 0;
+ }
+ if (op === "undo") {
+ const r = await undoProjectCharacters(project.dir);
+ out({ ok: true, scope: "project", undone: r.undone, at: r.at, left: r.left, token: r.token }, `undone: ${r.undone} (${r.left} undo point(s) left)`);
+ return 0;
+ }
+ if (op === "pool") {
+ // "Add to the pool": the project's character into the cast, then out of the project (the cast's answers here too).
+ const [id] = rest;
+ if (!id) throw new CastError("cast project pool takes the character's id");
+ const own = await readProjectCharacters(project.dir);
+ if (own.error) throw new CastError(own.error);
+ const c = (own.doc.characters ?? []).map(upgradeCharacter).find((x) => x.id === id);
+ if (!c) throw new CastError(`no ${id} among ${project.id}'s characters`);
+ if (c.anonymous) throw new CastError(`${id} is anonymous: it stays in this video (umtool cast project ${project.id} set ${id} --no-anonymous first, if that is meant)`);
+ if (!c.synthetic?.voice) throw new CastError(`${id} has no stock voice: a cast character has one (umtool cast project ${project.id} set ${id} --voice <engine:voice>)`);
+ const castPath = (await castForProject(project.dir, reportsRoot)).file ?? file;
+ const w = await castWrite(castPath, (chars) => {
+ if (chars.some((x) => x.id === id)) throw new CastError(`${id} is in the cast already (umtool cast set ${id} …; or umtool cast project ${project.id} rm ${id})`);
+ chars.push(c);
+ return { character: c };
+ }, { what: `${id} into the pool (from ${project.id})` });
+ await projectCharactersWrite(project.dir, (chars) => {
+ const at = chars.findIndex((x) => x.id === id);
+ if (at >= 0) chars.splice(at, 1);
+ return {};
+ }, { what: what(`${id} into the pool`) });
+ out({ ok: true, scope: "cast", changed: "pooled", character: characterView(w.character), token: w.token }, `${id} is in the pool now, for every project: ${line(w.character)}`);
+ return 0;
+ }
+ if (op === "keep") {
+ // "Keep in this video only": a cast character copied here, or an author with none given one here.
+ const [who] = rest;
+ if (!who) throw new CastError("cast project keep takes a cast character (its id) or an author (@handle)");
+ const v = await projectView(project, { reportsRoot });
+ if (v.ownRead.error) throw new CastError(v.ownRead.error);
+ const t = handlesOf(who, v.castRead, v.view, v.ownRead);
+ if (t.layer === "project") throw new CastError(`${t.character.id} is one of ${project.id}'s characters already (umtool cast project ${project.id} set ${t.character.id} …)`);
+ const f = fieldsOf(p);
+ const r = await projectCharactersWrite(project.dir, (chars) => {
+ let base;
+ if (t.character) {
+ // The cast's, as it is now -- never its narrator mark (the narrator is the cast's).
+ const { narrator: _n, ...copy } = upgradeCharacter((v.castRead.cast.characters ?? []).find((x) => x.id === t.character.id));
+ base = copy;
+ } else {
+ const h = t.handles[0];
+ if (!h || h === "*") throw new CastError(`${who}: no such character, and not a handle`);
+ const now = t.row?.voice ?? null;
+ const spec = now && now.engine ? voiceSpecOf({ engine: now.engine, voice: now.voice }) : null;
+ base = { id: idOfHandle(h), name: (t.row?.name || h).slice(0, 80), handles: [h], ...(isQualifiedVoice(spec) ? { synthetic: { voice: spec } } : {}) };
+ }
+ if (chars.some((x) => x.id === base.id)) throw new CastError(`${base.id} is one of ${project.id}'s characters already`);
+ const c = characterFrom(base, base.id, f, p, { layer: "project", anon: () => nextAnonName(chars) });
+ chars.push(c);
+ return { character: c };
+ }, { what: what(`keep ${who}`) });
+ out({ ok: true, scope: "project", changed: "kept", character: characterView(r.character), token: r.token }, `kept in ${project.id} only: ${line(r.character)}`);
+ return 0;
+ }
+ throw new CastError(`cast project <p>: nothing (the view), add, set, rm, undo, pool or keep (not ${op})`);
}
/**
@@ -164,26 +457,20 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
if (sub === "add") {
if (at >= 0) throw new CastError(`${id} is in the cast already (umtool cast set ${id} …)`);
if (!f.name || !f.voice) throw new CastError('cast add takes --name "…" and --voice <engine:voice>');
- const c = { id, name: f.name, handles: f.handles ?? [], voice: f.voice, ...(f.convert ? { convert: f.convert } : {}), ...(f.speakers ? { speakers: f.speakers } : {}), ...(f.avatar ? { avatar: f.avatar } : {}), ...(f.note ? { note: f.note } : {}), ...(p.has("--narrator") ? { narrator: true } : {}) };
+ const c = characterFrom(null, id, f, p, { layer: "cast" });
if (c.narrator) for (const x of chars) delete x.narrator;
chars.push(c);
return { changed: "added", character: c };
}
if (at < 0) throw new CastError(`no ${id} in the cast (umtool cast ls)`);
- const c = { ...chars[at], ...f };
- for (const h of p.all("--add-handle").map(handleKey)) if (h && !c.handles.includes(h)) c.handles = [...c.handles, h];
- for (const h of p.all("--remove-handle").map(handleKey)) c.handles = c.handles.filter((x) => x !== h);
- if (p.has("--no-convert")) delete c.convert;
- if (p.has("--narrator")) {
- for (const x of chars) delete x.narrator;
- c.narrator = true;
- }
- if (p.has("--no-narrator")) delete c.narrator;
- for (const k of ["note", "avatar"]) if (c[k] === "") delete c[k];
+ // The flags are laid over the character's presets: --convert-pitch alone keeps its engine and voice.
+ const c = characterFrom(chars[at], id, f, p, { layer: "cast" });
+ if (p.has("--narrator")) for (const x of chars) delete x.narrator;
+ if (p.has("--narrator")) c.narrator = true;
chars[at] = c;
return { changed: "updated", character: c };
}, { what: `${sub} ${id}` });
- out({ ok: true, changed: r.changed, character: r.character, token: r.token }, `${r.changed} ${line(r.character)}`);
+ out({ ok: true, changed: r.changed, character: characterView(r.character), token: r.token }, `${r.changed} ${line(r.character)}`);
return 0;
}
if (sub === "rm" || sub === "remove") {
@@ -195,7 +482,7 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
const [gone] = chars.splice(at, 1);
return { removed: gone };
}, { what: `rm ${id}` });
- out({ ok: true, removed: r.removed, token: r.token }, `removed ${id} from the cast (umtool cast undo puts it back)`);
+ out({ ok: true, removed: characterView(r.removed), token: r.token }, `removed ${id} from the cast (umtool cast undo puts it back)`);
return 0;
}
if (sub === "undo") {
@@ -204,20 +491,32 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
return 0;
}
if (sub === "project") {
- const [ref] = rest;
+ const [ref, psub, ...prest] = rest;
if (!ref) throw new CastError("cast project takes the project");
const project = await projectOf(ref, reportsRoot);
- const { view, map, castRead } = await projectView(project, { reportsRoot });
+ if (psub && psub !== "ls") return await projectCharactersCommand(project, psub, prest, p, { reportsRoot, out, file });
+ const { view, map, castRead, ownRead } = await projectView(project, { reportsRoot });
if (json) {
- log(JSON.stringify({ ok: true, project: project.id, castFile: castRead.file, ...(castRead.error ? { castError: castRead.error } : {}), map, ...view }, null, 2));
+ log(JSON.stringify({
+ ok: true, project: project.id, castFile: castRead.file, ...(castRead.error ? { castError: castRead.error } : {}),
+ charactersFile: ownRead.file, charactersToken: ownRead.token, ...(ownRead.error ? { charactersError: ownRead.error } : {}), map, ...view,
+ }, null, 2));
return 0;
}
- log(`${project.id}: ${view.characters.length} character(s); the narrator ${view.narrator.spec} (${view.narrator.from})${castRead.error ? `\n the cast is NOT read: ${castRead.error}` : ""}`);
+ const fromWords = (v) => `${v.from}${v.character && v.from !== "narrator" && v.from !== "default" ? `: ${v.character}` : ""}`;
+ const speedWords = (v) => (typeof v.speed === "number" ? ` ×${v.speed}` : "");
+ log(`${project.id}: ${view.characters.length} character(s); the narrator ${view.narrator.spec} (${view.narrator.from})${castRead.error ? `\n the cast is NOT read: ${castRead.error}` : ""}${ownRead.error ? `\n this video's characters are NOT read: ${ownRead.error}` : ""}`);
for (const c of view.characters) {
- log(` ${(c.character ? c.character.id : c.key).padEnd(18)} ${c.voice.spec.padEnd(20)} (${c.voice.from}) ${c.items} item(s), ${c.context} context${c.speaker ? ` real voice: ${c.speaker}` : ""}`);
+ log(` ${(c.character ? c.character.id : c.key).padEnd(18)} ${`${c.voice.spec}${speedWords(c.voice)}`.padEnd(20)} (${fromWords(c.voice)}) ${c.items} item(s), ${c.context} context${c.speaker ? ` real voice: ${c.speaker}` : ""}${c.character?.anonymous ? ` shown as "${c.character.shown}"` : ""}`);
+ if (c.recorded && (c.character?.recorded || c.recorded.convert.voice)) log(` a recording of them: ${c.recorded.convert.voice ? `converted to ${c.recorded.convert.voice}${c.recorded.convert.engine ? ` (${c.recorded.convert.engine})` : ""}${convertPitchLabel(c.recorded.convert) ? `, pitch ${convertPitchLabel(c.recorded.convert)}` : ""}` : "not converted (no stock voice)"}; ${c.recorded.enhance ? "cleaned" : "not cleaned"}; ${c.recorded.trim.on ? `edges trimmed${c.recorded.trim.padMs !== null ? ` (pad ${c.recorded.trim.padMs} ms)` : ""}` : "edges not trimmed"}${c.recorded.direction ? `; direction: "${c.recorded.direction}"` : ""}`);
if (c.drift.length) log(` ${c.drift.length} read(s) in another voice: ${c.drift.map((d) => `${d.id} ${d.reads} (now ${d.want})`).join(", ")} -- umtool cast reread ${project.id} ${c.character?.id ?? `@${c.handles[0]}`}`);
}
for (const o of view.overrides) log(` note: @${o.handle} (${o.character}) reads in ${o.project} here -- the cast says ${o.cast} (an override on purpose)`);
+ if (view.own.length) {
+ log(` this video's own characters (${ownRead.file}):`);
+ for (const c of view.own) log(` ${line(c)}`);
+ }
+ for (const it of view.itemCharacters) log(` item ${it.id} is read as ${it.character}${it.found ? ` (${it.layer === "project" ? "this video's" : "the cast's"}): ${it.voice.spec}${speedWords(it.voice)} (${fromWords(it.voice)})` : ` -- NO SUCH CHARACTER: it reads as its author does, ${it.voice.spec} (${fromWords(it.voice)}); umtool posts character ${project.id} ${it.id} --clear`}`);
return 0;
}
if (sub === "use") {
@@ -225,27 +524,35 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
if (!ref || !who || !voice) throw new CastError("cast use takes the project, the character (or @handle) and the voice: cast use quartering-diet thequartering kokoro:am_michael");
const project = await projectOf(ref, reportsRoot);
const before = await projectView(project, { reportsRoot });
- const t = handlesOf(who, before.castRead, before.view);
+ if (before.ownRead.error) throw new CastError(before.ownRead.error);
+ const t = handlesOf(who, before.castRead, before.view, before.ownRead);
if (!t.handles.length) throw new CastError(`${who} has no handles to give a voice (umtool cast set ${who} --add-handle <h>)`);
if (!voiceRefOf(voice)) throw new CastError(`${voice} is not a stock voice (tara, kokoro:am_michael): a file or a recording is never a voice`);
const { updateVoiceMap } = await import("./postSay.mjs");
const removed = [];
let scope = "project";
+ const cast = before.castRead.cast;
+ // This video's own characters that answer for these handles (their presets come before the cast's).
+ const ownFor = projectCharactersOf(before.ownRead.doc).filter((c) => (c.handles ?? []).some((h) => t.handles.includes(h)));
if (p.has("--everywhere")) {
+ const anon = ownFor.find((c) => c.anonymous);
+ if (anon) throw new CastError(`${anon.id} is anonymous: it stays in this video, never the pool (umtool cast use ${project.id} ${anon.id} ${voice} sets its voice here)`);
if (!isQualifiedVoice(voice)) throw new CastError(`--everywhere takes a voice with its engine (kokoro:am_michael), so every project reads it the same`);
scope = "cast";
const castPath = before.castRead.file ?? file;
+ // The cast's character: the one named, else the one a handle belongs to (a project's own character is not it).
+ const target = t.layer === "cast" ? t.character : t.handles.map((h) => characterOf(cast, h)).find(Boolean) ?? null;
await castWrite(castPath, (chars) => {
- const c = t.character ? chars.find((x) => x.id === t.character.id) : null;
- if (c) c.voice = voice;
+ const c = target ? chars.find((x) => x.id === target.id) : null;
+ if (c) c.synthetic = { ...(c.synthetic ?? {}), voice };
else {
const h = t.handles[0];
- const id = h.replace(/[^a-z0-9_-]/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 48) || "character";
+ const id = idOfHandle(h);
if (chars.some((x) => x.id === id)) throw new CastError(`${id} is in the cast already, without @${h}: umtool cast set ${id} --add-handle ${h}`);
- chars.push({ id, name: (t.row?.name || h).slice(0, 80), handles: [h], voice });
+ chars.push({ id, name: (t.row?.name || h).slice(0, 80), handles: [h], synthetic: { voice } });
}
return {};
- }, { what: `${t.character?.id ?? `@${t.handles[0]}`} reads in ${voice} (from ${project.id})` });
+ }, { what: `${target?.id ?? `@${t.handles[0]}`} reads in ${voice} (from ${project.id})` });
// Its voice everywhere -- here too: the project's own override of it goes.
for (const h of t.handles) {
if (h in before.map) {
@@ -253,16 +560,29 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
removed.push(h);
}
}
+ // (A character of this video's own for the handle still answers first: said below, never removed unasked.)
} else {
- for (const h of t.handles) await updateVoiceMap(project.dir, { set: { handle: h, voice } });
+ // This video's own character for a handle takes it (its preset answers before the voice map); else the map.
+ const own = projectCharactersOf(before.ownRead.doc);
+ const mineOf = (h) => own.find((c) => (c.handles ?? []).includes(h) && c.voice) ?? null;
+ const ids = [...new Set(t.handles.map((h) => mineOf(h)?.id).filter(Boolean))];
+ if (ids.length) {
+ if (!isQualifiedVoice(voice)) throw new CastError(`${ids.join(", ")} is this video's own character: its voice names its engine (kokoro:am_michael)`);
+ await projectCharactersWrite(project.dir, (chars) => {
+ for (const c of chars) if (ids.includes(c.id)) c.synthetic = { ...(c.synthetic ?? {}), voice };
+ return {};
+ }, { what: `${ids.join(", ")} read${ids.length === 1 ? "s" : ""} in ${voice} (${project.id})` });
+ }
+ for (const h of t.handles) if (!mineOf(h)) await updateVoiceMap(project.dir, { set: { handle: h, voice } });
}
const after = await projectView(project, { reportsRoot });
const { rereadPlan } = await import("./castProject.mjs");
const plan = rereadPlan(project.id, after.manifest, after.view.characters.flatMap((c) => c.drift), t.handles);
out(
- { ok: true, scope, handles: t.handles, voice, removed, reread: plan.items.map((x) => ({ id: x.id, take: x.take, thread: x.thread, reads: x.reads, argv: x.argv })), skipped: plan.skipped },
+ { ok: true, scope, handles: t.handles, voice, removed, ...(scope === "cast" && ownFor.some((c) => c.voice) ? { shadowedBy: ownFor.filter((c) => c.voice).map((c) => c.id) } : {}), reread: plan.items.map((x) => ({ id: x.id, take: x.take, thread: x.thread, reads: x.reads, argv: x.argv })), skipped: plan.skipped },
[
- `${t.handles.map((h) => `@${h}`).join(", ")} read${t.handles.length === 1 ? "s" : ""} in ${voice} ${scope === "cast" ? "everywhere (the cast)" : `in ${project.id} (its voice map)`}${removed.length ? `; ${project.id}'s own override removed (${removed.join(", ")})` : ""}`,
+ `${t.handles.map((h) => `@${h}`).join(", ")} read${t.handles.length === 1 ? "s" : ""} in ${voice} ${scope === "cast" ? "everywhere (the cast)" : `in ${project.id}`}${removed.length ? `; ${project.id}'s own override removed (${removed.join(", ")})` : ""}`,
+ ...(scope === "cast" ? ownFor.filter((c) => c.voice).map((c) => ` here, this video's own character ${c.id} still answers first (${c.voice}): umtool cast project ${project.id} rm ${c.id} follows the cast`) : []),
plan.items.length ? ` ${plan.items.length} item(s) read them in another voice -- umtool cast reread ${project.id} ${who}:` : " no picked read says them in another voice",
...plan.items.map((x) => ` ${x.id} ${x.reads.map((r) => `${r.role} ${r.reads} -> ${r.want}`).join(", ")}`),
].join("\n"),
@@ -274,7 +594,7 @@ export async function castCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
if (!ref || !who) throw new CastError("cast reread takes the project and the character (or @handle)");
const project = await projectOf(ref, reportsRoot);
const v = await projectView(project, { reportsRoot });
- const t = handlesOf(who, v.castRead, v.view);
+ const t = handlesOf(who, v.castRead, v.view, v.ownRead);
const { rereadPlan } = await import("./castProject.mjs");
const plan = rereadPlan(project.id, v.manifest, v.view.characters.flatMap((c) => c.drift), t.handles);
if (p.has("--dry-run") || !plan.items.length) {
diff --git a/umtool/lib/report/castProject.mjs b/umtool/lib/report/castProject.mjs
@@ -1,39 +1,52 @@
// A PROJECT's CAST (the Voices panel; `umtool cast project <p>`): every character the project's reads use -- the
// post items' authors, the authors of the posts they answer, quote and link, and the narrator -- with the voice each
-// reads in NOW and where it comes from (the project's map, the cast, the narrator's, the default), how many items it
+// reads in NOW and where it comes from (the item's own character, the project's own characters and its map, the
+// cast, the narrator's, the default: post-say.mjs voiceSourceOf, the chain every read asks), how many items it
// reads, what its picked reads are actually in (stale ones: DRIFT), its real-voice reference (speakers.json) and its
// lines to audition; and THE RE-READS a voice change asks for, as the commands that make them.
//
// Plain ESM.
import { postNarrationKnobs } from "umtool-report-to-video/post-narration";
import { handleKey, resolvePieceVoice, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say";
-import { castDrift, castVoiceMap, characterOf, charactersOf, convertTargetOf, narratorOf, speakerFor, takeReads, voiceDrift, ENGINE_WEIGHT } from "umtool-report-to-video/cast";
+import {
+ castDrift, castPresetMap, characterForRead, characterOf, charactersOf, convertTargetOf, itemCharacterOf, itemPresetOf, narratorOf, projectCharactersOf, projectPresetMap, recordedPresetOf,
+ shownNameOf, speakerFor, takeReads, voiceDrift, ENGINE_WEIGHT,
+} from "umtool-report-to-video/cast";
import { characterLines } from "./castAudition.mjs";
const str = (v) => (typeof v === "string" ? v : "");
/**
* The voice a piece of a picked read would be said in NOW, as the read that made it would ask (its own --voice-for
- * and --voice kept: an override made on purpose): `(e, role, handle, take, read) => { engine, voice, from }`. A read
- * converted from a recording is compared with its character's convert target (the cast's), else not at all.
+ * and --voice kept: an override made on purpose): `(e, role, handle, take, read) => { engine, voice, from, speed?,
+ * character? }`. A read converted from a recording is compared with its character's convert target (the chain's:
+ * cast.mjs characterForRead), else not at all. `project` is the project's own characters (characters.json's document).
*/
-export function resolverFor({ map = {}, cast = null, render = {} }) {
- const castMap = castVoiceMap(cast);
+export function resolverFor({ map = {}, cast = null, project = null, render = {} }) {
+ const castMap = castPresetMap(cast);
+ const layer = projectPresetMap(project, map);
return (e, role, handle, take, read = null) => {
if (read?.kind === "converted") {
- const c = characterOf(cast, handle);
- const ref = c ? voiceRefOf(convertTargetOf(c).voice) : null;
- return ref ? { ...ref, from: "cast" } : null;
+ const who = characterForRead(e, { project, cast });
+ const ref = who?.character && who.layer !== "narrator" ? voiceRefOf(convertTargetOf(who.character).voice) : null;
+ return ref ? { ...ref, from: who.layer } : null;
}
const k = postNarrationKnobs(e, render);
const tr = take?.read?.kind === "thread" ? take.read : null;
return resolvePieceVoice({ handle, role }, {
- map, cast: castMap, overrides: tr?.voiceFor ?? {}, voice: tr?.voice ?? null, self: e.handle ?? null,
+ map: layer, cast: castMap, item: itemPresetOf(e, { project, cast }), overrides: tr?.voiceFor ?? {}, voice: tr?.voice ?? null, self: e.handle ?? null,
narrator: e.narration?.voice ?? k.voice, engine: e.narration?.engine ?? k.engine,
});
};
}
+/** A character as a row carries it: its id, name, presets (and the `voice` / `convert` they answer to), what it is. */
+const rowCharacter = (c, layer) => ({
+ id: c.id, name: c.name, layer, ...(c.voice ? { voice: c.voice } : {}), ...(c.convert ? { convert: c.convert } : {}),
+ ...(c.synthetic ? { synthetic: c.synthetic } : {}), ...(c.recorded ? { recorded: c.recorded } : {}),
+ ...(c.note ? { note: c.note } : {}), ...(c.narrator ? { narrator: true } : {}), ...(c.anonymous ? { anonymous: true, shown: shownNameOf(c) } : {}),
+});
+
/** The post items' authors and context authors: `Map<handle, { handle, name, items: id[], context: id[] }>`. */
export function authorsOf(manifest) {
const out = new Map();
@@ -57,21 +70,28 @@ export function authorsOf(manifest) {
}
/**
- * THE PROJECT's CHARACTERS, pure: `{ narrator, characters: [...], drift, overrides }` -- each character
- * `{ key, character, name, handles, items, context, itemIds, contextIds, voice: {engine, voice, spec, from},
- * contextVoice?, reads: [{ id, role, spec, kind }], drift: [...], speaker, lines, weight }`, the most-read first.
+ * THE PROJECT's CHARACTERS, pure: `{ narrator, characters: [...], drift, overrides, own, itemCharacters }` -- each
+ * character `{ key, character, name, handles, items, context, itemIds, contextIds, voice: {engine, voice, spec, from,
+ * speed?, character?}, contextVoice?, recorded?, reads: [{ id, role, spec, kind }], drift: [...], speaker, lines,
+ * weight }`, the most-read first. A handle's character is the project's own (characters.json) before the cast's;
+ * `character.layer` says which. `own` is every character the project holds, in the cut or not; `itemCharacters` the
+ * post items that name their own (`narration.character`), each with the character it names (`found: false`: no such
+ * one -- the read falls to the layers under it).
*/
-export function projectCharacters(manifest, { map = {}, cast = null, speakers = [] } = {}) {
+export function projectCharacters(manifest, { map = {}, cast = null, project = null, speakers = [] } = {}) {
const render = manifest?.render ?? {};
const k = postNarrationKnobs({}, render);
- const resolve = resolverFor({ map, cast, render });
- const castMap = castVoiceMap(cast);
+ const resolve = resolverFor({ map, cast, project, render });
+ const castMap = castPresetMap(cast);
+ const layer = projectPresetMap(project, map);
+ const pchars = projectCharactersOf(project);
const drift = voiceDrift(manifest, resolve);
const groups = new Map();
for (const a of authorsOf(manifest).values()) {
- const c = characterOf(cast, a.handle);
+ const own = pchars.find((c) => (c.handles ?? []).includes(a.handle)) ?? null;
+ const c = own ?? characterOf(cast, a.handle);
const key = c ? c.id : `@${a.handle}`;
- const g = groups.get(key) ?? { key, character: c, name: c?.name ?? a.name ?? a.handle, handles: [], itemIds: [], contextIds: [] };
+ const g = groups.get(key) ?? { key, character: c, layer: c ? (own ? "project" : "cast") : null, name: c ? shownNameOf(c) : a.name ?? a.handle, handles: [], itemIds: [], contextIds: [] };
g.handles.push(a.handle);
for (const id of a.items) if (!g.itemIds.includes(id)) g.itemIds.push(id);
for (const id of a.context) if (!g.contextIds.includes(id)) g.contextIds.push(id);
@@ -82,19 +102,23 @@ export function projectCharacters(manifest, { map = {}, cast = null, speakers =
for (const e of tl) if (e?.type === "post") for (const r of takeReads(e)) reads.push({ id: e.id, ...r });
const rows = [...groups.values()].map((g) => {
const h = g.handles[0];
- const first = tl.find((e) => e?.type === "post" && g.itemIds.includes(e.id)) ?? null;
- const ctxItem = tl.find((e) => e?.type === "post" && g.contextIds.includes(e.id)) ?? null;
+ // The handle's own voice: an item that names its own character answers for itself (itemCharacters), not for the handle.
+ const plain = (e) => !e?.narration?.character;
+ const first = tl.find((e) => e?.type === "post" && g.itemIds.includes(e.id) && plain(e)) ?? null;
+ const ctxItem = tl.find((e) => e?.type === "post" && g.contextIds.includes(e.id) && plain(e)) ?? null;
const own = first ? resolve(first, "post", h, null) : null;
- const ctx = ctxItem ? resolve(ctxItem, "parent:0", h, null) : resolvePieceVoice({ handle: h, role: "parent:0" }, { map, cast: castMap, narrator: k.voice, engine: k.engine });
+ const ctx = ctxItem ? resolve(ctxItem, "parent:0", h, null) : resolvePieceVoice({ handle: h, role: "parent:0" }, { map: layer, cast: castMap, narrator: k.voice, engine: k.engine });
const now = own ?? ctx;
const mine = new Set(g.handles);
const sp = speakerFor(g.character ?? { name: g.name, handles: g.handles, id: h }, speakers);
return {
key: g.key, name: g.name, handles: g.handles,
- character: g.character ? { id: g.character.id, name: g.character.name, voice: g.character.voice, ...(g.character.convert ? { convert: g.character.convert } : {}), ...(g.character.note ? { note: g.character.note } : {}), ...(g.character.narrator ? { narrator: true } : {}) } : null,
+ character: g.character ? rowCharacter(g.character, g.layer) : null,
items: g.itemIds.length, context: g.contextIds.length, itemIds: g.itemIds, contextIds: g.contextIds,
voice: { ...now, spec: voiceSpecOf(now) },
...(own && ctx && voiceSpecOf(own) !== voiceSpecOf(ctx) ? { contextVoice: { ...ctx, spec: voiceSpecOf(ctx) } } : {}),
+ // What a recording of them is made into (the recorded preset, its defaults filled) -- a character's only.
+ ...(g.character ? { recorded: recordedPresetOf(g.character) } : {}),
weight: ENGINE_WEIGHT[now.engine] ?? "fast",
reads: reads.filter((r) => r.handle && mine.has(handleKey(r.handle))).map((r) => ({ id: r.id, role: r.role, spec: voiceSpecOf({ engine: r.engine, voice: r.voice }), kind: r.kind })),
drift: drift.filter((d) => mine.has(d.handle)),
@@ -105,11 +129,18 @@ export function projectCharacters(manifest, { map = {}, cast = null, speakers =
rows.sort((a, b) => b.items + b.context - (a.items + a.context) || a.name.localeCompare(b.name));
const nar = narratorOf(cast);
const recorded = reads.filter((r) => r.kind === "recorded" || r.kind === "converted");
+ const itemCharacters = tl.filter((e) => e?.type === "post" && e.narration?.character).map((e) => {
+ const it = itemCharacterOf(e, { project, cast });
+ const v = resolve(e, "post", e.handle ?? null, null);
+ return { id: e.id, handle: handleKey(e.handle) || null, character: it.id, found: !!it.character, layer: it.layer, ...(it.character ? { name: shownNameOf(it.character) } : {}), voice: { ...v, spec: voiceSpecOf(v) } };
+ });
return {
narrator: { engine: k.engine, voice: k.voice, spec: `${k.engine}:${k.voice}`, from: render?.postNarration?.voice ? "project" : "default", character: nar ? { id: nar.id, name: nar.name, voice: nar.voice } : null, recorded: recorded.map((r) => ({ id: r.id, kind: r.kind, voice: r.voice })) },
characters: rows,
...castDrift(manifest, { cast, map, resolve }),
cast: charactersOf(cast).length,
+ own: pchars.map((c) => rowCharacter(c, "project")).map((c, i) => ({ ...c, handles: pchars[i].handles ?? [] })),
+ itemCharacters,
};
}
@@ -125,6 +156,7 @@ export function threadArgvOf(read, { handles = [], author = null } = {}) {
if (read.seen === true) a.push("--read-seen");
for (const [h, v] of Object.entries(read.voiceFor ?? {})) if (!drop.has(handleKey(h))) a.push("--voice-for", `${h}=${v}`);
if (read.voice && !(author && drop.has(handleKey(author)))) a.push("--voice", String(read.voice));
+ if (typeof read.speed === "number") a.push("--speed", String(read.speed));
return a;
}
diff --git a/umtool/lib/report/castStore.mjs b/umtool/lib/report/castStore.mjs
@@ -2,6 +2,12 @@
//
// <REPORTS_ROOT>/.umtool/cast.json the characters, for every project
// <REPORTS_ROOT>/.umtool/cast.undo.json the undo points: the file as it was before each write (the last 50)
+// <project>/narration/characters.json THE PROJECT's OWN characters (cast.mjs PROJECT_CHARACTERS_FILE): the
+// <project>/narration/characters.undo.json same writer, the same rules, its own undo points
+//
+// A version 1 cast (`voice` / `convert` at a character's top) is READ as version 2 (cast.mjs upgradeCast) and
+// written as version 2 by the first write after -- whose undo point is the version 1 text, so `undo` puts the old
+// file back as it was, and it reads the same.
//
// Every write is serialised in-process, re-reads the file inside the lock, checks the caller's token (the sha1 of
// the file it read: a write over a newer file is refused), refuses a cast cast.mjs refuses (whole), keeps an undo
@@ -15,7 +21,10 @@
import { createHash } from "node:crypto";
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
import path from "node:path";
-import { CAST_FORMAT, CAST_VERSION, emptyCast, validateCast } from "umtool-report-to-video/cast";
+import {
+ CAST_FORMAT, CAST_VERSION, PROJECT_CHARACTERS_FILE, PROJECT_CHARACTERS_FORMAT, PROJECT_CHARACTERS_VERSION, characterView, emptyCast, emptyProjectCharacters, foldWritten, upgradeCharacter,
+ validateCast, validateProjectCharacters,
+} from "umtool-report-to-video/cast";
import { REPORTS_ROOT } from "../paths.mjs";
import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
@@ -52,27 +61,53 @@ export async function castFileFor(dir, reportsRoot = REPORTS_ROOT) {
const sha = (text) => createHash("sha1").update(text).digest("hex").slice(0, 16);
-/**
- * The cast as its file holds it: `{ cast, token, file, exists, error? }` -- `token` the sha1 of the text (null with
- * no file). A file that does not parse or is refused reads as the empty cast with `error`.
- */
-export async function readCastFile(file) {
+/** The two files this store writes: what each is called, how it is refused, read and written. */
+const CAST_KIND = Object.freeze({
+ what: "the cast", validate: validateCast, empty: emptyCast,
+ doc: (characters) => ({ format: CAST_FORMAT, version: CAST_VERSION, characters }),
+});
+const PROJECT_KIND = Object.freeze({
+ what: "the project's characters", validate: validateProjectCharacters, empty: emptyProjectCharacters,
+ doc: (characters) => ({ format: PROJECT_CHARACTERS_FORMAT, version: PROJECT_CHARACTERS_VERSION, characters }),
+});
+
+async function readKind(kind, file) {
let text;
try {
text = await readFile(file, "utf8");
} catch (e) {
- if (e?.code === "ENOENT") return { cast: emptyCast(), token: null, file, exists: false, text: null };
- return { cast: emptyCast(), token: null, file, exists: false, text: null, error: `${file} cannot be read: ${e?.message ?? e}` };
+ if (e?.code === "ENOENT") return { cast: kind.empty(), token: null, file, exists: false, text: null };
+ return { cast: kind.empty(), token: null, file, exists: false, text: null, error: `${file} cannot be read: ${e?.message ?? e}` };
}
let doc;
try {
doc = JSON.parse(text);
} catch (e) {
- return { cast: emptyCast(), token: sha(text), file, exists: true, text, error: `${file} is not JSON: ${e instanceof Error ? e.message : e}` };
+ return { cast: kind.empty(), token: sha(text), file, exists: true, text, error: `${file} is not JSON: ${e instanceof Error ? e.message : e}` };
}
- const errors = validateCast(doc, path.basename(file));
- if (errors.length) return { cast: emptyCast(), token: sha(text), file, exists: true, text, error: `${path.basename(file)} is refused: ${errors.join("; ")}` };
- return { cast: doc, token: sha(text), file, exists: true, text };
+ const errors = kind.validate(doc, path.basename(file));
+ if (errors.length) return { cast: kind.empty(), token: sha(text), file, exists: true, text, error: `${path.basename(file)} is refused: ${errors.join("; ")}` };
+ // As a reader is handed it: each character version 2's shape, with the `voice` / `convert` its presets answer to.
+ return { cast: { ...kind.doc(doc.characters.map(characterView)) }, token: sha(text), file, exists: true, text };
+}
+
+/**
+ * The cast as its file holds it: `{ cast, token, file, exists, error? }` -- `token` the sha1 of the text (null with
+ * no file), `cast` as VERSION 2 whatever the file's, each character a VIEW (cast.mjs characterView). A file that does not parse or is refused
+ * reads as the empty cast with `error`.
+ */
+export const readCastFile = (file) => readKind(CAST_KIND, file);
+
+/** A project's own characters file. */
+export const projectCharactersFile = (dir) => path.join(/* turbopackIgnore: true */ dir, ...PROJECT_CHARACTERS_FILE.split("/"));
+
+/**
+ * A project's OWN characters as its file holds them: `{ doc, token, file, exists, error? }` (readCastFile's shape,
+ * the document under `doc`). No file: none. A file that does not parse or is refused reads as none, with `error`.
+ */
+export async function readProjectCharacters(dir) {
+ const { cast, ...rest } = await readKind(PROJECT_KIND, projectCharactersFile(dir));
+ return { doc: cast, ...rest };
}
/** The cast under a reports root. */
@@ -110,23 +145,19 @@ function withCastLock(fn) {
return run;
}
-/**
- * ONE WRITE of the cast: `mutate(characters)` (a copy; it throws CastError to refuse) returns what the caller
- * wants back. Refused when the file changed since the caller's `token` (409), when it does not parse, or when the
- * result is refused (cast.mjs validateCast). Returns `{ ...result, cast, token, undo: <points left> }`.
- * @param {string} file
- * @param {(chars: any[]) => any} mutate
- * @param {{ token?: string | null, what?: string }} [o]
- */
-export function castWrite(file, mutate, { token = null, what = "an edit" } = {}) {
+function writeKind(kind, file, mutate, { token = null, what = "an edit" } = {}) {
return withCastLock(async () => {
- const read = await readCastFile(file);
+ const read = await readKind(kind, file);
if (read.error && read.exists) throw new CastError(`${read.error} -- fix the file first; nothing written`, 409);
- if (token !== null && token !== undefined && token !== read.token) throw new CastError(`the cast changed since it was read (${token} -> ${read.token}): read it again`, 409);
- const chars = JSON.parse(JSON.stringify(read.cast.characters ?? []));
+ if (token !== null && token !== undefined && token !== read.token) throw new CastError(`${kind.what} changed since it was read (${token} -> ${read.token}): read it again`, 409);
+ // The mutation is handed version 2's characters (no `voice` / `convert` beside the presets), and what is written
+ // is version 2's shape: a `voice` / `convert` it sets the old way is the newer word unless it changed the preset
+ // itself (cast.mjs foldWritten, against the character as it was handed).
+ const chars = JSON.parse(JSON.stringify((read.cast.characters ?? []).map(upgradeCharacter)));
+ const was = new Map(chars.map((c) => [c?.id, JSON.parse(JSON.stringify(c))]));
const result = mutate(chars) ?? {};
- const doc = { format: CAST_FORMAT, version: CAST_VERSION, characters: chars };
- const errors = validateCast(doc);
+ const doc = kind.doc(chars.map((c) => foldWritten(c, was.get(c?.id) ?? null)));
+ const errors = kind.validate(doc, path.basename(file));
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`);
@@ -136,18 +167,49 @@ export function castWrite(file, mutate, { token = null, what = "an edit" } = {})
});
}
-/** Put the cast back as it was before its last write (that write's undo point, taken off the list). */
-export function undoCast(file, { token = null } = {}) {
+function undoKind(kind, file, { token = null } = {}) {
return withCastLock(async () => {
- const read = await readCastFile(file);
- if (token !== null && token !== undefined && token !== read.token) throw new CastError(`the cast changed since it was read: read it again`, 409);
+ const read = await readKind(kind, file);
+ if (token !== null && token !== undefined && token !== read.token) throw new CastError(`${kind.what} changed since it was read: read it again`, 409);
const points = await readCastUndo(file);
const last = points.pop();
- if (!last) throw new CastError("nothing to undo on the cast");
- if (last.text === null) await writeAtomic(file, `${JSON.stringify(emptyCast(), null, 1)}\n`);
+ if (!last) throw new CastError(`nothing to undo on ${kind.what}`);
+ if (last.text === null) await writeAtomic(file, `${JSON.stringify(kind.empty(), null, 1)}\n`);
else await writeAtomic(file, last.text);
await writeAtomic(undoFileOf(file), `${JSON.stringify({ file: path.basename(file), points }, null, 1)}\n`);
- const now = await readCastFile(file);
+ const now = await readKind(kind, file);
return { undone: last.what, at: last.at, left: points.length, cast: now.cast, token: now.token };
});
}
+
+/**
+ * ONE WRITE of the cast: `mutate(characters)` (a copy, as version 2 holds them; it throws CastError to refuse)
+ * returns what the caller wants back. Refused when the file changed since the caller's `token` (409), when it does
+ * not parse, or when the result is refused (cast.mjs validateCast). Written as VERSION 2. Returns `{ ...result,
+ * cast, token, undo: <points left> }`.
+ * @param {string} file
+ * @param {(chars: any[]) => any} mutate
+ * @param {{ token?: string | null, what?: string }} [o]
+ */
+export const castWrite = (file, mutate, o) => writeKind(CAST_KIND, file, mutate, o);
+
+/** Put the cast back as it was before its last write (that write's undo point, taken off the list). */
+export const undoCast = (file, o) => undoKind(CAST_KIND, file, o);
+
+/**
+ * ONE WRITE of a project's own characters (`<dir>/narration/characters.json`): castWrite's rules -- a token, an undo
+ * point, atomic, refused whole (cast.mjs validateProjectCharacters). Returns `{ ...result, doc, token, undo }`.
+ * @param {string} dir the project's folder
+ * @param {(chars: any[]) => any} mutate
+ * @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);
+ return { ...rest, doc: cast };
+}
+
+/** A project's own characters as they were before their last write. */
+export async function undoProjectCharacters(dir, o) {
+ const { cast, ...rest } = await undoKind(PROJECT_KIND, projectCharactersFile(dir), o);
+ return { ...rest, doc: cast };
+}
diff --git a/umtool/lib/report/chain-run.mjs b/umtool/lib/report/chain-run.mjs
@@ -3,6 +3,7 @@
//
// node --import tsx umtool/lib/report/chain-run.mjs step <article> <n> <step>
// [--projects-root <dir>] [--site-origin <url>] [--final] [--model <m>]
+// [--mode draft-all] [--allow-whole-recording]
//
// — under tsx, because the article registry, the iterations store and the
// reports CLIs it calls are common's TypeScript. The Next app never imports
@@ -34,6 +35,7 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { articleDir, articleFile } from "yt-dlp-transcript-common/lib/report/registry";
import {
lineage,
+ lineageSource,
makeCurrent,
projectOf,
readIteration,
@@ -49,16 +51,22 @@ import { main as prepareMain } from "yt-dlp-transcript-common/bin/reports-prepar
import { toManifestMain } from "yt-dlp-transcript-common/bin/reports-convert";
import { attachVideoMain } from "yt-dlp-transcript-common/bin/reports-attach-video";
import { checkMain } from "yt-dlp-transcript-common/bin/reports-check";
-import { ALL_CHAIN_STEP_NAMES, CHAIN_WINDOW_PAD, REPO_ROOT, chainStepDef, configuredProjectsRoot, chainTask, chainWindows, originFromSweep } from "./chain.mjs";
+import { ALL_CHAIN_STEP_NAMES, CHAIN_WINDOW_PAD, REPO_ROOT, chainStepDef, configuredProjectsRoot, chainTask, chainWindows, cutWindows, originFromSweep } from "./chain.mjs";
import { deckChrome, deckRefusedDetail, deckStepDetail, draftFileOf, draftOutcome, draftPrecheck } from "./chain-draft.mjs";
import { ChromeRefused, addDeckChrome } from "./manifest.mjs";
import { socialTexts } from "umtool-report-to-video/social";
import { PIPELINE_DIR } from "./driver.mjs";
+import { resolveLocalSource } from "umtool-report-to-video/sources";
import { dedupeMedia, seedFromParent } from "./iterations.mjs";
import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
+import { WHOLE_RECORDING_REFUSED, connectedArchives, disconnectedArchiveRefusal, originOfHandle } from "yt-dlp-transcript-common/lib/remoteArchives";
+import { detectPlatform } from "yt-dlp-transcript-common/lib/detectPlatform.mjs";
+import { archiveRecordPageHref } from "yt-dlp-transcript-common/controller/remoteOnlyChannel";
+import { cachedArchiveGetJson } from "yt-dlp-transcript-common/lib/archiveCache-server";
const OPS = path.join(REPO_ROOT, "scripts", "archilyzer-ops.mjs");
const SCREENSHOT_MISSING = /no captured screenshot/;
+const CLIP_MISSING = /fetch the window or persist the video in the editor/;
/** A step that ends early with a reason: failed, with that line. */
class StepFailed extends Error {}
@@ -98,7 +106,58 @@ async function ownProblems(paths, article) {
const index = await readStoreMediaIndex(articleReportStore(paths));
const own = (index?.problems ?? []).filter((p) => isArticleProblem(p, article));
const shots = own.filter((p) => p.kind === "missing-media" && SCREENSHOT_MISSING.test(p.message) && p.moment);
- return { own, shots, rest: own.filter((p) => !shots.includes(p)) };
+ // An evidence clip whose window is not on disk (publish/reportMedia.ts).
+ const clips = own.filter((p) => p.kind === "missing-media" && CLIP_MISSING.test(p.message) && !shots.includes(p));
+ return { own, shots, clips, rest: own.filter((p) => !shots.includes(p) && !clips.includes(p)) };
+}
+
+/**
+ * Ask the editor for a step's windows (demo epic D1 adds the archive): when
+ * the lineage read a connected archive (`scope.source`), the body names it and
+ * each item carries its page URL from the archive's record, so the editor
+ * registers a channel it does not hold as remote-only. Then a DRY RUN first:
+ * a remote-only channel's whole recording (Rumble) refused with its size fails
+ * the step with every such refusal — nothing fetched — until the chain runs
+ * again with `allowWholeRecording` (umtool's one press). Then the run, waited on.
+ */
+async function fetchWindowsStep(ctx, body, what) {
+ const origin = originOfHandle(await lineageSource(ctx.article, ctx.n, ctx.paths).catch(() => null));
+ if (origin) {
+ // An archive removed from settings is not read any more (the editor
+ // refuses its channels' windows too): nothing is asked of it, and the step
+ // says to connect it again. The connected ones are settings.json's and
+ // TRANSCRIPT_SITE_URL's, as the source picker lists them (lib/research/sources.ts).
+ const settingsFile = process.env.SETTINGS_FILE?.trim() || path.join(REPO_ROOT, "settings.json");
+ const stored = await readFile(settingsFile, "utf8").then((t) => JSON.parse(t)?.remoteArchives, () => null);
+ const gone = disconnectedArchiveRefusal(origin, connectedArchives(stored));
+ if (gone) throw new StepFailed(`this article was swept over a published archive, and ${gone}`);
+ const getJson = cachedArchiveGetJson();
+ body.archive = origin;
+ for (const item of body.items) {
+ if (item.webpageUrl) continue;
+ // Only a video platform's page (the editor refuses any other, too), and
+ // as the URL the check parsed — never the record's own string.
+ const href = await archiveRecordPageHref(origin, item.slug, item.id, detectPlatform, { getJson });
+ if (href) item.webpageUrl = href;
+ }
+ if (ctx.allowWholeRecording) body.allowWholeRecording = true;
+ const dry = await editorCall(await editorEnv(), "POST", "/api/ops/fetch-windows", { ...body, dryRun: true });
+ if (!dry.ok) throw new StepFailed(`the editor refused the windows: ${dry.error}`);
+ const whole = (dry.body?.unresolved ?? []).filter((u) => String(u?.error ?? "").startsWith(WHOLE_RECORDING_REFUSED));
+ if (whole.length > 0) {
+ const sizes = whole.map((u) => /: (\S+ is [^.]+|\S+'s length is not known to its archive)\./.exec(String(u.error))?.[1] ?? `${u.item?.slug}/${u.item?.id}`);
+ throw new StepFailed(
+ `${WHOLE_RECORDING_REFUSED} ${whole.length} window(s) need their whole recording downloaded — ${[...new Set(sizes)].join("; ")}. ` +
+ "Allow the whole recordings to fetch them (the chain again, allowWholeRecording).",
+ );
+ }
+ }
+ await mkdir(ctx.project, { recursive: true });
+ const file = path.join(ctx.project, "windows.json");
+ await writeJson(file, body);
+ const code = await ops("fetch-windows", ["--file", file]);
+ if (code !== 0) throw new StepFailed(`the editor's fetch-windows ended ${code} (a re-run fetches only what is missing)`);
+ return `${body.items.length} window(s) ${what} on disk${origin ? ` (archive ${origin})` : ""}`;
}
const describe = (problems) =>
@@ -121,24 +180,51 @@ const STEPS = {
const report = JSON.parse(await readFile(articleFile(ctx.paths, ctx.article), "utf8"));
const body = chainWindows(report, { pad: CHAIN_WINDOW_PAD, requestedBy: `umtool chain ${ctx.article} i${ctx.n}` });
if (body.items.length === 0) return "no clip windows cited";
- await mkdir(ctx.project, { recursive: true });
- const file = path.join(ctx.project, "windows.json");
- await writeJson(file, body);
- const code = await ops("fetch-windows", ["--file", file]);
- if (code !== 0) throw new StepFailed(`the editor's fetch-windows ended ${code} (a re-run fetches only what is missing)`);
- return `${body.items.length} window(s) on disk`;
+ return fetchWindowsStep(ctx, body, "cited");
+ },
+
+ // Draft everything's (demo epic D1): the windows of the clips the cut kept.
+ async ["cut-windows"](ctx) {
+ const file = path.join(ctx.project, "video.manifest.json");
+ const manifest = await readJsonOr(file);
+ if (!manifest) throw new StepFailed(`no video manifest at ${file}: run the chain's manifest step first`);
+ const body = cutWindows(manifest, { pad: CHAIN_WINDOW_PAD, requestedBy: `umtool chain ${ctx.article} i${ctx.n} cut` });
+ if (body.items.length === 0) return "the cut has no clip";
+ // What the build would find on disk is not asked for: the project's own
+ // out/clips-raw, the corpus's windows, a saved recording (sources.mjs, the
+ // build's lookup order).
+ const rawDir = path.join(ctx.project, "out", "clips-raw");
+ const missing = [];
+ for (const item of body.items) {
+ const hit = await resolveLocalSource({ video: item.id, slug: item.slug, from: item.from, to: item.to }, { rawDir, channelsDir: ctx.paths.channelsDir }).catch(() => null);
+ if (!hit) missing.push(item);
+ }
+ if (missing.length === 0) return `the cut's ${body.items.length} window(s) are on disk already`;
+ const held = body.items.length - missing.length;
+ const said = await fetchWindowsStep(ctx, { ...body, items: missing }, "of the cut's");
+ return held ? `${said}; ${held} on disk already` : said;
},
async prepare(ctx) {
const code = await prepareMain({ article: ctx.article, only: true });
if (code === 0) return "the evidence media is complete; the article is exported";
- const { own, shots, rest } = await ownProblems(ctx.paths, ctx.article);
- if (own.length > 0 && rest.length === 0) return `${shots.length} post screenshot(s) to capture (the next step)`;
- throw new StepFailed(rest.length ? describe(rest) : `reports prepare ended ${code}`);
+ const { own, shots, clips, rest } = await ownProblems(ctx.paths, ctx.article);
+ // Draft everything fetches the CUT's windows later (cut-windows): an
+ // evidence clip not fetched yet does not stop it.
+ const later = ctx.mode === "draft-all" ? clips : [];
+ const blocking = ctx.mode === "draft-all" ? rest : [...clips, ...rest];
+ if (own.length > 0 && blocking.length === 0) {
+ return [
+ shots.length ? `${shots.length} post screenshot(s) to capture (the next step)` : "",
+ later.length ? `${later.length} evidence clip(s) not fetched: the cut's are fetched after the cut is drafted; the rest by Fetch missing evidence` : "",
+ ].filter(Boolean).join("; ");
+ }
+ throw new StepFailed(blocking.length ? describe(blocking) : `reports prepare ended ${code}`);
},
async posts(ctx) {
- const { shots, rest } = await ownProblems(ctx.paths, ctx.article);
+ const { shots, clips, rest: others } = await ownProblems(ctx.paths, ctx.article);
+ const rest = ctx.mode === "draft-all" ? others : [...clips, ...others];
if (rest.length > 0) throw new StepFailed(`prepare has this article's other problems first: ${describe(rest)}`);
if (shots.length === 0) return "no post screenshot to capture";
const bySlug = new Map();
@@ -155,7 +241,9 @@ const STEPS = {
const code = await prepareMain({ article: ctx.article, only: true });
if (code !== 0) {
const again = await ownProblems(ctx.paths, ctx.article);
- throw new StepFailed(again.own.length ? describe(again.own) : `reports prepare ended ${code}`);
+ const left = ctx.mode === "draft-all" ? [...again.shots, ...again.rest] : again.own;
+ if (left.length === 0) return `${shots.length} post screenshot(s) captured; ${again.clips.length} evidence clip(s) not fetched yet`;
+ throw new StepFailed(left.length ? describe(left) : `reports prepare ended ${code}`);
}
return `${shots.length} post screenshot(s) captured; the evidence media is complete`;
},
@@ -437,13 +525,17 @@ async function writeJson(file, value) {
// The archive the sweep's moment links name — the QR codes' origin: the
// newest sweep.md in the iteration's lineage that names one.
+// When none does (a hand-made iteration, a sweep.md without moment links),
+// the published archive the lineage read (demo epic D1: `scope.source`,
+// remote:<origin>) — the editor cited it there.
async function sweepOrigin(ctx) {
const line = await lineage(ctx.article, ctx.n, ctx.paths).catch(() => [ctx.n]);
for (const n of [...line].reverse()) {
const origin = originFromSweep(await readIterationFile(ctx.article, n, "sweep.md", ctx.paths));
if (origin) return origin;
}
- return undefined;
+ const source = await lineageSource(ctx.article, ctx.n, ctx.paths).catch(() => null);
+ return originOfHandle(source) ?? undefined;
}
/**
@@ -481,6 +573,8 @@ export async function runChainStep(article, n, name, opts = {}) {
siteOrigin: opts.siteOrigin,
final: opts.final === true,
model: opts.model,
+ mode: opts.mode === "draft-all" ? "draft-all" : "video",
+ allowWholeRecording: opts.allowWholeRecording === true,
cancels: [],
onCancel(fn) {
this.cancels.push(fn);
@@ -552,6 +646,8 @@ function parseArgs(argv) {
siteOrigin: flag("--site-origin"),
final: rest.includes("--final"),
model: flag("--model"),
+ mode: flag("--mode"),
+ allowWholeRecording: rest.includes("--allow-whole-recording"),
};
}
@@ -559,7 +655,7 @@ const isMain = !!process.argv[1] && path.resolve(process.argv[1]) === fileURLToP
if (isMain) {
const a = parseArgs(process.argv.slice(2));
if (a.cmd !== "step" || !a.article || !Number.isInteger(a.n) || !a.name) {
- console.error("usage: node --import tsx chain-run.mjs step <article> <n> <step> [--projects-root <dir>] [--site-origin <url>] [--final] [--model <m>]");
+ console.error("usage: node --import tsx chain-run.mjs step <article> <n> <step> [--projects-root <dir>] [--site-origin <url>] [--final] [--model <m>] [--mode draft-all] [--allow-whole-recording]");
process.exit(2);
}
runChainStep(a.article, a.n, a.name, a).then(
diff --git a/umtool/lib/report/chain-run.test.mjs b/umtool/lib/report/chain-run.test.mjs
@@ -156,3 +156,57 @@ test("refusals: a queued iteration, an unknown step, no such iteration", () => {
assert.equal(none.code, 2);
assert.match(none.out, /has no iteration i9/);
});
+
+test("manifest: with no sweep.md naming an origin, the archive the sweep read (scope.source) is the QR origin (demo epic D1)", () => {
+ const dir = path.join(ARTICLES, "synth-remote", "iterations", "1");
+ put(path.join(dir, "iteration.json"), iteration(1, { article: "synth-remote", scope: { channels: ["synth-kitchen"], source: "remote:https://stub.test" } }));
+ put(path.join(dir, "report.json"), { ...basic, id: "synth-remote" });
+ const run = (name) =>
+ spawnSync(process.execPath, ["--import", "tsx", CHAIN_RUN, "step", "synth-remote", "1", name, "--projects-root", PROJECTS], {
+ cwd: REPO_ROOT,
+ env: ENV,
+ encoding: "utf8",
+ timeout: 120_000,
+ });
+ for (const name of ["current", "manifest"]) {
+ const r = run(name);
+ assert.equal(r.status, 0, `${name}: ${r.stdout}\n${r.stderr}`);
+ }
+ const m = json(path.join(PROJECTS, "synth-remote", "i1", "video.manifest.json"));
+ assert.equal(m.provenance.siteOrigin, "https://stub.test");
+});
+
+test("windows: an article swept over an archive that is no longer connected asks nothing of it, and says to connect it again (demo epic D1 re-check)", () => {
+ // synth-remote's lineage read remote:https://stub.test (the test above); settings.json names no archive.
+ const env = { ...ENV };
+ delete env.TRANSCRIPT_SITE_URL;
+ const r = spawnSync(process.execPath, ["--import", "tsx", CHAIN_RUN, "step", "synth-remote", "1", "windows", "--projects-root", PROJECTS], {
+ cwd: REPO_ROOT,
+ env,
+ encoding: "utf8",
+ timeout: 120_000,
+ });
+ assert.equal(r.status, 1, `${r.stdout}\n${r.stderr}`);
+ const s = Object.fromEntries(json(path.join(ARTICLES, "synth-remote", "iterations", "1", "iteration.json")).steps.map((x) => [x.task, x]))["chain:windows"];
+ assert.equal(s.status, "failed");
+ assert.match(s.detail, /swept over a published archive, and its archive https:\/\/stub\.test is no longer connected — connect it again/);
+ // Refused before the plan is written or the editor asked.
+ assert.equal(existsSync(path.join(PROJECTS, "synth-remote", "i1", "windows.json")), false);
+});
+
+test("cut-windows (Draft everything, demo epic D1): the cut's windows the project already holds are not asked of the editor", () => {
+ // i2's project: its manifest (from the manifest test) and the cut's window in out/clips-raw.
+ const project = path.join(PROJECTS, "synth-basic", "i2");
+ const m = json(path.join(project, "video.manifest.json"));
+ const clips = (m.timeline ?? []).filter((e) => e.type === "clip");
+ assert.ok(clips.length > 0);
+ for (const c of clips) {
+ const from = Math.max(0, Math.floor((c.start - 3) * 100) / 100);
+ const to = Math.ceil((c.end + 3) * 100) / 100;
+ put(path.join(project, "out", "clips-raw", `${c.video}_${from.toFixed(2)}-${to.toFixed(2)}.mp4`), Buffer.alloc(64, 1));
+ }
+ // The editor is a closed port: had the step asked it, it would have failed.
+ const r = step(2, "cut-windows", "--mode", "draft-all");
+ assert.equal(r.code, 0, r.out);
+ assert.match(recorded(2)["chain:cut-windows"].detail, /the cut's \d+ window\(s\) are on disk already/);
+});
diff --git a/umtool/lib/report/chain.mjs b/umtool/lib/report/chain.mjs
@@ -5,7 +5,8 @@
// current make the iteration current (the article's report.json)
// windows the editor fetches every cited clip window, padded to the
// video build's fetchPad, so one fetch serves both the article's
-// evidence clips and the cut
+// evidence clips and the cut (in "make the video" the cut IS every
+// cited clip: to-manifest makes one of each)
// prepare `reports prepare --article <id> --only`
// posts the editor captures THIS article's missing post screenshots,
// then prepare again
@@ -24,11 +25,28 @@
// steps in it, each OPTIONAL — `draft-<task>` runs one `report-draft` job on
// the iteration through the editor and waits for it:
//
-// current → windows → prepare → posts → manifest → draft-cut →
+// current → prepare → posts → manifest → draft-cut → cut-windows →
// draft-onscreen → draft-teaser → draft-flips → draft-threads →
// draft-narrate → voices → video (fast, never --final) → podcast →
// draft-youtube → draft-social
//
+// WINDOWS FOR THE CUT, NOT FOR EVERY CITATION (demo epic D1): Draft
+// everything has no early `windows`; `cut-windows` fetches the windows of the
+// clips the drafted cut kept (cutWindows, from the manifest), so a 37-citation
+// report whose cut keeps 9 asks the editor for 9. Its prepare and posts steps
+// go on past evidence clips not fetched yet (the article's remaining evidence
+// is the site's Fetch missing evidence, never the chain's).
+//
+// STOP BEFORE RENDER (demo epic D1, `stopBeforeRender`, off by default): the
+// chain ends before `voices` — nothing voiced, built or attached — so the cut
+// can be walked first; the next run resumes at `voices`.
+//
+// A connected archive's sweep (its iteration's `scope.source`, demo epic D1):
+// the windows steps name the archive and each clip's page URL from its record,
+// so the editor registers the channel remote-only; a remote-only channel's
+// whole recording (Rumble) is refused with its size until the chain is run
+// again with `allowWholeRecording` (umtool's one press).
+//
// The drafts go after `manifest` (a media task drafts the project's manifest)
// and before `voices` (narration is voiced) and the build (the drafts are in
// it); YouTube's after the build, which then re-muxes its chapters so
@@ -64,6 +82,7 @@ import { existsSync, readFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { UMTOOL_DIR } from "./driver.mjs";
+import { defaultProjectsRoot } from "yt-dlp-transcript-common/lib/projectsRoot.mjs";
// `draft`: the report-draft task an optional generation step runs.
// `modes`: the chains a step is in ("video" — make the video; "draft-all").
@@ -74,11 +93,12 @@ const DRAFT_TIMEOUT = 3 * 60 * 60_000;
export const CHAIN_STEPS = [
{ name: "current", label: "make the iteration current", timeoutMs: 2 * 60_000, modes: BOTH },
- { name: "windows", label: "fetch the cited clip windows (editor)", timeoutMs: 6 * 60 * 60_000, modes: BOTH },
+ { name: "windows", label: "fetch the cited clip windows (editor)", timeoutMs: 6 * 60 * 60_000, modes: VIDEO_ONLY },
{ name: "prepare", label: "prepare the article's evidence media", timeoutMs: 60 * 60_000, modes: BOTH },
{ name: "posts", label: "capture the article's post screenshots (editor)", timeoutMs: 3 * 60 * 60_000, modes: BOTH },
{ name: "manifest", label: "make the video manifest, seeded from the parent", timeoutMs: 5 * 60_000, modes: BOTH },
{ name: "draft-cut", label: "draft the cut: which clips, in what order", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "cut" },
+ { name: "cut-windows", label: "fetch the cut's clip windows (editor)", timeoutMs: 6 * 60 * 60_000, modes: DRAFT_ONLY },
{ name: "draft-onscreen", label: "draft the on-screen titles", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "onscreen" },
{ name: "draft-teaser", label: "draft the teaser", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "teaser" },
{ name: "deck", label: "add the on-screen deck when the cut has none", timeoutMs: 5 * 60_000, modes: DRAFT_ONLY, optional: true, option: "deck" },
@@ -97,19 +117,26 @@ export const CHAIN_STEPS = [
/** The chains: "video" (make the video, the default) and "draft-all" (Draft everything). */
export const CHAIN_MODES = ["video", "draft-all"];
-/** The chains' options: `deck` (Draft everything's deck step, release 29 G1). Each is off by default. */
-export const CHAIN_OPTIONS = ["deck"];
+/** The chains' options: `deck` (Draft everything's deck step, release 29 G1), `stopBeforeRender` (demo epic D1). Each is off by default. */
+export const CHAIN_OPTIONS = ["deck", "stopBeforeRender"];
+
+/** The step a `stopBeforeRender` chain ends before: nothing is voiced or built. */
+export const RENDER_STEP = "voices";
/**
* A chain's steps, in order. A step with an `option` is in it only when that
- * option is on (`{ deck: true }`); with none on, the chain is as it always was.
+ * option is on (`{ deck: true }`); `stopBeforeRender` ends it before
+ * RENDER_STEP; with none on, the chain is as it always was.
*
* @param {string} [mode]
- * @param {{ deck?: boolean }} [options]
+ * @param {{ deck?: boolean, stopBeforeRender?: boolean }} [options]
*/
export function chainStepsOf(mode = "video", options = {}) {
if (!CHAIN_MODES.includes(mode)) throw new Error(`no chain "${mode}" (${CHAIN_MODES.join(", ")})`);
- return CHAIN_STEPS.filter((s) => s.modes.includes(mode) && (!s.option || options?.[s.option] === true));
+ const steps = CHAIN_STEPS.filter((s) => s.modes.includes(mode) && (!s.option || options?.[s.option] === true));
+ if (options?.stopBeforeRender !== true) return steps;
+ const at = steps.findIndex((s) => s.name === RENDER_STEP);
+ return at < 0 ? steps : steps.slice(0, at);
}
/** Every step's name, either chain's (what the executor runs). */
@@ -131,8 +158,10 @@ export const chainTask = (name) => `chain:${name}`;
// STARTER_RENDER): the windows are fetched this wide so the cut finds them.
export const CHAIN_WINDOW_PAD = 3;
-// Off the corpus disk (D1): `settings.generation.projectsRoot`, blank = this.
-export const DEFAULT_PROJECTS_ROOT = path.join(/* turbopackIgnore: true */ os.homedir(), "reports", "articles");
+// Off the corpus disk (D1): `settings.generation.projectsRoot`, blank = this —
+// `<REPORTS_DIR>/articles` when REPORTS_DIR is set (a container's reports
+// volume), else ~/reports/articles (common/lib/projectsRoot.mjs, the one rule).
+export const DEFAULT_PROJECTS_ROOT = defaultProjectsRoot();
// From driver.mjs's package root, which is found from the module (or, under
// the Next server, the cwd) — never this module's URL alone.
@@ -171,8 +200,8 @@ export function chainProject(projectsRoot, article, n) {
* has not recorded finished (`done`: the step names recorded finished,
* doneSteps), else nothing (the whole chain is done: null).
*/
-export function chainStart({ from = null, done = [], mode = "video", deck = false } = {}) {
- const names = chainStepsOf(mode, { deck }).map((s) => s.name);
+export function chainStart({ from = null, done = [], mode = "video", deck = false, stopBeforeRender = false } = {}) {
+ const names = chainStepsOf(mode, { deck, stopBeforeRender }).map((s) => s.name);
if (from !== null && from !== undefined) {
if (!names.includes(from)) throw new Error(`--from must be one of ${names.join(", ")}`);
return from;
@@ -217,7 +246,7 @@ export function readIterationRecord(articlesDir, article, n) {
* `final` says, and `model` rides on the draft steps (else each task's route);
* `deck` adds its deck step (G1).
*
- * @param {{ article: string, n: number, projectsRoot?: string, start?: string | null, siteOrigin?: string, final?: boolean, node?: string, mode?: string, model?: string, deck?: boolean }} o
+ * @param {{ article: string, n: number, projectsRoot?: string, start?: string | null, siteOrigin?: string, final?: boolean, node?: string, mode?: string, model?: string, deck?: boolean, stopBeforeRender?: boolean, allowWholeRecording?: boolean }} o
* @returns {import("../trim").Step[]}
*/
export function chainSteps(o) {
@@ -225,7 +254,7 @@ export function chainSteps(o) {
chainProject(projectsRoot, o.article, o.n);
const mode = o.mode ?? "video";
if (o.deck === true && mode !== "draft-all") throw new Error("the deck is Draft everything's option (draft-all)");
- const defs = chainStepsOf(mode, { deck: o.deck === true });
+ const defs = chainStepsOf(mode, { deck: o.deck === true, stopBeforeRender: o.stopBeforeRender === true });
const start = o.start === undefined ? defs[0].name : o.start;
if (start === null) return [];
const at = defs.findIndex((s) => s.name === start);
@@ -238,6 +267,8 @@ export function chainSteps(o) {
projectsRoot,
...(o.siteOrigin ? ["--site-origin", o.siteOrigin] : []),
...(o.final && mode === "video" ? ["--final"] : []),
+ ...(mode !== "video" ? ["--mode", mode] : []),
+ ...(o.allowWholeRecording === true ? ["--allow-whole-recording"] : []),
];
return defs.slice(at).map((s, i) => ({
label: `${at + i + 1}/${defs.length} ${s.label}`,
@@ -256,7 +287,7 @@ export function chainSteps(o) {
* iteration not done, or an unknown `from`. `steps` is empty when every step
* is done.
*
- * @param {{ articlesDir: string, article: string, n: number, from?: string | null, projectsRoot?: string, siteOrigin?: string, final?: boolean, mode?: string, model?: string, deck?: boolean }} o
+ * @param {{ articlesDir: string, article: string, n: number, from?: string | null, projectsRoot?: string, siteOrigin?: string, final?: boolean, mode?: string, model?: string, deck?: boolean, stopBeforeRender?: boolean, allowWholeRecording?: boolean }} o
*/
export function planChain(o) {
const record = readIterationRecord(o.articlesDir, o.article, o.n);
@@ -265,19 +296,22 @@ export function planChain(o) {
const mode = o.mode ?? "video";
const deck = o.deck === true;
if (deck && mode !== "draft-all") throw new Error("the deck is Draft everything's option (draft-all)");
- const start = chainStart({ from: o.from ?? null, done: doneSteps(record), mode, deck });
+ const stopBeforeRender = o.stopBeforeRender === true;
+ const start = chainStart({ from: o.from ?? null, done: doneSteps(record), mode, deck, stopBeforeRender });
const steps = chainSteps({
article: o.article,
n: o.n,
start,
mode,
...(deck ? { deck } : {}),
+ ...(stopBeforeRender ? { stopBeforeRender } : {}),
+ ...(o.allowWholeRecording === true ? { allowWholeRecording: true } : {}),
...(o.model ? { model: o.model } : {}),
...(o.projectsRoot ? { projectsRoot: o.projectsRoot } : {}),
...(o.siteOrigin ? { siteOrigin: o.siteOrigin } : {}),
final: o.final === true,
});
- return { record, start, steps, mode, deck };
+ return { record, start, steps, mode, deck, stopBeforeRender };
}
const floor2 = (x) => Math.floor(x * 100 + 1e-6) / 100;
@@ -318,6 +352,39 @@ export function chainWindows(report, { pad = CHAIN_WINDOW_PAD, requestedBy = "um
return { items, requestedBy };
}
+/**
+ * The windows of the clips a CUT keeps (demo epic D1): its manifest's clip
+ * entries, each its span widened by `pad` and rounded outward to the
+ * hundredth, one per distinct moment — the same body chainWindows makes from
+ * a report, for the cut a draft (or a person) narrowed.
+ */
+export function cutWindows(manifest, { pad = CHAIN_WINDOW_PAD, requestedBy = "umtool chain" } = {}) {
+ const items = [];
+ const byMoment = new Map();
+ const fallbackChannel = manifest?.provenance?.channelSlug;
+ for (const e of manifest?.timeline ?? []) {
+ if (e?.type !== "clip") continue;
+ const slug = e.channel ?? fallbackChannel;
+ if (!slug || !e.video || typeof e.start !== "number" || typeof e.end !== "number") continue;
+ const from = floor2(Math.max(0, e.start - pad));
+ const to = ceil2(e.end + pad);
+ const key = `${slug}/${e.video}`;
+ if ((byMoment.get(key) ?? []).some((w) => w.from <= from && w.to >= to)) continue;
+ const item = {
+ slug,
+ id: e.video,
+ from,
+ to,
+ clipId: `${manifest.slug ?? "cut"}#${e.id}`,
+ reason: `cut ${manifest.slug ?? ""} ${e.id}`.trim(),
+ pad,
+ };
+ items.push(item);
+ byMoment.set(key, [...(byMoment.get(key) ?? []), item]);
+ }
+ return { items, requestedBy };
+}
+
/** The archive origin a sweep's moment links name (`https://host/?v=…`), or null. */
export function originFromSweep(text) {
const m = /(https?:\/\/[^/\s)"']+)\/?\?v=/.exec(String(text ?? ""));
diff --git a/umtool/lib/report/chain.test.mjs b/umtool/lib/report/chain.test.mjs
@@ -23,6 +23,7 @@ import {
chainWindows,
chainStepsOf,
CHAIN_OPTIONS,
+ cutWindows,
DRAFT_STEP_TASKS,
doneSteps,
originFromSweep,
@@ -55,7 +56,7 @@ test("the steps, in order, each one process of the executor under tsx, from the
});
test("the deck option (release 29 G1): a step before the flips, off by default — without it the chain is as it was", () => {
- assert.deepEqual(CHAIN_OPTIONS, ["deck"]);
+ assert.deepEqual(CHAIN_OPTIONS, ["deck", "stopBeforeRender"]);
const plain = chainStepsOf("draft-all").map((s) => s.name);
assert.ok(!plain.includes("deck"));
const withDeck = chainStepsOf("draft-all", { deck: true }).map((s) => s.name);
@@ -77,7 +78,7 @@ test("the deck option (release 29 G1): a step before the flips, off by default
);
assert.throws(() => chainSteps({ article: "art", n: 2, projectsRoot: "/p", deck: true }), /the deck is Draft everything's option/);
// Resume: a chain that ran to the threads without the deck starts again at the deck with it.
- const ran = ["current", "windows", "prepare", "posts", "manifest", "draft-cut", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads"];
+ const ran = ["current", "prepare", "posts", "manifest", "draft-cut", "cut-windows", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads"];
assert.equal(chainStart({ done: ran, mode: "draft-all", deck: true }), "deck");
assert.equal(chainStart({ done: ran, mode: "draft-all" }), "draft-narrate");
assert.ok(doneSteps({ steps: [{ task: "chain:deck", status: "failed" }] }).includes("deck"), "optional: a failed deck step is passed");
@@ -103,8 +104,8 @@ test("resume: the first step not recorded done; --from names one; all done is no
test("Draft everything: the drafts between the manifest and the fast build, YouTube after it; the default chain unchanged", () => {
const names = chainStepsOf("draft-all").map((s) => s.name);
assert.deepEqual(names, [
- "current", "windows", "prepare", "posts", "manifest",
- "draft-cut", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads", "draft-narrate",
+ "current", "prepare", "posts", "manifest",
+ "draft-cut", "cut-windows", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads", "draft-narrate",
"voices", "video", "podcast", "draft-youtube", "draft-social",
]);
assert.deepEqual(chainStepsOf("video").map((s) => s.name), CHAIN_STEP_NAMES);
@@ -114,14 +115,16 @@ test("Draft everything: the drafts between the manifest and the fast build, YouT
const steps = chainSteps({ article: "art", n: 2, projectsRoot: "/p", node: "node", mode: "draft-all", model: "qwen3:8b", final: true });
assert.equal(steps.length, 16);
- assert.equal(steps[5].label, "6/16 draft the cut: which clips, in what order");
+ assert.equal(steps[4].label, "5/16 draft the cut: which clips, in what order");
+ // demo epic D1: the cut's windows right after the cut is drafted, not every citation's before it.
+ assert.equal(steps[5].label, "6/16 fetch the cut's clip windows (editor)");
// The model rides on the draft steps only; the build is the fast one (--final is ignored).
for (const s of steps) {
const draft = s.argv[7].startsWith("draft-");
assert.equal(s.argv.includes("--model"), draft, s.argv[7]);
assert.ok(!s.argv.includes("--final"), s.argv[7]);
}
- assert.deepEqual(steps[5].argv.slice(8), ["--projects-root", "/p", "--model", "qwen3:8b"]);
+ assert.deepEqual(steps[4].argv.slice(8), ["--projects-root", "/p", "--mode", "draft-all", "--model", "qwen3:8b"]);
// No model: each task's route chooses.
assert.ok(chainSteps({ article: "art", n: 2, projectsRoot: "/p", mode: "draft-all" }).every((s) => !s.argv.includes("--model")));
assert.throws(() => chainSteps({ article: "art", n: 2, projectsRoot: "/p", mode: "draft-all", model: "a b" }), /not a model name/);
@@ -133,18 +136,19 @@ test("Draft everything resumes past a draft that ran — done, skipped or failed
const it = {
steps: ["current", "windows", "prepare", "posts", "manifest"].map((s) => ({ task: `chain:${s}`, status: "done" })).concat([
{ task: "chain:draft-cut", status: "done" },
+ { task: "chain:cut-windows", status: "done" },
{ task: "chain:draft-onscreen", status: "failed" },
{ task: "chain:draft-teaser", status: "skipped" },
{ task: "chain:draft-flips", status: "cancelled" },
]),
};
const done = doneSteps(it);
- assert.deepEqual(done.slice(5), ["draft-cut", "draft-onscreen", "draft-teaser"]);
+ assert.deepEqual(done.slice(5), ["draft-cut", "cut-windows", "draft-onscreen", "draft-teaser"]);
assert.equal(chainStart({ done, mode: "draft-all" }), "draft-flips");
// The default chain never sees the drafts: it resumes at voices.
assert.equal(chainStart({ done }), "voices");
- const failedCode = { steps: [{ task: "chain:current", status: "done" }, { task: "chain:windows", status: "failed" }] };
- assert.equal(chainStart({ done: doneSteps(failedCode), mode: "draft-all" }), "windows");
+ const failedCode = { steps: [{ task: "chain:current", status: "done" }, { task: "chain:prepare", status: "failed" }] };
+ assert.equal(chainStart({ done: doneSteps(failedCode), mode: "draft-all" }), "prepare");
assert.equal(chainStart({ from: "draft-threads", mode: "draft-all" }), "draft-threads");
assert.throws(() => chainStart({ from: "draft-threads" }), /--from must be one of/);
const all = chainStepsOf("draft-all").map((s) => s.name);
@@ -203,14 +207,14 @@ test("umtool chain --dry: the plan, resuming where the iteration left off; refus
// --draft-all: the same resume point, the drafts in the plan, the model on them.
const all = JSON.parse(run("art", "2", "--dry", "--json", "--draft-all", "--model", "claude-sonnet-5-5", "--projects-root", path.join(ROOT, "projects")));
assert.equal(all.start, "prepare");
- assert.deepEqual(all.steps.map((s) => s.argv[7]).slice(3, 9), ["draft-cut", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads", "draft-narrate"]);
+ assert.deepEqual(all.steps.map((s) => s.argv[7]).slice(3, 9), ["draft-cut", "cut-windows", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads"]);
assert.deepEqual(all.steps.map((s) => s.argv[7]).slice(-2), ["draft-youtube", "draft-social"]);
assert.ok(all.steps.at(-1).argv.includes("claude-sonnet-5-5"));
assert.throws(() => run("art", "2", "--dry", "--model", "qwen3:8b"), (e) => /--model is Draft everything's/.test(String(e.stderr)));
assert.throws(() => run("art", "2", "--dry", "--draft-all", "--final"), (e) => /builds the fast cut/.test(String(e.stderr)));
// --deck (release 29 G1): the deck step before the flips; Draft everything's only.
const deck = JSON.parse(run("art", "2", "--dry", "--json", "--draft-all", "--deck", "--projects-root", path.join(ROOT, "projects")));
- assert.deepEqual(deck.steps.map((s) => s.argv[7]).slice(6, 8), ["deck", "draft-flips"]);
+ assert.deepEqual(deck.steps.map((s) => s.argv[7]).slice(7, 9), ["deck", "draft-flips"]);
assert.throws(() => run("art", "2", "--dry", "--deck"), (e) => /--deck is Draft everything's option/.test(String(e.stderr)));
});
@@ -249,3 +253,43 @@ test("the projects root comes from settings.generation.projectsRoot (release 27
rmSync(dir, { recursive: true, force: true });
}
});
+
+// demo epic D1: windows for the cut; stop before render; the whole-recording allowance.
+test("cutWindows: the manifest's clips, padded and rounded outward, once per moment", () => {
+ const body = cutWindows(
+ {
+ slug: "art-i2",
+ provenance: { channelSlug: "fallback" },
+ timeline: [
+ { type: "card", id: "t0" },
+ { type: "clip", id: "c1", channel: "alpha", video: "v1", start: 10.004, end: 20 },
+ { type: "clip", id: "c2", channel: "alpha", video: "v1", start: 12, end: 18 }, // inside c1's window
+ { type: "clip", id: "c3", video: "v2", start: 1, end: 4 }, // the manifest's channel
+ { type: "clip", id: "bad", channel: "alpha", video: "v3" },
+ ],
+ },
+ { pad: 3, requestedBy: "t" },
+ );
+ assert.deepEqual(body, {
+ requestedBy: "t",
+ items: [
+ { slug: "alpha", id: "v1", from: 7, to: 23, clipId: "art-i2#c1", reason: "cut art-i2 c1", pad: 3 },
+ { slug: "fallback", id: "v2", from: 0, to: 7, clipId: "art-i2#c3", reason: "cut art-i2 c3", pad: 3 },
+ ],
+ });
+});
+
+test("stopBeforeRender ends either chain before the voices; the allowance rides on every step", () => {
+ const video = chainStepsOf("video", { stopBeforeRender: true }).map((s) => s.name);
+ assert.deepEqual(video, ["current", "windows", "prepare", "posts", "manifest"]);
+ const all = chainStepsOf("draft-all", { stopBeforeRender: true }).map((s) => s.name);
+ assert.equal(all.at(-1), "draft-narrate");
+ assert.ok(!all.includes("voices") && !all.includes("video"));
+ // All done before the render: nothing to run; without the option, it resumes at the voices.
+ assert.equal(chainStart({ done: video, stopBeforeRender: true }), null);
+ assert.equal(chainStart({ done: video }), "voices");
+ const steps = chainSteps({ article: "art", n: 2, projectsRoot: "/p", node: "node", stopBeforeRender: true, allowWholeRecording: true });
+ assert.equal(steps.length, 5);
+ assert.ok(steps.every((s) => s.argv.includes("--allow-whole-recording")));
+ assert.ok(chainSteps({ article: "art", n: 2, projectsRoot: "/p", node: "node" }).every((s) => !s.argv.includes("--allow-whole-recording") && !s.argv.includes("--mode")));
+});
diff --git a/umtool/lib/report/characterLayers.mjs b/umtool/lib/report/characterLayers.mjs
@@ -0,0 +1,49 @@
+// THE LAYERS ONE READ ASKS, read from a project's folder (cast.mjs, post-say.mjs voiceSourceOf; knobs.md, "A
+// character is a preset"): the project's own characters (`narration/characters.json`) over its voice map
+// (`narration/voices.json`), the CAST it reads (castStore.mjs castForProject), and the character a post item names
+// for itself (`narration.character`). Every reader -- a single post's take (readVoice.mjs), a thread read
+// (postThreadRead.mjs), a recording made a read (postNarrationCli.mjs importRecording), the bench's routes, `umtool
+// cast project` -- loads them here, so they ask the same files.
+//
+// A broken characters.json or cast.json reads as none (its `error` kept: `umtool cast project` says it); a broken
+// voice map reads as none too unless `strictMap` (a thread read refuses one, as before).
+//
+// Plain ESM.
+import { castPresetMap, characterForRead, itemCharacterOf, itemPresetOf, projectPresetMap, recordedPresetOf } from "umtool-report-to-video/cast";
+import { castForProject, readProjectCharacters } from "./castStore.mjs";
+
+/**
+ * The trim a recording of post item `e` is kept with (postRecord.mjs keepRecording's `trim`): its character's recorded
+ * preset's (cast.mjs characterForRead, recordedPresetOf) -- `{ on, padMs }` -- or null: no character, the recorder's own.
+ */
+export async function recordedTrimFor(dir, e) {
+ const who = (await readLayers(dir).catch(() => null))?.characterForRead(e) ?? null;
+ return who?.character ? recordedPresetOf(who.character).trim : null;
+}
+
+/**
+ * @param {string} dir the project's folder
+ * @param {{ reportsRoot?: string, strictMap?: boolean }} [o]
+ * @returns {Promise<{ castRead: any, projectRead: any, voiceMap: Record<string, string>, cast: any, project: any,
+ * map: Record<string, any>, castMap: Record<string, any>, itemOf: (e: any) => any, itemCharacterOf: (e: any) => any,
+ * characterForRead: (e: any, as?: string | null) => any }>}
+ */
+export async function readLayers(dir, { reportsRoot = undefined, strictMap = false } = {}) {
+ const { readVoiceMap } = await import("./postSay.mjs");
+ const castRead = await castForProject(dir, ...(reportsRoot ? [reportsRoot] : []));
+ const projectRead = await readProjectCharacters(dir);
+ const voiceMap = strictMap ? await readVoiceMap(dir) : await readVoiceMap(dir).catch(() => ({}));
+ const layers = { project: projectRead.doc, cast: castRead.cast };
+ return {
+ castRead, projectRead, voiceMap, ...layers,
+ /** voiceSourceOf's `map`: the project's characters over its voice map. */
+ map: projectPresetMap(projectRead.doc, voiceMap),
+ /** voiceSourceOf's `cast`. */
+ castMap: castPresetMap(castRead.cast),
+ /** voiceSourceOf's `item` for post item `e`. */
+ itemOf: (e) => itemPresetOf(e, layers),
+ itemCharacterOf: (e) => itemCharacterOf(e, layers),
+ /** The character a recording of `e` is made into (cast.mjs characterForRead). */
+ characterForRead: (e, as = null) => characterForRead(e, { ...layers, as }),
+ };
+}
diff --git a/umtool/lib/report/characters.test.mjs b/umtool/lib/report/characters.test.mjs
@@ -0,0 +1,464 @@
+// A character is a preset, on disk (castStore.mjs, castCli.mjs, characterLayers.mjs, postThreadRead.mjs,
+// postNarrationCli.mjs): a version 1 cast read as version 2 and written as it (undo puts the old file back), the
+// preset flags of `umtool cast set`, a project's OWN characters (one writer, an undo point a write, anonymous ones
+// "Anon 1", "Anon 2"), "Add to the pool" / "Keep in this video only", a post item's own character, the chain's answer
+// and its source in `umtool cast project`, a preset's SPEED on a single take and on a thread read's parts (and the
+// flag over it), and a recording made a read with its character's recorded preset. No editor: the tts and voice ops
+// are stubs; every project is a temp dir.
+import assert from "node:assert/strict";
+import { existsSync } from "node:fs";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+import { encodeWav16 } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs";
+import { VOICE_A, VOICE_B, syntheticVoice, withSilence } from "yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs";
+import { CastError, castFile, castWrite, projectCharactersFile, projectCharactersWrite, readCast, readCastFile, readProjectCharacters, undoCast, undoProjectCharacters } from "./castStore.mjs";
+import { castCommand } from "./castCli.mjs";
+import { readLayers, recordedTrimFor } from "./characterLayers.mjs";
+import { importRecording, makeTake } from "./postNarrationCli.mjs";
+import { postsCommand } from "./postsCli.mjs";
+import { partKey, readParts, threadReadPlan, threadTake, upToDate } from "./postThreadRead.mjs";
+import { itemReadVoice } from "./readVoice.mjs";
+import { threadArgvOf } from "./castProject.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-characters-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+const wavOf = async (file, voice, seconds = 1.5, silence = 0.3) => {
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, encodeWav16(withSilence(syntheticVoice({ ...voice, seconds }), { before: silence, after: silence })));
+};
+const run = (command, key) => async (args, extra = {}) => {
+ const lines = [];
+ const code = await command(args, { [key]: ROOT, log: (s) => lines.push(s), out: (s) => lines.push(s), err: (s) => lines.push(s), ...extra });
+ return { code, lines, text: () => lines.join("\n"), json: () => JSON.parse(lines.join("\n")) };
+};
+const cast = run(castCommand, "reportsRoot");
+const posts = run(postsCommand, "root");
+const stubAsk = (asked) => async (body) => {
+ asked.push(body);
+ await wavOf(body.out, body.voice === "am_michael" ? VOICE_A : VOICE_B, 1.2);
+ return { jobId: `job-${asked.length}`, result: { wav: body.out, engine: body.engine, voice: body.voice } };
+};
+
+// THE PROJECT: @hostman's post (p-1), his answer to @guest (p-2: a thread), @guest's own post (p-3), a stranger's (p-4).
+const DIR = path.join(ROOT, "chars");
+{
+ const post = (id, handle, author, o = {}) => ({ type: "post", id: `p-${id}`, post: `hostx/${id}`, platform: "x", author, handle, date: `2026-10-30T1${id}:00:00.000Z`, text: `words of ${id} from ${handle}.`, ...o });
+ await mkdir(DIR, { recursive: true });
+ await writeFile(path.join(DIR, "video.manifest.json"), JSON.stringify({
+ schemaVersion: 1, slug: "chars", title: "Characters", provenance: { channelsDir: "../channels", channelSlug: "chan" },
+ render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" }, postNarration: { engine: "kokoro", voice: "af_heart" } },
+ timeline: [
+ post("1", "hostman", "Host Man", { narration: { script: "Host's first line, read aloud." } }),
+ post("2", "hostman", "Host Man", { parents: [{ id: "20", handle: "guest", author: "The Guest", date: "2026-10-30T09:00:00.000Z", text: "the guest asks a question" }], narration: { script: "Host answers the guest." } }),
+ post("3", "guest", "The Guest", { narration: { script: "The guest's own line." } }),
+ post("4", "stranger", "A Stranger", { narration: { script: "A stranger says a thing." } }),
+ ],
+ }, null, 2));
+}
+const project = { id: "chars", dir: DIR };
+const manifest = async () => JSON.parse(await readFile(path.join(DIR, "video.manifest.json"), "utf8"));
+const item = async (id) => (await manifest()).timeline.find((e) => e.id === id);
+
+test("the store: a version 1 cast reads as version 2, the first write makes it version 2, undo puts the old file back", async () => {
+ const file = castFile(ROOT);
+ const v1 = `${JSON.stringify({ format: "umtool-cast", version: 1, characters: [
+ { id: "hostman", name: "Host Man", handles: ["hostman"], voice: "kokoro:am_michael", speakers: ["Host"] },
+ { id: "me", name: "Me", handles: ["operator"], voice: "kokoro:bm_george", convert: { engine: "seed-vc", pitch: "contour", semitones: 2 }, narrator: true },
+ ] }, null, 1)}\n`;
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, v1);
+ const r = await readCastFile(file);
+ assert.equal(r.error, undefined);
+ assert.equal(r.cast.version, 2, "in memory: version 2");
+ assert.deepEqual(r.cast.characters[1], {
+ id: "me", name: "Me", handles: ["operator"], synthetic: { voice: "kokoro:bm_george" }, recorded: { convert: { engine: "seed-vc", pitch: "contour", semitones: 2 } }, narrator: true,
+ voice: "kokoro:bm_george", convert: { engine: "seed-vc", pitch: "contour", semitones: 2 },
+ }, "its presets, and the voice / convert they answer to");
+ assert.equal(await readFile(file, "utf8"), v1, "reading writes nothing");
+ // A write: version 2 on disk, the presets alone (no voice / convert beside them).
+ const w = await castWrite(file, (chars) => {
+ assert.equal(chars[0].voice, undefined, "the mutation is handed version 2's characters");
+ chars[0].synthetic.speed = 1.1;
+ }, { token: r.token, what: "hostman at 1.1" });
+ const disk = JSON.parse(await readFile(file, "utf8"));
+ assert.equal(disk.version, 2);
+ assert.deepEqual(disk.characters[0], { id: "hostman", name: "Host Man", handles: ["hostman"], synthetic: { voice: "kokoro:am_michael", speed: 1.1 }, speakers: ["Host"] });
+ assert.deepEqual(disk.characters[1], { id: "me", name: "Me", handles: ["operator"], synthetic: { voice: "kokoro:bm_george" }, recorded: { convert: { engine: "seed-vc", pitch: "contour", semitones: 2 } }, narrator: true });
+ assert.equal(w.undo, 1);
+ // A view written back with its PRESET changed: the preset wins over the view's own alias (which still says the old voice).
+ const view = (await readCastFile(file)).cast.characters[0];
+ await castWrite(file, (chars) => { chars[0] = { ...view, synthetic: { ...view.synthetic, voice: "kokoro:am_onyx" } }; }, { what: "a view, its preset changed" });
+ assert.deepEqual(JSON.parse(await readFile(file, "utf8")).characters[0].synthetic, { voice: "kokoro:am_onyx", speed: 1.1 });
+ // …and the old way of setting one (`c.voice = …`) is still the newer word; neither leaves an alias on disk.
+ await castWrite(file, (chars) => { chars[0].voice = "kokoro:am_michael"; }, { what: "the old way" });
+ assert.deepEqual(JSON.parse(await readFile(file, "utf8")), disk);
+ await undoCast(file);
+ await undoCast(file);
+ // A refusal writes nothing: a convert target that is a file.
+ await assert.rejects(castWrite(file, (chars) => { chars[0].recorded = { convert: { voice: "narration/me.wav" } }; }), /never a file or a recording/);
+ assert.deepEqual(JSON.parse(await readFile(file, "utf8")), disk);
+ // Undo: the version 1 text, byte for byte -- and it reads the same.
+ const u = await undoCast(file);
+ assert.equal(u.undone, "hostman at 1.1");
+ assert.equal(await readFile(file, "utf8"), v1);
+ assert.equal((await readCast(ROOT)).cast.characters[0].voice, "kokoro:am_michael");
+});
+
+test("umtool cast set: the preset fields -- speed, clean, trim and its pad, the direction; default takes one off", async () => {
+ let r = await cast(["set", "hostman", "--speed", "1.15", "--enhance", "off", "--trim", "on", "--trim-pad", "120", "--direction", "higher, brisk, amused", "--convert-engine", "seed-vc", "--convert-pitch", "source", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual(r.json().character.synthetic, { voice: "kokoro:am_michael", speed: 1.15 });
+ assert.deepEqual(r.json().character.recorded, { convert: { engine: "seed-vc", pitch: "source" }, enhance: false, trim: { on: true, padMs: 120 }, direction: "higher, brisk, amused" });
+ assert.equal(r.json().character.voice, "kokoro:am_michael", "the view still says its voice");
+ assert.equal(JSON.parse(await readFile(castFile(ROOT), "utf8")).version, 2, "the write made the file version 2");
+ r = await cast(["ls"]);
+ assert.match(r.text(), /hostman\s+kokoro:am_michael ×1\.15\s+Host Man @hostman convert: seed-vc -> kokoro:am_michael, pitch source; not cleaned; trim pad 120 ms; direction: "higher, brisk, amused"/);
+ // `default` takes a key off; --no-speed the speed; "" the direction.
+ r = await cast(["set", "hostman", "--enhance", "default", "--trim", "default", "--convert-pitch", "default", "--no-speed", "--direction", "", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual(r.json().character.synthetic, { voice: "kokoro:am_michael" });
+ assert.deepEqual(r.json().character.recorded, { convert: { engine: "seed-vc" } });
+ for (const [args, re] of [
+ [["--speed", "3"], /--speed is a number from 0\.5 to 2/],
+ [["--enhance", "maybe"], /--enhance is on, off or default/],
+ [["--trim-pad", "9000"], /--trim-pad is a number of milliseconds from 0 to 2000/],
+ [["--direction", "x".repeat(201)], /--direction is one line for the person reading \(at most 200/],
+ [["--convert-voice", "me.wav"], /--convert-voice is a STOCK voice with its engine.*never a file or a recording/],
+ [["--anonymous"], /an anonymous character is one video's, never the pool's/],
+ [["--no-voice"], /a cast character has a stock voice/],
+ ]) {
+ r = await cast(["set", "hostman", ...args]);
+ assert.equal(r.code, 1, args.join(" "));
+ assert.match(r.text(), re);
+ }
+ assert.deepEqual((await readCast(ROOT)).cast.characters[0].recorded, { convert: { engine: "seed-vc" } }, "a refusal writes nothing");
+ r = await cast(["set", "hostman", "--speed", "1.15"]);
+ assert.equal(r.code, 0, r.text());
+});
+
+test("a project's own characters: one writer, an undo point a write, anonymous ones Anon 1, Anon 2; voices.json left alone", async () => {
+ await mkdir(path.join(DIR, "narration"), { recursive: true });
+ const voices = path.join(DIR, "narration", "voices.json");
+ const mapText = `${JSON.stringify({ stranger: "kokoro:am_onyx" }, null, 1)}\n`;
+ await writeFile(voices, mapText);
+ assert.equal((await readProjectCharacters(DIR)).exists, false);
+ let r = await cast(["project", "chars", "add", "anon-a", "--anonymous", "--handles", "@Guest", "--voice", "kokoro:am_puck", "--speed", "0.9", "--direction", "flat, tired", "--enhance", "off", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual(r.json().character, {
+ id: "anon-a", name: "Anon 1", anonymous: true, shown: "Anon 1", handles: ["guest"], synthetic: { voice: "kokoro:am_puck", speed: 0.9 }, recorded: { enhance: false, direction: "flat, tired" }, voice: "kokoro:am_puck",
+ });
+ r = await cast(["project", "chars", "add", "anon-b", "--anonymous", "--name", "the second one", "--json"]);
+ assert.deepEqual([r.json().character.shown, r.json().character.name, r.json().character.synthetic], ["Anon 2", "the second one", undefined], "the next shown name; no voice of its own");
+ const file = projectCharactersFile(DIR);
+ assert.equal(file, path.join(DIR, "narration", "characters.json"));
+ const disk = JSON.parse(await readFile(file, "utf8"));
+ assert.deepEqual([disk.format, disk.version, disk.characters.length], ["umtool-project-characters", 1, 2]);
+ assert.equal(disk.characters[0].voice, undefined, "the presets alone on disk");
+ assert.ok(existsSync(file.replace(/\.json$/, ".undo.json")));
+ // Refusals, in the layer's words -- nothing written.
+ for (const [args, re] of [
+ [["add", "anon-a", "--name", "Again"], /is one of chars's characters already/],
+ [["add", "plain"], /takes --name "…" \(or --anonymous/],
+ [["add", "plain", "--name", "Plain", "--shown", "X"], /--shown is an anonymous character's shown name/],
+ [["add", "plain", "--name", "Plain", "--narrator"], /the narrator is a cast character/],
+ [["add", "plain", "--name", "Plain", "--voice", "/tmp/me.wav"], /--voice is a STOCK voice with its engine/],
+ [["add", "plain", "--name", "Plain", "--convert-voice", "seedvc:/home/me.wav"], /never a file or a recording/],
+ [["add", "plain", "--name", "Plain", "--handles", "guest"], /@guest is anon-a's already/],
+ [["set", "nobody", "--speed", "1"], /no nobody among chars's characters/],
+ [["pool", "anon-a"], /anon-a is anonymous: it stays in this video/],
+ [["pool", "anon-b"], /anonymous/],
+ [["frobnicate"], /nothing \(the view\), add, set, rm, undo, pool or keep/],
+ ]) {
+ r = await cast(["project", "chars", ...args]);
+ assert.equal(r.code, 1, args.join(" "));
+ assert.match(r.text(), re);
+ }
+ assert.deepEqual(JSON.parse(await readFile(file, "utf8")), disk);
+ // The store itself: a stale token refused, a broken file never overwritten.
+ const read = await readProjectCharacters(DIR);
+ await assert.rejects(projectCharactersWrite(DIR, () => {}, { token: "stale" }), (e) => e instanceof CastError && e.status === 409);
+ await projectCharactersWrite(DIR, (chars) => { chars[1].shown = "The Second"; }, { token: read.token, what: "rename" });
+ assert.equal((await readProjectCharacters(DIR)).doc.characters[1].shown, "The Second");
+ const u = await undoProjectCharacters(DIR);
+ assert.equal(u.undone, "rename");
+ assert.equal((await readProjectCharacters(DIR)).doc.characters[1].shown, "Anon 2");
+ // set, rm, undo through the CLI.
+ r = await cast(["project", "chars", "set", "anon-b", "--shown", "Witness", "--voice", "kokoro:af_bella", "--json"]);
+ assert.deepEqual([r.json().character.shown, r.json().character.voice], ["Witness", "kokoro:af_bella"]);
+ r = await cast(["project", "chars", "set", "anon-b", "--no-voice", "--json"]);
+ assert.equal(r.json().character.synthetic, undefined);
+ r = await cast(["project", "chars", "rm", "anon-b"]);
+ assert.equal(r.code, 0, r.text());
+ assert.equal((await readProjectCharacters(DIR)).doc.characters.length, 1);
+ r = await cast(["project", "chars", "undo"]);
+ assert.match(r.text(), /undone: rm anon-b \(chars\)/);
+ assert.equal((await readProjectCharacters(DIR)).doc.characters.length, 2);
+ await cast(["project", "chars", "rm", "anon-b"]);
+ assert.equal(await readFile(voices, "utf8"), mapText, "voices.json is not rewritten");
+ // A broken file: read as none, said, never overwritten.
+ const good = await readFile(file, "utf8");
+ await writeFile(file, "{ nope");
+ assert.match((await readProjectCharacters(DIR)).error, /not JSON/);
+ r = await cast(["project", "chars", "add", "x", "--name", "X"]);
+ assert.equal(r.code, 1);
+ assert.match(r.text(), /fix the file first/);
+ assert.equal(await readFile(file, "utf8"), "{ nope");
+ r = await cast(["project", "chars"]);
+ assert.match(r.text(), /this video's characters are NOT read/);
+ await writeFile(file, good);
+});
+
+test("cast project: the chain's answer and its source for each author; a post item's own character", async () => {
+ let r = await cast(["project", "chars", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ let v = r.json();
+ const row = (key) => v.characters.find((c) => c.key === key);
+ // hostman: the cast's character, its speed with it. guest: this video's anonymous character, over nothing.
+ assert.deepEqual([row("hostman").voice.spec, row("hostman").voice.from, row("hostman").voice.speed, row("hostman").character.layer], ["kokoro:am_michael", "cast", 1.15, "cast"]);
+ assert.deepEqual([row("anon-a").voice.spec, row("anon-a").voice.from, row("anon-a").voice.speed, row("anon-a").voice.character], ["kokoro:am_puck", "project", 0.9, "anon-a"]);
+ assert.deepEqual([row("anon-a").name, row("anon-a").character.anonymous, row("anon-a").character.shown, row("anon-a").character.layer], ["Anon 1", true, "Anon 1", "project"], "shown under its shown name");
+ assert.deepEqual(row("anon-a").recorded, { convert: { engine: null, voice: "kokoro:am_puck" }, enhance: false, trim: { on: true, padMs: null }, direction: "flat, tired" });
+ // stranger: the voice map -- a project character with only a synthetic voice.
+ assert.deepEqual([row("@stranger").voice.spec, row("@stranger").voice.from, row("@stranger").character], ["kokoro:am_onyx", "project", null]);
+ assert.deepEqual(v.own.map((c) => [c.id, c.handles]), [["anon-a", ["guest"]]]);
+ assert.deepEqual(v.itemCharacters, []);
+ assert.equal(v.charactersFile, projectCharactersFile(DIR));
+ r = await cast(["project", "chars"]);
+ assert.match(r.text(), /hostman\s+kokoro:am_michael ×1\.15\s+\(cast: hostman\)/);
+ assert.match(r.text(), /anon-a\s+kokoro:am_puck ×0\.9\s+\(project: anon-a\).*shown as "Anon 1"/);
+ assert.match(r.text(), /a recording of them: converted to kokoro:am_puck; not cleaned; edges trimmed; direction: "flat, tired"/);
+ assert.match(r.text(), /@stranger\s+kokoro:am_onyx\s+\(project\)/);
+
+ // `posts voices ls` answers through the same layers: this video's own character, the map, the cast.
+ r = await posts(["voices", "chars", "ls", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ const author = (h) => r.json().authors.find((a) => a.handle === h);
+ assert.deepEqual([author("guest").voice, author("guest").from, author("guest").own, author("guest").speed], ["kokoro:am_puck", "project", "anon-a", 0.9]);
+ assert.deepEqual([author("stranger").voice, author("stranger").from, author("stranger").own, author("stranger").mapped], ["kokoro:am_onyx", "project", undefined, true]);
+ assert.deepEqual([author("hostman").voice, author("hostman").from, author("hostman").character], ["kokoro:am_michael", "cast", "hostman"]);
+ r = await posts(["voices", "chars", "ls"]);
+ assert.match(r.text(), /@guest kokoro:am_puck ×0\.9 \(this video's character: anon-a\)/);
+
+ // A POST ITEM's OWN CHARACTER: p-4 (the stranger's) read as the cast's `me`.
+ r = await posts(["character", "chars", "p-4", "ghost"]);
+ assert.equal(r.code, 2);
+ assert.match(r.text(), /no character ghost among chars's own or in the cast/);
+ r = await posts(["character", "chars", "p-4", "me", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual([r.json().character, r.json().layer, r.json().changed, r.json().voice.spec, r.json().voice.from], ["me", "cast", "set", "kokoro:bm_george", "item"]);
+ assert.equal((await item("p-4")).narration.character, "me");
+ r = await posts(["character", "chars", "p-4"]);
+ assert.match(r.text(), /p-4: read as me \(Me; the cast's\): kokoro:bm_george \(item: me\)/);
+ r = await cast(["project", "chars", "--json"]);
+ v = r.json();
+ assert.deepEqual(v.itemCharacters.map((x) => [x.id, x.character, x.found, x.layer, x.voice.spec, x.voice.from]), [["p-4", "me", true, "cast", "kokoro:bm_george", "item"]]);
+ assert.deepEqual([row("@stranger").voice.spec, row("@stranger").voice.from], ["kokoro:am_onyx", "project"], "the handle's own answer is still the map's");
+ // The single take asks the same chain (readVoice.mjs), and a thread read's plan.
+ assert.deepEqual(await itemReadVoice(project, await item("p-4"), { render: (await manifest()).render }), { engine: "kokoro", voice: "bm_george", from: "item", character: "me" });
+ // The project's own first: an id both layers have.
+ await projectCharactersWrite(DIR, (chars) => { chars.push({ id: "me", name: "Me, here", handles: [], synthetic: { voice: "kokoro:am_echo", speed: 1.3 } }); });
+ assert.deepEqual(await itemReadVoice(project, await item("p-4"), { render: (await manifest()).render }), { engine: "kokoro", voice: "am_echo", from: "item", speed: 1.3, character: "me" });
+ await undoProjectCharacters(DIR);
+ // --clear: by its author's handle again.
+ r = await posts(["character", "chars", "p-4", "--clear", "--json"]);
+ assert.deepEqual([r.json().character, r.json().changed, r.json().voice.from], [null, "cleared", "project"]);
+ assert.equal((await item("p-4")).narration.character, undefined);
+ r = await posts(["character", "chars", "p-4", "me", "--clear"]);
+ assert.equal(r.code, 2);
+});
+
+test("a preset's speed on a single take: the flag, then the character's, then the item's own", async () => {
+ const m = await manifest();
+ const asked = [];
+ // hostman (the cast: kokoro am_michael ×1.15): his take is asked at 1.15, and says so.
+ let t = await makeTake(project, await item("p-1"), { render: m.render, ask: stubAsk(asked), redaction: null });
+ assert.deepEqual([asked.at(-1).engine, asked.at(-1).voice, asked.at(-1).speed], ["kokoro", "am_michael", 1.15]);
+ assert.equal(t.take.speed, 1.15);
+ // The flag over it.
+ t = await makeTake(project, await item("p-1"), { render: m.render, speed: 0.8, ask: stubAsk(asked), redaction: null });
+ assert.equal(asked.at(-1).speed, 0.8);
+ // The item's own speed (narration.speed: set on this one item) beats its character's; the flag beats both.
+ const own = { ...(await item("p-1")), narration: { ...(await item("p-1")).narration, speed: 0.7 } };
+ t = await makeTake(project, own, { render: m.render, ask: stubAsk(asked), redaction: null });
+ assert.equal(asked.at(-1).speed, 0.7);
+ t = await makeTake(project, own, { render: m.render, speed: 1.4, ask: stubAsk(asked), redaction: null });
+ assert.equal(asked.at(-1).speed, 1.4);
+ // The stranger (the voice map: no preset): no speed asked.
+ t = await makeTake(project, await item("p-4"), { render: m.render, ask: stubAsk(asked), redaction: null });
+ assert.deepEqual([asked.at(-1).voice, "speed" in asked.at(-1)], ["am_onyx", false]);
+ assert.equal(t.take.speed, undefined);
+});
+
+test("a thread read: each part at its character's speed, the flag over them all, Orpheus none -- and another speed is another part", async () => {
+ const m = await manifest();
+ const e2 = await item("p-2");
+ const L = await readLayers(DIR);
+ const plan = threadReadPlan(m, e2, { map: L.map, cast: L.castMap, item: L.itemOf(e2) });
+ assert.deepEqual(plan.pieces.map((p) => [p.role, p.voice, p.from, p.speed ?? null, p.character ?? null]), [["parent:0", "am_puck", "project", 0.9, "anon-a"], ["post", "am_michael", "cast", 1.15, "hostman"]]);
+ const parts = readParts(plan);
+ assert.deepEqual(parts.map((p) => p.speed), [0.9, 1.15]);
+ assert.equal(parts[1].key, partKey("kokoro", "am_michael", parts[1].text, 1.15));
+ assert.notEqual(parts[1].key, partKey("kokoro", "am_michael", parts[1].text), "the same words at another speed are another part");
+ assert.equal(partKey("kokoro", "am_michael", "hi", 1), partKey("kokoro", "am_michael", "hi"), "at 1: the key as before");
+ // --speed: every part at that one.
+ assert.deepEqual(threadReadPlan(m, e2, { map: L.map, cast: L.castMap, speed: 1.4 }).pieces.map((p) => p.speed), [1.4, 1.4]);
+ // Orpheus has no speed: a piece in it is asked none, whatever the flag says.
+ assert.deepEqual(threadReadPlan(m, e2, { map: { guest: "orpheus:tara" }, cast: L.castMap, speed: 1.4 }).pieces.map((p) => [p.engine, p.speed ?? null]), [["orpheus", null], ["kokoro", 1.4]]);
+ // His own words at the item's own speed (narration.speed), as a single take -- over his character's; the others' untouched.
+ assert.deepEqual(threadReadPlan(m, { ...e2, narration: { ...e2.narration, speed: 0.75 } }, { map: {}, cast: {} }).pieces.map((p) => [p.role, p.speed ?? null]), [["parent:0", null], ["post", 0.75]]);
+ assert.deepEqual(threadReadPlan(m, { ...e2, narration: { ...e2.narration, speed: 0.75 } }, { map: L.map, cast: L.castMap }).pieces.map((p) => [p.role, p.speed ?? null]), [["parent:0", 0.9], ["post", 0.75]]);
+
+ // Made: the editor is asked each part at its speed, the take's parts keep it, and the same read again is up to date.
+ const asked = [];
+ const r = await threadTake(project, e2, { manifest: m, red: null, ask: stubAsk(asked), lanes: null });
+ assert.deepEqual(asked.map((b) => [b.voice, b.speed]), [["am_puck", 0.9], ["am_michael", 1.15]]);
+ assert.deepEqual(r.take.parts.map((p) => [p.role, p.voice, p.speed]), [["parent:0", "am_puck", 0.9], ["post", "am_michael", 1.15]]);
+ assert.equal(r.take.read.speed, undefined, "a preset's speed is the character's, not the read's");
+ const after = await item("p-2");
+ const again = await threadTake(project, after, { red: null, ask: stubAsk(asked), lanes: null });
+ assert.equal(again.upToDate, true);
+ assert.equal(asked.length, 2);
+ // The flag: not up to date; the parts asked again at it (new cache keys), the read records it, and a re-read keeps it.
+ assert.equal(upToDate(after, threadReadPlan(await manifest(), after, { map: L.map, cast: L.castMap, speed: 1.4 })), false);
+ const fast = await threadTake(project, after, { red: null, speed: 1.4, ask: stubAsk(asked), lanes: null });
+ assert.deepEqual(asked.slice(2).map((b) => b.speed), [1.4, 1.4]);
+ assert.equal(fast.take.read.speed, 1.4);
+ assert.deepEqual(threadArgvOf(fast.take.read), ["--speed", "1.4"]);
+ // Through the CLI: --speed reaches a thread read (it was ignored), and a bad one is refused in the flag's name.
+ let c = await posts(["narrate", "chars", "p-2", "--take", "--thread", "--speed", "1.4", "--dry-run", "--json"]);
+ assert.equal(c.code, 0, c.text());
+ assert.deepEqual(c.json().pieces.map((p) => p.speed), [1.4, 1.4]);
+ assert.equal(c.json().upToDate, true);
+ c = await posts(["narrate", "chars", "p-2", "--take", "--thread", "--speed", "9", "--dry-run"]);
+ assert.equal(c.code, 2);
+ assert.match(c.text(), /--speed is a number from 0\.5 to 2/);
+});
+
+test("\"Add to the pool\" and \"Keep in this video only\"", async () => {
+ // Keep an author with no character here: a character of this video, in the voice they read in now.
+ let r = await cast(["project", "chars", "keep", "@stranger", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual(r.json().character, { id: "stranger", name: "A Stranger", handles: ["stranger"], synthetic: { voice: "kokoro:am_onyx" }, voice: "kokoro:am_onyx" });
+ // Keep a cast character here: a copy, without its narrator mark; changing it leaves the pool's as it is.
+ r = await cast(["project", "chars", "keep", "me", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.equal(r.json().character.narrator, undefined);
+ assert.deepEqual(r.json().character.recorded, { convert: { engine: "seed-vc", pitch: "contour", semitones: 2 } });
+ r = await cast(["project", "chars", "set", "me", "--convert-semitones", "-3", "--json"]);
+ assert.equal(r.json().character.recorded.convert.semitones, -3);
+ assert.equal((await readCast(ROOT)).cast.characters.find((c) => c.id === "me").recorded.convert.semitones, 2, "the pool's is untouched");
+ r = await cast(["project", "chars", "keep", "me"]);
+ assert.equal(r.code, 1);
+ assert.match(r.text(), /me is one of chars's characters already/);
+ // `use` for this project: this video's own character takes it (its preset answers before the voice map).
+ r = await cast(["use", "chars", "@stranger", "kokoro:am_fenrir", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.equal((await readProjectCharacters(DIR)).doc.characters.find((c) => c.id === "stranger").voice, "kokoro:am_fenrir");
+ assert.deepEqual(JSON.parse(await readFile(path.join(DIR, "narration", "voices.json"), "utf8")), { stranger: "kokoro:am_onyx" }, "the map is left as it was");
+ // An anonymous character never reaches the pool through `use --everywhere` either.
+ r = await cast(["use", "chars", "anon-a", "kokoro:am_onyx", "--everywhere"]);
+ assert.equal(r.code, 1);
+ assert.match(r.text(), /anon-a is anonymous: it stays in this video, never the pool/);
+ r = await cast(["use", "chars", "@guest", "kokoro:am_onyx", "--everywhere"]);
+ assert.equal(r.code, 1, "by its handle too");
+ assert.equal((await readCast(ROOT)).cast.characters.some((c) => (c.handles ?? []).includes("guest")), false);
+ // Add to the pool: into the cast, out of the project; one the cast has already is refused.
+ r = await cast(["project", "chars", "pool", "me"]);
+ assert.equal(r.code, 1);
+ assert.match(r.text(), /me is in the cast already/);
+ r = await cast(["project", "chars", "pool", "stranger", "--json"]);
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual([r.json().scope, r.json().changed], ["cast", "pooled"]);
+ assert.deepEqual((await readCast(ROOT)).cast.characters.find((c) => c.id === "stranger").synthetic, { voice: "kokoro:am_fenrir" });
+ assert.equal((await readProjectCharacters(DIR)).doc.characters.some((c) => c.id === "stranger"), false);
+ r = await cast(["undo"]);
+ assert.match(r.text(), /undone: stranger into the pool \(from chars\)/);
+ await cast(["project", "chars", "rm", "me"]);
+});
+
+test("a recording made a read with its character's recorded preset: clean off, trim off, the direction; the flags over them", async () => {
+ const rec = path.join(ROOT, "my-read.wav");
+ await wavOf(rec, VOICE_B, 2, 0.6);
+ const ops = [];
+ const askOp = async (route, body) => {
+ ops.push(route.split("/").at(-1));
+ await wavOf(body.out, VOICE_A, 2);
+ return { jobId: `op-${ops.length}`, result: { engine: body.engine ?? "openvoice", voice: body.voice } };
+ };
+ // p-3 is @guest's: this video's anonymous character (enhance off, direction) -- not cleaned, converted to its voice.
+ let r = await importRecording(project, await item("p-3"), rec, { ask: askOp });
+ assert.deepEqual(r.character, { id: "anon-a", name: "Anon 1", voice: "kokoro:am_puck", layer: "project" }, "named as it is shown");
+ assert.equal(r.direction, "flat, tired");
+ assert.deepEqual(ops, ["voice-convert"]);
+ assert.deepEqual(r.takes.map((t) => t.step), ["recorded", "converted to kokoro:am_puck"]);
+ assert.match(r.notes[0], /not cleaned: anon-a's recorded preset says so/);
+ assert.equal(r.disclosure, "Narration: voice converted to a synthetic voice (openvoice · kokoro:am_puck)", "the disclosure line is what it was");
+ const kept = (await item("p-3")).narration.takes[0];
+ assert.match(kept.note, /recorded for Anon 1/);
+ const trimmed = kept.seconds;
+ assert.ok(trimmed < 2.6, `its edges trimmed (${trimmed} s of 3.2)`);
+ // The command over the preset: clean it this once.
+ ops.length = 0;
+ r = await importRecording(project, await item("p-3"), rec, { clean: true, ask: askOp });
+ assert.deepEqual(ops, ["voice-enhance", "voice-convert"]);
+ // The preset says trim off: kept as recorded, edges and all; a pad is the room kept.
+ await cast(["project", "chars", "set", "anon-a", "--trim", "off"]);
+ r = await importRecording(project, await item("p-3"), rec, { convert: false, ask: askOp });
+ const whole = (await item("p-3")).narration.takes.find((t) => t.file === r.takes[0].file).seconds;
+ assert.ok(whole > 3, `not trimmed (${whole} s)`);
+ await cast(["project", "chars", "set", "anon-a", "--trim", "on", "--trim-pad", "400"]);
+ r = await importRecording(project, await item("p-3"), rec, { convert: false, ask: askOp });
+ const padded = (await item("p-3")).narration.takes.find((t) => t.file === r.takes[0].file).seconds;
+ assert.ok(padded > trimmed + 0.3 && padded < whole, `the pad kept (${padded} s between ${trimmed} and ${whole})`);
+ // The record page's two paths ask the same preset (characterLayers.mjs recordedTrimFor): the room kept; none with no character.
+ assert.deepEqual(await recordedTrimFor(DIR, await item("p-3")), { on: true, padMs: 400 });
+ assert.deepEqual(await recordedTrimFor(DIR, await item("p-1")), { on: true, padMs: null }, "the cast's character: trimmed, the recorder's own room");
+ assert.deepEqual(await recordedTrimFor(DIR, { id: "x", handle: "nobody-at-all" }), { on: true, padMs: null }, "nobody's: the narrator's");
+ // --as: a character of this video's by id, the cast's by id; the item's own character before its author's.
+ r = await importRecording(project, await item("p-1"), rec, { as: "anon-a", convert: false, ask: askOp });
+ assert.equal(r.character.layer, "flag");
+ await assert.rejects(importRecording(project, await item("p-1"), rec, { as: "ghost", ask: askOp }), /--as ghost: no such character in this video's characters or the cast/);
+ await posts(["character", "chars", "p-3", "me"]);
+ ops.length = 0;
+ r = await importRecording(project, await item("p-3"), rec, { ask: askOp });
+ assert.deepEqual([r.character.id, r.character.layer], ["me", "item"]);
+ assert.deepEqual(r.takes.map((t) => t.step), ["recorded", "cleaned", "converted to kokoro:bm_george (pitch: contour +2 st)"]);
+ await posts(["character", "chars", "p-3", "--clear"]);
+});
+
+test("posts narrate --derive --op convert: the character's recorded preset unless a flag says otherwise; no character and no voice is refused", async () => {
+ // p-3 is @guest's (anon-a: kokoro:am_puck); the cast's narrator `me` converts by seed-vc, contour +2.
+ const rec = path.join(ROOT, "derive-read.wav");
+ await wavOf(rec, VOICE_B, 1.5, 0.3);
+ const asked = [];
+ const ask = async (route, body) => {
+ asked.push({ op: route.split("/").at(-1), ...body });
+ await wavOf(body.out, VOICE_A, 1.5);
+ return { jobId: `d-${asked.length}`, result: { engine: body.engine ?? "openvoice", voice: body.voice ?? "zac" } };
+ };
+ const r0 = await importRecording(project, await item("p-3"), rec, { convert: false, clean: false, ask });
+ const n = (await item("p-3")).narration.takes.findIndex((t) => t.file === r0.takes[0].file) + 1;
+ // No flags: anon-a's stock voice -- never the editor's default (the stub's "zac").
+ let r = await posts(["narrate", "chars", "p-3", "--derive", String(n), "--op", "convert", "--json"], { ask });
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual([asked.at(-1).op, asked.at(-1).voice, asked.at(-1).engine, asked.at(-1).pitch], ["voice-convert", "kokoro:am_puck", undefined, undefined]);
+ assert.equal(r.json().take.steps[0].voice, "kokoro:am_puck");
+ // --as: another character's whole convert entry; a flag over one key of it.
+ r = await posts(["narrate", "chars", "p-3", "--derive", String(n), "--op", "convert", "--as", "me"], { ask });
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual([asked.at(-1).engine, asked.at(-1).voice, asked.at(-1).pitch, asked.at(-1).semitones], ["seed-vc", "kokoro:bm_george", "contour", 2]);
+ assert.match(r.text(), /as me: seed-vc -> kokoro:bm_george \(pitch: contour \+2 st\)/);
+ r = await posts(["narrate", "chars", "p-3", "--derive", String(n), "--op", "convert", "--as", "me", "--semitones", "-1", "--voice", "kokoro:am_onyx"], { ask });
+ assert.deepEqual([asked.at(-1).engine, asked.at(-1).voice, asked.at(-1).pitch, asked.at(-1).semitones], ["seed-vc", "kokoro:am_onyx", "contour", -1]);
+ r = await posts(["narrate", "chars", "p-3", "--derive", String(n), "--op", "convert", "--as", "ghost"], { ask });
+ assert.equal(r.code, 2);
+ assert.match(r.text(), /--as ghost: no such character/);
+ // An enhance asks no character.
+ const before = asked.length;
+ r = await posts(["narrate", "chars", "p-3", "--derive", String(n), "--op", "enhance"], { ask });
+ assert.equal(r.code, 0, r.text());
+ assert.equal(asked.length, before + 1);
+ assert.equal("voice" in asked.at(-1), false);
+});
diff --git a/umtool/lib/report/derivePitch.mjs b/umtool/lib/report/derivePitch.mjs
@@ -0,0 +1,103 @@
+// A CONVERT'S PITCH, between umtool and the editor's voice-convert (the pitch a converted read lands on: knobs.md,
+// "The pitch a converted read lands on"). The pure pieces the CLI's derive (postNarrationCli.mjs deriveTake) and the
+// app's (app/api/report/post-narration/route.ts, the post bench's "run AI on take") share, so they ask, record and
+// refuse alike:
+//
+// derivePitchOf what a derive is asked with (`pitch`, `semitones`), checked before any job
+// convertAskOf what a CONVERT derive is asked with: what the ask named, the rest from the character's recorded
+// preset -- never the editor's default voice
+// stepPitchOf what the new take's step keeps: the pitch as the editor RAN it, never the target's own
+// deriveRefusalOf an editor refusal read as "no engine for it" -- or passed through as it is, when it already
+// names the command that fixes it
+//
+// Dependency-free but for cast.mjs's constants.
+import { CAST_CONVERT_PITCH, CAST_SEMITONES_MAX } from "umtool-report-to-video/cast";
+
+/**
+ * A derive's `pitch` / `semitones` as asked (a body's, a flag's): `{ ok: true, value: {pitch?, semitones?} }` with only
+ * what was given, or `{ ok: false, error }`. `semitones` may be a number or its string (a form field, a query). They
+ * are a convert's: asked of another op they are refused.
+ */
+export function derivePitchOf({ pitch, semitones } = {}, op = "convert") {
+ const none = (v) => v === undefined || v === null || v === "";
+ if (none(pitch) && none(semitones)) return { ok: true, value: {} };
+ if (op !== "convert") return { ok: false, error: `pitch and semitones are a convert's: ${op} keeps the read's own pitch` };
+ const value = {};
+ if (!none(pitch)) {
+ if (!CAST_CONVERT_PITCH.includes(pitch)) return { ok: false, error: `pitch is one of ${CAST_CONVERT_PITCH.join(", ")} (got ${JSON.stringify(pitch)})` };
+ value.pitch = pitch;
+ }
+ if (!none(semitones)) {
+ const n = typeof semitones === "number" ? semitones : typeof semitones === "string" && semitones.trim() !== "" ? Number(semitones) : NaN;
+ if (!Number.isFinite(n) || Math.abs(n) > CAST_SEMITONES_MAX) return { ok: false, error: `semitones is a number from -${CAST_SEMITONES_MAX} to ${CAST_SEMITONES_MAX} (got ${JSON.stringify(semitones)})` };
+ value.semitones = n;
+ }
+ return { ok: true, value };
+}
+
+/**
+ * WHAT A CONVERT DERIVE IS ASKED WITH (operator, 11 Nov: a derive with no flags asked the editor for ITS defaults and
+ * made a take in the wrong voice). `asked` is what the command or the body named (`engine`, `voice`, `pitch`,
+ * `semitones`: only those given); `convert` the recorded preset's convert entry of the character the read is made
+ * as (cast.mjs recordedPresetOf(character).convert -- `{engine, voice, pitch?, semitones?}`, null: no character);
+ * `who` its id, for the sentences. What was asked wins, each key by itself; the rest is the character's:
+ *
+ * engine, voice the character's convert engine and stock voice
+ * pitch the character's -- unless the ask names ANOTHER engine than the character's (a followed pitch is
+ * one engine's: the editor refuses it of another)
+ * semitones the character's, with a followed pitch; dropped with `pitch: "target"` asked for this read
+ *
+ * With no stock voice from either, `{ ok: false, error, fix }`: one sentence (and the flags that answer it), and the
+ * editor is never asked for its default voice. Else `{ ok: true, value: {engine, voice, pitch?, semitones?}, from: "asked" | "character" }` --
+ * `from` says whose voice it is.
+ *
+ * @param {{ engine?: string | null, voice?: string | null, pitch?: string | null, semitones?: number | null }} [asked]
+ * @param {{ engine?: string | null, voice?: string | null, pitch?: string, semitones?: number } | null} [convert]
+ * @param {string | null} [who]
+ * @returns {{ ok: true, value: { engine: string | null, voice: string, pitch?: string, semitones?: number }, from: "asked" | "character" } | { ok: false, error: string, fix: string }}
+ */
+export function convertAskOf(asked = {}, convert = null, who = null) {
+ const given = (v) => v !== undefined && v !== null && v !== "";
+ const cv = convert ?? {};
+ const voice = given(asked.voice) ? asked.voice : given(cv.voice) ? cv.voice : null;
+ if (!voice) {
+ // `error`: the sentence, for any surface; `fix`: the commands that answer it, for a terminal.
+ return who
+ ? { ok: false, error: `a convert needs a stock voice to convert to, and ${who} has none`, fix: `--voice <engine:voice>, or umtool cast set ${who} --convert-voice <engine:voice>` }
+ : { ok: false, error: "a convert needs a stock voice to convert to, and this post has no character with one", fix: "--voice <engine:voice>, --as <character>, or umtool cast add … for its author" };
+ }
+ const engine = given(asked.engine) ? asked.engine : given(cv.engine) ? cv.engine : null;
+ // The character's pitch is its engine's: another engine asked for this read is asked for none.
+ const own = !given(asked.engine) || !given(cv.engine) || asked.engine === cv.engine;
+ const pitch = given(asked.pitch) ? asked.pitch : own && given(cv.pitch) ? cv.pitch : undefined;
+ const semitones = given(asked.semitones) ? asked.semitones : own && pitch !== undefined && pitch !== "target" && given(cv.semitones) ? cv.semitones : undefined;
+ return {
+ ok: true,
+ value: { engine: engine ?? null, voice, ...(pitch !== undefined && pitch !== null ? { pitch } : {}), ...(semitones !== undefined && semitones !== null ? { semitones } : {}) },
+ from: given(asked.voice) ? "asked" : "character",
+ };
+}
+
+/**
+ * The pitch a derived take's step keeps: what the editor says it ran (its `@@voice-result`: its default when none was
+ * asked), else what was asked. The stock voice's own pitch is not a step's news (`{}`), and 0 semitones is none.
+ */
+export function stepPitchOf(asked = {}, said = {}) {
+ const pitch = typeof said?.pitch === "string" ? said.pitch : asked?.pitch;
+ if (!pitch || pitch === "target" || !CAST_CONVERT_PITCH.includes(pitch)) return {};
+ const n = typeof said?.semitones === "number" ? said.semitones : asked?.semitones;
+ return { pitch, ...(typeof n === "number" && Number.isFinite(n) && n !== 0 ? { semitones: n } : {}) };
+}
+
+/**
+ * An editor refusal of a derive, read: `null` (an ordinary error), or `{ installed: false, error }` -- the editor has
+ * no engine for the op (an older editor has no route; a newer one names the setup to run). A refusal that names an
+ * OPTIONAL group to fetch (`… --with f0`: the engine is there, its pitch-following model is not) is passed through in
+ * the editor's words: "no convert engine installed" would be false.
+ */
+export function deriveRefusalOf(op, status, message) {
+ const msg = String(message ?? "").replace(/^the editor refused it: /, "");
+ if (!(status === 404 || /not installed|no engine|unknown|not found|404/i.test(msg))) return null;
+ if (/--with\b/.test(msg)) return { installed: false, error: msg };
+ return { installed: false, error: `the editor has no ${op} engine installed (not installed: ${msg})` };
+}
diff --git a/umtool/lib/report/derivePitch.test.mjs b/umtool/lib/report/derivePitch.test.mjs
@@ -0,0 +1,92 @@
+// lib/report/derivePitch.mjs: a convert's pitch between umtool and the editor -- what a derive is asked with, what the
+// new take's step keeps, and which editor refusals mean "no engine". The app's derive route
+// (app/api/report/post-narration/route.ts) and the CLI's (postNarrationCli.mjs deriveTake) both go through it.
+// Run: node --test umtool/lib/report/derivePitch.test.mjs
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { validatePostNarration } from "umtool-report-to-video/post-narration";
+import { convertAskOf, derivePitchOf, deriveRefusalOf, stepPitchOf } from "./derivePitch.mjs";
+
+test("a derive's pitch as asked: only what was given, a body's number or a query's string, a convert's alone", () => {
+ assert.deepEqual(derivePitchOf({}), { ok: true, value: {} });
+ assert.deepEqual(derivePitchOf({ pitch: null, semitones: "" }), { ok: true, value: {} }, "a query with neither");
+ assert.deepEqual(derivePitchOf({ pitch: "contour", semitones: 2 }), { ok: true, value: { pitch: "contour", semitones: 2 } });
+ assert.deepEqual(derivePitchOf({ pitch: "source", semitones: "-1.5" }), { ok: true, value: { pitch: "source", semitones: -1.5 } });
+ assert.deepEqual(derivePitchOf({ pitch: "target" }), { ok: true, value: { pitch: "target" } });
+ assert.deepEqual(derivePitchOf({ semitones: 0 }), { ok: true, value: { semitones: 0 } }, "0 is said, not dropped: the editor's default may be another");
+ for (const [given, re] of [
+ [{ pitch: "up" }, /^pitch is one of target, source, contour \(got "up"\)$/],
+ [{ pitch: 2 }, /pitch is one of/],
+ [{ pitch: "source", semitones: 13 }, /^semitones is a number from -12 to 12 \(got 13\)$/],
+ [{ pitch: "source", semitones: "two" }, /semitones is a number from -12 to 12 \(got "two"\)/],
+ [{ pitch: "source", semitones: true }, /semitones is a number/],
+ ]) {
+ const r = derivePitchOf(given);
+ assert.equal(r.ok, false, JSON.stringify(given));
+ assert.match(r.error, re);
+ }
+ const en = derivePitchOf({ pitch: "source" }, "enhance");
+ assert.equal(en.ok, false);
+ assert.match(en.error, /pitch and semitones are a convert's: enhance keeps the read's own pitch/);
+ assert.deepEqual(derivePitchOf({}, "enhance"), { ok: true, value: {} });
+});
+
+test("a convert derive is the character's: what the ask names wins, the rest is its recorded preset's, and no voice is refused", () => {
+ const savvy = { engine: "seed-vc", voice: "orpheus:mia", pitch: "contour", semitones: 2 };
+ // No flags: the character's, whole (the 11 Nov bug: the editor's default voice was asked instead).
+ assert.deepEqual(convertAskOf({}, savvy, "madam-savvy"), { ok: true, value: savvy, from: "character" });
+ assert.deepEqual(convertAskOf({ engine: null, voice: null }, savvy, "madam-savvy").value, savvy, "a flag not given is null");
+ // Each key by itself.
+ assert.deepEqual(convertAskOf({ semitones: 0 }, savvy).value, { ...savvy, semitones: 0 }, "0 is asked, not absent");
+ assert.deepEqual(convertAskOf({ pitch: "source" }, savvy).value, { ...savvy, pitch: "source" }, "the nudge goes with another followed pitch");
+ assert.deepEqual(convertAskOf({ pitch: "target" }, savvy).value, { engine: "seed-vc", voice: "orpheus:mia", pitch: "target" }, "the target's own pitch takes no semitones");
+ assert.deepEqual(convertAskOf({ voice: "orpheus:tara" }, savvy), { ok: true, value: { ...savvy, voice: "orpheus:tara" }, from: "asked" });
+ // Another engine than the character's: its pitch is not that engine's to follow.
+ assert.deepEqual(convertAskOf({ engine: "openvoice" }, savvy).value, { engine: "openvoice", voice: "orpheus:mia" });
+ assert.deepEqual(convertAskOf({ engine: "openvoice", pitch: "target" }, savvy).value, { engine: "openvoice", voice: "orpheus:mia", pitch: "target" });
+ assert.deepEqual(convertAskOf({ engine: "seed-vc" }, savvy).value, savvy, "the same engine, named");
+ // A character with only a voice (its synthetic one): the editor's engine and pitch.
+ assert.deepEqual(convertAskOf({}, { engine: null, voice: "kokoro:am_puck" }, "anon-a").value, { engine: null, voice: "kokoro:am_puck" });
+ // No character: the flags alone; none: refused in one sentence, with what answers it.
+ assert.deepEqual(convertAskOf({ voice: "zac" }, null), { ok: true, value: { engine: null, voice: "zac" }, from: "asked" });
+ const none = convertAskOf({ engine: "seed-vc", pitch: "contour" }, null);
+ assert.equal(none.ok, false);
+ assert.equal(none.error, "a convert needs a stock voice to convert to, and this post has no character with one");
+ assert.match(none.fix, /--voice <engine:voice>, --as <character>/);
+ const mute = convertAskOf({}, { engine: null, voice: null }, "ghost");
+ assert.equal(mute.error, "a convert needs a stock voice to convert to, and ghost has none");
+ assert.match(mute.fix, /umtool cast set ghost --convert-voice/);
+});
+
+test("the step keeps the pitch the editor ran, else the one asked; never the target's own, never 0 semitones", () => {
+ assert.deepEqual(stepPitchOf({}, {}), {});
+ assert.deepEqual(stepPitchOf({ pitch: "target" }, {}), {});
+ assert.deepEqual(stepPitchOf({ pitch: "contour", semitones: 2 }, {}), { pitch: "contour", semitones: 2 }, "an editor that says nothing");
+ assert.deepEqual(stepPitchOf({ pitch: "source", semitones: 0 }, null), { pitch: "source" });
+ // The editor's default, when none was asked.
+ assert.deepEqual(stepPitchOf({}, { pitch: "contour", semitones: 2 }), { pitch: "contour", semitones: 2 });
+ // What it ran beats what was asked (its settings' semitones under an asked pitch).
+ assert.deepEqual(stepPitchOf({ pitch: "source" }, { pitch: "source", semitones: -1 }), { pitch: "source", semitones: -1 });
+ assert.deepEqual(stepPitchOf({ pitch: "contour", semitones: 2 }, { pitch: "target" }), {});
+ assert.deepEqual(stepPitchOf({}, { pitch: "sideways" }), {}, "not a pitch the manifest takes");
+ // Whatever it returns is a step the manifest's validator takes.
+ for (const p of [{ pitch: "contour", semitones: 2 }, { pitch: "source" }, {}]) {
+ const entry = { id: "p-1", narration: { script: "x", takes: [{ file: "narration/posts/1/take-2.convert-seed-vc.wav", engine: "derived", voice: "af_bella", seconds: 1, source: { kind: "take", from: "take-1.recorded-operator" }, steps: [{ op: "convert", engine: "seed-vc", voice: "kokoro:af_bella", ...stepPitchOf(p, {}) }] }], pick: 0 } };
+ assert.deepEqual(validatePostNarration(entry).filter((e) => /steps/.test(e)), [], JSON.stringify(p));
+ }
+});
+
+test("an editor refusal: no engine, an ordinary error, or a missing optional model said in the editor's words", () => {
+ assert.deepEqual(deriveRefusalOf("enhance", 404, "HTTP 404"), { installed: false, error: "the editor has no enhance engine installed (not installed: HTTP 404)" });
+ assert.deepEqual(
+ deriveRefusalOf("convert", 400, "the editor refused it: OpenVoice v2 is not installed (/v/openvoice): missing the python venv — run `archilyzer voice setup --engine openvoice`"),
+ { installed: false, error: "the editor has no convert engine installed (not installed: OpenVoice v2 is not installed (/v/openvoice): missing the python venv — run `archilyzer voice setup --engine openvoice`)" },
+ );
+ // seed-vc IS installed; its pitch-following model is not: the editor's sentence, as it is.
+ const f0 = "pitch \"source\" needs Seed-VC (v1, 22 kHz speech)'s f0 model, which is not installed (/v/seed-vc: missing rmvpe.pt) — run `archilyzer voice setup --engine seed-vc --with f0`";
+ assert.deepEqual(deriveRefusalOf("convert", 400, `the editor refused it: ${f0}`), { installed: false, error: f0 });
+ assert.equal(/no convert engine/.test(deriveRefusalOf("convert", 400, f0).error), false);
+ // Not about an install: the caller answers it as the error it is.
+ assert.equal(deriveRefusalOf("convert", 400, "OpenVoice v2 (tone-colour converter) has no pitch control — it lands every read on the target's own pitch"), null);
+ assert.equal(deriveRefusalOf("convert", 400, "\"semitones\" moves a followed pitch"), null);
+});
diff --git a/umtool/lib/report/fetchWindows.mjs b/umtool/lib/report/fetchWindows.mjs
@@ -63,7 +63,7 @@ export const isMontage = (manifest) =>
*
* @param {Record<string, any>} manifest
* @param {{ manifestPath: string, project: string, rulings?: { rulings: Record<string, { verdict: string }> } | null, reason?: string | null }} opts
- * @returns {{ body: { requestedBy: string, manifest: string, storedUrl: "fallback", items: Record<string, any>[] }, skipped: { clipId: string, why: string }[] }}
+ * @returns {{ body: { requestedBy: string, manifest: string, storedUrl: "fallback", archive?: string, items: Record<string, any>[] }, skipped: { clipId: string, why: string }[] }}
*/
export function fetchWindowsBody(manifest, { manifestPath, project, rulings = null, reason = null }) {
const montage = isMontage(manifest);
@@ -106,8 +106,18 @@ export function fetchWindowsBody(manifest, { manifestPath, project, rulings = nu
});
}
}
+ // The archive the cut cites (demo epic D1): its provenance.siteOrigin. The
+ // editor registers a channel it does not hold as remote-only only when that
+ // origin is a CONNECTED archive; any other origin changes nothing.
+ const site = typeof manifest?.provenance?.siteOrigin === "string" ? manifest.provenance.siteOrigin.trim().replace(/\/+$/, "") : "";
return {
- body: { requestedBy: `umtool:${project}`, manifest: path.resolve(manifestPath), storedUrl: "fallback", items },
+ body: {
+ requestedBy: `umtool:${project}`,
+ manifest: path.resolve(manifestPath),
+ storedUrl: "fallback",
+ ...(/^https?:\/\//.test(site) ? { archive: site } : {}),
+ items,
+ },
skipped,
};
}
diff --git a/umtool/lib/report/knobsCli.mjs b/umtool/lib/report/knobsCli.mjs
@@ -59,7 +59,7 @@ export const VERTICAL_SET_KEYS = Object.freeze(["vertical", "vertical.crop", "ve
export const SIDE_SET_KEYS = Object.freeze(["side", "side.item", "side.post", "side.from", "side.to", "side.place"]);
const SET_KEYS = [
"claim", ...CLAIM_KNOBS.map((k) => `claim.${k}`), ...MARK_KEYS, ...AUDIO_KNOBS.map((k) => `audio.${k}`), ...BLUR_KNOBS.map((k) => `blur.${k}`), "layout", ...REVIEW_KEYS,
- ...FX_KEYS, ...GAP_KEYS, "chat", "hideModules", "shelfNote",
+ ...FX_KEYS, ...GAP_KEYS, "chat", "hideModules", "shelfNote", "chapter",
// The vertical format (lane vertical): the clip's 9:16 crop and layout, and its side post.
...VERTICAL_SET_KEYS, ...SIDE_SET_KEYS,
];
@@ -105,6 +105,8 @@ export const SET_USAGE = [
" footage no dodge can know of; any entry, a post item too): goals peak promise diet streak; `hideModules=` none.",
" shelfNote='Weighed in on camera' puts one line (≤ 80 characters) on the shelf (render.chrome.deck.shelf, its",
" `note` slot) over this entry's span, coming and going with it; any entry; `shelfNote=` none.",
+ " chapter='The weigh-in' names this entry in the chapter list (out/chapters, youtube.txt) in place of its on-screen",
+ " title or the line derived from its record: one line, ≤ 100 characters; any entry; `chapter=` none.",
" --take <t>: the entry knobs (not claim.* or marks) land in takes/<t>/take.json's patch, an undo point first",
" (`umtool timeline <p> --take <t> undo`); the project's manifest is untouched.",
" vertical.crop='[x,y,w,h]' (fractions of the source: the 9:16 box a vertical render cuts; vertical.aspect the",
@@ -119,7 +121,9 @@ export const SET_USAGE = [
].join("\n");
export const LOOK_USAGE = [
- "usage: umtool look <project> key=value … [--unset render.<key>]… [--json]",
+ "usage: umtool look <project> key=value … [--unset render.<key>]… [--take <t>] [--json]",
+ " --take <t>: the deck.* keys given are set on THAT TAKE (its patch, an undo point of its own:",
+ " umtool timeline <p> --take <t> undo); the project's manifest is untouched. deck.* keys only",
" chrome.layout=deck: the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck)",
" --unset render.<key>: drop a legacy render key (rail chromeEngine railEngine chromeRegions claimSchedule wordmark",
" title finale cut) -- with chrome.layout=deck in ONE write (the deck refuses the old rail beside it), an undo point first",
@@ -245,6 +249,11 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso
entryPatch.shelfNote = value === null || value === undefined ? null : String(value);
continue;
}
+ if (key === "chapter") {
+ // The entry's name in the chapter list (manifest.mjs parseEntryChapter checks it); words whatever they parse as.
+ entryPatch.chapter = value === null || value === undefined ? null : String(value);
+ continue;
+ }
if (key === "hideModules") {
// The modules hidden over this entry's span (deck.mjs parseHideModules checks the ids); `hideModules=` none.
entryPatch.hideModules = value === null || value === undefined ? null : value;
@@ -334,6 +343,7 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso
if (take) results.take = { id: take, undo: result.revision?.rel ? `takes/${take}/${result.revision.rel}` : null };
if ("hideModules" in entryPatch) results.hideModules = result.entry.hideModules ?? null;
if ("shelfNote" in entryPatch) results.shelfNote = result.entry.shelfNote ?? null;
+ if ("chapter" in entryPatch) results.chapter = result.entry.chapter ?? null;
if ("audio" in entryPatch) results.audio = result.entry.audio ?? null;
if ("blur" in entryPatch) results.blur = result.entry.blur ?? null;
if ("layout" in entryPatch) results.layout = result.entry.layout ?? "clip";
@@ -371,6 +381,7 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso
if ("layout" in results) out(`${clipId}: layout ${results.layout}`);
if ("hideModules" in results) out(`${clipId}${results.take ? ` (take ${results.take.id})` : ""}: hideModules ${results.hideModules ? `${results.hideModules.join(", ")} (hidden over its span)` : "none"}`);
if ("shelfNote" in results) out(`${clipId}${results.take ? ` (take ${results.take.id})` : ""}: shelfNote ${results.shelfNote ? JSON.stringify(results.shelfNote) + " (on the shelf over its span)" : "none"}`);
+ if ("chapter" in results) out(`${clipId}${results.take ? ` (take ${results.take.id})` : ""}: chapter ${results.chapter ? JSON.stringify(results.chapter) + " (its name in the chapter list)" : "none (named by its on-screen title, else its record)"}`);
if (results.take?.undo) out(` undo point: ${results.take.undo} (umtool timeline ${project.id} --take ${results.take.id} undo)`);
if ("chat" in results) out(`${clipId}: chat ${results.chat === true ? "on (its video's live_chat.cues.json beside the footage; the build says if there is none)" : results.chat === false ? "off" : "default (off)"}`);
if ("fx" in results) out(`${clipId}: fx ${results.fx ? JSON.stringify(results.fx) : "none"}`);
@@ -480,6 +491,45 @@ export async function lookCommand(args, { root = REPORTS_ROOT, out = (s) => cons
}
const project = await projectOf(projectArg, root);
const pairs = parseAssignments(rest);
+ // A TAKE'S DECK KEYS (`--take <t>`, 12 Nov: `deck.goals.baseMaxDays` for one take): the same write over the take's
+ // manifest, landing in its patch with an undo point of the take's own (takeScope.mjs) -- the project's manifest
+ // untouched. The deck's keys only: the other knobs here are the project's.
+ if (flags.has("--take")) {
+ const take = typeof flags.get("--take") === "string" && flags.get("--take") ? String(flags.get("--take")) : null;
+ if (!take) throw new CliError("--take needs a take id");
+ const other = pairs.filter(([k]) => !k.startsWith("deck."));
+ if (other.length || flags.has("--unset")) {
+ throw new CliError(`--take sets a take's deck keys (deck.<key>=…); ${other.length ? other.map(([k]) => k).join(", ") : "--unset"} is the project's (set it without --take)`);
+ }
+ const { isTakeId, takesDirOf, TAKE_FILE } = await import("./takes.mjs");
+ if (!isTakeId(take)) throw new CliError(`"${take}" is not a take id (lower-case letters, digits, dashes)`);
+ const { stat } = await import("node:fs/promises");
+ const { default: nodePath } = await import("node:path");
+ if (!(await stat(nodePath.join(takesDirOf(project.dir), take, TAKE_FILE)).catch(() => null))) {
+ err(`${project.id} has no take ${take} (no takes/${take}/${TAKE_FILE})`);
+ return 1;
+ }
+ const busy = await (await import("./takeImport.mjs")).takeRenderingNow(project.dir, take);
+ if (busy) {
+ err(`not edited: ${busy}`);
+ return 1;
+ }
+ const { withTakeScope } = await import("./takeScope.mjs");
+ const lines = [];
+ const code = await withTakeScope(project.dir, take, () =>
+ lookCommand([projectArg, ...rest, ...(json ? ["--json"] : [])], { root, out: (l) => lines.push(l), err }));
+ if (json && code === 0) {
+ for (const l of lines) {
+ let doc = null;
+ try { doc = JSON.parse(l); } catch { /* a line of prose */ }
+ out(doc && typeof doc === "object" ? JSON.stringify({ ...doc, take: { id: take, undo: `umtool timeline ${project.id} --take ${take} undo` } }, null, 2) : l);
+ }
+ } else {
+ for (const l of lines) out(l);
+ if (code === 0) out(`take ${take}: written to its patch (undo: umtool timeline ${project.id} --take ${take} undo)`);
+ }
+ return code;
+ }
// THE DECK ON, LEGACY KEYS OFF (updateRenderKeys): `chrome.layout=deck` (render.chrome created when the cut has
// none) and `--unset render.<key>`, in one write with an undo point -- before any deck.* key, which needs the chrome.
const chromeOn = pairs.filter(([k]) => k === "chrome.layout" || k === "chrome.engine");
diff --git a/umtool/lib/report/knobsCli.test.mjs b/umtool/lib/report/knobsCli.test.mjs
@@ -342,3 +342,60 @@ test("umtool look chrome.layout=deck --unset render.<key>: the deck turned on an
assert.equal(await run("fresh", "chrome.layout=deck", "deck.sectionTitle=true"), 0, lines.join("\n"));
assert.deepEqual((await read(fresh)).render.chrome.deck, { sectionTitle: true });
});
+
+test("umtool look deck.<key>=… --take <t>: the take's patch, an undo point of the take's, the project's manifest untouched; deck keys only", async () => {
+ const dir = await project("looktake");
+ const { lines, run } = runner(lookCommand);
+ const { draftTake } = await import("./takeMaker.mjs");
+ const { resolveTakeManifest } = await import("./takeManifest.mjs");
+ await draftTake(dir, { id: "a9", label: "A9", patch: {} });
+ const before = await readFile(path.join(dir, "video.manifest.json"), "utf8");
+ assert.equal(await run("looktake", "deck.goals.base=true", "deck.goals.baseMaxDays=365", "--take", "a9"), 0, lines.join("\n"));
+ assert.match(lines.join("\n"), /deck\.goals: \{"base":true,"baseMaxDays":365\}/);
+ assert.match(lines.at(-1), /take a9: written to its patch \(undo: umtool timeline looktake --take a9 undo\)/);
+ assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), before);
+ assert.deepEqual((await resolveTakeManifest(dir, "a9")).manifest.render.chrome.deck.goals, { base: true, baseMaxDays: 365 });
+ // One field off again keeps the rest.
+ assert.equal(await run("looktake", "deck.goals.baseMaxDays=", "--take", "a9"), 0, lines.join("\n"));
+ assert.deepEqual((await resolveTakeManifest(dir, "a9")).manifest.render.chrome.deck.goals, { base: true });
+ // The build's rules still refuse; other knobs and a take that is not there are refused.
+ assert.equal(await run("looktake", "deck.goals.baseMaxDays=-3", "--take", "a9"), 1);
+ assert.match(lines.at(-1), /baseMaxDays must be null \(every base counts\) or whole days/);
+ assert.equal(await run("looktake", "transition=0.3", "--take", "a9"), 2);
+ assert.match(lines.at(-1), /--take sets a take's deck keys/);
+ assert.equal(await run("looktake", "deck.goals.baseMaxDays=365", "--take", "nope"), 1);
+ assert.match(lines.at(-1), /has no take nope/);
+ assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), before);
+});
+
+test("umtool set chapter='…': an entry's name in the chapter list, any entry; chapter= clears; --take writes the take's patch", async () => {
+ const dir = await project("chapter");
+ const m = await read(dir);
+ m.timeline.push({ type: "post", id: "x01", item: "123" });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n");
+ const { lines, run } = runner(setCommand);
+ assert.equal(await run("chapter", "c02", "chapter= The weigh-in "), 0, lines.join("\n"));
+ assert.equal((await read(dir)).timeline[1].chapter, "The weigh-in", "trimmed");
+ assert.match(lines.at(-1), /c02: chapter "The weigh-in" \(its name in the chapter list\)/);
+ assert.equal(await run("chapter", "x01", "chapter=2026"), 0, lines.join("\n"));
+ assert.equal((await read(dir)).timeline[2].chapter, "2026", "a post item too; words whatever they parse as");
+ // Beside a clip's other knobs in one command.
+ assert.equal(await run("chapter", "c01", "chapter=Arrival", "audio.gain=2"), 0, lines.join("\n"));
+ assert.deepEqual([(await read(dir)).timeline[0].chapter, (await read(dir)).timeline[0].audio], ["Arrival", { gain: 2 }]);
+ assert.equal(await run("chapter", "c02", `chapter=${"x".repeat(101)}`), 1);
+ assert.match(lines.at(-1), /chapter is 101 characters \(at most 100\)/);
+ assert.equal((await read(dir)).timeline[1].chapter, "The weigh-in", "a refused write changes nothing");
+ assert.equal(await run("chapter", "c02", "chapter="), 0);
+ assert.equal("chapter" in (await read(dir)).timeline[1], false);
+ assert.match(lines.at(-1), /c02: chapter none/);
+ const { draftTake } = await import("./takeMaker.mjs");
+ const { resolveTakeManifest } = await import("./takeManifest.mjs");
+ await draftTake(dir, { id: "a9", label: "A9", patch: {} });
+ const before = await readFile(path.join(dir, "video.manifest.json"), "utf8");
+ assert.equal(await run("chapter", "c02", "chapter=Day 41", "--take", "a9"), 0, lines.join("\n"));
+ assert.match(lines.join("\n"), /c02 \(take a9\): chapter "Day 41"/);
+ assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), before);
+ assert.equal((await resolveTakeManifest(dir, "a9")).manifest.timeline[1].chapter, "Day 41");
+ assert.equal(await run("chapter", "x01", "chapter=", "--take", "a9"), 0, lines.join("\n"));
+ assert.equal("chapter" in (await resolveTakeManifest(dir, "a9")).manifest.timeline[2], false);
+});
diff --git a/umtool/lib/report/ledgerCli.mjs b/umtool/lib/report/ledgerCli.mjs
@@ -28,7 +28,9 @@ export const LEDGER_USAGE = [
"instruments' own: run (a loss claim's run, his words placing it), retro (a loss told in the past with no asOf:",
"off the odometer), promise (a promise_check's or promise_claim's promise), kept, due (YYYY-MM-DD), speaker (another",
"party's key: a promise_claim's -- her rows move none of his numbers), paidOn (YYYY-MM-DD), outcome (a",
- "promise_outcome's: kept, refunded, withdrawn)) or a declared field; `null`",
+ "promise_outcome's: kept, refunded, withdrawn), stampNote (a promise_outcome's: the words under its stamp on the",
+ "promise clock in place of \"by <date> · no video\" -- one line; the strip shows its first clause; `umtool lint` warns",
+ "past 26 characters)) or a declared field; `null`",
"clears a value. rm refuses a row a timeline entry pins or another row names.",
].join("\n");
diff --git a/umtool/lib/report/ledgerCli.test.mjs b/umtool/lib/report/ledgerCli.test.mjs
@@ -118,6 +118,15 @@ test("umtool ledger: add, set, unset, rm -- through the writers, on the file", a
assert.equal(await run(ledgerCommand, "weigh", "add", "o02", "--date", "2026-10-31", "--scope", "weight", "--population", "promise_outcome",
"--promise", "p01", "--outcome", "forgotten", "--scopeBasis", "x"), 1);
assert.match(lines.at(-1), /outcome kept, refunded, withdrawn/);
+ // The words under its stamp (`stampNote`): a promise_outcome's, one line; null takes them off again.
+ assert.equal(await run(ledgerCommand, "weigh", "set", "o01", "--stampNote", "by her account · no receipt"), 0, lines.join("\n"));
+ assert.equal((await manifestOf(dir)).ledger.find((r) => r.id === "o01").stampNote, "by her account · no receipt");
+ assert.equal(await run(ledgerCommand, "weigh", "set", "o01", "--stampNote", "x".repeat(81)), 1);
+ assert.match(lines.at(-1), /stampNote is one line of 1–80 characters/);
+ assert.equal(await run(ledgerCommand, "weigh", "set", "p01", "--stampNote", "nope"), 1);
+ assert.match(lines.at(-1), /stampNote is a promise_outcome's/);
+ assert.equal(await run(ledgerCommand, "weigh", "set", "o01", "--stampNote", "null"), 0, lines.join("\n"));
+ assert.equal((await manifestOf(dir)).ledger.find((r) => r.id === "o01").stampNote ?? null, null);
assert.equal(await run(ledgerCommand, "weigh", "rm", "o01"), 0);
assert.equal(await run(ledgerCommand, "weigh", "rm", "s01"), 0);
// A loss told in the past: off the odometer; then put back on it.
diff --git a/umtool/lib/report/ledgerRows.mjs b/umtool/lib/report/ledgerRows.mjs
@@ -18,7 +18,7 @@
// subject) is a lower-case key; another speaker's row moves none of his
// numbers (measure-slice.mjs).
import {
- EVENTS, LEDGER_BUILTIN_KEYS, PROMISE_FORMS, PROMISE_OUTCOMES, SCOPE_CONFIDENCE, VALUE_KINDS, measureDisplay, measureGaps, measureSchema, validateFields,
+ EVENTS, LEDGER_BUILTIN_KEYS, PROMISE_FORMS, PROMISE_OUTCOMES, SCOPE_CONFIDENCE, STAMP_NOTE, VALUE_KINDS, measureDisplay, measureGaps, measureSchema, validateFields,
} from "umtool-report-to-video/ledger-totals";
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
@@ -35,7 +35,7 @@ export const LEDGER_KEY_TYPES = Object.freeze({
display: "text?", label: "text?", quote: "text?", deadline: "text?", src: "text?", channel: "text?", video: "text?",
cite: "seconds?", citeFrom: "text?", scopeBasis: "text", scopeConfidence: "text", valueKind: "text", flags: "list",
hedged: "bool?", unsourced: "bool?", plotted: "bool?", hidden: "bool?", entryId: "text?", authorNote: "text?",
- run: "run?", retro: "bool?", promise: "text?", kept: "bool?", due: "day?", speaker: "speaker?", paidOn: "day?", outcome: "text?",
+ run: "run?", retro: "bool?", promise: "text?", kept: "bool?", due: "day?", speaker: "speaker?", paidOn: "day?", outcome: "text?", stampNote: "text?",
});
/** Is this manifest's ledger a measure ledger (the one these writers write)? */
@@ -143,6 +143,13 @@ export function ledgerRowOf(manifest, base, patch, { unset = [] } = {}) {
if (row.population === "promise_outcome") {
if (!PROMISE_OUTCOMES.includes(row.outcome)) errors.push(`a promise_outcome says how it ended: outcome ${PROMISE_OUTCOMES.join(", ")}`);
} else if (row.outcome !== undefined && row.outcome !== null) errors.push("outcome is a promise_outcome's");
+ // The words under the outcome's stamp on the promise clock (measure-extras.mjs STAMP_NOTE): one line of text.
+ if (row.stampNote !== undefined && row.stampNote !== null) {
+ if (row.population !== "promise_outcome") errors.push("stampNote is a promise_outcome's (the words under its stamp)");
+ else if (typeof row.stampNote !== "string" || !row.stampNote.trim() || /[\n\r]/.test(row.stampNote) || row.stampNote.trim().length > STAMP_NOTE.max) {
+ errors.push(`stampNote is one line of 1–${STAMP_NOTE.max} characters (the stamp's second line; past ${STAMP_NOTE.fit} the lint warns it may not fit)`);
+ }
+ }
if (["promise_check", "promise_claim", "promise_outcome"].includes(row.population)) {
const p = ledger.find((r) => r?.id === row.promise);
if (!row.promise) errors.push(`a ${row.population} names its promise (--promise <row id>)`);
diff --git a/umtool/lib/report/linkCheck.mjs b/umtool/lib/report/linkCheck.mjs
@@ -28,7 +28,7 @@
// Plain ESM: the CLI runs it under bare node.
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import path from "node:path";
-import { createJsonCache, DEFAULT_CACHE_DIR, pagesVersionOf, pageUrlFrom } from "umtool-report-to-video/cues";
+import { createJsonCache, DEFAULT_CACHE_DIR, pagesVersionOf, pageUrlFrom, transcriptsManifestUrl } from "umtool-report-to-video/cues";
import { qrsOf } from "umtool-report-to-video/lint";
import { jitterUp } from "yt-dlp-transcript-common/lib/jitter.mjs";
import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
@@ -213,11 +213,13 @@ export async function checkLinks(
});
continue;
}
- const manifestUrl = ch.manifests?.transcripts;
- if (typeof manifestUrl !== "string" || !manifestUrl) {
+ if (typeof ch.manifests?.transcripts !== "string" || !ch.manifests.transcripts) {
out.push({ clip, url, state: "dead", origin: a.origin, why: `${host} publishes no transcripts for "${a.channel}"` });
continue;
}
+ // The manifest the corpus names, when it is on the archive's own origin;
+ // one named elsewhere is not followed (report-to-video/archive-fetch.mjs).
+ const manifestUrl = transcriptsManifestUrl(a.origin, ch);
const man = await channelManifest(manifestUrl);
if (!man.doc) {
out.push({ clip, url, state: "unverified", origin: a.origin, why: `couldn't read ${a.channel}'s manifest on ${host} (${man.error})` });
diff --git a/umtool/lib/report/lintCli.mjs b/umtool/lib/report/lintCli.mjs
@@ -72,9 +72,12 @@ export async function castProblems(manifest, project, reportsRoot = REPORTS_ROOT
const { readVoiceMap } = await import("./postSay.mjs");
const { resolverFor } = await import("./castProject.mjs");
const map = await readVoiceMap(project.dir).catch(() => ({}));
- const { drift, overrides } = castDrift(manifest, { cast: castRead.cast, map, resolve: resolverFor({ map, cast: castRead.cast, render: manifest?.render ?? {} }) });
+ // This video's own characters answer before the cast's (cast.mjs: the chain every read asks).
+ const { readProjectCharacters } = await import("./castStore.mjs");
+ const own = (await readProjectCharacters(project.dir)).doc;
+ const { drift, overrides } = castDrift(manifest, { cast: castRead.cast, map, resolve: resolverFor({ map, cast: castRead.cast, project: own, render: manifest?.render ?? {} }) });
return {
- warnings: drift.map((d) => `timeline ${d.id}: @${d.handle} (${d.character}) reads in ${d.reads} -- now ${d.want} (${d.from === "project" ? "the project's voice map" : d.from === "cast" ? "the cast" : d.from}): umtool cast reread ${project.id} ${d.character}`),
+ warnings: drift.map((d) => `timeline ${d.id}: @${d.handle} (${d.character}) reads in ${d.reads} -- now ${d.want} (${d.from === "project" ? (d.handle in map ? "the project's voice map" : "this video's own character") : d.from === "cast" ? "the cast" : d.from === "item" ? "the item's own character" : d.from}): umtool cast reread ${project.id} ${d.character}`),
notes: overrides.map((o) => `@${o.handle} (${o.character}) reads in ${o.project} in this project -- the cast says ${o.cast} (an override on purpose; umtool posts voices ${project.id} remove ${o.handle} follows the cast)`),
};
}
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -328,8 +328,41 @@ function applyShelfNote(entry, value) {
else delete entry.shelfNote;
}
+/** The most characters an entry's `chapter` may have: one line of a chapter list (a YouTube title's own limit). */
+export const ENTRY_CHAPTER_MAX = 100;
+
+/**
+ * An entry's `chapter` as written: its name in the chapter list (build-video.mjs chapterTitle: an authored `chapter`
+ * wins over the on-screen title and the line derived from the record). One line, at most ENTRY_CHAPTER_MAX
+ * characters, trimmed; null, "" or blank is none.
+ * @param {unknown} v
+ * @returns {{ value: string | null, error: string | null }}
+ */
+export function parseEntryChapter(v) {
+ if (v === null || v === undefined || v === "" || v === false) return { value: null, error: null };
+ if (typeof v !== "string") return { value: null, error: `chapter is words, not ${JSON.stringify(v)}` };
+ const s = v.trim();
+ if (!s) return { value: null, error: null };
+ if (/[\r\n]/.test(s)) return { value: null, error: "chapter must be one line" };
+ if ([...s].length > ENTRY_CHAPTER_MAX) return { value: null, error: `chapter is ${[...s].length} characters (at most ${ENTRY_CHAPTER_MAX})` };
+ return { value: s, error: null };
+}
+
+/**
+ * Set an entry's `chapter` (parseEntryChapter); null or "" removes it -- the chapter list names the entry by its
+ * on-screen title or its record again.
+ * @param {Record<string, unknown>} entry
+ * @param {unknown} value
+ */
+function applyChapter(entry, value) {
+ const { value: text, error } = parseEntryChapter(value);
+ if (error) throw new Error(error);
+ if (text) entry.chapter = text;
+ else delete entry.chapter;
+}
+
/** The patch keys any timeline entry may carry (a post item, a still, a clip): applied before the clip-only rules. */
-const ANY_ENTRY_KEYS = Object.freeze(["hideModules", "shelfNote"]);
+const ANY_ENTRY_KEYS = Object.freeze(["hideModules", "shelfNote", "chapter"]);
/**
* updateClip's rules over a manifest held in memory: the ONE place a clip
@@ -358,8 +391,9 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n
// So may its note on the shelf (`shelfNote`, deck.mjs entryShelfNotes).
if (patch !== RESTORE_PATCH && Object.keys(patch).length && Object.keys(patch).every((k) => ANY_ENTRY_KEYS.includes(k))) {
if (patch.hideModules !== undefined) applyHideModules(entry, patch.hideModules);
- if (patch.shelfNote !== undefined) applyShelfNote(entry, patch.shelfNote);
if (patch.shelfNote !== undefined) applyShelfNote(entry, patch.shelfNote);
+ // Its name in the chapter list (`chapter`, build-video.mjs chapterTitle).
+ if (patch.chapter !== undefined) applyChapter(entry, patch.chapter);
return { entry, before: { start: entry.start, end: entry.end } };
}
// `!== "clip"`, not `=== "card"`. The timeline's vocabulary is open -- one
@@ -781,6 +815,8 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n
}
if (patch.hideModules !== undefined) applyHideModules(entry, patch.hideModules);
+ // A clip's chapter name beside its other knobs in one patch.
+ if (patch.chapter !== undefined) applyChapter(entry, patch.chapter);
// The live-chat column beside this clip (chat.mjs): true shows it, false is
// the explicit no, null/"" removes the key (the default: off).
@@ -3307,7 +3343,7 @@ export function handlesWithoutAvatar(m, handles) {
// ---- a post item's narration (report-to-video/post-narration.mjs) ----------
/** The narration keys a write may set on one post item (post-narration.mjs; knobs.md, "A narrated post item"). */
-export const POST_NARRATION_KNOBS = Object.freeze(["script", "excerpt", "engine", "voice", "speed", "pick", "approved", "off", "lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate", "pace", "window"]);
+export const POST_NARRATION_KNOBS = Object.freeze(["script", "excerpt", "engine", "voice", "speed", "character", "pick", "approved", "off", "lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate", "pace", "window"]);
/**
* One post item's narration, changed in place (`m` the manifest inside a
diff --git a/umtool/lib/report/postAvatarStores.test.mjs b/umtool/lib/report/postAvatarStores.test.mjs
@@ -0,0 +1,140 @@
+// The archive's authors' pictures found where they are (postReel.mjs
+// archiveAvatarStores, `umtool posts avatars`, `umtool posts avatar`):
+// a project whose channels tree is a SHADOW (posts copied in, no _avatars/)
+// reads the corpus's stores behind it; a channel with no store at all does
+// not end the search; the store's "TheSubject" is the card's "thesubject"
+// (quartering-diet rev 9, 11 Nov: "copied 0 picture(s) … no picture yet for
+// @thequartering, @madamsavvy" while the corpus held both).
+//
+// Temp dirs under UMTOOL_TEST_TMP when set (a scratch dir off /tmp), else the
+// system's.
+import assert from "node:assert/strict";
+import { mkdtempSync } from "node:fs";
+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+
+const BASE = process.env.UMTOOL_TEST_TMP || tmpdir();
+await mkdir(BASE, { recursive: true });
+const ROOT = mkdtempSync(path.join(BASE, "umtool-post-avatar-stores-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+const CORPUS = path.join(ROOT, "corpus-channels");
+const REPORTS = path.join(ROOT, "reports");
+// The corpus is CHANNELS_DIR, read when paths.mjs loads: set before the imports.
+process.env.CHANNELS_DIR = CORPUS;
+delete process.env.CHANNELS_FALLBACK;
+const reel = await import("./postReel.mjs");
+const { postsCommand } = await import("./postsCli.mjs");
+
+// First-listed channel: posts only, no posts-media/ anywhere. Then a store keyed
+// "TheSubject" (as X printed it) and one keyed "MadamOther".
+const CHANNELS = ["first-x", "subj-X", "other-x"];
+
+async function store(tree, slug, doc) {
+ const dir = path.join(tree, slug, "posts-media", "_avatars");
+ await mkdir(dir, { recursive: true });
+ for (const a of Object.values(doc)) await writeFile(path.join(dir, a.file), "picture");
+ await writeFile(path.join(dir, "avatars.json"), JSON.stringify(doc, null, 2));
+}
+async function posts(tree, slug) {
+ await mkdir(path.join(tree, slug, "posts"), { recursive: true });
+ await writeFile(path.join(tree, slug, "posts", "2026-10.jsonl"), "");
+}
+
+const item = (slug, id, handle) => ({
+ type: "post", id: `p-${id}`, post: `${slug}/${id}`, platform: "x", author: handle.toUpperCase(), handle,
+ date: `2026-10-2${id}T10:00:00.000Z`, text: `post ${id}`,
+});
+
+async function project(name) {
+ const dir = path.join(REPORTS, name);
+ const shadow = path.join(dir, ".shadow-channels");
+ for (const c of CHANNELS) await posts(shadow, c);
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({
+ schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "", channelSlug: "subj-X", channelsDir: ".shadow-channels" },
+ render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" } },
+ // The first card spells the author in lower case, as a mention does.
+ timeline: [item("first-x", "1", "thesubject"), item("subj-X", "2", "TheSubject"), item("other-x", "3", "MadamOther")],
+ }, null, 2));
+ return { id: name, dir, shadow };
+}
+const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"));
+const cli = async (args) => {
+ const lines = [];
+ const errs = [];
+ const code = await postsCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => errs.push(s) });
+ return { code, out: lines.join("\n"), err: errs.join("\n") };
+};
+
+for (const c of CHANNELS) await posts(CORPUS, c);
+await store(CORPUS, "subj-X", {
+ TheSubject: { file: "TheSubject.png", url: "https://pbs.twimg.com/a.png", capturedAt: "2026-11-07T00:00:00Z" },
+ MadamOther: { file: "MadamOther.jpg", capturedAt: "2026-11-01T00:00:00Z" },
+});
+await store(CORPUS, "other-x", { MadamOther: { file: "MadamOther.jpg", url: "https://pbs.twimg.com/b.jpg", capturedAt: "2026-11-07T00:00:00Z" } });
+
+test("archiveAvatarStores: every tree, every channel; a missing _avatars/ is noted and skipped; keys any case", async () => {
+ const p = await project("unit");
+ const { store: got, searched } = await reel.archiveAvatarStores([p.shadow, CORPUS], CHANNELS);
+ assert.deepEqual([...got.keys()].sort(), ["madamother", "thesubject"]);
+ assert.equal(got.get("thesubject").handle, "TheSubject");
+ // The newest of two stores' pictures of one author.
+ assert.equal(got.get("madamother").file, path.join(CORPUS, "other-x", "posts-media", "_avatars", "MadamOther.jpg"));
+ assert.deepEqual(searched.map((s) => `${s.channel}@${s.tree === CORPUS ? "corpus" : "shadow"}:${s.state}`), [
+ "first-x@shadow:none", "first-x@corpus:none", "subj-X@shadow:none", "subj-X@corpus:read", "other-x@shadow:none", "other-x@corpus:read",
+ ]);
+ const said = reel.avatarStoresSaid(searched);
+ assert.equal(said.length, 3);
+ assert.match(said[0], /^first-x: no _avatars\/ in .*\.shadow-channels or .*corpus-channels$/);
+ assert.match(said[1], /^subj-X: 2 picture\(s\) in .*corpus-channels\/subj-X\/posts-media\/_avatars; no _avatars\/ in .*\.shadow-channels$/);
+ // One tree, as a string, as before.
+ assert.equal((await reel.archiveAvatars(CORPUS, ["subj-X"])).size, 2);
+});
+
+test("posts avatars: a shadow-channels project copies the corpus's pictures, names the stores it searched", async () => {
+ const p = await project("shadowed");
+ const r = await cli(["avatars", "shadowed"]);
+ assert.equal(r.code, 0, r.err);
+ assert.match(r.out, /^copied 2 picture\(s\) from subj-X \+ other-x's stores: /, r.out);
+ assert.doesNotMatch(r.out, /no picture yet/, r.out);
+ assert.match(r.out, /first-x: no _avatars\//);
+ const m = await manifest(p);
+ assert.equal(m.postAvatars.TheSubject.src, "posts-media/_avatars/TheSubject.png");
+ assert.equal(m.postAvatars.TheSubject.source, "archive");
+ assert.equal(m.postAvatars.MadamOther.url, "https://pbs.twimg.com/b.jpg");
+ await readFile(path.join(p.dir, "posts-media", "_avatars", "TheSubject.png"));
+ // Again: nothing more to copy, and nobody without one.
+ const again = await cli(["avatars", "shadowed", "--json"]);
+ const j = JSON.parse(again.out);
+ assert.deepEqual(j.copied, {});
+ assert.deepEqual(j.without, []);
+ assert.ok(j.stores.some((s) => s.channel === "first-x" && s.state === "none"));
+});
+
+test("posts avatars: no store anywhere says so, and names the author as the card draws them", async () => {
+ const p = await project("bare");
+ const m0 = await manifest(p);
+ m0.timeline = [item("first-x", "1", "NoPicture")];
+ await writeFile(path.join(p.dir, "video.manifest.json"), JSON.stringify(m0, null, 2));
+ const r = await cli(["avatars", "bare"]);
+ assert.equal(r.code, 0, r.err);
+ assert.match(r.out, /^copied 0 picture\(s\) from no store/);
+ assert.match(r.out, /no picture yet for @NoPicture /);
+});
+
+test("posts avatar: a handle in any case sets and clears the drawn author's picture", async () => {
+ const p = await project("manual");
+ const pic = path.join(ROOT, "manual.png");
+ await writeFile(pic, "picture");
+ assert.equal((await cli(["avatar", "manual", "@madamother", pic])).code, 0);
+ let m = await manifest(p);
+ assert.deepEqual(m.postAvatars, { MadamOther: { src: "posts-media/_avatars/MadamOther-manual.png", source: "manual" } });
+ // The archive's never replaces it.
+ assert.equal((await cli(["avatars", "manual"])).code, 0);
+ m = await manifest(p);
+ assert.equal(m.postAvatars.MadamOther.source, "manual");
+ assert.equal(m.postAvatars.TheSubject.source, "archive");
+ assert.equal((await cli(["avatar", "manual", "MADAMOTHER", "off"])).code, 0);
+ assert.equal((await manifest(p)).postAvatars.MadamOther, undefined);
+});
diff --git a/umtool/lib/report/postComboCli.mjs b/umtool/lib/report/postComboCli.mjs
@@ -16,7 +16,7 @@
// Plain ESM: the CLI runs it under bare node.
import { COMBO_DEFAULTS, COMBO_ITEM_KEYS, comboKnobs, repeatGroups } from "umtool-report-to-video/post-combo";
import { captureOnlyMedia, projectCombos } from "umtool-report-to-video/post-combo-prints";
-import { channelsDirFor, readManifest } from "../projects/report.mjs";
+import { channelsDirFor, channelsLayersFor, hasShadowChannels, readManifest } from "../projects/report.mjs";
import { withEditNotes } from "./edit-guard.mjs";
import { copyFile, mkdir, realpath, stat } from "node:fs/promises";
import path from "node:path";
@@ -45,6 +45,8 @@ export const REPEATS_USAGE = [
" umtool posts attach <project> [<item> … | --all] [--dry-run] [--json]",
" a post item with no attachment whose capture holds one (captured after it went in): its media copied in and",
" set, as posts reel would have made it -- nothing else of the entry changes. One write (one undo point).",
+ " The capture is looked for in the project's channels tree, then the archive's (read only: the files are",
+ " copied into the project); --dry-run prints the tree each file would come from.",
].join("\n");
const OFF = new Set(["off", "no", "false", "0"]);
@@ -95,7 +97,7 @@ export async function repeatsView(project, { match = null, cacheDir = undefined,
const opts = { channelsDir: corpus, ...(match ? { match } : {}), ...(cacheDir !== undefined ? { cacheDir } : {}) };
const cut = await projectCombos(project.dir, manifest, opts);
// The posts whose capture has a file their entry does not carry: in the cut's order, as if they played it.
- const captured = await captureOnlyMedia(manifest, { channelsDir: corpus });
+ const captured = await captureOnlyMedia(manifest, { channelsDirs: await captureTrees(project, manifest, channelsDir) });
const tl = (manifest.timeline ?? []).map((e) => (captured[e?.id] ? { ...e, media: captured[e.id].map((m) => ({ src: `@capture/${m.slug}/${m.name}`, kind: "capture" })) } : e));
const prints = (id, i) => (captured[id] ? { mediaId: captured[id][i]?.mediaId ?? null, sha256: captured[id][i]?.sha256 ?? null } : cut.prints[`${id}:${i}`]);
const all = repeatGroups(tl, prints, { match: cut.match });
@@ -148,8 +150,17 @@ export async function scenesView(project, { channelsDir = null } = {}) {
const TIER_WORDS = { "media-id": "X media id", sha256: "same file", audio: "same sound" };
const MATCH_WORDS = { id: "the X media id", file: "the X media id, then the file's bytes", audio: "the X media id, the bytes, then the sound" };
+/**
+ * Is this ONE path segment -- a capture's file name, a post id, a channel slug as a capture or a manifest gives them?
+ * Not empty, not `.` or `..`, no separator (either slash) and no NUL: a name is joined into a path in a channels tree
+ * and in the project, and `../../x` would read, and write, outside both.
+ */
+export const isPathSegment = (v) => typeof v === "string" && v !== "" && v !== "." && v !== ".." && !/[/\\\0]/.test(v);
+
/** Copy a capture's file into the project (never through a link out of it); the same size already there is left. */
async function copyIn(projectDir, from, rel) {
+ // Before anything is made: every segment a plain name (attachFromCaptures checks them too -- this is the writer's own).
+ if (!rel.split("/").every(isPathSegment)) throw new ComboError(`${JSON.stringify(rel)} is not a path inside the project — not copying`);
const to = path.join(projectDir, ...rel.split("/"));
const [a, b] = await Promise.all([stat(from).catch(() => null), stat(to).catch(() => null)]);
if (a && b && a.size === b.size) return;
@@ -160,20 +171,40 @@ async function copyIn(projectDir, from, rel) {
}
/**
+ * THE CHANNELS TREES A CAPTURE IS LOOKED FOR IN (12 Nov: a project with a `.shadow-channels` tree saw only that, and
+ * the captures in the real archive's `channels/<slug>/posts-media/<id>/` were invisible): the project's own tree
+ * first, then the archive behind it -- as the other readers resolve them (projects/report.mjs channelsLayersFor;
+ * `provenance.channelsFallback: false` or CHANNELS_FALLBACK=0 keeps it to the project's). READ ONLY toward both:
+ * attach copies into the project.
+ * @returns {Promise<string[]>}
+ */
+async function captureTrees(project, manifest, channelsDir = null, channelsDirs = null) {
+ if (Array.isArray(channelsDirs) && channelsDirs.length) return channelsDirs;
+ if (channelsDir) return [channelsDir];
+ return channelsLayersFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) });
+}
+
+/** A tree in words: the first is the project's own, any after it the archive's. */
+const treeKindOf = (trees, tree) => (trees.indexOf(tree) <= 0 ? "project" : "archive");
+
+/**
* ATTACH WHAT THE CAPTURES HOLD (`umtool posts attach`): each post item with no
* attachment whose capture has one (captured after it went in) gets its media
* as `posts reel` would have made it -- the files copied into the project's
* posts-media/, measured -- and nothing else of the entry changes (its
* paraphrases, narration, knobs kept). One write. `ids` narrows it.
+ * A capture is looked for in the project's channels tree, then the archive's (captureTrees); each planned item
+ * says which it came from (`tree`, `treeKind`: project | archive), and `--dry-run` prints it per file.
*
* @param {{ id: string, dir: string }} project
- * @param {{ ids?: string[] | null, dryRun?: boolean, channelsDir?: string | null }} [o]
+ * @param {{ ids?: string[] | null, dryRun?: boolean, channelsDir?: string | null, channelsDirs?: string[] | null }} [o]
+ * `channelsDirs`: the trees to look in, in order (default: the project's, then the archive's)
*/
-export async function attachFromCaptures(project, { ids = null, dryRun = false, channelsDir = null } = {}) {
+export async function attachFromCaptures(project, { ids = null, dryRun = false, channelsDir = null, channelsDirs = null } = {}) {
const manifest = await readManifest(project.dir);
if (!manifest) throw new ComboError(`${project.id} has no manifest`);
- const corpus = channelsDir ?? channelsDirFor(project.dir, manifest);
- const captured = await captureOnlyMedia(manifest, { channelsDir: corpus });
+ const trees = await captureTrees(project, manifest, channelsDir, channelsDirs);
+ const captured = await captureOnlyMedia(manifest, { channelsDirs: trees });
const tl = Array.isArray(manifest.timeline) ? manifest.timeline : [];
const want = ids ? ids.map((r) => tl.find((e) => e?.type === "post" && (e.id === r || String(e.post ?? "").split("/")[1] === r))?.id ?? r) : null;
if (want) for (const id of want) if (!tl.some((e) => e?.id === id && e.type === "post")) throw new ComboError(`no post item ${id} in ${project.id}`);
@@ -184,7 +215,11 @@ export async function attachFromCaptures(project, { ids = null, dryRun = false,
const postId = String(tl.find((e) => e?.id === id)?.post ?? "").split("/")[1];
const media = [];
for (const m of list) {
- const from = path.join(corpus, m.slug, "posts-media", postId, m.name);
+ // A capture's names are data: refused before any file is looked at, in whichever tree it was found.
+ for (const [what, v] of [["file name", m.name], ["post id", postId], ["channel", m.slug]]) {
+ if (!isPathSegment(v)) throw new ComboError(`${id}: its capture's ${what} ${JSON.stringify(v ?? null)} is not a plain name (a path separator, "." or "..", or empty) — nothing attached`);
+ }
+ const from = path.join(m.tree, m.slug, "posts-media", postId, m.name);
if (!(await stat(from).catch(() => null))) continue;
const rel = `posts-media/${m.slug}/${postId}/${m.name}`;
const probe = await probeMediaFile(from);
@@ -202,7 +237,7 @@ export async function attachFromCaptures(project, { ids = null, dryRun = false,
}
if (!media.length) continue;
patches[id] = media.map((x) => x.item);
- plan.push({ id, media: media.map((x) => ({ src: x.item.src, kind: x.item.kind, from: x.from })) });
+ plan.push({ id, tree: list[0].tree, treeKind: treeKindOf(trees, list[0].tree), media: media.map((x) => ({ src: x.item.src, kind: x.item.kind, from: x.from })) });
}
if (dryRun || !plan.length) return { dryRun, attached: plan, result: null, editNotes: null };
for (const p of plan) for (const m of p.media) await copyIn(project.dir, m.from, m.src);
@@ -210,6 +245,19 @@ export async function attachFromCaptures(project, { ids = null, dryRun = false,
return { dryRun, attached: plan.filter((p) => result.ids.includes(p.id)), result, editNotes };
}
+/** What `posts attach` prints: each item's media, and the channels tree each file is read from (a dry run: per file). */
+export function attachLines(r, projectId) {
+ const out = [`${r.dryRun ? "would attach" : "attached"} the capture's media to ${r.attached.length} post item(s) in ${projectId}`];
+ for (const a of r.attached) {
+ const whose = a.treeKind === "archive" ? "the archive's" : "the project's";
+ out.push(` ${a.id} ${a.media.map((m) => `${m.kind} ${m.src}`).join(", ")}`);
+ if (r.dryRun) for (const m of a.media) out.push(` from ${whose} channels tree: ${m.from}`);
+ else out.push(` from ${whose} channels tree (${a.tree})`);
+ }
+ if (r.result?.snapshot?.rel && !r.result.snapshot.skipped) out.push(` undo point: ${r.result.snapshot.rel} (umtool timeline ${projectId} undo)`);
+ return out;
+}
+
/** The repeats view as lines. */
export function repeatsLines(v) {
const out = [];
@@ -262,9 +310,7 @@ async function comboRun(verb, words, flags, { root, json, out, err }) {
const r = await attachFromCaptures(project, { ids: items.length ? items : null, dryRun: flags.has("--dry-run") });
if (json) out(JSON.stringify({ ok: true, ...r, result: r.result ? { ids: r.result.ids, snapshot: r.result.snapshot, token: r.result.token } : null }, null, 2));
else {
- out(`${r.dryRun ? "would attach" : "attached"} the capture's media to ${r.attached.length} post item(s) in ${project.id}`);
- for (const a of r.attached) out(` ${a.id} ${a.media.map((m) => `${m.kind} ${m.src}`).join(", ")}`);
- if (r.result?.snapshot?.rel && !r.result.snapshot.skipped) out(` undo point: ${r.result.snapshot.rel} (umtool timeline ${project.id} undo)`);
+ for (const l of attachLines(r, project.id)) out(l);
}
return 0;
}
diff --git a/umtool/lib/report/postComboCli.test.mjs b/umtool/lib/report/postComboCli.test.mjs
@@ -8,7 +8,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { after, test } from "node:test";
import { postsCommand } from "./postsCli.mjs";
-import { repeatsView } from "./postComboCli.mjs";
+import { attachFromCaptures, attachLines, isPathSegment, repeatsView } from "./postComboCli.mjs";
const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-combo-"));
after(() => rm(ROOT, { recursive: true, force: true }));
@@ -125,3 +125,96 @@ test("posts attach: the capture's media onto the item that carries none, nothing
assert.deepEqual(v.groups[0].members.map((m) => `${m.id}:${m.attached ? m.badge : "-"}`), ["p-1:1", "p-2:2", "p-3:3", "p-5:4"]);
assert.equal((await run(["attach", "att"])).code, 2, "names the items, or --all");
});
+
+test("posts attach reads every channels tree: the project's first, then the archive's -- read only; a dry run says which tree each file came from", async () => {
+ const { execFileSync } = await import("node:child_process");
+ const { readdir, stat } = await import("node:fs/promises");
+ const p = await project("trees");
+ // The project's own tree (a .shadow-channels) holds no capture of post 3; the ARCHIVE's does.
+ const shadow = path.join(p.dir, ".shadow-channels");
+ await mkdir(path.join(shadow, "obv-x"), { recursive: true });
+ const archive = path.join(ROOT, "archive-channels");
+ const capDir = path.join(archive, "obv-x", "posts-media", "3");
+ await mkdir(capDir, { recursive: true });
+ const gif = path.join(capDir, "3_1.mp4");
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=1", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-an", gif]);
+ await writeFile(path.join(capDir, "capture.json"), JSON.stringify({ media: [{ name: "3_1.mp4", url: "https://video.twimg.com/tweet_video/C.mp4" }] }));
+ const listing = async () => (await readdir(archive, { recursive: true })).sort().join("\n");
+ const archiveBefore = await listing();
+ const mtimeBefore = (await stat(gif)).mtimeMs;
+
+ // Only the project's tree, as before: nothing to attach.
+ assert.deepEqual((await attachFromCaptures(p, { channelsDirs: [shadow], dryRun: true })).attached, []);
+ // Both: found in the archive, and said so.
+ const dry = await attachFromCaptures(p, { channelsDirs: [shadow, archive], dryRun: true });
+ assert.deepEqual(dry.attached.map((a) => [a.id, a.treeKind, a.tree]), [["p-3", "archive", archive]]);
+ assert.equal(dry.attached[0].media[0].from, gif);
+ const lines = attachLines(dry, "trees");
+ assert.match(lines[0], /would attach the capture's media to 1 post item\(s\) in trees/);
+ assert.ok(lines.includes(` from the archive's channels tree: ${gif}`), lines.join("\n"));
+ assert.equal((await manifest(p)).timeline.find((e) => e.id === "p-3").media, undefined, "a dry run writes nothing");
+
+ // The project's own capture wins when both hold one.
+ const own = path.join(shadow, "obv-x", "posts-media", "3");
+ await mkdir(own, { recursive: true });
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=1", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-an", path.join(own, "3_9.mp4")]);
+ await writeFile(path.join(own, "capture.json"), JSON.stringify({ media: [{ name: "3_9.mp4", url: "https://video.twimg.com/tweet_video/D.mp4" }] }));
+ const both = await attachFromCaptures(p, { channelsDirs: [shadow, archive], dryRun: true });
+ assert.deepEqual(both.attached.map((a) => [a.treeKind, a.media[0].src]), [["project", "posts-media/obv-x/3/3_9.mp4"]]);
+ assert.ok(attachLines(both, "trees").some((l) => l.startsWith(" from the project's channels tree: ")));
+ await rm(own, { recursive: true, force: true });
+
+ // The write: copied INTO the project; the archive is exactly as it was.
+ const done = await attachFromCaptures(p, { channelsDirs: [shadow, archive] });
+ assert.deepEqual(done.attached.map((a) => a.id), ["p-3"]);
+ assert.ok(attachLines(done, "trees").includes(` from the archive's channels tree (${archive})`));
+ const e = (await manifest(p)).timeline.find((x) => x.id === "p-3");
+ assert.equal(e.media[0].src, "posts-media/obv-x/3/3_1.mp4");
+ const copied = await stat(path.join(p.dir, "posts-media", "obv-x", "3", "3_1.mp4"));
+ assert.ok(copied.isFile() && !copied.isSymbolicLink());
+ assert.equal(await listing(), archiveBefore, "nothing added to the archive");
+ assert.equal((await stat(gif)).mtimeMs, mtimeBefore, "its file untouched");
+});
+
+test("posts attach refuses a capture whose file name is not a plain name, before any file is touched -- in either tree", async () => {
+ const { readdir } = await import("node:fs/promises");
+ for (const bad of ["../../x", "a/b", "..", ".", "a\\b"]) assert.equal(isPathSegment(bad), false, bad);
+ assert.equal(isPathSegment(""), false);
+ assert.equal(isPathSegment("3_1.mp4"), true);
+ let n = 0;
+ for (const bad of ["../../x", "a/b", ".."]) {
+ for (const where of ["project", "archive"]) {
+ n += 1;
+ const p = await project(`bad${n}`);
+ const shadow = path.join(p.dir, ".shadow-channels");
+ const archive = path.join(ROOT, `bad-archive-${n}`);
+ const tree = where === "project" ? shadow : archive;
+ const capDir = path.join(tree, "obv-x", "posts-media", "3");
+ await mkdir(capDir, { recursive: true });
+ await mkdir(shadow, { recursive: true });
+ await mkdir(archive, { recursive: true });
+ // A file where the name points, so only the check stands between it and a read.
+ await writeFile(path.join(tree, "x"), "OUTSIDE");
+ await writeFile(path.join(capDir, "capture.json"), JSON.stringify({ media: [{ name: bad, url: "https://video.twimg.com/tweet_video/C.mp4" }] }));
+ const before = (await readdir(p.dir, { recursive: true })).sort().join("\n");
+ const manifestBefore = await readFile(path.join(p.dir, "video.manifest.json"), "utf8");
+ for (const dryRun of [true, false]) {
+ await assert.rejects(attachFromCaptures(p, { channelsDirs: [shadow, archive], dryRun }), (e) => {
+ assert.match(e.message, /p-3: its capture's file name .* is not a plain name/, `${bad} in the ${where}'s tree`);
+ return true;
+ });
+ }
+ assert.equal((await readdir(p.dir, { recursive: true })).sort().join("\n"), before, "no directory made in the project");
+ assert.equal(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"), manifestBefore);
+ // The CLI says it and exits 2.
+ if (where === "project") {
+ const m = JSON.parse(manifestBefore);
+ m.provenance.channelsDir = shadow;
+ await writeFile(path.join(p.dir, "video.manifest.json"), JSON.stringify(m, null, 2));
+ const r = await run(["attach", `bad${n}`, "--all", "--dry-run"]);
+ assert.equal(r.code, 2, r.out + r.err);
+ assert.match(r.err, /is not a plain name/);
+ }
+ }
+ }
+});
diff --git a/umtool/lib/report/postNarration.test.mjs b/umtool/lib/report/postNarration.test.mjs
@@ -8,7 +8,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { after, test } from "node:test";
import { postsCommand } from "./postsCli.mjs";
-import { importPatches, makeTake, mixPatchOf } from "./postNarrationCli.mjs";
+import { importPatches, makeTake, mixPatchOf, pitchFlags } from "./postNarrationCli.mjs";
import { fitPostItem, rmsFrames, scanAttachment, scoreWindows } from "./postFit.mjs";
import { manifestToken, updatePostNarration } from "./manifest.mjs";
import { postItemPlan } from "umtool-report-to-video/post-item";
@@ -292,6 +292,7 @@ test("a DERIVED take: run through the editor's op into a new take, the original
});
assert.equal(asked.at(-1).route, "/api/ops/voice-enhance");
assert.equal("voice" in asked.at(-1).body, false);
+ assert.equal("pitch" in asked.at(-1).body, false);
assert.equal(e1.take.voice, "operator");
assert.deepEqual([e1.take.steps[0].op, e1.take.steps[0].engine, e1.take.steps[0].voice], ["enhance", "deepfilternet", undefined]);
// A convert that named no target: the stock voice the editor landed on.
@@ -302,7 +303,26 @@ test("a DERIVED take: run through the editor's op into a new take, the original
assert.equal("voice" in asked.at(-1).body, false);
assert.equal(c1.take.voice, "zac");
assert.deepEqual([c1.take.steps[0].engine, c1.take.steps[0].voice], ["openvoice", "zac"]);
- for (const k of [3, 2]) await deleteTake(p, (await manifest(p)).timeline[0], k);
+ // A convert's PITCH goes as asked, and the step keeps what the editor says it ran.
+ const c2 = await deriveTake(p, (await manifest(p)).timeline[0], {
+ from: 0, op: "convert", engine: "seed-vc", voice: "kokoro:af_bella", pitch: "contour", semitones: 2,
+ ask: async (route, body) => { asked.push({ route, body }); wav(body.out, 1.5); return { jobId: "job-p", result: { op: "convert", engine: "seed-vc", voice: "af_bella", pitch: "contour", semitones: 2, f0: { targetHz: 197.5, sourceHz: 208.8, shiftSemitones: 1.04 } } }; },
+ });
+ assert.deepEqual([asked.at(-1).body.pitch, asked.at(-1).body.semitones], ["contour", 2]);
+ assert.deepEqual([c2.take.steps[0].pitch, c2.take.steps[0].semitones, c2.take.voice], ["contour", 2, "af_bella"]);
+ // Asked of an enhance, a pitch is not sent; the flags' values are checked in their own names.
+ const e2 = await deriveTake(p, (await manifest(p)).timeline[0], {
+ from: 0, op: "enhance", pitch: "source", semitones: 2,
+ ask: async (route, body) => { asked.push({ route, body }); wav(body.out, 1.5); return { jobId: "job-e2", result: { op: "enhance", engine: "deepfilternet" } }; },
+ });
+ assert.deepEqual(["pitch" in asked.at(-1).body, "semitones" in asked.at(-1).body, "pitch" in e2.take.steps[0]], [false, false, false]);
+ const flag = (o) => pitchFlags((k) => o[k] ?? null);
+ assert.deepEqual(flag({}), {});
+ assert.deepEqual(flag({ "--pitch": "source", "--semitones": "-2.5" }), { pitch: "source", semitones: -2.5 });
+ assert.throws(() => flag({ "--pitch": "up" }), /--pitch is one of target, source, contour \(got up\)/);
+ assert.throws(() => flag({ "--semitones": "20" }), /--semitones is a number from -12 to 12 \(got 20\)/);
+ assert.throws(() => flag({ "--semitones": "" }), /--semitones is a number/);
+ for (const k of [5, 4, 3, 2]) await deleteTake(p, (await manifest(p)).timeline[0], k);
// An op the editor has no engine for.
const { OpNotInstalled } = await import("umtool-report-to-video/narrate-via-editor");
await assert.rejects(
diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs
@@ -24,8 +24,10 @@ import { mkdir, readFile, readdir, rename, stat } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import {
- NARRATION_INDEX, POST_DERIVE_OPS, POST_DERIVE_ROUTES, derivedFileOf, draftScript, takeIdOf, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takesDirOf,
+ NARRATION_INDEX, POST_DERIVE_OPS, POST_NARRATION_LIMITS, POST_DERIVE_ROUTES, derivedFileOf, draftScript, takeIdOf, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takesDirOf,
} from "umtool-report-to-video/post-narration";
+import { CAST_CONVERT_PITCH, CAST_SEMITONES_MAX, convertPitchLabel } from "umtool-report-to-video/cast";
+import { convertAskOf, stepPitchOf } from "./derivePitch.mjs";
import { excerptSpansOf, postItemPlan, postReadText } from "umtool-report-to-video/post-item";
import { partRoles } from "umtool-report-to-video/post-thread";
import { spokenRead } from "umtool-report-to-video/post-redact";
@@ -44,9 +46,15 @@ export const NARRATE_USAGE = [
" umtool posts narrate <project> <item> [--script \"…\"] [--take [--note \"…\"] [--voice v] [--engine e] [--speed s]]",
" [--pick <n>] [--approve|--unapprove] [--off|--on] [lead=… tail=… ramp=… linger=… clip=read|full",
" wet=… lowpass=… duck=on|off short=hold|loop attach=under|after lufs=… rate=… pace=fast|normal] [--json]",
- " umtool posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert]",
+ " umtool posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean|--clean] [--no-trim|--trim] [--no-convert]",
+ " [--pitch target|source|contour] [--semitones <n>]",
+ " umtool posts narrate <project> <item> [--recording <file>] --preview [--as <character>] [--out <file>] [--trim-span [<part>=]<from>-<to>]…",
+ " [--no-clean|--clean] [--no-trim|--trim] [--no-convert] [--engine e] [--voice v] [--pitch …] [--semitones <n>] [--events]",
+ " umtool posts narrate <project> <item> --keep-preview | --discard-preview [--label operator]",
+ " umtool posts narrate <project> <item> --derive <n> --op enhance|convert [--engine e] [--voice v] [--as <character>]",
+ " [--pitch target|source|contour] [--semitones <n>]",
" umtool posts narrate <project> <item> --take --thread [--parents 0|all|none|<n>] [--skip-parent <id>]… [--no-quoted]",
- " [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--force] [--dry-run]",
+ " [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--speed s] [--force] [--dry-run]",
" umtool posts narrate <project> <item> … --in-take <take> any of these on a TAKE of the project: the pick, a new",
" read (--take, --thread), the script, the mix -- written into the take's patch (umtool posts --help)",
" umtool posts narrate <project> --all --draft-scripts [--force] | --all --take [--limit N]",
@@ -67,10 +75,31 @@ export const NARRATE_USAGE = [
" --delete <n>: the take out of the list, its file moved to narration/posts/<postId>/.trash/ (soft).",
" --recording <file> [--as <character>] [--no-clean] [--no-convert] [--label operator]: a person's RECORDING of the",
" item made a character's read -- kept as a recorded take (the original), cleaned (the editor's voice-enhance), then",
- " converted to the character's STOCK voice (umtool cast: its convert voice; default the post's author's, else the",
- " narrator) -- each a new take, the last picked, the disclosure line said.",
+ " converted to the character's STOCK voice (umtool cast: its convert voice) -- each a new take, the last picked, the",
+ " disclosure line said. The character: --as (this video's own, else the cast's), else the item's own (umtool posts",
+ " character), this video's for the post's author, the cast's, the narrator. Its RECORDED PRESET says whether the",
+ " read is cleaned and its edges trimmed to speech (and the room kept): --clean | --no-clean and --trim | --no-trim",
+ " say otherwise for this read.",
+ " --recording <file> --preview: THE SAME CHAIN, NO TAKE MADE (lib/report/recordPreview.mjs; the record page's",
+ " Filter) -- cleaned, its edges cut (--trim-span 0.4-3.1: at these seconds of the recording instead of the auto",
+ " trim's; a parted read: 2=0.2-4), converted -- into the scratch dir narration/.record-preview/<postId>.<label>/,",
+ " its paths printed; --out <file> copies the filtered read there. Without --recording: the record page's session",
+ " of the item. A step whose inputs did not change is not run again (another --pitch asks for the convert alone).",
+ " --keep-preview makes its takes (recorded, cleaned, converted; the last picked) from those files, converting",
+ " nothing again; --discard-preview removes it. --events: its progress as one JSON object a line.",
+ " --speed <s> (--take, --take --thread): the speed the read is asked at (0.5-2; Orpheus has none) -- default the",
+ " item's own, else its character's (the synthetic preset's: umtool cast set <id> --speed). A thread read: every part.",
" --derive <n> --op enhance|convert [--engine e] [--voice v]: a NEW take made from take n by the editor's op",
" (enhance: denoise, level; convert: the performance kept, the timbre a STOCK synthetic voice) -- the original kept.",
+ " A convert is the CHARACTER's (--as, else the item's own, this video's for the author, the cast's, the narrator):",
+ " its recorded preset's engine, stock voice, pitch and semitones, each unless its flag says otherwise. With no",
+ " character and no --voice it is refused: the editor's default voice is never asked for.",
+ " --pitch target|source|contour [--semitones <n>] (a convert, by --derive or --recording): the PITCH the converted",
+ " read lands on -- target: the stock voice's own (the read's intonation is flattened to it); source: the pitch it",
+ " was read at (raise your voice and it rises); contour: the read's rises and falls, moved as a whole to the stock",
+ " voice's register; --semitones (-12 to 12) then moves a followed pitch. Default: the character's own (umtool cast",
+ " set <id> --convert-pitch …), else the editor's (settings.voice.convert). source and contour are seed-vc's, with",
+ " its f0 model (archilyzer voice setup --engine seed-vc --with f0); the editor refuses what it cannot do.",
" A narrated post lasts lead + its read + tail + linger (1.8 s); a longer video is cut to that -- its best part,",
" pace=fast plays a post (or, with --cut, every post) back to back: lead 0.1, tail 0.15, ramp 0.3, linger 0.45 --",
" unless it sets one itself; pace=normal the cut's gaps.",
@@ -319,12 +348,15 @@ export async function makeTake(project, e, { script = null, note = null, engine
const k = postNarrationKnobs(e, render);
const words = String(script ?? e.narration?.script ?? "").trim();
if (!words) throw new NarrateError(`${e.id} has no script to read (--script "…", or --all --draft-scripts)`);
- // The voice his own read is said in: the one asked for, the project's voice map, the CAST, the narrator's (readVoice.mjs).
+ // The voice his own read is said in: the one asked for, the item's own character, the project's characters and voice
+ // map, the CAST, the narrator's (readVoice.mjs).
const { itemReadVoice } = await import("./readVoice.mjs");
const said0 = await itemReadVoice(project, e, { render, engine, voice });
const eng = said0.engine;
const vox = said0.voice;
- const spd = speed ?? e.narration?.speed ?? null;
+ // Its speed: the one asked for (--speed), else the item's own (`narration.speed`: set on this one item), else its
+ // character's (the synthetic preset's that answered for the voice).
+ const spd = speed ?? e.narration?.speed ?? said0.speed ?? null;
const pid = postIdOf(e);
const dir = path.join(project.dir, ...takesDirOf(pid).split("/"));
await mkdir(dir, { recursive: true });
@@ -409,7 +441,7 @@ async function timeTakeWords(project, rel, script, { askOp = null, emit = () =>
}
/** `umtool posts narrate …` (postsCli.mjs routes it here). */
-export async function narrateCommand(project, words, flags, { json = false, dryRun = false, out = (s) => console.log(s), str, multi = () => [] }) {
+export async function narrateCommand(project, words, flags, { json = false, dryRun = false, out = (s) => console.log(s), str, multi = () => [], ask = null }) {
const manifest = await readManifest(project.dir);
if (!manifest) throw new NarrateError(`${project.id} has no manifest`);
const render = manifest.render ?? {};
@@ -518,10 +550,76 @@ export async function narrateCommand(project, words, flags, { json = false, dryR
out(json ? JSON.stringify({ ok: true, id: e.id, narration: r.narration, token: r.token }, null, 2) : `${e.id}: take ${k} moved to the post's .trash/ (out of the list)\n${narrationLines(r.entry, render).join("\n")}`);
return 0;
}
+ if (flags.has("--preview") || flags.has("--keep-preview") || flags.has("--discard-preview")) {
+ // RECORD -> FILTER -> PREVIEW (recordPreview.mjs): the chain run into the scratch dir, no take made; then kept, or dropped.
+ const { discardPreview, keepPreview, previewDirOf, runPreview } = await import("./recordPreview.mjs");
+ const label = str("--label") ?? "operator";
+ if (flags.has("--discard-preview")) {
+ await discardPreview(project.dir, e, label);
+ out(json ? JSON.stringify({ ok: true, id: e.id, discarded: previewDirOf(project.dir, e, label) }, null, 2) : `${e.id}: its preview is gone (${previewDirOf(project.dir, e, label)})`);
+ return 0;
+ }
+ if (flags.has("--keep-preview")) {
+ // A preview of the record page's session is kept only while the session is still the recording it was made from.
+ const { readPreview } = await import("./recordPreview.mjs");
+ const made = await readPreview(project.dir, e, label);
+ const parts = made?.session ? await (await import("./recordSession.mjs")).sessionParts(project.dir, e, label).catch(() => null) : null;
+ if (made?.session && !parts) throw new NarrateError(`${e.id}'s preview is of the record page's session, and that session is gone or not whole any more: --discard-preview, and Filter again`);
+ const r = await keepPreview(project, e, { label, note: str("--note"), script: str("--script"), parts });
+ // A preview of the record page's session: its parts are takes now, the session is over.
+ if (r.session) await (await import("./recordSession.mjs")).clearSession(project.dir, e, label);
+ if (json) out(JSON.stringify({ ok: true, id: e.id, takes: r.takes, picked: r.picked, notes: r.notes, disclosure: r.disclosure, character: r.character, token: r.token }, null, 2));
+ else {
+ out(`${e.id}: ${r.takes.map((t) => `${t.step} -> ${t.file}`).join(", ")}; picked ${r.picked} (from its preview: nothing converted again)`);
+ if (r.disclosure) out(` disclosure: ${r.disclosure}`);
+ }
+ return 0;
+ }
+ // The recording: the file named, else the record page's session of this post (every part of it in).
+ const file = str("--recording");
+ let parts;
+ const fromSession = file === null;
+ if (file !== null) {
+ const abs = path.resolve(file);
+ if (!(await stat(abs).catch(() => null))?.isFile()) throw new NarrateError(`--recording takes a sound file (no ${file})`);
+ parts = [{ file: abs, text: String(e.narration?.script ?? "") }];
+ } else {
+ const { sessionParts } = await import("./recordSession.mjs");
+ try {
+ parts = await sessionParts(project.dir, e, label);
+ } catch (err) {
+ throw new NarrateError(`--preview takes --recording <file>, or the record page's session of ${e.id}: ${err.message}`);
+ }
+ }
+ const events = flags.has("--events");
+ const r = await runPreview(project, e, parts, {
+ label, session: fromSession, as: str("--as"), clean: flags.has("--no-clean") ? false : flags.has("--clean") ? true : undefined,
+ ...(flags.has("--no-trim") ? { trim: { on: false, padMs: null } } : flags.has("--trim") ? { trim: { on: true, padMs: null } } : {}),
+ spans: trimSpans(multi("--trim-span"), parts.length), convert: !flags.has("--no-convert"), engine: str("--engine"), voice: str("--voice"), ...pitchFlags(str), out: str("--out"), ask,
+ // --events: one JSON object a line (the record page's job reads them); else the sentences.
+ emit: (ev, f) => (events ? out(JSON.stringify({ ev, ...f })) : !json && f?.message && out(ev === "note" ? f.message : ` ${f.message}`)),
+ });
+ if (events) out(JSON.stringify({ ev: "result", ok: true, id: e.id, ...r }));
+ else if (json) out(JSON.stringify({ ok: true, id: e.id, ...r }, null, 2));
+ else {
+ out(`${e.id}: previewed${r.character ? ` as ${r.character.name}` : ""} -- NO TAKE MADE`);
+ out(` raw ${r.raw}`);
+ if (r.clean) out(` cleaned ${r.clean}`);
+ if (r.filtered) out(` filtered ${r.filtered}${r.convert ? ` (${r.convert.engine ?? "the editor's engine"} -> ${r.convert.voice}${convertPitchLabel(r.convert) ? `, pitch: ${convertPitchLabel(r.convert)}` : ""})` : ""}`);
+ if (r.out) out(` copied to ${r.out}`);
+ for (const n of r.notes) out(` ${n}`);
+ out(` keep it: umtool posts narrate ${project.id} ${e.id} --keep-preview${label !== "operator" ? ` --label ${label}` : ""} (drop it: --discard-preview)`);
+ }
+ return 0;
+ }
if (str("--recording") !== null) {
// A RECORDING made a character's read: kept as a take (the original), cleaned, converted to its stock voice.
const r = await importRecording(project, e, str("--recording"), {
- as: str("--as"), label: str("--label") ?? "operator", clean: !flags.has("--no-clean"), convert: !flags.has("--no-convert"), note: str("--note"),
+ // --no-clean / --clean and --no-trim / --trim win over the character's recorded preset; neither: the preset's.
+ as: str("--as"), label: str("--label") ?? "operator", clean: flags.has("--no-clean") ? false : flags.has("--clean") ? true : undefined,
+ ...(flags.has("--no-trim") ? { trim: { on: false, padMs: null } } : flags.has("--trim") ? { trim: { on: true, padMs: null } } : {}),
+ convert: !flags.has("--no-convert"), note: str("--note"),
+ ...pitchFlags(str),
emit: (_ev, f) => !json && f?.message && out(f.message),
});
if (json) out(JSON.stringify({ ok: true, id: e.id, ...r }, null, 2));
@@ -537,7 +635,23 @@ export async function narrateCommand(project, words, flags, { json = false, dryR
if (!Number.isInteger(k) || k < 1) throw new NarrateError("--derive takes a take's number as --list shows it (1 = the first)");
const op = str("--op") ?? "";
try {
- const r = await deriveTake(project, e, { from: k - 1, op, engine: str("--engine"), voice: str("--voice"), emit: (_ev, f) => !json && f?.message && out(f.message) });
+ const pitched = pitchFlags(str);
+ if (op !== "convert" && (pitched.pitch !== undefined || pitched.semitones !== undefined)) throw new NarrateError("--pitch and --semitones are a convert's (--op convert): an enhance keeps the read's own pitch");
+ let asked = { engine: str("--engine"), voice: str("--voice"), ...pitched };
+ if (op === "convert") {
+ // A convert is the CHARACTER's (cast.mjs characterForRead: --as, the item's own, this video's for the author,
+ // the cast's, the narrator): its recorded preset's engine, stock voice, pitch and semitones, each unless a flag
+ // says otherwise -- and with no character and no --voice it is refused, never the editor's default voice.
+ const { readLayers } = await import("./characterLayers.mjs");
+ const { recordedPresetOf } = await import("umtool-report-to-video/cast");
+ const who = (await readLayers(project.dir)).characterForRead(e, str("--as"));
+ if (str("--as") && !who?.character) throw new NarrateError(`--as ${str("--as")}: no such character in this video's characters or the cast (umtool cast project ${project.id}, umtool cast ls)`);
+ const d = convertAskOf(asked, who?.character ? recordedPresetOf(who.character).convert : null, who?.character?.id ?? null);
+ if (!d.ok) throw new NarrateError(`${d.error} (${d.fix})`);
+ asked = d.value;
+ if (!json && d.from === "character") out(` as ${who.character.id}: ${asked.engine ?? "the editor's engine"} -> ${asked.voice}${convertPitchLabel(asked) ? ` (pitch: ${convertPitchLabel(asked)})` : ""}`);
+ }
+ const r = await deriveTake(project, e, { from: k - 1, op, ...asked, ask, emit: (_ev, f) => !json && f?.message && out(f.message) });
if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take, token: r.result.token }, null, 2));
else out(`${e.id}: take ${r.take.file} (${r.take.seconds} s), from take ${k} by ${op}, picked`);
return 0;
@@ -571,15 +685,14 @@ export async function narrateCommand(project, words, flags, { json = false, dryR
return threadCommand(project, e, {
manifest, json, out, overrides, parents, skip: multi("--skip-parent").flatMap((x) => x.split(",")).map((x) => x.trim()).filter(Boolean),
quoted: !flags.has("--no-quoted"), linked: !flags.has("--no-linked"), readSeen: flags.has("--read-seen"),
- voice: str("--voice"), engine: str("--engine"), note: str("--note"), force: flags.has("--force"), hold: !flags.has("--no-hold"), dryRun,
+ voice: str("--voice"), engine: str("--engine"), speed: speedFlag(str), note: str("--note"), force: flags.has("--force"), hold: !flags.has("--no-hold"), dryRun,
});
}
if (flags.has("--thread")) throw new NarrateError("--thread goes with --take (umtool posts narrate <p> <item> --take --thread)");
if (flags.has("--take")) {
- const speedRaw = str("--speed");
const r = await makeTake(project, e, {
script: str("--script"), note: str("--note"), engine: str("--engine"), voice: str("--voice"),
- speed: speedRaw === null ? null : Number(speedRaw), render, emit: (_ev, f) => !json && f?.message && out(f.message),
+ speed: speedFlag(str), render, emit: (_ev, f) => !json && f?.message && out(f.message),
});
if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take, narration: r.result.narration, token: r.result.token }, null, 2));
else out(`${e.id}: take ${r.take.file} (${r.take.seconds} s), picked${r.take.note ? ` — note: ${r.take.note}` : ""}`);
@@ -608,6 +721,58 @@ export async function narrateCommand(project, words, flags, { json = false, dryR
return 0;
}
+export const CHARACTER_USAGE = [
+ "usage: umtool posts character <project> <item> [<character> | --clear] [--json]",
+ " THE CHARACTER ONE POST ITEM's OWN READ IS MADE WITH (its `narration.character`): the id of one of this video's",
+ " own characters (umtool cast project <p>), else of the cast's (umtool cast ls) -- its presets answer for this",
+ " item's read before its author's handle does: the synthetic one for a new take or a thread read (voice, speed),",
+ " the recorded one for a recording made its read (--recording). No character: the one it names, and what its read",
+ " resolves to now. --clear: by its author's handle again. One undoable write; no take is made or changed (a picked",
+ " read in another voice is DRIFT: umtool cast project <p>).",
+].join("\n");
+
+/** `umtool posts character <p> <item> [<id> | --clear]` -- a post item's own character (cast.mjs itemCharacterOf). */
+export async function characterCommand(project, rest, { flags = new Map(), json = false, out = (s) => console.log(s) } = {}) {
+ const [ref, id] = rest;
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new NarrateError(`${project.id} has no manifest`);
+ const e0 = findPostItem(manifest, ref);
+ if (!e0) throw new NarrateError(`no post item ${ref} in ${project.id} (its id, or the post's id)`);
+ const clear = flags.has("--clear");
+ if (clear && id) throw new NarrateError("posts character: a character's id, or --clear -- not both");
+ const { readLayers } = await import("./characterLayers.mjs");
+ const { characterById, shownNameOf } = await import("umtool-report-to-video/cast");
+ const { itemReadVoice } = await import("./readVoice.mjs");
+ const { voiceSpecOf } = await import("umtool-report-to-video/post-say");
+ const layers = await readLayers(project.dir);
+ let e = e0;
+ let changed = null;
+ if (clear || id) {
+ let want = null;
+ if (id) {
+ const hit = characterById(id, layers);
+ if (!hit) throw new NarrateError(`no character ${id} among ${project.id}'s own or in the cast (umtool cast project ${project.id}; umtool cast ls)${layers.projectRead.error ? ` -- and this video's characters are not read: ${layers.projectRead.error}` : ""}`);
+ want = hit.character.id;
+ }
+ if ((e0.narration?.character ?? null) !== want) {
+ const { result } = await withEditNotes(project, async () => updatePostNarration(project.dir, e0.id, { character: want }, { token: await manifestToken(project.dir) }));
+ e = result.entry;
+ changed = want ? "set" : "cleared";
+ }
+ }
+ const it = layers.itemCharacterOf(e);
+ const v = await itemReadVoice(project, e, { render: manifest.render ?? {}, map: layers.map, cast: layers.castMap, item: layers.itemOf(e) });
+ const voice = { ...v, spec: voiceSpecOf(v) };
+ if (json) out(JSON.stringify({ ok: true, id: e.id, character: it?.id ?? null, found: it ? !!it.character : null, layer: it?.layer ?? null, changed, voice }, null, 2));
+ else {
+ const how = `${voice.spec}${typeof voice.speed === "number" ? ` ×${voice.speed}` : ""} (${voice.from}${voice.character && voice.from !== "narrator" ? `: ${voice.character}` : ""})`;
+ if (!it) out(`${e.id}: no character of its own${changed ? " now" : ""} -- read by its author's handle: ${how}`);
+ else if (!it.character) out(`${e.id}: names ${it.id}, which is NOT a character of this video's or the cast's -- it reads as its author does: ${how} (umtool posts character ${project.id} ${e.id} --clear)`);
+ else out(`${e.id}: read as ${it.id} (${shownNameOf(it.character)}; ${it.layer === "project" ? "this video's own" : "the cast's"}): ${how}`);
+ }
+ return 0;
+}
+
export const FIT_USAGE = [
"usage: umtool posts fit <project> [--all | <item> …] [--linger <s>] [--dry-run] [--json]",
" NARRATED POSTS, NO LINGERING: each post read in full, then over `linger` (1.8 s) after the words; a video",
@@ -659,16 +824,61 @@ export async function fitCommand(project, refs, { all = false, linger = null, js
return 0;
}
+/** `--speed` as a read takes it (null: not given); a value the tts op would refuse is refused here, in the flag's name. */
+function speedFlag(str) {
+ const raw = str("--speed");
+ if (raw === null) return null;
+ const n = Number(raw);
+ const [lo, hi] = POST_NARRATION_LIMITS.speed;
+ if (String(raw).trim() === "" || !Number.isFinite(n) || n < lo || n > hi) throw new NarrateError(`--speed is a number from ${lo} to ${hi} (got ${raw || "nothing"})`);
+ return n;
+}
+
+/**
+ * `--trim-span` as the cut marks of a preview: `<from>-<to>` (the first part) or `<n>=<from>-<to>` (part n), seconds
+ * in the part as recorded, once a part. Returns `[{ from, to } | null]` per part, or null when none was given.
+ */
+export function trimSpans(specs, count) {
+ if (!specs.length) return null;
+ const out = new Array(count).fill(null);
+ for (const spec of specs) {
+ const m = /^(?:(\d+)=)?(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$/.exec(String(spec).trim());
+ const n = m ? Number(m[1] ?? 1) : 0;
+ if (!m || n < 1 || n > count || !(Number(m[3]) - Number(m[2]) >= 0.2)) throw new NarrateError(`--trim-span is <from>-<to> or <part>=<from>-<to> in seconds, at least 0.2 s, for a part 1-${count} (got ${spec || "nothing"})`);
+ if (out[n - 1]) throw new NarrateError(`--trim-span names part ${n} twice`);
+ out[n - 1] = { from: Number(m[2]), to: Number(m[3]) };
+ }
+ return out;
+}
+
+/** `--pitch` / `--semitones` as a convert takes them (only those given); a value the editor would refuse anyway is refused here, in the flag's name. */
+export function pitchFlags(str) {
+ const out = {};
+ const p = str("--pitch");
+ if (p !== null) {
+ if (!CAST_CONVERT_PITCH.includes(p)) throw new NarrateError(`--pitch is one of ${CAST_CONVERT_PITCH.join(", ")} (got ${p || "nothing"})`);
+ out.pitch = p;
+ }
+ const s = str("--semitones");
+ if (s !== null) {
+ const n = Number(s);
+ if (s.trim() === "" || !Number.isFinite(n) || Math.abs(n) > CAST_SEMITONES_MAX) throw new NarrateError(`--semitones is a number from -${CAST_SEMITONES_MAX} to ${CAST_SEMITONES_MAX} (got ${s || "nothing"})`);
+ out.semitones = n;
+ }
+ return out;
+}
+
/**
* A DERIVED TAKE (post-narration.mjs: "run AI on recorded voice"): take
* `from` (an index) run through the editor's `op` (`enhance`, `convert`) into
* a NEW take -- source `{kind: "take", from: <its id>}`, its step recorded --
* the original untouched; a parted take part by part (its parts kept). The
* editor's op is a job (`POST /api/ops/voice-enhance|voice-convert` with
- * `{file, out, engine?, voice?, params?, parts?}`); one it has no engine for
- * throws OpNotInstalled.
+ * `{file, out, engine?, voice?, pitch?, semitones?, params?, parts?}`); one it has no engine for
+ * throws OpNotInstalled. A convert's `pitch` / `semitones` (the pitch the read lands on: the editor's voice-convert)
+ * go as asked and are kept on the take's step as the editor says it ran them.
*/
-export async function deriveTake(project, e, { from, op, engine = null, voice = null, params = null, emit = () => {}, editor = null, ask = null } = {}) {
+export async function deriveTake(project, e, { from, op, engine = null, voice = null, pitch = null, semitones = null, params = null, emit = () => {}, editor = null, ask = null } = {}) {
const takes = e.narration?.takes ?? [];
const t = takes[from];
if (!t) throw new NarrateError(`${e.id} has no take ${from + 1}`);
@@ -688,6 +898,7 @@ export async function deriveTake(project, e, { from, op, engine = null, voice =
const body = {
file: abs(t.file), out: abs(rel),
...(engine ? { engine } : {}), ...(target ? { voice: target } : {}), ...(params ? { params } : {}),
+ ...(op === "convert" && pitch ? { pitch } : {}), ...(op === "convert" && typeof semitones === "number" ? { semitones } : {}),
...(parts ? { parts: t.parts.map((p, k) => ({ file: abs(p.file), out: abs(parts[k].file) })) } : {}),
};
const askOp = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorOp;
@@ -697,11 +908,13 @@ export async function deriveTake(project, e, { from, op, engine = null, voice =
// The editor's defaults, when the ask named none: the engine it ran, the stock voice it landed on.
const ran = engine ?? (typeof said?.engine === "string" ? said.engine : null);
const landed = op === "convert" ? (target ?? (typeof said?.voice === "string" ? said.voice : null)) : null;
+ // The pitch it landed on, as the editor ran it (its default when none was asked); the target's own is not a step's news.
+ const pitched = op === "convert" ? stepPitchOf({ pitch, semitones }, said) : {};
const take = {
// A take's voice is the bare stock voice ("am_michael"); its step keeps the target as asked ("kokoro:am_michael").
file: rel, engine: "derived", voice: (landed ? String(landed).split(":").pop() : null) ?? t.voice ?? "?", seconds: m.seconds ?? t.seconds,
source: { kind: "take", from: takeIdOf(t) },
- steps: [{ op, ...(ran ? { engine: ran } : {}), ...(landed ? { voice: landed } : {}), ...(params ? { params } : {}), ranAt: new Date().toISOString(), job: jobId }],
+ 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 } : {}),
};
@@ -715,30 +928,41 @@ export async function deriveTake(project, e, { from, op, engine = null, voice =
* as a RECORDED take (postRecord.mjs keepRecording: trimmed, levelled -- the original, never overwritten), then a
* derived take CLEANED by the editor's voice-enhance (skipped, and said, when it has no engine for it), then a
* derived take CONVERTED by its voice-convert to the character's STOCK voice (cast.mjs convertTargetOf: its convert
- * voice, else its voice) -- the character `as` names (an id, a handle), else the post's author's in the cast, else
- * the cast's narrator; none: kept as recorded (and cleaned). Each step a new take, the last one picked, with the
- * disclosure line the cut will carry. Returns `{ takes: [{ step, file }], picked, notes, disclosure, character }`.
+ * voice, else its voice) at the PITCH asked (`pitch`, `semitones`), else the character's own (its convert entry's),
+ * else the editor's.
+ *
+ * THE CHARACTER, and its RECORDED PRESET (cast.mjs characterForRead, recordedPresetOf): the one `as` names (an id, a
+ * handle, a name -- the project's own characters first), else the item's own (`narration.character`), else the
+ * project's for the post's author, else the cast's, else the cast's narrator; none: kept as recorded (and cleaned).
+ * What the command says wins over the preset: `clean` (undefined: the preset's `enhance`, on unless it says off),
+ * `trim` (undefined: the preset's -- its edges trimmed to speech unless `trim.on` is false, `trim.padMs` the room
+ * kept either side), `pitch` / `semitones`. Each step a new take, the last one picked, with the disclosure line the
+ * cut will carry. Returns `{ takes: [{ step, file }], picked, notes, disclosure, character, direction }`.
*/
-export async function importRecording(project, e0, file, { as = null, label = "operator", clean = true, convert = true, note = null, emit = () => {}, editor = null, ask = null } = {}) {
+export async function importRecording(project, e0, file, { as = null, label = "operator", clean = undefined, convert = true, trim = undefined, pitch = undefined, semitones = undefined, note = null, emit = () => {}, editor = null, ask = null } = {}) {
const abs = path.resolve(String(file ?? ""));
if (!(await stat(abs).catch(() => null))?.isFile()) throw new NarrateError(`--recording takes a sound file (no ${file})`);
const { keepRecording } = await import("./postRecord.mjs");
- const { castForProject } = await import("./castStore.mjs");
- const { characterOf, convertTargetOf, findCharacter, narratorOf } = await import("umtool-report-to-video/cast");
+ const { readLayers } = await import("./characterLayers.mjs");
+ const { convertPitchLabel, recordedPresetOf, shownNameOf } = await import("umtool-report-to-video/cast");
const { postNarrationDisclosure } = await import("umtool-report-to-video/post-narration");
- const castRead = await castForProject(project.dir);
- const character = as ? findCharacter(castRead.cast, String(as).replace(/^@+/, "")) : characterOf(castRead.cast, e0.handle) ?? narratorOf(castRead.cast);
- if (as && !character) throw new NarrateError(`--as ${as}: no such character in the cast (umtool cast ls)`);
+ const layers = await readLayers(project.dir);
+ const who = layers.characterForRead(e0, as);
+ const character = who?.character ?? null;
+ if (as && !character) throw new NarrateError(`--as ${as}: no such character in this video's characters or the cast (umtool cast project ${project.id}, umtool cast ls)`);
+ const preset = character ? recordedPresetOf(character) : null;
+ const doClean = clean ?? preset?.enhance ?? true;
+ const doTrim = trim ?? (preset ? preset.trim : undefined);
const notes = [];
const takes = [];
const fresh = async () => findPostItem(await readManifest(project.dir), e0.id);
- const kept = await keepRecording(project, e0, [{ file: abs, text: String(e0.narration?.script ?? "") }], { label, manifest: await readManifest(project.dir), note: note ?? `recorded${character ? ` for ${character.name}` : ""}` });
+ const kept = await keepRecording(project, e0, [{ file: abs, text: String(e0.narration?.script ?? "") }], { label, manifest: await readManifest(project.dir), note: note ?? `recorded${character ? ` for ${shownNameOf(character)}` : ""}`, ...(doTrim ? { trim: doTrim } : {}) });
takes.push({ step: "recorded", file: kept.take.file });
- emit("note", { message: `kept as recorded: ${kept.take.file} (levelled ${kept.gain >= 0 ? "+" : ""}${kept.gain} dB)` });
+ emit("note", { message: `kept as recorded: ${kept.take.file} (levelled ${kept.gain >= 0 ? "+" : ""}${kept.gain} dB${doTrim?.on === false ? ", its edges not trimmed" : ""})` });
let e = await fresh();
const indexOf = (rel) => (e?.narration?.takes ?? []).findIndex((t) => t.file === rel);
let from = indexOf(kept.take.file);
- if (clean) {
+ if (doClean) {
try {
const r = await deriveTake(project, e, { from, op: "enhance", emit, editor, ask });
takes.push({ step: "cleaned", file: r.take.file });
@@ -748,14 +972,19 @@ export async function importRecording(project, e0, file, { as = null, label = "o
if (err?.name !== "OpNotInstalled" && !/not installed/i.test(String(err?.message))) throw err;
notes.push(`not cleaned: ${err.message} (archilyzer voice setup --engine deepfilternet)`);
}
- }
+ } else if (clean === undefined) notes.push(`not cleaned: ${character.id}'s recorded preset says so (enhance off)`);
if (convert) {
- if (!character) notes.push("not converted: no character to convert to (--as <character>, or the post's author or a narrator in the cast: umtool cast add …)");
+ const target = character ? preset.convert : null;
+ if (!character) notes.push("not converted: no character to convert to (--as <character>, the item's own, or the post's author or a narrator in the cast: umtool cast add …)");
+ else if (!target.voice) notes.push(`not converted: ${character.id} has no stock voice to convert to (umtool cast ${who.layer === "cast" || who.layer === "narrator" ? "" : `project ${project.id} `}set ${character.id} --convert-voice <engine:voice>)`);
else {
- const target = convertTargetOf(character);
+ // The pitch asked for this read, else the character's; semitones asked of the target's own pitch are dropped
+ // with it (a character kept at "contour +2" read once with --pitch target).
+ const pitched = { pitch: pitch ?? target.pitch ?? null, semitones: semitones ?? (pitch === "target" ? null : target.semitones ?? null) };
try {
- const r = await deriveTake(project, e, { from, op: "convert", engine: target.engine, voice: target.voice, emit, editor, ask });
- takes.push({ step: `converted to ${target.voice}`, file: r.take.file });
+ const r = await deriveTake(project, e, { from, op: "convert", engine: target.engine, voice: target.voice, ...pitched, emit, editor, ask });
+ const how = convertPitchLabel(r.take.steps?.[0]);
+ takes.push({ step: `converted to ${target.voice}${how ? ` (pitch: ${how})` : ""}`, file: r.take.file });
e = await fresh();
} catch (err) {
if (err?.name !== "OpNotInstalled" && !/not installed/i.test(String(err?.message))) throw err;
@@ -763,7 +992,11 @@ export async function importRecording(project, e0, file, { as = null, label = "o
}
}
}
- return { takes, picked: takes.at(-1).file, notes, disclosure: e ? postNarrationDisclosure(e) : null, character: character ? { id: character.id, name: character.name, voice: character.voice } : null };
+ return {
+ takes, picked: takes.at(-1).file, notes, disclosure: e ? postNarrationDisclosure(e) : null,
+ character: character ? { id: character.id, name: shownNameOf(character), voice: character.voice ?? null, layer: who.layer } : null,
+ ...(preset?.direction ? { direction: preset.direction } : {}),
+ };
}
/**
diff --git a/umtool/lib/report/postRecord.mjs b/umtool/lib/report/postRecord.mjs
@@ -13,7 +13,7 @@
// project's synthesized takes (their measured loudness, else -21 LUFS) by one
// gain under a -1 dBFS limiter. Nothing else: no cloning, no TTS, no effects.
import { execFile } from "node:child_process";
-import { mkdir, readdir, rename, rm, stat } from "node:fs/promises";
+import { mkdir, open, readdir, rename, rm, stat } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { detectSilence } from "umtool-report-to-video/cut-points";
@@ -54,53 +54,81 @@ export function targetLufsOf(manifest) {
}
/**
- * KEEP A RECORDING: `parts` `[{ file (an uploaded blob, absolute), text, para }]`
- * in reading order, made into take-<n>.recorded-<label>.wav and added to
- * `entry`'s takes (picked) through the writer. Returns the take.
- *
- * @param {{ id: string, dir: string }} project
- * @param {Record<string, any>} entry
- * @param {Array<{ file: string, text?: string, para?: number }>} parts
- * @param {{ label?: string, manifest?: Record<string, any>, note?: string | null, script?: string | null }} [o]
+ * A part's span as a person set it (the record page's cut marks: `{ from, to }` in the part's own seconds), kept
+ * inside `[0, seconds]`; null when it is not one (not two numbers, or under 0.2 s) -- the caller's auto trim then.
*/
-export async function keepRecording(project, entry, parts, { label = "operator", manifest = null, note = null, script = null } = {}) {
- if (!RECORD_LABEL_RE.test(label)) throw new Error(`"${label}" is not a voice label (a-z, 0-9, - and _)`);
- if (!parts.length) throw new Error("nothing was recorded");
- const pid = postIdOf(entry);
- const dir = path.join(project.dir, ...takesDirOf(pid).split("/"));
- await mkdir(dir, { recursive: true });
- const n = nextTakeNumber(entry, await readdir(dir).catch(() => []));
- const base = `take-${n}.recorded-${label}`;
- const rel = `${takesDirOf(pid)}/${base}.wav`;
- const partsRel = `${takesDirOf(pid)}/${base}.parts`;
- const partsDir = path.join(project.dir, ...partsRel.split("/"));
- await mkdir(partsDir, { recursive: true });
+export function explicitSpan(span, seconds) {
+ if (!span || !Number.isFinite(span.from) || !Number.isFinite(span.to)) return null;
+ const from = Math.max(0, Math.min(seconds, span.from));
+ const to = Math.max(0, Math.min(seconds, span.to));
+ return to - from >= 0.2 ? { from: r3(from), to: r3(to) } : null;
+}
+
+/**
+ * Is `file` TEXT where a sound should be -- a playlist, a concat script, an SDP, a manifest (m3u8, ffconcat, MPD …)?
+ * ffmpeg would follow one to OTHER files and addresses; a recording is a binary container, so its first bytes are
+ * never all text. An upload that is, is refused before ffmpeg sees it.
+ */
+export async function looksLikeText(file) {
+ const fh = await open(file, "r");
+ try {
+ const buf = Buffer.alloc(2048);
+ const { bytesRead } = await fh.read(buf, 0, buf.length, 0);
+ if (!bytesRead) return false;
+ for (let i = 0; i < bytesRead; i += 1) {
+ const b = buf[i];
+ if (b === 0 || (b < 9) || (b > 13 && b < 32)) return false;
+ }
+ return true;
+ } finally {
+ await fh.close();
+ }
+}
+
+/**
+ * One part as it was recorded (any sound ffmpeg reads) -> a 48 kHz mono wav, measured: `{ seconds, silences }`. The
+ * file is an UPLOAD: a text file (a playlist: looksLikeText) is refused, and ffmpeg may open local files only
+ * (`-protocol_whitelist file`: no http, no concat, no pipe).
+ */
+export async function decodePart(src, out) {
+ if (await looksLikeText(src)) throw Object.assign(new Error("that is not a sound file: it is text (a playlist or a script), and a recording is refused one"), { status: 400 });
+ await execFileP(FFMPEG(), ["-nostdin", "-v", "error", "-y", "-protocol_whitelist", "file", "-i", src, "-vn", "-ac", "1", "-ar", "48000", "-c:a", "pcm_s16le", out]);
+ const { seconds } = await measureTake(out);
+ const silences = await detectSilence(out, { silenceMinDur: 0.15 }).catch(() => []);
+ return { seconds: r3(seconds ?? 0), silences };
+}
+
+/** The room kept either side of a part's words: a preset's `trim.padMs`, else the recorder's own. */
+export const roomOf = (trim) => (trim && Number.isFinite(trim.padMs) ? { head: trim.padMs / 1000, tail: trim.padMs / 1000 } : RECORD_ROOM);
+
+/**
+ * THE PARTS OF A RECORDING, CUT AND JOINED: `sources` `[{ wav (48 kHz mono, absolute), from, to, text?, para? }]` in
+ * reading order -> each cut to its span into `<partsDir>/pNN.wav`, joined with post-narration.mjs's pauses and
+ * brought to `target` LUFS by one gain under a -1 dBFS limiter, into `out`. Returns `{ seconds, lufs, gain, parts:
+ * [{ n, para, text?, name: "pNN.wav", start, seconds, gapBefore }] }` -- a part's `name` is its file in `partsDir`.
+ * keepRecording's and the record page's preview (recordPreview.mjs) make the same file from the same spans.
+ */
+export async function joinRecording(sources, { out, partsDir, target }) {
const ff = FFMPEG();
- // Each part: decoded, measured, trimmed of its silence at either end.
+ await mkdir(partsDir, { recursive: true });
const made = [];
- for (const [k, p] of parts.entries()) {
- const raw = path.join(partsDir, `.p${String(k + 1).padStart(2, "0")}.raw.wav`);
- await execFileP(ff, ["-nostdin", "-v", "error", "-y", "-i", p.file, "-vn", "-ac", "1", "-ar", "48000", "-c:a", "pcm_s16le", raw]);
- const { seconds } = await measureTake(raw);
- const sil = await detectSilence(raw, { silenceMinDur: 0.15 }).catch(() => []);
- const span = trimSpan(sil, seconds ?? 0);
- const out = path.join(partsDir, `p${String(k + 1).padStart(2, "0")}.wav`);
- await execFileP(ff, ["-nostdin", "-v", "error", "-y", "-i", raw, "-af", `atrim=${span.from}:${span.to},asetpts=PTS-STARTPTS`, "-ar", "48000", "-ac", "1", "-c:a", "pcm_s16le", out]);
- await rm(raw, { force: true });
- made.push({ out, seconds: r3(span.to - span.from), text: p.text, para: Number.isInteger(p.para) ? p.para : k });
+ for (const [k, p] of sources.entries()) {
+ const name = `p${String(k + 1).padStart(2, "0")}.wav`;
+ const file = path.join(partsDir, name);
+ await execFileP(ff, ["-nostdin", "-v", "error", "-y", "-i", p.wav, "-af", `atrim=${p.from}:${p.to},asetpts=PTS-STARTPTS`, "-ar", "48000", "-ac", "1", "-c:a", "pcm_s16le", file]);
+ made.push({ file, name, seconds: r3(p.to - p.from), text: p.text, para: Number.isInteger(p.para) ? p.para : k });
}
// Joined with the pauses, then brought to the synthesized takes' level.
- const withPara = made.map((m) => ({ ...m }));
const inputs = [];
const chain = [];
let start = 0;
- const partsOut = [];
- withPara.forEach((m, k) => {
- const gap = partGapBefore(withPara, k);
+ const parts = [];
+ made.forEach((m, k) => {
+ const gap = partGapBefore(made, k);
if (gap > 0) chain.push({ silence: gap });
start += gap;
- partsOut.push({ n: k + 1, para: m.para, ...(m.text ? { text: m.text } : {}), file: `${partsRel}/p${String(k + 1).padStart(2, "0")}.wav`, start: r3(start), seconds: m.seconds, gapBefore: gap });
- chain.push({ file: m.out });
+ parts.push({ n: k + 1, para: m.para, ...(m.text ? { text: m.text } : {}), name: m.name, start: r3(start), seconds: m.seconds, gapBefore: gap });
+ chain.push({ file: m.file });
start += m.seconds;
});
const filters = [];
@@ -115,25 +143,70 @@ export async function keepRecording(project, entry, parts, { label = "operator",
}
labels.push(`[s${j}]`);
}
- const joined = path.join(dir, `.${base}.joined.wav`);
+ const joined = `${out}.joined.wav`;
await execFileP(ff, ["-nostdin", "-v", "error", "-y", ...inputs, "-filter_complex", `${filters.join(";")};${labels.join("")}concat=n=${labels.length}:v=0:a=1[a]`, "-map", "[a]", "-c:a", "pcm_s16le", joined]);
const measured = await measureTake(joined);
- const target = targetLufsOf(manifest ?? {});
const gain = Number.isFinite(measured.lufs) ? Math.max(-20, Math.min(30, target - measured.lufs)) : 0;
- const tmp = path.join(dir, `.${base}.tmp.wav`);
+ const tmp = `${out}.tmp.wav`;
await execFileP(ff, ["-nostdin", "-v", "error", "-y", "-i", joined, "-af", `volume=${gain.toFixed(2)}dB,alimiter=limit=0.891251:level=0:latency=1`, "-ar", "48000", "-ac", "1", "-c:a", "pcm_s16le", tmp]);
await rm(joined, { force: true });
+ await rename(tmp, out);
+ if (!(await stat(out).catch(() => null))?.isFile()) throw new Error(`${out} was not written`);
+ const m = await measureTake(out);
+ return { seconds: m.seconds, lufs: m.lufs, gain: Math.round(gain * 100) / 100, parts };
+}
+
+/** joinRecording's parts as a take keeps them: each one's file under `relDir` (project-relative). */
+export const partsIn = (parts, relDir) => parts.map((p) => ({ n: p.n, para: p.para, ...(p.text ? { text: p.text } : {}), file: `${relDir}/${p.name}`, start: p.start, seconds: p.seconds, gapBefore: p.gapBefore }));
+
+/**
+ * KEEP A RECORDING: `parts` `[{ file (an uploaded blob, absolute), text, para }]`
+ * in reading order, made into take-<n>.recorded-<label>.wav and added to
+ * `entry`'s takes (picked) through the writer. Returns the take.
+ *
+ * `spans`: the cut marks a person set, per part in reading order (`[{ from, to } | null]`, the part's own seconds:
+ * the record page's waveform) -- a part with one is cut there, whatever `trim` says; the others are trimmed as below.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {Record<string, any>} entry
+ * @param {Array<{ file: string, text?: string, para?: number }>} parts
+ * @param {{ label?: string, manifest?: Record<string, any>, note?: string | null, script?: string | null, trim?: { on?: boolean, padMs?: number | null } | null, spans?: Array<{ from: number, to: number } | null> | null }} [o]
+ */
+export async function keepRecording(project, entry, parts, { label = "operator", manifest = null, note = null, script = null, trim = null, spans = null } = {}) {
+ // A character's recorded preset (cast.mjs recordedPresetOf): its edges left as recorded (`trim.on` false), or the
+ // room kept either side of the words (`trim.padMs`); none: trimmed, RECORD_ROOM.
+ const room = roomOf(trim);
+ if (!RECORD_LABEL_RE.test(label)) throw new Error(`"${label}" is not a voice label (a-z, 0-9, - and _)`);
+ if (!parts.length) throw new Error("nothing was recorded");
+ const pid = postIdOf(entry);
+ const dir = path.join(project.dir, ...takesDirOf(pid).split("/"));
+ await mkdir(dir, { recursive: true });
+ const n = nextTakeNumber(entry, await readdir(dir).catch(() => []));
+ const base = `take-${n}.recorded-${label}`;
+ const rel = `${takesDirOf(pid)}/${base}.wav`;
+ const partsRel = `${takesDirOf(pid)}/${base}.parts`;
+ const partsDir = path.join(project.dir, ...partsRel.split("/"));
+ await mkdir(partsDir, { recursive: true });
+ // Each part: decoded, measured, cut to its marks or trimmed of its silence at either end.
+ const sources = [];
+ for (const [k, p] of parts.entries()) {
+ const raw = path.join(partsDir, `.p${String(k + 1).padStart(2, "0")}.raw.wav`);
+ const { seconds, silences } = await decodePart(p.file, raw);
+ const span = explicitSpan(spans?.[k], seconds) ?? (trim?.on === false ? { from: 0, to: seconds } : trimSpan(silences, seconds, room));
+ sources.push({ wav: raw, ...span, text: p.text, para: p.para });
+ }
const abs = path.join(project.dir, ...rel.split("/"));
- await rename(tmp, abs);
- if (!(await stat(abs).catch(() => null))?.isFile()) throw new Error(`${rel} was not written`);
- const m = await measureTake(abs);
+ const target = targetLufsOf(manifest ?? {});
+ const j = await joinRecording(sources, { out: abs, partsDir, target });
+ for (const x of sources) await rm(x.wav, { force: true });
+ const partsOut = partsIn(j.parts, partsRel);
const take = {
- file: rel, engine: "recorded", voice: label, label, seconds: m.seconds, source: { kind: "recorded", voice: label }, script: String(script ?? entry.narration?.script ?? ""),
- at: new Date().toISOString(), ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), ...(note ? { note } : {}),
+ file: rel, engine: "recorded", voice: label, label, seconds: j.seconds, source: { kind: "recorded", voice: label }, script: String(script ?? entry.narration?.script ?? ""),
+ at: new Date().toISOString(), ...(Number.isFinite(j.lufs) ? { lufs: j.lufs } : {}), ...(note ? { note } : {}),
...(partsOut.length > 1 ? { parts: partsOut } : {}),
};
const { result, editNotes } = await withEditNotes(project, async () =>
updatePostNarration(project.dir, entry.id, { addTake: take, ...(script !== null && script !== entry.narration?.script ? { script } : {}) }, { token: await manifestToken(project.dir) }),
);
- return { take, gain: Math.round(gain * 100) / 100, target, result, editNotes };
+ return { take, gain: j.gain, target, result, editNotes };
}
diff --git a/umtool/lib/report/postReel.mjs b/umtool/lib/report/postReel.mjs
@@ -330,32 +330,92 @@ async function copyInto(projectDir, from, rel) {
/**
* The archive's pictures (each channel's posts-media/_avatars/avatars.json,
* the editor's capture-posts store: `{ <handle>: { file, url, capturedAt } }`),
- * by handle key, the newest when two channels hold one.
+ * by handle key -- the handle without `@`, LOWERCASED: the store keys a
+ * picture by the handle as X printed it ("TheQuartering"), a card or a
+ * mention may spell it otherwise ("@thequartering") -- the newest when two
+ * stores hold one.
*
- * @returns {Promise<Map<string, { handle: string, file: string, url: string | null, capturedAt: string | null }>>}
+ * `layers` is one channels tree or the trees a project reads, in order
+ * (projects/report.mjs channelsLayersFor: its own `.shadow-channels/` or
+ * `provenance.channelsDir`, then the corpus behind it). EVERY tree's store of
+ * EVERY channel is read -- not only the project's own tree, nor the first
+ * tree that holds the channel's posts: a shadow is made by copying a
+ * channel's `posts/` (and a capture or two), never its `_avatars/`, so the
+ * pictures are in the corpus while the posts are in the shadow
+ * (quartering-diet rev 9, 11 Nov: the shadow held the three channels' posts
+ * and none of their stores, `posts avatars` read the shadow alone and copied
+ * 0 of the two pictures the corpus had -- "no picture yet for
+ * @thequartering, @madamsavvy"). A channel with no store in one tree -- or in
+ * any -- is noted in `searched` and skipped, never the end of the search.
+ *
+ * @param {string | string[]} layers
+ * @param {string[]} channels
+ * @returns {Promise<{ store: Map<string, { handle: string, file: string, url: string | null, capturedAt: string | null }>,
+ * searched: Array<{ channel: string, tree: string, dir: string, state: "read" | "none" | "unreadable", pictures: number }> }>}
*/
-export async function archiveAvatars(channelsDir, channels) {
- const out = new Map();
+export async function archiveAvatarStores(layers, channels) {
+ const trees = [...new Set((Array.isArray(layers) ? layers : [layers]).filter((d) => typeof d === "string" && d).map((d) => path.resolve(d)))];
+ const store = new Map();
+ const searched = [];
for (const slug of channels) {
- const dir = path.join(channelsDir, slug, "posts-media", ARCHIVE_AVATARS_DIR);
- let doc;
- try {
- doc = JSON.parse(await readFile(path.join(dir, ARCHIVE_AVATARS_FILE), "utf8"));
- } catch {
- continue;
- }
- if (!doc || typeof doc !== "object" || Array.isArray(doc)) continue;
- for (const [h, a] of Object.entries(doc)) {
- if (!a || typeof a !== "object" || typeof a.file !== "string" || a.file.includes("/") || a.file.includes("\\") || !AVATAR_EXT_RE.test(a.file)) continue;
- const file = path.join(dir, a.file);
- if (!(await stat(file).catch(() => null))?.isFile()) continue;
- const had = out.get(handleKey(h));
- const at = typeof a.capturedAt === "string" ? a.capturedAt : null;
- if (had && (had.capturedAt ?? "") >= (at ?? "")) continue;
- out.set(handleKey(h), { handle: h.replace(/^@/, ""), file, url: typeof a.url === "string" ? a.url : null, capturedAt: at });
+ for (const tree of trees) {
+ const dir = path.join(tree, slug, "posts-media", ARCHIVE_AVATARS_DIR);
+ let doc;
+ try {
+ doc = JSON.parse(await readFile(path.join(dir, ARCHIVE_AVATARS_FILE), "utf8"));
+ } catch (e) {
+ searched.push({ channel: slug, tree, dir, state: e?.code === "ENOENT" || e?.code === "ENOTDIR" ? "none" : "unreadable", pictures: 0 });
+ continue;
+ }
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) {
+ searched.push({ channel: slug, tree, dir, state: "unreadable", pictures: 0 });
+ continue;
+ }
+ let pictures = 0;
+ for (const [h, a] of Object.entries(doc)) {
+ if (!a || typeof a !== "object" || typeof a.file !== "string" || a.file.includes("/") || a.file.includes("\\") || !AVATAR_EXT_RE.test(a.file)) continue;
+ const file = path.join(dir, a.file);
+ if (!(await stat(file).catch(() => null))?.isFile()) continue;
+ pictures += 1;
+ const k = handleKey(h);
+ const had = store.get(k);
+ const at = typeof a.capturedAt === "string" ? a.capturedAt : null;
+ if (had && (had.capturedAt ?? "") >= (at ?? "")) continue;
+ store.set(k, { handle: h.replace(/^@/, ""), file, url: typeof a.url === "string" ? a.url : null, capturedAt: at });
+ }
+ searched.push({ channel: slug, tree, dir, state: "read", pictures });
}
}
- return out;
+ return { store, searched };
+}
+
+/** The archive's pictures alone (archiveAvatarStores' `store`); `layers` one channels tree or several. */
+export async function archiveAvatars(layers, channels) {
+ return (await archiveAvatarStores(layers, channels)).store;
+}
+
+/**
+ * What archiveAvatarStores searched, in words, one line per channel: each
+ * store it read (and how many pictures it holds), and each tree that had
+ * none -- so "no picture" says WHERE it looked. PURE.
+ *
+ * @param {Array<{ channel: string, tree: string, dir: string, state: string, pictures: number }>} searched
+ * @returns {string[]}
+ */
+export function avatarStoresSaid(searched) {
+ const by = new Map();
+ for (const s of searched ?? []) {
+ if (!by.has(s.channel)) by.set(s.channel, []);
+ by.get(s.channel).push(s);
+ }
+ const lines = [];
+ for (const [channel, rows] of by) {
+ const said = rows.filter((r) => r.state === "read").map((r) => `${r.pictures} picture(s) in ${r.dir}`);
+ const none = rows.filter((r) => r.state !== "read");
+ if (none.length) said.push(`no ${ARCHIVE_AVATARS_DIR}/ in ${none.map((r) => `${r.tree}${r.state === "unreadable" ? ` (${ARCHIVE_AVATARS_FILE} unreadable)` : ""}`).join(" or ")}`);
+ lines.push(`${channel}: ${said.join("; ")}`);
+ }
+ return lines;
}
/** Every handle an entry's card draws UNBLURRED (a redacted author never gets a picture). */
@@ -482,9 +542,9 @@ export async function postsReel(project, o) {
entries.push(made.entry);
dropped += made.dropped;
}
- // The authors' pictures: the archive's, for every author the cards draw unblurred that the cut has none of.
- const store = new Map();
- for (const c of channels) for (const [k, v] of await archiveAvatars(await root(c), [c])) if (!store.has(k)) store.set(k, v);
+ // The authors' pictures: the archive's, for every author the cards draw unblurred that the cut has none of --
+ // from every tree's store (the project's, the corpus behind it), not only the tree its posts were read from.
+ const store = await archiveAvatars(layers, channels);
const avatars = store.size ? await avatarsToCopy(manifest, entries, store, o.dryRun ? async (_f, rel) => rel : (from, rel) => copyInto(project.dir, from, rel)) : {};
const summary = { channels, channelsDir, archived: index.size, selected: picked.length, already, added: entries.length, droppedMedia: dropped, avatars: Object.keys(avatars) };
if (o.dryRun) return { ...summary, entries, dryRun: true, result: null, editNotes: null };
@@ -548,8 +608,8 @@ export async function postItemFromArchive(project, manifest, slug, postId, { id
* @param {{ channelsDir?: string | null }} [o]
*/
export async function archiveAvatarsFor(project, manifest, channels, entries, { channelsDir = null } = {}) {
- const dir = channelsDir ?? channelsDirFor(project.dir, manifest);
- const store = await archiveAvatars(dir, channels);
+ // Every tree the project reads (its own, the corpus behind it): a shadow copies posts, not the stores.
+ const store = await archiveAvatars(channelsDir ?? channelsLayersFor(project.dir, manifest), channels);
if (!store.size) return {};
return avatarsToCopy(manifest, entries, store, (from, rel) => copyInto(project.dir, from, rel));
}
diff --git a/umtool/lib/report/postRevoice.mjs b/umtool/lib/report/postRevoice.mjs
@@ -210,12 +210,16 @@ export function revoicePlan(entry, { match, occurrence = 1, say, voice = null, x
to: { lo: r3(Math.min(Math.max(to, b.end), Math.max(to - REVOICE_REACH_WIDE, b.end))), hi: r3(Math.min(total, to + REVOICE_REACH_WIDE, next ? next.end : total)) },
};
const v = voice ?? voiceOf(entry, take, parts[part], render);
+ const partSpeed = parts[part]?.speed ?? (parts.length ? null : take.speed ?? null);
+ const speed = typeof partSpeed === "number" && Number.isFinite(partSpeed) && partSpeed !== 1 && engine !== "orpheus" ? partSpeed : null;
const spoken = red ? spokenOf(say, entry, red) : { text: say, lexicon: [] };
const fixedAt = (Array.isArray(entry.fx) ? entry.fx : []).filter((fx) => fin(fx?.at)).length;
return {
take, picked, recut, target, first, last, phrase: words.slice(first, last + 1).map((w) => w.w).join(" "),
nominal: { from: r3(from), to: r3(Math.min(total, to)) }, windows, wide,
- say, said: spoken.text, lexicon: spoken.lexicon, voice: v, engine, key: partKey(engine, v, spoken.text), part, xfade, fixedAt,
+ // The speed the part it sits in was synthesized at (its character's preset's, or the read's --speed): the phrase
+ // put in is asked at it too, so it does not sound slower or faster than the words around it.
+ say, said: spoken.text, lexicon: spoken.lexicon, voice: v, engine, ...(speed !== null ? { speed } : {}), key: partKey(engine, v, spoken.text, speed), part, xfade, fixedAt,
};
}
@@ -390,7 +394,7 @@ export async function revoiceTake(project, e, o) {
const askTts = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorTts;
emit("note", { message: `re-voicing "${plan.phrase}" as "${plan.said}" (${plan.engine} · ${plan.voice}): asking the editor…` });
try {
- ({ jobId = null } = (await askTts({ text: plan.said, engine: plan.engine, voice: plan.voice, out: wav }, { ...(editor ? { editor } : {}), emit })) ?? {});
+ ({ jobId = null } = (await askTts({ text: plan.said, engine: plan.engine, voice: plan.voice, out: wav, ...(typeof plan.speed === "number" ? { speed: plan.speed } : {}) }, { ...(editor ? { editor } : {}), emit })) ?? {});
} catch (err) {
throw new RevoiceError(`"${plan.said}" (${plan.voice}) was not synthesized: ${err instanceof Error ? err.message : err}`);
}
diff --git a/umtool/lib/report/postRevoice.test.mjs b/umtool/lib/report/postRevoice.test.mjs
@@ -53,6 +53,26 @@ function tones(seconds, spans, { amp = 0.2, freq = 220 } = {}) {
return x;
}
+test("a re-voice is asked at the speed its part was synthesized at (a character's preset's, the read's --speed); Orpheus has none", async () => {
+ const { partKey } = await import("./postThreadRead.mjs");
+ const fast = (engine) => {
+ const e = item();
+ const t = e.narration.takes[0];
+ t.engine = engine;
+ t.parts[0].speed = 1.2;
+ return e;
+ };
+ const p = revoicePlan(fast("kokoro"), ASK);
+ assert.equal(p.speed, 1.2);
+ assert.equal(p.key, partKey("kokoro", p.voice, p.said, 1.2), "another speed is another cached part");
+ assert.notEqual(p.key, partKey("kokoro", p.voice, p.said));
+ // The second part has no speed of its own: asked as before.
+ const q = revoicePlan(fast("kokoro"), { match: "4", occurrence: 2, say: "four" });
+ assert.equal(q.speed, undefined);
+ assert.equal(q.key, partKey("kokoro", q.voice, q.said));
+ assert.equal(revoicePlan(fast("orpheus"), ASK).speed, undefined);
+});
+
test("THE ASK: the phrase and #n, --say, --voice (auto: the piece's own), --xfade 0-0.2 (default 0.03); the refusals are usage errors", () => {
assert.deepEqual(parseRevoice({ phrase: "20 10 4 0", say: " 20... 10... " }), { match: "20 10 4 0", occurrence: 1, say: "20... 10...", voice: null, xfade: 0.03, cut: null });
assert.deepEqual(parseRevoice({ phrase: "4#2", say: "four", voice: "auto", xfade: "0.05" }), { match: "4", occurrence: 2, say: "four", voice: null, xfade: 0.05, cut: null });
diff --git a/umtool/lib/report/postSay.mjs b/umtool/lib/report/postSay.mjs
@@ -293,6 +293,9 @@ export async function voicesCommand(project, rest, { json = false, out = (s) =>
const k = postNarrationKnobs({}, manifest.render ?? {});
const castRead = await castForProject(project.dir);
const cast = castVoiceMap(castRead.cast);
+ // The layers a read asks (characterLayers.mjs): this video's own characters over this map, then the cast -- so the
+ // table says what a read would say, and why.
+ const L = await (await import("./characterLayers.mjs")).readLayers(project.dir);
// Every author a thread read could voice: the items' own, their parents', quoted and linked posts'.
const authors = new Map();
const count = (h, own) => {
@@ -312,9 +315,11 @@ export async function voicesCommand(project, rest, { json = false, out = (s) =>
}
// Each author's voice as a context post, and WHERE it comes from: the project's map, the cast, the default.
const rows = [...authors.values()].sort((a, b) => b.items + b.context - (a.items + a.context)).map((a) => {
- const v = voiceSourceOf({ handle: a.handle, role: "parent:0" }, { map, cast, narrator: k.voice, engine: k.engine });
+ const v = voiceSourceOf({ handle: a.handle, role: "parent:0" }, { map: L.map, cast: L.castMap, narrator: k.voice, engine: k.engine });
const c = characterOf(castRead.cast, a.handle);
- return { ...a, voice: v.spec, from: v.from, mapped: a.handle in map, ...(c ? { character: c.id, castVoice: c.voice } : {}) };
+ // `own`: this video's own character that answers for the handle (narration/characters.json), before the map.
+ const own = v.from === "project" && v.character ? v.character : null;
+ return { ...a, voice: v.spec, from: v.from, ...(typeof v.speed === "number" ? { speed: v.speed } : {}), mapped: a.handle in map, ...(own ? { own } : {}), ...(c ? { character: c.id, castVoice: c.voice } : {}) };
});
if (json) out(JSON.stringify({ ok: true, file: VOICES_FILE, voices: map, narrator: k.voice, engine: k.engine, cast: { file: castRead.file, characters: Object.keys(cast).length, ...(castRead.error ? { error: castRead.error } : {}) }, authors: rows }, null, 2));
else {
@@ -322,7 +327,8 @@ export async function voicesCommand(project, rest, { json = false, out = (s) =>
for (const [h, v] of Object.entries(map)) out(` ${h === VOICE_MAP_OTHER ? "* (everyone else)" : `@${h}`} -> ${v}${cast[h] && cast[h] !== v ? ` (the cast says ${cast[h]}: overridden here)` : ""}`);
if (castRead.error) out(` the cast is not read: ${castRead.error}`);
if (rows.length) out(" the cut's authors, as a context post (their own items read in the narrator's voice unless mapped or cast):");
- for (const r of rows) out(` @${r.handle} ${r.voice} (${r.from === "project" ? "project" : r.from === "cast" ? `cast: ${r.character}` : "default"}) -- ${r.items} item(s), ${r.context} context post(s)`);
+ if (L.projectRead.error) out(` this video's own characters are not read: ${L.projectRead.error}`);
+ for (const r of rows) out(` @${r.handle} ${r.voice}${r.speed !== undefined ? ` ×${r.speed}` : ""} (${r.from === "project" ? (r.own ? `this video's character: ${r.own}${r.mapped ? "; the map's entry is under it" : ""}` : "project") : r.from === "cast" ? `cast: ${r.character}` : "default"}) -- ${r.items} item(s), ${r.context} context post(s)`);
}
return 0;
}
diff --git a/umtool/lib/report/postThreadRead.mjs b/umtool/lib/report/postThreadRead.mjs
@@ -56,7 +56,7 @@ import { chronoPieces } from "umtool-report-to-video/post-thread";
import { cardText, parentsOf } from "umtool-report-to-video/post-item";
import { planContext } from "umtool-report-to-video/post-conversation";
import { spokenRead } from "umtool-report-to-video/post-redact";
-import { resolvePieceVoice } from "umtool-report-to-video/post-say";
+import { readSpeedOf, resolvePieceVoice } from "umtool-report-to-video/post-say";
import { readManifest } from "../projects/report.mjs";
import { withEditNotes } from "./edit-guard.mjs";
import { manifestToken, updatePostNarration } from "./manifest.mjs";
@@ -81,11 +81,12 @@ export class ThreadReadError extends Error {
export const THREAD_READ_USAGE = [
" umtool posts narrate <project> <item> --take --thread [--parents 0|all|none|<n>] [--skip-parent <id|parent:i>]…",
- " [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e]",
+ " [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--speed s]",
" [--note \"…\"] [--force] [--no-hold] [--dry-run] [--json]",
" A THREAD READ: the post it answers (--parents all: every ancestor; none: no parent), the post it quotes, the posts",
" its words link to and his words, in DATE order, each in its author's voice (the project's voice map, umtool posts",
- " voices; --voice-for handle=voice for this read), the redaction, the slur filter and the pronunciation lexicon",
+ " voices; --voice-for handle=voice for this read) and at its character's SPEED (its synthetic preset's; --speed s:",
+ " every part at that one; Orpheus has no speed), the redaction, the slur filter and the pronunciation lexicon",
" (umtool posts say) applied. A parent or quoted post the item before already shows is not read again (--read-seen:",
" it is). Each part is synthesized once by the editor (its tts op, a job) into narration/parts-cache/ and reused by",
" every read after; the take (take-<n>.<engine>-thread.wav + take-<n>.parts.json) is saved with its parts' roles and",
@@ -94,15 +95,22 @@ export const THREAD_READ_USAGE = [
" could not be synthesized (the parts already made stay cached: run it again).",
].join("\n");
-/** The project's cast as a voice map (castStore.mjs: the cast the project reads; `{}` with none, or a broken one). */
+/**
+ * The project's cast as a preset layer (castStore.mjs: the cast the project reads; `{}` with none, or a broken one):
+ * `{ handle: { voice, speed?, character } }` (cast.mjs castPresetMap), voiceSourceOf's `cast`.
+ */
export async function projectCastMap(dir) {
const { castForProject } = await import("./castStore.mjs");
- const { castVoiceMap } = await import("umtool-report-to-video/cast");
- return castVoiceMap((await castForProject(dir)).cast);
+ const { castPresetMap } = await import("umtool-report-to-video/cast");
+ return castPresetMap((await castForProject(dir)).cast);
}
-/** A part's cache key: sha1 of `voice|text` (an engine other than Orpheus: `engine|voice|text`). */
-export const partKey = (engine, voice, text) => createHash("sha1").update(engine === "orpheus" ? `${voice}|${text}` : `${engine}|${voice}|${text}`).digest("hex");
+/**
+ * A part's cache key: sha1 of `voice|text` (an engine other than Orpheus: `engine|voice|text`), and of its SPEED when
+ * it is read at one (`…|x1.1`: the same words at another speed are another part; none, or 1: the key as before).
+ */
+/** @type {(engine: string, voice: string, text: string, speed?: number | null) => string} */
+export const partKey = (engine, voice, text, speed = null) => createHash("sha1").update(`${engine === "orpheus" ? `${voice}|${text}` : `${engine}|${voice}|${text}`}${typeof speed === "number" && speed !== 1 ? `|x${speed}` : ""}`).digest("hex");
/** `--parents` as a selector: "0" (default), "all", "none", or a whole number n (parents 0..n). */
export function parentsSelector(v) {
@@ -135,14 +143,16 @@ export function seenIds(manifest, e) {
*
* @param {Record<string, any>} manifest
* @param {Record<string, any>} e the post item
- * `cast` is the cast as a voice map (cast.mjs castVoiceMap: `{ handle: "engine:voice" }`). Each piece's `engine` is
- * its voice's (a voice that names one), else the read's; `from` where its voice came from (post-say.mjs voiceSourceOf).
- * The read's `engine` is his piece's.
+ * `map`, `cast` and `item` are voiceSourceOf's layers (cast.mjs projectPresetMap, castPresetMap, itemPresetOf: an entry
+ * a voice as written, or a character's preset `{ voice, speed?, character }`). Each piece's `engine` is its voice's
+ * (a voice that names one), else the read's; `from` where its voice came from (post-say.mjs voiceSourceOf); `speed`
+ * the speed it is asked at (readSpeedOf: the command's `speed`, else the item's own for his words, else its
+ * character's preset's -- none for Orpheus, which has none, or at 1). The read's `engine` is his piece's.
*
- * @param {{ red?: any, map?: Record<string, string>, cast?: Record<string, string>, overrides?: Record<string, string>, parents?: string,
- * skip?: string[], quoted?: boolean, linked?: boolean, readSeen?: boolean, voice?: string | null, engine?: string | null }} [o]
+ * @param {{ red?: any, map?: Record<string, any>, cast?: Record<string, any>, item?: any, overrides?: Record<string, string>, parents?: string,
+ * skip?: string[], quoted?: boolean, linked?: boolean, readSeen?: boolean, voice?: string | null, engine?: string | null, speed?: number | null }} [o]
*/
-export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null } = {}) {
+export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, item = null, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null, speed = null } = {}) {
const render = manifest?.render ?? {};
const k = postNarrationKnobs(e, render);
const eng = engine ?? e.narration?.engine ?? k.engine;
@@ -200,8 +210,9 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, o
skipped.push({ role: p.role, why: "nothing left to say (all of it redacted)" });
continue;
}
- const v = resolvePieceVoice({ handle: p.handle, role: p.role }, { map, cast, overrides, self: str(e.handle), voice, narrator, engine: eng });
- pieces.push({ role: p.role, handle: p.handle, date: p.date, voice: v.voice, engine: v.engine, from: v.from, written, text: said.text.trim(), lexicon: said.lexicon ?? [], slurs: said.slurs });
+ const v = resolvePieceVoice({ handle: p.handle, role: p.role }, { map, cast, item, overrides, self: str(e.handle), voice, narrator, engine: eng });
+ const spd = readSpeedOf({ flag: speed, preset: v.speed ?? null, own: p.role === "post" ? e.narration?.speed ?? null : null, engine: v.engine });
+ pieces.push({ role: p.role, handle: p.handle, date: p.date, voice: v.voice, engine: v.engine, from: v.from, ...(spd !== null ? { speed: spd } : {}), ...(v.character ? { character: v.character } : {}), written, text: said.text.trim(), lexicon: said.lexicon ?? [], slurs: said.slurs });
}
if (!pieces.some((p) => p.role === "post")) throw new ThreadReadError(`${e.id} has no words of his own to read (--script "…" first)`);
const lexicon = [...new Map(pieces.flatMap((p) => p.lexicon).map((x) => [`${x.word.toLowerCase()}|${x.item ?? ""}`, x])).values()];
@@ -218,12 +229,12 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, o
export function readParts(plan) {
return plan.pieces.flatMap((pc, piece) => {
const eng = pc.engine ?? plan.engine;
- return scriptParts(pc.text).map((q) => ({ piece, para: q.para, role: pc.role, voice: pc.voice, engine: eng, text: q.text, key: partKey(eng, pc.voice, q.text) }));
+ return scriptParts(pc.text).map((q) => ({ piece, para: q.para, role: pc.role, voice: pc.voice, engine: eng, ...(pc.speed !== undefined ? { speed: pc.speed } : {}), text: q.text, key: partKey(eng, pc.voice, q.text, pc.speed ?? null) }));
});
}
-/** Each piece's `engine:voice`, in order, once each -- what a read sounds like, for "is it up to date". */
-const voiceSig = (rows, fallback) => [...new Set(rows.map((p) => `${p.engine ?? fallback}:${p.voice}`))].join("+");
+/** Each piece's `engine:voice` (and its speed, when it has one), in order, once each -- what a read sounds like, for "is it up to date". */
+const voiceSig = (rows, fallback) => [...new Set(rows.map((p) => `${p.engine ?? fallback}:${p.voice}${typeof p.speed === "number" && p.speed !== 1 ? `x${p.speed}` : ""}`))].join("+");
/**
* THE JOIN's TIMES, pure: each part's start in the take, its length, the gap before it (POST_PART_GAP: a new piece,
@@ -237,7 +248,7 @@ export function joinTimes(parts, seconds, { fileOf = (p) => `${PARTS_CACHE}/${p.
const gap = !prev ? 0 : p.piece !== prev.piece ? POST_PART_GAP.piece : p.para !== prev.para ? POST_PART_GAP.para : POST_PART_GAP.inside;
t += gap;
const s = Number(seconds[i]);
- const row = { n: i + 1, para: p.piece * 100 + p.para, text: p.text, voice: p.voice, ...(p.engine ? { engine: p.engine } : {}), role: p.role, piece: p.piece, file: fileOf(p), start: r3(t), seconds: r3(s), gapBefore: gap };
+ const row = { n: i + 1, para: p.piece * 100 + p.para, text: p.text, voice: p.voice, ...(p.engine ? { engine: p.engine } : {}), ...(typeof p.speed === "number" ? { speed: p.speed } : {}), role: p.role, piece: p.piece, file: fileOf(p), start: r3(t), seconds: r3(s), gapBefore: gap };
t += s;
return row;
});
@@ -245,11 +256,13 @@ export function joinTimes(parts, seconds, { fileOf = (p) => `${PARTS_CACHE}/${p.
}
/** The `read` record of a take: how it was asked for (only what differs from the defaults). */
-export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = true, readSeen = false, overrides = {}, voice = null }) {
+export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = true, readSeen = false, overrides = {}, voice = null, speed = null }) {
return {
kind: "thread", parents: parentsSelector(parents),
...(skip?.length ? { skip: [...skip] } : {}), ...(quoted ? {} : { quoted: false }), ...(linked ? {} : { linked: false }),
...(readSeen ? { seen: true } : {}), ...(Object.keys(overrides ?? {}).length ? { voiceFor: { ...overrides } } : {}), ...(voice ? { voice } : {}),
+ // The speed the command asked for the whole read (`--speed`); a character's own is its preset's, not the read's.
+ ...(typeof speed === "number" && Number.isFinite(speed) ? { speed } : {}),
};
}
@@ -257,9 +270,9 @@ export function readRecordOf({ parents = "0", skip = [], quoted = true, linked =
export function upToDate(e, plan) {
const t = pickedTake(e);
if (!t || norm(t.script) !== norm(plan.want) || str(t.voice) !== plan.voice || (t.engine ?? "orpheus") !== plan.engine) return false;
- // A take whose parts say their voices: each piece in the same engine and voice.
+ // A take whose parts say their voices: each piece in the same engine and voice, at the same speed.
const parts = Array.isArray(t.parts) ? t.parts.filter((p) => typeof p?.voice === "string") : [];
- if (!parts.length) return true;
+ if (!parts.length) return !plan.pieces.some((p) => typeof p.speed === "number");
return voiceSig(parts, t.engine ?? "orpheus") === voiceSig(plan.pieces, plan.engine);
}
@@ -281,16 +294,20 @@ async function durationOf(file) {
*/
export async function threadTake(project, e, opts = {}) {
const {
- manifest: m0 = null, red: red0 = undefined, map: map0 = undefined, cast: cast0 = undefined, overrides = {}, parents = "0", skip = [], quoted = true, linked = true,
- readSeen = false, voice = null, engine = null, note = null, force = false, hold = true, dryRun = false,
+ manifest: m0 = null, red: red0 = undefined, map: map0 = undefined, cast: cast0 = undefined, item: item0 = undefined, overrides = {}, parents = "0", skip = [], quoted = true, linked = true,
+ readSeen = false, voice = null, engine = null, speed = null, note = null, force = false, hold = true, dryRun = false,
ask = null, lanes: lanes0 = undefined, emit = () => {}, editor = null, signals = false,
} = opts;
const manifest = m0 ?? (await readManifest(project.dir));
if (!manifest) throw new ThreadReadError(`${project.id} has no manifest`);
const red = red0 !== undefined ? red0 : await (await import("./postRedaction.mjs")).projectRedaction(project.dir, manifest);
- const map = map0 !== undefined ? map0 : await (await import("./postSay.mjs")).readVoiceMap(project.dir);
- const cast = cast0 !== undefined ? cast0 : await projectCastMap(project.dir);
- const plan = threadReadPlan(manifest, e, { red, map, cast, overrides, parents, skip, quoted, linked, readSeen, voice, engine });
+ // The layers (characterLayers.mjs): the project's characters over its voice map (a broken map refuses the read), the
+ // cast, the item's own character -- each the caller's when it hands one in.
+ const L = map0 !== undefined && cast0 !== undefined && item0 !== undefined ? null : await (await import("./characterLayers.mjs")).readLayers(project.dir, { strictMap: map0 === undefined });
+ const map = map0 !== undefined ? map0 : L.map;
+ const cast = cast0 !== undefined ? cast0 : L.castMap;
+ const item = item0 !== undefined ? item0 : L?.itemOf(e) ?? null;
+ const plan = threadReadPlan(manifest, e, { red, map, cast, item, overrides, parents, skip, quoted, linked, readSeen, voice, engine, speed });
const parts = readParts(plan);
const cacheDir = path.join(project.dir, ...PARTS_CACHE.split("/"));
const wavOf = (p) => path.join(cacheDir, `${p.key}.wav`);
@@ -353,7 +370,7 @@ export async function threadTake(project, e, opts = {}) {
emit("note", { message: `part ${n + 1}/${todo.length} (${p.role}, ${p.engine === plan.engine ? p.voice : `${p.engine}:${p.voice}`}): asking the editor…` });
await writeFile(path.join(cacheDir, `${p.key}.txt`), p.text);
try {
- const { jobId } = await askTts({ text: p.text, engine: p.engine ?? plan.engine, voice: p.voice, out: wavOf(p) }, { ...(editor ? { editor } : {}), emit });
+ const { jobId } = await askTts({ text: p.text, engine: p.engine ?? plan.engine, voice: p.voice, out: wavOf(p), ...(typeof p.speed === "number" ? { speed: p.speed } : {}) }, { ...(editor ? { editor } : {}), emit });
if (jobId) jobs.push(jobId);
} catch (err) {
throw new ThreadReadError(`part ${p.role} "${p.text.slice(0, 60)}${p.text.length > 60 ? "…" : ""}" (${p.voice}) was not synthesized: ${err instanceof Error ? err.message : err} -- the ${fresh + base.cached} part(s) made are cached; run it again`);
@@ -397,7 +414,7 @@ export async function threadTake(project, e, opts = {}) {
parts: meta,
...(plan.slurs ? { slurs: plan.slurs } : {}),
...(plan.lexicon.length ? { lexicon: plan.lexicon } : {}),
- read: readRecordOf({ parents, skip, quoted, linked, readSeen, overrides, voice }),
+ read: readRecordOf({ parents, skip, quoted, linked, readSeen, overrides, voice, speed }),
};
const patch = { addTake: take, ...(plan.script ? { script: plan.script } : {}) };
const { result, editNotes } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, patch, { token: await manifestToken(project.dir) }));
@@ -429,19 +446,19 @@ export async function threadCommand(project, e, o) {
}
throw err;
}
- const pieces = r.plan.pieces.map((p) => ({ role: p.role, handle: p.handle, date: p.date, voice: p.voice, engine: p.engine, from: p.from, words: p.text.split(/\s+/).filter(Boolean).length, ...(p.lexicon.length ? { lexicon: p.lexicon } : {}) }));
+ const pieces = r.plan.pieces.map((p) => ({ role: p.role, handle: p.handle, date: p.date, voice: p.voice, engine: p.engine, from: p.from, ...(p.speed !== undefined ? { speed: p.speed } : {}), ...(p.character ? { character: p.character } : {}), words: p.text.split(/\s+/).filter(Boolean).length, ...(p.lexicon.length ? { lexicon: p.lexicon } : {}) }));
const guard = r.take ? await guardOf(project, e.id) : null;
if (json) {
out(JSON.stringify({
ok: true, id: e.id, upToDate: r.upToDate, dryRun: r.dryRun, engine: r.plan.engine, voice: r.plan.voice, pieces, skipped: r.plan.skipped,
- parts: r.parts.map((p) => ({ role: p.role, voice: p.voice, engine: p.engine, key: p.key, cached: p.cached, text: p.text })),
+ parts: r.parts.map((p) => ({ role: p.role, voice: p.voice, engine: p.engine, ...(p.speed !== undefined ? { speed: p.speed } : {}), key: p.key, cached: p.cached, text: p.text })),
fresh: r.fresh, cached: r.cached, jobs: r.jobs, lane: r.lane,
...(r.take ? { take: r.take, pick: r.result.narration?.pick ?? null, token: r.result.token, snapshot: r.result.snapshot ?? null, guard } : {}),
}, null, 2));
return 0;
}
out(`${e.id}: a thread read of ${pieces.length} piece(s), ${r.parts.length} part(s) (${r.cached} cached${r.dryRun ? `, ${r.parts.length - r.cached} to synthesize` : ""})`);
- for (const p of pieces) out(` ${p.role.padEnd(9)} ${(p.engine !== r.plan.engine ? `${p.engine}:${p.voice}` : p.voice).padEnd(6)} ${p.from === "cast" ? "(cast) " : ""}${p.handle ? `@${p.handle}` : ""}${p.date ? ` ${p.date.slice(0, 16)}` : ""} ${p.words} words${p.lexicon ? ` (said: ${p.lexicon.map((x) => `${x.word} -> ${x.say}`).join(", ")})` : ""}`);
+ for (const p of pieces) out(` ${p.role.padEnd(9)} ${(p.engine !== r.plan.engine ? `${p.engine}:${p.voice}` : p.voice).padEnd(6)} ${p.from === "cast" ? "(cast) " : p.from === "item" ? `(the item's character: ${p.character}) ` : p.from === "project" && p.character ? `(this video's character: ${p.character}) ` : ""}${p.speed !== undefined ? `×${p.speed} ` : ""}${p.handle ? `@${p.handle}` : ""}${p.date ? ` ${p.date.slice(0, 16)}` : ""} ${p.words} words${p.lexicon ? ` (said: ${p.lexicon.map((x) => `${x.word} -> ${x.say}`).join(", ")})` : ""}`);
for (const s of r.plan.skipped) out(` (not read: ${s.role}${s.id ? ` ${s.id}` : ""} -- ${s.why})`);
if (r.upToDate) {
out(` up to date: the picked take already reads this, in these voices (--force makes it again)`);
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -80,6 +80,9 @@ const SAY_LINES = [
" masked slur and a redacted word are never replaced. stale: the picked reads that still say one the old way.",
" umtool posts voices <project> [ls] | set <handle|*> <voice> | remove <handle|*> [--json]",
" THE VOICE MAP (narration/voices.json): the voice a thread read gives each author (* everyone else; default leo).",
+ " umtool posts character <project> <item> [<character> | --clear] [--json]",
+ " THE CHARACTER ONE ITEM's OWN READ IS MADE WITH: one of this video's own (umtool cast project <p>) or the cast's;",
+ " its presets answer before its author's handle does. --clear: by its handle again (posts character --help).",
];
export const POSTS_USAGE = [
@@ -195,9 +198,9 @@ export const POSTS_USAGE = [
" none: the rule as it stands",
].join("\n");
-const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item", "--recording", "--as", "--label"]);
+const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--pitch", "--semitones", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item", "--recording", "--as", "--label", "--out", "--trim-span"]);
/** The valued flags that may be given more than once (each value kept, in order). */
-const MULTI = new Set(["--skip-parent", "--voice-for"]);
+const MULTI = new Set(["--skip-parent", "--voice-for", "--trim-span"]);
const SLUG_RE = /^[A-Za-z0-9._-]+$/;
const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
@@ -447,7 +450,7 @@ export async function addPostFromArchive(project, { slug, postId, attach = null,
* @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts]
* @returns {Promise<number>} the exit code
*/
-export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
+export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), ask = null } = {}) {
// A TAKE-SCOPED EDIT (`--in-take <take>`, takeScope.mjs): the same command over the take's manifest, written into its patch.
let scoped;
try {
@@ -523,6 +526,15 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
throw e?.name === "RereadError" || e?.name === "YellError" ? new CliError(e.message) : e;
});
}
+ if (verb === "character") {
+ // A post item's own character (postNarrationCli.mjs characterCommand; cast.mjs).
+ const { CHARACTER_USAGE, characterCommand } = await import("./postNarrationCli.mjs");
+ if (!projectArg || flags.has("--help") || words.length < 3) {
+ err(CHARACTER_USAGE);
+ return 2;
+ }
+ return await characterCommand(await projectOf(projectArg, root), words.slice(2), { flags, json, out });
+ }
if (verb === "narrate") {
const { NARRATE_USAGE, narrateCommand } = await import("./postNarrationCli.mjs");
if (!projectArg || flags.has("--help")) {
@@ -537,7 +549,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
const named = words.slice(3).find((w) => takes.has(w));
if (named) throw new CliError(`posts narrate: --take makes a NEW READ (TTS); "${named}" is a take of ${project.id} -- to edit take ${named}, say --in-take ${named}`);
}
- return await narrateCommand(project, words.slice(2), flags, { json, dryRun, out, str, multi });
+ return await narrateCommand(project, words.slice(2), flags, { json, dryRun, out, str, multi, ask });
}
if (verb === "fx") {
const { FX_USAGE, fxCommand } = await import("./postFxCli.mjs");
@@ -1319,8 +1331,14 @@ async function avatarCommand(projectArg, rest, { root, json, out }) {
else for (const [h, a] of Object.entries(map)) out(`@${h} ${a.src} (${a.source ?? "manual"}${a.capturedAt ? `, captured ${String(a.capturedAt).slice(0, 10)}` : ""})`);
return 0;
}
- const h = String(handle).replace(/^@/, "");
- if (!/^[A-Za-z0-9_.-]{1,64}$/.test(h)) throw new CliError(`"${handle}" is not a handle`);
+ const typed = String(handle).replace(/^@/, "");
+ if (!/^[A-Za-z0-9_.-]{1,64}$/.test(typed)) throw new CliError(`"${handle}" is not a handle`);
+ // Matched without regard to case (post-avatars.mjs handleKey): "thequartering" sets the picture of the
+ // author the cards draw as "TheQuartering", and is kept under that spelling (the first card's).
+ const { handleKey } = await import("umtool-report-to-video/post-avatars");
+ const { shownHandles } = await import("./postReel.mjs");
+ const drawnAs = ((await readManifest(project.dir))?.timeline ?? []).flatMap((e) => shownHandles(e)).map((x) => String(x).replace(/^@/, "")).find((x) => handleKey(x) === handleKey(typed));
+ const h = drawnAs && /^[A-Za-z0-9_.-]{1,64}$/.test(drawnAs) ? drawnAs : typed;
if (!file) throw new CliError(`name the picture: umtool posts avatar ${project.id} ${h} <image-file> (or off)`);
if (OFF.has(String(file).toLowerCase())) {
const { result, editNotes } = await withEditNotes(project, async () => setPostAvatar(project.dir, h, null, { token: await manifestToken(project.dir) }));
@@ -1354,10 +1372,13 @@ async function avatarsCommand(projectArg, { root, json, dryRun, out }) {
const project = await projectOf(projectArg, root);
const manifest = await readManifest(project.dir);
if (!manifest) throw new CliError(`${project.id} has no manifest`);
- const { archiveAvatars, avatarsToCopy, postChannelsOf, shownHandles } = await import("./postReel.mjs");
- const { channelsDirFor } = await import("../projects/report.mjs");
+ const { archiveAvatarStores, avatarStoresSaid, avatarsToCopy, postChannelsOf, shownHandles } = await import("./postReel.mjs");
+ const { channelsLayersFor } = await import("../projects/report.mjs");
+ const { handleKey } = await import("umtool-report-to-video/post-avatars");
const channels = postChannelsOf(manifest);
- const store = await archiveAvatars(channelsDirFor(project.dir, manifest), channels);
+ // Every tree the project reads -- its own (.shadow-channels/, provenance.channelsDir) and the corpus behind
+ // it: a shadow copies a channel's posts, never its _avatars/ (postReel.mjs archiveAvatarStores).
+ const { store, searched } = await archiveAvatarStores(channelsLayersFor(project.dir, manifest), channels);
const pics = store.size
? await avatarsToCopy(manifest, [], store, dryRun ? async (_f, rel) => rel : async (from, rel) => {
const to = path.join(project.dir, ...rel.split("/"));
@@ -1366,16 +1387,21 @@ async function avatarsCommand(projectArg, { root, json, dryRun, out }) {
return rel;
})
: {};
- const drawn = [...new Set((manifest.timeline ?? []).flatMap((e) => shownHandles(e)).map((h) => h.toLowerCase()))];
- const have = Object.keys(manifest.postAvatars ?? {}).map((h) => h.toLowerCase());
- const without = drawn.filter((h) => !have.includes(h) && !Object.keys(pics).some((p) => p.toLowerCase() === h));
+ // The authors drawn, compared by handle key (no @, any case), each said as its first card spells it.
+ const drawnAs = new Map();
+ for (const h of (manifest.timeline ?? []).flatMap((e) => shownHandles(e))) if (!drawnAs.has(handleKey(h))) drawnAs.set(handleKey(h), String(h).replace(/^@/, ""));
+ const have = new Set([...Object.keys(manifest.postAvatars ?? {}), ...Object.keys(pics)].map(handleKey));
+ const without = [...drawnAs].filter(([k]) => !have.has(k)).map(([, h]) => h);
let result = null;
if (!dryRun && Object.keys(pics).length) ({ result } = await withEditNotes(project, async () => addArchiveAvatars(project.dir, pics, { token: await manifestToken(project.dir) })));
if (json) {
- out(JSON.stringify({ ok: true, dryRun, channels, copied: pics, without, snapshot: result?.snapshot ?? null }, null, 2));
+ out(JSON.stringify({ ok: true, dryRun, channels, stores: searched, copied: pics, without, snapshot: result?.snapshot ?? null }, null, 2));
return 0;
}
- out(`${dryRun ? "would copy" : "copied"} ${Object.keys(pics).length} picture(s) from ${channels.join(" + ") || "no channel"}'s store${Object.keys(pics).length ? `: ${Object.keys(pics).map((h) => `@${h}`).join(", ")}` : ""}`);
+ const read = [...new Set(searched.filter((s) => s.state === "read").map((s) => s.channel))];
+ out(`${dryRun ? "would copy" : "copied"} ${Object.keys(pics).length} picture(s) from ${read.length ? `${read.join(" + ")}'s store${read.length > 1 ? "s" : ""}` : "no store"}${Object.keys(pics).length ? `: ${Object.keys(pics).map((h) => `@${h}`).join(", ")}` : ""}`);
+ if (!channels.length) out(" the cut has no post item from a posts channel (post: \"<channel>/<postId>\") -- no store to read");
+ for (const line of avatarStoresSaid(searched)) out(` ${line}`);
if (without.length) out(` no picture yet for ${without.map((h) => `@${h}`).join(", ")} (pnpm ops capture-posts … "avatars": true, or umtool posts avatar ${project.id} <handle> <image>)`);
return 0;
}
diff --git a/umtool/lib/report/quoteCheck.mjs b/umtool/lib/report/quoteCheck.mjs
@@ -23,7 +23,8 @@
// --quote-ruled`: heard and ruled by a person).
//
// Plain ESM: the CLI runs under bare node; the app reads the file.
-import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { mkdir, readFile, realpath, rename, rmdir, writeFile } from "node:fs/promises";
+import os from "node:os";
import path from "node:path";
import { createCueSource, siteOriginFromManifest } from "umtool-report-to-video/cues";
import { cueWords, findQuote, ON_TIME_S, quoteOffset } from "umtool-report-to-video/quote-in-audio";
@@ -234,16 +235,90 @@ async function editorWords(req, { emit }) {
}
/**
+ * WHERE THE EDITOR WRITES THE WORDS (12 Nov): the work files were `<project>/out/quote-check/<clip>.words.json`, and
+ * a project's `out/` may be a symlink onto the media drive -- inside a corpus location, where the editor rightly
+ * refuses to write (transcribeFile.ts: `"out" … is inside the corpus`). So the work dir is never under `out/`:
+ * these, in order, each by its REAL path (a link in the way is followed here, not found out by the editor), the
+ * next one taken when the editor refuses the one before as inside the corpus --
+ *
+ * <project>/.quote-check/ beside the manifest
+ * <reports>/.umtool/quote-check/<project>/ umtool's own state, when the project dir itself is in a location
+ * $XDG_CACHE_HOME|~/.cache/umtool/quote-check/<project>/
+ *
+ * The rows are the project's whichever it is: quote-check.json, beside the manifest.
+ * @param {string} dir the project's dir
+ * @param {{ reportsRoot?: string | null, env?: Record<string, string | undefined>, home?: string }} [opts]
+ * @returns {Promise<string[]>}
+ */
+export async function quoteCheckWorkDirs(dir, { reportsRoot = null, env = process.env, home = os.homedir() } = {}) {
+ const real = async (p) => {
+ // The deepest ancestor that exists, resolved; the rest as named (the dir may not be made yet).
+ const rest = [];
+ let cur = path.resolve(p);
+ for (;;) {
+ const r = await realpath(cur).catch(() => null);
+ if (r) return path.join(r, ...rest);
+ const up = path.dirname(cur);
+ if (up === cur) return path.resolve(p);
+ rest.unshift(path.basename(cur));
+ cur = up;
+ }
+ };
+ const name = path.basename(path.resolve(dir));
+ const cache = env.XDG_CACHE_HOME && path.isAbsolute(env.XDG_CACHE_HOME) ? env.XDG_CACHE_HOME : path.join(home, ".cache");
+ const all = [
+ path.join(dir, ".quote-check"),
+ path.join(reportsRoot ?? path.dirname(path.resolve(dir)), ".umtool", "quote-check", name),
+ path.join(cache, "umtool", "quote-check", name),
+ ];
+ const out = [];
+ for (const p of all) {
+ const r = await real(p);
+ if (!out.includes(r)) out.push(r);
+ }
+ return out;
+}
+
+/**
+ * Is this the editor's refusal of an `out` inside the corpus? The controller's sentence is
+ * `"out" <path> is inside the corpus (<root>) — this command never writes there; pick a path outside it`
+ * (common/controller/transcribeFile.ts checkTranscribeFileRequest), answered at once as HTTP 400 `{ error }` by
+ * POST /api/ops/transcribe (the route's jobResponse), which askEditorOp throws as `the editor refused it (<route>,
+ * HTTP 400): <error>`. Matched on the part that says what it is -- `"out" … is inside the corpus` -- not on the path,
+ * the root or the advice after the dash (quoteCheck.test.mjs holds the controller's source to these words).
+ */
+export const OUT_INSIDE_CORPUS = /"out" .* is inside the corpus\b/;
+const insideCorpus = (e) => OUT_INSIDE_CORPUS.test(e instanceof Error ? e.message : String(e));
+
+/**
+ * Take back the directories a refused work dir cost: `dir` and every parent made for it, up to `first` (what
+ * mkdir's `recursive` says it made first) -- each only when empty (rmdir), so nothing that was there is touched
+ * and no empty `.quote-check/` is left inside a corpus location.
+ */
+async function unmake(dir, first) {
+ if (!first) return;
+ const stop = path.resolve(first);
+ let cur = path.resolve(dir);
+ for (;;) {
+ if (cur !== stop && !cur.startsWith(stop + path.sep)) return;
+ if (!(await rmdir(cur).then(() => true, () => false))) return;
+ if (cur === stop) return;
+ cur = path.dirname(cur);
+ }
+}
+
+/**
* Check the planned clips; merge the rows into quote-check.json.
* @param {string} dir
* @param {Record<string, any>} manifest
* @param {Awaited<ReturnType<typeof planQuoteCheck>>} plan
* @param {{ transcribe?: typeof editorWords, cuesOf?: (slug: string, video: string) => Promise<any[] | null>, log?: (l: string) => void, now?: () => Date }} [opts]
*/
-export async function runQuoteCheck(dir, manifest, plan, { transcribe = editorWords, cuesOf = null, log = () => {}, now = () => new Date() } = {}) {
+export async function runQuoteCheck(dir, manifest, plan, { transcribe = editorWords, cuesOf = null, log = () => {}, now = () => new Date(), workDirs = null, reportsRoot = null } = {}) {
const doc = await readQuoteCheck(dir);
- const work = path.join(dir, "out", "quote-check");
- await mkdir(work, { recursive: true });
+ // Never under out/ (quoteCheckWorkDirs): the first the editor does not refuse as inside the corpus.
+ const works = workDirs ?? (await quoteCheckWorkDirs(dir, { reportsRoot }));
+ let wi = 0;
const cueSource = cuesOf
? null
: createCueSource({ channelsDirs: channelsLayersFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) }), siteOrigin: siteOriginFromManifest(manifest) });
@@ -271,10 +346,24 @@ export async function runQuoteCheck(dir, manifest, plan, { transcribe = editorWo
log(rowLine(p.id, results[p.id]));
continue;
}
- const out = path.join(work, `${p.id}.words.json`);
let words;
try {
- words = await transcribe({ path: p.source.path, start: p.file.start, end: p.file.end, out }, { emit: () => {} });
+ for (;;) {
+ // The editor needs the directory to be there (it refuses an `out` whose directory is not), so it is made
+ // -- and taken back, with any parent made for it, the moment the editor says it is inside the corpus.
+ const made = await mkdir(works[wi], { recursive: true });
+ const out = path.join(works[wi], `${p.id}.words.json`);
+ try {
+ words = await transcribe({ path: p.source.path, start: p.file.start, end: p.file.end, out }, { emit: () => {} });
+ break;
+ } catch (e) {
+ if (!insideCorpus(e)) throw e;
+ await unmake(works[wi], made);
+ if (wi + 1 >= works.length) throw e;
+ log(`quote-check: the editor will not write in ${works[wi]} (inside the corpus) -- its work files go to ${works[wi + 1]}`);
+ wi += 1;
+ }
+ }
} catch (e) {
log(`${p.id}: the transcription failed: ${e instanceof Error ? e.message : String(e)}`);
continue;
@@ -287,7 +376,7 @@ export async function runQuoteCheck(dir, manifest, plan, { transcribe = editorWo
}
const merged = { version: 1, checkedAt: now().toISOString(), clips: { ...doc.clips, ...results } };
const file = await writeQuoteCheck(dir, merged);
- return { file, doc: merged, results };
+ return { file, doc: merged, results, work: works[wi] };
}
// ---------------------------------------------------------------------------
@@ -301,6 +390,9 @@ export const QUOTE_CHECK_USAGE = [
`Each clip's cut ±${SEARCH_PAD_S} s (--pad) of the source the render would cut it from is transcribed by the`,
"editor (its transcription lane, words on), and the quote is found in those words and in the recording's",
`cues: ok (within ${ON_TIME_S} s), moved (heard elsewhere: umtool window <p> <clip> --align), not-found.`,
+ "The editor's work files (<clip>.words.json) go to <project>/.quote-check/ -- never under out/, which may be a link",
+ "onto a media drive the editor will not write in; were the project itself inside the corpus, to umtool's own",
+ "<reports>/.umtool/quote-check/<project>/, then ~/.cache/umtool/quote-check/<project>/.",
`Rows go to <project>/${QUOTE_CHECK_FILE}; umtool check reads them, and a take refuses a moved or`,
"missing quote unless the clip is ruled (umtool window <p> <clip> --quote-ruled).",
].join("\n");
@@ -351,12 +443,13 @@ export async function quoteCheckCommand(args, { reportsRoot = REPORTS_ROOT, log
if (!channelsDirs.length) throw new CliError("no channels directory (CHANNELS_DIR) to read the windows from");
const plan = await planQuoteCheck(project.dir, manifest, { channelsDirs, clipIds, pad });
if (clipIds.length && !plan.length) throw new CliError(`none of ${clipIds.join(", ")} is a clip of ${project.id}`);
- const { file, results } = await runQuoteCheck(project.dir, manifest, plan, {
+ const { file, results, work } = await runQuoteCheck(project.dir, manifest, plan, {
...(transcribe ? { transcribe } : {}),
...(cuesOf ? { cuesOf } : {}),
+ reportsRoot,
log: json ? () => {} : log,
});
- if (json) log(JSON.stringify({ project: project.id, file, clips: results }, null, 1));
+ if (json) log(JSON.stringify({ project: project.id, file, work, clips: results }, null, 1));
else {
const count = (s) => Object.values(results).filter((x) => x.status === s).length;
log(`→ ${file}: ${count("ok")} ok, ${count("moved")} moved, ${count("not-found")} not found, ${count("no-window")} with no window`);
diff --git a/umtool/lib/report/quoteCheck.test.mjs b/umtool/lib/report/quoteCheck.test.mjs
@@ -185,3 +185,135 @@ test("prep --status says the quote check's verdicts on the clips as they are now
await rm(p.root, { recursive: true, force: true });
}
});
+
+test("the editor's work files are never under out/: <project>/.quote-check by its real path, and the next dir when the editor refuses one as inside the corpus", async () => {
+ const { quoteCheckWorkDirs } = await import("./quoteCheck.mjs");
+ const { realpath, symlink, stat } = await import("node:fs/promises");
+ const p = await project();
+ try {
+ const root = await realpath(p.root);
+ // out/ linked onto "the media drive" (rev9-a9's project): nothing of the check is written through it.
+ const drive = path.join(root, "drive", "diet-out");
+ await mkdir(path.dirname(drive), { recursive: true });
+ const { rename } = await import("node:fs/promises");
+ await rename(path.join(p.dir, "out"), drive);
+ await symlink(drive, path.join(p.dir, "out"));
+ const dirs = await quoteCheckWorkDirs(p.dir, { reportsRoot: p.root, env: { XDG_CACHE_HOME: path.join(root, "cache") } });
+ assert.deepEqual(dirs, [
+ path.join(root, "diet", ".quote-check"),
+ path.join(root, ".umtool", "quote-check", "diet"),
+ path.join(root, "cache", "umtool", "quote-check", "diet"),
+ ]);
+ const plan = await planQuoteCheck(p.dir, p.manifest, { channelsDirs: [p.channels] });
+ const outs = [];
+ const seen = async (req) => { outs.push(req.out); return fakeTranscribe(req); };
+ const first = await runQuoteCheck(p.dir, p.manifest, plan, { transcribe: seen, cuesOf: fakeCues, workDirs: dirs });
+ assert.equal(first.work, dirs[0]);
+ assert.ok(outs.length >= 2 && outs.every((o) => path.dirname(o) === dirs[0]), outs.join("\n"));
+ assert.equal(await stat(path.join(drive, "quote-check")).catch(() => null), null, "nothing under out/");
+ assert.equal(first.doc.clips.c44.status, "ok");
+
+ // The project dir itself inside a location: the editor refuses the first dir, the check moves on and still lands its rows.
+ const lines = [];
+ const refused = [];
+ const picky = async (req) => {
+ if (path.dirname(req.out) === dirs[0]) {
+ refused.push(req.out);
+ throw new Error(`the editor refused it (/api/ops/transcribe, HTTP 400): "out" ${req.out} is inside the corpus (/mnt/media) — this command never writes there; pick a path outside it`);
+ }
+ outs.push(req.out);
+ return fakeTranscribe(req);
+ };
+ outs.length = 0;
+ const second = await runQuoteCheck(p.dir, p.manifest, plan, { transcribe: picky, cuesOf: fakeCues, workDirs: dirs, log: (l) => lines.push(l) });
+ assert.equal(refused.length, 1, "asked once, not once per clip");
+ assert.equal(second.work, dirs[1]);
+ assert.ok(outs.length >= 2 && outs.every((o) => path.dirname(o) === dirs[1]));
+ assert.match(lines.join("\n"), /the editor will not write in .*\.quote-check \(inside the corpus\) -- its work files go to .*\.umtool\/quote-check\/diet/);
+ assert.equal(second.doc.clips.c43.status, "moved");
+ assert.deepEqual(await readQuoteCheck(p.dir), second.doc);
+ // Any other failure is that clip's, as before -- no hopping dirs.
+ const broken = await runQuoteCheck(p.dir, p.manifest, plan, { transcribe: async () => { throw new Error("no engine"); }, cuesOf: fakeCues, workDirs: dirs, log: (l) => lines.push(l) });
+ assert.equal(broken.work, dirs[0]);
+ assert.match(lines.join("\n"), /c43: the transcription failed: no engine/);
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+test("through the real editor client: the editor's own refusal reaches the fall-through, and the refused work dir is taken back -- no empty .quote-check left in the corpus", async () => {
+ const http = await import("node:http");
+ const { stat, readdir } = await import("node:fs/promises");
+ const { OUT_INSIDE_CORPUS, quoteCheckWorkDirs } = await import("./quoteCheck.mjs");
+ // The controller's sentence, as the editor's source has it: the words the fall-through matches are there.
+ const controller = await readFile(path.join(HERE, "..", "..", "..", "common", "controller", "transcribeFile.ts"), "utf8");
+ const sentence = /error: `("out" \$\{req\.out\} is inside the corpus \(\$\{root\}\)[^`]*)`/.exec(controller);
+ assert.ok(sentence, "transcribeFile.ts still refuses an out inside the corpus in these words");
+ const refusalFor = (out, root) => sentence[1].replace("${req.out}", out).replace("${root}", root);
+ assert.match(refusalFor("/mnt/media/x/.quote-check/c43.words.json", "/mnt/media"), OUT_INSIDE_CORPUS);
+ assert.doesNotMatch('"out": the directory /x does not exist', OUT_INSIDE_CORPUS);
+ assert.doesNotMatch("editor job abc failed — out of memory inside the corpus reader", OUT_INSIDE_CORPUS);
+
+ const p = await project();
+ const corpus = p.dir; // the project itself sits in a "location": its .quote-check is refused
+ const asked = [];
+ // The editor, stood in for over HTTP: /api/ops/transcribe answers as ops' jobResponse does (400 { ok: false, error }
+ // for a refusal, { ok: true, jobId } and the words written to `out` otherwise), /api/ops/job/<id> a finished job.
+ const server = http.createServer((req, res) => {
+ let text = "";
+ req.on("data", (d) => (text += d));
+ req.on("end", async () => {
+ const send = (status, body) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(body)); };
+ if (req.method === "POST" && req.url === "/api/ops/transcribe") {
+ const body = JSON.parse(text);
+ asked.push(body.out);
+ if (body.out.startsWith(corpus + path.sep)) return send(400, { ok: false, error: refusalFor(body.out, corpus) });
+ if (!(await stat(path.dirname(body.out)).catch(() => null))) return send(400, { ok: false, error: `"out": the directory ${path.dirname(body.out)} does not exist` });
+ const words = await fakeTranscribe(body);
+ await writeFile(body.out, JSON.stringify({ words }));
+ return send(200, { ok: true, jobId: `j${asked.length}` });
+ }
+ if (req.method === "GET" && req.url.startsWith("/api/ops/job/")) return send(200, { ok: true, job: { status: "done" }, tail: [] });
+ return send(404, { ok: false, error: "no such route" });
+ });
+ });
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
+ const env = { url: process.env.ARCHILYZER_EDITOR_URL, token: process.env.WORKER_TOKEN };
+ process.env.ARCHILYZER_EDITOR_URL = `http://127.0.0.1:${server.address().port}`;
+ process.env.WORKER_TOKEN = "test-token";
+ try {
+ const dirs = await quoteCheckWorkDirs(p.dir, { reportsRoot: p.root, env: { XDG_CACHE_HOME: path.join(p.root, "cache") } });
+ const plan = (await planQuoteCheck(p.dir, p.manifest, { channelsDirs: [p.channels] })).filter((r) => r.id !== "c43");
+ const lines = [];
+ // No `transcribe` given: runQuoteCheck's own editorWords, askEditorOp and all.
+ const r = await runQuoteCheck(p.dir, p.manifest, plan, { cuesOf: fakeCues, workDirs: dirs, log: (l) => lines.push(l) });
+ assert.equal(asked[0], path.join(dirs[0], "c44.words.json"), "the project's .quote-check is asked first");
+ assert.equal(asked[1], path.join(dirs[1], "c44.words.json"));
+ assert.equal(r.work, dirs[1]);
+ assert.equal(r.doc.clips.c44.status, "ok", lines.join("\n"));
+ assert.match(lines.join("\n"), /the editor will not write in .* \(inside the corpus\)/);
+ assert.equal(await stat(dirs[0]).catch(() => null), null, "the refused .quote-check is not left behind");
+ assert.ok((await readdir(dirs[1])).includes("c44.words.json"));
+
+ // Every dir refused: each one made is taken back, with the parents made for it; the clip's failure says why.
+ await rm(dirs[1], { recursive: true, force: true });
+ await rm(path.join(p.root, ".umtool"), { recursive: true, force: true });
+ const inCorpus = [dirs[0], path.join(p.dir, "deep", "er", "work")];
+ lines.length = 0;
+ const none = await runQuoteCheck(p.dir, p.manifest, plan, { cuesOf: fakeCues, workDirs: inCorpus, log: (l) => lines.push(l) });
+ assert.match(lines.join("\n"), /c44: the transcription failed: the editor refused it \(\/api\/ops\/transcribe, HTTP 400\): "out" .* is inside the corpus/);
+ assert.equal(await stat(dirs[0]).catch(() => null), null);
+ assert.equal(await stat(path.join(p.dir, "deep")).catch(() => null), null, "the parents made for it too");
+ assert.equal(none.results.c44, undefined);
+ // A work dir that was already there, with a file in it, is never removed.
+ await mkdir(dirs[0], { recursive: true });
+ await writeFile(path.join(dirs[0], "kept.txt"), "x");
+ await runQuoteCheck(p.dir, p.manifest, plan, { cuesOf: fakeCues, workDirs: [dirs[0]], log: () => {} });
+ assert.ok((await readdir(dirs[0])).includes("kept.txt"));
+ } finally {
+ if (env.url === undefined) delete process.env.ARCHILYZER_EDITOR_URL; else process.env.ARCHILYZER_EDITOR_URL = env.url;
+ if (env.token === undefined) delete process.env.WORKER_TOKEN; else process.env.WORKER_TOKEN = env.token;
+ await new Promise((r) => server.close(r));
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/readVoice.mjs b/umtool/lib/report/readVoice.mjs
@@ -1,22 +1,24 @@
// THE VOICE A POST ITEM's OWN READ IS SAID IN (a single post's take: `umtool posts narrate <p> <item> --take`, the
// bench's Re-take), through the SAME function a thread read asks for his piece (post-say.mjs resolvePieceVoice): the
-// read's own voice (--voice, the bench's voice field), the project's voice map, the CAST, the narrator's (the item's
-// own `narration.voice`, else the cut's). So a post read alone and the same post read with its thread agree.
+// read's own voice (--voice, the bench's voice field), the item's own character (`narration.character`), the
+// project's characters and voice map, the CAST, the narrator's (the item's own `narration.voice`, else the cut's). So
+// a post read alone and the same post read with its thread agree.
//
// Plain ESM.
import { postNarrationKnobs } from "umtool-report-to-video/post-narration";
import { resolvePieceVoice, voiceRefOf } from "umtool-report-to-video/post-say";
/**
- * `{ engine, voice, from }` for post item `e`'s own read -- `from` "override", "project", "cast", "narrator".
- * `map` and `cast` are read from the project when not given (a broken voice map reads as none here: the read is not
- * refused for it; `umtool posts voices` says what is wrong with it).
+ * `{ engine, voice, from, speed?, character? }` for post item `e`'s own read -- `from` "override", "item", "project",
+ * "cast", "narrator"; `speed` and `character` the preset's that answered (a character's `synthetic.speed`, its id).
+ * `map`, `cast` and `item` (voiceSourceOf's layers) are read from the project when not given (characterLayers.mjs; a
+ * broken voice map reads as none here: the read is not refused for it; `umtool posts voices` says what is wrong).
*
* @param {{ dir: string }} project
* @param {Record<string, any>} e
- * @param {{ render?: Record<string, any>, engine?: string | null, voice?: string | null, map?: Record<string, string>, cast?: Record<string, string> }} [o]
+ * @param {{ render?: Record<string, any>, engine?: string | null, voice?: string | null, map?: Record<string, any>, cast?: Record<string, any>, item?: any }} [o]
*/
-export async function itemReadVoice(project, e, { render = {}, engine = null, voice = null, map = undefined, cast = undefined } = {}) {
+export async function itemReadVoice(project, e, { render = {}, engine = null, voice = null, map = undefined, cast = undefined, item = undefined } = {}) {
const k = postNarrationKnobs(e, render);
const eng = engine ?? e.narration?.engine ?? k.engine;
const narrator = e.narration?.voice ?? k.voice;
@@ -24,9 +26,11 @@ export async function itemReadVoice(project, e, { render = {}, engine = null, vo
const ref = voiceRefOf(voice, eng) ?? { engine: eng, voice: String(voice) };
return { engine: engine ?? ref.engine ?? eng, voice: ref.voice, from: "override" };
}
- const m = map !== undefined ? map : await (await import("./postSay.mjs")).readVoiceMap(project.dir).catch(() => ({}));
- const c = cast !== undefined ? cast : await (await import("./postThreadRead.mjs")).projectCastMap(project.dir).catch(() => ({}));
- const r = resolvePieceVoice({ handle: e.handle ?? null, role: "post" }, { map: m, cast: c, self: e.handle ?? null, narrator, engine: eng });
+ const L = map !== undefined && cast !== undefined && item !== undefined ? null : await (await import("./characterLayers.mjs")).readLayers(project.dir).catch(() => null);
+ const m = map !== undefined ? map : L?.map ?? {};
+ const c = cast !== undefined ? cast : L?.castMap ?? {};
+ const it = item !== undefined ? item : L?.itemOf(e) ?? null;
+ const r = resolvePieceVoice({ handle: e.handle ?? null, role: "post" }, { map: m, cast: c, item: it, self: e.handle ?? null, narrator, engine: eng });
// An engine asked for outright that the resolved voice is not of: the narrator's voice in it.
if (engine && r.engine !== engine) return { engine, voice: narrator, from: "narrator" };
return r;
diff --git a/umtool/lib/report/recordPreview.mjs b/umtool/lib/report/recordPreview.mjs
@@ -0,0 +1,445 @@
+// RECORD -> FILTER -> PREVIEW (operator, 11 Nov: "run the filter and preview it seamlessly in the record UI"): a
+// recording of a post item run through its character's RECORDED PRESET -- cleaned (the editor's voice-enhance), its
+// edges trimmed to speech (or cut at the marks a person set), converted to the character's STOCK voice (the editor's
+// voice-convert) -- WITHOUT making a take, so it can be listened to beside the raw read first. The record page's
+// Filter and `umtool posts narrate <p> <item> --recording <file> --preview` are this one chain.
+//
+// <project>/narration/.record-preview/<postId>.<label>/ the SCRATCH DIR: one per post item and voice label,
+// preview.json what is in it, and what each file was made from removed on Keep, on Again, when the
+// pNN.raw.wav each part as recorded, 48 kHz mono, UNTRIMMED page is left, and when the recording
+// pNN.clean.wav each part cleaned, untrimmed it was made from changes; one a
+// raw.wav, raw.parts/ the parts cut to their spans, joined, levelled crash left behind is removed the next
+// clean.wav, clean.parts/ the same from the cleaned parts time a preview is prepared (a day old)
+// filtered.wav[, filtered.parts/] clean.wav (else raw.wav) converted
+//
+// THE ORDER is clean -> trim -> convert: the parts are cleaned WHOLE, so moving a cut mark re-cuts the cleaned sound
+// and asks the editor for the convert alone; changing the pitch asks for the convert alone too. Each step is kept
+// with a key of what it was made from (`source`: the recording's files; `built`: + the spans; `convert`: + the
+// engine, voice, pitch and semitones) and a step whose key still answers is not run again.
+//
+// KEEP (keepPreview) makes the takes `posts narrate --recording` would -- the recorded one (the original, trimmed,
+// levelled), the cleaned one, the converted one, each a new take, the last picked -- FROM THE PREVIEW's FILES: nothing
+// is converted again. Plain ESM; the editor is asked through narrate-via-editor.mjs askEditorOp (`ask` in a test).
+import { createHash } from "node:crypto";
+import { execFile } from "node:child_process";
+import { copyFile, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { promisify } from "node:util";
+import { POST_DERIVE_ROUTES, derivedFileOf, nextTakeNumber, postIdOf, postNarrationDisclosure, takeIdOf, takesDirOf } from "umtool-report-to-video/post-narration";
+import { convertPitchLabel, recordedPresetOf, shownNameOf } from "umtool-report-to-video/cast";
+import { readManifest } from "../projects/report.mjs";
+import { readLayers } from "./characterLayers.mjs";
+import { convertAskOf, stepPitchOf } from "./derivePitch.mjs";
+import { withEditNotes } from "./edit-guard.mjs";
+import { manifestToken, updatePostNarration } from "./manifest.mjs";
+import { NarrateError, findPostItem, measureTake } from "./postNarrationCli.mjs";
+import { RECORD_LABEL_RE, decodePart, explicitSpan, joinRecording, partsIn, roomOf, targetLufsOf, trimSpan } from "./postRecord.mjs";
+
+const execFileP = promisify(execFile);
+const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg";
+
+/** The scratch dirs' parent, project-relative. */
+export const PREVIEW_DIR = "narration/.record-preview";
+/** How many levels a part's waveform is drawn from. */
+export const PREVIEW_PEAKS = 240;
+/** A scratch dir nobody removed (a crash, a closed laptop) is removed after this long. */
+export const PREVIEW_STALE_MS = 24 * 60 * 60 * 1000;
+
+const sha = (v) => createHash("sha1").update(typeof v === "string" ? v : JSON.stringify(v)).digest("hex");
+const pad2 = (n) => String(n).padStart(2, "0");
+const checkLabel = (label) => {
+ if (!RECORD_LABEL_RE.test(String(label))) throw Object.assign(new NarrateError(`"${label}" is not a voice label (a-z, 0-9, - and _)`), { status: 400 });
+};
+
+/** The scratch dir of post item `entry`'s preview for voice `label` (absolute). */
+export const previewDirOf = (projectDir, entry, label = "operator") => path.join(projectDir, ...PREVIEW_DIR.split("/"), `${postIdOf(entry)}.${label}`);
+
+/** The preview's record (`preview.json`), or null: none, or unreadable. */
+export async function readPreview(projectDir, entry, label = "operator") {
+ checkLabel(label);
+ try {
+ const doc = JSON.parse(await readFile(path.join(previewDirOf(projectDir, entry, label), "preview.json"), "utf8"));
+ return doc && doc.version === 1 && Array.isArray(doc.parts) ? doc : null;
+ } catch {
+ return null;
+ }
+}
+
+async function writePreview(dir, doc) {
+ const tmp = path.join(dir, `.preview.${process.pid}.${Date.now()}.json`);
+ await writeFile(tmp, `${JSON.stringify(doc, null, 1)}\n`, "utf8");
+ await rename(tmp, path.join(dir, "preview.json"));
+}
+
+/** Remove the preview of `entry` (Again, leaving the page, Keep). */
+export async function discardPreview(projectDir, entry, label = "operator") {
+ checkLabel(label);
+ await rm(previewDirOf(projectDir, entry, label), { recursive: true, force: true });
+}
+
+/** Scratch dirs of this project nobody removed in PREVIEW_STALE_MS (not `keep`): gone. */
+async function pruneStale(projectDir, keep, now = Date.now()) {
+ const root = path.join(projectDir, ...PREVIEW_DIR.split("/"));
+ for (const name of await readdir(root).catch(() => [])) {
+ const dir = path.join(root, name);
+ if (dir === keep) continue;
+ const st = await stat(path.join(dir, "preview.json")).catch(() => null) ?? (await stat(dir).catch(() => null));
+ if (st && now - st.mtimeMs > PREVIEW_STALE_MS) await rm(dir, { recursive: true, force: true });
+ }
+}
+
+/** What a recording is, for the cache: its files, their sizes and times. */
+export async function sourceKeyOf(parts) {
+ const rows = [];
+ for (const p of parts) {
+ const st = await stat(p.file).catch(() => null);
+ if (!st?.isFile()) throw new NarrateError(`no recording at ${p.file}`);
+ rows.push([p.file, st.size, Math.round(st.mtimeMs)]);
+ }
+ return sha(rows);
+}
+
+/** A wav's levels for a waveform: PREVIEW_PEAKS values 0-1, the loudest sample of each slice. */
+export async function peaksOf(wav, count = PREVIEW_PEAKS) {
+ const { stdout } = await execFileP(FFMPEG(), ["-nostdin", "-v", "error", "-i", wav, "-ac", "1", "-ar", "8000", "-f", "s16le", "-"], { encoding: "buffer", maxBuffer: 512 * 1024 * 1024 });
+ const samples = Math.floor(stdout.length / 2);
+ const out = new Array(count).fill(0);
+ if (!samples) return out;
+ for (let i = 0; i < samples; i += 1) {
+ const k = Math.min(count - 1, Math.floor((i * count) / samples));
+ const v = Math.abs(stdout.readInt16LE(i * 2)) / 32768;
+ if (v > out[k]) out[k] = v;
+ }
+ return out.map((v) => Math.round(v * 1000) / 1000);
+}
+
+/**
+ * PREPARE: the recording's parts decoded into the scratch dir (once: a recording that has not changed is not decoded
+ * again), each with its length, its waveform and the AUTO TRIM's answer -- `auto: { from, to }`, the span of its
+ * speech with the room kept (`trim.padMs`, else the recorder's own), or the whole part when `trim.on` is false. No
+ * editor, no take. Returns the preview's record.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {Record<string, any>} entry
+ * @param {Array<{ file: string, text?: string, para?: number }>} parts
+ * @param {{ label?: string, trim?: { on?: boolean, padMs?: number | null } | null }} [o]
+ */
+export async function preparePreview(project, entry, parts, { label = "operator", trim = null } = {}) {
+ checkLabel(label);
+ if (!parts.length) throw new NarrateError("nothing was recorded");
+ const dir = previewDirOf(project.dir, entry, label);
+ const source = await sourceKeyOf(parts);
+ let doc = await readPreview(project.dir, entry, label);
+ if (!doc || doc.source !== source) {
+ // Another recording than the one in the scratch dir (a part re-recorded, another file): everything from it goes.
+ await rm(dir, { recursive: true, force: true });
+ await mkdir(dir, { recursive: true });
+ await pruneStale(project.dir, dir);
+ doc = { version: 1, id: entry.id, label, source, at: new Date().toISOString(), parts: [], clean: null, cleaned: null, built: null, convert: null, notes: [] };
+ for (const [k, p] of parts.entries()) {
+ const raw = `p${pad2(k + 1)}.raw.wav`;
+ const { seconds, silences } = await decodePart(p.file, path.join(dir, raw));
+ doc.parts.push({ n: k + 1, para: Number.isInteger(p.para) ? p.para : k, text: String(p.text ?? ""), raw, seconds, silences, peaks: await peaksOf(path.join(dir, raw)) });
+ }
+ }
+ const on = trim?.on !== false;
+ const room = roomOf(trim);
+ doc.trim = { on, padMs: Number.isFinite(trim?.padMs) ? trim.padMs : null };
+ for (const p of doc.parts) p.auto = on ? trimSpan(p.silences, p.seconds, room) : { from: 0, to: p.seconds };
+ await writePreview(dir, doc);
+ return doc;
+}
+
+const notInstalled = (err) => err?.name === "OpNotInstalled" || /not installed/i.test(String(err?.message));
+
+/**
+ * THE CHAIN, no take made: `parts` (`[{ file, text?, para? }]`, a recording in reading order) prepared, CLEANED
+ * (unless the character's preset or `clean` says not to; an editor with no enhance engine: said, and gone without),
+ * cut to `spans` (per part, `{ from, to }` in its own seconds; a part without one: the auto trim's) and joined,
+ * CONVERTED to the character's stock voice at `pitch` / `semitones` (each unless given: the preset's;
+ * derivePitch.mjs convertAskOf). The character is `as`, else the chain's (cast.mjs characterForRead). What the
+ * command says wins over the preset: `clean`, `trim`, `pitch`, `semitones`, `engine`, `voice`; `convert: false` stops
+ * after the clean.
+ *
+ * `emit("stage", { stage: "decode" | "clean" | "trim" | "convert" | "done", state, message })` says where it is --
+ * `state`: `running`, `cached`, `skipped`, `done`, and while the editor's job waits `queued` (behind other jobs),
+ * `memory` or `slot` (at the heavy slot: the gate working, not an error).
+ *
+ * Returns `{ dir, raw, clean, filtered, listen, notes, character, direction, convert, spans, lufs, cached }` -- the
+ * files absolute; `listen` is what to compare with `raw` (the converted read, else the cleaned one, else null).
+ * `out`: `listen` (else `raw`) copied there. `session: true`: the parts are the record page's session of the item
+ * (keepPreview says so, and its caller clears the session).
+ */
+export async function runPreview(project, entry, parts, {
+ label = "operator", as = null, clean = undefined, trim = undefined, spans = null, convert = true, pitch = undefined, semitones = undefined, engine = null, voice = null,
+ out = null, emit = () => {}, editor = null, ask = null, session = false,
+} = {}) {
+ const layers = await readLayers(project.dir);
+ const who = layers.characterForRead(entry, as);
+ const character = who?.character ?? null;
+ if (as && !character) throw new NarrateError(`--as ${as}: no such character in this video's characters or the cast (umtool cast project ${project.id}, umtool cast ls)`);
+ const preset = character ? recordedPresetOf(character) : null;
+ const doClean = clean ?? preset?.enhance ?? true;
+ const doTrim = trim ?? preset?.trim ?? null;
+ const stage = (name, state, message, more = {}) => emit("stage", { stage: name, state, message, ...more });
+ const askOp = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorOp;
+ const { opWaitOf } = await import("umtool-report-to-video/narrate-via-editor");
+ const waiting = (name, what) => {
+ let last = "";
+ return (st) => {
+ const w = opWaitOf(st);
+ const key = `${w.state}|${w.position ?? ""}`;
+ if (key === last) return;
+ last = key;
+ const say = w.state === "queued" ? `${what}: queued at the editor${w.position ? ` (position ${w.position})` : ""}`
+ : w.state === "memory" ? `${what}: waiting for memory (the heavy slot admits it when there is room -- not an error)`
+ : w.state === "slot" ? `${what}: waiting for the heavy slot (another heavy job holds it -- not an error)`
+ : `${what}: running`;
+ stage(name, w.state, say, { job: st.jobId, ...(w.line ? { line: w.line } : {}) });
+ };
+ };
+ const note = (_ev, f) => f?.message && emit("note", { message: f.message });
+
+ stage("decode", "running", "reading the recording");
+ let doc = await preparePreview(project, entry, parts, { label, trim: doTrim });
+ const dir = previewDirOf(project.dir, entry, label);
+ const abs = (name) => path.join(dir, ...String(name).split("/"));
+ const has = async (name) => !!(await stat(abs(name)).catch(() => null))?.isFile();
+ const notes = [];
+ const cached = { clean: false, convert: false };
+
+ // CLEAN: the parts whole, as recorded (one job of the editor's: one admission to the heavy slot).
+ if (!doClean) {
+ doc.cleaned = { state: "off" };
+ notes.push(clean === undefined && character ? `not cleaned: ${character.id}'s recorded preset says so (enhance off)` : "not cleaned: asked not to (--no-clean)");
+ stage("clean", "skipped", notes.at(-1));
+ } else if (doc.clean?.key === doc.source && (await Promise.all(doc.clean.files.map(has))).every(Boolean)) {
+ doc.cleaned = { state: "done" };
+ cached.clean = true;
+ stage("clean", "cached", "cleaned already (this recording, unchanged)");
+ } else {
+ stage("clean", "running", "cleaning: asking the editor (voice-enhance)");
+ const files = doc.parts.map((p) => p.raw.replace(/\.raw\.wav$/, ".clean.wav"));
+ try {
+ const { jobId, result } = await askOp(POST_DERIVE_ROUTES.enhance, {
+ file: abs(doc.parts[0].raw), out: abs(files[0]),
+ ...(doc.parts.length > 1 ? { parts: doc.parts.slice(1).map((p, k) => ({ file: abs(p.raw), out: abs(files[k + 1]) })) } : {}),
+ }, { ...(editor ? { editor } : {}), emit: note, onState: waiting("clean", "cleaning") });
+ for (const f of files) if (!(await has(f))) throw new NarrateError(`the editor's job ${jobId} finished but ${f} is not there`);
+ doc.clean = { key: doc.source, files, engine: typeof result?.engine === "string" ? result.engine : null, job: jobId, ranAt: new Date().toISOString() };
+ doc.cleaned = { state: "done" };
+ stage("clean", "done", "cleaned");
+ } catch (err) {
+ if (!notInstalled(err)) throw err;
+ doc.cleaned = { state: "skipped" };
+ notes.push(`not cleaned: ${err.message} (archilyzer voice setup --engine deepfilternet)`);
+ stage("clean", "skipped", notes.at(-1));
+ }
+ await writePreview(dir, doc);
+ }
+ const cleaned = doc.cleaned.state === "done";
+
+ // TRIM: each part cut to its span -- the marks given, else the auto trim's -- the raw read and the cleaned one alike.
+ const cut = doc.parts.map((p, k) => explicitSpan(spans?.[k], p.seconds) ?? p.auto);
+ const target = targetLufsOf((await readManifest(project.dir)) ?? {});
+ const builtKey = sha([doc.source, cut, cleaned, target]);
+ if (doc.built?.key === builtKey && (await has("raw.wav")) && (!cleaned || (await has("clean.wav")))) {
+ stage("trim", "cached", "cut and joined already (these marks)");
+ } else {
+ stage("trim", "running", `cutting ${doc.parts.length === 1 ? "it" : `its ${doc.parts.length} parts`} to ${doc.parts.length === 1 ? "its marks" : "their marks"}`);
+ const sources = (file) => doc.parts.map((p, k) => ({ wav: abs(file(p, k)), ...cut[k], text: p.text, para: p.para }));
+ for (const f of ["raw.parts", "clean.parts", "filtered.parts"]) await rm(abs(f), { recursive: true, force: true });
+ for (const f of ["clean.wav", "filtered.wav"]) await rm(abs(f), { force: true });
+ const raw = await joinRecording(sources((p) => p.raw), { out: abs("raw.wav"), partsDir: abs("raw.parts"), target });
+ const cl = cleaned ? await joinRecording(sources((_p, k) => doc.clean.files[k]), { out: abs("clean.wav"), partsDir: abs("clean.parts"), target }) : null;
+ doc.built = { key: builtKey, spans: cut, target, raw: { file: "raw.wav", ...raw }, clean: cl ? { file: "clean.wav", ...cl } : null };
+ doc.convert = null;
+ await writePreview(dir, doc);
+ stage("trim", "done", `cut: ${raw.seconds} s`);
+ }
+
+ // CONVERT: the cleaned read (else the raw one) to the character's stock voice, at the pitch asked or the preset's.
+ if (!convert) {
+ notes.push("not converted: asked not to (--no-convert)");
+ stage("convert", "skipped", notes.at(-1));
+ } else {
+ const d = convertAskOf({ engine, voice, pitch, semitones }, character ? preset.convert : null, character?.id ?? null);
+ if (!d.ok) {
+ notes.push(`not converted: ${d.error} (${d.fix})`);
+ stage("convert", "skipped", notes.at(-1));
+ } else {
+ const a = d.value;
+ const key = sha([builtKey, a.engine, a.voice, a.pitch ?? null, a.semitones ?? null]);
+ if (doc.convert?.key === key && (await has("filtered.wav"))) {
+ cached.convert = true;
+ stage("convert", "cached", `converted already (${a.voice}${convertPitchLabel(doc.convert) ? `, pitch: ${convertPitchLabel(doc.convert)}` : ""})`);
+ } else {
+ stage("convert", "running", `converting to ${a.voice}: asking the editor (voice-convert)`);
+ const src = doc.built.clean ?? doc.built.raw;
+ const srcParts = src.file.replace(/\.wav$/, ".parts");
+ await rm(abs("filtered.parts"), { recursive: true, force: true });
+ try {
+ const { jobId, result } = await askOp(POST_DERIVE_ROUTES.convert, {
+ file: abs(src.file), out: abs("filtered.wav"), ...(a.engine ? { engine: a.engine } : {}), voice: a.voice,
+ ...(a.pitch ? { pitch: a.pitch } : {}), ...(typeof a.semitones === "number" ? { semitones: a.semitones } : {}),
+ ...(src.parts.length > 1 ? { parts: src.parts.map((p) => ({ file: abs(`${srcParts}/${p.name}`), out: abs(`filtered.parts/${p.name}`) })) } : {}),
+ }, { ...(editor ? { editor } : {}), emit: note, onState: waiting("convert", "converting") });
+ if (!(await has("filtered.wav"))) throw new NarrateError(`the editor's job ${jobId} finished but filtered.wav is not there`);
+ const m = await measureTake(abs("filtered.wav"));
+ doc.convert = {
+ key, built: builtKey, file: "filtered.wav", asked: a,
+ engine: a.engine ?? (typeof result?.engine === "string" ? result.engine : null), voice: a.voice, ...stepPitchOf(a, result ?? {}),
+ job: jobId, ranAt: new Date().toISOString(), seconds: m.seconds, ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}),
+ };
+ stage("convert", "done", `converted to ${a.voice}${convertPitchLabel(doc.convert) ? ` (pitch: ${convertPitchLabel(doc.convert)})` : ""}`);
+ } catch (err) {
+ if (!notInstalled(err)) throw err;
+ doc.convert = null;
+ notes.push(`not converted: ${err.message} (archilyzer voice setup --engine ${a.engine ?? "openvoice"})`);
+ stage("convert", "skipped", notes.at(-1));
+ }
+ }
+ }
+ }
+ doc.notes = notes;
+ // Made from the record page's session (not a file): keeping it is the end of that session.
+ doc.session = session === true;
+ doc.character = character ? { id: character.id, name: shownNameOf(character), layer: who.layer } : null;
+ await writePreview(dir, doc);
+ const listen = doc.convert ? abs(doc.convert.file) : doc.built.clean ? abs(doc.built.clean.file) : null;
+ let copied = null;
+ if (out) {
+ copied = path.resolve(String(out));
+ await mkdir(path.dirname(copied), { recursive: true });
+ await copyFile(listen ?? abs("raw.wav"), copied);
+ }
+ stage("done", "done", listen ? "the preview is ready: nothing was kept" : "nothing to filter it with: the raw read alone");
+ return {
+ dir, raw: abs("raw.wav"), clean: doc.built.clean ? abs("clean.wav") : null, filtered: doc.convert ? abs(doc.convert.file) : null, listen, ...(copied ? { out: copied } : {}),
+ notes, character: doc.character, ...(preset?.direction ? { direction: preset.direction } : {}),
+ convert: doc.convert ? { engine: doc.convert.engine, voice: doc.convert.voice, ...(doc.convert.pitch ? { pitch: doc.convert.pitch } : {}), ...(typeof doc.convert.semitones === "number" ? { semitones: doc.convert.semitones } : {}) } : null,
+ spans: cut, lufs: { raw: doc.built.raw.lufs ?? null, filtered: doc.convert?.lufs ?? doc.built.clean?.lufs ?? null }, cached,
+ };
+}
+
+/**
+ * What the record page is told of a preview (`preview.json` without the silences): each part's length, waveform, auto
+ * span and the span it was cut at; what was made (`raw`, `clean`, `filtered`: seconds and loudness, so both play at one
+ * level); the convert as it ran; the notes. `null`: none.
+ */
+export function previewView(doc) {
+ if (!doc) return null;
+ const made = (x) => (x ? { seconds: x.seconds ?? null, lufs: Number.isFinite(x.lufs) ? x.lufs : null } : null);
+ return {
+ id: doc.id, label: doc.label, source: doc.source, trim: doc.trim ?? { on: true, padMs: null },
+ parts: doc.parts.map((p, k) => ({ n: p.n, text: p.text, seconds: p.seconds, auto: p.auto, peaks: p.peaks, span: doc.built?.spans?.[k] ?? null })),
+ cleaned: doc.cleaned?.state ?? null,
+ raw: made(doc.built?.raw), clean: made(doc.built?.clean),
+ filtered: doc.convert && doc.convert.built === doc.built?.key ? { ...made(doc.convert), engine: doc.convert.engine, voice: doc.convert.voice, pitch: doc.convert.pitch ?? "target", semitones: doc.convert.semitones ?? 0, asked: doc.convert.asked ?? null } : null,
+ notes: doc.notes ?? [], character: doc.character ?? null,
+ };
+}
+
+/**
+ * The absolute file of one of a preview's sounds (`raw`, `clean`, `filtered`, or `part` + n: that part as recorded), or null.
+ *
+ * @param {string} projectDir
+ * @param {Record<string, any>} entry
+ * @param {string} which
+ * @param {{ label?: string, n?: number | null }} [o]
+ */
+export async function previewFile(projectDir, entry, which, { label = "operator", n = null } = {}) {
+ const doc = await readPreview(projectDir, entry, label);
+ if (!doc) return null;
+ const dir = previewDirOf(projectDir, entry, label);
+ const name = which === "raw" ? doc.built?.raw?.file : which === "clean" ? doc.built?.clean?.file : which === "filtered" ? (doc.convert?.built === doc.built?.key ? doc.convert?.file : null)
+ : which === "part" ? doc.parts.find((p) => p.n === Number(n))?.raw : null;
+ if (!name) return null;
+ const f = path.join(dir, name);
+ return (await stat(f).catch(() => null))?.isFile() ? f : null;
+}
+
+/**
+ * KEEP THE PREVIEW: its files made the takes a recording made a read would be -- take-<n>.recorded-<label>.wav (the
+ * original: trimmed, joined, levelled), the cleaned one (`steps: [{op: "enhance"}]`), the converted one (`steps: [{op:
+ * "convert", engine, voice, pitch?, semitones?}]`) -- each a new take through the writer (an undo point each), the
+ * last one PICKED (a pick takes the approval away: it awaits approval). Nothing is asked of the editor. The scratch dir
+ * is removed. `parts`: the recording meant (the session's parts now) -- a preview of another is refused (409). Returns `{ takes: [{ step, file }], picked, notes, disclosure, character, session, entry, token }`.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {Record<string, any>} entry
+ * @param {{ label?: string, script?: string | null, note?: string | null, parts?: Array<{ file: string }> | null }} [o]
+ */
+export async function keepPreview(project, entry, { label = "operator", script = null, note = null, parts: meant = null } = {}) {
+ const doc = await readPreview(project.dir, entry, label);
+ if (!doc?.built) throw Object.assign(new NarrateError(`${entry.id} has no preview to keep (Filter it first: umtool posts narrate ${project.id} ${entry.id} --recording <file> --preview)`), { status: 409 });
+ // The recording the caller means to keep (the record page's session, as it is NOW): a preview made from another
+ // one -- a part recorded again since the Filter -- is refused; its sound is not what was read last.
+ if (meant && (await sourceKeyOf(meant)) !== doc.source) throw Object.assign(new NarrateError(`${entry.id}'s preview is of an earlier recording (a part was recorded again since the Filter): Filter again, or keep the recording alone`), { status: 409 });
+ const dir = previewDirOf(project.dir, entry, label);
+ const pid = postIdOf(entry);
+ const takesDir = path.join(project.dir, ...takesDirOf(pid).split("/"));
+ await mkdir(takesDir, { recursive: true });
+ let n = nextTakeNumber(entry, await readdir(takesDir).catch(() => []));
+ const abs = (rel) => path.join(project.dir, ...rel.split("/"));
+ const multi = doc.parts.length > 1;
+ // One of the preview's sounds (and its parts) moved to a take's name.
+ const move = async (made, rel) => {
+ await rename(path.join(dir, made.file), abs(rel));
+ const partsRel = rel.replace(/\.wav$/, ".parts");
+ const from = path.join(dir, made.file.replace(/\.wav$/, ".parts"));
+ if (await stat(from).catch(() => null)) {
+ await rm(abs(partsRel), { recursive: true, force: true });
+ await rename(from, abs(partsRel));
+ }
+ return partsRel;
+ };
+ const write = async (patch) => (await withEditNotes(project, async () => updatePostNarration(project.dir, entry.id, patch, { token: await manifestToken(project.dir) }))).result;
+ const takes = [];
+ const at = () => new Date().toISOString();
+ const lufs = (x) => (Number.isFinite(x?.lufs) ? { lufs: x.lufs } : {});
+ const text = String(script ?? entry.narration?.script ?? "");
+ const who = doc.character;
+
+ // The original.
+ const rel = `${takesDirOf(pid)}/take-${n}.recorded-${label}.wav`;
+ const partsRel = await move(doc.built.raw, rel);
+ const parts = multi ? partsIn(doc.built.raw.parts, partsRel) : null;
+ const recorded = {
+ file: rel, engine: "recorded", voice: label, label, seconds: doc.built.raw.seconds, source: { kind: "recorded", voice: label }, script: text,
+ at: at(), ...lufs(doc.built.raw), note: note ?? `recorded${who ? ` for ${who.name}` : ""}`, ...(parts ? { parts } : {}),
+ };
+ let result = await write({ addTake: recorded, ...(script !== null && script !== entry.narration?.script ? { script } : {}) });
+ takes.push({ step: "recorded", file: rel });
+ let from = recorded;
+ const derived = (file, made, step, voiceOf, partsDir, job) => ({
+ file, engine: "derived", voice: voiceOf, seconds: made.seconds, source: { kind: "take", from: takeIdOf(from) }, steps: [step], script: text, at: at(), ...(job ? { jobId: job } : {}), ...lufs(made),
+ ...(parts ? { parts: parts.map((p) => ({ ...p, file: `${partsDir}/p${pad2(p.n)}.wav` })) } : {}),
+ });
+
+ // The cleaned one.
+ if (doc.built.clean) {
+ n += 1;
+ const r2 = derivedFileOf(pid, n, "enhance", "default");
+ const p2 = await move(doc.built.clean, r2);
+ const take = derived(r2, doc.built.clean, { op: "enhance", ...(doc.clean?.engine ? { engine: doc.clean.engine } : {}), ranAt: doc.clean?.ranAt ?? at(), ...(doc.clean?.job ? { job: doc.clean.job } : {}) }, label, p2, doc.clean?.job);
+ result = await write({ addTake: take });
+ takes.push({ step: "cleaned", file: r2 });
+ from = take;
+ }
+ // The converted one -- when it is of these marks (a mark moved after the Filter leaves it behind).
+ if (doc.convert && doc.convert.built === doc.built.key && (await stat(path.join(dir, doc.convert.file)).catch(() => null))?.isFile()) {
+ n += 1;
+ const c = doc.convert;
+ const r3 = derivedFileOf(pid, n, "convert", c.asked?.engine ?? c.asked?.voice ?? "default");
+ const p3 = await move(c, r3);
+ const pitched = c.pitch ? { pitch: c.pitch, ...(typeof c.semitones === "number" ? { semitones: c.semitones } : {}) } : {};
+ const take = derived(r3, c, { op: "convert", ...(c.engine ? { engine: c.engine } : {}), voice: c.voice, ...pitched, ranAt: c.ranAt ?? at(), ...(c.job ? { job: c.job } : {}) }, String(c.voice).split(":").pop(), p3, c.job);
+ result = await write({ addTake: take });
+ const how = convertPitchLabel(c);
+ takes.push({ step: `converted to ${c.voice}${how ? ` (pitch: ${how})` : ""}`, file: r3 });
+ }
+ await rm(dir, { recursive: true, force: true });
+ const now = findPostItem(await readManifest(project.dir), entry.id);
+ return { takes, picked: takes.at(-1).file, notes: doc.notes ?? [], disclosure: now ? postNarrationDisclosure(now) : null, character: who ?? null, session: doc.session === true, entry: result.entry, token: result.token };
+}
diff --git a/umtool/lib/report/recordPreview.test.mjs b/umtool/lib/report/recordPreview.test.mjs
@@ -0,0 +1,382 @@
+// RECORD -> FILTER -> PREVIEW (recordPreview.mjs; postRecord.mjs keepRecording's spans; narrate-via-editor.mjs
+// opWaitOf): the chain into a scratch dir with no take made, each step kept and not run again while what it was made
+// from stands (another pitch asks for the convert alone; a mark moved re-cuts and converts, never cleans again), the
+// heavy slot's wait read as a state, Keep making the takes from the preview's files, and the CLI twin
+// (`posts narrate --recording <file> --preview`, `--keep-preview`, `--discard-preview`). No editor: the voice ops are
+// stubs; every project is a temp dir.
+// Run: node --test umtool/lib/report/recordPreview.test.mjs
+import assert from "node:assert/strict";
+import { existsSync } from "node:fs";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+import { encodeWav16 } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs";
+import { VOICE_A, VOICE_B, syntheticVoice, withSilence } from "yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs";
+import { opWaitOf } from "umtool-report-to-video/narrate-via-editor";
+import { validatePostNarration } from "umtool-report-to-video/post-narration";
+import { castCommand } from "./castCli.mjs";
+import { measureTake, trimSpans } from "./postNarrationCli.mjs";
+import { postsCommand } from "./postsCli.mjs";
+import { decodePart, explicitSpan, keepRecording, looksLikeText } from "./postRecord.mjs";
+import { PREVIEW_PEAKS, discardPreview, keepPreview, preparePreview, previewDirOf, previewFile, previewView, readPreview, runPreview } from "./recordPreview.mjs";
+import { finishSession, savePart } from "./recordSession.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-record-preview-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+const wavOf = async (file, voice, seconds = 1.5, silence = 0.3) => {
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, encodeWav16(withSilence(syntheticVoice({ ...voice, seconds }), { before: silence, after: silence })));
+};
+const run = (command, key) => async (args, extra = {}) => {
+ const lines = [];
+ const code = await command(args, { [key]: ROOT, log: (s) => lines.push(s), out: (s) => lines.push(s), err: (s) => lines.push(s), ...extra });
+ return { code, lines, text: () => lines.join("\n"), json: () => JSON.parse(lines.join("\n")) };
+};
+const cast = run(castCommand, "reportsRoot");
+const posts = run(postsCommand, "root");
+
+const DIR = path.join(ROOT, "rec");
+{
+ const post = (id, handle, author, o = {}) => ({ type: "post", id: `p-${id}`, post: `hostx/${id}`, platform: "x", author, handle, date: `2026-10-30T1${id}:00:00.000Z`, text: `words of ${id} from ${handle}.`, ...o });
+ await mkdir(DIR, { recursive: true });
+ await writeFile(path.join(DIR, "video.manifest.json"), JSON.stringify({
+ schemaVersion: 1, slug: "rec", title: "Record", provenance: { channelsDir: "../channels", channelSlug: "chan" },
+ render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" }, postNarration: { engine: "kokoro", voice: "af_heart" } },
+ timeline: [
+ post("1", "savvy", "Madam Savvy", { narration: { script: "Savvy's line, read aloud." } }),
+ post("2", "savvy", "Madam Savvy", { narration: { script: "A first paragraph.\n\nA second one." } }),
+ post("3", "nobody", "No Body", { narration: { script: "Nobody's line." } }),
+ ],
+ }, null, 2));
+}
+const project = { id: "rec", dir: DIR };
+const manifest = async () => JSON.parse(await readFile(path.join(DIR, "video.manifest.json"), "utf8"));
+const item = async (id) => (await manifest()).timeline.find((e) => e.id === id);
+// The editor's two voice ops: each writes a voice to `out` (and to each part's), and says what it ran.
+const editor = () => {
+ const ops = [];
+ const ask = async (route, body, o = {}) => {
+ const op = route.split("/").at(-1);
+ ops.push({ op, ...body });
+ // The heavy slot's gate, then the engine: what the editor's job says while it runs.
+ o.onState?.({ jobId: `op-${ops.length}`, status: "queued", queue: { position: 2 }, tail: [] });
+ const gate = ["heavy: waiting for memory — 4100 MB available, the floor is 6000 MB", " (HEAVY_MIN_FREE_MB=<MB> to change it; 0, or HEAVY=0, to skip it)"];
+ o.onState?.({ jobId: `op-${ops.length}`, status: "running", tail: gate });
+ o.onState?.({ jobId: `op-${ops.length}`, status: "running", tail: [...gate, "heavy: 6900 MB available after 40s — admitted"] });
+ const { seconds } = await measureTake(body.file);
+ await wavOf(body.out, op === "voice-convert" ? VOICE_A : VOICE_B, seconds, 0);
+ for (const p of body.parts ?? []) await wavOf(p.out, op === "voice-convert" ? VOICE_A : VOICE_B, (await measureTake(p.file)).seconds, 0);
+ return { jobId: `op-${ops.length}`, result: { engine: body.engine ?? (op === "voice-enhance" ? "deepfilternet" : "openvoice"), voice: body.voice, ...(body.pitch ? { pitch: body.pitch, semitones: body.semitones ?? 0 } : {}) } };
+ };
+ return { ops, ask, names: () => ops.map((o) => o.op) };
+};
+
+test("the heavy slot's wait is a state, not an error: queued, waiting for memory, the slot held, admitted", () => {
+ assert.deepEqual(opWaitOf({ status: "queued", queue: { position: 3 } }), { state: "queued", position: 3, line: null });
+ assert.equal(opWaitOf({ status: "queued" }).position, null);
+ // The gate's own lines (scripts/queue-lock.mjs), as the editor's job log carries them.
+ const first = [
+ "Running Seed-VC (v1, 22 kHz speech) behind the heavy slot (estimate 6500 MB)…",
+ "heavy: waiting for memory — 6706 MB available, 8000 MB promised to 2 running jobs, the floor is 6000 MB",
+ " running: lane-remote-archive (lane/remote-archive, pid 917913, 1500 MB) for 34m41s: playwright test",
+ " (HEAVY_MIN_FREE_MB=<MB> to change it; 0, or HEAVY=0, to skip it)",
+ ];
+ const mem = opWaitOf({ status: "running", tail: first });
+ assert.deepEqual([mem.state, /6706 MB available/.test(mem.line)], ["memory", true], "the continuation lines after it are still the wait");
+ assert.equal(opWaitOf({ status: "running", tail: [...first, "heavy: still waiting (memory, 30s; 6372 MB available)"] }).state, "memory");
+ assert.equal(opWaitOf({ status: "running", tail: ["heavy: still waiting for memory (4200 MB available, 1m 10s)"] }).state, "memory");
+ assert.equal(opWaitOf({ status: "running", tail: ["heavy: this machine has 3900 MB in all, under the 6000 MB floor — one heavy job at a time; waiting for: x"] }).state, "memory");
+ assert.equal(opWaitOf({ status: "running", tail: ["heavy: still waiting (build, 1m00s; 9000 MB available)"] }).state, "slot");
+ assert.equal(opWaitOf({ status: "running", tail: ["heavy: waiting for a job that runs alone: a render"] }).state, "slot");
+ assert.equal(opWaitOf({ status: "running", tail: ["queue-lock: held for a render (umtool take p --id a, since 13:31) — waiting", " (render mode: `umtool render-mode off` ends it; RENDER_PRIORITY=0 to run anyway)"] }).state, "slot");
+ assert.equal(opWaitOf({ status: "running", tail: ["queue-lock: still waiting for the render (2m; umtool take p --id a)"] }).state, "slot");
+ // Admitted: the gate says so, or the engine has spoken since.
+ assert.equal(opWaitOf({ status: "running", tail: [...first, "heavy: 7100 MB available after 1m10s — admitted"] }).state, "running");
+ assert.equal(opWaitOf({ status: "running", tail: [...first, "heavy: admitted beside 1 running job (1500 MB promised)"] }).state, "running");
+ assert.equal(opWaitOf({ status: "running", tail: [...first, "heavy: capped at 8192 MB (swap 2048 MB) in a scope of its own"] }).state, "running");
+ assert.equal(opWaitOf({ status: "running", tail: ["queue-lock: the render let go after 3m — going on"] }).state, "running");
+ assert.equal(opWaitOf({ status: "running", tail: [...first, "loading the model"] }).state, "running");
+ assert.equal(opWaitOf({ status: "running", tail: ["Running Seed-VC behind the heavy slot (estimate 5000 MB)…"] }).state, "running");
+ assert.equal(opWaitOf({ status: "running" }).state, "running");
+});
+
+test("cut marks: a span a person set is kept inside the part, a bad one is not one; --trim-span says them", () => {
+ assert.deepEqual(explicitSpan({ from: 0.4, to: 2.1 }, 3), { from: 0.4, to: 2.1 });
+ assert.deepEqual(explicitSpan({ from: -1, to: 9 }, 3), { from: 0, to: 3 }, "clamped");
+ assert.equal(explicitSpan({ from: 1, to: 1.1 }, 3), null, "under 0.2 s");
+ assert.equal(explicitSpan(null, 3), null);
+ assert.equal(explicitSpan({ from: "a", to: 2 }, 3), null);
+ assert.equal(trimSpans([], 2), null);
+ assert.deepEqual(trimSpans(["0.4-3.1"], 1), [{ from: 0.4, to: 3.1 }]);
+ assert.deepEqual(trimSpans(["2=0.2-4"], 2), [null, { from: 0.2, to: 4 }]);
+ for (const bad of [["3=0-1"], ["1-1.1"], ["x"], ["1=0-1", "0-2"]]) assert.throws(() => trimSpans(bad, 2), /--trim-span/);
+});
+
+test("keepRecording with explicit spans: the part is cut at the marks, whatever the trim says", async () => {
+ const rec = path.join(ROOT, "spans.wav");
+ await wavOf(rec, VOICE_B, 2, 0.6); // 3.2 s: 0.6 s of silence either side
+ const auto = await keepRecording(project, await item("p-3"), [{ file: rec }], { manifest: await manifest() });
+ assert.ok(auto.take.seconds < 2.6, `auto: trimmed (${auto.take.seconds})`);
+ const marked = await keepRecording(project, await item("p-3"), [{ file: rec }], { manifest: await manifest(), spans: [{ from: 1, to: 2 }] });
+ assert.ok(Math.abs(marked.take.seconds - 1) < 0.05, `the marks' second (${marked.take.seconds})`);
+ const off = await keepRecording(project, await item("p-3"), [{ file: rec }], { manifest: await manifest(), trim: { on: false }, spans: [{ from: 0.5, to: 3.0 }] });
+ assert.ok(Math.abs(off.take.seconds - 2.5) < 0.05, "a mark over trim off");
+ const whole = await keepRecording(project, await item("p-3"), [{ file: rec }], { manifest: await manifest(), trim: { on: false }, spans: [null] });
+ assert.ok(whole.take.seconds > 3.1, "no mark, trim off: as recorded");
+});
+
+test("the chain into the scratch dir: no take; a step is not run again while what it was made from stands; Keep makes the takes from its files", async () => {
+ await cast(["project", "rec", "add", "madam-savvy", "--name", "Madam Savvy", "--handles", "savvy", "--voice", "orpheus:mia", "--convert-engine", "seed-vc", "--convert-pitch", "contour", "--convert-semitones", "2", "--direction", "higher, brisk, amused"]);
+ const rec = path.join(ROOT, "savvy.wav");
+ await wavOf(rec, VOICE_B, 2, 0.6);
+ const ed = editor();
+ const stages = [];
+ const emit = (ev, f) => ev === "stage" && stages.push(`${f.stage}:${f.state}`);
+ const before = JSON.stringify((await item("p-1")).narration);
+ let r = await runPreview(project, await item("p-1"), [{ file: rec, text: "Savvy's line, read aloud." }], { ask: ed.ask, emit });
+ assert.deepEqual(ed.names(), ["voice-enhance", "voice-convert"]);
+ assert.equal(JSON.stringify((await item("p-1")).narration), before, "no take made");
+ assert.deepEqual(r.character, { id: "madam-savvy", name: "Madam Savvy", layer: "project" });
+ assert.equal(r.direction, "higher, brisk, amused");
+ assert.deepEqual(r.convert, { engine: "seed-vc", voice: "orpheus:mia", pitch: "contour", semitones: 2 });
+ assert.deepEqual([ed.ops[1].engine, ed.ops[1].voice, ed.ops[1].pitch, ed.ops[1].semitones], ["seed-vc", "orpheus:mia", "contour", 2], "the preset's convert, asked whole");
+ const dir = previewDirOf(DIR, await item("p-1"));
+ assert.equal(dir, path.join(DIR, "narration", ".record-preview", "1.operator"));
+ assert.equal(r.dir, dir);
+ for (const f of [r.raw, r.clean, r.filtered]) assert.ok(existsSync(f), f);
+ assert.equal(r.listen, r.filtered);
+ // Cleaned WHOLE (the part as recorded, 3.2 s), then cut: the convert was asked of the cut, cleaned read.
+ assert.ok(ed.ops[0].file.endsWith("p01.raw.wav"));
+ assert.ok(Math.abs((await measureTake(ed.ops[0].file)).seconds - 3.2) < 0.05);
+ assert.ok(ed.ops[1].file.endsWith("clean.wav"));
+ assert.ok((await measureTake(r.raw)).seconds < 2.6, "its edges trimmed");
+ // The wait at the heavy slot was a state on the way, never a failure.
+ assert.deepEqual(stages, ["decode:running", "clean:running", "clean:queued", "clean:memory", "clean:running", "clean:done", "trim:running", "trim:done", "convert:running", "convert:queued", "convert:memory", "convert:running", "convert:done", "done:done"]);
+ // What the page is told: the waveform, the auto trim's marks, both levels.
+ const v = previewView(await readPreview(DIR, await item("p-1")));
+ assert.equal(v.parts.length, 1);
+ assert.equal(v.parts[0].peaks.length, PREVIEW_PEAKS);
+ assert.ok(v.parts[0].auto.from > 0.3 && v.parts[0].auto.to < 2.9, JSON.stringify(v.parts[0].auto));
+ assert.deepEqual(v.parts[0].span, v.parts[0].auto);
+ assert.ok(Number.isFinite(v.raw.lufs) && Number.isFinite(v.filtered.lufs));
+ assert.deepEqual([v.filtered.pitch, v.filtered.semitones, v.cleaned], ["contour", 2, "done"]);
+ assert.equal("silences" in v.parts[0], false);
+ assert.equal(await previewFile(DIR, await item("p-1"), "filtered"), r.filtered);
+ assert.ok((await previewFile(DIR, await item("p-1"), "part", { n: 1 })).endsWith("p01.raw.wav"));
+
+ // The same again: nothing is asked.
+ r = await runPreview(project, await item("p-1"), [{ file: rec }], { ask: ed.ask });
+ assert.equal(ed.ops.length, 2);
+ assert.deepEqual(r.cached, { clean: true, convert: true });
+ // Another pitch: the convert ALONE, on the cleaned sound already there.
+ r = await runPreview(project, await item("p-1"), [{ file: rec }], { ask: ed.ask, pitch: "source", semitones: -1 });
+ assert.deepEqual(ed.names(), ["voice-enhance", "voice-convert", "voice-convert"]);
+ assert.deepEqual([ed.ops[2].pitch, ed.ops[2].semitones, ed.ops[2].voice], ["source", -1, "orpheus:mia"]);
+ assert.deepEqual(r.cached, { clean: true, convert: false });
+ // A mark moved: re-cut and converted, never cleaned again.
+ r = await runPreview(project, await item("p-1"), [{ file: rec }], { ask: ed.ask, spans: [{ from: 1, to: 2.2 }] });
+ assert.deepEqual(ed.names().slice(3), ["voice-convert"]);
+ assert.deepEqual(r.spans, [{ from: 1, to: 2.2 }]);
+ assert.ok(Math.abs((await measureTake(r.raw)).seconds - 1.2) < 0.05);
+ // --out: the filtered read copied where asked.
+ const out = path.join(ROOT, "out", "savvy-filtered.wav");
+ r = await runPreview(project, await item("p-1"), [{ file: rec }], { ask: ed.ask, spans: [{ from: 1, to: 2.2 }], out });
+ assert.equal(r.out, out);
+ assert.ok(existsSync(out));
+ assert.equal(ed.ops.length, 4, "a copy asks nothing");
+
+ // KEEP: three takes from the preview's files, the last picked, nothing asked of the editor; the scratch dir gone.
+ const k = await keepPreview(project, await item("p-1"));
+ assert.equal(ed.ops.length, 4);
+ assert.deepEqual(k.takes.map((t) => t.step), ["recorded", "cleaned", "converted to orpheus:mia (pitch: contour +2 st)"]);
+ assert.deepEqual(k.takes.map((t) => t.file), ["narration/posts/1/take-1.recorded-operator.wav", "narration/posts/1/take-2.enhance-default.wav", "narration/posts/1/take-3.convert-seed-vc.wav"]);
+ const n = (await item("p-1")).narration;
+ assert.equal(n.pick, 2);
+ assert.notEqual(n.approved, true, "awaiting approval");
+ assert.deepEqual(validatePostNarration(await item("p-1")), []);
+ assert.deepEqual(n.takes[0].source, { kind: "recorded", voice: "operator" });
+ assert.match(n.takes[0].note, /recorded for Madam Savvy/);
+ assert.deepEqual(n.takes[1].source, { kind: "take", from: "take-1.recorded-operator" });
+ assert.deepEqual([n.takes[1].steps[0].op, n.takes[1].steps[0].engine, n.takes[1].steps[0].job], ["enhance", "deepfilternet", "op-1"]);
+ assert.deepEqual(n.takes[2].source, { kind: "take", from: "take-2.enhance-default" });
+ assert.deepEqual([n.takes[2].voice, n.takes[2].steps[0].engine, n.takes[2].steps[0].voice, n.takes[2].steps[0].pitch, n.takes[2].steps[0].semitones], ["mia", "seed-vc", "orpheus:mia", "contour", 2]);
+ for (const t of n.takes) assert.ok(existsSync(path.join(DIR, t.file)), t.file);
+ assert.equal(k.disclosure, "Narration: voice converted to a synthetic voice (seed-vc · orpheus:mia)", "the disclosure line is what a recording made a read says");
+ assert.equal(existsSync(dir), false, "the scratch dir is removed on Keep");
+ await assert.rejects(keepPreview(project, await item("p-1")), /no preview to keep/);
+});
+
+test("the preset is honoured: enhance off, trim off; an editor with no enhance engine is said and gone without; no character converts nothing", async () => {
+ const rec = path.join(ROOT, "quiet.wav");
+ await wavOf(rec, VOICE_B, 2, 0.6);
+ await cast(["project", "rec", "set", "madam-savvy", "--enhance", "off", "--trim", "off"]);
+ let ed = editor();
+ let r = await runPreview(project, await item("p-1"), [{ file: rec }], { ask: ed.ask });
+ assert.deepEqual(ed.names(), ["voice-convert"]);
+ assert.match(r.notes[0], /not cleaned: madam-savvy's recorded preset says so/);
+ assert.equal(r.clean, null);
+ assert.ok((await measureTake(r.raw)).seconds > 3.1, "trim.on false: its edges as recorded");
+ assert.ok(ed.ops[0].file.endsWith("raw.wav"), "converted from the raw read");
+ let v = previewView(await readPreview(DIR, await item("p-1")));
+ assert.deepEqual(v.parts[0].auto, { from: 0, to: v.parts[0].seconds });
+ assert.deepEqual(v.trim, { on: false, padMs: null });
+ // The command over the preset, and a pad: the room kept either side.
+ r = await runPreview(project, await item("p-1"), [{ file: rec }], { ask: ed.ask, trim: { on: true, padMs: 400 }, clean: true });
+ assert.deepEqual(ed.names(), ["voice-convert", "voice-enhance", "voice-convert"]);
+ const padded = (await measureTake(r.raw)).seconds;
+ assert.ok(padded > 2.6 && padded < 3.1, `the pad kept (${padded})`);
+ await discardPreview(DIR, await item("p-1"));
+ assert.equal(existsSync(previewDirOf(DIR, await item("p-1"))), false);
+ await cast(["project", "rec", "set", "madam-savvy", "--enhance", "on", "--trim", "on"]);
+ // No enhance engine: said, and the raw read converted.
+ ed = editor();
+ const noEnhance = async (route, body, o) => {
+ if (route.endsWith("voice-enhance")) throw Object.assign(new Error("the editor has no engine for /api/ops/voice-enhance yet (not installed: DeepFilterNet 3 is not installed)"), { name: "OpNotInstalled" });
+ return ed.ask(route, body, o);
+ };
+ r = await runPreview(project, await item("p-1"), [{ file: rec }], { ask: noEnhance });
+ assert.match(r.notes[0], /not cleaned: .*not installed.*archilyzer voice setup --engine deepfilternet/);
+ assert.deepEqual(ed.names(), ["voice-convert"]);
+ assert.ok(r.filtered && !r.clean);
+ const k = await keepPreview(project, await item("p-1"));
+ assert.deepEqual(k.takes.map((t) => t.step), ["recorded", "converted to orpheus:mia (pitch: contour +2 st)"]);
+ // p-3's author has no character (and there is no cast): cleaned, not converted -- the cleaned read is what to listen to.
+ ed = editor();
+ r = await runPreview(project, await item("p-3"), [{ file: rec }], { ask: ed.ask });
+ assert.deepEqual(ed.names(), ["voice-enhance"]);
+ assert.match(r.notes[0], /not converted: a convert needs a stock voice to convert to, and this post has no character with one/);
+ assert.equal(r.character, null);
+ assert.equal(r.listen, r.clean);
+ // A voice named for this read converts it all the same.
+ r = await runPreview(project, await item("p-3"), [{ file: rec }], { ask: ed.ask, voice: "kokoro:am_puck" });
+ assert.deepEqual([ed.names().at(-1), ed.ops.at(-1).voice], ["voice-convert", "kokoro:am_puck"]);
+ await assert.rejects(runPreview(project, await item("p-3"), [{ file: rec }], { ask: ed.ask, as: "ghost" }), /--as ghost: no such character/);
+ await discardPreview(DIR, await item("p-3"));
+});
+
+test("the record page's session: a parted read previewed part by part, kept from the terminal (the session over), or kept alone at its marks", async () => {
+ const e = await item("p-2");
+ const a = path.join(ROOT, "part-a.wav");
+ const b = path.join(ROOT, "part-b.wav");
+ await wavOf(a, VOICE_B, 1.5, 0.4);
+ await wavOf(b, VOICE_B, 1.0, 0.4);
+ await savePart(DIR, e, { n: 1, count: 2, text: "A first paragraph.", para: 0, bytes: await readFile(a), type: "audio/wav" });
+ await savePart(DIR, e, { n: 2, count: 2, text: "A second one.", para: 1, bytes: await readFile(b), type: "audio/wav" });
+ const { sessionParts } = await import("./recordSession.mjs");
+ const parts = await sessionParts(DIR, e);
+ const pre = await preparePreview(project, e, parts);
+ assert.deepEqual(pre.parts.map((p) => [p.n, p.text]), [[1, "A first paragraph."], [2, "A second one."]]);
+ const ed = editor();
+ const r = await runPreview(project, e, parts, { ask: ed.ask, spans: [null, { from: 0.3, to: 1.5 }] });
+ assert.deepEqual(ed.names(), ["voice-enhance", "voice-convert"]);
+ assert.equal(ed.ops[0].parts.length, 1, "the second part cleaned in the same job");
+ assert.equal(ed.ops[1].parts.length, 2, "each cut part converted beside the whole");
+ assert.deepEqual(r.spans[1], { from: 0.3, to: 1.5 });
+ // The CLI twin over the session: cached, so nothing is asked; --keep-preview makes parted takes.
+ let c = await posts(["narrate", "rec", "p-2", "--preview", "--trim-span", "2=0.3-1.5", "--json"], { ask: ed.ask });
+ assert.equal(c.code, 0, c.text());
+ assert.equal(ed.ops.length, 2);
+ assert.deepEqual(c.json().cached, { clean: true, convert: true });
+ c = await posts(["narrate", "rec", "p-2", "--keep-preview", "--json"]);
+ assert.equal(c.code, 0, c.text());
+ const n = (await item("p-2")).narration;
+ assert.deepEqual(n.takes.map((t) => t.parts.length), [2, 2, 2]);
+ assert.deepEqual(n.takes[2].parts.map((p) => p.file), ["narration/posts/2/take-3.convert-seed-vc.parts/p01.wav", "narration/posts/2/take-3.convert-seed-vc.parts/p02.wav"]);
+ for (const t of n.takes) for (const p of t.parts) assert.ok(existsSync(path.join(DIR, p.file)), p.file);
+ assert.ok(Math.abs(n.takes[0].parts[1].seconds - 1.2) < 0.02, "the second part at its marks");
+ assert.deepEqual(validatePostNarration(await item("p-2")), []);
+ assert.equal(existsSync(path.join(DIR, "narration", "posts", "2", ".recording-operator")), false, "a session's preview kept: the session is over");
+ // finishSession with marks (Keep with no Filter): the recorded take alone, cut at them.
+ await savePart(DIR, e, { n: 1, count: 2, text: "A first paragraph.", para: 0, bytes: await readFile(a), type: "audio/wav" });
+ await savePart(DIR, e, { n: 2, count: 2, text: "A second one.", para: 1, bytes: await readFile(b), type: "audio/wav" });
+ const kept = await finishSession(project, await item("p-2"), { manifest: await manifest(), spans: [{ from: 0.5, to: 1.5 }, null] });
+ assert.ok(Math.abs(kept.take.parts[0].seconds - 1) < 0.02);
+ assert.equal(existsSync(path.join(DIR, "narration", "posts", "2", ".recording-operator")), false);
+});
+
+test("the CLI twin: --recording <file> --preview prints the paths and makes no take; --events is one object a line; --discard-preview", async () => {
+ const rec = path.join(ROOT, "cli.wav");
+ await wavOf(rec, VOICE_B, 2, 0.6);
+ const ed = editor();
+ const takes = (await item("p-1")).narration.takes.length;
+ let c = await posts(["narrate", "rec", "p-1", "--recording", rec, "--preview", "--pitch", "source"], { ask: ed.ask });
+ assert.equal(c.code, 0, c.text());
+ assert.match(c.text(), /p-1: previewed as Madam Savvy -- NO TAKE MADE/);
+ assert.match(c.text(), /raw\s+.*narration\/\.record-preview\/1\.operator\/raw\.wav/);
+ assert.match(c.text(), /filtered\s+.*filtered\.wav \(seed-vc -> orpheus:mia, pitch: source \+2 st\)/);
+ assert.match(c.text(), /converting: waiting for memory \(the heavy slot admits it when there is room -- not an error\)/);
+ assert.match(c.text(), /keep it: umtool posts narrate rec p-1 --keep-preview/);
+ assert.equal((await item("p-1")).narration.takes.length, takes, "no take");
+ c = await posts(["narrate", "rec", "p-1", "--recording", rec, "--preview", "--as", "madam-savvy", "--pitch", "target", "--events"], { ask: ed.ask });
+ const evs = c.lines.map((l) => JSON.parse(l));
+ assert.deepEqual(evs.at(-1).ev, "result");
+ assert.ok(evs.at(-1).filtered.endsWith("filtered.wav"));
+ assert.ok(evs.some((x) => x.ev === "stage" && x.stage === "convert" && x.state === "memory"));
+ assert.equal(evs.at(-1).character.layer, "flag");
+ assert.equal(ed.ops.at(-1).semitones, undefined, "the target's own pitch takes no semitones");
+ c = await posts(["narrate", "rec", "p-1", "--recording", path.join(ROOT, "nope.wav"), "--preview"]);
+ assert.equal(c.code, 2);
+ c = await posts(["narrate", "rec", "p-3", "--preview"]);
+ assert.equal(c.code, 2);
+ assert.match(c.text(), /--preview takes --recording <file>, or the record page's session of p-3: nothing recorded yet/);
+ c = await posts(["narrate", "rec", "p-1", "--discard-preview"]);
+ assert.equal(c.code, 0);
+ assert.equal(existsSync(previewDirOf(DIR, await item("p-1"))), false);
+ c = await posts(["narrate", "rec", "p-1", "--keep-preview"]);
+ assert.notEqual(c.code, 0);
+ assert.match(c.text(), /no preview to keep/);
+});
+
+test("a preview is kept only for the recording it was made from: a part recorded again since the Filter is refused, nothing kept", async () => {
+ const e = await item("p-2");
+ const a = path.join(ROOT, "again-a.wav");
+ const b = path.join(ROOT, "again-b.wav");
+ await wavOf(a, VOICE_B, 1.5, 0.4);
+ await wavOf(b, VOICE_B, 1.0, 0.4);
+ await savePart(DIR, e, { n: 1, count: 2, text: "A first paragraph.", para: 0, bytes: await readFile(a), type: "audio/wav" });
+ await savePart(DIR, e, { n: 2, count: 2, text: "A second one.", para: 1, bytes: await readFile(b), type: "audio/wav" });
+ const { sessionParts } = await import("./recordSession.mjs");
+ const ed = editor();
+ await runPreview(project, e, await sessionParts(DIR, e), { ask: ed.ask, session: true });
+ const takes = (await item("p-2")).narration.takes.length;
+ // Part 2 recorded again (Space, with no Again): the session is another recording now.
+ await new Promise((res) => setTimeout(res, 20));
+ await savePart(DIR, e, { n: 2, count: 2, text: "A second one.", para: 1, bytes: await readFile(a), type: "audio/wav" });
+ await assert.rejects(keepPreview(project, await item("p-2"), { parts: await sessionParts(DIR, e) }), (err) => err.status === 409 && /preview is of an earlier recording/.test(err.message));
+ assert.equal((await item("p-2")).narration.takes.length, takes, "nothing kept");
+ assert.ok(existsSync(path.join(DIR, "narration", "posts", "2", ".recording-operator", "session.json")), "the new part is still there");
+ // The terminal's --keep-preview asks the same.
+ const c = await posts(["narrate", "rec", "p-2", "--keep-preview"]);
+ assert.notEqual(c.code, 0);
+ assert.match(c.text(), /preview is of an earlier recording/);
+ // The same recording: kept.
+ await runPreview(project, await item("p-2"), await sessionParts(DIR, e), { ask: ed.ask, session: true });
+ const k = await keepPreview(project, await item("p-2"), { parts: await sessionParts(DIR, e) });
+ assert.equal(k.session, true);
+ const { clearSession } = await import("./recordSession.mjs");
+ await clearSession(DIR, e);
+});
+
+test("an upload that is text (a playlist, a concat script) is refused before ffmpeg opens it; ffmpeg may open local files only", async () => {
+ const secret = path.join(ROOT, "secret.wav");
+ await wavOf(secret, VOICE_A, 1, 0);
+ const lists = {
+ "list.m3u8": `#EXTM3U\n#EXT-X-TARGETDURATION:10\n#EXTINF:10,\n${secret}\n#EXT-X-ENDLIST\n`,
+ "list.wav": `#EXTM3U\n#EXTINF:10,\nhttp://127.0.0.1:9/x.ts\n`,
+ "script.ffconcat": `ffconcat version 1.0\nfile '${secret}'\n`,
+ };
+ for (const [name, text] of Object.entries(lists)) {
+ const f = path.join(ROOT, name);
+ await writeFile(f, text);
+ assert.equal(await looksLikeText(f), true, name);
+ const out = path.join(ROOT, `${name}.out.wav`);
+ await assert.rejects(decodePart(f, out), (err) => err.status === 400 && /not a sound file: it is text/.test(err.message), name);
+ assert.equal(existsSync(out), false, `${name}: nothing decoded`);
+ await assert.rejects(keepRecording(project, await item("p-3"), [{ file: f }], { manifest: await manifest() }), /not a sound file/);
+ await assert.rejects(runPreview(project, await item("p-3"), [{ file: f }], { ask: editor().ask }), /not a sound file/);
+ }
+ assert.equal(await looksLikeText(secret), false, "a wav is binary");
+ const ok = await decodePart(secret, path.join(ROOT, "secret.out.wav"));
+ assert.ok(ok.seconds > 0.9);
+});
diff --git a/umtool/lib/report/recordSession.mjs b/umtool/lib/report/recordSession.mjs
@@ -45,7 +45,8 @@ async function writeSession(dir, doc) {
await rename(tmp, path.join(dir, "session.json"));
}
-const extOf = (type) => (/ogg/.test(type) ? "ogg" : /wav/.test(type) ? "wav" : /mp4|aac/.test(type) ? "m4a" : "webm");
+// A browser recording is webm or ogg; a sound file chosen for a part keeps what it is (ffmpeg reads it either way).
+const extOf = (type) => (/ogg/.test(type) ? "ogg" : /wav/.test(type) ? "wav" : /mp4|aac|m4a/.test(type) ? "m4a" : /mpeg|mp3/.test(type) ? "mp3" : /flac/.test(type) ? "flac" : "webm");
/**
* KEEP ONE PART: its bytes written (through a rename: never half a file), the
@@ -98,26 +99,45 @@ export async function partFile(projectDir, entry, n, label = "operator") {
}
/**
- * FINISH: every part of the post in -> one recorded take (keepRecording),
- * picked; the session cleared. Refused, naming the missing parts, otherwise.
- *
- * @param {{ id: string, dir: string }} project
- * @param {Record<string, any>} entry
- * @param {{ label?: string, manifest?: Record<string, any> | null, script?: string | null }} [o]
+ * The session's parts in reading order, as keepRecording and the preview take them (`[{ file, text, para }]`, the
+ * files absolute). Refused, naming the missing parts, when the post's read is not all in.
*/
-export async function finishSession(project, entry, { label = "operator", manifest = null, script = null } = {}) {
- const doc = await readSession(project.dir, entry, label);
+export async function sessionParts(projectDir, entry, label = "operator") {
+ const doc = await readSession(projectDir, entry, label);
const count = doc.count ?? 0;
const missing = [];
for (let n = 1; n <= count; n += 1) if (!doc.parts[String(n)]) missing.push(n);
if (!count || missing.length) throw Object.assign(new Error(count ? `parts ${missing.join(", ")} of ${count} are not recorded yet` : "nothing recorded yet"), { status: 400 });
- const dir = sessionDirOf(project.dir, entry, label);
+ const dir = sessionDirOf(projectDir, entry, label);
const parts = [];
for (let n = 1; n <= count; n += 1) {
const p = doc.parts[String(n)];
parts.push({ file: path.join(dir, p.file), text: p.text, para: p.para });
}
- const kept = await keepRecording(project, entry, parts, { label, manifest, script });
- await rm(dir, { recursive: true, force: true });
+ return parts;
+}
+
+/** Remove the session (its parts are a take now, or were given up). */
+export async function clearSession(projectDir, entry, label = "operator") {
+ checkLabel(label);
+ await rm(sessionDirOf(projectDir, entry, label), { recursive: true, force: true });
+}
+
+/**
+ * FINISH: every part of the post in -> one recorded take (keepRecording),
+ * picked; the session cleared. Refused, naming the missing parts, otherwise.
+ * `spans`: the cut marks a person set on the record page, per part (`[{ from, to } | null]`); a part without one is
+ * trimmed as its character's recorded preset says.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {Record<string, any>} entry
+ * @param {{ label?: string, manifest?: Record<string, any> | null, script?: string | null, spans?: Array<{ from: number, to: number } | null> | null }} [o]
+ */
+export async function finishSession(project, entry, { label = "operator", manifest = null, script = null, spans = null } = {}) {
+ const parts = await sessionParts(project.dir, entry, label);
+ // Its character's recorded preset says whether its edges are trimmed, and the room kept (characterLayers.mjs).
+ const { recordedTrimFor } = await import("./characterLayers.mjs");
+ const kept = await keepRecording(project, entry, parts, { label, manifest, script, trim: await recordedTrimFor(project.dir, entry), spans });
+ await clearSession(project.dir, entry, label);
return kept;
}
diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs
@@ -366,6 +366,9 @@ export function withPatchEntries(takeTimeline, baseTimeline, ids) {
* CLIPPED to the steps inside it -- the window keeps a straddling clip
* (windowEntries), so it keeps the part of the claim that clip carries;
* a goalpost with no step inside is dropped.
+ * - an effect's clip list (`render.chrome.fx`): `kineticQuote.clips`, `redact.clips` and `glitch.clips` keep the
+ * clips inside (a glitch's only with a clip right before it: it tears at that cut), `thenNow.pairs` the pairs
+ * with both ends inside; an effect left with none is off in the window.
*
* The kept ones need no re-timing: each names a clip by id, and its `t` is a
* source second of that clip, which the window renders whole.
@@ -391,6 +394,35 @@ export function windowManifest(manifest, ids) {
});
}
}
+ // The effects that name clips (fx.mjs validateFxEntries refuses a name the cut does not hold -- rev9-a9, 12 Nov:
+ // `take --preview --at … --dur …` was refused with "render.chrome.fx.glitch.clips names k06, which is not a clip
+ // of the cut"). A list keeps the clips inside; an effect left naming none is off in the window (an empty list is
+ // not one fx.mjs takes). The glitch tears at the cut INTO a clip, so a named clip stays only with a clip right
+ // before it in the window; a then/now pair needs both its ends.
+ const fx = m.render?.chrome?.fx;
+ if (isObj(fx)) {
+ const at = new Map(m.timeline.map((e, i) => [e?.id, i]));
+ const isClip = (id) => typeof id === "string" && m.timeline[at.get(id)]?.type === "clip";
+ for (const k of ["kineticQuote", "redact"]) {
+ if (!isObj(fx[k]) || !Array.isArray(fx[k].clips)) continue;
+ const clips = fx[k].clips.filter(isClip);
+ if (clips.length) fx[k].clips = clips;
+ else delete fx[k];
+ }
+ // Only a glitch on "clips" reads its list (fx.mjs); in another mode the list is not looked at, so it is left
+ // alone -- and the glitch with it.
+ if (isObj(fx.glitch) && fx.glitch.on === "clips" && Array.isArray(fx.glitch.clips)) {
+ const clips = fx.glitch.clips.filter((id) => isClip(id) && m.timeline[at.get(id) - 1]?.type === "clip");
+ if (clips.length) fx.glitch.clips = clips;
+ else delete fx.glitch;
+ }
+ if (isObj(fx.thenNow) && Array.isArray(fx.thenNow.pairs)) {
+ const pairs = fx.thenNow.pairs.filter((p) => !isObj(p) || (isClip(p.then) && isClip(p.now)));
+ if (pairs.length) fx.thenNow.pairs = pairs;
+ else delete fx.thenNow;
+ }
+ if (!Object.keys(fx).length) delete m.render.chrome.fx;
+ }
return m;
}
diff --git a/umtool/lib/report/takeMaker.test.mjs b/umtool/lib/report/takeMaker.test.mjs
@@ -32,6 +32,7 @@ import {
} from "./takeMaker.mjs";
import { listTakes, readVerdicts, setTakeVerdict } from "./takes.mjs";
import { validateDeckClaims, validateDeckMarkers } from "umtool-report-to-video/deck";
+import { validateFxEntries } from "umtool-report-to-video/fx";
import { PROJECT_KINDS } from "../projects/kinds.mjs";
// The kind takes are made of, from the registry (never its id spelled here).
@@ -562,6 +563,54 @@ test("windowManifest: markers and claim checks outside the window are dropped; a
assert.equal(all.render.chrome.deck.claims[2].steps.length, 2);
});
+test("windowManifest: an effect's clip list keeps the window's clips -- a glitch's with a clip before it, a then/now pair with both ends -- and an effect left with none is off", () => {
+ const clipIds = ["k01", "k02", "k03", "k04", "k05", "k06"];
+ const manifest = {
+ ...MANIFEST,
+ timeline: clipIds.map((id, i) => clip(id, 10 * i, 10 * i + 5)),
+ render: {
+ ...MANIFEST.render,
+ chrome: {
+ engine: "hyperframes", layout: "deck", deck: {},
+ fx: {
+ glitch: { on: "clips", clips: ["k02", "k03", "k06"] },
+ thenNow: { pairs: [{ then: "k02", now: "k03" }, { then: "k05", now: "k06" }] },
+ kineticQuote: { clips: ["k01", "k03"] },
+ redact: { clips: ["k06"] },
+ wipe: {},
+ },
+ },
+ },
+ };
+ const before = JSON.stringify(manifest);
+ // The whole manifest windowed as-was is what the build refused (rev9-a9: "names k06, which is not a clip of the cut").
+ const naive = { ...manifest, timeline: manifest.timeline.filter((e) => ["k02", "k03", "k04"].includes(e.id)) };
+ assert.match(validateFxEntries(naive, { schedule: null }).join("\n"), /render\.chrome\.fx\.glitch\.clips names k06, which is not a clip of the cut/);
+ const m = windowManifest(manifest, ["k02", "k03", "k04"]);
+ const fx = m.render.chrome.fx;
+ // k02 opens the window: no clip before it, no cut to tear at.
+ assert.deepEqual(fx.glitch, { on: "clips", clips: ["k03"] });
+ assert.deepEqual(fx.thenNow.pairs, [{ then: "k02", now: "k03" }]);
+ assert.deepEqual(fx.kineticQuote.clips, ["k03"]);
+ assert.equal("redact" in fx, false, "it named only a clip outside: off in the window");
+ assert.deepEqual(fx.wipe, {}, "an effect that names no clip is as it was");
+ assert.deepEqual(validateFxEntries(m, { schedule: null }), []);
+ assert.equal(JSON.stringify(manifest), before, "the project's manifest is not touched");
+ // A window with none of them: the effects are off, the rest of the chrome as it was.
+ const none = windowManifest(manifest, ["k04"]);
+ assert.deepEqual(none.render.chrome.fx, { wipe: {} });
+ assert.deepEqual(validateFxEntries(none, { schedule: null }), []);
+ // The full window keeps every one.
+ assert.deepEqual(windowManifest(manifest, clipIds).render.chrome.fx, manifest.render.chrome.fx);
+ // A glitch in another mode never reads its list (fx.mjs): the window leaves it, and the glitch, as they were.
+ const byYear = { ...manifest, render: { ...manifest.render, chrome: { ...manifest.render.chrome, fx: { glitch: { on: "year", clips: ["k06"] } } } } };
+ assert.deepEqual(windowManifest(byYear, ["k02", "k03", "k04"]).render.chrome.fx, { glitch: { on: "year", clips: ["k06"] } });
+ const noMode = { ...manifest, render: { ...manifest.render, chrome: { ...manifest.render.chrome, fx: { glitch: { clips: ["k06"] } } } } };
+ assert.deepEqual(windowManifest(noMode, ["k02", "k03", "k04"]).render.chrome.fx, { glitch: { clips: ["k06"] } });
+ // A pair cut by the window's edge is dropped, the other kept.
+ assert.deepEqual(windowManifest(manifest, ["k03", "k04", "k05", "k06"]).render.chrome.fx.thenNow.pairs, [{ then: "k05", now: "k06" }]);
+});
+
test("withPatchEntries: a clip only the take's patch adds stays in the window beside the covered clip before it", () => {
const base = [{ id: "a" }, { id: "b" }, { id: "c" }, { id: "d" }];
// The patch adds x after b (covered), y after x, z after d (not covered).
diff --git a/umtool/lib/research/sources.test.ts b/umtool/lib/research/sources.test.ts
@@ -0,0 +1,89 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// The source picker (demo epic D1): connected archives are offered through
+// the one resolver; with no local build, the first archive is the default.
+const root = await mkdtemp(path.join(os.tmpdir(), "umtool-sources-"));
+const local = path.join(root, "public");
+const settingsFile = path.join(root, "settings.json");
+await mkdir(path.join(root, "sites", "mysite"), { recursive: true });
+await writeFile(path.join(root, "sites", "mysite", "site.json"), JSON.stringify({ siteUrl: "https://stub.test/", siteTitle: "From site.json" }));
+await writeFile(settingsFile, JSON.stringify({ remoteArchives: [{ id: "stub", origin: "https://stub.test", title: "Stubalyzer", addedAt: "2026-11-11T00:00:00Z" }] }));
+process.env.SITES_DIR = path.join(root, "sites");
+process.env.SETTINGS_FILE = settingsFile;
+process.env.TRANSCRIPT_LOCAL_DIR = local;
+process.env.TRANSCRIPT_HUB_URL = "";
+process.env.TRANSCRIPT_SITE_URL = "https://env.test";
+const { listSources, buildIdentity } = await import("./sources");
+
+test.after(() => rm(root, { recursive: true, force: true }));
+
+test("no local build: the connected archives come first, site.json's duplicate is dropped, the env's is offered", async () => {
+ const s = await listSources();
+ assert.deepEqual(
+ s.map((x) => [x.handle, x.label]),
+ [
+ ["remote:https://stub.test", "Stubalyzer"],
+ ["remote:https://env.test", "env.test"],
+ [`local:${local}`, "Local corpus"],
+ ],
+ );
+ assert.equal(s[2].detail, "this machine · no build");
+});
+
+test("with a local build the local corpus is the default, the archives after it", async () => {
+ await mkdir(local, { recursive: true });
+ await writeFile(path.join(local, "corpus.json"), JSON.stringify({ site: { title: "Mine" } }));
+ const s = await listSources();
+ assert.equal(s[0].handle, `local:${local}`);
+ assert.deepEqual(s.slice(1).map((x) => x.handle), ["remote:https://stub.test", "remote:https://env.test"]);
+});
+
+// demo epic D1 re-review, item 4: a source's build is read from its own origin, bounded.
+test("a remote source's build identity: corpus.json on its own origin; a redirect elsewhere or an oversize answer is no identity", async () => {
+ const option = { handle: "remote:https://stub.test", kind: "remote", label: "Stub" } as never;
+ const asked: { url: string; redirect?: string }[] = [];
+ const fake = (answers: Record<string, () => Response>) =>
+ (async (url: string, init?: { redirect?: string }) => {
+ asked.push({ url, redirect: init?.redirect });
+ return (answers[url] ?? (() => new Response("nope", { status: 404 })))();
+ }) as never;
+
+ assert.equal(await buildIdentity(option, fake({ "https://stub.test/corpus.json": () => new Response(JSON.stringify({ generatedAt: "2026-11-01T00:00:00Z" })) })), "2026-11-01T00:00:00Z");
+ assert.deepEqual(asked, [{ url: "https://stub.test/corpus.json", redirect: "manual" }]);
+
+ // A same-origin redirect is followed.
+ assert.equal(
+ await buildIdentity(
+ option,
+ fake({
+ "https://stub.test/corpus.json": () => new Response(null, { status: 301, headers: { location: "/v2/corpus.json" } }),
+ "https://stub.test/v2/corpus.json": () => new Response(JSON.stringify({ generatedAt: "g2" })),
+ }),
+ ),
+ "g2",
+ );
+
+ // One that leaves the origin is not: nothing is asked of the other host.
+ asked.length = 0;
+ assert.equal(
+ await buildIdentity(
+ option,
+ fake({
+ "https://stub.test/corpus.json": () => new Response(null, { status: 302, headers: { location: "http://127.0.0.1:3001/api/ops/settings" } }),
+ "http://127.0.0.1:3001/api/ops/settings": () => new Response(JSON.stringify({ generatedAt: "leaked" })),
+ }),
+ ),
+ null,
+ );
+ assert.deepEqual(asked.map((a) => a.url), ["https://stub.test/corpus.json"]);
+
+ // An answer declaring more than the document bound is not read.
+ assert.equal(
+ await buildIdentity(option, fake({ "https://stub.test/corpus.json": () => new Response(JSON.stringify({ generatedAt: "big" }), { headers: { "content-length": String(64 * 1024 * 1024) } }) })),
+ null,
+ );
+});
diff --git a/umtool/lib/research/sources.ts b/umtool/lib/research/sources.ts
@@ -1,6 +1,8 @@
import { readdir, readFile, stat } from "node:fs/promises";
import path from "node:path";
import { SourceRegistry, type ShardSource, type SourceSpec } from "yt-dlp-transcript-mcp/research";
+import { connectedArchives } from "yt-dlp-transcript-common/lib/remoteArchives";
+import { fetchOnOrigin, readBounded, type FetchLike } from "yt-dlp-transcript-common/lib/remoteArchives-server";
import { REPO_ROOT, REPORTS_ROOT, SITES_DIR } from "../paths.mjs";
import { readCensus } from "./census.mjs";
import type { SourceOption } from "./types";
@@ -12,8 +14,11 @@ import type { SourceOption } from "./types";
// local the composed public dir on this machine, resolved as the MCP
// server's default resolves it: TRANSCRIPT_LOCAL_DIR, else
// EXPORT_PUBLIC_DIR, else <repo>/export/public
-// remote a published site: every transcripts/sites/*/site.json with a
-// `siteUrl` (a private site has none, and is not offered)
+// remote a published archive: every CONNECTED archive (settings.json
+// `remoteArchives`, plus TRANSCRIPT_SITE_URL's — the one resolver,
+// yt-dlp-transcript-common/lib/remoteArchives.ts), then every
+// transcripts/sites/*/site.json with a `siteUrl` not already
+// listed (a private site has none, and is not offered)
// hub TRANSCRIPT_HUB_URL, else settings.json `homepageUrl`
//
// Only an OFFERED handle opens: a request naming any other directory or origin
@@ -50,7 +55,7 @@ async function readJson<T>(file: string): Promise<T | null> {
}
}
-/** Every corpus the ask bar may read, the local one first. */
+/** Every corpus the ask bar may read, the default first: the local one, unless it has no build and an archive is offered. */
export async function listSources(): Promise<SourceOption[]> {
const dir = localDir();
const corpus = await readJson<{ site?: { title?: string } }>(path.join(/* turbopackIgnore: true */ dir, "corpus.json"));
@@ -62,13 +67,24 @@ export async function listSources(): Promise<SourceOption[]> {
detail: corpus?.site?.title ? `this machine · ${corpus.site.title} build` : "this machine",
},
];
- const ids = await readdir(/* turbopackIgnore: true */ SITES_DIR).catch(() => [] as string[]);
+ const settingsFile = process.env.SETTINGS_FILE?.trim() || path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json");
+ const settings = await readJson<{ homepageUrl?: unknown; remoteArchives?: unknown }>(settingsFile);
const sites: SourceOption[] = [];
+ for (const a of connectedArchives(settings?.remoteArchives)) {
+ sites.push({
+ handle: `remote:${a.origin}`,
+ kind: "remote",
+ label: a.title,
+ detail: `connected · ${a.origin.replace(/^https?:\/\//, "")}`,
+ });
+ }
+ const ids = await readdir(/* turbopackIgnore: true */ SITES_DIR).catch(() => [] as string[]);
for (const id of ids.sort()) {
if (id.startsWith("_") || id.startsWith(".")) continue;
const site = await readJson<{ siteUrl?: unknown; siteTitle?: unknown }>(path.join(/* turbopackIgnore: true */ SITES_DIR, id, "site.json"));
const url = typeof site?.siteUrl === "string" ? site.siteUrl.trim().replace(/\/+$/, "") : "";
if (!/^https?:\/\//.test(url)) continue;
+ if (sites.some((x) => x.handle === `remote:${url}`)) continue;
sites.push({
handle: `remote:${url}`,
kind: "remote",
@@ -76,9 +92,15 @@ export async function listSources(): Promise<SourceOption[]> {
detail: `published · ${url.replace(/^https?:\/\//, "")}`,
});
}
- out.push(...sites);
- const settingsFile = process.env.SETTINGS_FILE?.trim() || path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json");
- const hub = hubUrl(await readJson<{ homepageUrl?: unknown }>(settingsFile));
+ // NO LOCAL CORPUS (no composed corpus.json on this machine — a fresh
+ // clone) and an archive to read: the archives come first, so the default
+ // source (`sources[0]` everywhere, and openSource with no handle) is the
+ // first archive (demo epic D1 item 2). The local entry stays offered, last.
+ if (!corpus && sites.length > 0) {
+ out[0] = { ...out[0], detail: "this machine · no build" };
+ out.unshift(...sites);
+ } else out.push(...sites);
+ const hub = hubUrl(settings);
if (hub) out.push({ handle: `hub:${hub}`, kind: "hub", label: "Hub", detail: `every listed site · ${hub.replace(/^https?:\/\//, "")}` });
return out;
}
@@ -128,7 +150,7 @@ const IDENTITY_TIMEOUT_MS = 10_000;
* file's mtime and size (a recomposed export/public changes both). Null when
* it cannot be told -- then the census is counted but not kept.
*/
-export async function buildIdentity(option: SourceOption): Promise<string | null> {
+export async function buildIdentity(option: SourceOption, doFetch: FetchLike = fetch as unknown as FetchLike): Promise<string | null> {
if (option.kind === "local") {
const file = path.join(/* turbopackIgnore: true */ option.handle.slice("local:".length), "corpus.json");
const st = await stat(/* turbopackIgnore: true */ file).catch(() => null);
@@ -138,9 +160,12 @@ export async function buildIdentity(option: SourceOption): Promise<string | null
}
const url = option.handle.replace(/^(remote|hub):/, "").replace(/#.*$/, "");
try {
- const res = await fetch(`${url}/corpus.json`, { signal: AbortSignal.timeout(IDENTITY_TIMEOUT_MS) });
+ // An archive is untrusted input: read on its own origin (no redirect
+ // elsewhere is followed) and never past the document bound.
+ const at = `${url}/corpus.json`;
+ const res = await fetchOnOrigin(doFetch, at, { signal: AbortSignal.timeout(IDENTITY_TIMEOUT_MS) });
if (!res.ok) return null;
- const j = (await res.json()) as { generatedAt?: unknown };
+ const j = JSON.parse(await readBounded(res, at)) as { generatedAt?: unknown };
return typeof j.generatedAt === "string" && j.generatedAt ? j.generatedAt : null;
} catch {
return null;
diff --git a/umtool/package.json b/umtool/package.json
@@ -8,7 +8,7 @@
"build": "next build",
"start": "next start --port ${UMTOOL_PORT:-3050}",
"typecheck": "tsc --noEmit",
- "test": "tsx --test lib/brandIcon.test.ts lib/research/*.test.ts lib/inbox/*.test.ts lib/clips/*.test.ts components/projects/bench/*.test.ts",
+ "test": "tsx --test lib/brandIcon.test.ts lib/articles/*.test.ts lib/research/*.test.ts lib/inbox/*.test.ts lib/clips/*.test.ts components/projects/bench/*.test.ts",
"e2e": "node ../scripts/worktree.mjs run -- node ../scripts/queue-lock.mjs --name e2e-umtool --estimate 1500 --prebuild umtool --ports UMTOOL_E2E_PORT:3051,EDITOR_STUB_PORT:3052 -- playwright test"
},
"dependencies": {
diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts
@@ -14,6 +14,9 @@ import { dataRootRefusal } from "./lib/e2eEnvGuard.mjs";
// it was asked (e2e/fixtures/editor-stub.mjs)
// E2E_GEN_PROJECTS set below on the editor stub: where a stubbed video
// revision writes its project (release 27)
+// E2E_UMTOOL_SETTINGS_FILE set below on the editor stub: the settings file its
+// `archives` action writes (demo epic D1) -- the
+// fixture's copy the app reads as SETTINGS_FILE
// E2E_UMTOOL_EXTRA_KINDS set by projects.spec.ts on the CLI it runs: a kind
// injected into the registry (lib/projects/kinds.mjs)
// E2E_MODE `start` (the default): the app runs under
@@ -164,6 +167,11 @@ export default defineConfig({
// article store, and a video revision's project under gen-projects.
ARTICLES_DIR: `${FIXTURE}/articles`,
E2E_GEN_PROJECTS: `${FIXTURE}/gen-projects`,
+ // demo epic D1: the file the archives action writes -- the fixture's
+ // settings, which the app reads. NOT the stub's own SETTINGS_FILE: the
+ // stub starts beside make-fixture.mjs, before that copy exists, and its
+ // in-process common code (the real verdict-review) reads settings.
+ E2E_UMTOOL_SETTINGS_FILE: `${FIXTURE}/settings.json`,
},
},
{
@@ -192,6 +200,11 @@ export default defineConfig({
// Research's local corpus (R1): the fixture's composed public dir, read as
// the MCP's --local reads one -- never the checkout's export/public.
`TRANSCRIPT_LOCAL_DIR=${FIXTURE}/research-public TRANSCRIPT_HUB_URL= ` +
+ // The settings the app reads (demo epic D1): the fixture's copy of the
+ // checkout's (make-fixture.mjs), so Connect an archive writes there; no
+ // archive from the shell's TRANSCRIPT_SITE_URL; the archive cache the
+ // fixture's own (common/lib/archiveCache-server.ts).
+ `SETTINGS_FILE=${FIXTURE}/settings.json TRANSCRIPT_SITE_URL= ARCHIVE_CACHE_DIR=${FIXTURE}/archive-cache ` +
// The generation usage ledger (release 27): the fixture's, never the
// checkout's .generation/usage.jsonl.
`GENERATION_USAGE_FILE=${FIXTURE}/generation-usage.jsonl ` +
diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md
@@ -2601,8 +2601,11 @@ node umtool/report-to-video/compose-chrome.mjs <manifest.json> --region posts --
- **The stack is planned in the page.** Whether the next card overflows the
column depends on how its words wrap in the deck's face, so the page
measures the cards once the fonts are in and hands the heights to
- `postsCues` — the module's own function, carried in by its source text, so
- the tests run the exact plan the page runs. The timeline is built and
+ `postsPlan` — the module's own function, carried in by its source text, so
+ the tests run the exact plan the page runs. An embedded function reaches
+ nothing outside its own body (a built umtool minifies every module-scope
+ name), so the first-frame fold is handed to it as a parameter;
+ `embedded-source.test.mjs` holds every function a page carries to that. The timeline is built and
registered in that callback; the renderer awaits `document.fonts.ready`
before its first seek.
- **The overlay:** each window is an input with `-itsoffset <from>` (negative
diff --git a/umtool/report-to-video/archive-fetch.mjs b/umtool/report-to-video/archive-fetch.mjs
@@ -0,0 +1,106 @@
+// READING A PUBLISHED ARCHIVE, AS UNTRUSTED INPUT (demo epic D1 re-review, item 3).
+//
+// An archive is someone else's server and someone else's JSON. The editor
+// reads one through common/lib/remoteArchives-server.ts (fetchOnOrigin,
+// readBounded, and archiveRecordOf's "a manifest the corpus names elsewhere is
+// not followed"); this is the same three rules for the render's cue walk and
+// the other readers of createJsonCache (cues.mjs), in plain JS because these
+// scripts run under bare node with no tsx. Change one, change the other.
+//
+// - a document is read on the origin it was asked on: a redirect is followed
+// by hand, up to three, and only to the same scheme, host and port;
+// - no document past 32 MB is read (a shard page is up to 8 MB);
+// - a channel's transcripts manifest is the one corpus.json names only when
+// that is on the corpus's own origin; otherwise the contract's URL.
+
+export const MAX_ARCHIVE_DOCUMENT_BYTES = 32 * 1024 * 1024;
+const MAX_REDIRECTS = 3;
+
+/** Whether `url` is on `origin`'s own scheme, host and port. */
+export function sameOrigin(url, origin) {
+ try {
+ return new URL(url).origin === new URL(origin).origin;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * A GET that stays on `url`'s origin. `fetchImpl(url, init)` is asked with
+ * `redirect: "manual"`; a 3xx with a Location is followed only on the same
+ * origin, at most three times, and one that leaves it throws before it is
+ * followed.
+ */
+export async function fetchOnOrigin(fetchImpl, url, init = {}) {
+ let at = url;
+ for (let hop = 0; ; hop += 1) {
+ const res = await fetchImpl(at, { ...init, redirect: "manual" });
+ const status = Number(res?.status);
+ if (!(status >= 300 && status <= 399) || status === 304) return res;
+ const location = res.headers?.get?.("location");
+ if (!location) return res;
+ const next = new URL(location, at).href;
+ if (!sameOrigin(next, url)) {
+ throw new Error(`GET ${at} redirects to ${new URL(next).origin}: an archive's documents are read from its own origin only`);
+ }
+ if (hop >= MAX_REDIRECTS) throw new Error(`GET ${url} redirects more than ${MAX_REDIRECTS} times`);
+ at = next;
+ }
+}
+
+/**
+ * A response's JSON, refused past `max` bytes: by its Content-Length first,
+ * then as the body streams. A response with no stream (a test's stub) is read
+ * as it offers itself, its text measured when it has one.
+ */
+export async function readJsonBounded(res, url, max = MAX_ARCHIVE_DOCUMENT_BYTES) {
+ const over = () => new Error(`GET ${url} is over ${Math.round(max / 1024 / 1024)} MB: an archive document that large is not read`);
+ const declared = Number(res.headers?.get?.("content-length"));
+ if (Number.isFinite(declared) && declared > max) {
+ await res.body?.cancel?.().catch(() => {});
+ throw over();
+ }
+ if (res.body && typeof res.body.getReader === "function") {
+ const reader = res.body.getReader();
+ const chunks = [];
+ let total = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > max) {
+ await reader.cancel().catch(() => {});
+ throw over();
+ }
+ chunks.push(value);
+ }
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
+ }
+ if (typeof res.text === "function") {
+ const text = await res.text();
+ if (Buffer.byteLength(text) > max) throw over();
+ return JSON.parse(text);
+ }
+ return res.json();
+}
+
+/**
+ * Where a channel's transcripts manifest is read: the URL its corpus.json
+ * entry names when that is on `origin` itself (a relative one is resolved
+ * against it), else the contract's `<origin>/transcripts/<slug>/manifest.json`
+ * — a manifest named on another origin is never followed.
+ */
+export function transcriptsManifestUrl(origin, entry) {
+ const base = new URL(origin).origin;
+ const contract = `${base}/transcripts/${encodeURIComponent(String(entry?.slug ?? ""))}/manifest.json`;
+ const named = entry?.manifests?.transcripts;
+ if (typeof named !== "string" || !named.trim()) return contract;
+ let resolved;
+ try {
+ resolved = new URL(named.trim(), `${base}/`);
+ } catch {
+ return contract;
+ }
+ if (resolved.origin !== base || resolved.username || resolved.password) return contract;
+ return resolved.href;
+}
diff --git a/umtool/report-to-video/attribution.mjs b/umtool/report-to-video/attribution.mjs
@@ -119,7 +119,9 @@ export function attributionLine(entry, meta, provenance = {}) {
// A cut with no channel to name anywhere reproduces the old line exactly,
// rather than opening on a stray separator.
const head = [channel, title].filter((s) => String(s ?? "").length > 0).join(" · ");
- return `${head} · ${date} @ ${hms(at)}`;
+ // An undated recording (a local recording with no recording date: its
+ // uploadDate is "") drops the date, not leaves an empty field between dots.
+ return String(date ?? "").length > 0 ? `${head} · ${date} @ ${hms(at)}` : `${head} @ ${hms(at)}`;
}
/**
diff --git a/umtool/report-to-video/attribution.test.mjs b/umtool/report-to-video/attribution.test.mjs
@@ -10,6 +10,7 @@ import test from "node:test";
import {
attributionLine,
+ attributionParts,
channelName,
cleanTitle,
hms,
@@ -131,3 +132,12 @@ test("isCalendarDate / uploadDateToIso", () => {
assert.equal(uploadDateToIso("20250101"), "2025-01-01");
assert.equal(uploadDateToIso("2025-01-01"), "2025-01-01");
});
+
+// lane/local-media: an undated local recording's uploadDate is "".
+test("attributionLine: an undated recording drops the date, not leaves an empty field", () => {
+ assert.equal(
+ attributionLine({ start: 62 }, { title: "Lesson one", uploadDate: "", channel: "Classroom" }),
+ "Classroom · Lesson one @ 1:02",
+ );
+ assert.equal(attributionParts({ start: 62 }, { title: "Lesson one", uploadDate: "" }).date, "");
+});
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -125,6 +125,7 @@
//
// Requires: yt-dlp, ffmpeg/ffprobe, ImageMagick with Pango.
+import { localRecordingFetchRefusal } from "./local-recording.mjs";
import { presetManifest } from "./presets.mjs";
// The basic output mode (render.mode "basic"): the footage alone, cut and spliced in basic.mjs.
import { renderBasic } from "./basic.mjs";
@@ -1365,6 +1366,8 @@ async function fetchClip(entry, meta, render, local, opts) {
// thing in a build, and the two cuts overlap almost entirely.
const name = rawWindowName(entry.video, from, to);
const dest = path.join(rawDir, name);
+ const localRefusal = localRecordingFetchRefusal(entry.video, meta.platform);
+ if (localRefusal) throw new Error(localRefusal);
if (opts.noNetwork) throw new Error(`--no-network set and no local source covers ${name}`);
if (opts.skipFetch) throw new Error(`--skip-fetch set and no cached window covers ${name}`);
diff --git a/umtool/report-to-video/cast.mjs b/umtool/report-to-video/cast.mjs
@@ -1,24 +1,52 @@
// THE CAST (operator, 6 Nov 2026: "I'd like to be able to pick different voices
// for different characters, and in UI alone be able to try rendering different
// ones to compare … and try to maintain consistent voices for different
-// repeating characters"): the CHARACTERS that recur across projects, each with
-// the stock voice it reads in, stored ONCE for every project
-// (`<REPORTS_ROOT>/.umtool/cast.json`, lib/report/castStore.mjs its one writer).
+// repeating characters"): the CHARACTERS that recur across projects, stored
+// ONCE for every project (`<REPORTS_ROOT>/.umtool/cast.json`,
+// lib/report/castStore.mjs its one writer).
//
-// { "format": "umtool-cast", "version": 1,
+// A CHARACTER IS A PRESET (operator, 11 Nov 2026: "a preset of voice and other
+// settings … different presets for synthetic and human-filtered voices"): two
+// of them, picked by how the read is made --
+//
+// { "format": "umtool-cast", "version": 2,
// "characters": [ { "id": "thequartering", "name": "TheQuartering",
// "handles": ["thequartering"], // X handles / channel slugs (no @, lower case)
-// "voice": "kokoro:am_michael", // <tts engine>:<stock voice>
-// "convert": { "engine": "seed-vc", "voice": "kokoro:am_michael" }, // a recording made his (optional)
+// "synthetic": { "voice": "kokoro:am_michael", // <tts engine>:<stock voice>
+// "speed": 1.1 }, // the tts op's speed, 0.5-2 (absent: 1)
+// "recorded": { // a RECORDING made his read
+// "convert": { "engine": "seed-vc", "voice": "kokoro:am_michael",
+// "pitch": "contour", "semitones": 2 }, // CAST_CONVERT_PITCH, the editor's voice-convert
+// "enhance": true, // cleaned first (DeepFilterNet); absent: yes
+// "trim": { "on": true, "padMs": 120 }, // its edges trimmed to speech, the room kept (absent: on, RECORD_ROOM)
+// "direction": "higher, brisk, amused" }, // one line for the PERSON reading -- never sent to a model
// "speakers": ["Jeremy"], // his REAL voice's name in a project's speakers.json
// "avatar": "…", "note": "…", "narrator": true } ] }
//
+// VERSION 1 kept the stock voice in `voice` and the convert entry in `convert`
+// at the character's top: those keys are READ AS THE PRESETS (upgradeCharacter:
+// `voice` is `synthetic.voice`, `convert` is `recorded.convert`), in a file of
+// either version, and the writer writes version 2. A
+// reader is handed a VIEW (charactersOf, characterView): the presets AND the
+// `voice` / `convert` they answer to, so what read version 1 reads version 2.
+//
+// A PROJECT's OWN CHARACTERS (`<project>/narration/characters.json`,
+// PROJECT_CHARACTERS_FORMAT; the same store) are the same shape, with no
+// narrator and with `anonymous: true` + `shown` ("Anon 1") for a person who
+// must not enter the pool: they live in that video only. (The shown name is
+// what umtool's own surfaces call them; the cut's card is not anonymised yet.)
+//
// A project's `narration/voices.json` (post-say.mjs) stays the project's
-// OVERRIDE LAYER. The voice a piece of a read is said in, in order: the read's
-// own override (--voice-for, --voice), the project's map, the CAST, the
-// narrator's (the item's own author), the map's "*", the engine's default --
-// post-say.mjs voiceForPiece, which every read goes through (a single post's
-// take, each piece of a thread read), so they agree.
+// OVERRIDE LAYER (a handle in it reads as a project character with only a
+// synthetic voice). The preset one read is made with, FIRST HIT WINS: the
+// command's flags (--voice-for, --voice, --speed, --as, --pitch …), the item's
+// own character (`narration.character`), the project's character for the
+// handle (characters.json, then voices.json), the CAST's, the narrator's (the
+// item's own author), the map's "*", the engine's default -- post-say.mjs
+// voiceSourceOf for a synthesized read (a single post's take, each piece of a
+// thread read: they agree), characterForRead below for a recording. A layer
+// answers for a preset it HAS: a project character with no synthetic voice
+// leaves the voice to the layers under it.
//
// A voice is ALWAYS a stock synthetic one (`<engine>:<voice>`): a character's
// REAL voice (`speakers`) is a reference to compare a candidate with
@@ -31,12 +59,43 @@ import { CONTEXT_VOICE_DEFAULTS, TTS_ENGINE_IDS, handleKey, voiceRefOf, voiceSpe
export { voiceRefOf, voiceSpecOf };
export const CAST_FORMAT = "umtool-cast";
-export const CAST_VERSION = 1;
+export const CAST_VERSION = 2;
+/** The versions a reader takes (1: `voice` / `convert` at the character's top). */
+export const CAST_VERSIONS_READ = Object.freeze([1, 2]);
export const CAST_MAX = 300;
-export const CAST_KEYS = Object.freeze(["id", "name", "handles", "voice", "convert", "speakers", "avatar", "note", "narrator"]);
+export const CAST_KEYS = Object.freeze(["id", "name", "handles", "synthetic", "recorded", "speakers", "avatar", "note", "narrator"]);
+/** Version 1's keys, read as the presets (upgradeCharacter). */
+export const CAST_LEGACY_KEYS = Object.freeze(["voice", "convert"]);
+/** A character's two presets: how a SYNTHESIZED read is made, and how a RECORDED one is. */
+export const SYNTHETIC_KEYS = Object.freeze(["voice", "speed"]);
+export const RECORDED_KEYS = Object.freeze(["convert", "enhance", "trim", "direction"]);
+export const TRIM_KEYS = Object.freeze(["on", "padMs"]);
+/** The tts op's speed (the editor's: 0.5-2), the room a trim may keep, a direction's length. */
+export const CAST_SPEED = Object.freeze([0.5, 2]);
+export const TRIM_PAD_MAX_MS = 2000;
+export const DIRECTION_MAX = 200;
+
+/** A project's own characters: the file (relative to the project's folder), its format, its extra keys. */
+export const PROJECT_CHARACTERS_FILE = "narration/characters.json";
+export const PROJECT_CHARACTERS_FORMAT = "umtool-project-characters";
+export const PROJECT_CHARACTERS_VERSION = 1;
+export const PROJECT_CHARACTER_KEYS = Object.freeze([...CAST_KEYS.filter((k) => k !== "narrator"), "anonymous", "shown"]);
+/**
+ * The name an anonymous character is shown under when none is given: "Anon 1", "Anon 2" … (`{n}` the first number
+ * the project does not use). THE ONE PLACE the pattern is written.
+ */
+export const ANON_NAME_PATTERN = "Anon {n}";
/** The tts engines a cast voice may name (the editor's tts op), and the convert engines (its voice-convert op). */
export const CAST_TTS_ENGINES = TTS_ENGINE_IDS;
export const CAST_CONVERT_ENGINES = Object.freeze(["openvoice", "seed-vc"]);
+/**
+ * The pitch a converted read lands on (the editor's voice-convert, common/lib/voiceApps.ts VoicePitch): the stock
+ * voice's own (`target`), the pitch it was read at (`source`), or the read's rises and falls at the stock voice's
+ * register (`contour`); `semitones` moves a followed one. The engines that can follow a pitch.
+ */
+export const CAST_CONVERT_PITCH = Object.freeze(["target", "source", "contour"]);
+export const CAST_PITCH_ENGINES = Object.freeze(["seed-vc"]);
+export const CAST_SEMITONES_MAX = 12;
/** Which engine is heavy to run (the operator's rule: Orpheus pins ~8.5 GB; Kokoro first). */
export const ENGINE_WEIGHT = Object.freeze({ kokoro: "fast", "espeak-ng": "fast", orpheus: "heavy" });
@@ -51,57 +110,201 @@ export const isQualifiedVoice = (spec) => !!voiceRefOf(spec) && str(spec).includ
/** The empty cast. */
export const emptyCast = () => ({ format: CAST_FORMAT, version: CAST_VERSION, characters: [] });
+/** A project with no characters of its own. */
+export const emptyProjectCharacters = () => ({ format: PROJECT_CHARACTERS_FORMAT, version: PROJECT_CHARACTERS_VERSION, characters: [] });
-/** Every reason a cast document is refused (empty: it is fine). */
-export function validateCast(doc, where = "cast.json") {
- if (!isObj(doc)) return [`${where} must be {"format": "${CAST_FORMAT}", "version": ${CAST_VERSION}, "characters": [...]}`];
+const KEY_ORDER = ["id", "name", "anonymous", "shown", "handles", "synthetic", "recorded", "speakers", "avatar", "note", "narrator"];
+
+/**
+ * A character as VERSION 2 holds it, from either version (pure, a copy): `voice` read as `synthetic.voice`, `convert`
+ * as `recorded.convert`, and the keys in one order. Where a preset says the key too, THE PRESET WINS: a top-level
+ * `voice` / `convert` beside it is a view's alias (characterView), which may be stale -- a view whose
+ * `synthetic.voice` was changed folds to the new value. (A writer's mutation that SETS `c.voice` the old way is told
+ * apart by what the character was before: foldWritten.) Anything else is left as it is (validateCast says what is wrong).
+ */
+export function upgradeCharacter(c) {
+ if (!isObj(c)) return c;
+ const { voice, convert, synthetic, recorded, ...rest } = c;
+ const syn = synthetic !== undefined && !isObj(synthetic) ? synthetic : { ...(voice !== undefined ? { voice } : {}), ...(synthetic ?? {}) };
+ const rec = recorded !== undefined && !isObj(recorded) ? recorded : { ...(convert !== undefined ? { convert } : {}), ...(recorded ?? {}) };
+ const all = { ...rest, ...(!isObj(syn) || Object.keys(syn).length ? { synthetic: syn } : {}), ...(!isObj(rec) || Object.keys(rec).length ? { recorded: rec } : {}) };
+ const out = {};
+ for (const k of KEY_ORDER) if (k in all) out[k] = all[k];
+ for (const k of Object.keys(all)) if (!(k in out)) out[k] = all[k];
+ return out;
+}
+
+/**
+ * A character AS A WRITE LEAVES IT, folded to version 2 (pure): `c` what the mutation left, `before` the character it
+ * was handed (version 2's, no aliases; null: a new one). A top-level `voice` / `convert` on it was put there by the
+ * mutation -- the old way of setting one (`c.voice = …`) -- and is the newer word WHEN THE PRESET IS AS IT WAS; a
+ * preset the mutation changed itself wins (the top-level key is then a stale alias: a view written back).
+ */
+export function foldWritten(c, before = null) {
+ if (!isObj(c)) return c;
+ const out = { ...c };
+ const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
+ if (out.voice !== undefined && isObj(out.synthetic) && out.synthetic.voice !== undefined && before && same(before.synthetic?.voice, out.synthetic.voice)) out.synthetic = { ...out.synthetic, voice: out.voice };
+ if (out.convert !== undefined && isObj(out.recorded) && out.recorded.convert !== undefined && before && same(before.recorded?.convert, out.recorded.convert)) out.recorded = { ...out.recorded, convert: out.convert };
+ return upgradeCharacter(out);
+}
+
+/** A cast document as version 2 holds it (upgradeCharacter each); a document that is not one is returned as it is. */
+export function upgradeCast(doc) {
+ if (!isObj(doc) || !Array.isArray(doc.characters) || doc.format !== CAST_FORMAT || !CAST_VERSIONS_READ.includes(doc.version)) return doc;
+ return { ...doc, version: CAST_VERSION, characters: doc.characters.map(upgradeCharacter) };
+}
+
+/** A character's stock voice (`synthetic.voice`; version 1's `voice`), its speed, its convert entry -- of either shape. */
+export const characterVoice = (c) => (isObj(c?.synthetic) && c.synthetic.voice !== undefined ? c.synthetic.voice : c?.voice) ?? null;
+export const characterSpeed = (c) => (isObj(c?.synthetic) && typeof c.synthetic.speed === "number" ? c.synthetic.speed : null);
+export const characterConvert = (c) => (isObj(c?.recorded) && c.recorded.convert !== undefined ? c.recorded.convert : c?.convert);
+
+/**
+ * A character as a READER is handed it: version 2's shape, AND the `voice` / `convert` its presets answer to (what
+ * version 1's readers ask). Never written: the writer's characters are upgradeCharacter's.
+ */
+export function characterView(c) {
+ if (!isObj(c)) return c;
+ const u = upgradeCharacter(c);
+ const voice = characterVoice(u);
+ const convert = characterConvert(u);
+ return { ...u, ...(voice !== null ? { voice } : {}), ...(convert !== undefined ? { convert } : {}) };
+}
+
+/** What is wrong with a convert entry (`{engine?, voice?, pitch?, semitones?}`), as sentences that start at `w`. */
+function convertErrors(cv, w) {
+ if (!isObj(cv) || Object.keys(cv).some((k) => !["engine", "voice", "pitch", "semitones"].includes(k))) return [`${w} must be {engine?, voice?, pitch?, semitones?}`];
+ const errors = convertPitchErrors(cv).map((m) => `${w}.${m}`);
+ if (cv.engine !== undefined && !CAST_CONVERT_ENGINES.includes(cv.engine)) errors.push(`${w}.engine must be one of ${CAST_CONVERT_ENGINES.join(", ")}`);
+ if (cv.voice !== undefined && !isQualifiedVoice(cv.voice)) errors.push(`${w}.voice must be a STOCK voice, "<engine>:<voice>" (never a file or a recording)`);
+ return errors;
+}
+
+/**
+ * What is wrong with ONE character (upgraded: upgradeCharacter), as sentences that start at `w`. `layer` "cast" (a
+ * stock voice is required; it may be the narrator) or "project" (a preset is optional -- the layers under it answer
+ * -- and it may be `anonymous`, with the name it is `shown` under). Both layers refuse a voice, or a convert target,
+ * that is not a STOCK synthetic one.
+ */
+export function characterErrors(c, w, { layer = "cast" } = {}) {
+ const keys = layer === "project" ? PROJECT_CHARACTER_KEYS : CAST_KEYS;
+ if (!isObj(c)) return [`${w} must be {id, name, handles, synthetic, …}`];
+ const errors = [];
+ for (const k of Object.keys(c)) if (!keys.includes(k)) errors.push(`${w}.${k} is not a character key (${keys.join(", ")})`);
+ if (!CHARACTER_ID_RE.test(str(c.id))) errors.push(`${w}.id must be lower case letters, digits, - and _ (got ${JSON.stringify(c.id)})`);
+ if (!str(c.name).trim() || str(c.name).length > 80) errors.push(`${w}.name must be 1-80 characters`);
+ if (!Array.isArray(c.handles ?? [])) errors.push(`${w}.handles must be a list of handles`);
+ else {
+ if ((c.handles ?? []).length > 20) errors.push(`${w}.handles: at most 20`);
+ for (const h of c.handles ?? []) if (typeof h !== "string" || !HANDLE_RE.test(h) || h !== handleKey(h)) errors.push(`${w}.handles: "${h}" is not a handle as the cast keys it (lower case, no @)`);
+ }
+ const syn = c.synthetic;
+ if (syn === undefined) {
+ if (layer === "cast") errors.push(`${w}.voice must be a STOCK voice with its engine, "<${CAST_TTS_ENGINES.join("|")}>:<voice>" (got ${JSON.stringify(undefined)})`);
+ } else if (!isObj(syn) || Object.keys(syn).some((k) => !SYNTHETIC_KEYS.includes(k))) errors.push(`${w}.synthetic must be {voice, speed?}`);
+ else {
+ if (!isQualifiedVoice(syn.voice)) errors.push(`${w}.voice must be a STOCK voice with its engine, "<${CAST_TTS_ENGINES.join("|")}>:<voice>" (got ${JSON.stringify(syn.voice)})`);
+ if (syn.speed !== undefined && !(typeof syn.speed === "number" && Number.isFinite(syn.speed) && syn.speed >= CAST_SPEED[0] && syn.speed <= CAST_SPEED[1])) errors.push(`${w}.synthetic.speed must be a number from ${CAST_SPEED[0]} to ${CAST_SPEED[1]}`);
+ }
+ const rec = c.recorded;
+ if (rec !== undefined) {
+ if (!isObj(rec) || Object.keys(rec).some((k) => !RECORDED_KEYS.includes(k))) errors.push(`${w}.recorded must be {convert?, enhance?, trim?, direction?}`);
+ else {
+ if (rec.convert !== undefined) errors.push(...convertErrors(rec.convert, `${w}.recorded.convert`));
+ if (rec.enhance !== undefined && typeof rec.enhance !== "boolean") errors.push(`${w}.recorded.enhance must be true or false`);
+ if (rec.trim !== undefined) {
+ const t = rec.trim;
+ if (!isObj(t) || Object.keys(t).some((k) => !TRIM_KEYS.includes(k)) || (t.on !== undefined && typeof t.on !== "boolean")) errors.push(`${w}.recorded.trim must be {on?: true | false, padMs?}`);
+ else if (t.padMs !== undefined && !(typeof t.padMs === "number" && Number.isFinite(t.padMs) && t.padMs >= 0 && t.padMs <= TRIM_PAD_MAX_MS)) errors.push(`${w}.recorded.trim.padMs must be a number of milliseconds from 0 to ${TRIM_PAD_MAX_MS}`);
+ }
+ if (rec.direction !== undefined && (typeof rec.direction !== "string" || !rec.direction.trim() || rec.direction.length > DIRECTION_MAX || /[\r\n]/.test(rec.direction))) errors.push(`${w}.recorded.direction must be one line for the person reading (at most ${DIRECTION_MAX} characters)`);
+ }
+ }
+ if (c.speakers !== undefined && !(Array.isArray(c.speakers) && c.speakers.length <= 10 && c.speakers.every((s) => typeof s === "string" && SPEAKER_RE.test(s)))) errors.push(`${w}.speakers must be the names his real voice goes by in a project's speakers.json (at most 10)`);
+ for (const k of ["avatar", "note"]) if (c[k] !== undefined && (typeof c[k] !== "string" || c[k].length > 500)) errors.push(`${w}.${k} must be a string (at most 500)`);
+ if (c.narrator !== undefined && c.narrator !== true) errors.push(`${w}.narrator must be true or absent`);
+ if (layer === "project") {
+ if (c.anonymous !== undefined && c.anonymous !== true) errors.push(`${w}.anonymous must be true or absent`);
+ if (c.shown !== undefined && (typeof c.shown !== "string" || !c.shown.trim() || c.shown.length > 80)) errors.push(`${w}.shown must be the name it is shown under (1-80 characters)`);
+ if (c.shown !== undefined && c.anonymous !== true) errors.push(`${w}.shown is an anonymous character's shown name (anonymous: true)`);
+ }
+ return errors;
+}
+
+/** A list of characters refused: each one's reasons, an id twice, a handle two characters hold. */
+function listErrors(list, where, layer) {
const errors = [];
- if (doc.format !== CAST_FORMAT) errors.push(`${where}: format must be "${CAST_FORMAT}"`);
- if (doc.version !== CAST_VERSION) errors.push(`${where}: version must be ${CAST_VERSION}`);
- const list = doc.characters;
- if (!Array.isArray(list)) return [...errors, `${where}.characters must be a list`];
- if (list.length > CAST_MAX) errors.push(`${where}: at most ${CAST_MAX} characters`);
const ids = new Set();
const owner = new Map();
- let narrators = 0;
- list.forEach((c, i) => {
+ list.forEach((c0, i) => {
const w = `${where}.characters[${i}]`;
- if (!isObj(c)) return errors.push(`${w} must be {id, name, handles, voice, …}`);
- for (const k of Object.keys(c)) if (!CAST_KEYS.includes(k)) errors.push(`${w}.${k} is not a character key (${CAST_KEYS.join(", ")})`);
- if (!CHARACTER_ID_RE.test(str(c.id))) errors.push(`${w}.id must be lower case letters, digits, - and _ (got ${JSON.stringify(c.id)})`);
- else if (ids.has(c.id)) errors.push(`${w}: two characters are "${c.id}"`);
- ids.add(c.id);
- if (!str(c.name).trim() || str(c.name).length > 80) errors.push(`${w}.name must be 1-80 characters`);
- if (!Array.isArray(c.handles ?? [])) errors.push(`${w}.handles must be a list of handles`);
- else {
- if ((c.handles ?? []).length > 20) errors.push(`${w}.handles: at most 20`);
- for (const h of c.handles ?? []) {
- if (typeof h !== "string" || !HANDLE_RE.test(h) || h !== handleKey(h)) errors.push(`${w}.handles: "${h}" is not a handle as the cast keys it (lower case, no @)`);
- else if (owner.has(h) && owner.get(h) !== c.id) errors.push(`${w}.handles: @${h} is ${owner.get(h)}'s already (a handle is one character's)`);
- else owner.set(h, c.id);
- }
+ const c = upgradeCharacter(c0);
+ errors.push(...characterErrors(c, w, { layer }));
+ if (!isObj(c)) return;
+ if (CHARACTER_ID_RE.test(str(c.id))) {
+ if (ids.has(c.id)) errors.push(`${w}: two characters are "${c.id}"`);
+ ids.add(c.id);
}
- if (!isQualifiedVoice(c.voice)) errors.push(`${w}.voice must be a STOCK voice with its engine, "<${CAST_TTS_ENGINES.join("|")}>:<voice>" (got ${JSON.stringify(c.voice)})`);
- if (c.convert !== undefined) {
- const cv = c.convert;
- if (!isObj(cv) || Object.keys(cv).some((k) => !["engine", "voice"].includes(k))) errors.push(`${w}.convert must be {engine?, voice?}`);
- else {
- if (cv.engine !== undefined && !CAST_CONVERT_ENGINES.includes(cv.engine)) errors.push(`${w}.convert.engine must be one of ${CAST_CONVERT_ENGINES.join(", ")}`);
- if (cv.voice !== undefined && !isQualifiedVoice(cv.voice)) errors.push(`${w}.convert.voice must be a STOCK voice, "<engine>:<voice>" (never a file or a recording)`);
- }
+ for (const h of Array.isArray(c.handles) ? c.handles : []) {
+ if (typeof h !== "string" || h !== handleKey(h)) continue;
+ if (owner.has(h) && owner.get(h) !== c.id) errors.push(`${w}.handles: @${h} is ${owner.get(h)}'s already (a handle is one character's)`);
+ else owner.set(h, c.id);
}
- if (c.speakers !== undefined && !(Array.isArray(c.speakers) && c.speakers.length <= 10 && c.speakers.every((s) => typeof s === "string" && SPEAKER_RE.test(s)))) errors.push(`${w}.speakers must be the names his real voice goes by in a project's speakers.json (at most 10)`);
- for (const k of ["avatar", "note"]) if (c[k] !== undefined && (typeof c[k] !== "string" || c[k].length > 500)) errors.push(`${w}.${k} must be a string (at most 500)`);
- if (c.narrator !== undefined && c.narrator !== true) errors.push(`${w}.narrator must be true or absent`);
- if (c.narrator === true) narrators += 1;
});
- if (narrators > 1) errors.push(`${where}: one character at most is the narrator`);
return errors;
}
-/** The cast's characters (the invalid ones dropped, never fatal for a reader). */
+/** Every reason a cast document is refused (empty: it is fine). A version 1 document is read as version 2. */
+export function validateCast(doc, where = "cast.json") {
+ if (!isObj(doc)) return [`${where} must be {"format": "${CAST_FORMAT}", "version": ${CAST_VERSION}, "characters": [...]}`];
+ const errors = [];
+ if (doc.format !== CAST_FORMAT) errors.push(`${where}: format must be "${CAST_FORMAT}"`);
+ if (!CAST_VERSIONS_READ.includes(doc.version)) errors.push(`${where}: version must be ${CAST_VERSION} (or ${CAST_VERSIONS_READ.filter((v) => v !== CAST_VERSION).join(", ")}, read as it)`);
+ const list = doc.characters;
+ if (!Array.isArray(list)) return [...errors, `${where}.characters must be a list`];
+ if (list.length > CAST_MAX) errors.push(`${where}: at most ${CAST_MAX} characters`);
+ errors.push(...listErrors(list, where, "cast"));
+ if (list.filter((c) => isObj(c) && c.narrator === true).length > 1) errors.push(`${where}: one character at most is the narrator`);
+ return errors;
+}
+
+/** Every reason a project's characters document is refused (empty: it is fine). */
+export function validateProjectCharacters(doc, where = "characters.json") {
+ 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}"`);
+ if (doc.version !== PROJECT_CHARACTERS_VERSION) errors.push(`${where}: version must be ${PROJECT_CHARACTERS_VERSION}`);
+ const list = doc.characters;
+ if (!Array.isArray(list)) return [...errors, `${where}.characters must be a list`];
+ if (list.length > CAST_MAX) errors.push(`${where}: at most ${CAST_MAX} characters`);
+ errors.push(...listErrors(list, where, "project"));
+ return errors;
+}
+
+/** The cast's characters, as views (characterView) -- the invalid ones dropped, never fatal for a reader. */
export function charactersOf(cast) {
- return (Array.isArray(cast?.characters) ? cast.characters : []).filter((c) => isObj(c) && CHARACTER_ID_RE.test(str(c.id)) && isQualifiedVoice(c.voice));
+ return (Array.isArray(cast?.characters) ? cast.characters : []).filter((c) => isObj(c) && CHARACTER_ID_RE.test(str(c.id)) && isQualifiedVoice(characterVoice(c))).map(characterView);
+}
+
+/** A project's own characters, as views -- one needs an id and a name; its presets are optional. */
+export function projectCharactersOf(doc) {
+ return (Array.isArray(doc?.characters) ? doc.characters : []).filter((c) => isObj(c) && CHARACTER_ID_RE.test(str(c.id)) && str(c.name).trim()).map(characterView);
+}
+
+/**
+ * The name a character goes by where umtool names it (the Voices page, `umtool cast project`, a recording's note): an
+ * anonymous one's `shown` name, never its own. The cut's on-screen card does NOT ask this yet: it shows the post's author.
+ */
+export const shownNameOf = (c) => (c?.anonymous === true ? str(c.shown).trim() || ANON_NAME_PATTERN.replace("{n}", "1") : str(c?.name));
+
+/** 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()]));
+ for (let n = 1; ; n += 1) {
+ const name = ANON_NAME_PATTERN.replace("{n}", String(n));
+ if (!used.has(name.toLowerCase())) return name;
+ }
}
/** The character a handle belongs to, or null. */
@@ -130,9 +333,137 @@ export function castVoiceMap(cast) {
return out;
}
-/** A character's convert target -- what a recording is made into: its convert voice, else its voice. */
+/** A character's SYNTHETIC preset as a layer's entry (post-say.mjs voiceSourceOf): `{ voice, speed?, character }`, or null when it has no stock voice. */
+export function presetEntryOf(c) {
+ const voice = characterVoice(c);
+ if (!isQualifiedVoice(voice)) return null;
+ const speed = characterSpeed(c);
+ return { voice, ...(speed !== null && speed !== 1 ? { speed } : {}), character: c.id };
+}
+
+/** The cast as a preset layer: `{ "<handle>": { voice, speed?, character } }` -- castVoiceMap with each character's speed and id. */
+export function castPresetMap(cast) {
+ const out = {};
+ for (const c of charactersOf(cast)) for (const h of c.handles ?? []) out[h] = presetEntryOf(c);
+ return out;
+}
+
+/**
+ * THE PROJECT's LAYER, pure: its voice map (`narration/voices.json`: a handle in it reads as a project character with
+ * only a synthetic voice; "*" kept) under its own characters (`narration/characters.json`: each handle of one that
+ * HAS a synthetic voice) -- `{ "<handle>": "<voice>" | { voice, speed?, character } }`, voiceSourceOf's `map`.
+ */
+export function projectPresetMap(doc, voiceMap = {}) {
+ const out = { ...(isObj(voiceMap) ? voiceMap : {}) };
+ for (const c of projectCharactersOf(doc)) {
+ const entry = presetEntryOf(c);
+ if (entry) for (const h of c.handles ?? []) out[h] = entry;
+ }
+ return out;
+}
+
+/** The character an id names, the project's own first: `{ character, layer: "project" | "cast" }`, or null. */
+export function characterById(id, { project = null, cast = null } = {}) {
+ const k = str(id).trim().toLowerCase();
+ if (!k) return null;
+ const p = projectCharactersOf(project).find((c) => c.id === k);
+ if (p) return { character: p, layer: "project" };
+ const c = charactersOf(cast).find((x) => x.id === k);
+ return c ? { character: c, layer: "cast" } : null;
+}
+
+/** The character a post item names for its own read (`narration.character`): `{ id, character, layer }` (character null: no such one), or null. */
+export function itemCharacterOf(e, layers = {}) {
+ const id = str(e?.narration?.character).trim();
+ if (!id) return null;
+ const hit = characterById(id, layers);
+ return { id, character: hit?.character ?? null, layer: hit?.layer ?? null };
+}
+
+/** The item's own character as a layer's entry (voiceSourceOf's `item`), or null: none named, no such one, or one with no synthetic voice. */
+export function itemPresetOf(e, layers = {}) {
+ const it = itemCharacterOf(e, layers);
+ return it?.character ? presetEntryOf(it.character) : null;
+}
+
+/** Can a character be a RECORDED read's (it has a recorded preset, or a stock voice to convert to)? */
+const readsRecorded = (c) => !!c && (isObj(c.recorded) || isQualifiedVoice(characterVoice(c)));
+
+/**
+ * THE CHARACTER A RECORDING OF POST ITEM `e` IS MADE INTO, pure -- the chain a synthesized read asks, for the
+ * recorded preset: `as` (the command's --as: an id, a handle or a name, the project's own first), the item's own
+ * character, the project's character for its author, the cast's, the cast's narrator. `{ character, layer: "flag" |
+ * "item" | "project" | "cast" | "narrator" }`, or null: no one to convert to. `as` that names no one is `{ character:
+ * null, layer: "flag" }`.
+ */
+export function characterForRead(e, { project = null, cast = null, as = null } = {}) {
+ const pchars = projectCharactersOf(project);
+ if (str(as).trim()) {
+ const r = str(as).trim().replace(/^@+/, "");
+ const low = r.toLowerCase();
+ const p = pchars.find((c) => c.id === low) ?? (str(as).trim().startsWith("@") ? null : pchars.find((c) => str(c.name).toLowerCase() === low)) ?? pchars.find((c) => (c.handles ?? []).includes(handleKey(r)) && readsRecorded(c));
+ return { character: p ?? findCharacter(cast, r), layer: "flag" };
+ }
+ const it = itemCharacterOf(e, { project, cast });
+ if (readsRecorded(it?.character)) return { character: it.character, layer: "item" };
+ const h = handleKey(e?.handle);
+ const p = h ? pchars.find((c) => (c.handles ?? []).includes(h)) : null;
+ if (readsRecorded(p)) return { character: p, layer: "project" };
+ const c = characterOf(cast, h);
+ if (c) return { character: c, layer: "cast" };
+ const n = narratorOf(cast);
+ return n ? { character: n, layer: "narrator" } : null;
+}
+
+/**
+ * A character's RECORDED preset, its defaults filled: `{ convert: convertTargetOf, enhance (true unless it says
+ * false), trim: { on (true unless false), padMs (null: the recorder's own room) }, direction (null: none) }`.
+ */
+export function recordedPresetOf(c) {
+ const rec = isObj(c?.recorded) ? c.recorded : {};
+ return {
+ convert: convertTargetOf(c),
+ enhance: rec.enhance !== false,
+ trim: { on: rec.trim?.on !== false, padMs: typeof rec.trim?.padMs === "number" ? rec.trim.padMs : null },
+ direction: typeof rec.direction === "string" && rec.direction.trim() ? rec.direction.trim() : null,
+ };
+}
+
+/**
+ * What is wrong with a convert entry's pitch (`{engine?, pitch?, semitones?}`), as sentences that start at the key:
+ * the mode is one of CAST_CONVERT_PITCH, the semitones a number within CAST_SEMITONES_MAX, a followed pitch is an
+ * engine's that can follow one (CAST_PITCH_ENGINES; an entry with no engine takes the editor's default, which answers
+ * for itself), and semitones move a FOLLOWED pitch. The editor's op refuses the same things in its own words.
+ */
+export function convertPitchErrors(cv) {
+ const errors = [];
+ const { engine, pitch, semitones } = cv ?? {};
+ if (pitch !== undefined && !CAST_CONVERT_PITCH.includes(pitch)) errors.push(`pitch must be one of ${CAST_CONVERT_PITCH.join(", ")}`);
+ if (semitones !== undefined && !(typeof semitones === "number" && Number.isFinite(semitones) && Math.abs(semitones) <= CAST_SEMITONES_MAX)) errors.push(`semitones must be a number from -${CAST_SEMITONES_MAX} to ${CAST_SEMITONES_MAX}`);
+ if (errors.length) return errors;
+ const follows = pitch === "source" || pitch === "contour";
+ if (follows && engine !== undefined && !CAST_PITCH_ENGINES.includes(engine)) errors.push(`pitch "${pitch}" is ${CAST_PITCH_ENGINES.join(", ")}'s: ${engine} lands every read on the target's own pitch`);
+ if (semitones && !follows) errors.push(`semitones moves a followed pitch: it needs pitch source or contour`);
+ return errors;
+}
+
+/** How a convert entry's (or a step's) pitch is said: "contour +2 st", "source", "" for the target's own. */
+export function convertPitchLabel(cv) {
+ if (!cv?.pitch || cv.pitch === "target") return "";
+ const n = Number(cv.semitones) || 0;
+ return n ? `${cv.pitch} ${n > 0 ? "+" : "−"}${Math.abs(n)} st` : cv.pitch;
+}
+
+/**
+ * A character's convert target -- what a recording is made into: its convert voice, else its voice -- and, when the
+ * entry says one, the pitch the read lands on (`pitch`, `semitones`; absent: the editor's default).
+ */
export function convertTargetOf(c) {
- return { engine: c?.convert?.engine ?? null, voice: c?.convert?.voice ?? c?.voice ?? null };
+ const cv = characterConvert(c);
+ return {
+ engine: cv?.engine ?? null, voice: cv?.voice ?? characterVoice(c) ?? null,
+ ...(cv?.pitch !== undefined ? { pitch: cv.pitch } : {}), ...(cv?.semitones !== undefined ? { semitones: cv.semitones } : {}),
+ };
}
/** The names a character's real voice may go by in a project's speakers.json (lower case, no punctuation). */
diff --git a/umtool/report-to-video/cast.test.mjs b/umtool/report-to-video/cast.test.mjs
@@ -4,7 +4,7 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import {
- castDrift, castVoiceMap, characterOf, convertTargetOf, emptyCast, findCharacter, isQualifiedVoice, narratorOf, speakerFor, takeReads, validateCast, voiceDrift, voiceRefOf,
+ castDrift, castVoiceMap, characterOf, convertPitchLabel, convertTargetOf, emptyCast, findCharacter, isQualifiedVoice, narratorOf, speakerFor, takeReads, validateCast, voiceDrift, voiceRefOf,
} from "./cast.mjs";
import { resolvePieceVoice, validateVoiceMap, voiceForPiece, voiceOverridesOf, voiceSourceOf } from "./post-say.mjs";
@@ -34,6 +34,16 @@ test("validateCast: the shape, ids, one owner a handle, stock voices only, one n
assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, voice: "/tmp/jeremy.wav" }] }).some((e) => /STOCK voice with its engine/.test(e)));
assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, convert: { voice: "me.wav" } }] }).some((e) => /never a file/.test(e)));
assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, narrator: true }, S] }).some((e) => /one character at most is the narrator/.test(e)));
+ // The pitch a converted read lands on: a mode, semitones in range, and only what an engine can follow.
+ const conv = (convert) => validateCast({ ...emptyCast(), characters: [{ ...Q, convert }] });
+ assert.deepEqual(conv({ engine: "seed-vc", pitch: "contour", semitones: 2 }), []);
+ assert.deepEqual(conv({ pitch: "source" }), [], "no engine: the editor's default answers for itself");
+ assert.deepEqual(conv({ engine: "openvoice", pitch: "target" }), []);
+ assert.ok(conv({ pitch: "high" }).some((e) => /convert\.pitch must be one of target, source, contour/.test(e)));
+ assert.ok(conv({ pitch: "source", semitones: 13 }).some((e) => /convert\.semitones must be a number from -12 to 12/.test(e)));
+ assert.ok(conv({ engine: "openvoice", pitch: "contour" }).some((e) => /convert\.pitch "contour" is seed-vc's: openvoice lands every read on the target's own pitch/.test(e)));
+ assert.ok(conv({ engine: "seed-vc", semitones: 2 }).some((e) => /convert\.semitones moves a followed pitch/.test(e)));
+ assert.ok(conv({ engine: "seed-vc", speed: 2 }).some((e) => /convert must be \{engine\?, voice\?, pitch\?, semitones\?\}/.test(e)));
assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, handles: ["@TheQuartering"] }] }).some((e) => /lower case, no @/.test(e)));
assert.ok(validateCast({ ...emptyCast(), characters: [{ ...Q, extra: 1 }] }).some((e) => /extra is not a character key/.test(e)));
});
@@ -47,6 +57,8 @@ test("a character by handle, id or name; the narrator; a recording's target; the
assert.deepEqual(castVoiceMap(cast), { thequartering: "kokoro:am_michael", madamsavvy: "orpheus:tara" });
assert.deepEqual(convertTargetOf(S), { engine: "seed-vc", voice: "orpheus:tara" });
assert.deepEqual(convertTargetOf({ ...Q, convert: { voice: "kokoro:am_onyx" } }), { engine: null, voice: "kokoro:am_onyx" });
+ assert.deepEqual(convertTargetOf({ ...S, convert: { engine: "seed-vc", pitch: "contour", semitones: 2 } }), { engine: "seed-vc", voice: "orpheus:tara", pitch: "contour", semitones: 2 });
+ assert.deepEqual([convertPitchLabel(undefined), convertPitchLabel({ pitch: "target" }), convertPitchLabel({ pitch: "source" }), convertPitchLabel({ pitch: "contour", semitones: 2 }), convertPitchLabel({ pitch: "source", semitones: -1.5 })], ["", "", "source", "contour +2 st", "source −1.5 st"]);
const speakers = [{ name: "Jeremy" }, { name: "Melonie Mac" }];
assert.equal(speakerFor(Q, speakers)?.name, "Jeremy");
assert.equal(speakerFor({ id: "mm", name: "MelonieMac", handles: [] }, speakers)?.name, "Melonie Mac", "the name, its punctuation and case aside");
diff --git a/umtool/report-to-video/characters.test.mjs b/umtool/report-to-video/characters.test.mjs
@@ -0,0 +1,204 @@
+// A character is a preset (cast.mjs): version 1's `voice` / `convert` read as the synthetic and recorded presets and
+// back (a view), what each layer refuses, a project's own characters (anonymous ones, "Anon 1"), the chain one read
+// asks -- the command's flags, the item's own character, the project's, the cast's, the narrator's, the default
+// (post-say.mjs voiceSourceOf for a synthesized read; characterForRead for a recording) -- and the speed a part is
+// asked at.
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import {
+ ANON_NAME_PATTERN, CAST_VERSION, PROJECT_CHARACTERS_FILE, castPresetMap, castVoiceMap, characterById, characterForRead, characterView, charactersOf, convertTargetOf, emptyCast, foldWritten,
+ emptyProjectCharacters, itemCharacterOf, itemPresetOf, nextAnonName, projectCharactersOf, projectPresetMap, recordedPresetOf, shownNameOf, upgradeCast, upgradeCharacter, validateCast,
+ validateProjectCharacters,
+} from "./cast.mjs";
+import { readSpeedOf, resolvePieceVoice, voiceSourceOf } from "./post-say.mjs";
+
+// Version 1, as the files on disk are today.
+const V1 = {
+ format: "umtool-cast", version: 1,
+ characters: [
+ { id: "thequartering", name: "TheQuartering", handles: ["thequartering"], voice: "kokoro:am_michael", speakers: ["Jeremy"], note: "the host" },
+ { id: "savvy", name: "MadamSavvy", handles: ["madamsavvy"], voice: "orpheus:tara", convert: { engine: "seed-vc", pitch: "contour", semitones: 2 }, narrator: true },
+ ],
+};
+
+test("migration on read: version 1's voice and convert are the synthetic and recorded presets, the version bumps", () => {
+ assert.deepEqual(validateCast(V1), [], "a version 1 file is fine as it is");
+ const up = upgradeCast(V1);
+ assert.equal(up.version, CAST_VERSION);
+ assert.equal(CAST_VERSION, 2);
+ assert.deepEqual(up.characters[0], { id: "thequartering", name: "TheQuartering", handles: ["thequartering"], synthetic: { voice: "kokoro:am_michael" }, speakers: ["Jeremy"], note: "the host" });
+ assert.deepEqual(up.characters[1], { id: "savvy", name: "MadamSavvy", handles: ["madamsavvy"], synthetic: { voice: "orpheus:tara" }, recorded: { convert: { engine: "seed-vc", pitch: "contour", semitones: 2 } }, narrator: true });
+ assert.deepEqual(validateCast(up), []);
+ assert.deepEqual(upgradeCast(up), up, "upgrading version 2 changes nothing");
+ assert.equal(V1.characters[0].synthetic, undefined, "a copy: the document read is not touched");
+ // Not a cast, or a version nobody reads: left as it is, and refused in words.
+ assert.equal(upgradeCast({ format: "x", version: 1, characters: [] }).version, 1);
+ assert.match(validateCast({ ...V1, version: 3 })[0], /version must be 2 \(or 1, read as it\)/);
+});
+
+test("migration the other way: a reader is handed the presets AND the voice / convert they answer to", () => {
+ const v2 = upgradeCast(V1);
+ const views = charactersOf(v2);
+ assert.equal(views[0].voice, "kokoro:am_michael");
+ assert.deepEqual(views[0].synthetic, { voice: "kokoro:am_michael" });
+ assert.deepEqual(views[1].convert, { engine: "seed-vc", pitch: "contour", semitones: 2 });
+ assert.deepEqual(charactersOf(V1), views, "either version reads the same");
+ assert.deepEqual(castVoiceMap(V1), castVoiceMap(v2));
+ assert.deepEqual(convertTargetOf(V1.characters[1]), convertTargetOf(v2.characters[1]));
+ assert.deepEqual(convertTargetOf(v2.characters[1]), { engine: "seed-vc", voice: "orpheus:tara", pitch: "contour", semitones: 2 });
+ // A view written back is the same character: its `voice` says what its preset says.
+ assert.deepEqual(upgradeCharacter(views[1]), v2.characters[1]);
+ assert.deepEqual(characterView(views[1]), views[1]);
+ // A VIEW WHOSE PRESET WAS CHANGED folds to the new value: the preset wins over its own (now stale) alias.
+ const edited = { ...views[0], synthetic: { ...views[0].synthetic, voice: "kokoro:am_onyx", speed: 1.1 } };
+ assert.equal(edited.voice, "kokoro:am_michael", "the alias still says the old voice");
+ assert.deepEqual(upgradeCharacter(edited).synthetic, { voice: "kokoro:am_onyx", speed: 1.1 });
+ assert.equal(characterView(edited).voice, "kokoro:am_onyx", "and a view of it says the new one");
+ assert.deepEqual(upgradeCharacter({ ...views[1], recorded: { convert: { engine: "openvoice" } } }).recorded, { convert: { engine: "openvoice" } });
+ // A WRITE's mutation that sets `c.voice` the old way, on the character it was handed (no alias): the newer word.
+ const handed = v2.characters[0];
+ assert.deepEqual(foldWritten({ ...handed, voice: "kokoro:am_onyx" }, handed).synthetic, { voice: "kokoro:am_onyx" });
+ assert.deepEqual(foldWritten({ ...v2.characters[1], convert: { engine: "openvoice" } }, v2.characters[1]).recorded, { convert: { engine: "openvoice" } });
+ assert.deepEqual(foldWritten({ ...handed, synthetic: { voice: "kokoro:am_michael", speed: 1.1 }, voice: "kokoro:am_onyx" }, handed).synthetic, { voice: "kokoro:am_onyx", speed: 1.1 }, "its speed kept");
+ // …but a mutation that changed the preset itself wins over a stale alias beside it (a view written back).
+ assert.deepEqual(foldWritten(edited, handed).synthetic, { voice: "kokoro:am_onyx", speed: 1.1 });
+ assert.deepEqual(foldWritten({ id: "new", name: "New", handles: [], voice: "kokoro:am_echo" }, null).synthetic, { voice: "kokoro:am_echo" }, "a new character the old way");
+ assert.equal(foldWritten(handed, handed).voice, undefined, "no alias is written");
+});
+
+test("validation: the presets' shape, in the cast -- a voice and a convert target are STOCK voices, never a file", () => {
+ const one = (c) => validateCast({ ...emptyCast(), characters: [{ id: "q", name: "Q", handles: ["q"], synthetic: { voice: "kokoro:am_michael" }, ...c }] });
+ assert.deepEqual(one({}), []);
+ assert.deepEqual(one({ synthetic: { voice: "kokoro:am_michael", speed: 1.15 }, recorded: { convert: { engine: "seed-vc", voice: "kokoro:am_onyx", pitch: "source" }, enhance: false, trim: { on: true, padMs: 120 }, direction: "higher, brisk, amused" } }), []);
+ assert.ok(one({ synthetic: undefined }).some((e) => /voice must be a STOCK voice with its engine/.test(e)), "a cast character has a stock voice");
+ assert.ok(one({ synthetic: { voice: "/home/me/jeremy.wav" } }).some((e) => /STOCK voice with its engine/.test(e)));
+ assert.ok(one({ synthetic: { voice: "kokoro:am_michael", speed: 3 } }).some((e) => /synthetic\.speed must be a number from 0\.5 to 2/.test(e)));
+ assert.ok(one({ synthetic: { voice: "kokoro:am_michael", emotion: "on" } }).some((e) => /synthetic must be \{voice, speed\?\}/.test(e)));
+ assert.ok(one({ recorded: { convert: { voice: "me.wav" } } }).some((e) => /recorded\.convert\.voice must be a STOCK voice.*never a file or a recording/.test(e)));
+ assert.ok(one({ recorded: { convert: { voice: "seedvc:/home/me.wav" } } }).some((e) => /never a file or a recording/.test(e)));
+ assert.ok(one({ recorded: { convert: { engine: "openvoice", pitch: "contour" } } }).some((e) => /pitch "contour" is seed-vc's/.test(e)));
+ assert.ok(one({ recorded: { enhance: "yes" } }).some((e) => /recorded\.enhance must be true or false/.test(e)));
+ assert.ok(one({ recorded: { trim: { on: "off" } } }).some((e) => /recorded\.trim must be \{on\?: true \| false, padMs\?\}/.test(e)));
+ assert.ok(one({ recorded: { trim: { padMs: 5000 } } }).some((e) => /trim\.padMs must be a number of milliseconds from 0 to 2000/.test(e)));
+ assert.ok(one({ recorded: { direction: "two\nlines" } }).some((e) => /direction must be one line for the person reading/.test(e)));
+ assert.ok(one({ recorded: { direction: "x".repeat(201) } }).some((e) => /at most 200/.test(e)));
+ assert.ok(one({ recorded: { model: "x" } }).some((e) => /recorded must be \{convert\?, enhance\?, trim\?, direction\?\}/.test(e)));
+ assert.ok(one({ anonymous: true }).some((e) => /anonymous is not a character key/.test(e)), "an anonymous character is never the pool's");
+});
+
+test("a project's own characters: the same shape, a preset optional, anonymous ones under a shown name, no narrator", () => {
+ const doc = (chars) => ({ ...emptyProjectCharacters(), characters: chars });
+ assert.equal(PROJECT_CHARACTERS_FILE, "narration/characters.json");
+ assert.deepEqual(validateProjectCharacters(doc([])), []);
+ const anon = { id: "anon-1", name: "the reply guy", anonymous: true, shown: "Anon 1", handles: ["replyguy99"], synthetic: { voice: "kokoro:am_puck", speed: 0.9 } };
+ const bare = { id: "witness", name: "A witness", handles: ["w1"] };
+ assert.deepEqual(validateProjectCharacters(doc([anon, bare])), [], "a character with no preset leaves the voice to the layers under it");
+ assert.match(validateProjectCharacters({ format: "umtool-cast", version: 2, characters: [] })[0], /format must be "umtool-project-characters"/);
+ assert.ok(validateProjectCharacters(doc([{ ...anon, narrator: true }])).some((e) => /narrator is not a character key/.test(e)));
+ assert.ok(validateProjectCharacters(doc([{ ...bare, shown: "Anon 2" }])).some((e) => /shown is an anonymous character's shown name/.test(e)));
+ assert.ok(validateProjectCharacters(doc([{ ...anon, anonymous: false }])).some((e) => /anonymous must be true or absent/.test(e)));
+ assert.ok(validateProjectCharacters(doc([anon, { ...bare, handles: ["replyguy99"] }])).some((e) => /@replyguy99 is anon-1's already/.test(e)));
+ assert.ok(validateProjectCharacters(doc([anon, { ...bare, id: "anon-1" }])).some((e) => /two characters are "anon-1"/.test(e)));
+ // Both layers refuse a convert target that is not a stock synthetic voice.
+ assert.ok(validateProjectCharacters(doc([{ ...bare, recorded: { convert: { voice: "narration/me.wav" } } }])).some((e) => /never a file or a recording/.test(e)));
+ assert.ok(validateProjectCharacters(doc([{ ...bare, synthetic: { voice: "operator" } }])).some((e) => /STOCK voice with its engine/.test(e)));
+ // The shown name: an anonymous character's, never its own; the next unused one of the pattern.
+ assert.equal(ANON_NAME_PATTERN, "Anon {n}");
+ assert.equal(shownNameOf(anon), "Anon 1");
+ assert.equal(shownNameOf(bare), "A witness");
+ assert.equal(nextAnonName([]), "Anon 1");
+ assert.equal(nextAnonName([anon, bare]), "Anon 2");
+ assert.equal(nextAnonName([anon, { id: "b", name: "x", anonymous: true, shown: "anon 2" }]), "Anon 3", "any case");
+ assert.deepEqual(projectCharactersOf(doc([anon, bare])).map((c) => [c.id, c.voice ?? null]), [["anon-1", "kokoro:am_puck"], ["witness", null]]);
+});
+
+// The layers of one project: the cast (V1), the project's own characters, its voice map.
+const cast = upgradeCast(V1);
+const own = {
+ ...emptyProjectCharacters(),
+ characters: [
+ { id: "anon-1", name: "the reply guy", anonymous: true, shown: "Anon 1", handles: ["replyguy99"], synthetic: { voice: "kokoro:am_puck", speed: 0.9 }, recorded: { enhance: false, direction: "flat, tired" } },
+ { id: "savvy-here", name: "Savvy, this video", handles: ["madamsavvy"], synthetic: { voice: "kokoro:af_bella", speed: 1.2 } },
+ { id: "witness", name: "A witness", handles: ["thequartering"] },
+ { id: "guest-star", name: "Guest star", handles: [], synthetic: { voice: "kokoro:bm_george", speed: 1.1 }, recorded: { convert: { voice: "kokoro:bm_lewis" }, trim: { on: false } } },
+ ],
+};
+const voiceMap = { madamsavvy: "leah", someone: "dan", "*": "zoe" };
+
+test("the layers as voiceSourceOf takes them: the project's characters over its voice map, the cast with its speeds", () => {
+ const map = projectPresetMap(own, voiceMap);
+ assert.deepEqual(map, {
+ madamsavvy: { voice: "kokoro:af_bella", speed: 1.2, character: "savvy-here" }, someone: "dan", "*": "zoe",
+ replyguy99: { voice: "kokoro:am_puck", speed: 0.9, character: "anon-1" },
+ }, "a character with a voice wins its handle; one with none (witness) leaves it; voices.json is kept for the rest");
+ assert.deepEqual(projectPresetMap(null, voiceMap), voiceMap, "no characters.json: the voice map as it is");
+ assert.deepEqual(castPresetMap(cast), { thequartering: { voice: "kokoro:am_michael", character: "thequartering" }, madamsavvy: { voice: "orpheus:tara", character: "savvy" } });
+ assert.deepEqual(characterById("savvy", { project: own, cast })?.layer, "cast");
+ assert.deepEqual(characterById("anon-1", { project: own, cast })?.layer, "project");
+ assert.equal(characterById("nobody", { project: own, cast }), null);
+});
+
+test("the chain for a synthesized read, first hit wins: flags, the item's character, the project's, the cast's, the narrator's, the default", () => {
+ const e = { id: "p-1", handle: "MadamSavvy", narration: { character: "guest-star" } };
+ const layers = { project: own, cast };
+ const full = { map: projectPresetMap(own, voiceMap), cast: castPresetMap(cast), item: itemPresetOf(e, layers), self: e.handle, narrator: "zac", engine: "orpheus" };
+ const her = { handle: "MadamSavvy", role: "post" };
+ // 1. the command's flags.
+ assert.deepEqual(voiceSourceOf(her, { ...full, overrides: { madamsavvy: "leo" }, voice: "dan" }), { spec: "leo", from: "override" });
+ assert.deepEqual(voiceSourceOf(her, { ...full, voice: "dan" }), { spec: "dan", from: "override" });
+ // 2. the item's own character.
+ assert.deepEqual(voiceSourceOf(her, full), { spec: "kokoro:bm_george", from: "item", speed: 1.1, character: "guest-star" });
+ assert.deepEqual(resolvePieceVoice(her, full), { engine: "kokoro", voice: "bm_george", from: "item", speed: 1.1, character: "guest-star" });
+ // 3. the project's character for the handle -- over its own voice map, which is next.
+ assert.deepEqual(voiceSourceOf(her, { ...full, item: null }), { spec: "kokoro:af_bella", from: "project", speed: 1.2, character: "savvy-here" });
+ assert.deepEqual(voiceSourceOf(her, { ...full, item: null, map: voiceMap }), { spec: "leah", from: "project" }, "voices.json alone: a project character with only a synthetic voice");
+ // 4. the cast's.
+ assert.deepEqual(voiceSourceOf(her, { ...full, item: null, map: {} }), { spec: "orpheus:tara", from: "cast", character: "savvy" });
+ // 5. the narrator's (the item's own author), 6. the map's "*", the default.
+ assert.deepEqual(voiceSourceOf(her, { ...full, item: null, map: {}, cast: {} }), { spec: "zac", from: "narrator" });
+ assert.deepEqual(voiceSourceOf({ handle: "stranger", role: "parent:0" }, full), { spec: "zoe", from: "project" });
+ assert.deepEqual(voiceSourceOf({ handle: "stranger", role: "parent:0" }, { ...full, map: {} }), { spec: "leo", from: "default" });
+ // The item's character is its OWN words' -- another author's piece of the same read asks its own layers.
+ assert.deepEqual(voiceSourceOf({ handle: "replyguy99", role: "parent:0" }, full), { spec: "kokoro:am_puck", from: "project", speed: 0.9, character: "anon-1" });
+ assert.deepEqual(voiceSourceOf({ handle: "TheQuartering", role: "quoted" }, full), { spec: "kokoro:am_michael", from: "cast", character: "thequartering" }, "a project character with no voice leaves it to the cast");
+ // An item naming a character nobody has, or one with no voice: the layers under it.
+ assert.deepEqual(itemCharacterOf({ narration: { character: "ghost" } }, layers), { id: "ghost", character: null, layer: null });
+ assert.equal(itemPresetOf({ narration: { character: "ghost" } }, layers), null);
+ assert.equal(itemPresetOf({ narration: { character: "witness" } }, layers), null);
+ assert.equal(itemPresetOf({ narration: {} }, layers), null);
+});
+
+test("the speed a part is asked at: the flag, the item's own, the preset's -- none for Orpheus, or at 1", () => {
+ assert.equal(readSpeedOf({ flag: 1.3, preset: 1.1, own: 0.9, engine: "kokoro" }), 1.3);
+ assert.equal(readSpeedOf({ preset: 1.1, own: 0.9, engine: "kokoro" }), 0.9, "set on the one item: it beats its character's");
+ assert.equal(readSpeedOf({ preset: 1.1, engine: "kokoro" }), 1.1);
+ assert.equal(readSpeedOf({ own: 0.9, engine: "kokoro" }), 0.9);
+ assert.equal(readSpeedOf({ engine: "kokoro" }), null);
+ assert.equal(readSpeedOf({ flag: 1.3, engine: "orpheus" }), null, "Orpheus has no speed");
+ assert.equal(readSpeedOf({ flag: 1, preset: 1.2, engine: "kokoro" }), null, "the flag wins, and 1 is no speed");
+});
+
+test("the chain for a recording: --as, the item's character, the project's for the author, the cast's, the narrator", () => {
+ const layers = { project: own, cast };
+ const e = { id: "p-1", handle: "MadamSavvy", narration: { character: "guest-star" } };
+ assert.deepEqual([characterForRead(e, { ...layers, as: "anon-1" }).character.id, characterForRead(e, { ...layers, as: "anon-1" }).layer], ["anon-1", "flag"]);
+ assert.equal(characterForRead(e, { ...layers, as: "@replyguy99" }).character.id, "anon-1", "by a handle");
+ assert.equal(characterForRead(e, { ...layers, as: "TheQuartering" }).character.id, "thequartering", "the cast's, when the project has none of that name");
+ assert.deepEqual(characterForRead(e, { ...layers, as: "nobody" }), { character: null, layer: "flag" });
+ assert.deepEqual([characterForRead(e, layers).character.id, characterForRead(e, layers).layer], ["guest-star", "item"]);
+ const plain = { id: "p-2", handle: "MadamSavvy" };
+ assert.deepEqual([characterForRead(plain, layers).character.id, characterForRead(plain, layers).layer], ["savvy-here", "project"]);
+ assert.deepEqual([characterForRead(plain, { cast }).character.id, characterForRead(plain, { cast }).layer], ["savvy", "cast"]);
+ // A project character with neither a voice nor a recorded preset names someone: it is not what a recording is made into.
+ assert.deepEqual([characterForRead({ handle: "TheQuartering" }, layers).character.id, characterForRead({ handle: "TheQuartering" }, layers).layer], ["thequartering", "cast"]);
+ assert.deepEqual([characterForRead({ handle: "stranger" }, layers).character.id, characterForRead({ handle: "stranger" }, layers).layer], ["savvy", "narrator"]);
+ assert.equal(characterForRead({ handle: "stranger" }, { cast: { ...cast, characters: [cast.characters[0]] } }), null, "nobody to convert to");
+});
+
+test("a recorded preset, its defaults filled: cleaned and trimmed unless it says not, the convert target a stock voice", () => {
+ const [anon, , , star] = projectCharactersOf(own);
+ assert.deepEqual(recordedPresetOf(anon), { convert: { engine: null, voice: "kokoro:am_puck" }, enhance: false, trim: { on: true, padMs: null }, direction: "flat, tired" });
+ assert.deepEqual(recordedPresetOf(star), { convert: { engine: null, voice: "kokoro:bm_lewis" }, enhance: true, trim: { on: false, padMs: null }, direction: null });
+ assert.deepEqual(recordedPresetOf(charactersOf(cast)[1]), { convert: { engine: "seed-vc", voice: "orpheus:tara", pitch: "contour", semitones: 2 }, enhance: true, trim: { on: true, padMs: null }, direction: null });
+ assert.deepEqual(recordedPresetOf({ id: "x", name: "X", recorded: { trim: { padMs: 120 } } }).trim, { on: true, padMs: 120 });
+});
diff --git a/umtool/report-to-video/check-availability.mjs b/umtool/report-to-video/check-availability.mjs
@@ -36,6 +36,7 @@
// --allow-missing Exit 0 even when a source is gone (report only)
// --max-age <days> Reuse a recorded verdict younger than this (default: 0)
+import { localRecordingFetchRefusal } from "./local-recording.mjs";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { readFile, stat, writeFile } from "node:fs/promises";
@@ -107,7 +108,7 @@ export async function cueMeta(videoId, channelSlug) {
// The record's directory: a Twitch v<n> is data/<n>/ (release 23 F1b).
const p = path.join(await resolveVideoDir(CHANNELS_DIR, channelSlug, videoId), "transcript.cues.json");
const d = JSON.parse(await readFile(p, "utf8"));
- return { title: d.title, webpageUrl: d.webpageUrl, duration: d.duration };
+ return { title: d.title, webpageUrl: d.webpageUrl, duration: d.duration, ...(d.platform ? { platform: d.platform } : {}) };
}
/** A source's verdict, as the inbox, the CLI and the build read it: true, false, or null (not checked). */
@@ -221,6 +222,12 @@ export async function checkAvailability(manifestPath, {
};
continue;
}
+ // A local recording has no source to probe (an empty URL would read as dead).
+ const localRefusal = localRecordingFetchRefusal(w.video, meta.platform);
+ if (localRefusal) {
+ rows[i] = { ...w, ok: false, state: "local-media", title: meta.title, url: null, checkedAt: iso(), error: localRefusal };
+ continue;
+ }
probes.push({ i, w, meta, platform: detectPlatform(meta.webpageUrl) ?? "other" });
}
diff --git a/umtool/report-to-video/chrome-cues.mjs b/umtool/report-to-video/chrome-cues.mjs
@@ -14,6 +14,7 @@
//
// PURE: data in, an HTML string out.
import { pageDuration } from "./deck.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
/** Instant cues still take a millisecond: a zero-duration tween has its own seek rules. */
export const INSTANT = 0.001;
@@ -55,7 +56,7 @@ export function compileCues(init, events) {
freeAt.set(e.k, r4(at + dur));
cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease });
}
- return { init, cues };
+ return { init, cues: settleFirstFrame(init, cues) };
}
/**
diff --git a/umtool/report-to-video/chrome-deck.mjs b/umtool/report-to-video/chrome-deck.mjs
@@ -46,6 +46,7 @@ import { claimsCues, claimsMarkup } from "./chrome-claims.mjs";
import { fitTallyLabel, resolveFactcheck, TALLY_WRITTEN, tallyCues, tallyFinals, tallyKey, tallyOf, tallyPopIns } from "./factcheck.mjs";
import { resolveCounter } from "./counter.mjs";
import { SUBSECTION_SEPARATOR } from "./marker-limits.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
/**
* GSAP, vendored, for every chrome region.
@@ -450,7 +451,7 @@ export function deckCues(schedule, render) {
cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease, why: e.why });
}
return {
- init, cues, pips, slideY, choreography: ch, ...(markers.length ? { markers } : {}), ...(claims ? { claims } : {}),
+ init, cues: settleFirstFrame(init, cues, fps), pips, slideY, choreography: ch, ...(markers.length ? { markers } : {}), ...(claims ? { claims } : {}),
...(sections ? { sections: { ...sections, fuses: fuseParts ?? [], rings } } : {}),
...(sectionTitle ? { sectionTitle } : {}),
};
diff --git a/umtool/report-to-video/chrome-finale.mjs b/umtool/report-to-video/chrome-finale.mjs
@@ -26,6 +26,7 @@ import { cueTime, cueTimeAfter, finaleRail, pageDuration, resolveDeck } from "./
import { finaleClaimsMarkup } from "./chrome-claims.mjs";
import { mix, rgba, shapeCss, subtitleMarkup, subtitlePartsCss, subtitleTokens } from "./chrome-deck.mjs";
import { resolveFactcheck, tallyCells, tallyFinals, tallyOf } from "./factcheck.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
import { resolveCounter } from "./counter.mjs";
import { aboveTop, FINALE_CLAIMS, FINALE_MOTION, finaleGeometry, resolveFinale } from "./finale.mjs";
@@ -299,7 +300,7 @@ export function finaleCues(schedule, render, L = finaleLayout(schedule, render))
freeAt.set(e.k, at + dur);
cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease, why: e.why });
}
- return { init, cues };
+ return { init, cues: settleFirstFrame(init, cues, fps) };
}
/**
diff --git a/umtool/report-to-video/chrome-instruments.mjs b/umtool/report-to-video/chrome-instruments.mjs
@@ -19,6 +19,8 @@ import { mix, rgba } from "./chrome-deck.mjs";
import { finaleLayout } from "./chrome-finale.mjs";
import { FINALE_MOTION } from "./finale.mjs";
import { resolveDial, resolveOdometer, resolveTrail } from "./instruments.mjs";
+import { TRAIL_REFLOW, trailLayout, trailPoints, trailStates } from "./trail-plan.mjs";
+import { deckAwaySpans, flashCss, flashCues, flashOn, flashTimes } from "./update-flash.mjs";
import { promiseStates, upSpans } from "./measure-extras.mjs";
import { ghostOpacity, ghostRamp, ghostTicks, resolveGhosts } from "./measure-ghosts.mjs";
import { goalBoard, goalsAt } from "./measure-goals.mjs";
@@ -99,7 +101,8 @@ function withDeck(L, schedule, render, k) {
const D = Number(schedule.transition) || 0;
const m = Math.max(D, 0.3);
for (const sd of mergedSpans(stackedStandDowns(schedule))) {
- shown.push({ at: Math.max(0, sd.from), dur: m, hide: true });
+ // Standing down from the cut's first instant is init, not a fade over the opening (cue-start.mjs).
+ shown.push({ at: Math.max(0, sd.from), dur: sd.from <= 0 ? INSTANT : m, hide: true });
if (sd.to < (schedule.total ?? Infinity) - 0.05) shown.push({ at: sd.to, dur: m, hide: false });
}
// Each change once, in time: a stand-down inside a span the deck is already away for adds nothing.
@@ -247,6 +250,33 @@ export function clearSpot(spots, obstacles, m = 0) {
/** A centred box `w` x `h` at (x, y). */
const boxAt = (x, y, w, h) => ({ x0: x - w / 2, x1: x + w / 2, y0: y - h / 2, y1: y + h / 2 });
+/** How the dial shows a remembered weight (`deck.dial.rememberedAs`): "needle" (the long grey needle, as it was), "rim", "readout", "callout". */
+export const rememberedMode = (cfg) => (["rim", "readout", "callout"].includes(cfg?.rememberedAs) ? cfg.rememberedAs : "needle");
+
+/** His highest remembered weight above every one he stated (the peak extra's `totals.peakDrift`), or null. */
+export const heaviestOf = (measure) => {
+ const drift = Array.isArray(measure?.totals?.peakDrift) ? measure.totals.peakDrift.filter(Number.isFinite) : [];
+ return drift.length ? Math.max(...drift) : null;
+};
+
+/**
+ * A remembered weight's words, from its own fields: `value` with its qualifier ("≈390"), `when` its asOf's month
+ * ("FEB 2023", null without one), `kind` "HEAVIEST HE'S SAID" when it is `heaviest` (heaviestOf) else "HE SAYS HE
+ * WAS"; and the forms the looks draw -- `head`/`sub` (the rim's flag), `line` (the readout's).
+ */
+export function rememberedWords(g, heaviest = null) {
+ const value = weightWords(g);
+ const top = heaviest !== null && Number.isFinite(g.value) && Math.abs(g.value - heaviest) < 0.05;
+ const when = g.asOf ? fmtDate(g.asOf, { day: false }) : null;
+ const kind = top ? "HEAVIEST HE'S SAID" : "HE SAYS HE WAS";
+ return {
+ value, when, kind, heaviest: top,
+ head: top ? `HEAVIEST ${value}` : value,
+ sub: [when ? `AS OF ${when}` : "REMEMBERED", top ? "HE SAYS" : ""].filter(Boolean).join(" · "),
+ line: `${kind}: ${value}${when ? ` (${when})` : ""}`,
+ };
+}
+
/**
* An as-of label's places, best first: along its ghost (angle `a`) at half the face's radius, each of its `forms`
* (its small words on one line, then on two), then stepping in toward the hub; never lower than just under the hub,
@@ -274,7 +304,7 @@ function asofSpots({ C, Rf, u, a, head, forms, px, fpx }) {
* the hub and the readout blocks. Shared by the column's dial and the
* finale's. Returns its markup and css; its cues are the caller's.
*/
-function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, marks = [], lines = [], ghosts = null, prefix = "", preState = true }) {
+function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, marks = [], lines = [], ghosts = null, prefix = "", preState = true, heaviest = null }) {
const face = dialFaceSvg({ size, scale, mark: cfg.mark, colors: { ...colors, mark: colors.accent }, labelFont: fontStack(fonts, "condensed") });
const { C, R, Rf, u } = face;
const px = (v) => Math.round(v * u * 100) / 100;
@@ -348,7 +378,8 @@ function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, marks = [],
parts.push(`<div class="ly" data-k="${prefix}gm${i}">${svg(`gm${i}h`, head)}${svg(`gm${i}o`, other)}${svg(`gm${i}x`, strike)}${svg(`gm${i}p`, flash)}</div>`);
});
}
- if (cfg.ghosts && track.remembered.length) {
+ const mode = rememberedMode(cfg);
+ if (cfg.ghosts && track.remembered.length && (mode === "needle" || mode === "callout")) {
parts.push(layer("gn", `<line x1="${C}" y1="${C + 22 * u}" x2="${C}" y2="${C - Rf + 66 * u}" stroke="${colors.ghost}" stroke-width="${px(5)}" stroke-linecap="round"/>`));
}
// The needle: a tapered blade from a counterweight through the hub.
@@ -359,7 +390,7 @@ function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, marks = [],
// The as-of labels, each by its ghost, up while it is the latest -- and never on a scale figure (rev 9: "≈390 ·
// AS OF FEB 2025 · TOLD 4×" sat on the 380). Along its ghost, never down into the readout's words under the hub;
// where its box would touch a figure's, its words go on two lines, then it steps in toward the hub.
- if (cfg.ghosts) {
+ if (cfg.ghosts && mode === "needle") {
track.remembered.forEach((g, j) => {
const a = dialAngle(g.value, scale);
const head = weightWords(g);
@@ -371,6 +402,52 @@ function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, marks = [],
parts.push(`<div class="asof" data-k="${prefix}ga${j}" style="left:${spot.x}px; top:${spot.y}px"><b>${esc(head)}</b>${spot.lines.map((l) => `<span>${esc(l)}</span>`).join("")}</div>`);
});
}
+ // THE REMEMBERED WEIGHT'S OTHER LOOKS (`deck.dial.rememberedAs`, 11 Nov: the long grey second needle and its
+ // small words crossed the main needle and the readout and did not say what the weight was). Each from the
+ // ledger's own fields -- the qualifier, the asOf, "heaviest" only for the record's highest remembered weight above
+ // every one he stated (the peak extra's `totals.peakDrift`) -- never words of ours.
+ // rim a bold marker on the rim at the value and a flag inside it, clear of the hub, the figures and the readout
+ // readout a line in the readout under the date ("HEAVIEST HE'S SAID: ≈390 (FEB 2023)"), a marker on the rim
+ // callout a ghost needle sweeps to the value as he says it, a clear label holds ~2 s, then the rim's flag
+ const readoutBox = { x0: C - 128 * u, x1: C + 128 * u, y0: C + 60 * u, y1: C + 230 * u };
+ if (cfg.ghosts && mode !== "needle") {
+ const ink = mix(colors.ghost, colors.fg, 0.55);
+ track.remembered.forEach((g, j) => {
+ const w = rememberedWords(g, heaviest);
+ const a = dialAngle(g.value, scale);
+ // The marker: a bold wedge across the rim, pointing in -- the scale's own ticks show through either side.
+ parts.push(layer(`gk${j}`, `<polygon points="${C - 9 * u},${C - R - 3 * u} ${C + 9 * u},${C - R - 3 * u} ${C + 3 * u},${C - Rf + 30 * u} ${C - 3 * u},${C - Rf + 30 * u}" fill="${ink}" stroke="${colors.bg}" stroke-width="${px(2)}"/>`));
+ if (mode === "readout") {
+ parts.push(`<div class="rline" data-k="${prefix}gr${j}" style="top:${C + 188 * u}px">${esc(w.line)}</div>`);
+ return;
+ }
+ // The flag: inside the rim by the marker -- along it, then turning a little either way, stepping in -- clear of
+ // the scale's figures, the hub, the readout and the needle where it stands as he says it.
+ const hb = px(22), hs = fpx(12);
+ const flagLines = [w.heaviest ? "HEAVIEST" : "REMEMBERED", w.when ? w.when : ""].filter(Boolean);
+ const fw = Math.max(w.value.length * hb * 0.56, ...flagLines.map((l) => l.length * hs * 0.66)) + 2 * px(8);
+ const fh = hb * 1.08 + flagLines.length * hs * 1.12 + 2 * px(4);
+ const stands = [...track.current].filter((c) => c.t <= g.t + 1e-9 && Number.isFinite(c.value)).pop();
+ const needle = [];
+ if (stands) {
+ const na = dialAngle(stands.value, scale);
+ for (let r = 24 * u; r <= Rf - 30 * u; r += 14 * u) { const [x, y] = polar(C, C, r, na); needle.push(boxAt(x, y, 10 * u, 10 * u)); }
+ }
+ const spots = [];
+ for (const da of [0, -8, 8, -16, 16, -24, 24, -32, 32, -40, -48]) {
+ for (let r = Rf * 0.64; r >= Rf * 0.34 - 1e-9; r -= Rf * 0.04) {
+ const [x, y] = polar(C, C, r, a + da);
+ spots.push({ x, y, box: boxAt(x, y, fw, fh) });
+ }
+ }
+ const spot = clearSpot(spots, [...faceFigures.map((f) => f.box), hub, readoutBox, ...needle], 4 * u);
+ const [l0, l1] = flagLines;
+ parts.push(`<div class="rflag" data-k="${prefix}gl${j}" style="left:${spot.x}px; top:${spot.y}px"><span>${esc(l0)}</span><b>${esc(w.value)}</b>${l1 ? `<span>${esc(l1)}</span>` : ""}</div>`);
+ if (mode === "callout") {
+ parts.push(`<div class="rcall" data-k="${prefix}gc${j}" style="top:${C - 104 * u}px"><span>${esc(w.kind)}</span><b>${esc(w.value)}</b>${w.when ? `<span>AS OF ${esc(w.when)}</span>` : ""}</div>`);
+ }
+ });
+ }
// The readout under the hub: the words, the weight, the weighing's date, the goal.
// Inside the face's open quarter: each line kept within the chord at its height.
parts.push(`<div class="rlab" style="top:${C + 72 * u}px">${esc(cfg.label)}</div>`);
@@ -382,7 +459,9 @@ function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, marks = [],
});
if (cfg.goal) {
lines.forEach((g, j) => {
- parts.push(`<div class="goalw${g.missed ? " miss" : ""}" data-k="${prefix}gw${j}" style="top:${C + 188 * u}px">${esc(g.words)}</div>`);
+ // Under the remembered line when the readout carries one (rememberedAs "readout").
+ const gy = cfg.ghosts && mode === "readout" && track.remembered.length ? C + 210 * u : C + 188 * u;
+ parts.push(`<div class="goalw${g.missed ? " miss" : ""}" data-k="${prefix}gw${j}" style="top:${gy}px">${esc(g.words)}</div>`);
});
}
const css = `
@@ -408,7 +487,19 @@ function dialParts({ size, ox, oy, scale, cfg, colors, fonts, track, marks = [],
color: ${colors.accent}; white-space: nowrap; padding: ${px(1)}px ${px(6)}px; border-radius: ${px(5)}px; background: ${rgba(colors.face, 0.9)}; }
.dial .goalw { position: absolute; left: 0; width: ${size}px; text-align: center; font-family: ${fontStack(fonts, "bold")};
font-size: ${fpx(17)}px; line-height: ${Math.max(15, px(20))}px; letter-spacing: 0.05em; color: ${colors.amber}; white-space: nowrap; }
- .dial .goalw.miss { color: ${colors.needle}; }`;
+ .dial .goalw.miss { color: ${colors.needle}; }${cfg.ghosts && mode !== "needle" && track.remembered.length ? `
+ .dial .rflag { position: absolute; transform: translate(-50%, -50%); text-align: center; white-space: nowrap; line-height: 1.08;
+ padding: ${px(4)}px ${px(8)}px; border-radius: ${px(6)}px; background: ${rgba(colors.face, 0.92)};
+ border: ${px(1.5)}px solid ${rgba(mix(colors.ghost, colors.fg, 0.55), 0.7)}; color: ${mix(colors.ghost, colors.fg, 0.6)}; }
+ .dial .rflag b { display: block; font-family: ${fontStack(fonts, "display")}; font-weight: 400; font-size: ${px(22)}px; }
+ .dial .rflag span { display: block; font-family: ${fontStack(fonts, "condensed")}; font-size: ${fpx(12)}px; letter-spacing: 0.1em; color: ${colors.ghost}; }
+ .dial .rline { position: absolute; left: 0; width: ${size}px; text-align: center; font-family: ${fontStack(fonts, "condensed")};
+ font-size: ${fpx(16)}px; line-height: ${Math.max(15, px(20))}px; letter-spacing: 0.06em; color: ${mix(colors.ghost, colors.fg, 0.55)}; white-space: nowrap; }
+ .dial .rcall { position: absolute; left: 50%; transform: translate(-50%, -50%); text-align: center; white-space: nowrap; line-height: 1.05;
+ padding: ${px(6)}px ${px(14)}px; border-radius: ${px(8)}px; background: ${rgba(colors.face, 0.94)};
+ border: ${px(2)}px solid ${mix(colors.ghost, colors.fg, 0.55)}; color: ${mix(colors.ghost, colors.fg, 0.7)}; }
+ .dial .rcall b { display: block; font-family: ${fontStack(fonts, "display")}; font-weight: 400; font-size: ${px(40)}px; }
+ .dial .rcall span { display: block; font-family: ${fontStack(fonts, "condensed")}; font-size: ${fpx(15)}px; letter-spacing: 0.1em; color: ${colors.ghost}; }` : ""}`;
return { html: `<div class="dial">${parts.join("\n ")}</div>`, css, face };
}
@@ -461,7 +552,8 @@ function dialCues(L, { track, scale, cfg, marks = [], lines = [], ghosts = null,
L.add(k(`gb${j}`), g.t, M.fade, { autoAlpha: 1 }, "power1.out");
}
});
- if (track.remembered.length && finale) {
+ if (rememberedMode(cfg) !== "needle") rememberedCues(L, { track, scale, cfg, k, finale });
+ else if (track.remembered.length && finale) {
// All at once: the long ghost and its words on the last (the finale puts his highest there).
const last = track.remembered.length - 1;
const g = track.remembered[last];
@@ -482,6 +574,52 @@ function dialCues(L, { track, scale, cfg, marks = [], lines = [], ghosts = null,
if (ghosts) ghostCues(L, { ghosts, scale, k, finale, at });
}
+/** The callout's hold (rememberedAs "callout"): the label up this long after he says it, then the rim's flag. */
+export const CALLOUT_HOLD = 2.2;
+
+/**
+ * The remembered weight's cues in the looks other than the long needle (dialParts, `deck.dial.rememberedAs`): its
+ * rim marker and its flag (or its readout line) up while it is the latest remembered; with "callout", first the
+ * ghost needle sweeping from where the needle stands to the value and the label held CALLOUT_HOLD s. In the finale,
+ * the last one's, all at once. The finale never plays the callout: its labels and its ghost needle are hidden there, the
+ * rim's marker and flag stay.
+ */
+function rememberedCues(L, { track, scale, cfg, k, finale }) {
+ const M = INSTRUMENT_MOTION;
+ const R = track.remembered;
+ if (!R.length) return;
+ const mode = rememberedMode(cfg);
+ const call = mode === "callout" && !finale;
+ const label = mode === "readout" ? "gr" : "gl";
+ const startOf = (g) => (call ? g.t + CALLOUT_HOLD : g.t);
+ R.forEach((g, j) => {
+ L.set(k(`gk${j}`), { rotation: dialAngle(g.value, scale), autoAlpha: 0 });
+ L.set(k(`${label}${j}`), { autoAlpha: 0 });
+ // The callout's label is drawn whenever the look is "callout" (dialParts), so it is hidden whenever it is drawn:
+ // in the finale too, where nothing calls it up (rev9-a9: every box sat at its CSS default over the hub).
+ if (mode === "callout") L.set(k(`gc${j}`), { autoAlpha: 0 });
+ if (finale && j !== R.length - 1) return;
+ const next = finale ? null : R[j + 1];
+ for (const key of [`gk${j}`, `${label}${j}`]) {
+ L.add(k(key), startOf(g), M.fade, { autoAlpha: 1 }, "power1.out");
+ if (next) L.add(k(key), startOf(next), M.fade * 0.6, { autoAlpha: 0 }, "power1.in");
+ }
+ });
+ // The ghost needle likewise: drawn with the look, hidden with it -- the finale never sweeps it.
+ if (mode === "callout") L.set(k("gn"), { rotation: dialAngle(R[0].value, scale), autoAlpha: 0 });
+ if (!call) return;
+ const a0 = dialAngle(scale.min, scale);
+ R.forEach((g, j) => {
+ // From where the needle stands as he says it (his stated weight in force then; the scale's foot before one).
+ const cur = [...track.current].filter((c) => c.t <= g.t + 1e-9 && Number.isFinite(c.value)).pop();
+ L.add(k("gn"), g.t, INSTANT, { rotation: cur ? dialAngle(cur.value, scale) : a0, autoAlpha: 0.9 }, "none");
+ L.add(k("gn"), g.t + 0.05, M.needle, { rotation: dialAngle(g.value, scale) }, "power2.inOut");
+ L.add(k("gn"), g.t + CALLOUT_HOLD, 0.4, { autoAlpha: 0 }, "power1.in");
+ L.add(k(`gc${j}`), g.t + 0.25, M.fade, { autoAlpha: 1 }, "power1.out");
+ L.add(k(`gc${j}`), g.t + CALLOUT_HOLD, 0.4, { autoAlpha: 0 }, "power1.in");
+ });
+}
+
/**
* The goal board's cues (goalMarks, goalLines): each mark's status from each board state -- the headline's triangle,
* an other's tick, a miss struck in red with a flash -- and the goal line's words.
@@ -578,16 +716,26 @@ export function dialHtml(schedule, render, opts = {}) {
const marks = goalMarks(board, M.scale);
const lines = goalLines(board);
const ghosts = ghostsOf(M, render, colors);
- const parts = dialParts({ size, ox: Math.floor((W - size) / 2), oy: Math.floor((H - size) / 2), scale: M.scale, cfg, colors, fonts, track, marks, lines, ghosts });
+ const parts = dialParts({ size, ox: Math.floor((W - size) / 2), oy: Math.floor((H - size) / 2), scale: M.scale, cfg, colors, fonts, track, marks, lines, ghosts, heaviest: heaviestOf(M) });
const L = cueList(fps);
withDeck(L, schedule, render, "rt");
dialCues(L, { track, scale: M.scale, cfg, marks, lines, ghosts });
+ // THE UPDATE FLASH (update-flash.mjs): the bezel lights as a weight is stated or remembered, or the goal changes.
+ let flash = { html: "", css: "" };
+ if (flashOn(render, cfg.flash)) {
+ const times = [...track.current.slice(1), ...track.remembered, ...track.goals.slice(1)].map((x) => x.t);
+ flashCues(L, "fl", flashTimes(times, { fps, away: deckAwaySpans(schedule, render) }));
+ flash = {
+ html: `<div class="flw" style="left:${Math.floor((W - size) / 2)}px; top:${Math.floor((H - size) / 2)}px; width:${size}px; height:${size}px"><div class="fl" data-k="fl"></div></div>`,
+ css: `\n .flw { position: absolute; }\n ${flashCss(".flw .fl", colors.accent, { radius: "50%", width: 3 })}`,
+ };
+ }
const { init, cues } = L.build();
return pageHtml({
id: "dial", W, H, fps, fonts, gsap: opts.gsap,
data: { total: r4(schedule.total), window: windowOf(schedule, opts, "dial"), init, cues },
- css: `#rt { position: absolute; inset: 0; }${parts.css}`,
- body: `<div id="rt" data-k="rt">${parts.html}</div>`,
+ css: `#rt { position: absolute; inset: 0; }${parts.css}${flash.css}`,
+ body: `<div id="rt" data-k="rt">${parts.html}${flash.html}</div>`,
});
}
@@ -681,12 +829,19 @@ export function odometerHtml(schedule, render, opts = {}) {
});
if (cfg.runs) blocks(L, track.lost, "rn");
if (cfg.net) blocks(L, track.net, "nt");
+ // THE UPDATE FLASH (update-flash.mjs): the card lights as the pounds lost go up, its runs or NET change.
+ let flash = { html: "", css: "" };
+ if (flashOn(render, cfg.flash)) {
+ const times = [...track.lost.slice(1), ...(cfg.net ? track.net.slice(1) : [])].map((x) => x.t);
+ flashCues(L, "fl", flashTimes(times, { fps, away: deckAwaySpans(schedule, render) }));
+ flash = { html: `<div class="fl" data-k="fl"></div>`, css: `\n ${flashCss("#rt > .fl", colors.accent, { radius: `${Math.round(10 * u * 100) / 100}px`, width: 2 })}` };
+ }
const { init, cues } = L.build();
return pageHtml({
id: "odometer", W, H, fps, fonts, gsap: opts.gsap,
data: { total: r4(schedule.total), window: windowOf(schedule, opts, "odometer"), init, cues },
- css: `#rt { position: absolute; inset: 0; }${parts.css}`,
- body: `<div id="rt" data-k="rt">${parts.html}</div>`,
+ css: `#rt { position: absolute; inset: 0; }${parts.css}${flash.css}`,
+ body: `<div id="rt" data-k="rt">${parts.html}${flash.html}</div>`,
});
}
@@ -707,58 +862,126 @@ export function trailHtml(schedule, render, opts = {}) {
const colors = colorsOf(render);
const track = measureTrack(M);
const mark = Number.isFinite(cfg.mark) ? cfg.mark : null;
- // By date: each stated weight at the day it was weighed, in date order.
- const pts = track.stated
- .map((p, n) => ({ ...p, day: dayNumber(p.date), n }))
- .filter((p) => Number.isFinite(p.day))
- .sort((a, b) => a.day - b.day || a.n - b.n);
- const x0 = px(54), x1 = W - px(18), y0 = px(38), y1 = H - px(26);
- let d0 = pts.length ? pts[0].day : 0, d1 = pts.length ? pts[pts.length - 1].day : 1;
- if (d1 - d0 < 60) { d0 -= 30; d1 += 30; }
- const vals = pts.map((p) => p.value).concat(mark !== null ? [mark] : []);
- const lo = vals.length ? Math.floor((Math.min(...vals) - 5) / 10) * 10 : M.scale.min;
- const hi = vals.length ? Math.ceil((Math.max(...vals) + 5) / 10) * 10 : M.scale.max;
- const X = (d) => r4(x0 + ((d - d0) / (d1 - d0)) * (x1 - x0));
- const Y = (v) => r4(y1 - ((v - lo) / Math.max(1, hi - lo)) * (y1 - y0));
- const parts = [];
- // The years along the foot.
- const yearOf = (d) => new Date(d * 86400000).getUTCFullYear();
- for (let yr = yearOf(d0) + 1; yr <= yearOf(d1); yr += 1) {
- const x = X(Date.UTC(yr, 0, 1) / 86400000);
- parts.push(`<div class="yr" style="left:${x}px; top:${y1 + px(4)}px">${yr}</div><div class="ytick" style="left:${x}px; top:${y0}px; height:${y1 - y0}px"></div>`);
- }
- if (mark !== null && mark >= lo && mark <= hi) {
- parts.push(`<div class="mark" style="left:${x0}px; top:${Y(mark)}px; width:${x1 - x0}px"></div><div class="marklab" style="left:${px(12)}px; top:${Y(mark)}px">${mark}</div>`);
- }
- parts.push(`<div class="lohi" style="left:${px(12)}px; top:${y0}px">${hi}</div><div class="lohi" style="left:${px(12)}px; top:${y1}px">${lo}</div>`);
+ // THE PLAN (trail-plan.mjs): a state per moment a weight is said -- stated, and remembered unless `remembered` is
+ // off -- each laid out on axes that fit what is shown, the time axis broken across long empty stretches.
+ const pts = trailPoints(M, { remembered: cfg.remembered !== false });
+ const box = { x0: px(54), x1: W - px(18), y0: px(38), y1: H - px(26), gapPx: px(22), yearPx: px(34) };
+ const states = trailStates(pts, box, { gap: cfg.gap ?? "auto", mark, bounds: cfg.bounds ?? "fit" });
+ const first = states[0]?.layout ?? trailLayout([], box, { mark });
+ const { y0, y1 } = box;
const L = cueList(fps);
withDeck(L, schedule, render, "rt");
const M2 = INSTRUMENT_MOTION;
- // The line: each pair of neighbours by date, drawn once both have been said.
- for (let j = 0; j + 1 < pts.length; j += 1) {
- const a = pts[j], b = pts[j + 1];
- const xa = X(a.day), ya = Y(a.value), xb = X(b.day), yb = Y(b.value);
- const len = r4(Math.hypot(xb - xa, yb - ya));
- const ang = r4((Math.atan2(yb - ya, xb - xa) * 180) / Math.PI);
- parts.push(`<div class="seg" data-k="s${j}" style="left:${xa}px; top:${ya}px; width:${len}px"></div>`);
- L.set(`s${j}`, { rotation: ang, scaleX: 0, transformOrigin: "0% 50%" });
- L.add(`s${j}`, Math.max(a.t, b.t), M2.segment, { scaleX: 1 }, "power2.out");
- }
- pts.forEach((p, j) => {
- parts.push(`<div class="pt${p.qualifier ? " q" : ""}" data-k="p${j}" style="left:${X(p.day)}px; top:${Y(p.value)}px"></div>`);
- L.set(`p${j}`, { autoAlpha: 0, scale: 0.3 });
- L.add(`p${j}`, p.t, M2.point, { autoAlpha: 1, scale: 1 }, "back.out(2)");
+ const RF = TRAIL_REFLOW;
+ const parts = [];
+ const moved = (a, b) => !a || !b || Math.abs(a.x - b.x) > 0.05 || Math.abs(a.y - b.y) > 0.05;
+
+ // The axes: a label per year (its tick inside a cluster), a break per gap between clusters, the bounds' two figures
+ // and the mark line -- each shown, moved and hidden state by state; before the first weight, the first state's axes.
+ const yearKeys = new Map();
+ const gapKeys = new Map();
+ const bounds = new Map();
+ states.forEach((st) => {
+ for (const y of st.layout.years) if (!yearKeys.has(y.key)) yearKeys.set(y.key, y);
+ for (const g of st.layout.gaps) if (!gapKeys.has(g.key)) gapKeys.set(g.key, g);
+ for (const v of [`hi${st.layout.hi}`, `lo${st.layout.lo}`]) bounds.set(v, null);
});
- // The latest said, ringed in the needle's red: it travels to each as it lands.
- if (pts.length) {
- parts.push(`<div class="ring" data-k="pl"></div>`);
- const inCut = [...pts].sort((a, b) => a.t - b.t || a.n - b.n);
- L.set("pl", { x: X(inCut[0].day), y: Y(inCut[0].value), autoAlpha: 0 });
- inCut.forEach((p, j) => {
- if (j === 0) L.add("pl", p.t, M2.point, { autoAlpha: 1 }, "power1.out");
- else L.add("pl", p.t, M2.point, { x: X(p.day), y: Y(p.value) }, "power2.inOut");
- });
+ if (!states.length) for (const v of [`hi${first.hi}`, `lo${first.lo}`]) bounds.set(v, null);
+ for (const [key, y] of yearKeys) {
+ parts.push(`<div class="yw" data-k="y${key}">${y.tick ? `<div class="ytick" style="top:${y0}px; height:${r4(y1 - y0)}px"></div>` : ""}<div class="yr" style="top:${r4(y1 + px(4))}px">${y.text}</div></div>`);
+ }
+ for (const [key] of gapKeys) {
+ parts.push(`<div class="gp" data-k="g${key}" style="top:${y0}px; height:${r4(y1 - y0)}px"><div class="gz">//</div></div>`);
}
+ for (const key of bounds.keys()) {
+ parts.push(`<div class="lohi" data-k="b${key}" style="left:${px(12)}px; top:${key.startsWith("hi") ? y0 : y1}px">${key.slice(2)}</div>`);
+ }
+ if (mark !== null) parts.push(`<div class="mark" data-k="mk" style="left:${box.x0}px; width:${r4(box.x1 - box.x0)}px"></div><div class="marklab" data-k="ml" style="left:${px(12)}px">${mark}</div>`);
+ const axisAt = (layout, at, prev) => {
+ const vis = (list) => new Map(list.map((x) => [x.key, x]));
+ const ys = vis(layout.years), gs = vis(layout.gaps);
+ const pys = prev ? vis(prev.years) : new Map(), pgs = prev ? vis(prev.gaps) : new Map();
+ for (const [key] of yearKeys) {
+ const now = ys.get(key), was = pys.get(key);
+ if (!prev) { L.set(`y${key}`, { x: (now ?? yearKeys.get(key)).x ?? 0, autoAlpha: now ? 1 : 0 }); continue; }
+ if (now && was) { if (Math.abs(now.x - was.x) > 0.05) L.add(`y${key}`, at, RF, { x: now.x }, "power2.inOut"); }
+ else if (now) L.add(`y${key}`, at, RF, { x: now.x, autoAlpha: 1 }, "power2.out");
+ else if (was) L.add(`y${key}`, at, RF * 0.6, { autoAlpha: 0 }, "power1.in");
+ }
+ for (const [key] of gapKeys) {
+ const now = gs.get(key), was = pgs.get(key);
+ if (!prev) { L.set(`g${key}`, { x: (now ?? gapKeys.get(key)).x, autoAlpha: now ? 1 : 0 }); continue; }
+ if (now && was) { if (Math.abs(now.x - was.x) > 0.05) L.add(`g${key}`, at, RF, { x: now.x }, "power2.inOut"); }
+ else if (now) L.add(`g${key}`, at, RF, { x: now.x, autoAlpha: 1 }, "power2.out");
+ else if (was) L.add(`g${key}`, at, RF * 0.6, { autoAlpha: 0 }, "power1.in");
+ }
+ // A bound's figure gives way to the mark's when they would sit on each other.
+ const clear = (lay, v) => mark === null || Math.abs(lay.Y(mark) - lay.Y(v)) >= px(14);
+ const shows = (lay, key) => (key === `hi${lay.hi}` && clear(lay, lay.hi)) || (key === `lo${lay.lo}` && clear(lay, lay.lo));
+ for (const key of bounds.keys()) {
+ const on = shows(layout, key);
+ const was = prev ? shows(prev, key) : null;
+ if (!prev) L.set(`b${key}`, { autoAlpha: on ? 1 : 0 });
+ else if (on !== was) L.add(`b${key}`, at, RF * 0.6, { autoAlpha: on ? 1 : 0 }, "power1.inOut");
+ }
+ if (mark !== null) {
+ const y = layout.Y(mark);
+ if (!prev) { L.set("mk", { y }); L.set("ml", { y, yPercent: -50 }); }
+ else if (Math.abs(prev.Y(mark) - y) > 0.05) { L.add("mk", at, RF, { y }, "power2.inOut"); L.add("ml", at, RF, { y }, "power2.inOut"); }
+ }
+ };
+ axisAt(first, 0, null);
+
+ // The points: each pops in at its place in the state it is said in, then moves with every reflow after.
+ const firstState = new Map();
+ states.forEach((st, j) => { for (const n of st.shown) if (!firstState.has(n)) firstState.set(n, j); });
+ for (const p of pts) {
+ const j = firstState.get(p.n);
+ const at = states[j].pos.get(p.n);
+ const cls = `pt${p.kind === "remembered" ? " rem" : ""}${p.qualifier ? " q" : ""}`;
+ parts.push(`<div class="${cls}" data-k="p${p.n}"></div>`);
+ L.set(`p${p.n}`, { x: at.x, y: at.y, autoAlpha: 0, scale: 0.3 });
+ L.add(`p${p.n}`, p.t, M2.point, { autoAlpha: 1, scale: 1 }, "back.out(2)");
+ }
+ // The line: neighbours by date among the stated points shown, a pair drawn in when it first is one, moved with the
+ // reflows while it lasts, gone the moment a weight said later lands between them. Across a break it is dotted.
+ const pairFirst = new Map();
+ states.forEach((st, j) => { for (const pr of st.pairs) if (!pairFirst.has(pr.key)) pairFirst.set(pr.key, { ...pr, j }); });
+ const geomOf = (st, pr) => {
+ const a = st.pos.get(pr.a), b = st.pos.get(pr.b);
+ return { x: a.x, y: a.y, width: r4(Math.hypot(b.x - a.x, b.y - a.y)), rotation: r4((Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI) };
+ };
+ for (const [key, pr] of pairFirst) {
+ parts.push(`<div class="seg${pr.gap ? " gap" : ""}" data-k="s${key}"></div>`);
+ L.set(`s${key}`, { ...geomOf(states[pr.j], pr), scaleX: 0, autoAlpha: 1, transformOrigin: "0% 50%" });
+ L.add(`s${key}`, states[pr.j].at, M2.segment, { scaleX: 1 }, "power2.out");
+ }
+ // The latest said, ringed in the needle's red: it travels to each as it lands, and with the reflows.
+ if (pts.length) parts.push(`<div class="ring" data-k="pl"></div>`);
+ states.forEach((st, j) => {
+ const prev = j ? states[j - 1] : null;
+ const latest = pts.filter((p) => p.t <= st.at + 1e-9).at(-1);
+ if (!prev) {
+ const at0 = st.pos.get(latest.n);
+ L.set("pl", { x: at0.x, y: at0.y, autoAlpha: 0 });
+ L.add("pl", st.at, M2.point, { autoAlpha: 1 }, "power1.out");
+ return;
+ }
+ axisAt(st.layout, st.at, prev.layout);
+ for (const n of prev.shown) {
+ const a = prev.pos.get(n), b = st.pos.get(n);
+ if (moved(a, b)) L.add(`p${n}`, st.at, RF, { x: b.x, y: b.y }, "power2.inOut");
+ }
+ const was = new Map(prev.pairs.map((pr) => [pr.key, pr]));
+ const now = new Map(st.pairs.map((pr) => [pr.key, pr]));
+ for (const [key, pr] of was) {
+ if (!now.has(key)) { L.add(`s${key}`, st.at, RF * 0.5, { autoAlpha: 0 }, "power1.in"); continue; }
+ const g0 = geomOf(prev, pr), g1 = geomOf(st, pr);
+ if (moved(g0, g1) || Math.abs(g0.width - g1.width) > 0.05 || Math.abs(g0.rotation - g1.rotation) > 0.05) L.add(`s${key}`, st.at, RF, g1, "power2.inOut");
+ }
+ const ring = st.pos.get(latest.n);
+ L.add("pl", st.at, RF, { x: ring.x, y: ring.y }, "power2.inOut");
+ });
// How many times he says he is under 300, counted as each lands.
const counts = cfg.count && mark === 300 ? track.under.slice().sort((a, b) => a.t - b.t).map((x, n) => ({ t: x.t, n: n + 1 })) : [];
counts.forEach((c) => parts.push(`<div class="cnt" data-k="uc${c.n - 1}">UNDER ${mark} · SAID ${c.n}×</div>`));
@@ -770,26 +993,39 @@ export function trailHtml(schedule, render, opts = {}) {
if (sp.out < schedule.total - 0.05) L.add("ty", sp.out, 0.4, { autoAlpha: 1 }, "power1.out");
}
L.set("ty", { autoAlpha: 1 });
+ // THE UPDATE FLASH (update-flash.mjs): the card lights as each weight lands on it.
+ const flashing = flashOn(render, cfg.flash);
+ if (flashing) {
+ flashCues(L, "fl", flashTimes(states.map((st) => st.at), { fps, away: deckAwaySpans(schedule, render) }));
+ parts.push(`<div class="fl" data-k="fl"></div>`);
+ }
const { init, cues } = L.build();
const css = `
#rt { position: absolute; inset: 0; }
- .ty { position: absolute; inset: 0; }
- .trail { position: absolute; inset: 0; border-radius: ${px(10)}px; background: ${colors.card}; }
+ .ty { position: absolute; inset: 0; }${flashing ? `\n ${flashCss(".trail .fl", colors.accent, { radius: `${px(10)}px`, width: 2 })}` : ""}
+ .trail { position: absolute; inset: 0; border-radius: ${px(10)}px; background: ${colors.card}; overflow: hidden; }
.trail .lab { position: absolute; left: ${px(14)}px; top: ${px(10)}px; font-family: ${fontStack(fonts, "condensed")}; font-size: ${px(14)}px;
letter-spacing: 0.12em; color: ${colors.muted}; white-space: nowrap; }
.trail .cnt { position: absolute; right: ${px(16)}px; top: ${px(9)}px; font-family: ${fontStack(fonts, "bold")}; font-size: ${px(15)}px;
letter-spacing: 0.06em; color: ${colors.accent}; white-space: nowrap; }
- .trail .yr { position: absolute; transform: translateX(-50%); font-family: ${fontStack(fonts, "condensed")}; font-size: ${px(13)}px;
- color: ${colors.muted}; letter-spacing: 0.06em; }
- .trail .ytick { position: absolute; width: 1px; background: ${colors.rule}; }
- .trail .mark { position: absolute; height: 0; border-top: ${px(2)}px dashed ${rgba(colors.accent, 0.75)}; }
+ .trail .yw { position: absolute; left: 0; top: 0; width: 0; height: 0; }
+ .trail .yr { position: absolute; left: 0; transform: translateX(-50%); font-family: ${fontStack(fonts, "condensed")}; font-size: ${px(13)}px;
+ color: ${colors.muted}; letter-spacing: 0.06em; white-space: nowrap; }
+ .trail .ytick { position: absolute; left: 0; width: 1px; background: ${colors.rule}; }
+ .trail .gp { position: absolute; left: 0; width: ${px(14)}px; margin-left: -${px(7)}px; background: ${rgba(colors.muted, 0.08)}; }
+ .trail .gz { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); font-family: ${fontStack(fonts, "condensed")};
+ font-size: ${px(13)}px; color: ${colors.muted}; letter-spacing: -0.1em; }
+ .trail .mark { position: absolute; top: 0; height: 0; border-top: ${px(2)}px dashed ${rgba(colors.accent, 0.75)}; }
.trail .marklab, .trail .lohi { position: absolute; transform: translateY(-50%); font-family: ${fontStack(fonts, "condensed")};
font-size: ${px(13)}px; color: ${colors.muted}; }
- .trail .marklab { color: ${colors.accent}; font-family: ${fontStack(fonts, "bold")}; }
- .trail .seg { position: absolute; height: ${px(2.6)}px; margin-top: -${px(1.3)}px; background: ${colors.accent}; border-radius: ${px(2)}px; }
- .trail .pt { position: absolute; width: ${px(10)}px; height: ${px(10)}px; margin: -${px(5)}px 0 0 -${px(5)}px; border-radius: 50%;
+ .trail .marklab { top: 0; transform: none; color: ${colors.accent}; font-family: ${fontStack(fonts, "bold")}; }
+ .trail .seg { position: absolute; left: 0; top: 0; height: ${px(2.6)}px; margin-top: -${px(1.3)}px; background: ${colors.accent}; border-radius: ${px(2)}px; }
+ .trail .seg.gap { height: 0; margin-top: -${px(1)}px; background: none; border-top: ${px(2)}px dotted ${rgba(colors.accent, 0.55)}; border-radius: 0; }
+ .trail .pt { position: absolute; left: 0; top: 0; width: ${px(10)}px; height: ${px(10)}px; margin: -${px(5)}px 0 0 -${px(5)}px; border-radius: 50%;
background: ${colors.accent}; border: ${px(2)}px solid ${colors.card}; }
.trail .pt.q { background: ${colors.card}; border: ${px(2.4)}px solid ${colors.accent}; }
+ .trail .pt.rem { background: ${colors.card}; border: ${px(2.4)}px solid ${colors.ghost}; }
+ .trail .pt.rem.q { border-style: dashed; }
.trail .ring { position: absolute; left: 0; top: 0; width: ${px(20)}px; height: ${px(20)}px; margin: -${px(10)}px 0 0 -${px(10)}px;
border-radius: 50%; border: ${px(3)}px solid ${colors.needle}; }`;
return pageHtml({
@@ -934,7 +1170,7 @@ export function dialFinaleHtml(schedule, render, window, opts = {}) {
const k = size / 524;
const dial = dialParts({
size, ox: portrait ? Math.floor((W - size) / 2) : 0, oy: portrait ? titleH + Math.round(18 * u) + Math.floor((cardH - size) / 2) : Math.floor((H - size) / 2),
- scale: M.scale, cfg, colors, fonts, track, marks, lines, ghosts, prefix: "f", preState: false,
+ scale: M.scale, cfg, colors, fonts, track, marks, lines, ghosts, prefix: "f", preState: false, heaviest: heaviestOf(M),
});
const rw = portrait ? W - Math.round(48 * u) : W - size - Math.round(40 * k);
const top = Math.max(Number(M.totals?.lost) || 0, nums.lost);
diff --git a/umtool/report-to-video/chrome-measure-extras.mjs b/umtool/report-to-video/chrome-measure-extras.mjs
@@ -17,11 +17,12 @@ import { rgba } from "./chrome-deck.mjs";
import { compileCues, cuePageHtml, esc, INSTANT, joinSpans, r4, spanEvents } from "./chrome-cues.mjs";
import {
daysBetween, daysLeftText, daysText, DIET_TAG, dietDays, dietStates, dietTagStep, goalStates, goalText, GOALS_SHELF, jitter, measureBox, measureExtraGeometry, measureOf, MEASURE_BOXES, promiseStripRect, promiseStripType,
- MEASURE_DODGE_MOVE, measurePlacements, monthYear, peakStates, promiseStates, shortDate, streakStates, upSpans, weightText,
+ MEASURE_DODGE_MOVE, measurePlacements, monthYear, peakStates, promiseStates, shortDate, stampNoteClause, stampNoteLine, streakStates, upSpans, weightText,
} from "./measure-extras.mjs";
import { dietTagWidth, MEASURE_RED, resolveMeasureExtra, SHELF_POSITION } from "./modules/measure-extras-settings.mjs";
import { dialFinaleGeometry, dialFinaleHandoff } from "./chrome-instruments.mjs";
import { goalBoard, goalsAt } from "./measure-goals.mjs";
+import { deckAwaySpans, flashCss, flashEvents, flashOn, flashTimes } from "./update-flash.mjs";
/** How each module's panel comes in and goes out, s. */
export const MEASURE_FADE = Object.freeze({ in: 0.35, out: 0.4 });
@@ -203,9 +204,19 @@ export function goalsHtml(schedule, render, opts = {}) {
const paper = cfg.color ?? pal.amber ?? "#E8A33F";
const spans = upSpans(states.map((s) => s.at), cfg, schedule);
const items = [];
+ // THE UPDATE FLASH (update-flash.mjs): a goal set lights the note that lands -- not the first, the stack's entrance.
+ const flashing = flashOn(render, cfg.flash);
+ const away = flashing ? deckAwaySpans(schedule, render) : [];
const { init, cues } = stateCues(states, spans, {
own: (st, j, init) => {
const ev = [];
+ if (flashing && j > 0) {
+ const top = st.notes.find((n) => n.key === st.top);
+ if (top) {
+ init[`s${j}.${top.id}.fl`] = { opacity: 0 };
+ ev.push(...flashEvents(`s${j}.${top.id}.fl`, flashTimes([st.at], { fps: F.fps, away })));
+ }
+ }
for (const n of st.notes) {
const k = `s${j}.${n.id}`;
const to = notePlace(n, n.depth, px, H);
@@ -236,7 +247,9 @@ export function goalsHtml(schedule, render, opts = {}) {
: "";
const count = n.count > 1 ? `<div class="ct" data-k="${k}c">×${n.count}</div>` : "";
const shade = n.depth ? `<div class="sh" style="opacity:${r4(Math.min(0.5, 0.14 * n.depth))}"></div>` : "";
- return `<div class="note${dl ? " due" : ""}" data-k="${k}" style="z-index:${20 - n.depth}"><div class="tape"></div><div class="nh">Goal${n.date ? ` · ${esc(monthYear(n.date))}` : ""}</div><div class="nt">${esc(n.text)}</div>${dl}${count}${shade}</div>`;
+ const fr = n.base ? `<div class="fr">${esc(n.base)}</div>` : "";
+ const fl = flashing && j > 0 && n.key === st.top ? `<div class="fl" data-k="${k}.fl"></div>` : "";
+ return `<div class="note${dl ? " due" : ""}${fr ? " based" : ""}" data-k="${k}" style="z-index:${20 - n.depth}"><div class="tape"></div><div class="nh">Goal${n.date ? ` · ${esc(monthYear(n.date))}` : ""}</div><div class="nt">${esc(n.text)}</div>${fr}${dl}${count}${shade}${fl}</div>`;
}).join("");
const html = `<div class="st" data-k="s${j}">${notes}<div class="hd"><span class="hn">${st.goalsSet}</span> goal${st.goalsSet === 1 ? "" : "s"} set</div></div>`;
items.push({ key: `s${j}`, gate: [`s${j}`, "autoAlpha"], html });
@@ -256,6 +269,9 @@ export function goalsHtml(schedule, render, opts = {}) {
text-transform: uppercase; color: rgba(42, 28, 6, 0.62); }
.nt { font-family: ${DISPLAY}; font-size: ${px(54)}px; line-height: ${px(58)}px; white-space: nowrap; letter-spacing: 0.01em; }
.due .nt { font-size: ${px(44)}px; line-height: ${px(48)}px; }
+ .based .nt { font-size: ${px(46)}px; line-height: ${px(50)}px; }
+ .based.due .nt { font-size: ${px(38)}px; line-height: ${px(41)}px; }
+ .fr { font-family: ${DISPLAY}; font-size: ${px(22)}px; line-height: ${px(25)}px; color: rgba(42, 28, 6, 0.78); white-space: nowrap; letter-spacing: 0.02em; }
.dl { font-family: 'DeckSansBold', sans-serif; font-size: ${px(19)}px; line-height: ${px(23)}px; color: #7d150c; white-space: nowrap; }
.dl2 { font-family: 'DeckSansBold', sans-serif; font-size: ${px(18)}px; line-height: ${px(22)}px; color: rgba(42, 28, 6, 0.8); white-space: nowrap; }
/* The count sits in the note's top strip: what shows of a note further down the pile. */
@@ -266,13 +282,27 @@ export function goalsHtml(schedule, render, opts = {}) {
.hd { position: absolute; left: ${px(10)}px; bottom: ${px(4)}px; height: ${px(32)}px; padding: 0 ${px(14)}px; border-radius: ${px(16)}px;
background: ${rgba(pal.bg, 0.88)}; color: ${pal.muted}; font-family: 'DeckSansBold', sans-serif; font-size: ${px(17)}px;
line-height: ${px(32)}px; letter-spacing: 0.12em; text-transform: uppercase; white-space: nowrap; }
- .hn { color: ${paper}; font-family: ${DISPLAY}; font-size: ${px(22)}px; letter-spacing: 0.02em; }`;
+ .hn { color: ${paper}; font-family: ${DISPLAY}; font-size: ${px(22)}px; letter-spacing: 0.02em; }${flashing ? `
+ ${flashCss(".note .fl", paper, { radius: `${px(5)}px`, width: Math.max(2, Math.round(px(3))), inset: `-${px(5)}px` })}` : ""}`;
const body = `<div id="pn" data-k="pn">
${blocks.join("\n ")}
</div>`;
return { html: page("goals", schedule, opts, F, css, body, init, cues, states.map((_, j) => `s${j}`), render), items };
}
+/** A back card's padding (design px): its sides and foot, and the top it leaves to the ×n badge. */
+export const GOALS_BACK = Object.freeze({ pad: 8, top: 30, max: 24, min: 17 });
+
+/**
+ * A back card's words a size that fits `room` (design px, the strip that shows) when they can -- the display face
+ * at ~0.5 em a letter, 24 px at most -- and 17 px at the least: below that they keep their size, right-aligned, and
+ * their left goes under the card in front.
+ */
+export function backTextSize(text, room) {
+ const n = Math.max(1, [...String(text)].length);
+ return Math.max(GOALS_BACK.min, Math.min(GOALS_BACK.max, Math.floor(room / (0.5 * n))));
+}
+
/**
* The goal stack ON THE SHELF (`goals.position: "shelf"`): the count of goals
* set in a column at the left, then the notes -- the same paper, tape, shadow
@@ -294,6 +324,8 @@ function goalsShelfHtml(schedule, render, opts, cfg, states) {
const room = geo.width / F.k - G.count - G.gap - G.card;
const step = max > 1 ? Math.max(G.back, Math.min(G.card + G.step, room / (max - 1))) : 0;
const backs = step < G.card;
+ // The strip of a back card that shows beside the card in front (design px), less its padding.
+ const strip = Math.min(step, G.card) - 14 - 2 * GOALS_BACK.pad;
const place = (note, depth) => ({
x: px(G.count + G.gap + depth * step),
y: Math.round(px(6) + note.dx * 0.15 * F.k + (depth ? px(1) : 0)),
@@ -304,9 +336,22 @@ function goalsShelfHtml(schedule, render, opts, cfg, states) {
// THE ORDER ON THE SHELF is the dial's (shelfGoalStates): the goal board's headline -- the closest goal in force --
// in front with "+N more" for the others in force, the rest by how recently he set them, a missed goal struck.
const shelfStates = shelfGoalStates(schedule, states);
+ // THE UPDATE FLASH (update-flash.mjs): a goal set lights the note that lands -- not the first, the shelf's entrance.
+ const flashing = flashOn(render, cfg.flash);
+ const away = flashing ? deckAwaySpans(schedule, render) : [];
+ const flashKey = (st, j) => {
+ if (!flashing || j === 0 || !st.top) return null;
+ const top = st.notes.find((n) => n.key === st.top);
+ return top ? `s${j}.${top.id}.fl` : null;
+ };
const { init, cues } = stateCues(shelfStates, spans, {
own: (st, j, init) => {
const ev = [];
+ const fk = flashKey(st, j);
+ if (fk) {
+ init[fk] = { opacity: 0 };
+ ev.push(...flashEvents(fk, flashTimes([st.at], { fps: F.fps, away })));
+ }
for (const n of st.notes) {
const k = `s${j}.${n.id}`;
const to = place(n, n.depth);
@@ -348,13 +393,18 @@ function goalsShelfHtml(schedule, render, opts, cfg, states) {
const more = n.depth === 0 && st.headline && Number.isFinite(st.active) && st.active > 1 ? `<div class="mo">+${st.active - 1} more</div>` : "";
const front = n.depth === 0 || !backs;
const crossing = backs && n.prev === 0 && n.depth > 0;
- const face = `<div class="nf"${crossing ? ` data-k="${k}f"` : ""} style="opacity:${front || crossing ? 1 : 0}"><div class="nh">Goal${n.date ? ` · ${esc(monthYear(n.date))}` : ""}</div><div class="nt">${esc(n.text)}</div>${dl}</div>`;
+ const fr = n.base ? `<div class="fr">${esc(n.base)}</div>` : "";
+ const face = `<div class="nf${fr ? " based" : ""}"${crossing ? ` data-k="${k}f"` : ""} style="opacity:${front || crossing ? 1 : 0}"><div class="nh">Goal${n.date ? ` · ${esc(monthYear(n.date))}` : ""}</div><div class="nt">${esc(n.text)}</div>${fr}${dl}</div>`;
+ // A BACK CARD's words end at its right edge and are never cut there (11 Nov): the right end is what tells one
+ // goal from another ("LOSE 1…" read as any of three). Sized to fit the strip that shows when they can
+ // (backTextSize); when they cannot, it is their LEFT that goes under the card in front.
const back = backs && n.depth > 0
- ? `<div class="nb"${crossing ? ` data-k="${k}b"` : ""} style="opacity:${crossing ? 0 : 1}"><div class="bt">${esc(n.text)}</div>${n.date ? `<div class="bh">${esc(monthYear(n.date))}</div>` : ""}</div>`
+ ? `<div class="nb"${crossing ? ` data-k="${k}b"` : ""} style="opacity:${crossing ? 0 : 1}"><div class="bt" style="font-size:${px(backTextSize(n.text, strip))}px">${esc(n.text)}</div>${n.base ? `<div class="bf">${esc(n.base)}</div>` : ""}${n.date ? `<div class="bh">${esc(monthYear(n.date))}</div>` : ""}</div>`
: "";
// Missed (the board's, held as the dial holds it): struck in red, MISSED on it.
const miss = st.missed?.includes(n.key) ? `<div class="mx"></div><div class="ms">Missed</div>` : "";
- return `<div class="note${miss ? " missed" : ""}" data-k="${k}" style="z-index:${20 - n.depth}"><div class="tape"></div>${face}${back}${count}${more}${miss}</div>`;
+ const fl = flashKey(st, j) === `${k}.fl` ? `<div class="fl" data-k="${k}.fl"></div>` : "";
+ return `<div class="note${miss ? " missed" : ""}" data-k="${k}" style="z-index:${20 - n.depth}"><div class="tape"></div>${face}${back}${count}${more}${miss}${fl}</div>`;
}).join("");
const html = `<div class="st" data-k="s${j}"><div class="gc"><div class="gn" data-k="s${j}.c">${st.goalsSet}</div><div class="gl">goal${st.goalsSet === 1 ? "" : "s"} set</div></div>${notes}</div>`;
items.push({ key: `s${j}`, gate: [`s${j}`, "autoAlpha"], html });
@@ -374,16 +424,19 @@ function goalsShelfHtml(schedule, render, opts, cfg, states) {
.tape { position: absolute; left: 50%; top: ${px(-6)}px; width: ${px(70)}px; height: ${px(18)}px; margin-left: ${px(-35)}px;
background: rgba(255, 255, 255, 0.38); transform: rotate(-3deg); }
.nf { position: absolute; inset: 0; padding: ${px(8)}px ${px(14)}px; display: flex; flex-direction: column; justify-content: center; gap: ${px(1)}px; overflow: hidden; }
- .nb { position: absolute; right: 0; top: 0; bottom: 0; width: ${px(Math.min(step, G.card) - 14)}px; padding: 0 ${px(6)}px;
- display: flex; flex-direction: column; justify-content: center; align-items: center; overflow: hidden; }
+ .nb { position: absolute; left: 0; right: 0; top: 0; bottom: 0; padding: ${px(GOALS_BACK.top)}px ${px(GOALS_BACK.pad)}px ${px(GOALS_BACK.pad)}px;
+ display: flex; flex-direction: column; justify-content: center; align-items: flex-end; text-align: right; overflow: hidden; }
.nh { font-family: 'DeckSansBold', sans-serif; font-size: ${px(13)}px; line-height: ${px(16)}px; letter-spacing: 0.14em;
text-transform: uppercase; color: rgba(42, 28, 6, 0.62); white-space: nowrap; }
.nt { font-family: ${DISPLAY}; font-size: ${px(40)}px; line-height: ${px(44)}px; white-space: nowrap; letter-spacing: 0.01em; }
.dl { font-family: 'DeckSansBold', sans-serif; font-size: ${px(13)}px; line-height: ${px(16)}px; color: #7d150c; white-space: nowrap;
overflow: hidden; text-overflow: ellipsis; }
- .bt { font-family: ${DISPLAY}; font-size: ${px(24)}px; line-height: ${px(27)}px; white-space: nowrap; max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
+ .bt { font-family: ${DISPLAY}; line-height: 1.12; white-space: nowrap; flex: none; }
+ .bf { font-family: ${DISPLAY}; font-size: ${px(15)}px; line-height: ${px(18)}px; color: rgba(42, 28, 6, 0.78); white-space: nowrap; flex: none; }
.bh { font-family: 'DeckSansBold', sans-serif; font-size: ${px(12)}px; line-height: ${px(15)}px; letter-spacing: 0.1em; text-transform: uppercase;
- color: rgba(42, 28, 6, 0.62); white-space: nowrap; }
+ color: rgba(42, 28, 6, 0.62); white-space: nowrap; flex: none; }
+ .fr { font-family: ${DISPLAY}; font-size: ${px(18)}px; line-height: ${px(20)}px; color: rgba(42, 28, 6, 0.78); white-space: nowrap; letter-spacing: 0.02em; }
+ .nf.based .nt { font-size: ${px(36)}px; line-height: ${px(38)}px; }
.mo { position: absolute; right: ${px(8)}px; bottom: ${px(6)}px; padding: 0 ${px(7)}px; height: ${px(20)}px; border-radius: ${px(10)}px;
background: rgba(42, 28, 6, 0.85); color: ${paper}; font-family: 'DeckSansBold', sans-serif; font-size: ${px(12)}px; line-height: ${px(20)}px; }
.mx { position: absolute; left: ${px(6)}px; right: ${px(6)}px; top: 50%; height: ${px(4)}px; margin-top: ${px(-2)}px; background: ${MEASURE_RED};
@@ -393,7 +446,8 @@ function goalsShelfHtml(schedule, render, opts, cfg, states) {
letter-spacing: 0.1em; text-transform: uppercase; }
.ct { position: absolute; right: ${px(8)}px; top: ${px(5)}px; min-width: ${px(40)}px; height: ${px(24)}px; padding: 0 ${px(7)}px;
border-radius: ${px(12)}px; background: #2a1c06; color: ${paper}; text-align: center;
- font-family: ${DISPLAY}; font-size: ${px(19)}px; line-height: ${px(24)}px; }`;
+ font-family: ${DISPLAY}; font-size: ${px(19)}px; line-height: ${px(24)}px; }${flashing ? `
+ ${flashCss(".note .fl", paper, { radius: `${px(4)}px`, width: Math.max(2, Math.round(px(3))), inset: `-${px(4)}px` })}` : ""}`;
const body = `<div id="pn" data-k="pn">
${blocks.join("\n ")}
</div>`;
@@ -589,7 +643,7 @@ function promiseStrip(states, place, cfg, render, opts, items) {
const claim = r.claim ? `<span class="sp">·</span><span>${esc(cfg.claimVerb)} ${esc(shortDate(r.claim.paidOn ?? r.claim.date))} by @${esc(handleOf(r.claim.speaker, cfg, opts))}</span>` : "";
const o = r.outcome;
const status = o && o.kind !== "kept"
- ? `<span class="no">${o.kind === "refunded" ? "refunded" : "withdrawn"} · no video</span>`
+ ? `<span class="no">${o.kind === "refunded" ? "refunded" : "withdrawn"} · ${esc(stampNoteClause(o))}</span>`
: r.kept ? `<span class="ok">${esc(cfg.kept)}</span>` : `<span class="no">${esc(cfg.broken)}</span>`;
const html = `<div class="sl" data-k="${k}"><span>${esc(r.what)} ${esc(cfg.verb)} ${esc(shortDate(r.said))}</span>${claim}<span class="sp">·</span><b>${esc(days)}</b><span class="sp">·</span>${status}</div>`;
items.push({ key: k, gate: [k, "autoAlpha"], html });
@@ -671,7 +725,7 @@ export function promiseHtml(schedule, render, opts = {}) {
const o = r.outcome;
if (o && o.kind !== "kept") {
const word = o.kind === "refunded" ? "Refunded" : "Withdrawn";
- status = `<div class="stamp ${esc(o.kind)}" data-k="${k}o"><div class="sw">${word}</div><div class="ss">${o.date ? `by ${esc(shortDate(o.date))} · ` : ""}no video</div></div>`;
+ status = `<div class="stamp ${esc(o.kind)}" data-k="${k}o"><div class="sw">${word}</div><div class="ss">${esc(stampNoteLine(o))}</div></div>`;
} else status = `<div class="pill">${esc(r.kept ? cfg.kept : cfg.broken)}</div>`;
let q;
if (r.word) {
@@ -993,6 +1047,21 @@ function dietTagsHtml(schedule, render, opts, cfg, states) {
dayBlocks.get(r.card).push(`<div class="dy" data-k="${k}"><div class="dyn">${r.days}</div><div class="dyl">day${r.days === 1 ? "" : "s"}</div></div>`);
});
}
+ // THE UPDATE FLASH (update-flash.mjs): a new diet -- a new front tag, or new words for it -- lights that tag in its
+ // ink; never the running day count, never the first tag (the badge's entrance).
+ const flashing = flashOn(render, cfg.flash);
+ const flashed = new Set();
+ if (flashing) {
+ const away = deckAwaySpans(schedule, render);
+ states.forEach((st, j) => {
+ const front = st.tags[0]?.id;
+ if (!j || front === undefined || front === states[j - 1].tags[0]?.id) return;
+ const k = `t${front}.fl`;
+ init[k] = { opacity: 0 };
+ flashed.add(front);
+ ev.push(...flashEvents(k, flashTimes([st.at], { fps: F.fps, away })));
+ });
+ }
const { cues } = compileCues(init, ev);
const items = [];
const room = DIET_TAG.width - 44;
@@ -1015,14 +1084,16 @@ function dietTagsHtml(schedule, render, opts, cfg, states) {
? `<div class="bk" data-k="${k}.b"><div class="bl" style="font-size:${px(Math.min(32, tagWordSize(label, step - 30)))}px">${esc(label)}</div>${date ? `<div class="bd">${esc(date)}</div>` : ""}</div>`
: "";
const html = `<div class="tg" data-k="${k}"${fan ? ` style="z-index:${10 + t.id}"` : ""}><div class="dm" data-k="${k}.d"><div class="sw" data-k="${k}.w"><div class="sp${d ? "" : " off"}" data-k="${k}.s">` +
- `<div class="ink" style="color:${ink};border-color:${ink}"><div class="fr"${fan ? ` data-k="${k}.f"` : ""}>${face}</div>${back}</div></div></div></div></div>`;
+ `<div class="ink" style="color:${ink};border-color:${ink}"><div class="fr"${fan ? ` data-k="${k}.f"` : ""}>${face}</div>${back}</div>` +
+ `${flashed.has(t.id) ? `<div class="fl" data-k="${k}.fl" style="color:${ink}"></div>` : ""}</div></div></div></div>`;
items.push({ key: k, gate: [k, "autoAlpha"], html });
return html;
});
const css = `
#pn { position: absolute; inset: 0; visibility: hidden; opacity: 0; }
.tg { position: absolute; left: 0; top: 0; width: ${px(W)}px; height: ${px(DIET_TAG.height)}px; visibility: hidden; opacity: 0;${fan ? " transform-origin: 30% 60%;" : ""} }
- .dm, .sw { position: absolute; inset: 0; }
+ .dm, .sw { position: absolute; inset: 0; }${flashing ? `
+ ${flashCss(".sp > .fl", "currentColor", { radius: `${px(9)}px`, width: Math.max(2, Math.round(px(3))), inset: `-${px(2)}px` })}` : ""}
/* A tag: the stamp's plate and pressed ink, small. The plate is solid; only the ink is pressed. */
.sp { position: absolute; left: ${px(4)}px; top: ${px(4)}px; right: ${px(4)}px; bottom: ${px(4)}px; border-radius: ${px(8)}px;
background: ${rgba(pal.bg, fan ? 0.97 : 0.93)}; padding: ${px(4)}px;
diff --git a/umtool/report-to-video/chrome-posts.mjs b/umtool/report-to-video/chrome-posts.mjs
@@ -22,8 +22,9 @@
// and whether one would overflow depends on how tall each card is, which is
// how its words wrap in the deck's own face. Only the browser knows that, and
// only once the faces are in. So the page measures every card after the fonts
-// load and hands the heights to `postsCues` -- THIS module's function, written
-// into the page by its source text. The plan (every cue, its from, its time)
+// load and hands the heights to `postsPlan` -- THIS module's function, written
+// into the page by its source text (`postsCues` here is the same function, with
+// the first-frame fold handed in). The plan (every cue, its from, its time)
// is the same function the tests call with heights of their choosing; the
// browser holds no logic a test cannot see. The timeline is built, and then
// registered, inside that fonts-loaded callback: the renderer awaits
@@ -34,6 +35,7 @@
import { formatDeckDate } from "./attribution.mjs";
import { pageDuration, postsGeometry, resolveDeck, snapWindow } from "./deck.mjs";
import { mix, rgba } from "./chrome-deck.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
// The window arithmetic is deck.mjs's (pure, and loaded by the build without
// this page module); re-exported for the page's own callers.
@@ -79,6 +81,16 @@ export function windowPosts(schedule, segment) {
* production build turned `postsCues` into `d`, and the page then threw a
* ReferenceError and drew nothing). As a named const of a parenthesised
* function expression, the page's name never depends on the module's.
+ *
+ * The name is half of it. The text is the function's BODY as the bundler left
+ * it, so a module-scope name the body uses (an import, a constant, a helper)
+ * is the minified one there too, and nothing in the page is called that: 11
+ * Nov, `postsCues` called `settleFirstFrame` and the built app's page threw
+ * `h is not defined`, though it embedded `settleFirstFrame` under its own
+ * name. An embedded function reaches NOTHING outside its own body but the
+ * language's globals (and, a page function, the DOM's); what it needs of the
+ * module is a PARAMETER, handed over by the page under the embedded name.
+ * embedded-source.test.mjs holds every embedded function to that.
*/
export function embedFn(name, fn) {
return `const ${name} = (${fn.toString()});`;
@@ -87,7 +99,10 @@ export function embedFn(name, fn) {
/**
* Everything the posts timeline does, as data. PURE and SELF-CONTAINED: the
* page carries this function's own source text and calls it with the heights
- * it measured, so it may reference nothing outside its own body.
+ * it measured, so it may reference nothing outside its own body -- which is
+ * why the first-frame fold (cue-start.mjs settleFirstFrame) is its second
+ * PARAMETER, `settle`, and not the import (embedFn). Module callers use
+ * `postsCues`, which hands it in.
*
* `posts` are `[{ id, appear, out: [a, b] }]` in slot order (oldest first),
* times in the CUT's clock; `heights` are the cards' heights in px; `column`
@@ -109,10 +124,10 @@ export function embedFn(name, fn) {
* @returns {{ tops: number[], init: Record<string, object>,
* cues: Array<{ k: string, at: number, dur: number, from: object, to: object, ease: string, why: string }> }}
*/
-export function postsCues({
+export function postsPlan({
posts, heights, column, gap = 14, enter = 0.55, slide = 0.35, enterX = 624,
glowAt = 0.3, glowUp = 0.18, glowDown = 1.1, glowRest = 0.3, pans = [], panHold = 1.2,
-}) {
+}, settle) {
const R = (v) => Math.round(v * 10000) / 10000;
const MIN = 0.001;
const tops = [];
@@ -195,7 +210,17 @@ export function postsCues({
// keeps every element's own order (and so every from).
cues.sort((x, y) => x.at - y.at || x.n - y.n);
for (const c of cues) delete c.n;
- return { tops, init, cues };
+ return { tops, init, cues: settle(init, cues) };
+}
+
+/**
+ * `postsPlan` with the first-frame fold handed in: the posts timeline as the
+ * page plans it. Never embedded -- it names an import.
+ *
+ * @param {Parameters<typeof postsPlan>[0]} args
+ */
+export function postsCues(args) {
+ return postsPlan(args, settleFirstFrame);
}
/** A card's head: `@handle · Bluesky`, the separator in the deck's accent. */
@@ -428,7 +453,8 @@ export function postsHtml(schedule, render, window, opts = {}) {
const P = JSON.parse(document.getElementById("posts-data").textContent);
const byK = {};
for (const el of document.querySelectorAll("[data-k]")) byK[el.dataset.k] = el;
- ${embedFn("postsCues", postsCues)}
+ ${embedFn("settleFirstFrame", settleFirstFrame)}
+ ${embedFn("postsPlan", postsPlan)}
const params = new URLSearchParams(location.search);
const local = (t) => Math.max(0, Math.min(P.dur, (Number(t) || 0) - P.from));
@@ -478,9 +504,9 @@ export function postsHtml(schedule, render, window, opts = {}) {
return img && !view.hasAttribute("data-crop") ? Math.max(0, Math.round(img.offsetHeight - view.clientHeight)) : 0;
});
document.documentElement.dataset.pans = pans.join(",");
- const plan = postsCues({ posts: P.posts, heights, pans, column: P.column, gap: P.gap,
+ const plan = postsPlan({ posts: P.posts, heights, pans, column: P.column, gap: P.gap,
enter: P.enter, slide: P.slide, enterX: P.enterX, glowAt: P.glowAt,
- glowUp: P.glowUp, glowDown: P.glowDown, glowRest: P.glowRest });
+ glowUp: P.glowUp, glowDown: P.glowDown, glowRest: P.glowRest }, settleFirstFrame);
cards.forEach((c, j) => { c.style.top = plan.tops[j] + "px"; });
for (const k of Object.keys(plan.init)) if (byK[k]) gsap.set(byK[k], plan.init[k]);
// The cues are in the cut's clock; the window plays [from, from + dur] of it.
diff --git a/umtool/report-to-video/chrome-posts.test.mjs b/umtool/report-to-video/chrome-posts.test.mjs
@@ -13,7 +13,7 @@ import test from "node:test";
import { fileURLToPath } from "node:url";
import {
- postDate, postParagraphs, postsCues, postsHtml, postWho, snapWindow, windowPosts,
+ postDate, postParagraphs, postsCues, postsHtml, postsPlan, postWho, snapWindow, windowPosts,
} from "./chrome-posts.mjs";
import { postSchedule, postsGeometry, postWindows, threadShotOf, validatePosts } from "./deck.mjs";
import { postThreadFile } from "./compose-chrome.mjs";
@@ -176,7 +176,8 @@ test("the page's times are postSchedule's: data, enter and leave cues", () => {
near(leave.at + leave.dur, p.out[1], `${p.id} gone`);
});
// The page runs this very function, by its source.
- assert.ok(html.includes(postsCues.toString()));
+ assert.ok(html.includes(postsPlan.toString()));
+ assert.match(html, /const plan = postsPlan\(\{[^;]*\}, settleFirstFrame\);/);
});
test("postsCues: cards stack top-down; when the next would overflow, the oldest slide up and out", () => {
@@ -454,8 +455,7 @@ test("embedFn: the page declares the planner under its own name, whatever the bu
const src = embedFn("postsCues", renamed);
assert.equal(new Function(`${src}; return postsCues(21);`)(), 42);
// And the page the module writes uses it, not a bare toString().
- const { postsCues } = await import("./chrome-posts.mjs");
- assert.match(embedFn("postsCues", postsCues), /^const postsCues = \(function postsCues\(/);
+ assert.match(embedFn("postsPlan", postsPlan), /^const postsPlan = \(function postsPlan\(/);
});
test("a post with a screenshot draws it in place of its text card, its QR cell kept; the page waits for it", () => {
diff --git a/umtool/report-to-video/chrome-stamp.mjs b/umtool/report-to-video/chrome-stamp.mjs
@@ -14,6 +14,7 @@
import { cueTime, cueTimeAfter, pageDuration, stampGeometry, stampsOnFrames } from "./deck.mjs";
import { mix, rgba } from "./chrome-deck.mjs";
import { drawnStamps, resolveFactcheck, STAMP_MOTION } from "./factcheck.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
/** Instant cues still take a millisecond: a zero-duration tween has its own seek rules. */
const INSTANT = 0.001;
@@ -102,7 +103,7 @@ export function stampCues(schedule, render = null) {
freeAt.set(e.k, at + dur);
cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease, why: e.why });
}
- return { init, cues };
+ return { init, cues: settleFirstFrame(init, cues, fps) };
}
/**
diff --git a/umtool/report-to-video/chrome-stats.mjs b/umtool/report-to-video/chrome-stats.mjs
@@ -18,6 +18,7 @@
import { pageDuration, statsGeometry } from "./deck.mjs";
import { rgba } from "./chrome-deck.mjs";
import { STATS_LABELS, STATS_MOTION } from "./stats.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
/** Instant cues still take a millisecond: a zero-duration tween has its own seek rules. */
const INSTANT = 0.001;
@@ -112,7 +113,7 @@ export function statsCues(schedule) {
freeAt.set(e.k, r4(at + dur));
cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease });
}
- return { init, cues };
+ return { init, cues: settleFirstFrame(init, cues, schedule.fps) };
}
/**
diff --git a/umtool/report-to-video/chrome-teaser.mjs b/umtool/report-to-video/chrome-teaser.mjs
@@ -31,6 +31,7 @@ import {
export { TEASER_MOTION };
import { mix, rgba } from "./chrome-deck.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
/**
* The display face: Archivo, a variable font (wght 100–900, wdth 62–125),
@@ -222,7 +223,7 @@ export function teaserCues({ lines, tail = "", seconds, motion = TEASER_MOTION,
}
// `need` is the validator's; the page's data is what it always was.
const { T: _T, need: _need, ...times } = beats;
- return { init, cues, beats: times, scale: beats.scale };
+ return { init, cues: settleFirstFrame(init, cues), beats: times, scale: beats.scale };
}
/** Each role's type: size (px, the most it may be), weight, width (%), tracking (em), and the fit floor. */
diff --git a/umtool/report-to-video/cue-start.mjs b/umtool/report-to-video/cue-start.mjs
@@ -0,0 +1,66 @@
+// THE CUT'S FIRST FRAME (the frame-zero fix, 11 Nov): a cue that takes effect
+// at the cut's first instant belongs in a page's init, not in its cue list.
+//
+// Every cue page sets its init, then builds a paused timeline of fromTo tweens
+// (`immediateRender: false`) and is seeked frame by frame. The renderer's first
+// frame is a seek to 0 -- no change to GSAP, and a tween placed at 0 shows its
+// FROM there anyway -- so a cue at 0 shorter than a frame is drawn on frame 1,
+// never on frame 0. That is how the instruments' column (dial, odometer, trail:
+// chrome-instruments.mjs withDeck) showed for one frame over a cut that opens on
+// the intro: their root is up in init and hidden by an instant cue at 0.
+//
+// LEAF: no imports, so every cue compiler can call it -- and SELF-CONTAINED
+// (no module constant): the posts' page embeds postsPlan, and this with it, in
+// the browser, and hands this to it as a parameter (chrome-posts.mjs embedFn).
+
+/**
+ * Fold every cue that has finished before frame 1 and starts at the cut's
+ * first instant (at or before 0, or where an earlier folded cue on the same
+ * element ended) into init. A cue a frame or longer, or one after a cue on
+ * its element that stays, is left alone: frame 0 then shows its FROM, which is
+ * init, as it should.
+ *
+ * `init` is changed IN PLACE (an entry replaced, never mutated -- entries may
+ * be shared) because several callers read their own init after compiling; the
+ * cue list is returned without the folded cues.
+ *
+ * @template {{ k: string, at: number, dur: number, to: object }} C
+ * @param {Record<string, object>} init
+ * @param {C[]} cues in time order per element (every compiler's output)
+ * @param {number} [fps]
+ * @returns {C[]}
+ */
+export function settleFirstFrame(init, cues, fps = 30) {
+ // At or before this, a time is the cut's first instant.
+ const START_EPS = 1e-4;
+ const frame = 1 / (Number(fps) > 0 ? Number(fps) : 30);
+ /** element -> where its folded cues end; absent once a cue on it stays. */
+ const foldEnd = new Map();
+ const kept = new Set();
+ const out = [];
+ for (const c of cues) {
+ const start = foldEnd.has(c.k) ? foldEnd.get(c.k) : 0;
+ const foldable = !kept.has(c.k) && Number(c.at) <= start + START_EPS && Number(c.at) + Number(c.dur) < frame - START_EPS;
+ if (!foldable) {
+ kept.add(c.k);
+ out.push(c);
+ continue;
+ }
+ init[c.k] = { ...(init[c.k] ?? {}), ...c.to };
+ foldEnd.set(c.k, Number(c.at) + Number(c.dur));
+ }
+ return out;
+}
+
+/**
+ * The cues a renderer's frame 0 cannot show: a change at the cut's first
+ * instant, over before frame 1. Empty for a page settleFirstFrame has seen.
+ *
+ * @param {{ init?: object, cues?: Array<{ k: string, at: number, dur: number, from?: object, to: object }> }} data
+ */
+export function unseenFirstFrameCues(data, fps = 30) {
+ const init = structuredClone(data.init ?? {});
+ const cues = (data.cues ?? []).filter((c) => JSON.stringify(c.from ?? null) !== JSON.stringify(c.to));
+ const settled = settleFirstFrame(init, cues, fps);
+ return cues.filter((c) => !settled.includes(c));
+}
diff --git a/umtool/report-to-video/cues.mjs b/umtool/report-to-video/cues.mjs
@@ -64,6 +64,10 @@ import os from "node:os";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
+import { fetchOnOrigin, readJsonBounded, transcriptsManifestUrl } from "./archive-fetch.mjs";
+
+// For the other readers of an archive that come through this module (linkCheck.mjs).
+export { transcriptsManifestUrl };
// This file lives at <repo>/umtool/report-to-video/, so the corpus a plain
// checkout would have is two levels up. Previously this defaulted to an absolute
@@ -244,9 +248,11 @@ export function createJsonCache({
if (inflight.has(flight)) return inflight.get(flight);
const pending = (async () => {
log(`fetch ${url}`);
- const res = await fetchImpl(url);
+ // An archive is untrusted input (archive-fetch.mjs): the document is
+ // read on the origin it was asked on, and never past 32 MB.
+ const res = await fetchOnOrigin(fetchImpl, url);
if (!res.ok) throw new Error(`GET ${url} -> ${res.status}`);
- const json = await res.json();
+ const json = await readJsonBounded(res, url);
mem.set(url, { version, body: json });
fetchedAt.set(url, Date.now());
if (disk) {
@@ -324,10 +330,11 @@ export function createCueSource({
// terrible one to pay silently, so the direct lookup fails with instructions
// instead and this runs only when asked.
async function resolveSiteId(origin, entry, wanted) {
- const manifest = await getJson(entry.manifests.transcripts);
+ const manifestAt = transcriptsManifestUrl(origin, entry);
+ const manifest = await getJson(manifestAt);
log(`resolving "${wanted}" by scanning ${manifest.pageCount} shard(s) of ${entry.slug}`);
for (let n = 0; n < manifest.pageCount; n += 1) {
- const page = await getJson(pageUrlFrom(entry.manifests.transcripts, n), { version: pagesVersionOf(manifest) });
+ const page = await getJson(pageUrlFrom(manifestAt, n), { version: pagesVersionOf(manifest) });
const hit = page.find(
(r) => r.id === wanted || r.slug === wanted || String(r.webpageUrl ?? "").includes(wanted),
);
@@ -348,7 +355,10 @@ export function createCueSource({
const siteChannel = hints.siteChannel ?? channelSlug;
const siteVideo = hints.siteVideo ?? videoId;
const entry = await channelEntry(origin, siteChannel);
- const manifest = await getJson(entry.manifests.transcripts);
+ // The manifest corpus.json names, when it is on the archive's own origin;
+ // one named elsewhere is not followed — the contract's URL is read instead.
+ const manifestAt = transcriptsManifestUrl(origin, entry);
+ const manifest = await getJson(manifestAt);
const pageNumber = manifest.slugToPage?.[siteVideo];
if (pageNumber === undefined) {
@@ -365,17 +375,17 @@ export function createCueSource({
` up to 8 MB per shard until it matches).\n` +
` Note that a clip's citeUrl is NOT usable here — it may deliberately cite a\n` +
` different recording (a mirror that reads better), whose clock is not the same.`,
- { channelSlug, videoId, tried: [entry.manifests.transcripts] },
+ { channelSlug, videoId, tried: [manifestAt] },
);
}
- const page = await getJson(pageUrlFrom(entry.manifests.transcripts, pageNumber), { version: pagesVersionOf(manifest) });
+ const page = await getJson(pageUrlFrom(manifestAt, pageNumber), { version: pagesVersionOf(manifest) });
const record = page.find((r) => r.id === siteVideo || r.slug === siteVideo);
if (!record) {
throw new CueLookupError(
`${siteChannel}/${siteVideo} is on shard ${pageNumber} per the manifest, but no record ` +
`there has that id — the published archive is inconsistent`,
- { channelSlug, videoId, tried: [pageUrlFrom(entry.manifests.transcripts, pageNumber)] },
+ { channelSlug, videoId, tried: [pageUrlFrom(manifestAt, pageNumber)] },
);
}
return { ...record, from: "http" };
diff --git a/umtool/report-to-video/cues.test.mjs b/umtool/report-to-video/cues.test.mjs
@@ -19,6 +19,7 @@ import {
pageUrlFrom,
siteOriginFromManifest,
} from "./cues.mjs";
+import { readJsonBounded, transcriptsManifestUrl } from "./archive-fetch.mjs";
const ORIGIN = "https://example.pages.dev";
@@ -91,6 +92,17 @@ test("a page URL replaces only the manifest's last segment", () => {
);
});
+test("a shard's URL stays on the manifest's origin, whatever the manifest says its page number is", () => {
+ // slugToPage is the archive's own JSON: a "page number" may be any value.
+ const at = "https://x.dev/transcripts/some-chan/manifest.json";
+ for (const n of ["//evil.example/x", "/../../../../etc/passwd", "@evil.example/", "\\\\evil.example\\x", "https://evil.example/x", "?x=1#y", "$`$'$&", "\n", -1, 1.5, NaN, null, {}, [], "0000.json/../../../corpus"]) {
+ const url = new URL(pageUrlFrom(at, n));
+ assert.equal(url.origin, "https://x.dev", String(n));
+ assert.equal(url.search, "", String(n));
+ assert.equal(url.hash, "", String(n));
+ }
+});
+
test("resolves a video over HTTP with cues intact", async () => {
const got = await source().load("chan", "vid1");
assert.equal(got.from, "http");
@@ -567,6 +579,106 @@ test("prefer:local refuses to fall back rather than cut from other cues", async
});
});
+// --- an archive is untrusted input (demo epic D1 re-review, item 3) ----------
+
+test("a manifest corpus.json names on another origin is not followed: the contract's URL on the archive's own origin is read", async () => {
+ const seen = [];
+ const routes = {
+ ...ROUTES,
+ [`${ORIGIN}/corpus.json`]: { channels: [{ slug: "chan", manifests: { transcripts: "http://127.0.0.1:3001/api/ops/settings" } }] },
+ "http://127.0.0.1:3001/api/ops/settings": { pageCount: 1, slugToPage: { vid1: 0 } },
+ "http://127.0.0.1:3001/api/ops/page-0000.json": [{ ...RECORD, title: "from the other host" }],
+ };
+ const rec = await source({ fetchImpl: stubFetch(routes, seen) }).load("chan", "vid1");
+ assert.equal(rec.title, "A Title");
+ assert.deepEqual(seen, [`${ORIGIN}/corpus.json`, `${ORIGIN}/transcripts/chan/manifest.json`, `${ORIGIN}/transcripts/chan/page-0000.json`]);
+ // The opt-in shard scan walks the same manifest.
+ const seen2 = [];
+ const hit = await source({ fetchImpl: stubFetch(routes, seen2), resolveSiteIds: true }).load("chan", "v94hyv");
+ assert.equal(hit.id, "other");
+ assert.equal(seen2.some((u) => !u.startsWith(ORIGIN)), false);
+});
+
+test("transcriptsManifestUrl: the named manifest on the origin (absolute or relative), else the contract's", () => {
+ const at = (transcripts, slug = "chan") => transcriptsManifestUrl(ORIGIN, { slug, manifests: { transcripts } });
+ assert.equal(at(`${ORIGIN}/transcripts/chan/manifest.json`), `${ORIGIN}/transcripts/chan/manifest.json`);
+ assert.equal(at(`${ORIGIN}/shared/chan/manifest.json`), `${ORIGIN}/shared/chan/manifest.json`, "a same-origin manifest elsewhere in the tree is the archive's to name");
+ assert.equal(at("/transcripts/chan/manifest.json"), `${ORIGIN}/transcripts/chan/manifest.json`);
+ for (const off of [
+ "https://evil.example/transcripts/chan/manifest.json",
+ "http://example.pages.dev/transcripts/chan/manifest.json", // another scheme is another origin
+ "https://example.pages.dev:8443/transcripts/chan/manifest.json",
+ "https://user:pw@example.pages.dev/transcripts/chan/manifest.json",
+ "//evil.example/m.json",
+ "file:///etc/passwd",
+ "",
+ undefined,
+ 42,
+ ]) {
+ assert.equal(at(off), `${ORIGIN}/transcripts/chan/manifest.json`, String(off));
+ }
+ assert.equal(at(undefined, "../../x"), `${ORIGIN}/transcripts/..%2F..%2Fx/manifest.json`, "a slug cannot climb out of the tree");
+ assert.equal(transcriptsManifestUrl(`${ORIGIN}/`, { slug: "chan" }), `${ORIGIN}/transcripts/chan/manifest.json`);
+});
+
+test("the cache reads a document on its own origin: a same-origin redirect is followed, one elsewhere refused unfollowed, more than three refused", async () => {
+ const asked = [];
+ const answers = {
+ [`${ORIGIN}/a.json`]: { status: 301, location: "/b.json" },
+ [`${ORIGIN}/b.json`]: { status: 200, body: { ok: 1 } },
+ [`${ORIGIN}/leave.json`]: { status: 302, location: "http://169.254.169.254/latest/meta-data/" },
+ "http://169.254.169.254/latest/meta-data/": { status: 200, body: { leaked: true } },
+ [`${ORIGIN}/loop.json`]: { status: 302, location: "/loop.json" },
+ };
+ const fetchImpl = async (url, init) => {
+ asked.push(url);
+ assert.equal(init?.redirect, "manual", "every request is asked not to follow redirects");
+ const a = answers[url];
+ if (!a) return new Response("nope", { status: 404 });
+ return new Response(a.body === undefined ? null : JSON.stringify(a.body), { status: a.status, headers: a.location ? { location: a.location } : {} });
+ };
+ const { getJson } = createJsonCache({ cacheDir: null, fetchImpl });
+ assert.deepEqual(await getJson(`${ORIGIN}/a.json`), { ok: 1 });
+ await assert.rejects(() => getJson(`${ORIGIN}/leave.json`), /redirects to http:\/\/169\.254\.169\.254: an archive's documents are read from its own origin only/);
+ assert.equal(asked.includes("http://169.254.169.254/latest/meta-data/"), false);
+ await assert.rejects(() => getJson(`${ORIGIN}/loop.json`), /redirects more than 3 times/);
+ assert.equal(asked.filter((u) => u.endsWith("/loop.json")).length, 4);
+});
+
+test("the cache reads no document past the bound: by its declared length, and as it streams", async () => {
+ const big = 33 * 1024 * 1024;
+ const declared = createJsonCache({
+ cacheDir: null,
+ fetchImpl: async () => new Response("{}", { headers: { "content-length": String(big) } }),
+ });
+ await assert.rejects(() => declared.getJson(`${ORIGIN}/big.json`), /is over 32 MB: an archive document that large is not read/);
+ // No Content-Length: counted as it arrives, and the stream cancelled.
+ let sent = 0;
+ let cancelled = false;
+ const chunk = new Uint8Array(1024 * 1024).fill(0x20);
+ const streaming = createJsonCache({
+ cacheDir: null,
+ fetchImpl: async () =>
+ new Response(
+ new ReadableStream({
+ pull(c) {
+ sent += 1;
+ c.enqueue(chunk);
+ },
+ cancel() {
+ cancelled = true;
+ },
+ }),
+ ),
+ });
+ await assert.rejects(() => streaming.getJson(`${ORIGIN}/endless.json`), /is over 32 MB/);
+ assert.equal(cancelled, true);
+ assert.ok(sent < 40, `stopped reading soon after the bound (${sent} MB sent)`);
+ // A document under it is read as before.
+ assert.deepEqual(await readJsonBounded(new Response(JSON.stringify({ a: 1 })), `${ORIGIN}/x.json`), { a: 1 });
+ await assert.rejects(() => readJsonBounded(new Response("x".repeat(64)), `${ORIGIN}/x.json`, 16), /is over 0 MB/);
+});
+
// --- origin discovery -------------------------------------------------------
test("the archive origin comes from the manifest, in priority order", () => {
diff --git a/umtool/report-to-video/embedded-source.test.mjs b/umtool/report-to-video/embedded-source.test.mjs
@@ -0,0 +1,173 @@
+// A function a page carries by its SOURCE TEXT reaches nothing outside itself.
+//
+// Three places send a module function into a browser as text: `embedFn`
+// (chrome-posts.mjs: the posts' and the feed's planners), shoot-page.mjs's
+// `pageExpression`, and every `page.evaluate(fn)` (playwright sends
+// `fn.toString()`). The text is the function's body as it is in the running
+// process -- and in a built umtool that is the bundler's: every module-scope
+// name (an import, a constant, a helper) is minified, and the page has nothing
+// called that. 11 Nov: `postsCues` called `settleFirstFrame`, the built app's
+// posts preview threw `ReferenceError: h is not defined`, and no unit test saw
+// it, because here the name is its own.
+//
+// So: each embedded function's text is parsed alone and every name it does not
+// declare itself must be a global of the language (or, for a page function,
+// of the DOM). And the sources are scanned, so a function embedded tomorrow is
+// held to it too -- or the scan fails and says to list it here.
+//
+// Run: node --test umtool/report-to-video/embedded-source.test.mjs
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readdirSync, readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import ts from "typescript";
+
+import { embedFn, postsCues, postsPlan } from "./chrome-posts.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
+import { pageExpression } from "./shoot-page.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+
+/** The language's own. */
+const ES = ["Array", "Boolean", "Infinity", "JSON", "Map", "Math", "NaN", "Number", "Object", "Set", "String", "isFinite", "parseFloat", "parseInt"];
+/** What a page has besides. */
+const DOM = ["document", "getComputedStyle", "window"];
+
+/**
+ * Every function sent to a page by name: module -> its functions, and whether
+ * they run on a document (`dom`) or are pure. `embedFn` and `page.evaluate`
+ * arguments found in the sources must all be here (the scan below).
+ */
+const EMBEDDED = {
+ "chrome-posts.mjs": { fns: ["postsPlan"] },
+ "cue-start.mjs": { fns: ["settleFirstFrame"] },
+ "chrome-feed.mjs": { fns: ["feedCues", "feedShotRoom", "feedShotLone", "feedShotWhole"] },
+ "post-clock.mjs": { dom: true, fns: ["mountClock", "setClockState", "measureClockPlace"] },
+ "read-follow.mjs": { dom: true, fns: ["measureFollow", "applyFollowState"] },
+ "post-link-visit.mjs": { dom: true, fns: ["applyVisitState"] },
+ "post-join.mjs": { dom: true, fns: ["applyJoinState"] },
+ "post-branch-map.mjs": { dom: true, fns: ["applyMapState"] },
+ "post-caption.mjs": { dom: true, fns: ["mountCaptions", "measureCaptionWords", "setCaptionState"] },
+ "post-slam.mjs": { dom: true, fns: ["mountSlams", "setSlamState"] },
+ "post-progress.mjs": { dom: true, fns: ["mountProgress", "measureProgressPlace", "setProgressState"] },
+};
+const LISTED = new Set(Object.values(EMBEDDED).flatMap((m) => m.fns));
+
+/**
+ * The names an expression's text uses and does not declare, by the compiler's
+ * own name resolution with no library at all (so `Math` is one of them).
+ */
+function freeNames(expr) {
+ const file = "/embedded.ts";
+ const sf = ts.createSourceFile(file, `const __embedded = (${expr});\nexport {};\n`, ts.ScriptTarget.ES2022, true, ts.ScriptKind.TS);
+ const host = {
+ getSourceFile: (f) => (f === file ? sf : undefined),
+ getDefaultLibFileName: () => "lib.d.ts",
+ writeFile() {},
+ getCurrentDirectory: () => "/",
+ getCanonicalFileName: (f) => f,
+ useCaseSensitiveFileNames: () => true,
+ getNewLine: () => "\n",
+ fileExists: (f) => f === file,
+ readFile: () => undefined,
+ };
+ const program = ts.createProgram([file], { noLib: true, noEmit: true, types: [], target: ts.ScriptTarget.ES2022 }, host);
+ assert.deepEqual(program.getSyntacticDiagnostics(sf).map((d) => ts.flattenDiagnosticMessageText(d.messageText, "\n")), [], "the text parses");
+ const names = new Set();
+ for (const d of program.getSemanticDiagnostics(sf)) {
+ const m = /^Cannot find name '([^']+)'/.exec(ts.flattenDiagnosticMessageText(d.messageText, "\n"));
+ if (m) names.add(m[1]);
+ }
+ return [...names].sort();
+}
+
+const outside = (expr, allowed) => freeNames(expr).filter((n) => !allowed.includes(n));
+
+test("freeNames: a name the text does not declare is found; its parameters, locals and own name are not", () => {
+ assert.deepEqual(freeNames("function f(a, { b = 1 }) { const c = a + b; return f(c) + outer + Math.max(1, helper(a)); }"), ["Math", "helper", "outer"]);
+ assert.deepEqual(freeNames("(a) => { for (const k of Object.keys(a)) if (typeof gone === 'undefined') return k; }"), ["Object", "gone"]);
+ // What the bundler makes of a module function that calls an import.
+ assert.deepEqual(outside("function d(a){return{cues:h(a)}}", ES), ["h"]);
+});
+
+for (const [mod, { fns, dom }] of Object.entries(EMBEDDED)) {
+ test(`${mod}: ${fns.join(", ")} -- nothing outside the function's own body but ${dom ? "the language's and the DOM's" : "the language's"} globals`, async () => {
+ const m = await import(`./${mod}`);
+ for (const name of fns) {
+ assert.equal(typeof m[name], "function", `${mod} exports ${name}`);
+ assert.deepEqual(outside(m[name].toString(), dom ? [...ES, ...DOM] : ES), [],
+ `${name} is sent to a page as its source text: a module-scope name in it is minified in a built umtool and undefined in the page -- hand it in as a parameter`);
+ }
+ });
+}
+
+test("shoot-page: the expression it sends declares every function it calls", () => {
+ assert.deepEqual(outside(pageExpression({ quote: "q" }), [...ES, ...DOM, "CSS"]), []);
+});
+
+test("the posts' page: its planner runs on its text alone, under names no module has, and is the module's plan", () => {
+ // The page's own lines, in a scope with nothing of this module in it.
+ const run = new Function("args", `${embedFn("settleFirstFrame", settleFirstFrame)}\n${embedFn("postsPlan", postsPlan)}\nreturn postsPlan(args, settleFirstFrame);`);
+ const args = {
+ posts: [{ id: "a", appear: 0, out: [8, 8.5] }, { id: "b", appear: 3, out: [8, 8.5] }, { id: "c", appear: 5, out: [8, 8.5] }],
+ heights: [300, 300, 300], pans: [0, 120, 0], column: 700,
+ };
+ const plan = run(structuredClone(args));
+ assert.deepEqual(plan, postsCues(structuredClone(args)));
+ assert.ok(plan.cues.length > 6);
+ // The first card's entrance starts at the cut's first instant and is a real move: it stays a cue.
+ assert.ok(plan.cues.some((c) => c.k === "c0" && c.at === 0));
+});
+
+/** Every call in a source file, with its callee's last name. */
+function callsIn(file) {
+ const sf = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.ES2022, true, ts.ScriptKind.JS);
+ const out = [];
+ const walk = (node) => {
+ if (ts.isCallExpression(node)) {
+ const callee = ts.isPropertyAccessExpression(node.expression) ? node.expression.name.text : ts.isIdentifier(node.expression) ? node.expression.text : null;
+ if (callee) out.push({ callee, node, sf });
+ }
+ ts.forEachChild(node, walk);
+ };
+ walk(sf);
+ return out;
+}
+
+const SOURCES = [HERE, path.join(HERE, "modules")]
+ .flatMap((dir) => readdirSync(dir).filter((f) => f.endsWith(".mjs") && !f.endsWith(".test.mjs")).map((f) => path.join(dir, f)));
+
+test("the scan: every function a source embeds (embedFn, page.evaluate) is listed above, and an inline one is self-contained", () => {
+ let embeds = 0;
+ let evaluates = 0;
+ for (const file of SOURCES) {
+ const rel = path.relative(HERE, file);
+ for (const { callee, node, sf } of callsIn(file)) {
+ const at = () => `${rel}:${sf.getLineAndCharacterOfPosition(node.getStart()).line + 1}`;
+ if (callee === "embedFn" && node.arguments.length === 2) {
+ const fn = node.arguments[1];
+ assert.ok(ts.isIdentifier(fn), `${at()}: embedFn takes a module function by name`);
+ assert.ok(LISTED.has(fn.text), `${at()}: ${fn.text} is embedded in a page -- list it in EMBEDDED (embedded-source.test.mjs)`);
+ embeds += 1;
+ }
+ if (callee === "evaluate" && node.arguments.length) {
+ const fn = node.arguments[0];
+ evaluates += 1;
+ if (ts.isIdentifier(fn)) {
+ assert.ok(LISTED.has(fn.text), `${at()}: ${fn.text} is sent to a page -- list it in EMBEDDED (embedded-source.test.mjs)`);
+ } else if (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) {
+ assert.deepEqual(outside(fn.getText(sf), [...ES, ...DOM]), [], `${at()}: the function sent to the page uses a name from outside itself`);
+ } else {
+ // Text built here: a literal, or shoot-page's expression (its own test above).
+ const text = fn.getText(sf);
+ assert.ok(ts.isStringLiteralLike(fn) || /^pageExpression\(/.test(text), `${at()}: page.evaluate(${text.slice(0, 40)}) -- neither a function nor a known expression`);
+ }
+ }
+ }
+ }
+ // The scan found what is there today (a regex that stopped matching would pass on nothing).
+ assert.ok(embeds >= 5, `embedFn calls found: ${embeds}`);
+ assert.ok(evaluates >= 40, `page.evaluate calls found: ${evaluates}`);
+});
diff --git a/umtool/report-to-video/fetch-via-editor.mjs b/umtool/report-to-video/fetch-via-editor.mjs
@@ -292,6 +292,9 @@ if (wantAll) {
items: local.items,
requestedBy: "umtool",
manifest: manifestId,
+ // The archive the cut cites (demo epic D1): a CONNECTED one registers a
+ // channel the editor does not hold as remote-only; any other is ignored.
+ ...(/^https?:\/\//.test(String(provenance.siteOrigin ?? "")) ? { archive: String(provenance.siteOrigin).trim().replace(/\/+$/, "") } : {}),
...(maxHeight !== undefined ? { maxHeight } : {}),
...storedUrl,
}),
diff --git a/umtool/report-to-video/fixtures/measure-remembered/measure.json b/umtool/report-to-video/fixtures/measure-remembered/measure.json
@@ -0,0 +1,249 @@
+{
+ "_fixture": "rev9-a7's moment for the dial's remembered-weight looks (11 Nov): 342.9 stated (21 Mar 2013), LOSE 75 in force, ≈390 remembered as of 24 Feb 2023 -- his heaviest (totals.peakDrift) -- and a 368 as of 2008 that is not.",
+ "version": 1,
+ "unit": "lb",
+ "scale": {
+ "min": 220,
+ "max": 400
+ },
+ "asOfRender": "2026-11-11",
+ "scopes": [
+ "weight"
+ ],
+ "events": [
+ {
+ "t": 1,
+ "row": "w1",
+ "scope": "weight",
+ "kind": "stated",
+ "value": 342.9,
+ "qualifier": null,
+ "date": "2013-03-21",
+ "asOf": null,
+ "display": "342.9 lb"
+ },
+ {
+ "t": 1.5,
+ "row": "g1",
+ "scope": "weight",
+ "kind": "goalLoss",
+ "value": -75,
+ "qualifier": null,
+ "date": "2023-07-26",
+ "asOf": null,
+ "display": "lose 75",
+ "deadline": null,
+ "due": null
+ },
+ {
+ "t": 3,
+ "row": "w21",
+ "scope": "weight",
+ "kind": "remembered",
+ "value": 390,
+ "qualifier": "≈",
+ "date": "2023-09-29",
+ "asOf": "2023-02-24",
+ "display": "≈390 lb"
+ },
+ {
+ "t": 8,
+ "row": "w35",
+ "scope": "weight",
+ "kind": "remembered",
+ "value": 368,
+ "qualifier": null,
+ "date": "2024-01-10",
+ "asOf": "2008-06-30",
+ "display": "368 lb"
+ }
+ ],
+ "hidden": [],
+ "state": [
+ {
+ "t": 0,
+ "current": null,
+ "remembered": [],
+ "goal": null,
+ "goals": [],
+ "lost": {
+ "total": 0,
+ "runs": []
+ },
+ "net": null
+ },
+ {
+ "t": 1,
+ "current": {
+ "value": 342.9,
+ "qualifier": null,
+ "row": "w1",
+ "date": "2013-03-21"
+ },
+ "remembered": [],
+ "goal": null,
+ "goals": [],
+ "lost": {
+ "total": 0,
+ "runs": []
+ },
+ "net": null
+ },
+ {
+ "t": 1.5,
+ "current": {
+ "value": 342.9,
+ "qualifier": null,
+ "row": "w1",
+ "date": "2013-03-21"
+ },
+ "remembered": [],
+ "goal": {
+ "value": 267.9,
+ "loss": 75,
+ "deadline": null,
+ "due": null,
+ "row": "g1",
+ "display": "lose 75",
+ "base": {
+ "value": 342.9,
+ "row": "w1",
+ "from": "stated"
+ }
+ },
+ "goals": [
+ {
+ "value": 267.9,
+ "loss": 75,
+ "deadline": null,
+ "due": null,
+ "row": "g1",
+ "display": "lose 75",
+ "base": {
+ "value": 342.9,
+ "row": "w1",
+ "from": "stated"
+ }
+ }
+ ],
+ "lost": {
+ "total": 0,
+ "runs": []
+ },
+ "net": null
+ },
+ {
+ "t": 3,
+ "current": {
+ "value": 342.9,
+ "qualifier": null,
+ "row": "w1",
+ "date": "2013-03-21"
+ },
+ "remembered": [
+ {
+ "value": 390,
+ "asOf": "2023-02-24",
+ "row": "w21"
+ }
+ ],
+ "goal": {
+ "value": 267.9,
+ "loss": 75,
+ "deadline": null,
+ "due": null,
+ "row": "g1",
+ "display": "lose 75",
+ "base": {
+ "value": 342.9,
+ "row": "w1",
+ "from": "stated"
+ }
+ },
+ "goals": [
+ {
+ "value": 267.9,
+ "loss": 75,
+ "deadline": null,
+ "due": null,
+ "row": "g1",
+ "display": "lose 75",
+ "base": {
+ "value": 342.9,
+ "row": "w1",
+ "from": "stated"
+ }
+ }
+ ],
+ "lost": {
+ "total": 0,
+ "runs": []
+ },
+ "net": null
+ },
+ {
+ "t": 8,
+ "current": {
+ "value": 342.9,
+ "qualifier": null,
+ "row": "w1",
+ "date": "2013-03-21"
+ },
+ "remembered": [
+ {
+ "value": 390,
+ "asOf": "2023-02-24",
+ "row": "w21"
+ },
+ {
+ "value": 368,
+ "asOf": "2008-06-30",
+ "row": "w35"
+ }
+ ],
+ "goal": {
+ "value": 267.9,
+ "loss": 75,
+ "deadline": null,
+ "due": null,
+ "row": "g1",
+ "display": "lose 75",
+ "base": {
+ "value": 342.9,
+ "row": "w1",
+ "from": "stated"
+ }
+ },
+ "goals": [
+ {
+ "value": 267.9,
+ "loss": 75,
+ "deadline": null,
+ "due": null,
+ "row": "g1",
+ "display": "lose 75",
+ "base": {
+ "value": 342.9,
+ "row": "w1",
+ "from": "stated"
+ }
+ }
+ ],
+ "lost": {
+ "total": 0,
+ "runs": []
+ },
+ "net": null
+ }
+ ],
+ "totals": {
+ "lost": 0,
+ "peakDrift": [
+ 390
+ ],
+ "under300": {
+ "said": 0,
+ "rows": []
+ }
+ }
+}
+\ No newline at end of file
diff --git a/umtool/report-to-video/frame-zero.test.mjs b/umtool/report-to-video/frame-zero.test.mjs
@@ -0,0 +1,88 @@
+// THE CUT'S FIRST FRAME (cue-start.mjs): a page a renderer seeks to 0 draws its
+// init there, so whatever the cut is at its first instant must be IN init. The
+// instruments' column (dial, odometer, trail) was up in init and hidden by an
+// instant cue at 0: over a cut that opens on the intro, frame 0 showed the
+// gauge, the counter and the chart strip before the wordmark (rev9-a6/a7, 11 Nov).
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { estimateSchedule } from "./deck.mjs";
+import { dialHtml, odometerHtml, trailHtml } from "./chrome-instruments.mjs";
+import { settleFirstFrame, unseenFirstFrameCues } from "./cue-start.mjs";
+import { cueList } from "./measure-draw.mjs";
+import { compileCues } from "./chrome-cues.mjs";
+import { statsCues } from "./chrome-stats.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const MEASURE = JSON.parse(readFileSync(path.join(HERE, "fixtures", "measure-dial", "measure.json"), "utf8"));
+const FPS = 30;
+const RENDER = {
+ width: 1920, height: 1080, fps: FPS, transition: 0.4,
+ palette: { bg: "#0F1312", fg: "#EDF0EC", muted: "#98A29B", accent: "#22AB83", amber: "#E8A33F" },
+ chrome: { engine: "hyperframes", layout: "deck", deck: { dial: true, odometer: true, trail: true, qr: { show: false }, finale: { video: "side", totals: false } } },
+};
+const fonts = { DeckSans: "assets/DeckSans.ttf", DeckSansBold: "assets/DeckSansBold.ttf" };
+
+/** The instruments' fixture cut, opening on the intro (selectVariant's entry: the deck hides over it). */
+function introCut() {
+ const timeline = Array.from({ length: 9 }, (_, i) => ({
+ type: "clip", id: `c${i + 1}`, video: "vidx", start: 10 * i, end: 10 * i + (i === 8 ? 14 : 8), cite: 1, section: 0,
+ quote: "q", onscreen: { title: `Clip ${i + 1}` }, ...(i === 8 ? { layout: "finale" } : {}),
+ }));
+ timeline.unshift({ type: "intro", id: "brand-intro", style: "boot-dark", seconds: 4.75, heading: "Intro" });
+ const manifest = { slug: "m", title: "M", provenance: {}, render: RENDER, timeline };
+ const schedule = { ...estimateSchedule(manifest), measure: MEASURE };
+ assert.equal(schedule.segments[0].hideDeck, true, "the intro hides the deck");
+ return schedule;
+}
+
+const dataOf = (html, id) => JSON.parse(new RegExp(`<script id="${id}-data" type="application/json">(.*?)</script>`, "s").exec(html)[1]);
+
+test("over an intro the instruments are hidden from frame 0: their root is down in init, with no instant cue at 0", () => {
+ const schedule = introCut();
+ for (const [id, html] of [["dial", dialHtml(schedule, RENDER, { fonts })], ["odometer", odometerHtml(schedule, RENDER, { fonts })], ["trail", trailHtml(schedule, RENDER, { fonts })]]) {
+ const data = dataOf(html, id);
+ assert.deepEqual(data.init.rt, { autoAlpha: 0 }, `${id}: hidden at the cut's first instant`);
+ assert.deepEqual(unseenFirstFrameCues(data, FPS), [], `${id}: no change at 0 that frame 0 cannot show`);
+ // And up again with the deck, after the intro: the first cue on the root shows it.
+ const first = data.cues.find((c) => c.k === "rt");
+ assert.ok(first.at > 4, `${id}: the column comes up after the intro (${first.at})`);
+ assert.deepEqual(first.to, { autoAlpha: 1 });
+ }
+});
+
+test("settleFirstFrame folds what happens at the first instant into init, and leaves every real move alone", () => {
+ const init = { a: { autoAlpha: 1 }, b: { opacity: 0 }, c: { x: 0 } };
+ const shared = init.a;
+ const cues = [
+ { k: "a", at: 0, dur: 0.001, from: { autoAlpha: 1 }, to: { autoAlpha: 0 } },
+ { k: "a", at: 0.001, dur: 0.001, from: { autoAlpha: 0 }, to: { autoAlpha: 0.5 } }, // chained after the first, still before frame 1
+ { k: "b", at: 0, dur: 0.4, from: { opacity: 0 }, to: { opacity: 1 } }, // a fade from 0: frame 0 is its from
+ { k: "b", at: 0.4, dur: 0.001, from: { opacity: 1 }, to: { opacity: 0 } },
+ { k: "c", at: 0.5, dur: 0.001, from: { x: 0 }, to: { x: 5 } },
+ ];
+ const out = settleFirstFrame(init, cues, 30);
+ assert.deepEqual(init.a, { autoAlpha: 0.5 });
+ assert.deepEqual(shared, { autoAlpha: 1 }, "an init entry is replaced, never mutated (entries may be shared)");
+ assert.deepEqual(out.map((c) => `${c.k}@${c.at}`), ["b@0", "b@0.4", "c@0.5"]);
+});
+
+test("every cue compiler settles the first frame: cueList, compileCues, the stats panel", () => {
+ const L = cueList(FPS);
+ L.set("rt", { autoAlpha: 1 });
+ L.add("rt", 0, 0, { autoAlpha: 0 });
+ L.add("rt", 5, 0.45, { autoAlpha: 1 });
+ const built = L.build();
+ assert.deepEqual(built.init.rt, { autoAlpha: 0 });
+ assert.deepEqual(built.cues.map((c) => c.at), [5]);
+ const cc = compileCues({ x: { autoAlpha: 0 } }, [{ k: "x", at: 0, dur: 0, to: { autoAlpha: 1 }, ease: "none" }]);
+ assert.deepEqual(cc.init.x, { autoAlpha: 1 });
+ assert.equal(cc.cues.length, 0);
+ // A stat card shown from the cut's first instant (v7gkv5w-poker-2's s0_0): up on frame 0, not frame 1.
+ const st = statsCues({ fps: FPS, stats: { clips: [{ in: 0, out: 6, states: [{ at: 0 }, { at: 3 }] }] } });
+ assert.deepEqual(unseenFirstFrameCues(st, FPS), []);
+ assert.equal(st.init.s0_0.autoAlpha, 1);
+});
diff --git a/umtool/report-to-video/fx.mjs b/umtool/report-to-video/fx.mjs
@@ -38,6 +38,7 @@
import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs";
import { offsetIn, sourceAtOffset } from "./gaps.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
/** Each effect's key under `render.chrome.fx`, in the order the page stacks them (later on top). */
export const FX_KEYS = Object.freeze(["scrubber", "receipts", "zoom", "kineticQuote", "redact", "odometer", "punchIn", "thenNow", "whip", "glitch"]);
@@ -1053,7 +1054,7 @@ export function compileCues(init, events) {
freeAt.set(e.k, r4(at + dur));
cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease });
}
- return cues;
+ return settleFirstFrame(init, cues);
}
/** An object's numbers with -0 as 0: the cue list is data, and JSON has no -0. */
diff --git a/umtool/report-to-video/goal-base-max-days.test.mjs b/umtool/report-to-video/goal-base-max-days.test.mjs
@@ -0,0 +1,89 @@
+// `deck.goals.baseMaxDays` (rev9-a9, 12 Nov): a loss goal's base is the latest weight he gave by the goal's date --
+// however long before. On the real record that put "(FROM 368)" on a goal set eight years after he said 368. With
+// the knob a base counts only when its weight was SAID at most that many days before the goal; a staler one is no
+// base -- no "(FROM …)" on the note, no target and no tick on the dial. Unset, every base counts, as before.
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { goalMarks, goalWords } from "./chrome-instruments.mjs";
+import { estimateSchedule, validateChrome } from "./deck.mjs";
+import { goalStates } from "./measure-extras.mjs";
+import { goalBoard } from "./measure-goals.mjs";
+import { goalBaseMaxDays, measureSlice } from "./measure-slice.mjs";
+
+const PAL = { bg: "#0F1312", fg: "#EDF0EC", muted: "#98A29B", accent: "#22AB83", amber: "#E8A33F" };
+const render = (goals) => ({ width: 1920, height: 1080, fps: 30, transition: 0.4, palette: PAL,
+ chrome: { engine: "hyperframes", layout: "deck", deck: { measure: { scopes: ["weight"], scale: { min: 100, max: 400 }, asOf: "2026-11-12" }, ...(goals === undefined ? {} : { goals }) } } });
+const schema = { kind: "measure", unit: "lb", yMin: 100, yMax: 400, bandGapDays: 60, tracks: [{ key: "weight", role: "value", label: "Weight" }], forms: ["current", "past", "delta", "goal", "goal_loss"] };
+const row = (o) => ({ scope: "weight", scopeBasis: "his words", scopeConfidence: "read", valueKind: "uttered", flags: [], asOf: null, ...o });
+// The gaps the real record has: 8 years, 0 days, 279 days, 434 days.
+const LEDGER = [
+ row({ id: "a1", date: "2015-01-10", population: "current", value: 368, display: "368 lb", entryId: "c1" }),
+ row({ id: "g8y", date: "2023-01-08", population: "goal_loss", value: -100, display: "lose 100", entryId: "c2" }),
+ row({ id: "b1", date: "2023-03-01", population: "current", value: 350, display: "350 lb", entryId: "c3" }),
+ row({ id: "g0", date: "2023-03-01", population: "goal_loss", value: -50, display: "lose 50", entryId: "c4" }),
+ row({ id: "g279", date: "2023-12-05", population: "goal_loss", value: -60, display: "lose 60", entryId: "c5" }),
+ row({ id: "g434", date: "2024-05-08", population: "goal_loss", value: -70, display: "lose 70", entryId: "c6" }),
+];
+
+function sliced(r, ledger = LEDGER) {
+ const timeline = Array.from({ length: 7 }, (_, i) => ({ type: "clip", id: `c${i + 1}`, video: "v", start: 10 * i, end: 10 * i + 8, cite: 1, section: 0, quote: "q", onscreen: { title: `Clip ${i + 1}` } }));
+ const manifest = { slug: "m", title: "M", provenance: {}, render: r, timeline, ledgerSchema: schema, ledger };
+ const doc = estimateSchedule(manifest);
+ const m = measureSlice(manifest, doc, {});
+ const goalAfter = (id) => m.state[m.events.findIndex((e) => e.row === id) + 1].goal;
+ return { m, schedule: { ...doc, measure: m }, goalAfter };
+}
+
+test("unset: every base counts, however old -- and each carries the date its weight was said", () => {
+ assert.equal(goalBaseMaxDays({ render: render(undefined) }), null);
+ assert.equal(goalBaseMaxDays({ render: render(true) }), null);
+ const { goalAfter } = sliced(render({ base: true }));
+ assert.deepEqual(goalAfter("g8y").base, { value: 368, row: "a1", from: "stated", date: "2015-01-10" });
+ assert.equal(goalAfter("g8y").value, 268);
+ assert.deepEqual(["g0", "g279", "g434"].map((id) => [goalAfter(id).base.row, goalAfter(id).base.date, goalAfter(id).value]),
+ [["b1", "2023-03-01", 300], ["b1", "2023-03-01", 290], ["b1", "2023-03-01", 280]]);
+});
+
+test("365: a base said 0 or 279 days before the goal stays; 434 days and eight years are no base -- no target, his words", () => {
+ const r = render({ base: true, baseMaxDays: 365 });
+ assert.deepEqual(validateChrome(r.chrome, r), []);
+ const { m, schedule, goalAfter } = sliced(r);
+ assert.deepEqual(["g8y", "g0", "g279", "g434"].map((id) => goalAfter(id).base?.row ?? null), [null, "b1", "b1", null]);
+ assert.deepEqual(["g8y", "g0", "g279", "g434"].map((id) => goalAfter(id).value), [null, 300, 290, null]);
+ assert.equal(goalWords(goalAfter("g8y")), "LOSE 100");
+ assert.equal(goalWords(goalAfter("g434")), "LOSE 70");
+ assert.match(goalWords(goalAfter("g279")), /^GOAL 290 · LOSE 60/);
+ // The notes: "(FROM …)" only where the base stands.
+ const states = goalStates(schedule, r);
+ const baseOf = (text) => states[states.length - 1].notes.find((n) => n.text === text)?.base ?? null;
+ assert.deepEqual([baseOf("LOSE 100"), baseOf("LOSE 50"), baseOf("LOSE 60"), baseOf("LOSE 70")], [null, "(FROM 350)", "(FROM 350)", null]);
+ // The dial: a goal with no base has no weight to mark -- no tick from a base it does not have.
+ const marks = goalMarks(goalBoard(m), m.scale);
+ const tick = (id) => marks.find((x) => x.goal.row === id).angle !== null;
+ assert.deepEqual(["g8y", "g0", "g279", "g434"].map(tick), [false, true, true, false]);
+ // Unset, all four are marked.
+ const before = sliced(render({ base: true })).m;
+ assert.deepEqual(goalMarks(goalBoard(before), before.scale).map((x) => x.angle !== null), [true, true, true, true]);
+});
+
+test("the day counts from when the weight was SAID, never a remembered weight's as-of; the edge day is inside", () => {
+ const ledger = [
+ row({ id: "p1", date: "2024-06-01", asOf: "2016-01-01", population: "past", value: 390, display: "≈390 lb", entryId: "c1" }),
+ row({ id: "g", date: "2024-06-10", population: "goal_loss", value: -100, display: "lose 100", entryId: "c2" }),
+ ];
+ const kept = sliced(render({ baseMaxDays: 30 }), ledger).goalAfter("g");
+ assert.deepEqual([kept.base.row, kept.base.from, kept.base.date, kept.value], ["p1", "remembered", "2024-06-01", 290]);
+ assert.equal(sliced(render({ baseMaxDays: 9 }), ledger).goalAfter("g").base.row, "p1", "9 days before, 9 allowed");
+ assert.equal(sliced(render({ baseMaxDays: 8 }), ledger).goalAfter("g").base, null);
+ // 0: only a weight said on the goal's own day.
+ assert.equal(sliced(render({ baseMaxDays: 0 })).goalAfter("g0").base.row, "b1");
+ assert.equal(sliced(render({ baseMaxDays: 0 })).goalAfter("g279").base, null);
+});
+
+test("the setting is checked: whole days from 0, or null", () => {
+ const problems = (v) => validateChrome(render({ baseMaxDays: v }).chrome, render({ baseMaxDays: v })).join("\n");
+ assert.equal(problems(null), "");
+ assert.equal(problems(0), "");
+ for (const bad of [-1, 1.5, "365", 40000]) assert.match(problems(bad), /deck\.goals\.baseMaxDays must be null \(every base counts\) or whole days from 0 to 36500/, String(bad));
+});
diff --git a/umtool/report-to-video/instruments.mjs b/umtool/report-to-video/instruments.mjs
@@ -66,12 +66,19 @@ export const DIAL_DEFAULTS = Object.freeze({
// "auto" (the default): "promise" when a promise is on camera, else "odometer" --
// the contract's finale: the dial drops, the odometer rolls, NET holds, THEN the promise clock.
finaleEnd: "auto",
+ // A remembered weight (11 Nov variants): "needle" -- the long grey second needle and its as-of words, as it was --
+ // "rim" (a bold rim marker and a flag), "readout" (a line under the date, a rim marker), "callout" (a ghost needle
+ // sweeps to it with a label held ~2 s, then the rim's flag). chrome-instruments.mjs dialParts.
+ rememberedAs: "needle",
+ // The update flash (update-flash.mjs): null follows render.chrome.deck.measure.flash; true/false for this one.
+ flash: null,
});
export const DIAL_PLACEMENTS = Object.freeze(["column", "corner"]);
export const DIAL_CORNERS = Object.freeze(["bottom-right", "bottom-left", "top-right", "top-left"]);
export const DIAL_MOTIONS = Object.freeze(["spring", "ease"]);
export const DIAL_FINALE_ENDS = Object.freeze(["auto", "odometer", "promise"]);
+export const DIAL_REMEMBERED = Object.freeze(["needle", "rim", "readout", "callout"]);
/** A corner dial's size bounds, px at 1920 wide. */
export const DIAL_SIZE = Object.freeze([200, 540]);
@@ -81,6 +88,8 @@ export const ODOMETER_DEFAULTS = Object.freeze({
net: true,
// "ACROSS 8 RUNS" under the wheels.
runs: true,
+ // The update flash (update-flash.mjs): null follows render.chrome.deck.measure.flash; true/false for this one.
+ flash: null,
});
export const TRAIL_DEFAULTS = Object.freeze({
@@ -89,6 +98,15 @@ export const TRAIL_DEFAULTS = Object.freeze({
// How many times he says he is under 300 (the measure's `totals.under300` rows), as they land.
count: true,
label: "WHAT HE SAYS HE WEIGHS, BY DATE",
+ // The axes: "fit" what is shown so far, reflowing as each weight lands; "fixed" to every point of the cut.
+ bounds: "fit",
+ // His remembered weights ("≈390, as of Feb 2023") as points too: hollow and grey, never joined into the line.
+ remembered: true,
+ // A stretch with no statement longer than this many days is a break in the time axis, not a line across it:
+ // "auto" (a year, or 8× the median spacing if that is longer), a number of days (30–3650), or 0 for none.
+ gap: "auto",
+ // The update flash (update-flash.mjs): null follows render.chrome.deck.measure.flash; true/false for this one.
+ flash: null,
});
/** A label's characters at most. */
@@ -171,10 +189,12 @@ export function validateDial(v, where = "render.chrome.deck.dial") {
oneOf("placement", DIAL_PLACEMENTS);
oneOf("motion", DIAL_MOTIONS);
oneOf("finaleEnd", DIAL_FINALE_ENDS);
+ oneOf("rememberedAs", DIAL_REMEMBERED);
oneOf("corner", DIAL_CORNERS);
if (obj.size !== undefined && !(Number.isInteger(obj.size) && numIn(obj.size, DIAL_SIZE[0], DIAL_SIZE[1]))) {
errors.push(`${where}.size must be a whole number of pixels from ${DIAL_SIZE[0]} to ${DIAL_SIZE[1]}`);
}
+ if (obj.flash !== undefined && obj.flash !== null) { const p = boolProblem(obj.flash, `${where}.flash`); if (p) errors.push(p); }
return errors;
}
@@ -184,6 +204,7 @@ export function validateOdometer(v, where = "render.chrome.deck.odometer") {
if (!obj) return errors;
for (const k of ["net", "runs"]) if (obj[k] !== undefined) { const p = boolProblem(obj[k], `${where}.${k}`); if (p) errors.push(p); }
if (obj.label !== undefined) { const p = labelProblem(obj.label, `${where}.label`); if (p) errors.push(p); }
+ if (obj.flash !== undefined && obj.flash !== null) { const p = boolProblem(obj.flash, `${where}.flash`); if (p) errors.push(p); }
return errors;
}
@@ -194,5 +215,9 @@ export function validateTrail(v, where = "render.chrome.deck.trail") {
if (obj.mark !== undefined) { const p = markProblem(obj.mark, `${where}.mark`); if (p) errors.push(p); }
if (obj.count !== undefined) { const p = boolProblem(obj.count, `${where}.count`); if (p) errors.push(p); }
if (obj.label !== undefined) { const p = labelProblem(obj.label, `${where}.label`); if (p) errors.push(p); }
+ if (obj.remembered !== undefined) { const p = boolProblem(obj.remembered, `${where}.remembered`); if (p) errors.push(p); }
+ if (obj.bounds !== undefined && !["fit", "fixed"].includes(obj.bounds)) errors.push(`${where}.bounds must be "fit" or "fixed"`);
+ if (obj.gap !== undefined && !(obj.gap === "auto" || obj.gap === 0 || numIn(obj.gap, 30, 3650))) errors.push(`${where}.gap must be "auto", 0 (no breaks) or 30 to 3650 days`);
+ if (obj.flash !== undefined && obj.flash !== null) { const p = boolProblem(obj.flash, `${where}.flash`); if (p) errors.push(p); }
return errors;
}
diff --git a/umtool/report-to-video/instruments.test.mjs b/umtool/report-to-video/instruments.test.mjs
@@ -112,14 +112,14 @@ test("the instruments' settings: true, an object of known keys, or off; the side
const side = validateChrome({ ...chromeWith({ trail: true }), threads: { list: [{ id: "a", label: "A" }] } }, {});
assert.ok(side.some((e) => /render\.chrome\.threads and render\.chrome\.deck\.trail both need the frame/.test(e)), side.join("\n"));
assert.deepEqual(resolveDial(RENDER), {
- mark: 300, ghosts: true, goal: true, needle: "#ff5a4e", finale: true, label: "HE SAYS HE WEIGHS", placement: "column", size: 340, corner: "bottom-right", motion: "spring", finaleEnd: "auto",
+ mark: 300, ghosts: true, goal: true, needle: "#ff5a4e", finale: true, label: "HE SAYS HE WEIGHS", placement: "column", size: 340, corner: "bottom-right", motion: "spring", finaleEnd: "auto", rememberedAs: "needle", flash: null,
});
assert.match(validateDial({ placement: "left" })[0], /placement must be "column" or "corner"/);
assert.match(validateDial({ size: 100 })[0], /size must be a whole number of pixels from 200 to 540/);
assert.match(validateDial({ motion: "bounce" })[0], /motion must be "spring" or "ease"/);
assert.match(validateDial({ finaleEnd: "net" })[0], /finaleEnd must be "auto" or "odometer" or "promise"/);
assert.equal(resolveDial({ chrome: chromeWith({ dial: false }) }), null);
- assert.deepEqual(moduleProblems({ render: { ...RENDER, chrome: chromeWith({ dial: { ghost: true } }) } }).dial, ["render.chrome.deck.dial.ghost is not a setting of it (mark, ghosts, goal, needle, finale, label, placement, size, corner, motion, finaleEnd)"]);
+ assert.deepEqual(moduleProblems({ render: { ...RENDER, chrome: chromeWith({ dial: { ghost: true } }) } }).dial, ["render.chrome.deck.dial.ghost is not a setting of it (mark, ghosts, goal, needle, finale, label, placement, size, corner, motion, finaleEnd, rememberedAs, flash)"]);
});
// ---------------------------------------------------------------------------
diff --git a/umtool/report-to-video/ledger-shared.mjs b/umtool/report-to-video/ledger-shared.mjs
@@ -102,6 +102,16 @@ export const LEDGER_BUILTIN_KEYS = new Set([
// who said it, when it is not the subject (a promise_claim's counterparty;
// such a row never moves the subject's numbers), and the day she says she paid
"speaker", "paidOn",
- // how a promise ended (a promise_outcome's: kept, refunded, withdrawn)
- "outcome",
+ // how a promise ended (a promise_outcome's: kept, refunded, withdrawn), and the words under its stamp
+ // (`stampNote`: the promise clock's second line in place of "by <date> · no video")
+ "outcome", "stampNote",
]);
+
+/**
+ * THE WORDS UNDER AN OUTCOME'S STAMP (a promise_outcome row's `stampNote`, 12 Nov): the promise clock wrote
+ * "by <date> · no video" under REFUNDED whatever the record said. A row's own note is that line instead; the strip
+ * (one line over a post's card) has room for its first clause only. `fit`: the characters the stamp's line holds
+ * beside the count and the as-of at the card's design width -- the longest the clock's own words come to ("by 26 Oct
+ * 2025 · no video" is 25) -- past it the lint warns; `max`: what a row may carry at all.
+ */
+export const STAMP_NOTE = Object.freeze({ fit: 26, max: 80 });
diff --git a/umtool/report-to-video/ledger-totals.mjs b/umtool/report-to-video/ledger-totals.mjs
@@ -46,7 +46,7 @@ import {
// Re-exported rather than redefined: every consumer already imports these from
// here, and two files owning one vocabulary is the divergence this module was
// written to stop.
-export { LEDGER_BUILTIN_KEYS, SCOPE_CONFIDENCE, VALUE_KINDS, addDays, chronological, dateKey, dayOf, daysBetween } from "./ledger-shared.mjs";
+export { LEDGER_BUILTIN_KEYS, SCOPE_CONFIDENCE, STAMP_NOTE, VALUE_KINDS, addDays, chronological, dateKey, dayOf, daysBetween } from "./ledger-shared.mjs";
export {
EVENTS,
MEASURE_PREDICATES,
diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs
@@ -53,6 +53,8 @@
// and validateTeasers refuses it.)
// - a QR under WARN_QR_PX_PER_MODULE_720P pixels per module at 720p: it
// scans on a good screen with a steady hand, not reliably.
+// - a promise outcome's `stampNote` (a ledger row's words under its stamp on the promise clock) longer than
+// the stamp's one line holds (measure-extras.mjs STAMP_NOTE.fit);
// - a tally label wider than its cell: drawn smaller, down to
// TALLY_LABEL_FLOOR, then cut with an ellipsis (factcheck.mjs
// fitTallyLabel) -- the chrome is never refused for it.
@@ -85,6 +87,7 @@ import {
validateChrome, validateCutEdits, validateDeckMarkers, validatePosts, validateTeasers, deckClaimNotes, validateDeckClaims,
} from "./deck.mjs";
import { tallyLabelNotes, validateClaims } from "./factcheck.mjs";
+import { stampNoteWarnings } from "./measure-extras.mjs";
import { validateClipAudioEntries } from "./clip-audio.mjs";
import { validateClipBlurEntries } from "./clip-blur.mjs";
import { validateGapEntries } from "./gaps.mjs";
@@ -457,6 +460,8 @@ export function lintManifest(manifest, {
// A tally label wider than its cell, drawn smaller or cut (factcheck.mjs fitTallyLabel): said, never refused.
if (!only) warnings.push(...tallyLabelNotes(render));
warnings.push(...stackedLintWarnings(manifest, { only }));
+ // A promise outcome's own stamp words (a ledger row's `stampNote`) longer than the stamp's line holds.
+ if (!only) warnings.push(...stampNoteWarnings(whole));
for (const { where, src } of imageSrcsOf(manifest, { only })) {
if (path.isAbsolute(src) || src.startsWith("~")) {
diff --git a/umtool/report-to-video/local-recording.mjs b/umtool/report-to-video/local-recording.mjs
@@ -0,0 +1,15 @@
+// A LOCAL RECORDING (a record the editor's local media import made, platform
+// "local", id `local-<32 hex>`) has no online source: umtool's own clip fetch
+// and its availability probe refuse it with the editor's sentence
+// (common/lib/localMedia.ts localMediaFetchRefusal), rather than run yt-dlp on
+// an empty URL. A local library channel's other records are refused at the
+// editor's doors, which umtool fetch goes through.
+
+export const LOCAL_RECORDING_ID_RE = /^local-[0-9a-f]{32}$/;
+
+/** @returns {string|null} why no clip can be fetched, or null when one may be. */
+export function localRecordingFetchRefusal(videoId, platform) {
+ const id = String(videoId ?? "");
+ if (platform !== "local" && !LOCAL_RECORDING_ID_RE.test(id)) return null;
+ return `"${id}" is a local recording with no online source, so no clip can be fetched for it.`;
+}
diff --git a/umtool/report-to-video/local-recording.test.mjs b/umtool/report-to-video/local-recording.test.mjs
@@ -0,0 +1,12 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { localRecordingFetchRefusal } from "./local-recording.mjs";
+
+test("a local recording is refused by id or by platform; anything else may fetch", () => {
+ const id = "local-" + "a".repeat(32);
+ assert.equal(localRecordingFetchRefusal(id, null),
+ `"${id}" is a local recording with no online source, so no clip can be fetched for it.`);
+ assert.match(localRecordingFetchRefusal("anything", "local"), /local recording with no online source/);
+ assert.equal(localRecordingFetchRefusal("dQw4w9WgXcQ", "youtube"), null);
+ assert.equal(localRecordingFetchRefusal("local-short", null), null);
+});
diff --git a/umtool/report-to-video/measure-draw.mjs b/umtool/report-to-video/measure-draw.mjs
@@ -16,6 +16,7 @@
//
// Pure: strings in, strings out. No fs.
import { cueTime, pageDuration } from "./deck.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
/** Instant cues still take a millisecond: a zero-duration tween has its own seek rules. */
export const INSTANT = 0.001;
@@ -71,7 +72,7 @@ export function cueList(fps) {
freeAt.set(e.k, r4(at + dur));
cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease });
}
- return { init, cues };
+ return { init, cues: settleFirstFrame(init, cues, fps) };
},
};
}
diff --git a/umtool/report-to-video/measure-extras.mjs b/umtool/report-to-video/measure-extras.mjs
@@ -28,6 +28,7 @@
import { deckGeometry, feedGeometry, instrumentsGeometry, overlayBox, pictureK } from "./deck.mjs";
import { chapterCover, chapterWindows } from "./chrome-story.mjs";
import { dietTagWidth, MEASURE_EXTRAS, MEASURE_POSITIONS, resolveMeasureExtra, SHELF_POSITION } from "./modules/measure-extras-settings.mjs";
+import { STAMP_NOTE } from "./ledger-shared.mjs";
import { resolveShelf } from "./modules/shelf-settings.mjs";
import { stackedOn, stackedStandDowns } from "./vertical-deck.mjs";
@@ -216,6 +217,18 @@ export function goalText(e, unit = "lb") {
}
/**
+ * A goal's base as its note writes it -- "(FROM 346.7)", "(FROM ≈390)" -- from the
+ * slice's `goal.base` ({ value, row }), the qualifier its row carries; null
+ * when there is none.
+ */
+export function goalBaseText(base, m) {
+ if (!base || !Number.isFinite(base.value)) return null;
+ const row = [...(m?.events ?? []), ...(m?.hidden ?? [])].find((e) => e.row === base.row);
+ const q = typeof row?.qualifier === "string" && /^[≈<>]$/.test(row.qualifier) ? row.qualifier : "";
+ return `(FROM ${q}${weightText(base.value)})`;
+}
+
+/**
* The pile's states: one per goal event, `{ at, top, goalsSet, notes }` --
* `notes` back to front (the last is the one that just landed, `top` its key),
* each `{ key, text, count, date, deadline, deadlineDate, days, target, rot,
@@ -255,6 +268,10 @@ export function goalStates(schedule, render) {
const target = s?.goal && s.goal.row === e.row && Number.isFinite(s.goal.value) ? s.goal.value
: e.kind === "goal" && Number.isFinite(e.value) ? e.value : null;
note.target = target;
+ // The weight he had stated when he set it (`goals.base`): the slice's own base for this goal -- the weight the
+ // gauge's target is reckoned from (measure-slice.mjs goalBase: the run's start, else the latest weight he gave by
+ // the goal's date) -- with its row's qualifier. None resolved, none shown: never one made up here.
+ note.base = cfg.base && s?.goal?.row === e.row ? goalBaseText(s.goal.base, m) : null;
order = [...order.filter((k) => k !== key), key];
const shown = order.slice(-cfg.max);
const depth = new Map(shown.map((k, i) => [k, shown.length - 1 - i]));
@@ -267,7 +284,7 @@ export function goalStates(schedule, render) {
const x = notes.get(k);
return {
key: k, id: x.id, text: x.text, count: x.count, date: x.date, deadline: x.deadline,
- deadlineDate: x.deadlineDate, days: x.days, target: x.target, rot: x.rot, dx: x.dx,
+ deadlineDate: x.deadlineDate, days: x.days, target: x.target, base: x.base ?? null, rot: x.rot, dx: x.dx,
depth: depth.get(k), prev: k === key ? null : prevDepth.get(k) ?? null,
};
}),
@@ -337,6 +354,38 @@ export const PROMISE_SETTLE = 4;
/** The count-up to the render date: a day a step, over at most this long. */
export const PROMISE_COUNT_UP = 1.2;
+export { STAMP_NOTE };
+
+/** The stamp's second line: the outcome's own note, else the clock's words ("by 26 Oct · no video"). */
+export function stampNoteLine(outcome) {
+ if (typeof outcome?.note === "string" && outcome.note.trim()) return outcome.note.trim();
+ return `${outcome?.date ? `by ${shortDate(outcome.date)} · ` : ""}no video`;
+}
+
+/** The strip's words after the outcome's: a note's first clause (to its first · , ; — or " -- "), else "no video". */
+export function stampNoteClause(outcome) {
+ const note = typeof outcome?.note === "string" ? outcome.note.trim() : "";
+ if (!note) return "no video";
+ return note.split(/\s+--\s+|\s*[·;—]\s*|,\s+/)[0].trim() || note;
+}
+
+/**
+ * The lint's warnings for the stamp notes (lint.mjs): a `stampNote` longer than the stamp's line holds -- it is one
+ * line, never wrapped, so it runs past the stamp's border and into the as-of beside it.
+ * @returns {string[]}
+ */
+export function stampNoteWarnings(manifest) {
+ const out = [];
+ for (const row of Array.isArray(manifest?.ledger) ? manifest.ledger : []) {
+ if (row?.population !== "promise_outcome" || typeof row.stampNote !== "string") continue;
+ const note = row.stampNote.trim();
+ if (note.length > STAMP_NOTE.fit) {
+ out.push(`ledger ${row.id}.stampNote "${note}" is ${note.length} characters: the promise clock's stamp holds about ${STAMP_NOTE.fit} on its second line (it is one line, never wrapped) -- it will run past the stamp; shorten it (umtool ledger <p> set ${row.id} --stampNote "…")`);
+ }
+ }
+ return out;
+}
+
/** The promise outcomes the clock draws (CONTRACT addendum 2): kept stops the count; refunded and withdrawn do not. */
export const PROMISE_OUTCOMES = Object.freeze(["kept", "refunded", "withdrawn"]);
@@ -371,7 +420,8 @@ export function promiseStates(schedule, render) {
const lastWord = new Map();
const outcomeOf = (p) => {
const o = isObj(p.outcome) && PROMISE_OUTCOMES.includes(p.outcome.kind) ? p.outcome : null;
- return o ? { kind: o.kind, date: o.date ?? null } : p.kept === true ? { kind: "kept", date: null } : null;
+ const note = typeof o?.note === "string" && o.note.trim() ? o.note.trim() : null;
+ return o ? { kind: o.kind, date: o.date ?? null, ...(note ? { note } : {}) } : p.kept === true ? { kind: "kept", date: null } : null;
};
const rowsAt = (s, freshRow) => (Array.isArray(s?.promises) ? s.promises : [])
.filter((p) => p && p.said)
diff --git a/umtool/report-to-video/measure-slice.mjs b/umtool/report-to-video/measure-slice.mjs
@@ -33,7 +33,7 @@ export const MEASURE_SLICE_VERSION = 1;
export { PROMISE_FORMS };
/** `render.chrome.deck.measure`'s keys. */
-export const MEASURE_SETTINGS_KEYS = Object.freeze(["scopes", "scale", "asOf", "ghosts"]);
+export const MEASURE_SETTINGS_KEYS = Object.freeze(["scopes", "scale", "asOf", "ghosts", "flash"]);
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
const isIso = (v) => typeof v === "string" && /^\d{4}-\d{2}-\d{2}$/.test(v) && !Number.isNaN(Date.parse(`${v}T00:00:00Z`));
@@ -66,6 +66,8 @@ export function validateMeasureSettings(v, where = "render.chrome.deck.measure")
else for (const k of Object.keys(s)) if (k !== "min" && k !== "max") errors.push(`${where}.scale.${k} is not a scale setting (min, max)`);
}
if (v.asOf !== undefined && !isIso(v.asOf)) errors.push(`${where}.asOf must be a date (YYYY-MM-DD)`);
+ // The update flash (update-flash.mjs): every measure widget's outline lights as its value changes.
+ if (v.flash !== undefined && typeof v.flash !== "boolean") errors.push(`${where}.flash must be true or false`);
errors.push(...validateGhosts(v.ghosts, `${where}.ghosts`));
return errors;
}
@@ -113,6 +115,19 @@ export function resolveMeasure(manifest, { asOf = null } = {}) {
};
}
+/**
+ * `render.chrome.deck.goals.baseMaxDays` as the slice reads it: whole days (0 = the goal's own day), or null when
+ * unset (or the goal stack is a bare true/false): how long before a loss goal a weight may have been said and still
+ * be the goal's base (measureSlice `goalBase`). The goal stack's settings check its shape (measure-extras-settings.mjs).
+ */
+export function goalBaseMaxDays(manifest) {
+ const v = manifest?.render?.chrome?.deck?.goals?.baseMaxDays;
+ return Number.isInteger(v) && v >= 0 ? v : null;
+}
+
+/** A promise_outcome row's `stampNote` -- the words under its stamp on the promise clock -- trimmed, or null. */
+export const stampNoteOf = (row) => (typeof row?.stampNote === "string" && row.stampNote.trim() ? row.stampNote.trim() : null);
+
// ---------------------------------------------------------------------------
// The odometer
// ---------------------------------------------------------------------------
@@ -491,17 +506,24 @@ export function measureSlice(manifest, schedule, opts = {}) {
const starts = readings.filter((r) => r.population === "past" && r.asOf && dateKey(r.date) <= dateKey(d) &&
dateKey(r.asOf) <= dateKey(run.start) && Math.round(daysBetween(r.asOf, run.start)) <= s.bandGapDays);
const last = starts[starts.length - 1];
- if (last) return { value: Number(last.value), row: last.id, from: "runStart" };
+ if (last) return { value: Number(last.value), row: last.id, from: "runStart", date: last.date ?? null };
}
const known = readings
.filter((r) => dateKey(r.date) <= dateKey(d))
.sort((a, b) => dateKey(plotDate(a)).localeCompare(dateKey(plotDate(b))) || dateKey(a.date).localeCompare(dateKey(b.date)));
const last = known[known.length - 1];
- return last ? { value: Number(last.value), row: last.id, from: last.population === "past" ? "remembered" : "stated" } : null;
+ return last ? { value: Number(last.value), row: last.id, from: last.population === "past" ? "remembered" : "stated", date: last.date ?? null } : null;
};
+ // `deck.goals.baseMaxDays` (rev9-a9, 12 Nov: "LOSE 100 (FROM 368)" off a weight he gave eight years before): a
+ // base counts only when its weight was SAID -- its row's date, never a remembered one's asOf -- at most that many
+ // days before the goal's date. A staler one is no base: his words stay the goal, no weight, no tick, no "(FROM …)".
+ // Unset: every base counts, as before.
+ const baseMaxDays = goalBaseMaxDays(manifest);
+ const fresh = (base, row) => baseMaxDays === null || !base || (base.date && Math.round(daysBetween(base.date, row.date)) <= baseMaxDays);
const scaleMin = Number.isFinite(settings.scale?.min) ? settings.scale.min : -Infinity;
const goalOf = (row) => {
let base = row.population === "goal_loss" ? goalBase(row) : null;
+ if (!fresh(base, row)) base = null;
let cell = goalCell(row, base, s);
if (base && Number.isFinite(cell.value) && cell.value < scaleMin) {
base = null;
@@ -513,7 +535,7 @@ export function measureSlice(manifest, schedule, opts = {}) {
/** A promise_claim as a promise carries it: who, when said, the day she says she paid, his-or-her words. */
/** A promise_outcome as a promise carries it. */
- const outcomeOf = (row) => ({ kind: row.outcome, date: row.date ?? null, row: row.id });
+ const outcomeOf = (row) => ({ kind: row.outcome, date: row.date ?? null, row: row.id, ...(stampNoteOf(row) ? { note: stampNoteOf(row) } : {}) });
const claimOf = (row) => ({ row: row.id, speaker: speakerOf(row), date: row.date ?? null, paidOn: isIso(row.paidOn) ? row.paidOn : null, label: row.label ?? row.display ?? null });
// ---- the state after each event -------------------------------------------
diff --git a/umtool/report-to-video/measure-slice.test.mjs b/umtool/report-to-video/measure-slice.test.mjs
@@ -175,7 +175,7 @@ test("state: after each event, from the shown rows only", () => {
assert.deepEqual(last.lost, { total: 49, runs: [{ run: 0, start: "2024-01-05", peak: 9, row: "w02" }, { run: 1, start: "2025-04-01", peak: 40, row: "w09" }] });
for (let i = 1; i < sl.state.length; i += 1) assert.ok(sl.state[i].lost.total >= sl.state[i - 1].lost.total, "the odometer only goes up");
// "Lose 65" against the start of its run: the 349 he remembers (asOf 20 March, 12 days before).
- assert.deepEqual(last.goal, { value: 284, loss: 65, deadline: "by Christmas", due: "2025-12-25", row: "w11", display: "284 lb", base: { value: 349, row: "w07", from: "runStart" } });
+ assert.deepEqual(last.goal, { value: 284, loss: 65, deadline: "by Christmas", due: "2025-12-25", row: "w11", display: "284 lb", base: { value: 349, row: "w07", from: "runStart", date: "2025-05-01" } });
assert.deepEqual(last.goals, ["w11"]);
assert.deepEqual(last.remembered.map((r) => r.row), ["w01", "w07"]);
assert.deepEqual(last.promises, [{ row: "p01", said: "2025-06-05", what: "post a video of the scale", due: null, kept: false, checks: [], claims: [], outcome: null }]);
@@ -198,7 +198,7 @@ test("the settings: their shape, their scopes against the ledger, and when a cut
assert.deepEqual(validateMeasureSettings(undefined), []);
assert.deepEqual(validateMeasureSettings({ scopes: ["weight"], scale: { min: 220, max: 400 }, asOf: "2026-11-05" }), []);
assert.deepEqual(validateMeasureSettings({ scopes: [], scale: { min: 4, max: 2 }, asOf: "Nov 5", x: 1 }), [
- "render.chrome.deck.measure.x is not a measure setting (scopes, scale, asOf, ghosts)",
+ "render.chrome.deck.measure.x is not a measure setting (scopes, scale, asOf, ghosts, flash)",
"render.chrome.deck.measure.scopes must be a list of the ledger's track keys (at least one)",
"render.chrome.deck.measure.scale.min must be below scale.max",
"render.chrome.deck.measure.asOf must be a date (YYYY-MM-DD)",
diff --git a/umtool/report-to-video/modules/dial.mjs b/umtool/report-to-video/modules/dial.mjs
@@ -43,6 +43,8 @@ export default defineModule({
{ key: "corner", type: "enum", options: ["bottom-right", "bottom-left", "top-right", "top-left"], label: "The corner", default: "bottom-right" },
{ key: "motion", type: "enum", options: ["spring", "ease"], label: "The needle's move", default: "spring" },
{ key: "finaleEnd", type: "enum", options: ["auto", "odometer", "promise"], label: "The finale's last beat", default: "auto" },
+ { key: "rememberedAs", type: "enum", options: ["needle", "rim", "readout", "callout"], label: "A remembered weight drawn as", default: "needle" },
+ { key: "flash", type: "boolean", label: "Flash its outline when its value changes (unset: deck.measure.flash)" },
],
docs: {
heading: "Scale dial",
@@ -52,6 +54,8 @@ export default defineModule({
["`deck.dial.mark`", "a weight, or `null` · default `300` (its tick and label in the accent)", "`umtool look <p> deck.dial.mark=300`"],
["`deck.dial.ghosts`, `.goal`", "bool · default `true` each (`.goal`: every goal in force, the closest headlined)", "`umtool look <p> deck.dial.ghosts=false`"],
["`deck.measure.ghosts`", "`true` · `{opacity, tolerance, ramp, pulse}` · `false` / absent: off (the default). CLAIM GHOSTS (measure-ghosts.mjs), not `deck.dial.ghosts`: every weight he has claimed so far -- each stated weight the needle goes to and each remembered one, his own, in cut order -- leaves a thin faint tick across the dial's rim at its value, under everything else on the face; a value claimed again (within `tolerance` lb of the tick's first value; an `≈` value as its rounded number; `>300` and `<300` at 300) steps that tick along the `ramp` -- 1× faint, 2× warm, 3× and up hot, a little thicker each step -- and it pulses once as the repeat lands (`pulse`). In the finale every tick stays at its count at the cut's end. Seek-safe: a frame at t draws the claims before t", "`umtool look <p> deck.measure.ghosts=true`"],
+ ["`deck.dial.rememberedAs`", "`needle` · `rim` · `readout` · `callout` · default `needle` (as it was: a long grey second needle from the hub to the value, its words -- \"≈390 / AS OF 24 FEB 2023\" -- along it). `rim`: no long needle; a bold marker across the rim at the value and a flag inside it -- \"HEAVIEST ≈390 / AS OF FEB 2023 · HE SAYS\" -- placed clear of the scale's figures, the hub and the readout. `readout`: a line in the readout under the date -- \"HEAVIEST HE'S SAID: ≈390 (FEB 2023)\", the goal under it -- and the rim marker. `callout`: as he says it a ghost needle sweeps from where the needle stands to the value and a label (\"HEAVIEST HE'S SAID / ≈390 / AS OF FEB 2023\") holds 2.2 s, then the rim's flag. The words are the ledger's: its qualifier, its asOf's month; HEAVIEST only for the record's highest remembered weight above every weight he stated (the peak extra's `totals.peakDrift`), else \"HE SAYS HE WAS\". Each is up while it is the latest remembered; the thin rim ticks of every remembered weight stay as they are", "`umtool look <p> deck.dial.rememberedAs=rim`"],
+ ["`deck.measure.flash`", "bool · default `false` (off: every cut renders as before) -- THE UPDATE FLASH for every measure widget at once (update-flash.mjs): at the moment a widget's shown value changes its outline lights in its own colour and decays (0.15 s up, 0.7 s down) -- the dial on a weight stated or remembered or a goal change, the odometer on the pounds lost or NET, the trail on each weight landing, the goal stack on a goal set, the diet tags on a new diet; widgets that change on one event flash together; never on frame 0, while the deck is away (the intro, a card) or on a widget's first appearance. A widget's own `flash` overrides it", "`umtool look <p> deck.measure.flash=true`"],
["`deck.measure.ghosts.opacity`, `.tolerance`", "0.15–0.9 (the 1× tick's; +0.2 a step, at most 0.95) · 0–5 lb · default `0.5`, `0.5`", "`umtool look <p> deck.measure.ghosts='{\"tolerance\":1}'`"],
["`deck.measure.ghosts.ramp`, `.pulse`", "2–4 #hex, 1× first (the last for every count from there up), or `null`: the palette's muted, amber, and amber half way to the needle's red · bool · default `null`, `true`", "`umtool look <p> deck.measure.ghosts='{\"ramp\":[\"#98a29b\",\"#e8a33f\",\"#f37e47\"],\"pulse\":false}'`"],
["`deck.dial.needle`", "a #hex · default `#ff5a4e`", "`umtool look <p> deck.dial.needle='\"#ff5a4e\"'`"],
@@ -62,6 +66,7 @@ export default defineModule({
["`deck.dial.corner`", "`bottom-right` `bottom-left` `top-right` `top-left` · default `bottom-right` (the corner only): the dial in that corner, the odometer and the trail up the same side. The measure extras stand at their own anchors in the footage (goals bottom-right, peak top-right, promise top-centre, diet bottom-left, streak bottom-centre): a corner instrument over one that is on is REFUSED by the build, naming it -- move one (`deck.goals.position`, …) or the corner; `top-left` is clear of all five", "`umtool look <p> deck.dial.corner=top-left`"],
["`deck.dial.motion`", "`spring` `ease` · default `spring`. A VARIANT: the needle's `back.out` overshoot and settle, or a plain `power2.inOut` (the finale's drop too)", "`umtool look <p> deck.dial.motion=ease`"],
["`deck.dial.finaleEnd`", "`auto` `odometer` `promise` · default `auto` (`promise` when a promise is on camera, else `odometer`): `promise` hands the finale's last beat to the promise clock (module `promise`) -- the instruments fade out once NET has held (`dialFinaleHandoff`) and the clock takes their place in the finale's lower column, clear of the rail; with no promise module on the cut it ends on the odometer", "`umtool look <p> deck.dial.finaleEnd=promise`"],
+ ["`deck.dial.flash`", "bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): the bezel lights as a weight is stated or remembered, or the goal in force changes; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away", "`umtool look <p> deck.dial.flash=false`"],
],
},
region: "dial",
diff --git a/umtool/report-to-video/modules/diet.mjs b/umtool/report-to-video/modules/diet.mjs
@@ -25,6 +25,7 @@ export default measureExtraModule({
{ key: "tags", type: "number", min: DIET_TAGS[0], max: DIET_TAGS[1], step: 1, label: "Tags in the row", default: 3, when: { form: "tags" } },
{ key: "overlap", type: "number", min: DIET_OVERLAP[0], max: DIET_OVERLAP[1], step: 0.05, label: "Overlap (0: side by side; the share of each older tag behind the one in front)", default: 0, when: { form: "tags" } },
{ key: "days", type: "boolean", label: "Days on the diet, on the front tag", default: false, when: { form: "tags" } },
+ { key: "flash", type: "boolean", label: "Flash its outline when its value changes (unset: deck.measure.flash)" },
],
docs: {
intro: "The diet he names as a rubber stamp in a corner of the footage box (`render.chrome.deck.diet`, measure-extras.mjs): at each change of the state's diet -- its regime or its diet number -- a new stamp slams on (in big and turned, onto the page, a shake), the regime's word in its ink and \"DIET #n\" under it with the ledger's words when they say more (\"Keto · 5 carbs a day\"); a change of words alone fades the new stamp in. A null diet after one fades to \"NO DIET\" in grey. It draws `state.diet` as the measure slice gives it -- the off-scope rule (\"off GLP-1\" while on keto is still keto) is the ledger's. The inks default to the quartering-diet regimes' (keto #E0913C, carnivore #C9534B, fasting #4E9BD8, calories #3FA9A0, glp1 #B168C6, other #8E97A8, off #98A29B).",
@@ -36,6 +37,7 @@ export default measureExtraModule({
["`deck.diet.overlap`", `${DIET_OVERLAP[0]}–${DIET_OVERLAP[1]}, the share of each older tag hidden behind the one in front · default 0 (side by side, the slam and the dim). Above 0 the tags FAN sideways the way the goal stack's notes pile: the newest in front at the left, landing from above like a goal note, each older one a place to the right behind it with its own small turn, keeping its colours (the depth is the overlap and the shadow), showing its regime word and date in the strip beside the one in front; the one past \`tags\` slides off the back. The fan is narrower by what hides. An older tag's word and date need ${DIET_BACK_MIN} design px of it, so it is refused past ${dietOverlapMax(false)} (${dietOverlapMax(true)} with \`days\`)`, "`umtool look <p> deck.diet.overlap=0.5`"],
["`deck.diet.days`", "`true` · `false`: the front tag's running count of days on its diet (to the in-record date at the playhead, the streak chain's \"Day N\"), in a column of its own -- the tag 300 design px wide · default `false`", "`umtool look <p> deck.diet.days=true`"],
["`deck.diet.colors`, `.labels`", "`{<regime>: #hex}` · `{<regime>: words ≤40}` · default the regimes' inks and names", "`umtool look <p> deck.diet.labels='{\"glp1\":\"Ozempic\"}'`"],
+ ["`deck.diet.flash`", "bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): with `form: \"tags\"`: the new front tag lights, in its ink, at a new diet or new words for it -- never the running day count, never the first tag; the stamp form does not flash; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away", "`umtool look <p> deck.diet.flash=false`"],
],
},
});
diff --git a/umtool/report-to-video/modules/goals.mjs b/umtool/report-to-video/modules/goals.mjs
@@ -22,15 +22,21 @@ export default measureExtraModule({
{ key: "max", type: "number", min: MEASURE_LIMITS.max[0], max: MEASURE_LIMITS.max[1], label: "Notes shown", default: 4 },
{ key: "color", type: "color", label: "Paper (default the palette's amber)" },
{ key: "countdown", type: "boolean", label: "Count a deadline down to the render date", default: true },
+ { key: "base", type: "boolean", label: "Say the weight he had stated when he set it", default: false },
+ { key: "baseMaxDays", type: "number", min: MEASURE_LIMITS.baseMaxDays[0], max: MEASURE_LIMITS.baseMaxDays[1], label: "A base weight said at most this many days before the goal (unset: any age)" },
+ { key: "flash", type: "boolean", label: "Flash its outline when its value changes (unset: deck.measure.flash)" },
],
docs: {
intro: "A sticky note per goal on a pile in a corner of the footage box, read off the schedule's `measure` slice (`render.chrome.deck.goals`, measure-extras.mjs): each goal or goalLoss event drops one, turned a little, onto the pile; the same goal in the same words (\"lose 100\") merges into its note with a count (\"×8\") and comes to the front; `max` notes show, the newest in front, with the goals set so far under them. A goal with a `deadline` counts down to `measure.asOfRender` (\"by Christmas · 50 days left · needs 226.5\"): Christmas is the next 25 Dec from the day he said it, \"next year\" a year on, a named year that year; words that name no date (\"by my birthday\") keep their label and no countdown. On whenever the cut has a measure slice with a goal on camera; `false` turns it off. Up for `hold` seconds after each goal (default 20), the pile as it stands each time. The four measure extras sit at anchors of the footage box by default, clear of the instrument panel's right column and of the top-left, where the streams' face cam most often is (the diet badge bottom-left, the goal stack bottom-right, the moving start top-right, the promise clock top-centre); `position` or `x`/`y` move one.",
rows: [
- ["`deck.goals`", "`true` · `false` · `{show, position, x, y, scale, hold, finale, max, color, countdown}` · default on with a measure slice", "`umtool look <p> deck.goals=false`"],
+ ["`deck.goals`", "`true` · `false` · `{show, position, x, y, scale, hold, finale, max, color, countdown, base, baseMaxDays}` · default on with a measure slice", "`umtool look <p> deck.goals=false`"],
["`deck.goals.position`, `.x`/`.y`, `.scale`", "`top-left` `top-right` `bottom-left` `bottom-right` `top-center` `bottom-center` · design px · 0.5–2 · default `bottom-right`, unset, 1", "`umtool look <p> deck.goals.position=bottom-left`"],
["`deck.goals.position=shelf`", "its shelf form (`deck.shelf`): the count of goals set in a column, then the notes fanned sideways like the diet's tags -- ordered by the dial's goal board (measure-goals.mjs \`goalsAt(goalBoard(schedule.measure), t)\`, so the shelf and the dial always agree): its headline -- the closest goal in force -- in front with \"+N more\" for the others in force, the rest by recency; a goal the board misses struck in red, MISSED on it, for the dial's 6 s; with no goal in force, the newest in front; a new goal landing from above as on the pile; each older one showing its goal's words in the strip beside it (all of each when there is room); a repeat comes to the front with its ×n. The fan takes the shelf's spare width (shelfLayout), up to its notes side by side. On the shelf it stays up from the first goal (`hold` unset). What the dial draws of the goal stays on the dial", "`umtool look <p> deck.shelf.items='[\"diet\",\"goals\"]' deck.goals.position=shelf`"],
["`deck.goals.max`, `.color`, `.countdown`", "1–8 notes · #hex paper · bool · default 4, the palette's amber, `true`", "`umtool look <p> deck.goals.max=6`"],
+ ["`deck.goals.base`", "bool · default `false`: each note also says the weight he had stated when he set the goal -- \"LOSE 100 (FROM 346.7)\", its qualifier kept (\"(FROM ≈390)\") -- the slice's own base for that goal, the one the gauge reckons its target from (measure-slice.mjs `goalBase`: the start of the run open when he set it, else the latest weight he gave by the goal's date, stated or remembered). A goal with no base (no weight by then, a target goal such as \"250 LB\", a base the scale's foot refuses) shows none -- never one made up. On a back card it is a line of its own, right-aligned like the label", "`umtool look <p> deck.goals.base=true`"],
+ ["`deck.goals.baseMaxDays`", "whole days 0–36500 · unset (default): every base counts. A loss goal's base is a weight he gave by the goal's date, however long before; with this set, a base counts only when its weight was SAID (its row's date, never a remembered weight's as-of) at most that many days before the goal's date. A staler one is no base: the note carries no \"(FROM …)\", and the slice resolves no target from it -- the dial draws no goal weight and no tick for that goal, his words (\"LOSE 100\") stay. It is the slice's rule (measure-slice.mjs `goalBaseMaxDays`), so the notes, the shelf and the dial agree; it needs `deck.goals` as settings (`deck.goals.base=true deck.goals.baseMaxDays=365`), and `baseMaxDays=null` takes it off", "`umtool look <p> deck.goals.baseMaxDays=365` (`--take <t>` for a take)"],
["`deck.goals.hold`, `.finale`", "0 (up from the first goal on) or 2–600 s after each · `hide` `show` · default 20, `hide`", "`umtool look <p> deck.goals.hold=0`"],
+ ["`deck.goals.flash`", "bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): the note that lands lights as a goal is set -- not the first note (the stack coming up), not the board's own changes; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away", "`umtool look <p> deck.goals.flash=false`"],
],
},
});
diff --git a/umtool/report-to-video/modules/measure-extras-settings.mjs b/umtool/report-to-video/modules/measure-extras-settings.mjs
@@ -6,10 +6,10 @@
// SETTINGS), so it imports only instruments.mjs (a leaf too: whether the
// instruments' column is on decides two defaults here).
//
-// render.chrome.deck.goals { show, position, x, y, scale, hold, finale, max, color, countdown }
+// render.chrome.deck.goals { show, position, x, y, scale, hold, finale, max, color, countdown, base, baseMaxDays, flash }
// render.chrome.deck.peak { show, position, x, y, scale, hold, finale, title, color, values }
// render.chrome.deck.promise { show, position, x, y, scale, hold, finale, label, verb, kept, broken, checks, speakers, claimVerb, claimColor }
-// render.chrome.deck.diet { show, position, x, y, scale, hold, finale, colors, labels, form, tags, overlap, days }
+// render.chrome.deck.diet { show, position, x, y, scale, hold, finale, colors, labels, form, tags, overlap, days, flash }
// render.chrome.deck.streak { show, position, x, y, scale, hold, finale, source, axis, title, color, colors, labels }
//
// Each is ON whenever the cut has a measure slice (the build writes one only
@@ -110,6 +110,7 @@ export const MEASURE_LIMITS = Object.freeze({
x: Object.freeze([0, 1920]),
y: Object.freeze([0, 1080]),
max: Object.freeze([1, 8]),
+ baseMaxDays: Object.freeze([0, 36500]),
text: 40,
quote: 160,
});
@@ -122,7 +123,11 @@ export const MEASURE_DEFAULTS = Object.freeze({
// The sticky notes pile in the bottom-right corner, up for `hold` seconds
// after each goal; `max` notes show, the newest in front; `color` is the
// paper (default the palette's amber).
- goals: Object.freeze({ ...COMMON, position: "bottom-right", hold: 20, max: 4, color: null, countdown: true }),
+ // `base`: each note also says the weight he had stated when he set it, "(FROM 346.7)" (the slice's goal base).
+ // `baseMaxDays`: a weight said more than this many days before a loss goal is not its base (measure-slice.mjs
+ // goalBase reads it): no "(FROM …)", no target, no tick from it. null: every base counts.
+ // `flash`: the update flash (update-flash.mjs) -- null follows deck.measure.flash, true/false for this module.
+ goals: Object.freeze({ ...COMMON, position: "bottom-right", hold: 20, max: 4, color: null, countdown: true, base: false, baseMaxDays: null, flash: null }),
// The moving start: up for `hold` seconds after each retelling.
peak: Object.freeze({ ...COMMON, position: "top-right", hold: 12, title: "The start keeps moving", color: null, values: "drift" }),
// The promise clock: up from the promise on, through the finale.
@@ -134,7 +139,7 @@ export const MEASURE_DEFAULTS = Object.freeze({
speakers: Object.freeze({}), claimVerb: "paid", claimColor: "#E37AB8", slot: "auto" }),
// The diet badge: up from the first diet on, re-stamped at every change.
// `form` "tags" (the default on the shelf): the last `tags` diets as dated tags, the newest slammed in at the left.
- diet: Object.freeze({ ...COMMON, position: "bottom-left", colors: Object.freeze({}), labels: Object.freeze({}), form: "stamp", tags: 3, overlap: 0, days: false }),
+ diet: Object.freeze({ ...COMMON, position: "bottom-left", colors: Object.freeze({}), labels: Object.freeze({}), form: "stamp", tags: 3, overlap: 0, days: false, flash: null }),
// The streak chain: bottom-centre, between the diet badge and the goal
// stack, so either or both can run. `title` null is the source's own word.
streak: Object.freeze({ ...COMMON, position: "bottom-center", source: "diet", axis: "date", title: null, color: null, colors: Object.freeze({}), labels: Object.freeze({}) }),
@@ -262,6 +267,13 @@ export function validateMeasureExtra(id, v, where = `render.chrome.deck.${id}`,
}
color(v.color, `${where}.color`, errors);
if (v.countdown !== undefined && typeof v.countdown !== "boolean") errors.push(`${where}.countdown must be true or false`);
+ if (v.base !== undefined && typeof v.base !== "boolean") errors.push(`${where}.base must be true or false`);
+ if (v.baseMaxDays !== undefined && v.baseMaxDays !== null && !(Number.isInteger(v.baseMaxDays) && numIn(v.baseMaxDays, L.baseMaxDays[0], L.baseMaxDays[1]))) {
+ errors.push(`${where}.baseMaxDays must be null (every base counts) or whole days from ${L.baseMaxDays[0]} to ${L.baseMaxDays[1]}`);
+ }
+ }
+ if (id === "goals" || id === "diet") {
+ if (v.flash !== undefined && v.flash !== null && typeof v.flash !== "boolean") errors.push(`${where}.flash must be true, false or null (deck.measure.flash)`);
}
if (id === "peak") {
text(v.title, L.text, `${where}.title`, errors, { nullable: false });
diff --git a/umtool/report-to-video/modules/odometer.mjs b/umtool/report-to-video/modules/odometer.mjs
@@ -31,6 +31,7 @@ export default defineModule({
{ key: "label", type: "text", label: "Over the wheels", default: ODOMETER_DEFAULTS.label },
{ key: "net", type: "boolean", label: "NET beside them", default: true },
{ key: "runs", type: "boolean", label: "How many runs", default: true },
+ { key: "flash", type: "boolean", label: "Flash its outline when its value changes (unset: deck.measure.flash)" },
],
docs: {
heading: "Lost odometer",
@@ -39,6 +40,7 @@ export default defineModule({
["`deck.odometer`", "`true` · an object of the knobs below · `false` off · absent: ON when the cut draws a measure (`deck.measure` set), else off", "`umtool look <p> deck.odometer=false`"],
["`deck.odometer.label`", "words over the wheels, ≤ 40 · default `POUNDS HE SAYS HE'S LOST`", "`umtool look <p> deck.odometer.label='\"…\"'`"],
["`deck.odometer.net`, `.runs`", "bool · default `true` each", "`umtool look <p> deck.odometer.net=false`"],
+ ["`deck.odometer.flash`", "bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): the card lights as the pounds lost go up (or the runs change) and as NET changes; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away", "`umtool look <p> deck.odometer.flash=false`"],
],
},
region: "odometer",
diff --git a/umtool/report-to-video/modules/promise.mjs b/umtool/report-to-video/modules/promise.mjs
@@ -9,7 +9,7 @@ import path from "node:path";
import { promiseHtml } from "../chrome-measure-extras.mjs";
import { measureOf, promiseStates } from "../measure-extras.mjs";
-import { avatarEntryOf } from "../post-avatars.mjs";
+import { avatarEntryOf, handleKey } from "../post-avatars.mjs";
import { measureExtraModule } from "./measure-extras-module.mjs";
import { PROMISE_CHECKS, resolveMeasureExtra } from "./measure-extras-settings.mjs";
@@ -27,10 +27,13 @@ async function speakerOpts(ctx) {
for (const s of m?.state ?? []) for (const p of s?.promises ?? []) for (const c of p?.claims ?? []) if (c?.speaker) speakers.add(c.speaker);
const handles = {};
const avatars = {};
+ // A speaker's settings matched as a handle is -- without @, without regard to case -- so
+ // `speakers.MadamSavvy` serves the measure's "madamsavvy" (post-avatars.mjs handleKey).
+ const spCfg = (sp) => cfg?.speakers?.[sp] ?? Object.entries(cfg?.speakers ?? {}).find(([k]) => handleKey(k) === handleKey(sp))?.[1];
for (const sp of speakers) {
- const want = cfg?.speakers?.[sp]?.handle ?? sp;
+ const want = spCfg(sp)?.handle ?? sp;
const entry = avatarEntryOf(ctx.manifest, want) ?? avatarEntryOf(ctx.manifest, sp);
- handles[sp] = String(cfg?.speakers?.[sp]?.handle ?? entry?.[0] ?? sp).replace(/^@/, "");
+ handles[sp] = String(spCfg(sp)?.handle ?? entry?.[0] ?? sp).replace(/^@/, "");
if (entry?.[1]?.src && ctx.manifestDir) {
const src = path.resolve(ctx.manifestDir, entry[1].src);
const url = await ctx.asset(src, `avatar-${sp.replace(/[^A-Za-z0-9_-]/g, "_")}${path.extname(src) || ".jpg"}`).catch(() => null);
@@ -66,6 +69,7 @@ export default measureExtraModule({
["`deck.promise.position`, `.x`/`.y`, `.scale`", "an anchor in the footage box · design px · 0.5–2 · default `top-center`, unset, 1", "`umtool look <p> deck.promise.position=bottom-center`"],
["`deck.promise.hold`, `.finale`", "0 (stays up) or 2–600 s · `hide` `show` · default 0, `show`", "`umtool look <p> deck.promise.finale=hide`"],
["`deck.promise.label`, `.verb`, `.kept`, `.broken`, `.checks`", "≤40 each · `label` `quote` · default the row's display, \"offered\", \"Posted\", \"None posted\", `label`", "`umtool look <p> deck.promise.label='scale video'`"],
+ ["a `promise_outcome` row's `stampNote`", "one line, 1–80 characters · unset (default): the clock's own words under the stamp, \"by <date> · no video\". The row's note is that second line instead (REFUNDED / \"by her account · no receipt\"); the strip over a post's card, which has one line for everything, shows its first clause (to its first `·`, `;`, `—`, `, ` or ` -- `: \"refunded · by her account\"). It is the ledger row's, so every take of the project reads it. `umtool lint` warns past 26 characters (the stamp's line is never wrapped: a longer one runs past its border)", "`umtool ledger <p> set <row> --stampNote \"by her account · no receipt\"` · off again: `--stampNote null`"],
["`deck.promise.speakers`, `.claimVerb`, `.claimColor`", "`{<speaker>: {handle, color}}` · ≤40 · #hex · default `{}` (the postAvatars handle), \"paid\", #E37AB8", "`umtool look <p> deck.promise.speakers='{\"madamsavvy\":{\"handle\":\"MadamSavvy\"}}'`"],
],
},
diff --git a/umtool/report-to-video/modules/rail.test.mjs b/umtool/report-to-video/modules/rail.test.mjs
@@ -28,10 +28,13 @@ test("the deck at a pitch: pips after the first hidden until the marker reaches
const s = estimateSchedule({ render: r, timeline: [clip("a"), clip("b"), clip("c")], posts: [], provenance: {} });
const { init, cues, pips } = deckCues(s, r);
assert.deepEqual(pips.map((p) => p.x), [48, 88, 128]);
- assert.deepEqual(init.pb1, { opacity: 0 });
+ // The marker stands on the first pip from the cut's first instant, so the one after it is up from frame 0: in init,
+ // not an instant cue at 0 that only frame 1 could show (cue-start.mjs settleFirstFrame).
+ assert.deepEqual(init.pb1, { opacity: 1 });
+ assert.ok(!cues.some((c) => c.k === "pb1"));
assert.deepEqual(init.pb2, { opacity: 0 });
assert.equal(init.pb0, undefined);
- assert.ok(cues.some((c) => c.k === "pb1" && c.to.opacity === 1));
+ assert.ok(cues.some((c) => c.k === "pb2" && c.to.opacity === 1 && c.at > 0));
const html = deckHtml(s, r, {});
assert.match(html, /\.fuse \{ position: absolute; left: 48px; top: -1px; width: 1824px;/);
assert.match(html, /<div class="pip" data-k="pb1" style="left:85px"><\/div>/);
diff --git a/umtool/report-to-video/modules/trail.mjs b/umtool/report-to-video/modules/trail.mjs
@@ -30,15 +30,22 @@ export default defineModule({
{ key: "mark", type: "number", min: 0, max: 2000, step: 1, label: "The line across", default: 300 },
{ key: "count", type: "boolean", label: "Count the \"under 300\" claims", default: true },
{ key: "label", type: "text", label: "Its title", default: TRAIL_DEFAULTS.label },
+ { key: "bounds", type: "enum", options: ["fit", "fixed"], label: "Axes: fit what is shown so far, or fixed to the whole cut", default: "fit" },
+ { key: "remembered", type: "boolean", label: "His remembered weights as points too (hollow, not joined)", default: true },
+ { key: "flash", type: "boolean", label: "Flash its outline when its value changes (unset: deck.measure.flash)" },
],
docs: {
heading: "Weight trail",
- intro: "At the foot of the instruments' column: every STATED weight the cut shows, placed by the date he was weighed (its `asOf`, else its date) across the span of them, a dot appearing at its event's `t` and the line between two neighbours drawn once both are said; a red ring on the latest said. The `mark` line (300) dashed across; with `count` and the mark at 300, `UNDER 300 · SAID n×` counts the measure's `totals.under300` rows as the cut reaches each.",
+ intro: "At the foot of the instruments' column: every weight the cut shows -- the STATED ones and (`remembered`) the remembered ones, \"≈390, as of Feb 2023\" -- placed by the date he was that weight (its `asOf`, else its date), a dot appearing at its event's `t`; the line joins neighbours by date among the stated ones once both are said (a remembered one is a hollow grey dot, never joined; a qualified one hollow). The axes FIT what has been said so far (trail-plan.mjs): each new weight outside them reflows the chart over 0.4 s -- the years, the bounds, every dot -- so the time axis advances with the story; a stretch with no statement longer than `gap` is a break in the time axis (a narrow dashed band, `//` at its foot, each side with its own years) and the line across it dotted, so a decade of nothing does not take the width from the dense run after it. A red ring on the latest said. The `mark` line (300) dashed across; with `count` and the mark at 300, `UNDER 300 · SAID n×` counts the measure's `totals.under300` rows as the cut reaches each.",
rows: [
["`deck.trail`", "`true` · an object of the knobs below · `false` off · absent: ON when the cut draws a measure (`deck.measure` set), else off", "`umtool look <p> deck.trail=false`"],
["`deck.trail.mark`", "a weight, or `null` · default `300`", "`umtool look <p> deck.trail.mark=300`"],
["`deck.trail.count`", "bool · default `true`", "`umtool look <p> deck.trail.count=false`"],
["`deck.trail.label`", "its title, ≤ 40 · default `WHAT HE SAYS HE WEIGHS, BY DATE`", "`umtool look <p> deck.trail.label='\"…\"'`"],
+ ["`deck.trail.bounds`", "`fit` · `fixed` · default `fit`: the axes fit the weights said so far and reflow as each lands; `fixed` lays every moment on the axes of all the cut's weights", "`umtool look <p> deck.trail.bounds=fixed`"],
+ ["`deck.trail.remembered`", "bool · default `true`: his remembered weights are points too, hollow and grey, not joined into the line", "`umtool look <p> deck.trail.remembered=false`"],
+ ["`deck.trail.gap`", "`auto` · days 30–3650 · `0` none · default `auto`: a stretch with no statement longer than a year (or 8× the median spacing, if longer) is a break in the time axis", "`umtool look <p> deck.trail.gap=540`"],
+ ["`deck.trail.flash`", "bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): the card lights as each weight lands on it; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away", "`umtool look <p> deck.trail.flash=false`"],
],
},
region: "trail",
diff --git a/umtool/report-to-video/narrate-via-editor.mjs b/umtool/report-to-video/narrate-via-editor.mjs
@@ -264,7 +264,8 @@ export function opResultIn(lines) {
* `body` (its `out` the absolute file the result is written to), then its job
* followed to the end. Returns `{ jobId, result }` (result: the job's result
* line, null when the op writes none and `out` is given). An op the editor
- * has no engine for throws OpNotInstalled.
+ * has no engine for throws OpNotInstalled. `onState({ jobId, status, queue, tail })` is told each poll of a job that
+ * is queued or running (read it with `opWaitOf`).
*/
/** An op that did not finish by its deadline (`askEditorOp`'s `deadlineMs`): its job may still be in the editor's queue. */
export class OpDeadline extends Error {
@@ -275,7 +276,49 @@ export class OpDeadline extends Error {
}
}
-export async function askEditorOp(route, body, { editor = editorFromEnv(), emit = () => {}, pollMs = POLL_MS, onJob = () => {}, deadlineMs = null } = {}) {
+/** How many of a job's last lines a caller that watches its state is handed (`askEditorOp`'s `onState`). */
+export const STATE_TAIL_LINES = 6;
+
+/**
+ * WHERE A QUEUED OR RUNNING EDITOR JOB IS, from one poll of it (`{ status, queue?, tail? }`): `queued` (behind other
+ * jobs of its queue: `position`), `memory` / `slot` (it runs, and its engine waits at the machine's heavy slot), else
+ * `running`. THE GATE WORKING, not an error. The gate speaks in the job's log (scripts/queue-lock.mjs, its stderr):
+ *
+ * heavy: waiting for memory — 6706 MB available, 8000 MB promised to 2 running jobs, the floor is 6000 MB
+ * running: … (indented lines continue the one above)
+ * (HEAVY_MIN_FREE_MB=<MB> to change it; …)
+ * heavy: still waiting (memory, 30s; 6372 MB available) memory | build | exclusive
+ * heavy: waiting for the build slot — … · heavy: waiting for a job that runs alone: …
+ * queue-lock: held for a render (…) — waiting · queue-lock: still waiting for the render (…)
+ * heavy: 7000 MB available after 1m10s — admitted · heavy: admitted beside … · heavy: capped at … · … let go after …
+ *
+ * The LAST gate line of the tail decides: a wait that has not been answered by an admission (or by a line of the
+ * engine's after it) is where the job is. Pure.
+ */
+export function opWaitOf({ status, queue = null, tail = [] } = {}) {
+ if (status === "queued") return { state: "queued", position: Number(queue?.position) > 0 ? Number(queue.position) : null, line: null };
+ const lines = (tail ?? []).map((l) => String(l)).filter((l) => l.trim());
+ const isGate = (l) => /\b(heavy|queue-lock): /.test(l);
+ const continues = (l) => /^\s+\S/.test(l) || /^\(?(running: |\(HEAVY_MIN_FREE_MB|\(render mode:|\(heavy jobs)/.test(l.trim());
+ let at = -1;
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
+ if (isGate(lines[i])) {
+ at = i;
+ break;
+ }
+ }
+ const running = { state: "running", position: null, line: lines.at(-1)?.trim() ?? null };
+ if (at < 0) return running;
+ const line = lines[at].trim();
+ // Something else was said after it (the engine's own output): it is in.
+ if (lines.slice(at + 1).some((l) => !continues(l))) return running;
+ if (/admitted|available after|capped at|let go after|running uncapped|not waiting for it|is not checked/.test(line)) return running;
+ if (/waiting for memory|still waiting \(memory|under the \d+ MB floor/.test(line)) return { state: "memory", position: null, line };
+ if (/waiting|held for a render/.test(line)) return { state: "slot", position: null, line };
+ return running;
+}
+
+export async function askEditorOp(route, body, { editor = editorFromEnv(), emit = () => {}, pollMs = POLL_MS, onJob = () => {}, deadlineMs = null, onState = null } = {}) {
const started = Date.now();
const headers = { authorization: `Bearer ${editor.token}`, "content-type": "application/json" };
const reach = async (url, init) => {
@@ -299,7 +342,8 @@ export async function askEditorOp(route, body, { editor = editorFromEnv(), emit
for (;;) {
let r;
try {
- r = await fetch(`${editor.url}/api/ops/job/${encodeURIComponent(jobId)}`, { headers });
+ // A caller that shows where the job is (`onState`) is handed its last lines too: the heavy slot's gate speaks there.
+ r = await fetch(`${editor.url}/api/ops/job/${encodeURIComponent(jobId)}${onState ? `?tail=${STATE_TAIL_LINES}` : ""}`, { headers });
} catch (err) {
failures += 1;
if (failures >= MAX_POLL_FAILURES) throw new Error(`lost contact with the editor at ${editor.url} while job ${jobId} ran (${err?.message ?? err}); it may still be running there`);
@@ -313,6 +357,7 @@ export async function askEditorOp(route, body, { editor = editorFromEnv(), emit
if (status !== last) emit("note", { message: ` editor job ${jobId}: ${status}` });
last = status;
const q = st.job?.queue;
+ if (onState && (status === "queued" || status === "running")) onState({ jobId, status, queue: q ?? null, tail: Array.isArray(st.tail) ? st.tail : [] });
if (status === "queued" && q && Number(q.position) > 0) {
const line = `queued — position ${q.position}${Number(q.queued) > 0 ? ` of ${q.queued}` : ""}`;
if (line !== place) emit("note", { message: ` editor job ${jobId}: ${line}` });
diff --git a/umtool/report-to-video/post-combo-prints.mjs b/umtool/report-to-video/post-combo-prints.mjs
@@ -198,27 +198,36 @@ export async function projectCombos(dir, manifest, o = {}) {
* the cut whose capture holds one (captured after the item went in -- its
* media was never copied). Its capture is looked for under its own channel,
* then every channel the cut's posts come from (a reply captured under the
- * replies channel). `{ <itemId>: [{ name, slug, mediaId, sha256, url }] }`.
+ * replies channel). `{ <itemId>: [{ name, slug, tree, mediaId, sha256, url }] }`.
+ *
+ * `channelsDirs`: the channels trees to look in, in order (the project's own first, then the archive behind it:
+ * sources.mjs channelsLayersFor) -- the first tree that holds the post's capture wins, and each file says which
+ * (`tree`). Read only: nothing is written into any of them.
*
* @param {Record<string, any>} manifest
- * @param {{ channelsDir?: string|null }} [o]
+ * @param {{ channelsDir?: string|null, channelsDirs?: string[]|null }} [o]
*/
-export async function captureOnlyMedia(manifest, { channelsDir = null } = {}) {
- if (!channelsDir) return {};
+export async function captureOnlyMedia(manifest, { channelsDir = null, channelsDirs = null } = {}) {
+ const trees = (Array.isArray(channelsDirs) && channelsDirs.length ? channelsDirs : [channelsDir]).filter((d) => typeof d === "string" && d);
+ if (!trees.length) return {};
const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
- const channels = [...new Set(tl.filter((e) => e?.type === "post" && typeof e.post === "string").map((e) => e.post.split("/")[0]).filter(Boolean))];
+ const channels = [...new Set(tl.filter((e) => e?.type === "post" && typeof e.post === "string").map((e) => e.post.split("/")[0]).filter((c) => c && c !== "." && c !== ".." && !/[\\\0]/.test(c)))];
const out = {};
for (const e of tl) {
if (e?.type !== "post" || typeof e.post !== "string" || (Array.isArray(e.media) && e.media.length)) continue;
const [own, postId] = e.post.split("/");
if (!own || !postId) continue;
- for (const slug of [own, ...channels.filter((c) => c !== own)]) {
- const dirOf = path.join(channelsDir, slug, "posts-media", postId);
- const cap = await readFile(path.join(dirOf, "capture.json"), "utf8").then((t) => JSON.parse(t), () => null);
- const media = Array.isArray(cap?.media) ? cap.media.filter((m) => typeof m?.name === "string") : [];
- if (!media.length) continue;
- out[e.id] = media.map((m) => ({ name: m.name, slug, mediaId: xMediaIdOf(m.url), sha256: typeof m.sha256 === "string" ? m.sha256 : null, url: typeof m.url === "string" ? m.url : null }));
- break;
+ // A post id of dots is no folder of a capture: never joined into a tree's path.
+ if ([own, postId].some((v) => v === "." || v === ".." || /[\\\0]/.test(v))) continue;
+ found: for (const tree of trees) {
+ for (const slug of [own, ...channels.filter((c) => c !== own)]) {
+ const dirOf = path.join(tree, slug, "posts-media", postId);
+ const cap = await readFile(path.join(dirOf, "capture.json"), "utf8").then((t) => JSON.parse(t), () => null);
+ const media = Array.isArray(cap?.media) ? cap.media.filter((m) => typeof m?.name === "string") : [];
+ if (!media.length) continue;
+ out[e.id] = media.map((m) => ({ name: m.name, slug, tree, mediaId: xMediaIdOf(m.url), sha256: typeof m.sha256 === "string" ? m.sha256 : null, url: typeof m.url === "string" ? m.url : null }));
+ break found;
+ }
}
}
return out;
diff --git a/umtool/report-to-video/post-links.mjs b/umtool/report-to-video/post-links.mjs
@@ -64,7 +64,8 @@ export function createPostChannelResolver({
refreshAfterMs = Infinity,
now = Date.now,
} = {}) {
- const timed = (url) => fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs) });
+ // `init` is the cache's (archive-fetch.mjs asks with `redirect: "manual"`).
+ const timed = (url, init) => fetchImpl(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
const get = getJson ?? createJsonCache({ ...(cacheDir !== undefined ? { cacheDir } : {}), fetchImpl: timed, log, refreshAfterMs }).getJson;
// ONE memo of failed reads, `url -> { err, at, refresh }`, consulted by both
// passes (the cached read and the fresh one): a URL that failed is not asked
diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs
@@ -49,6 +49,8 @@ export const POST_TAKE_ENGINES = Object.freeze([...POST_NARRATION_ENGINES, "reco
* { kind: "recorded", voice } a person's own read, recorded on the bench
* { kind: "take", from: <take id> } DERIVED: a new take made from another
* steps [{ op, engine?, params?, ranAt, job? }] the processing that made a derived take
+ * (a convert's also `voice`, the stock target, and -- when the read's pitch was FOLLOWED rather than
+ * flattened to the stock voice's -- `pitch: "source" | "contour"` and `semitones`, as the editor ran them)
*
* A derived take never overwrites the one it came from. Its ops are the
* editor's (each a job, like tts): `enhance` (denoise, level, de-reverb) and
@@ -188,13 +190,15 @@ const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz",
// `follow`: the cut's read-follow (read-follow.mjs) -- { on, dim, ease } -- kept here with the mix it rides on.
// `thread`: the cut's thread reads (post-thread.mjs) -- what each context post is on screen, the shrink and dim.
const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice", "follow", "thread"]);
-const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "takes", "pick", "approved", "off", "window"]);
+// `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"]);
const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs", "lexicon", "read"]);
-const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job", "drop", "tempo", "spans", "pauses", "revoice"]);
+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).
// `tempo`: the part's reading speed in the take's file against its first read (a `tempo` step's; absent: 1).
-const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "engine", "piece", "tempo"]);
+// `speed`: the speed the part was synthesized at (its character's preset's, or the read's --speed; absent: 1).
+const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "engine", "piece", "tempo", "speed"]);
const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/;
/** Orpheus's expressive tags (narration.mjs NARRATION_TAGS, the editor's list). */
const TAGS = ["laugh", "chuckle", "sigh", "cough", "sniffle", "groan", "yawn", "gasp"];
@@ -605,6 +609,7 @@ export function validatePostNarration(e) {
if (n.script !== undefined) errors.push(...scriptErrors(n.script, `${w}.script`));
for (const k of ["excerpt", "approved", "off"]) if (n[k] !== undefined && typeof n[k] !== "boolean") errors.push(`${w}.${k} must be true or false`);
if (n.speed !== undefined && !numIn(n.speed, POST_NARRATION_LIMITS.speed)) errors.push(`${w}.speed must be ${POST_NARRATION_LIMITS.speed.join("–")}`);
+ if (n.character !== undefined && !(typeof n.character === "string" && /^[a-z0-9][a-z0-9_-]{0,47}$/.test(n.character))) errors.push(`${w}.character must be a character's id (umtool posts character)`);
if (n.window !== undefined) {
const x = n.window;
if (!isObj(x) || !Number.isInteger(x.media) || !fin(x.start) || !fin(x.end) || x.end <= x.start || (x.score !== undefined && !fin(x.score)) || (x.reason !== undefined && typeof x.reason !== "string")) {
@@ -661,6 +666,9 @@ export function validatePostNarration(e) {
if (!isObj(st) || !(POST_DERIVE_OPS.includes(st.op) || POST_LOCAL_OPS.includes(st.op))) errors.push(`${tw}.steps[${k}].op must be one of ${[...POST_DERIVE_OPS, ...POST_LOCAL_OPS].join(", ")}`);
else {
for (const key of Object.keys(st)) if (!STEP_KEYS.has(key)) errors.push(`${tw}.steps[${k}].${key} is not a step key`);
+ // A convert's followed pitch, as the editor ran it.
+ if (st.pitch !== undefined && !["target", "source", "contour"].includes(st.pitch)) errors.push(`${tw}.steps[${k}].pitch must be target, source or contour`);
+ if (st.semitones !== undefined && !(fin(st.semitones) && Math.abs(st.semitones) <= 12)) errors.push(`${tw}.steps[${k}].semitones must be a number from -12 to 12`);
// A re-join's record: what it left out (a piece, "part <n>", "url").
if (st.drop !== undefined && !(Array.isArray(st.drop) && st.drop.length <= 200 && st.drop.every((d) => typeof d === "string"))) errors.push(`${tw}.steps[${k}].drop must be a list of what it left out`);
// A tempo step's record: each run of parts ("4-16", "21") and the tempo it reads at.
@@ -697,6 +705,7 @@ export function validatePostNarration(e) {
if (!(fin(p.start) && p.start >= 0)) errors.push(`${pw}.start must be where it starts in the take, seconds`);
if (!(fin(p.seconds) && p.seconds > 0)) errors.push(`${pw}.seconds must be its length`);
if (p.text !== undefined && typeof p.text !== "string") errors.push(`${pw}.text must be the words it reads`);
+ if (p.speed !== undefined && !numIn(p.speed, POST_NARRATION_LIMITS.speed)) errors.push(`${pw}.speed must be ${POST_NARRATION_LIMITS.speed.join("–")} (the speed it was synthesized at)`);
if (p.tempo !== undefined && !numIn(p.tempo, POST_NARRATION_LIMITS.tempo)) errors.push(`${pw}.tempo must be ${POST_NARRATION_LIMITS.tempo.join("–")} (its reading speed in the take)`);
if (p.role !== undefined && !(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d)$/.test(p.role))) errors.push(`${pw}.role must be post, quoted, parent:<i>, linked:<i> or media:<i> (the text it reads)`);
if (p.engine !== undefined && !POST_NARRATION_ENGINES.includes(p.engine)) errors.push(`${pw}.engine must be one of ${POST_NARRATION_ENGINES.join(", ")}`);
diff --git a/umtool/report-to-video/post-say.mjs b/umtool/report-to-video/post-say.mjs
@@ -40,9 +40,10 @@
// "*" is everyone the map does not name (default: CONTEXT_VOICE_DEFAULTS for
// the engine). The map is the project's OVERRIDE LAYER over THE CAST
// (cast.mjs: the characters that recur across projects, each with its voice):
-// the read's own override, the map, the cast, the narrator's (the item's own
-// author), the map's "*", the default -- voiceForPiece, the one function every
-// read goes through.
+// the read's own override, the item's own character, the map (and the
+// project's own characters: cast.mjs projectPresetMap), the cast, the
+// narrator's (the item's own author), the map's "*", the default --
+// voiceSourceOf, the one function every read goes through.
//
// PURE and dependency-free.
@@ -259,27 +260,49 @@ export function voiceRefOf(spec, engine = null) {
/** `{engine, voice}` as `engine:voice` (bare when there is no engine). */
export const voiceSpecOf = (r) => (r?.engine ? `${r.engine}:${r.voice}` : str(r?.voice));
+/** A layer's entry as `{ voice, speed?, character? }`: a voice as written ("tara"), or a character's preset; null when it names no voice. */
+function entryOf(v) {
+ if (typeof v === "string") return v ? { voice: v } : null;
+ return isObj(v) && typeof v.voice === "string" && v.voice ? v : null;
+}
+const hit = (entry, from) => ({
+ spec: entry.voice, from,
+ ...(typeof entry.speed === "number" && Number.isFinite(entry.speed) ? { speed: entry.speed } : {}),
+ ...(typeof entry.character === "string" && entry.character ? { character: entry.character } : {}),
+});
+
/**
- * The voice one piece of a read is said in, and WHERE IT CAME FROM, pure: `{ spec, from }` -- `spec` as written
- * (bare or `engine:voice`), `from` one of "override" (`--voice-for`, `--voice`), "project" (the map), "cast" (the
- * cast's character for the handle), "narrator" (the item's own author: the narrator's voice), "default". In order:
- * the run's own `overrides` (`--voice-for`), the item's `voice` for its own post (`--voice`), the map's for the
- * author, the CAST's, the narrator's for the item's own author, the map's "*", the engine's context default, the
- * narrator's.
+ * The voice one piece of a read is said in, and WHERE IT CAME FROM, pure: `{ spec, from, speed?, character? }` --
+ * `spec` as written (bare or `engine:voice`), `from` one of "override" (`--voice-for`, `--voice`), "item" (the item's
+ * own character: `narration.character`), "project" (the project's character for the author, or its voice map),
+ * "cast" (the cast's character for the handle), "narrator" (the item's own author: the narrator's voice), "default";
+ * `speed` the preset's (a character's `synthetic.speed`) and `character` its id, when the layer that answered is a
+ * character's. FIRST HIT WINS, in order: the run's own `overrides` (`--voice-for`), the item's `voice` for its own
+ * post (`--voice`), the item's own character for its author's words (`item`), the project's for the author (`map`),
+ * the CAST's, the narrator's for the item's own author, the map's "*", the engine's context default, the narrator's.
+ *
+ * A layer's entry (`map[h]`, `cast[h]`, `item`) is a voice as written or a character's synthetic preset
+ * `{ voice, speed?, character }` (cast.mjs presetEntryOf, projectPresetMap, castPresetMap).
*
* @param {{ handle?: string | null, role: string }} piece
- * @param {{ map?: Record<string, string>, cast?: Record<string, string>, overrides?: Record<string, string>,
+ * @param {{ map?: Record<string, any>, cast?: Record<string, any>, item?: any, overrides?: Record<string, string>,
* self?: string | null, voice?: string | null, narrator: string, engine?: string }} o
*/
-export function voiceSourceOf(piece, { map = {}, cast = {}, overrides = {}, self = null, voice = null, narrator, engine = "orpheus" }) {
+export function voiceSourceOf(piece, { map = {}, cast = {}, item = null, overrides = {}, self = null, voice = null, narrator, engine = "orpheus" }) {
const h = handleKey(piece?.handle);
const mine = piece?.role === "post" || (!!h && h === handleKey(self));
if (h && overrides[h]) return { spec: overrides[h], from: "override" };
if (piece?.role === "post" && voice) return { spec: voice, from: "override" };
- if (h && h !== VOICE_MAP_OTHER && map[h]) return { spec: map[h], from: "project" };
- if (h && h !== VOICE_MAP_OTHER && cast?.[h]) return { spec: cast[h], from: "cast" };
+ const own = mine ? entryOf(item) : null;
+ if (own) return hit(own, "item");
+ const named = h && h !== VOICE_MAP_OTHER;
+ const p = named ? entryOf(map?.[h]) : null;
+ if (p) return hit(p, "project");
+ const c = named ? entryOf(cast?.[h]) : null;
+ if (c) return hit(c, "cast");
if (mine) return { spec: narrator, from: "narrator" };
- if (map[VOICE_MAP_OTHER]) return { spec: map[VOICE_MAP_OTHER], from: "project" };
+ const other = entryOf(map?.[VOICE_MAP_OTHER]);
+ if (other) return { spec: other.voice, from: "project" };
return { spec: CONTEXT_VOICE_DEFAULTS[engine] ?? narrator, from: "default" };
}
@@ -289,13 +312,24 @@ export function voiceForPiece(piece, o) {
}
/**
- * The voice one piece is said in, RESOLVED: `{ engine, voice, from }` -- a bare voice in the read's `engine`, one that
- * names its own engine in that one. The thread read and a single post's take both ask this.
+ * The voice one piece is said in, RESOLVED: `{ engine, voice, from, speed?, character? }` -- a bare voice in the
+ * read's `engine`, one that names its own engine in that one; `speed` and `character` as voiceSourceOf says them.
+ * The thread read and a single post's take both ask this.
*/
export function resolvePieceVoice(piece, o) {
- const { spec, from } = voiceSourceOf(piece, o);
+ const { spec, from, speed, character } = voiceSourceOf(piece, o);
const ref = voiceRefOf(spec, o.engine ?? "orpheus") ?? { engine: o.engine ?? "orpheus", voice: String(spec) };
- return { engine: ref.engine ?? o.engine ?? "orpheus", voice: ref.voice, from };
+ return { engine: ref.engine ?? o.engine ?? "orpheus", voice: ref.voice, from, ...(speed !== undefined ? { speed } : {}), ...(character ? { character } : {}) };
+}
+
+/**
+ * THE SPEED A PART IS ASKED AT, pure: the command's (`flag`), else the item's own (`own`: `narration.speed`, for its
+ * own words -- set on that one item, it beats a character's), else the preset's (`preset`: the character's that
+ * answered for the voice) -- and none (null) for an engine that has no speed (Orpheus), or at 1.
+ */
+export function readSpeedOf({ flag = null, preset = null, own = null, engine = null } = {}) {
+ const v = [flag, own, preset].find((x) => typeof x === "number" && Number.isFinite(x));
+ return v === undefined || engine === "orpheus" || v === 1 ? null : v;
}
/** `--voice-for h=v` words as `{ handle: voice }` (handles keyed as the map keys them); throws naming a bad one. */
diff --git a/umtool/report-to-video/remembered-looks.test.mjs b/umtool/report-to-video/remembered-looks.test.mjs
@@ -0,0 +1,109 @@
+// THE DIAL'S REMEMBERED-WEIGHT LOOKS (`deck.dial.rememberedAs`; operator, 11 Nov: "max weight statements could be
+// shown better" -- the long grey second needle and its small words crossed the main needle and the readout and did
+// not say what the weight was). Three looks beside today's, each worded from the ledger entry's own fields.
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { CALLOUT_HOLD, dialFinaleHtml, dialHtml, heaviestOf, rememberedMode, rememberedWords } from "./chrome-instruments.mjs";
+import { estimateSchedule } from "./deck.mjs";
+import { validateDial } from "./instruments.mjs";
+import { moduleById } from "./modules/index.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const MEASURE = JSON.parse(readFileSync(path.join(HERE, "fixtures", "measure-remembered", "measure.json"), "utf8"));
+const PALETTE = { bg: "#0F1312", fg: "#EDF0EC", muted: "#98A29B", accent: "#22AB83", amber: "#E8A33F" };
+const renderAs = (as) => ({ width: 1920, height: 1080, fps: 30, transition: 0.4, palette: PALETTE,
+ chrome: { engine: "hyperframes", layout: "deck", deck: { dial: as === undefined ? true : { rememberedAs: as }, odometer: true, trail: true } } });
+const page = (as) => {
+ const r = renderAs(as);
+ const timeline = Array.from({ length: 3 }, (_, i) => ({ type: "clip", id: `c${i + 1}`, video: "v", start: 0, end: 10 }));
+ const html = dialHtml({ ...estimateSchedule({ slug: "m", title: "M", provenance: {}, render: r, timeline }), measure: MEASURE }, r, { fonts: {} });
+ return { html, data: JSON.parse(/<script id="dial-data" type="application\/json">(.*?)<\/script>/s.exec(html)[1]) };
+};
+
+test("the words are the ledger's: its qualifier, its asOf's month; HEAVIEST only for the record's highest above every stated weight", () => {
+ assert.equal(heaviestOf(MEASURE), 390);
+ assert.equal(heaviestOf({ totals: {} }), null);
+ const top = rememberedWords({ value: 390, qualifier: "≈", asOf: "2023-02-24" }, 390);
+ assert.deepEqual([top.value, top.when, top.kind, top.line], ["≈390", "FEB 2023", "HEAVIEST HE'S SAID", "HEAVIEST HE'S SAID: ≈390 (FEB 2023)"]);
+ const other = rememberedWords({ value: 368, qualifier: null, asOf: "2008-06-30" }, 390);
+ assert.deepEqual([other.kind, other.line], ["HE SAYS HE WAS", "HE SAYS HE WAS: 368 (JUN 2008)"]);
+ // No peak drift on the record: nothing is called his heaviest.
+ assert.equal(rememberedWords({ value: 390, qualifier: "≈", asOf: "2023-02-24" }, null).heaviest, false);
+ assert.equal(rememberedWords({ value: 390, qualifier: "≈", asOf: null }, 390).line, "HEAVIEST HE'S SAID: ≈390");
+});
+
+test("needle (the default) is today's dial; rim, readout and callout draw no long needle at rest and no floating as-of words", () => {
+ assert.equal(rememberedMode({}), "needle");
+ assert.deepEqual(validateDial({ rememberedAs: "rim" }), []);
+ assert.match(validateDial({ rememberedAs: "flag" }).join(), /rememberedAs must be "needle" or "rim" or "readout" or "callout"/);
+ const today = page(undefined);
+ assert.deepEqual(page("needle").html, today.html, "needle is the default, byte for byte");
+ assert.match(today.html, /data-k="gn"/);
+ assert.match(today.html, /class="asof" data-k="ga0"/);
+ for (const as of ["rim", "readout"]) {
+ const { html } = page(as);
+ assert.doesNotMatch(html, /data-k="gn"|class="asof"/, as);
+ assert.match(html, /data-k="gk0"/, `${as}: the rim marker`);
+ }
+ assert.match(page("rim").html, /class="rflag" data-k="gl0"[^>]*><span>HEAVIEST<\/span><b>≈390<\/b><span>FEB 2023<\/span>/);
+ assert.match(page("rim").html, /class="rflag" data-k="gl1"[^>]*><span>REMEMBERED<\/span><b>368<\/b><span>JUN 2008<\/span>/);
+ assert.match(page("readout").html, /class="rline" data-k="gr0"[^>]*>HEAVIEST HE'S SAID: ≈390 \(FEB 2023\)<|class="rline" data-k="gr0"[^>]*>HEAVIEST HE'S SAID: ≈390 \(FEB 2023\)</);
+ // The goal line moves under the remembered line in the readout look.
+ const goalTop = (html) => Number(/class="goalw" data-k="gw\d+" style="top:([\d.]+)px"/.exec(html)[1]);
+ assert.ok(goalTop(page("readout").html) > goalTop(today.html));
+});
+
+test("the rim's flag is never on the hub or the readout", () => {
+ const { html } = page("rim");
+ const at = /class="rflag" data-k="gl0" style="left:([\d.]+)px; top:([\d.]+)px"/.exec(html);
+ const [x, y] = [Number(at[1]), Number(at[2])];
+ // The dial's 540 face: centre 270, the readout's words from 60 px under it.
+ assert.ok(Math.hypot(x - 270, y - 270) > 80, `clear of the hub (${x}, ${y})`);
+ assert.ok(!(y > 270 + 40 && Math.abs(x - 270) < 128), `clear of the readout (${x}, ${y})`);
+});
+
+test("one at a time, the latest remembered; the callout sweeps a ghost needle and holds its label, then the flag", () => {
+ const rim = page("rim").data;
+ const up = (d, k) => d.cues.filter((c) => c.k === k && c.to.autoAlpha === 1).map((c) => c.at);
+ const down = (d, k) => d.cues.filter((c) => c.k === k && c.to.autoAlpha === 0).map((c) => c.at);
+ assert.deepEqual(up(rim, "gl0"), [3]);
+ assert.deepEqual(down(rim, "gl0"), [8], "gives way to the next remembered");
+ assert.deepEqual(up(rim, "gl1"), [8]);
+ const call = page("callout").data;
+ assert.deepEqual(up(call, "gl0"), [3 + CALLOUT_HOLD], "the flag after the hold");
+ assert.deepEqual(up(call, "gc0"), [3.25]);
+ assert.deepEqual(down(call, "gc0"), [3 + CALLOUT_HOLD]);
+ const gn = call.cues.filter((c) => c.k === "gn");
+ assert.ok(gn.some((c) => c.at === 3 && c.to.autoAlpha === 0.9), "the ghost needle comes up where the needle stands");
+ assert.ok(gn.some((c) => Math.abs(c.at - (3 + CALLOUT_HOLD)) < 1e-6 && c.to.autoAlpha === 0), "and goes after the hold");
+});
+
+// rev9-a9 (12 Nov): in the finale the callout's label boxes and its ghost needle are drawn (dialParts draws them
+// whenever the look is "callout") but nothing hid them -- every box sat at its CSS default over the dial's hub.
+test("the finale never shows the callout: every label box and the ghost needle hidden from the first frame, the last one's rim flag up", () => {
+ const r = renderAs("callout");
+ r.chrome.deck = { ...r.chrome.deck, qr: { show: false }, finale: { video: "side", totals: false } };
+ const timeline = Array.from({ length: 4 }, (_, i) => ({ type: "clip", id: `c${i + 1}`, video: "v", start: 10 * i, end: 10 * i + (i === 3 ? 14 : 8), cite: 1, section: 0,
+ quote: "q", onscreen: { title: `Clip ${i + 1}` }, ...(i === 3 ? { layout: "finale" } : {}) }));
+ const schedule = { ...estimateSchedule({ slug: "m", title: "M", provenance: {}, render: r, timeline }), measure: MEASURE };
+ const win = moduleById("dial-finale").window(schedule, { fps: 30, total: schedule.total });
+ const html = dialFinaleHtml(schedule, r, win, { fonts: {} });
+ const data = JSON.parse(/<script id="dial-finale-data" type="application\/json">(.*?)<\/script>/s.exec(html)[1]);
+ const drawn = [...html.matchAll(/class="rcall" data-k="(fgc\d+)"/g)].map((m) => m[1]);
+ assert.ok(drawn.length >= 2, "the fixture's remembered weights each draw a callout box");
+ for (const k of drawn) {
+ assert.equal(data.init[k]?.autoAlpha, 0, `${k} is hidden at load`);
+ assert.ok(!data.cues.some((c) => c.k === k && c.to.autoAlpha > 0), `${k} is never called up`);
+ }
+ assert.match(html, /data-k="fgn"/);
+ assert.equal(data.init.fgn?.autoAlpha, 0, "the ghost needle is hidden at load");
+ assert.ok(!data.cues.some((c) => c.k === "fgn" && c.to.autoAlpha > 0), "and never sweeps");
+ // The rim's marker and flag stay: the last remembered one's, all at once.
+ const last = drawn.length - 1;
+ assert.ok(data.cues.some((c) => c.k === `fgl${last}` && c.to.autoAlpha === 1));
+ assert.ok(data.cues.some((c) => c.k === `fgk${last}` && c.to.autoAlpha === 1));
+});
diff --git a/umtool/report-to-video/render-cards.mjs b/umtool/report-to-video/render-cards.mjs
@@ -1014,6 +1014,7 @@ export const SOURCE_TAG = {
restricted: "age-restricted",
"geo-blocked": "geo-blocked",
"no-cues": "no archived transcript",
+ "local-media": "local recording, not clipped",
maybe_missing: "source unreachable",
};
diff --git a/umtool/report-to-video/shelf.test.mjs b/umtool/report-to-video/shelf.test.mjs
@@ -10,11 +10,11 @@ import path from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
-import { dietHtml, goalsHtml, shelfGoalStates, tagWords, tagWordSize } from "./chrome-measure-extras.mjs";
+import { backTextSize, dietHtml, GOALS_BACK, goalsHtml, shelfGoalStates, tagWords, tagWordSize } from "./chrome-measure-extras.mjs";
import { goalBoard, goalsAt } from "./measure-goals.mjs";
import { shelfHtml, shelfNoteGeometry } from "./chrome-shelf.mjs";
import { deckGeometry, entryShelfNotes, estimateSchedule, instrumentsGeometry, parseShelfNote, validateChrome } from "./deck.mjs";
-import { dietDays, dietStates, goalStates, dietTagsBox, GOALS_SHELF, goalsShelfWidth, measureExtraGeometry, measurePlacements, shelfLayout, streakStates } from "./measure-extras.mjs";
+import { dietDays, dietStates, goalBaseText, goalStates, dietTagsBox, GOALS_SHELF, goalsShelfWidth, measureExtraGeometry, measurePlacements, shelfLayout, streakStates } from "./measure-extras.mjs";
import { slotRect } from "./modules/layout.mjs";
import { moduleById, moduleProblems, scheduleSlices } from "./modules/index.mjs";
import { resolveMeasureExtra, validateMeasureExtra } from "./modules/measure-extras-settings.mjs";
@@ -258,7 +258,7 @@ test("goals on the shelf: the count and the fanned notes, the fan taking the she
const { html, items } = goalsHtml(schedule(), r, { fonts: {} });
assert.match(html, /<div class="gc"><div class="gn" data-k="s0\.c">1<\/div><div class="gl">goal set<\/div><\/div>/);
assert.match(html, /class="note" data-k="s\d+\.n\d+" style="z-index:19"><div class="tape"><\/div><div class="nf"/);
- assert.match(html, /<div class="nb"[^>]*><div class="bt">LOSE 100<\/div>/, "an older note shows its words beside the one in front");
+ assert.match(html, /<div class="nb"[^>]*><div class="bt"[^>]*>LOSE 100<\/div>/, "an older note shows its words beside the one in front");
// A block per state of the fan: each goal he sets, and each second the goal board alone changes (shelfGoalStates).
assert.equal(items.length, shelfGoalStates(schedule(), goalStates(schedule(), r)).length);
// Off the shelf: the pile in the footage, as it was.
@@ -286,3 +286,78 @@ test("goals on the shelf: the dial's goal board orders the fan -- its headline i
const { html } = goalsHtml(sched, r, { fonts: {} });
assert.match(html, new RegExp(`<div class="mo">\\+${end.active.length - 1} more</div>`));
});
+
+// ---------------------------------------------------------------------------
+// A BACK CARD (operator, 11 Nov): "LOSE 1…" for "LOSE 100" -- the right end is what tells one goal from another, so a
+// back card is never cut on the right: its words end at the card's right edge and their LEFT goes under the card in
+// front. And a goal may say the weight he had stated when he set it, "LOSE 100 (FROM 346.7)" (`goals.base`).
+// ---------------------------------------------------------------------------
+
+/** The page's CSS rule for `sel`, as written. */
+const ruleOf = (html, sel) => new RegExp(`\\n\\s*\\${sel} \\{([^}]*)\\}`).exec(html)?.[1] ?? "";
+
+test("a back card's words are right-aligned to its right edge and never cut with an ellipsis -- for 2, 3, 4 and 8 notes", () => {
+ for (const max of [2, 3, 4, 8]) {
+ const r = renderOf({ ...FAN, goals: { position: "shelf", max } });
+ const { html } = goalsHtml(schedule(), r, { fonts: {} });
+ if (!/class="nb"/.test(html)) continue; // room for every note side by side: no back strips at all
+ const nb = ruleOf(html, ".nb"), bt = ruleOf(html, ".bt"), bh = ruleOf(html, ".bh");
+ assert.match(nb, /align-items: flex-end/, `${max}: the words end at the right`);
+ assert.match(nb, /text-align: right/);
+ assert.match(nb, /left: 0; right: 0/, `${max}: the strip is the card's whole width, so an overflow goes LEFT, under the card in front`);
+ for (const [name, rule] of [["bt", bt], ["bh", bh]]) {
+ assert.doesNotMatch(rule, /ellipsis|max-width/, `${max}: .${name} is never cut on the right`);
+ }
+ // The ×n badge has the top of the strip to itself: the words start under it.
+ const padTop = Number(/padding: ([\d.]+)px/.exec(nb)[1]);
+ const ct = ruleOf(html, ".ct");
+ const badgeFoot = Number(/top: ([\d.]+)px/.exec(ct)[1]) + Number(/height: ([\d.]+)px/.exec(ct)[1]);
+ assert.ok(badgeFoot <= padTop, `${max}: the ×n badge (to ${badgeFoot} px) is above the words (from ${padTop} px)`);
+ }
+ // Sized to fit the strip when they can, 17 px at the least; past that the left goes under.
+ assert.equal(backTextSize("LOSE 40", 80), 22);
+ assert.equal(backTextSize("LOSE 100", 80), 20);
+ assert.equal(backTextSize("LOSE 100 LB OR SO", 80), GOALS_BACK.min);
+ assert.equal(backTextSize("X", 300), GOALS_BACK.max);
+});
+
+test("goals.base: off by default; on, each loss goal says the weight the slice reckons it from, its qualifier kept, never one made up", () => {
+ assert.deepEqual(validateMeasureExtra("goals", { base: true }), []);
+ assert.match(validateMeasureExtra("goals", { base: "yes" }).join(), /base must be true or false/);
+ const off = goalStates(schedule(), renderOf(FAN));
+ assert.ok(off.every((st) => st.notes.every((n) => n.base === null)), "off: no base");
+ const r = renderOf({ ...FAN, goals: { position: "shelf", base: true } });
+ // The slice's bases (measure-slice.mjs goalBase; the fixture predates them): w06 from a stated 346.7, w13 from a
+ // remembered ≈390, every other goal none.
+ const m = clone(MEASURE);
+ m.events.push({ t: null, row: "wb1", kind: "stated", value: 346.7, qualifier: null }, { t: null, row: "wb2", kind: "remembered", value: 390, qualifier: "≈" });
+ for (const st of m.state) {
+ if (st.goal?.row === "w06") st.goal.base = { value: 346.7, row: "wb1", from: "stated" };
+ if (st.goal?.row === "w13") st.goal.base = { value: 390, row: "wb2", from: "remembered" };
+ }
+ const sched = schedule({ measure: m });
+ const states = goalStates(sched, r);
+ // Each note's base is its own goal's state's `goal.base` -- the gauge's -- or none.
+ let withBase = 0;
+ for (const st of states) {
+ const e = m.events.find((x) => x.t === st.at && (x.kind === "goal" || x.kind === "goalLoss"));
+ const s = [...m.state].reverse().find((x) => x.t <= st.at + 1e-9 && x.goal?.row === e.row);
+ const top = st.notes.find((n) => n.key === st.top);
+ const want = s?.goal?.base ? goalBaseText(s.goal.base, m) : null;
+ assert.equal(top.base, want, `${e.row}: the slice's base or none`);
+ if (want) withBase += 1;
+ }
+ assert.equal(withBase, 2);
+ assert.ok(states.some((st) => st.notes.some((n) => n.base === "(FROM ≈390)")));
+ // The words: "(FROM 346.7)", a qualifier kept, nothing for no base.
+ const mm = { events: [{ row: "w21", qualifier: "≈" }, { row: "w7", qualifier: null }] };
+ assert.equal(goalBaseText({ value: 346.7, row: "w7" }, mm), "(FROM 346.7)");
+ assert.equal(goalBaseText({ value: 390, row: "w21" }, mm), "(FROM ≈390)");
+ assert.equal(goalBaseText(null, mm), null);
+ // Drawn on the front card under the goal, and on a back card as a line of its own, right-aligned with the words.
+ const { html } = goalsHtml(sched, r, { fonts: {} });
+ assert.match(html, /<div class="nt">[^<]+<\/div><div class="fr">\(FROM [≈<>]?[\d.]+\)<\/div>/);
+ assert.match(html, /<div class="bt"[^>]*>[^<]+<\/div><div class="bf">\(FROM [≈<>]?[\d.]+\)<\/div>/);
+ // Off: none of it.
+ assert.doesNotMatch(goalsHtml(schedule(), renderOf(FAN), { fonts: {} }).html, /class="(fr|bf)"/);
+});
diff --git a/umtool/report-to-video/stamp-note.test.mjs b/umtool/report-to-video/stamp-note.test.mjs
@@ -0,0 +1,91 @@
+// THE WORDS UNDER AN OUTCOME'S STAMP (a promise_outcome row's `stampNote`, 12 Nov): the promise clock wrote
+// "by <date> · no video" under REFUNDED whatever the record said. A row's own note is that line; the strip over a
+// post's card shows its first clause; with none, the clock's words as they were.
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { promiseHtml } from "./chrome-measure-extras.mjs";
+import { estimateSchedule } from "./deck.mjs";
+import { lintManifest } from "./lint.mjs";
+import { promiseStates, STAMP_NOTE, stampNoteClause, stampNoteLine, stampNoteWarnings } from "./measure-extras.mjs";
+import { measureSlice } from "./measure-slice.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const MEASURE = JSON.parse(readFileSync(path.join(HERE, "fixtures/measure-extras/measure.json"), "utf8"));
+const PAL = { bg: "#0F1312", fg: "#EDF0EC", muted: "#98A29B", accent: "#22AB83", amber: "#E8A33F" };
+const render = (deck = {}) => ({ width: 1920, height: 1080, fps: 30, transition: 0.4, palette: PAL, chrome: { engine: "hyperframes", layout: "deck", deck } });
+const schedule = (measure, extra = {}) => ({ kind: "deck", fps: 30, total: 740, transition: 0.4, segments: [{ id: "a", start: 0, duration: 740, end: 740 }], measure, ...extra });
+const clone = (v) => JSON.parse(JSON.stringify(v));
+const noted = (note) => {
+ const m = clone(MEASURE);
+ for (const s of m.state) for (const p of s.promises ?? []) if (p.outcome) p.outcome.note = note;
+ return m;
+};
+
+test("the words: the note when the row has one, the clock's own otherwise; the strip takes the first clause", () => {
+ assert.equal(stampNoteLine({ kind: "refunded", date: "2026-10-31" }), "by 31 Oct · no video");
+ assert.equal(stampNoteLine({ kind: "refunded", date: null }), "no video");
+ assert.equal(stampNoteLine({ kind: "refunded", date: "2026-10-31", note: " her word · no receipt " }), "her word · no receipt");
+ assert.equal(stampNoteClause({ kind: "refunded" }), "no video");
+ assert.equal(stampNoteClause({ note: "her word · no receipt" }), "her word");
+ assert.equal(stampNoteClause({ note: "by her account, 31 Oct" }), "by her account");
+ assert.equal(stampNoteClause({ note: "she says -- nothing shown" }), "she says");
+ assert.equal(stampNoteClause({ note: "partly; the rest owed" }), "partly");
+ assert.equal(stampNoteClause({ note: "one clause only" }), "one clause only");
+});
+
+test("the slice carries a promise_outcome row's stampNote on the promise's outcome; a row without one is as before", () => {
+ const schema = { kind: "measure", unit: "lb", yMin: 100, yMax: 400, bandGapDays: 60, tracks: [{ key: "weight", role: "value", label: "Weight" }], forms: ["current"] };
+ const row = (o) => ({ scope: "weight", scopeBasis: "x", scopeConfidence: "read", valueKind: "uttered", flags: [], asOf: null, ...o });
+ const ledger = (note) => [
+ row({ id: "p01", date: "2026-10-23", population: "promise", display: "scale video", entryId: "c1" }),
+ row({ id: "o01", date: "2026-10-31", population: "promise_outcome", promise: "p01", outcome: "refunded", speaker: "madamsavvy", entryId: "c2", ...(note === undefined ? {} : { stampNote: note }) }),
+ ];
+ const r = render({ measure: { scopes: ["weight"], asOf: "2026-11-12" } });
+ const timeline = Array.from({ length: 3 }, (_, i) => ({ type: "clip", id: `c${i + 1}`, video: "v", start: 10 * i, end: 10 * i + 8, cite: 1, section: 0, quote: "q", onscreen: { title: `Clip ${i + 1}` } }));
+ const slice = (note) => {
+ const manifest = { slug: "m", title: "M", provenance: {}, render: r, timeline, ledgerSchema: schema, ledger: ledger(note) };
+ return measureSlice(manifest, estimateSchedule(manifest), {});
+ };
+ assert.deepEqual(slice(" by her account ").state.at(-1).promises[0].outcome, { kind: "refunded", date: "2026-10-31", row: "o01", note: "by her account" });
+ assert.deepEqual(slice(undefined).state.at(-1).promises[0].outcome, { kind: "refunded", date: "2026-10-31", row: "o01" });
+ assert.deepEqual(slice(" ").state.at(-1).promises[0].outcome, { kind: "refunded", date: "2026-10-31", row: "o01" });
+ // ... and the clock's states keep it.
+ assert.equal(promiseStates(schedule(slice("by her account")), r).find((s) => s.rows[0].outcome)?.rows[0].outcome.note, "by her account");
+});
+
+test("the page: the stamp's second line is the note (escaped); the column's compact stamp too; the strip its first clause", () => {
+ const r = render({ promise: { speakers: { madamsavvy: { handle: "MadamSavvy" } } } });
+ assert.match(promiseHtml(schedule(MEASURE), r, { fonts: {} }).html, /<div class="sw">Refunded<\/div><div class="ss">by 31 Oct · no video<\/div>/);
+ const html = promiseHtml(schedule(noted("her word · <no> receipt")), r, { fonts: {} }).html;
+ assert.match(html, /<div class="sw">Refunded<\/div><div class="ss">her word · <no> receipt<\/div>/);
+ assert.doesNotMatch(html, /no video/);
+ // The column's compact form (beside the instruments) draws the same stamp.
+ const col = render({ dial: true, promise: { label: "scale video" } });
+ assert.match(promiseHtml(schedule(noted("her word · no receipt")), col, { fonts: {} }).html, /<div class="ss">her word · no receipt<\/div>/);
+ // The strip (the footage slot, a post's card over the clock): "refunded · <first clause>".
+ const f = render({ promise: { label: "scale video" } });
+ const covered = (m) => schedule(m, { covers: [{ segment: "p", from: 715, to: 739, rects: [{ x: 300, y: 100, width: 700, height: 600 }] }] });
+ assert.match(promiseHtml(covered(MEASURE), f, { fonts: {} }).html, /<span class="no">refunded · no video<\/span>/);
+ const strip = promiseHtml(covered(noted("her word · no receipt")), f, { fonts: {} }).html;
+ assert.match(strip, /<span class="no">refunded · her word<\/span>/);
+ assert.doesNotMatch(strip, /<span class="no">refunded · no video<\/span>/);
+});
+
+test("the lint warns when a note is longer than the stamp's line holds -- never refuses", () => {
+ const manifest = (note) => ({ slug: "m", title: "M", provenance: {}, render: render({}), timeline: [{ type: "clip", id: "c1", video: "v", start: 0, end: 8 }],
+ ledger: [{ id: "o01", population: "promise_outcome", outcome: "refunded", stampNote: note }, { id: "w1", population: "current", stampNote: "x".repeat(60) }] });
+ assert.deepEqual(stampNoteWarnings(manifest("by her account")), []);
+ assert.deepEqual(stampNoteWarnings(manifest("x".repeat(STAMP_NOTE.fit))), []);
+ const long = "refunded in full by her account on 31 Oct";
+ const w = stampNoteWarnings(manifest(long));
+ assert.equal(w.length, 1);
+ assert.match(w[0], new RegExp(`ledger o01\\.stampNote "${long}" is ${long.length} characters: the promise clock's stamp holds about ${STAMP_NOTE.fit}`));
+ const lint = lintManifest(manifest(long), { validators: false });
+ assert.ok(lint.warnings.some((x) => x.startsWith("ledger o01.stampNote")), lint.warnings.join("\n"));
+ assert.ok(!lint.errors.some((x) => /stampNote/.test(x)));
+ assert.ok(!lintManifest(manifest("short"), { validators: false }).warnings.some((x) => /stampNote/.test(x)));
+});
diff --git a/umtool/report-to-video/stats.test.mjs b/umtool/report-to-video/stats.test.mjs
@@ -137,9 +137,11 @@ test("the page: one block per state, the numbers as the panel shows them, every
const schedule = estimateSchedule({ render: render(), timeline: ENTRIES, frameScan: OVERLAY });
const { init, cues } = statsCues(schedule);
assert.deepEqual(Object.keys(init).sort(), ["pn", "s0_0", "s0_1", "s1_0"]);
- // The first state shows at the clip's in, hides as the second shows.
+ // The first state shows at the clip's in -- here the cut's first instant, so it is up in init, on frame 0 (cue-start.mjs
+ // settleFirstFrame) -- and hides as the second shows.
const s00 = cues.filter((c) => c.k === "s0_0");
- assert.deepEqual(s00.map((c) => [c.at, c.from.autoAlpha, c.to.autoAlpha]), [[0, 0, 1], [6, 1, 0]]);
+ assert.equal(init.s0_0.autoAlpha, 1);
+ assert.deepEqual(s00.map((c) => [c.at, c.from.autoAlpha, c.to.autoAlpha]), [[6, 1, 0]]);
for (const c of cues) assert.ok(Object.keys(c.to).every((p) => p in c.from), JSON.stringify(c));
const html = statsHtml(schedule, render(), { fonts: { regular: "assets/DeckSans.ttf", bold: "assets/DeckSansBold.ttf" } });
diff --git a/umtool/report-to-video/threads.mjs b/umtool/report-to-video/threads.mjs
@@ -23,6 +23,7 @@ import { resolveFactcheck } from "./factcheck.mjs";
// The limits and the validators are common's (lib/report/panels.mjs, release
// 28): the threads draft task checks exactly what the build refuses.
import { THREADS_LIMITS, threadOf, threadsOn, validateThreadEntries, validateThreads } from "yt-dlp-transcript-common/lib/report/panels.mjs";
+import { settleFirstFrame } from "./cue-start.mjs";
export { THREADS_LIMITS, threadOf, threadsOn, validateThreadEntries, validateThreads };
@@ -172,7 +173,7 @@ export function planCues(init, events, instant = 0.001) {
freeAt.set(e.k, r4(at + dur));
cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease, why: e.why });
}
- return cues;
+ return settleFirstFrame(init, cues);
}
/** A card's resting opacity before its thread plays, and after. */
diff --git a/umtool/report-to-video/trail-plan.mjs b/umtool/report-to-video/trail-plan.mjs
@@ -0,0 +1,150 @@
+// THE TRAIL'S PLAN (the by-date chart strip under the instruments, 11 Nov): which
+// weights it shows at each moment of the cut, and where each one stands then.
+//
+// Before this the strip laid every STATED weight of the whole cut on one fixed
+// pair of axes from the first frame: a remembered weight ("≈390, as of Feb
+// 2023", "368 as of Jun 2008") was never a point, a 2013 weigh-in sat pinned at
+// the left edge of a 2013–2026 axis for minutes, and one straight line crossed
+// a decade of nothing to the 2025–26 points squeezed into the last pixels.
+//
+// Now the chart is a sequence of STATES, one per moment a weight is said: the
+// points said so far -- stated ones, and remembered ones (`remembered`, hollow
+// and grey, never joined into the line) -- at their own dates (asOf, else the
+// day said) and values; the axes FIT what is shown (`bounds: "fit"`; "fixed"
+// pins them to the whole cut's points); and a stretch of time with no statement
+// longer than the gap threshold (`gap`) is not drawn as data: the time axis is
+// cut there into CLUSTERS, each with its own years, a narrow break between them
+// and a dotted connector across it, so the dense recent run gets the width. The
+// page (chrome-instruments.mjs trailHtml) moves everything from one state's
+// places to the next's over TRAIL_REFLOW seconds.
+//
+// PURE: the measure slice and a box in, plain data out.
+import { dayNumber } from "./measure-draw.mjs";
+
+/** Seconds a reflow takes: the axes and every point moving to the new state's places. */
+export const TRAIL_REFLOW = 0.4;
+
+/** `gap: "auto"`: a stretch is a break when longer than this many days, or `GAP_MEDIANS` times the median spacing. */
+export const GAP_FLOOR_DAYS = 365;
+export const GAP_MEDIANS = 8;
+
+const r2 = (v) => Math.round(v * 100) / 100;
+
+/**
+ * The trail's points, in the order the cut says them: `{ n, t, row, value, qualifier, day, kind }`, `kind`
+ * "stated" or "remembered" (only with `remembered`), `day` the day number of its asOf, else its date.
+ */
+export function trailPoints(measure, { remembered = true } = {}) {
+ const out = [];
+ for (const e of measure?.events ?? []) {
+ // A row with no number is no point: `Number(null)` and `Number("")` are 0, which drew a 0 lb point (12 Nov).
+ if (!Number.isFinite(e.t) || e.value === null || e.value === undefined || e.value === "" || typeof e.value === "boolean" || !Number.isFinite(Number(e.value))) continue;
+ if (e.kind !== "stated" && !(remembered && e.kind === "remembered")) continue;
+ const day = dayNumber(e.asOf ?? e.date);
+ if (!Number.isFinite(day)) continue;
+ out.push({ t: e.t, row: e.row ?? null, value: Number(e.value), qualifier: e.qualifier ?? null, day, kind: e.kind });
+ }
+ out.sort((a, b) => a.t - b.t);
+ return out.map((p, n) => ({ ...p, n }));
+}
+
+/** The gap threshold in days: `gap` a number of days, 0/false never, "auto" from the data (see GAP_FLOOR_DAYS). */
+export function gapThreshold(points, gap = "auto") {
+ if (gap === 0 || gap === false) return Infinity;
+ if (typeof gap === "number" && gap > 0) return gap;
+ const days = [...new Set(points.map((p) => p.day))].sort((a, b) => a - b);
+ const steps = days.slice(1).map((d, i) => d - days[i]).sort((a, b) => a - b);
+ const median = steps.length ? steps[Math.floor(steps.length / 2)] : 0;
+ return Math.max(GAP_FLOOR_DAYS, GAP_MEDIANS * median);
+}
+
+/** Days, sorted, cut into clusters where a step is longer than `thr`: `[{ first, last }]`. */
+export function clustersOf(days, thr) {
+ const ds = [...new Set(days)].sort((a, b) => a - b);
+ const out = [];
+ for (const d of ds) {
+ const c = out[out.length - 1];
+ if (c && d - c.last <= thr) c.last = d;
+ else out.push({ first: d, last: d });
+ }
+ return out;
+}
+
+const yearOf = (d) => new Date(d * 86400000).getUTCFullYear();
+const jan1 = (y) => Date.UTC(y, 0, 1) / 86400000;
+
+/**
+ * One state's places: the y bounds (`lo`/`hi`, tens of the unit around the values shown and the mark), the
+ * clusters along x (each `{ first, last, from, to, x0, x1 }`: its days, its padded span, its pixels), the breaks
+ * between them (`gaps`: `{ key, x }`), the year labels (`years`: `{ key, text, x, tick }`), and `X(day)` / `Y(v)`.
+ *
+ * `box` = `{ x0, x1, y0, y1, gapPx, yearPx }` in page pixels.
+ */
+export function trailLayout(points, box, { thr = Infinity, mark = null } = {}) {
+ const { x0, x1, y0, y1 } = box;
+ const gapPx = box.gapPx ?? 22;
+ const yearPx = box.yearPx ?? 34;
+ const vals = points.map((p) => p.value).concat(mark !== null && mark !== undefined ? [mark] : []);
+ const lo = vals.length ? Math.floor((Math.min(...vals) - 5) / 10) * 10 : 0;
+ const hi = vals.length ? Math.ceil((Math.max(...vals) + 5) / 10) * 10 : 10;
+ const cl = clustersOf(points.map((p) => p.day), thr);
+ const spread = cl.reduce((s, c) => s + (c.last - c.first), 0);
+ const pad = Math.max(20, 0.04 * spread);
+ for (const c of cl) {
+ const p = c.last - c.first < 1 ? Math.max(pad, 60) : pad;
+ c.from = c.first - p;
+ c.to = c.last + p;
+ }
+ const widthDays = cl.reduce((s, c) => s + (c.to - c.from), 0) || 1;
+ const scale = Math.max(0, x1 - x0 - gapPx * Math.max(0, cl.length - 1)) / widthDays;
+ let at = x0;
+ for (const c of cl) {
+ c.x0 = r2(at);
+ c.x1 = r2(at + (c.to - c.from) * scale);
+ at = c.x1 + gapPx;
+ }
+ const X = (d) => {
+ const c = cl.find((k) => d >= k.from - 1e-9 && d <= k.to + 1e-9) ?? null;
+ return c ? r2(c.x0 + (d - c.from) * scale) : null;
+ };
+ const Y = (v) => r2(y1 - ((v - lo) / Math.max(1, hi - lo)) * (y1 - y0));
+ const gaps = cl.slice(1).map((c, i) => ({ key: `${cl[i].last}_${c.first}`, x: r2((cl[i].x1 + c.x0) / 2) }));
+ // The years: each cluster's first year labelled at its first point (unless that year's 1 January is a tick in it),
+ // each 1 January inside a cluster's span a tick; then thinned left to right so no two labels are closer than
+ // `yearPx`, a cluster's own year first.
+ const cands = [];
+ for (const c of cl) {
+ const firstYear = yearOf(c.first);
+ if (jan1(firstYear) < c.from) cands.push({ key: `c${firstYear}`, text: String(firstYear), x: X(c.first), tick: false, lead: true });
+ for (let y = yearOf(c.from) + 1; jan1(y) <= c.to; y += 1) cands.push({ key: `t${y}`, text: String(y), x: X(jan1(y)), tick: true });
+ }
+ cands.sort((a, b) => a.x - b.x || (b.lead ? 1 : 0) - (a.lead ? 1 : 0));
+ const years = [];
+ for (const y of cands) if (!years.length || y.x - years[years.length - 1].x >= yearPx) years.push(y);
+ return { lo, hi, clusters: cl, gaps, years, X, Y };
+}
+
+/**
+ * The trail's states: one per moment a point is said (`at`), each with the points shown (`shown`, their `n`), its
+ * layout, each shown point's place (`pos`: n -> {x, y}) and the line's pairs (`pairs`: neighbours by date among the
+ * STATED points shown, `{ key, a, b, gap }`, `gap` when they straddle a break). `bounds: "fixed"` lays every state on
+ * the layout of all the cut's points (the strip as it was, but with its breaks).
+ *
+ * @param {ReturnType<typeof trailPoints>} points
+ */
+export function trailStates(points, box, { gap = "auto", mark = null, bounds = "fit" } = {}) {
+ const thr = gapThreshold(points, gap);
+ const all = bounds === "fixed" ? trailLayout(points, box, { thr, mark }) : null;
+ const times = [...new Set(points.map((p) => p.t))].sort((a, b) => a - b);
+ return times.map((at) => {
+ const shown = points.filter((p) => p.t <= at + 1e-9);
+ const layout = all ?? trailLayout(shown, box, { thr, mark });
+ const pos = new Map(shown.map((p) => [p.n, { x: layout.X(p.day), y: layout.Y(p.value) }]));
+ const stated = shown.filter((p) => p.kind === "stated").sort((a, b) => a.day - b.day || a.t - b.t);
+ const pairs = stated.slice(1).map((b, i) => {
+ const a = stated[i];
+ return { key: `${a.n}_${b.n}`, a: a.n, b: b.n, gap: b.day - a.day > thr };
+ });
+ return { at, shown: shown.map((p) => p.n), layout, pos, pairs, thr };
+ });
+}
diff --git a/umtool/report-to-video/trail-plan.test.mjs b/umtool/report-to-video/trail-plan.test.mjs
@@ -0,0 +1,136 @@
+// THE TRAIL'S PLAN (trail-plan.mjs; chrome-instruments.mjs trailHtml): the by-date chart shows every weight said
+// so far -- stated and remembered -- on axes that fit them and reflow as each lands, its time axis broken across
+// long empty stretches (rev9-a7, 11 Nov: a 2013 dot pinned at the left edge for minutes, 2008 and ≈390 never drawn,
+// one line across a decade to the 2025–26 points squeezed at the right).
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { trailHtml } from "./chrome-instruments.mjs";
+import { estimateSchedule } from "./deck.mjs";
+import { clustersOf, GAP_FLOOR_DAYS, gapThreshold, trailLayout, trailPoints, trailStates } from "./trail-plan.mjs";
+import { dayNumber } from "./measure-draw.mjs";
+import { validateTrail } from "./instruments.mjs";
+
+/** The a7 sequence: a 2013 weigh-in and a second 2013 weight; a remembered ≈390 (as of Feb 2023) above them; a
+ * remembered 368 as of 2008 -- before everything and above the old top; then the dense 2025–26 run. */
+const ev = (t, kind, value, date, extra = {}) => ({ t, kind, value, date, row: `r${t}`, scope: "weight", qualifier: null, asOf: null, ...extra });
+const EVENTS = [
+ ev(9, "stated", 346.7, "2013-03-09"),
+ ev(31, "stated", 342.9, "2013-03-21"),
+ ev(60, "remembered", 390, "2023-09-29", { asOf: "2023-02-24", qualifier: "≈" }),
+ ev(100, "remembered", 368, "2025-01-10", { asOf: "2008-06-30" }),
+ ev(175, "stated", 349, "2025-04-08"),
+ ev(204, "stated", 341, "2025-06-02"),
+ ev(225, "stated", 336, "2025-07-15"),
+ ev(230, "stated", 331.5, "2025-08-01"),
+ ev(280, "stated", 322, "2025-10-08"),
+ ev(293, "stated", 318, "2025-11-20"),
+ ev(320, "stated", 305, "2026-01-16"),
+ ev(324, "stated", 299, "2026-03-02"),
+ ev(337, "stated", 296, "2026-06-01", { qualifier: "≈" }),
+ ev(347, "goal", 250, "2026-07-01"),
+];
+const MEASURE = { unit: "lb", scale: { min: 220, max: 400 }, events: EVENTS, state: [{ t: 0 }], totals: {} };
+const BOX = { x0: 54, x1: 582, y0: 38, y1: 174, gapPx: 22, yearPx: 34 };
+
+test("the trail's points: stated and remembered, each at its own date (asOf first), in the cut's order", () => {
+ const pts = trailPoints(MEASURE);
+ assert.equal(pts.length, 13, "the goal is not a weight");
+ assert.deepEqual(pts.map((p) => p.kind).slice(0, 5), ["stated", "stated", "remembered", "remembered", "stated"]);
+ assert.equal(pts[3].day, dayNumber("2008-06-30"), "a remembered weight stands at the day it was his weight");
+ assert.equal(trailPoints(MEASURE, { remembered: false }).length, 11);
+});
+
+test("at every moment the chart shows exactly the weights said by then, on axes that contain all of them", () => {
+ const pts = trailPoints(MEASURE);
+ const states = trailStates(pts, BOX, { mark: 300 });
+ assert.equal(states.length, 13);
+ for (const st of states) {
+ const shown = pts.filter((p) => p.t <= st.at);
+ assert.equal(st.shown.length, shown.length, `at ${st.at}`);
+ for (const p of shown) {
+ assert.ok(st.layout.lo <= p.value && p.value <= st.layout.hi, `at ${st.at}: ${p.value} inside ${st.layout.lo}–${st.layout.hi}`);
+ const { x, y } = st.pos.get(p.n);
+ assert.ok(x !== null && x >= BOX.x0 && x <= BOX.x1, `at ${st.at}: ${p.value} on the x axis (${x})`);
+ assert.ok(y >= BOX.y0 && y <= BOX.y1, `at ${st.at}: ${p.value} on the y axis (${y})`);
+ }
+ }
+ // The first weigh-in alone: in the middle of the strip, not pinned to its left edge.
+ const one = states[0].pos.get(0).x;
+ assert.ok(one > BOX.x0 + 100 && one < BOX.x1 - 100, `a lone point stands mid-strip (${one})`);
+ // The remembered ≈390 raises the top; the 2008 one moves the start of time back and keeps 390 in.
+ assert.ok(states[1].layout.hi < 390 && states[2].layout.hi >= 390);
+ assert.ok(states[3].pos.get(3).x < states[3].pos.get(0).x, "2008 stands left of 2013");
+ // The axes advance with the story: no 2026 on the axis until a 2026 weight is said.
+ const years = (st) => st.layout.years.map((y) => y.text);
+ assert.ok(!years(states[4]).includes("2026"));
+ assert.ok(years(states.at(-1)).includes("2026"));
+});
+
+test("the gap rule: a stretch longer than a year (or 8× the median spacing) breaks the time axis; the dense run gets the width", () => {
+ const pts = trailPoints(MEASURE);
+ // The median step between the dates here is 57 days: 8× is 456, past the year's floor.
+ assert.equal(gapThreshold(pts), 456);
+ assert.equal(gapThreshold([0, 7, 14, 21, 28].map((day) => ({ day }))), GAP_FLOOR_DAYS, "weekly statements: the year's floor rules");
+ assert.equal(gapThreshold(pts, 540), 540);
+ assert.equal(gapThreshold(pts, 0), Infinity);
+ // Spacing of 100 days: 8× is 800, past the floor.
+ const sparse = [0, 100, 200, 300, 400].map((day) => ({ day }));
+ assert.equal(gapThreshold(sparse), 800);
+ assert.deepEqual(clustersOf([1, 2, 500, 900, 901], 365), [{ first: 1, last: 2 }, { first: 500, last: 500 }, { first: 900, last: 901 }]);
+ const last = trailStates(pts, BOX, { mark: 300 }).at(-1);
+ // 2008 | 2013 | 2023 | 2025–26: three breaks, each a narrow band.
+ assert.equal(last.layout.clusters.length, 4);
+ assert.equal(last.layout.gaps.length, 3);
+ const dense = last.layout.clusters.at(-1);
+ assert.ok(dense.x1 - dense.x0 > 0.5 * (BOX.x1 - BOX.x0), `the 2025–26 run has most of the width (${dense.x1 - dense.x0} px)`);
+ // The line: stated neighbours only -- the remembered never joined -- dotted across a break.
+ const byN = new Map(pts.map((p) => [p.n, p]));
+ for (const pr of last.pairs) assert.ok(byN.get(pr.a).kind === "stated" && byN.get(pr.b).kind === "stated");
+ const across = last.pairs.find((pr) => byN.get(pr.a).value === 342.9);
+ assert.equal(across.gap, true, "2013 to 2025 is a dotted connector, not data");
+ assert.ok(last.pairs.filter((pr) => !pr.gap).length >= 8);
+ // gap: 0 -- one cluster, no breaks.
+ assert.equal(trailStates(pts, BOX, { gap: 0, mark: 300 }).at(-1).layout.gaps.length, 0);
+ // bounds: "fixed" -- every moment on the whole cut's axes.
+ const fixed = trailStates(pts, BOX, { bounds: "fixed", mark: 300 });
+ assert.equal(fixed[0].layout.hi, fixed.at(-1).layout.hi);
+});
+
+test("the page: points pop in where their moment puts them and move with every reflow, seek-safe; the knobs validate", () => {
+ const timeline = Array.from({ length: 4 }, (_, i) => ({ type: "clip", id: `c${i + 1}`, video: "v", start: 0, end: 100 }));
+ const render = { width: 1920, height: 1080, fps: 30, transition: 0.4, palette: { bg: "#0F1312", fg: "#EDF0EC", muted: "#98A29B", accent: "#22AB83", amber: "#E8A33F" },
+ chrome: { engine: "hyperframes", layout: "deck", deck: { dial: true, odometer: true, trail: true } } };
+ const schedule = { ...estimateSchedule({ slug: "m", title: "M", provenance: {}, render, timeline }), measure: MEASURE };
+ const html = trailHtml(schedule, render, { fonts: {} });
+ const data = JSON.parse(/<script id="trail-data" type="application\/json">(.*?)<\/script>/s.exec(html)[1]);
+ assert.match(html, /class="pt rem q" data-k="p2"/, "the remembered ≈390: hollow, grey, its qualifier dashed");
+ assert.match(html, /class="seg gap" data-k="s1_4"/, "2013 → 2025 dotted");
+ assert.ok(!/data-k="s\d+_2"|data-k="s2_\d+"/.test(html), "the remembered are never joined");
+ // p0 (the 2013 weigh-in) moves when the 2013 second weight lands, and again when 2008 pushes time back.
+ const moves = data.cues.filter((c) => c.k === "p0" && "x" in c.to).map((c) => c.at);
+ assert.ok(moves.includes(31) && moves.includes(100), `p0 reflows at 31 and 100 (${moves})`);
+ // Every cue states its from (seek-safe), and nothing changes at 0 that frame 0 cannot show.
+ assert.ok(data.cues.every((c) => Object.keys(c.to).every((k) => k in c.from)));
+ assert.deepEqual(validateTrail({ bounds: "fixed", remembered: false, gap: 540 }), []);
+ assert.match(validateTrail({ gap: 10 }).join(), /gap must be "auto", 0 \(no breaks\) or 30 to 3650 days/);
+ assert.match(validateTrail({ bounds: "loose" }).join(), /bounds must be "fit" or "fixed"/);
+});
+
+test("a row with no number is no point: a null, missing, empty or non-numeric value never becomes a 0 lb point", () => {
+ const ev = (o) => ({ t: 10, kind: "stated", date: "2026-01-01", row: "w", ...o });
+ const pts = trailPoints({ events: [
+ ev({ t: 1, row: "a", value: 300 }),
+ ev({ t: 2, row: "null", value: null }),
+ ev({ t: 3, row: "missing" }),
+ ev({ t: 4, row: "empty", value: "" }),
+ ev({ t: 5, row: "words", value: "about three hundred" }),
+ ev({ t: 6, row: "bool", value: false }),
+ ev({ t: 7, row: "zero", value: 0 }),
+ ev({ t: 8, row: "text", value: "291.5" }),
+ ev({ t: 9, row: "nan", value: NaN }),
+ ] });
+ // A real 0 and a number written as text are still points.
+ assert.deepEqual(pts.map((p) => [p.row, p.value]), [["a", 300], ["zero", 0], ["text", 291.5]]);
+ assert.deepEqual(pts.map((p) => p.n), [0, 1, 2]);
+});
diff --git a/umtool/report-to-video/update-flash.mjs b/umtool/report-to-video/update-flash.mjs
@@ -0,0 +1,84 @@
+// THE UPDATE FLASH (operator, 11 Nov: "whenever a widget gets updated, have it
+// show a subtle border flash or something to indicate that at a glance"): at
+// the moment a measure widget's shown value changes, a thin outline just inside
+// its edge lights over FLASH_MOTION.up and decays over FLASH_MOTION.down, in the
+// widget's own colour -- no size change, no layout shift. Widgets that change on
+// the same event flash together (each reads the same event times).
+//
+// What counts as a change, per widget (each page picks its own times):
+// the dial a new stated weight, a remembered one, a goal in force changing
+// the odometer the pounds lost going up (or its runs), NET changing
+// the trail each weight landing on the chart
+// the diet a new diet (a new front tag) -- never the running day count
+// the goals a goal set (a note landing) -- not the board's own changes
+// Never on frame 0, never while the deck is away (the intro, a card, the
+// finale's hand-over), never on a widget's first appearance (its own entrance
+// marks that) unless it is the dial, which stands from the start.
+//
+// OFF by default: `render.chrome.deck.measure.flash: true` turns it on for
+// every widget; a widget's own `flash` (true/false) overrides that for it.
+import { deckChoreography } from "./deck.mjs";
+
+/** Seconds: the outline's rise and its decay. */
+export const FLASH_MOTION = Object.freeze({ up: 0.15, down: 0.7 });
+
+/** Is the flash on for a widget: its own `flash` when it says, else `deck.measure.flash`. */
+export function flashOn(render, own = null) {
+ if (typeof own === "boolean") return own;
+ return render?.chrome?.deck?.measure?.flash === true;
+}
+
+/** The spans the deck is away (deckChoreography's visibility): `[{ from, to }]`, `to` Infinity when it stays away. */
+export function deckAwaySpans(schedule, render) {
+ let vis = [];
+ try {
+ vis = deckChoreography(schedule, render).visibility;
+ } catch {
+ return [];
+ }
+ const out = [];
+ let open = null;
+ for (const v of [...vis].sort((a, b) => a.at[0] - b.at[0])) {
+ if (v.hide && open === null) open = v.at[0];
+ else if (!v.hide && open !== null) { out.push({ from: open, to: v.at[1] }); open = null; }
+ }
+ if (open !== null) out.push({ from: open, to: Infinity });
+ return out;
+}
+
+/**
+ * The moments a widget flashes: its change `times`, sorted, one per 0.05 s, none before frame 1 and none while the
+ * deck is away (`away`, deckAwaySpans).
+ */
+export function flashTimes(times, { fps = 30, away = [] } = {}) {
+ const frame = 1 / (Number(fps) > 0 ? Number(fps) : 30);
+ const out = [];
+ for (const t of [...times].filter(Number.isFinite).sort((a, b) => a - b)) {
+ if (t < frame - 1e-9) continue;
+ if (away.some((s) => t >= s.from - 1e-6 && t < s.to)) continue;
+ if (out.length && t - out[out.length - 1] < 0.05) continue;
+ out.push(t);
+ }
+ return out;
+}
+
+/** The outline's cue events (compileCues / cueList shape): up, then down, at each time. */
+export function flashEvents(k, times) {
+ const { up, down } = FLASH_MOTION;
+ return times.flatMap((t) => [
+ { k, at: t, dur: up, to: { opacity: 1 }, ease: "power1.out" },
+ { k, at: t + up, dur: down, to: { opacity: 0 }, ease: "power2.out" },
+ ]);
+}
+
+/** A cueList's adds for the outline `k` (its init: hidden). */
+export function flashCues(L, k, times) {
+ L.set(k, { opacity: 0 });
+ for (const e of flashEvents(k, times)) L.add(e.k, e.at, e.dur, e.to, e.ease);
+}
+
+/** The outline's look: a thin line in `color` just inside the box (`inset` negative: just outside), a soft glow; `radius` its corners (CSS). */
+export function flashCss(sel, color, { radius = "0px", width = 2, inset = "0px" } = {}) {
+ return `${sel} { position: absolute; inset: ${inset}; border-radius: ${radius}; border: ${width}px solid ${color};
+ box-shadow: 0 0 ${width * 5}px ${color}, inset 0 0 ${width * 3}px ${color}; opacity: 0; pointer-events: none; }`;
+}
diff --git a/umtool/report-to-video/update-flash.test.mjs b/umtool/report-to-video/update-flash.test.mjs
@@ -0,0 +1,130 @@
+// THE UPDATE FLASH (update-flash.mjs; operator, 11 Nov): a measure widget's outline lights at the moment its
+// shown value changes -- exactly that widget, exactly then -- and never on frame 0, over the intro, or on a widget's
+// first appearance. Off by default: a cut renders as it did.
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { estimateSchedule } from "./deck.mjs";
+import { dialHtml, odometerHtml, trailHtml } from "./chrome-instruments.mjs";
+import { dietHtml, goalsHtml, shelfGoalStates } from "./chrome-measure-extras.mjs";
+import { dietStates, goalStates } from "./measure-extras.mjs";
+import { measureTrack } from "./measure-draw.mjs";
+import { validateMeasureSettings } from "./measure-slice.mjs";
+import { validateDial } from "./instruments.mjs";
+import { validateMeasureExtra } from "./modules/measure-extras-settings.mjs";
+import { trailPoints } from "./trail-plan.mjs";
+import { FLASH_MOTION, flashOn, flashTimes } from "./update-flash.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const DIAL = JSON.parse(readFileSync(path.join(HERE, "fixtures", "measure-dial", "measure.json"), "utf8"));
+const EXTRAS = JSON.parse(readFileSync(path.join(HERE, "fixtures", "measure-extras", "measure.json"), "utf8"));
+const FPS = 30;
+const PALETTE = { bg: "#0F1312", fg: "#EDF0EC", muted: "#98A29B", accent: "#22AB83", amber: "#E8A33F" };
+const deckOf = (deck) => ({ width: 1920, height: 1080, fps: FPS, transition: 0.4, palette: PALETTE, chrome: { engine: "hyperframes", layout: "deck", deck } });
+const INSTR = { dial: true, odometer: true, trail: true, qr: { show: false }, finale: { video: "side", totals: false } };
+const ON = deckOf({ ...INSTR, measure: { flash: true } });
+const OFF = deckOf(INSTR);
+
+/** The instruments' fixture cut: 9 clips, the last the finale -- optionally opening on the intro. */
+function cut(render, { intro = false } = {}) {
+ const timeline = Array.from({ length: 9 }, (_, i) => ({
+ type: "clip", id: `c${i + 1}`, video: "vidx", start: 10 * i, end: 10 * i + (i === 8 ? 14 : 8), cite: 1, section: 0,
+ quote: "q", onscreen: { title: `Clip ${i + 1}` }, ...(i === 8 ? { layout: "finale" } : {}),
+ }));
+ if (intro) timeline.unshift({ type: "intro", id: "brand-intro", style: "boot-dark", seconds: 4.75, heading: "Intro" });
+ return { ...estimateSchedule({ slug: "m", title: "M", provenance: {}, render, timeline }), measure: DIAL };
+}
+const dataOf = (html, id) => JSON.parse(new RegExp(`<script id="${id}-data" type="application/json">(.*?)</script>`, "s").exec(html)[1]);
+/** The moments an outline `k` lights: its rising cues. */
+const lit = (data, k = "fl") => data.cues.filter((c) => c.k === k && c.to.opacity === 1).map((c) => c.at);
+const near = (a, b) => a.length === b.length && a.every((x, i) => Math.abs(x - b[i]) < 0.02);
+
+test("off by default: no outline on any widget, and the pages are the pages they were", () => {
+ const s = cut(OFF);
+ for (const [id, html] of [["dial", dialHtml(s, OFF, {})], ["odometer", odometerHtml(s, OFF, {})], ["trail", trailHtml(s, OFF, {})]]) {
+ assert.doesNotMatch(html, /data-k="fl"/, id);
+ assert.equal(lit(dataOf(html, id)).length, 0, id);
+ }
+ assert.equal(flashOn(OFF), false);
+ assert.equal(flashOn(ON), true);
+ assert.equal(flashOn(ON, false), false, "a widget's own false beats the measure's true");
+ assert.equal(flashOn(OFF, true), true);
+});
+
+test("a value change at t lights exactly the widget whose value changed, at t -- and nothing else does", () => {
+ const s = cut(ON);
+ const track = measureTrack(DIAL);
+ const frame = 1 / FPS;
+ const want = (times) => flashTimes(times, { fps: FPS });
+ const dialT = want([...track.current.slice(1), ...track.remembered, ...track.goals.slice(1)].map((x) => x.t));
+ const odoT = want([...track.lost.slice(1), ...track.net.slice(1)].map((x) => x.t));
+ const trailT = want(trailPoints(DIAL).map((p) => p.t));
+ const got = { dial: lit(dataOf(dialHtml(s, ON, {}), "dial")), odometer: lit(dataOf(odometerHtml(s, ON, {}), "odometer")), trail: lit(dataOf(trailHtml(s, ON, {}), "trail")) };
+ assert.ok(near(got.dial, dialT), `dial ${got.dial} vs ${dialT}`);
+ assert.ok(near(got.odometer, odoT), `odometer ${got.odometer} vs ${odoT}`);
+ assert.ok(near(got.trail, trailT), `trail ${got.trail} vs ${trailT}`);
+ assert.ok(got.dial.length && got.odometer.length && got.trail.length);
+ // A moment only the odometer changes at (a loss claim, no weight stated): the odometer lights, the dial does not.
+ const onlyOdo = odoT.find((t) => !dialT.some((d) => Math.abs(d - t) < 0.02) && !trailT.some((d) => Math.abs(d - t) < 0.02));
+ assert.ok(onlyOdo !== undefined, "the fixture has a loss claim with no weight stated with it");
+ assert.ok(!got.dial.some((t) => Math.abs(t - onlyOdo) < 0.02));
+ // A stated weight lights the dial and the trail together, at the same instant.
+ const both = dialT.find((t) => trailT.some((d) => Math.abs(d - t) < 0.02));
+ assert.ok(both !== undefined && got.trail.some((t) => Math.abs(t - both) < 0.02));
+ // Up over 0.15 s, down over 0.7 s; never before frame 1.
+ const d = dataOf(dialHtml(s, ON, {}), "dial");
+ const up = d.cues.find((c) => c.k === "fl" && c.to.opacity === 1);
+ const down = d.cues.find((c) => c.k === "fl" && c.to.opacity === 0);
+ assert.equal(up.dur, FLASH_MOTION.up);
+ assert.equal(down.dur, FLASH_MOTION.down);
+ assert.ok(Object.values(got).flat().every((t) => t >= frame));
+ assert.deepEqual(d.init.fl, { opacity: 0 }, "dark on frame 0");
+});
+
+test("never over the intro: a change said while the deck is away does not light anything", () => {
+ const s = cut(ON, { intro: true });
+ const introEnd = s.segments[1].start;
+ for (const [id, html] of [["dial", dialHtml(s, ON, {})], ["odometer", odometerHtml(s, ON, {})], ["trail", trailHtml(s, ON, {})]]) {
+ const times = lit(dataOf(html, id));
+ assert.ok(times.every((t) => t >= introEnd), `${id}: ${times} after ${introEnd}`);
+ }
+ // The fixture's changes at 2 and 3.75 s fall inside the 4.75 s intro: they are dropped, not moved.
+ assert.ok(!lit(dataOf(dialHtml(s, ON, {}), "dial")).some((t) => t < introEnd));
+});
+
+test("the goal stack and the diet tags: a goal set / a new diet lights the card that lands -- never the first", () => {
+ const FAN = { dial: true, odometer: true, trail: true, shelf: { items: ["diet", "goals"] }, diet: { position: "shelf", form: "tags", overlap: 0.6, days: true }, goals: { position: "shelf" }, streak: false, measure: { flash: true } };
+ const r = deckOf(FAN);
+ const sched = { kind: "deck", fps: FPS, total: 740, transition: 0.4, segments: [{ id: "a", start: 0, duration: 740, end: 740 }], measure: EXTRAS };
+ const shelf = shelfGoalStates(sched, goalStates(sched, r));
+ const g = dataOf(goalsHtml(sched, r, { fonts: {} }).html, "goals");
+ const gLit = g.cues.filter((c) => /\.fl$/.test(c.k) && c.to.opacity === 1);
+ const wantG = shelf.filter((st, j) => j > 0 && st.top).map((st) => st.at);
+ assert.ok(near(gLit.map((c) => c.at), wantG), `goals ${gLit.map((c) => c.at)} vs ${wantG}`);
+ assert.ok(!gLit.some((c) => c.k.startsWith("s0.")), "the first goal is the stack's entrance");
+ // A board-only change (met, missed) is not a goal set: no outline.
+ assert.ok(shelf.some((st) => !st.top), "the fixture's board changes on its own") ;
+ const states = dietStates(sched, r);
+ const d = dataOf(dietHtml(sched, r, { fonts: {} }).html, "diet");
+ const dLit = d.cues.filter((c) => /\.fl$/.test(c.k) && c.to.opacity === 1).map((c) => c.at);
+ const wantD = states.filter((st, j) => j > 0 && st.tags[0]?.id !== states[j - 1].tags[0]?.id).map((st) => st.at);
+ assert.ok(near(dLit, wantD), `diet ${dLit} vs ${wantD}`);
+ // The running day count changes far more often than the diet: it never lights the tag.
+ assert.ok(dLit.length < d.cues.filter((c) => /\.y\d+$/.test(c.k)).length);
+ // Off: nothing.
+ const off = deckOf({ ...FAN, measure: undefined });
+ assert.doesNotMatch(goalsHtml(sched, off, { fonts: {} }).html, /class="fl"/);
+ assert.doesNotMatch(dietHtml(sched, off, { fonts: {} }).html, /class="fl"/);
+});
+
+test("the knobs: deck.measure.flash and each widget's own flash validate", () => {
+ assert.deepEqual(validateMeasureSettings({ flash: true }), []);
+ assert.match(validateMeasureSettings({ flash: "on" }).join(), /measure\.flash must be true or false/);
+ assert.deepEqual(validateDial({ flash: false }), []);
+ assert.match(validateDial({ flash: 1 }).join(), /dial\.flash must be true or false/);
+ assert.deepEqual(validateMeasureExtra("goals", { flash: true }), []);
+ assert.match(validateMeasureExtra("diet", { flash: "x" }).join(), /flash must be true, false or null/);
+});
diff --git a/umtool/report-to-video/vertical-deck.test.mjs b/umtool/report-to-video/vertical-deck.test.mjs
@@ -266,7 +266,10 @@ const MAIN = {
deck: "546848c82d65e45e4d1a4ac4c7a9c3c8",
dial: "f7e21e4a3622703975f746d39cbcb738",
odometer: "8425983d217408dddcb6ee794881c6c4",
- trail: "3512192be69f8b9bc33aec6e7b41a088",
+ // Re-pinned on lane/frame-zero (11 Nov): the trail's axes fit the weights said so far and reflow, its remembered
+ // weights are points, its time axis breaks over long empty stretches (trail-plan.mjs) -- the page is new by design.
+ // Main's was 3512192be69f8b9bc33aec6e7b41a088.
+ trail: "39c3694f4e26963277d9b22ebfd0f60b",
dialFinale: "52866e4d87e15bd55afe8c1a703414a3",
geometry: "182959796c281f769766df3d02962904",
bare: "7ce1f7a66452adec21575bcdbba900f1",