commit 6142eb2d5923e1501a89dbb35212573ab3bf8d83
parent e9a7a44fe40a7d77a33dd27cc13e975a06e7f43a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 11 Nov 2026 12:42:03 -0500
Merge main (fc5f479e) into lane/model-log: no conflicts; generated docs regenerated
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat:
195 files changed, 10037 insertions(+), 321 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
@@ -91,7 +91,7 @@ pnpm ops render-mode --json '{"on":true,"for":"90m"}' # the same with only pnpm
While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other
renders) waits at the heavy slot's door — `queue-lock: held for a render (umtool take <p> --id
<t>, since 13:31) — waiting` is the gate working — while the render runs on the floor 4000 MB
-and the cap 10240 MB; the editor's transcription and download lanes are held (only the ones
+and the cap 10240 MB; the editor's transcription, download and Speakers lanes are held (only the ones
not already held; only those are released). **A script uses `render-mode on -- <cmd …>`, never a bare `on`**: the
command carries the token, the hold is its pid, and it ends when the command exits — a bare `on`
in a script leaves a window behind and its later commands wait at the door (the chain trap);
diff --git a/CHANNEL.md b/CHANNEL.md
@@ -40,6 +40,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f
| `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. |
| `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. |
| `fullSweepIntervalMinutes` | config | Full-sweep cadence: a sync upgrades itself to a full sweep when `now - lastFullSweepAt >= fullSweepIntervalMinutes`. Absent = inherit `syncScheduler.fullSweepIntervalMinutes`; 0 = never sweep (every sync is a paged walk); positives clamp to [1, 44640]. |
| `skipLiveDownloads` | config | Per-channel override for the global `skipLiveDownloads`. Absent = inherit; false = allow downloading currently-live / upcoming videos. |
@@ -56,6 +57,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
@@ -143,6 +143,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. | |
@@ -167,8 +172,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `check-windows` | check-windows probes cached clip windows (data/<id>/clips/) for a picture that runs off the sound (a Rumble HLS seek) and sets each desynced one aside as <from>-<to>.desynced.<ext> (never deleted; no reader sees it, and evict-clips ages it out): {"slug"?, "video"?, "dryRun"?}. "video" needs "slug"; "dryRun" only lists. A fetch then fills the span again, from the saved video first. | |
| `reports-prepare` | reports-prepare cuts every clip and copies every post capture a site's published reports cite into its report-media cache, before its build: {"siteId"}. The job fails, naming each one, when a citation lacks media. When nothing is missing it then exports the reports, as reports-export. {"articles": true} does it for the published articles (transcripts/ reports/, the homepage's); {"article": "<id>"} adds that one (a draft). | `pnpm ops reports-prepare --json '{"siteId":"demo-site"}' --wait`<br>`pnpm ops reports-prepare --json '{"articles":true}' --wait` |
| `reports-export` | reports-export writes each published report as report.html, report.pdf, report.md, slides.html, slides.pdf and evidence-pack.zip for the site's build to publish: {"siteId", "reportId"?, "formats"?: \["html","pdf","md", "slides","slides-pdf","zip"\]}; {"articles": true, "reportId"?, …} the articles' (reportId: one article, published or a draft). | `pnpm ops reports-export --json '{"siteId":"demo-site","formats":["html","md"]}' --wait` |
-| `lane` | lane takes {"lane": "transcription"\|"download"\|"digest"\|"backfill"\| "publish", "enabled"?, "held"?, "action"?: "start"\|"stop"\|"drain"}, or {"lane": "report-schedule", "held"}: the recurring reports' gate, its only key. | `pnpm ops lane --json '{"lane":"download","held":true}'`<br>`pnpm ops lane --json '{"lane":"publish","action":"drain"}'` |
-| `render-mode` | 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 stages, other renders — waits at the heavy slot's door, and holds the transcription and download lanes (only the ones not already held; only those are released). The answer's "join" (RENDER\_PRIORITY\_TOKEN=…) lets a render in, on the floor 4000 MB and the cap 10240 MB; every `umtool take` joins by itself. {"on": false} ends it ("force": true ends a running take's hold, which otherwise ends with the take). `umtool take … --priority` is the same for one take. `get render-mode` says whether it is on, for what, since when, which lanes it holds. Close Firefox and other heavy apps while it renders. | `pnpm ops render-mode --json '{"on":true,"for":"90m","note":"the Ember cut"}'`<br>`pnpm ops render-mode --json '{"on":false}'` |
+| `lane` | lane takes {"lane": "transcription"\|"download"\|"digest"\|"backfill"\| "publish", "enabled"?, "held"?, "action"?: "start"\|"stop"\|"drain"}, or {"lane": "report-schedule", "held"}: the recurring reports' gate, its only key. An auto-queue lane also takes "operations": \[ids\] \| null (dispatch only these — \["diarization"\] is speakers only; null widens it again) and "order" ("space" on backfill: corpus-disk channels first, then the most audio bytes per audio-hour). The backfill (Speakers) lane takes "speakers": "work" (the deck's Work through speakers: arm, lift the hold, start a run) \| "pause" (hold; stays armed). | `pnpm ops lane --json '{"lane":"download","held":true}'`<br>`pnpm ops lane --json '{"lane":"backfill","operations":["diarization"],"order":"space"}'`<br>`pnpm ops lane --json '{"lane":"backfill","speakers":"work"}'`<br>`pnpm ops lane --json '{"lane":"publish","action":"drain"}'` |
+| `render-mode` | 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 stages, other renders — waits at the heavy slot's door, and holds the transcription, download and Speakers lanes (only the ones not already held; only those are released). The answer's "join" (RENDER\_PRIORITY\_TOKEN=…) lets a render in, on the floor 4000 MB and the cap 10240 MB; every `umtool take` joins by itself. {"on": false} ends it ("force": true ends a running take's hold, which otherwise ends with the take). `umtool take … --priority` is the same for one take. `get render-mode` says whether it is on, for what, since when, which lanes it holds. Close Firefox and other heavy apps while it renders. | `pnpm ops render-mode --json '{"on":true,"for":"90m","note":"the Ember cut"}'`<br>`pnpm ops render-mode --json '{"on":false}'` |
| `tags` | tags edits the curated-tag vocabulary through its one writer: {"op": "define", "tag": {...}} (the WHOLE definition: id, label, rules and "sites", the sites it exists on, absent = every site) or {"op": "remove", "tag": "<id>"}. `get tags [<id>]` reads it. | `pnpm ops tags --json '{"op":"define","tag":{"id":"eva-collab","label":"Collab"}}'` |
| `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"}'` |
@@ -180,7 +185,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `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. | |
-| `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":{"minFreeDiskGB":20}}'` |
+| `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"}'` |
| `dismiss-service` | — | |
@@ -191,6 +196,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `do-not-clean` | do-not-clean sets one video's "Do not clean" marker: {"slug", "id", "keep"?: true}; "keep": false removes it. (keep-videos is the bulk form.) | |
| `drop-saved-alternate` | drop-saved-alternate deletes one saved alternate of one video, as its "Drop this alternate" button does: {"slug", "id", "file", "dryRun"?}. "file" is a name `get saved-alternates` lists under "alternates"; the active copy, an unlisted name and any path are refused, and so is a store being moved. The file goes from the store and its entry from saved-video.json (the rest of the pointer is untouched); one already gone is cleaned from the pointer ("existed": false). "dryRun": true answers the same and changes nothing. No undo. | |
| `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait` |
+| `diarize` | diarize runs a channel's "Diarize speakers" as a job: {"slug"}. Every video still holding audio with no current diarization.json is diarized, and a diarized one without voice fingerprints gets them from its own turns — the voiceprint backfill, one channel at a time. Runs while the Speakers lane is paused; nothing is deleted. | `pnpm ops diarize --json '{"slug":"x"}' --wait` |
| `web-search` | web-search searches the web (DuckDuckGo's HTML page) and answers the results: {"query", "n"?: 6 (at most 20)} -> {results: \[{title, url, snippet}\]}. Read only, through the editor's one web queue: one request at a time, 3 s apart, backing off on a 429 or 503. For context; a web page is never cited as what someone said. | `pnpm ops web-search --json '{"query":"second shop opening","n":5}'` |
| `web-fetch` | web-fetch reads one web page as plain text: {"url", "maxChars"?: 12000 (at most 60000)} -> {page: {url, finalUrl, status, contentType, title?, text, truncated}}. http and https only; a private or loopback host (by name, by address, or by what its name resolves to, every redirect checked) is refused before any request, and so is a page that is not text (a PDF, an image). Read only, on the same web queue as web-search. | `pnpm ops web-fetch --json '{"url":"https://example.com/news/item","maxChars":4000}'` |
| `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -> {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. {"youtubeId", "limit"?: 10} looks for mirrors of one YouTube upload instead: items OF it (their identifier, a file name or their original URL names the id; a title or description that mentions it is not enough), each read for its files -> {query, found, items: \[{identifier, title?, file, url, source, size?, seconds?, namedBy}\], skipped: \[{identifier, why}\]}: each mirror's direct video file URL, an original preferred. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'`<br>`pnpm ops archive-search --json '{"youtubeId":"dQw4w9WgXcQ"}'` |
@@ -243,6 +249,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait]
pnpm ops get x-session [<slug>]
pnpm ops get x-run [<run id>]
pnpm ops get cleanup <slug>
+ pnpm ops get speakers
pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]
pnpm ops get transcript <videoId> [--slug <slug>]
pnpm ops get coverage <slug>
@@ -326,6 +333,14 @@ get x-run [<run id>] is the X run as /review's X run console shows it:
rank, slug), "jar" (its age, social.x.maxCookieAgeMinutes, staleAt:
when it passes the limit, and whether an X job would start now),
gapSeconds (X's queue gap) and maxPosts. Nothing is asked of X.
+get speakers is the speakers readout the lane deck and /cleanup print
+ ("line": waiting: X GB in N videos · freed this run: Y GB · about D
+ days left) and its numbers: waiting (audio held for the Speakers lane
+ that it will clear), neverClears, freed this run, the measured seconds
+ of engine per audio-hour, audio-hours and days left, voiceprinted and
+ 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 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/OPERATING.md b/OPERATING.md
@@ -604,6 +604,57 @@ pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150
the pause alone switched off (never one drained, degraded or disabled by hand); the pause stays on. The video
page's Transcribe row says **Transcribe now (workers paused)**.
+## Work through speakers and free the audio
+
+```sh
+pnpm ops get speakers # waiting · freed this run · days left, per channel
+pnpm ops lane --json '{"lane":"backfill","operations":["diarization"],"order":"space"}'
+pnpm ops settings --json '{"patch":{"attribution":{"textOnlyEnabled":false}}}'
+pnpm ops settings --json '{"patch":{"diarization":{"cleanAfterCapture":true}}}'
+pnpm ops lane --json '{"lane":"backfill","speakers":"work"}' # the deck's Work through speakers
+pnpm ops lane --json '{"lane":"backfill","speakers":"pause"}' # Pause: hold; stays armed
+pnpm ops diarize --json '{"slug":"example"}' --wait # one channel now, lane paused or not
+```
+
+- **What a video needs before its audio may go**: a transcript, its speakers (`diarization.json`) and their
+ voice fingerprints (`voiceprints`: one TitaNet centroid per speaker). The fingerprint is the one part that cannot
+ be made again without the audio, so with `diarization.requireVoiceprints` (on by default) Clean audio skips a
+ diarized video without them — "awaiting voice fingerprint" — and the Speakers lane adds them from the existing
+ turns (seconds of work, no re-clustering).
+- **The lane does speakers only** with `operations: ["diarization"]` on the backfill lane (and the text-only naming
+ pass off): diarization for what has none, fingerprints for what has turns but none. `order: "space"` takes
+ channels whose media is on the corpus disk first, then the videos freeing the most bytes per audio-hour. The
+ channel tiers on /channels still come first.
+- **Work through speakers** (the Speakers lane card, `speakers: "work"`) arms the lane, lifts its hold and starts a
+ run; **Pause** holds it (the video in flight finishes). It refuses a lane not narrowed to `["diarization"]` (it
+ names the command above) and a lane a render holds. With `cleanAfterCapture` on, each captured video's audio is
+ removed at once through every Clean audio gate (keep-latest, do-not-clean), and the bytes are counted in "freed
+ this run" (`transcripts/.speakers-run.json`). Off, Clean audio on each channel (or `cleanup
+ {"sweep":"transcribed"}`) frees them later.
+- **Clean after capture never asks a platform anything.** It reads the channel's availability verdict
+ (`availability-verdict.json`, written by the Quick check): a video a listing younger than
+ `diarization.cleanVerdictMaxAgeHours` (24) names is cleaned; one it does not name is held ("maybe missing" — Check
+ maybe missing resolves it); with no fresh listing the video is held "awaiting an availability check" and ONE
+ Quick check of the channel is queued on its platform's queue (once per max age, never while the platform is
+ held). A video whose cached availability says it is gone is pinned, as the sweep does.
+- **Held by clean after capture, cleaned by hand**: a channel with no `url` ("no source to check: clean by hand";
+ `cleanAfterCaptureUnverified: true` in its config lets it through) and a whole-recording channel
+ (`clips.wholeRecordingPlatforms`, Rumble — its audio is the recording clock's source; `diarization.
+ cleanWholeRecordingAudio` lets it through).
+- **Videos already fingerprinted are not cleaned by the lane**: a unit that finds the work done reports `fresh` and
+ the hook does not fire. They — and the audio already clearable before voiceprints existed — go by hand, per
+ channel: `pnpm ops diarize --json '{"slug":"<slug>"}' --wait` (fingerprints from the existing turns) → spot-check
+ a few `diarization.json` (`voiceprints` with 192-float centroids for the speakers with long turns,
+ `voiceprintsFrom` naming the audio) → Clean audio on the channel (`cleanup {"sweep":"transcribed"}`).
+- **A fingerprint is real or it is not recorded**: every speaker with a turn of 0.5 s or more needs a 192-float
+ centroid from the record's embedding model; the voiceprint step cuts only the video's own audio (never a
+ container or a saved video, whose clock can differ), and refuses a file whose duration is not the record's.
+- **The readout** (`get speakers`, the lane card, /cleanup): waiting = the audio the lane will clear; days left =
+ the audio-hours left times the seconds per audio-hour the sidecars measured, at one video at a time. Diarized
+ videos whose audio is already gone are `noFingerprintPossible` — listed, never an error. Audio the engine cannot
+ decode is recorded in `audio-integrity.json` and skipped until a different file is there.
+- **A render gets the cores**: render mode holds the Speakers lane with transcription and download.
+
## Record a live stream; import a file
```sh
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -407,6 +407,7 @@ Configuration for the automatic priority-queue runners (auto-transcribe / auto-d
| `order` | transcription `"listed"`<br>download `"listed"`<br>digest `"cheapest"`<br>backfill `"listed"` | Ordering within each rule (see AutoQueueOrder). Optional exactly like replaceAutoSubs: settings files written before this field existed lack it, and the sanitizer defaults them to "listed" (today's behaviour). |
| `snoozeUntil` | `null` | Epoch ms until which this runner idles WITHOUT stopping: next() returns null so the loop stays up, re-reads settings each iteration, and resumes by itself when the moment passes. null/absent/past = not snoozed. Survives a restart because it lives in settings.json, not in runner memory. |
| `held` | transcription `false`<br>download `false`<br>digest `false`<br>backfill `true` | THE LANE'S PAUSE GATE. Shut means the lane holds: every dispatch path asks lib/pauseGates.ts, whose limit()/guard returns 0 so runPool idle-waits. A hold, never a stop — see that file's header.<br><br>OPTIONAL IN THE TYPE, FILLED BY THE SANITIZER. Until slice 1.4 four separate settings fields carried this — `transcriptionsPaused`, `downloadsPaused`, `digest.digestsPaused` and (inverted) `backfill.enabled` — so `undefined` meant "ask the legacy field" and `sanitizePolicy` deliberately refused to default it: a default would have read a paused corpus as running. S0-pause deleted those four, on the precondition that the live settings.json already carried every `held` key, and the default came in with them (`defaultHeldFor` — free everywhere except backfill, whose field was inverted and shipped held).<br><br>It stays optional because a reader may be handed a PARTIAL settings object (laneGuards.test.ts casts one), and `isGateHeld` answers `false` for a lane that carries no key at all rather than throwing. |
+| `operations` | absent | Narrow an OPERATION lane to these operation ids (e.g. ["diarization"] on the backfill lane: speakers only, no naming pass). Absent or empty = every enabled operation on the lane's queue, as before.<br><br>On the POLICY rather than a leaf's `match.operation` because a channel-priority document compiles the lane's tree from its tiers and the stored leaves are not used while one exists; a lane-wide narrowing survives that and narrows the per-channel run, the counts and the runner alike (lib/operations.ts operationsForLane). |
| `root` | object — see below | The lane's rule tree: a group whose children are groups and leaves (see the node table). A missing root is the lane's default — empty for the runner lanes, one catch-all leaf for digest and backfill. While a channel-priority document exists, the four roots are compiled from it and not hand-edited. |
#### `autoQueue.<lane>.root (tree nodes)`
@@ -774,6 +775,10 @@ Speaker diarization captured right after transcription, while the audio is still
| `sortformerModel` | `""` | Model for the sortformer engine, produced by scripts/build-sortformer.sh. Empty = that engine cannot run, reported as the same `not-configured` skip as an unset `sortformerBin`. |
| `concurrency` | `1` | How many diarize runs may execute at once in the backfill pass. Kept low by default: diarization is CPU-bound and competes with GPU feeding and the digest sweep for the same 8 threads. |
| `maxAudioHours` | `0` | Videos longer than this are DEFERRED rather than diarized: reported as a third number that is never summed into reachable work, so a capped corpus can never read as finished.<br><br>THIS IS A STOPGAP AND IT IS NOT THE FIX. sherpa-onnx's clustering holds a pairwise distance matrix over speech-segment embeddings — O(n^2) in SEGMENT count — and speaker-turn density varies 40x across this corpus (33-1364 turns/hour), so duration does not actually predict the blowup: a sparse 7h42m video completed while a dense 6h12m one was OOM-killed. Duration is merely the only predictor available for free, from metadata already on disk, BEFORE spending 45 minutes to find out. n^2 at 30k segments is 6.7 GiB and at 40k is 11.9 GiB, which brackets the 10.6 GB and 9.6 GB peaks measured on this 16 GB box.<br><br>0 disables the cap. That is where this goes once windowed diarization lands: windowing divides per-window n by the window count, so the matrix falls by its square, and the cap stops being needed rather than being tuned. |
+| `cleanAfterCapture` | `false` | Delete a video's audio as soon as the Speakers lane has captured it.<br><br>When ON, a diarization unit that finishes with a complete set of voice fingerprints (diarization.json `voiceprints`) is followed at once by the per-video half of Clean audio, with every one of its gates: a transcript.json, outside the keep-latest window, not marked do-not-clean, and the availability check (a video gone upstream is pinned, not deleted). The bytes freed are logged and counted in the speakers readout. OFF by default: nothing deletes audio until the operator says so. |
+| `requireVoiceprints` | `true` | Hold a video's audio until its diarization.json carries voice fingerprints.<br><br>A fingerprint is the one part of a diarization that cannot be made again once the audio is gone, so with this ON (the default) Clean audio skips a diarized video whose sidecar has none, saying "awaiting voice fingerprint", and the Speakers lane adds them from the existing turns. Applies only while diarization is enabled, like the diarization guard itself. |
+| `cleanVerdictMaxAgeHours` | `24` | How old the channel's last listing may be for clean-after-capture to trust it.<br><br>Clean after capture asks NOTHING of the network: it reads the channel's availability verdict (availability-verdict.json, written by the quick availability check) — a video named in a listing younger than this is cleaned, one not named is held (maybe missing). With no fresh listing the video is held and ONE quick check of the channel is queued on its platform's queue, at most once per this many hours, never while the platform is held. The manual Clean audio sweep keeps its own live check. |
+| `cleanWholeRecordingAudio` | `false` | Let clean-after-capture delete the audio of channels on `clips.wholeRecordingPlatforms` (Rumble by default).<br><br>OFF by default, and the reason is the recording clock: on those platforms the cues are the transcription of audio.<ext>, and every clip is cut from another file of the recording through a time map fitted against that audio (common/lib/recordingClock.mjs). Deleting it as each video is captured leaves those recordings with no map to make later. The manual Clean audio sweep is unaffected. |
Default:
@@ -791,7 +796,11 @@ Default:
"sortformerBin": "",
"sortformerModel": "",
"concurrency": 1,
- "maxAudioHours": 0
+ "maxAudioHours": 0,
+ "cleanAfterCapture": false,
+ "requireVoiceprints": true,
+ "cleanVerdictMaxAgeHours": 24,
+ "cleanWholeRecordingAudio": false
}
```
diff --git a/WORKTREES.md b/WORKTREES.md
@@ -437,7 +437,7 @@ While it is on:
released when it exits — done, failed, or umtool signalled (the signal is passed on); the
exit code is the command's. A bare `on` in a script is the chain trap: the window outlives
the script, and a command that never got the token waits at the door behind it.
-- **the editor's transcription and download lanes are held** — only the ones not already
+- **the editor's transcription, download and Speakers lanes are held** — only the ones not already
held, and only those are released at the end (a hold someone else made stays). With no
editor to ask, render mode still holds the door and says the lanes were not held.
- the umtool take panel and the editor's `/jobs` show a banner; **close Firefox and other
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";
@@ -727,6 +729,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 +763,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 +809,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 +844,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 +912,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 +984,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 +993,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 +1014,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 +1026,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 +1245,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/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/components/StreamActionLog.tsx b/common/components/StreamActionLog.tsx
@@ -26,6 +26,8 @@ type Props = {
* that need a typed-confirmation gate before allowing the action.
*/
disabled?: boolean;
+ /** What the button does, in one sentence, as its tooltip. */
+ title?: string;
/**
* Called when a run SETTLES — the job's stream has been read to the end (or
* the trigger refused before one existed). `started` is false for a refusal.
@@ -57,6 +59,7 @@ export function StreamActionLog({
cancelAction,
extraControls,
disabled = false,
+ title,
onSettled,
}: Props) {
const accessibleName = label ?? buttonLabel;
@@ -205,6 +208,7 @@ export function StreamActionLog({
size="sm"
onClick={handleClick}
disabled={!hydrated || running || disabled}
+ title={title}
>
{running ? runningLabel : buttonLabel}
</Button>
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.ts b/common/controller/autoRunner.ts
@@ -1,4 +1,7 @@
import path from "node:path";
+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 { mapConcurrent } from "../lib/concurrency";
@@ -862,6 +865,11 @@ async function recencyOrdering(
if (order === "cheapest" && kind !== "digest") {
return { compare: null, keys: new Map() };
}
+ // `space` is the Speakers lane's: its candidates all hold audio and have a
+ // transcript, so each can be weighed. Elsewhere it is listed, as above.
+ if (order === "space" && kind !== "backfill") {
+ return { compare: null, keys: new Map() };
+ }
// Candidates AND their owning channel, derived in one pass from the same
// projection buildPendingByLeaf claims from — first-writer-wins, exactly as
// buildChannelWork builds its own owner map, so the two cannot disagree.
@@ -890,6 +898,21 @@ async function recencyOrdering(
// would be pure cost.
interpolate: kind === "download",
});
+ if (order === "space") {
+ // Corpus disk = the channel names no `mediaDir` (and no retired
+ // whole-dir `dataDir`); the rest live on another drive.
+ const external = new Set(
+ meta.filter((m) => !!m.config?.mediaDir || !!m.config?.dataDir).map((m) => m.slug),
+ );
+ const rates = await loadAudioRates(paths, owner, candidateIds);
+ return {
+ compare: spaceComparator({
+ external: (id) => external.has(owner.get(id) ?? ""),
+ bytesPerHour: (id) => rates.get(id) ?? null,
+ }),
+ keys,
+ };
+ }
if (order !== "cheapest") {
return { compare: makeRecencyComparator(keys, order), keys };
}
@@ -944,6 +967,34 @@ async function loadDurations(
const DURATION_READ_CONCURRENCY = 64;
+// Bytes of held audio per audio-hour, per candidate, for the `space` order. The
+// audio is what clean audio would remove (audioFilesToRemove), sized through
+// tier links; the duration is the memoized one `cheapest` uses. Read per tick
+// like the durations, at the same concurrency: a readdir and a stat or two per
+// candidate, and the Speakers lane's candidates are the videos still holding
+// audio (thousands, not the corpus).
+async function loadAudioRates(
+ paths: Paths,
+ owner: ReadonlyMap<string, string>,
+ candidateIds: ReadonlySet<string>,
+): Promise<Map<string, number | null>> {
+ const ids = [...candidateIds];
+ const rates = await mapConcurrent(ids, DURATION_READ_CONCURRENCY, async (id) => {
+ const slug = owner.get(id);
+ if (!slug) return null;
+ const dir = path.join(paths.channelsDir, slug, "data", id);
+ const entries = await readdir(dir).catch(() => [] as string[]);
+ let bytes = 0;
+ for (const name of audioFilesToRemove(entries)) {
+ bytes += await stat(path.join(dir, name)).then((st) => st.size, () => 0);
+ }
+ return audioBytesPerHour(bytes, await videoDurationSeconds(paths, slug, id));
+ });
+ const out = new Map<string, number | null>();
+ ids.forEach((id, i) => out.set(id, rates[i]));
+ return out;
+}
+
// How many drill-down ids the status payload carries per rule. Enough to see
// whether an ordering change did what you asked; small enough that a 9,000-video
// catch-all doesn't ship 9,000 strings on a 3-second poll.
diff --git a/common/controller/availabilityVerdict.ts b/common/controller/availabilityVerdict.ts
@@ -0,0 +1,210 @@
+// A CHANNEL'S AVAILABILITY VERDICT, cached: which videos its source listed the
+// last time the quick availability check asked, and when. Written by that check
+// (controller/quickAvailabilityCheck.ts, one flat-playlist listing on the
+// channel's platform queue); READ by clean-after-capture, which must never ask
+// the network itself (lane/speakers-run review, B1: one full listing per
+// cleaned video, outside every queue, gap and hold).
+//
+// The per-video question (verdictFor) has four answers:
+// listed — the channel's fresh listing names the video: safe to clean;
+// absent — a fresh listing does NOT name it: maybe deleted, maybe unlisted
+// (unlisted videos legitimately drop out of a listing). Held; the
+// manual "check maybe missing" resolves which;
+// stale — the newest listing is older than diarization.cleanVerdictMaxAgeHours;
+// none — the channel has never been listed by the check.
+// Stale and none hold the video "awaiting an availability check", and
+// requestAvailabilityCheck asks for at most one check of that channel per
+// max age, on its platform's own queue.
+
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server";
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import { heldPlatformRefusal } from "../jobs/downloadBackoff";
+import { raisedServiceAlert } from "../lib/serviceCookies-server";
+import { detectPlatform, platformQueueKey, queueKeyForUrl } from "../lib/platform";
+import { resolveQueueKey } from "../lib/queueKeys";
+import { readChannelConfig } from "./channels";
+import { runQuickAvailabilityCheck } from "./quickAvailabilityCheck";
+
+export const AVAILABILITY_VERDICT_FILENAME = "availability-verdict.json";
+
+export type AvailabilityVerdictRecord = {
+ version: 1;
+ // ISO 8601 of the listing, or null before the first one.
+ checkedAt: string | null;
+ // Canonical ids (data-dir names) the listing named, sorted.
+ ids: string[];
+ // ISO 8601 of the last check REQUESTED by clean-after-capture, so a lane that
+ // holds a hundred videos of one channel asks once, and a restart does not
+ // ask again inside the max age.
+ requestedAt?: string;
+};
+
+export function availabilityVerdictPath(paths: Pick<Paths, "channelsDir">, slug: string): string {
+ return path.join(paths.channelsDir, slug, AVAILABILITY_VERDICT_FILENAME);
+}
+
+function coerce(value: unknown): AvailabilityVerdictRecord | null {
+ const v = value as Partial<AvailabilityVerdictRecord> | null;
+ if (!v || typeof v !== "object" || !Array.isArray(v.ids)) return null;
+ return {
+ version: 1,
+ checkedAt: typeof v.checkedAt === "string" ? v.checkedAt : null,
+ ids: v.ids.filter((x): x is string => typeof x === "string"),
+ ...(typeof v.requestedAt === "string" ? { requestedAt: v.requestedAt } : {}),
+ };
+}
+
+export async function readAvailabilityVerdict(
+ paths: Pick<Paths, "channelsDir">,
+ slug: string,
+): Promise<AvailabilityVerdictRecord | null> {
+ const read = await readJsonFile(availabilityVerdictPath(paths, slug));
+ return read.ok ? coerce(read.value) : null;
+}
+
+async function update(
+ paths: Pick<Paths, "channelsDir">,
+ slug: string,
+ fn: (r: AvailabilityVerdictRecord) => AvailabilityVerdictRecord,
+): Promise<void> {
+ const file = availabilityVerdictPath(paths, slug);
+ await withJsonFileLock(file, async () => {
+ const cur = (await readAvailabilityVerdict(paths, slug)) ?? { version: 1, checkedAt: null, ids: [] };
+ await writeJsonAtomic(file, fn(cur));
+ });
+}
+
+// The quick check's half: what the listing named, and when.
+export function writeAvailabilityVerdict(
+ paths: Pick<Paths, "channelsDir">,
+ slug: string,
+ listing: { checkedAt: string; ids: Iterable<string> },
+): Promise<void> {
+ return update(paths, slug, (r) => ({
+ ...r,
+ checkedAt: listing.checkedAt,
+ ids: [...new Set(listing.ids)].sort(),
+ }));
+}
+
+export function markAvailabilityCheckRequested(
+ paths: Pick<Paths, "channelsDir">,
+ slug: string,
+ at: string,
+): Promise<void> {
+ return update(paths, slug, (r) => ({ ...r, requestedAt: at }));
+}
+
+export type VideoVerdict = "listed" | "absent" | "stale" | "none";
+
+const HOUR = 3_600_000;
+
+// PURE.
+export function verdictFor(
+ record: AvailabilityVerdictRecord | null,
+ videoId: string,
+ maxAgeHours: number,
+ now: number = Date.now(),
+): VideoVerdict {
+ if (!record?.checkedAt) return "none";
+ const at = Date.parse(record.checkedAt);
+ if (!Number.isFinite(at) || now - at > maxAgeHours * HOUR) return "stale";
+ return record.ids.includes(videoId) ? "listed" : "absent";
+}
+
+// PURE: may clean-after-capture ask for another check of this channel now?
+// Not when one was asked for within the max age (it is queued, running, or
+// failed — and a failure is not a reason to ask again sooner).
+export function mayRequestCheck(
+ record: AvailabilityVerdictRecord | null,
+ maxAgeHours: number,
+ now: number = Date.now(),
+): boolean {
+ const at = record?.requestedAt ? Date.parse(record.requestedAt) : NaN;
+ return !Number.isFinite(at) || now - at > maxAgeHours * HOUR;
+}
+
+// ---------------------------------------------------------------------------
+// Asking for a check — never doing one.
+
+
+// The quick availability check as a job on the channel's PLATFORM queue — the
+// one the channel page's Quick check button runs (kind
+// quick-availability-check, network: so runManagedFunction's network guard
+// applies: never unqueued, and an X job only on a fresh jar with no alert up).
+export async function startQuickAvailabilityCheckJob(opts: {
+ paths: Paths;
+ slug: string;
+ queueKey?: string;
+ onDone?: () => void;
+}): Promise<StreamActionResult> {
+ const config = await readChannelConfig(opts.paths, opts.slug);
+ const defaultQueue = config?.platform
+ ? platformQueueKey(config.platform)
+ : queueKeyForUrl(config?.url);
+ return runManagedFunction({
+ kind: "quick-availability-check",
+ queueKey: resolveQueueKey(defaultQueue, opts.queueKey),
+ paths: opts.paths,
+ channelSlug: opts.slug,
+ fn: async (onLog, signal) => {
+ await runQuickAvailabilityCheck({ channelSlug: opts.slug, paths: opts.paths, onLog, signal });
+ opts.onDone?.();
+ },
+ });
+}
+
+export type CheckRequestDeps = {
+ start?: (paths: Paths, slug: string) => Promise<StreamActionResult>;
+ platformRefusal?: (platform: string) => Promise<string | null>;
+ // The platform's open cookie/service alert (the store `get services`
+ // reads), as its evidence line, or null.
+ serviceAlert?: (platform: string) => Promise<string | null>;
+ now?: () => number;
+};
+
+export type CheckRequest =
+ | { status: "requested"; jobId?: string }
+ | { status: "already-requested"; at: string }
+ | { status: "platform-held"; why: string }
+ | { status: "service-alert"; why: string }
+ | { status: "refused"; why: string }
+ | { status: "no-url" };
+
+// At most one check per channel per max age, and none while its platform is
+// held: a hold is the platform asking us to stop, and a check is a request.
+export async function requestAvailabilityCheck(
+ paths: Paths,
+ slug: string,
+ maxAgeHours: number,
+ deps: CheckRequestDeps = {},
+): Promise<CheckRequest> {
+ const now = deps.now?.() ?? Date.now();
+ const config = await readChannelConfig(paths, slug);
+ if (!config?.url) return { status: "no-url" };
+ const platform = config.platform ?? detectPlatform(config.url) ?? "unknown";
+ const held = await (deps.platformRefusal ?? ((p: string) => heldPlatformRefusal(p, "An availability check", paths)))(platform);
+ if (held) return { status: "platform-held", why: held };
+ // An open cookie alert is the platform answering with a challenge or a
+ // login wall: a listing now would only add to it. Asked nothing until the
+ // operator's Recheck or Dismiss clears it.
+ const alert = await (
+ deps.serviceAlert ??
+ (async (p: string) => {
+ const e = await raisedServiceAlert(paths, p);
+ return e ? (e.evidence?.line ?? "alert raised") : null;
+ })
+ )(platform);
+ if (alert) return { status: "service-alert", why: alert };
+ const record = await readAvailabilityVerdict(paths, slug);
+ if (!mayRequestCheck(record, maxAgeHours, now)) {
+ return { status: "already-requested", at: record!.requestedAt! };
+ }
+ // Marked BEFORE the start, so two units finishing at once cannot both ask.
+ await markAvailabilityCheckRequested(paths, slug, new Date(now).toISOString());
+ const started = await (deps.start ?? ((p: Paths, s: string) => startQuickAvailabilityCheckJob({ paths: p, slug: s })))(paths, slug);
+ if (!started.ok) return { status: "refused", why: started.error ?? "the check could not be queued" };
+ return { status: "requested", jobId: started.jobId };
+}
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,
@@ -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
@@ -1102,18 +1105,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 +1583,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 +1602,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 +1651,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 +1669,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 +1864,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 +2245,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 +2395,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 +2428,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 +2495,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 +2526,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.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 {
@@ -549,7 +551,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 +639,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 +714,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 +727,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 +758,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 +771,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 +826,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";
@@ -27,6 +28,8 @@ import { isTierable } from "../lib/mediaTier";
import { isDriveNotAnswering, onDrive } from "../lib/storageHealth";
import { CLIPS_DIR_NAME } from "../lib/clipWindow";
import { getSettings } from "../lib/settings";
+import { hasVoiceprints, voiceprintsPossible } from "../lib/diarization";
+import { loadDiarization } from "../lib/diarization-server";
import {
loadAvailability,
resolveEffectiveAvailability,
@@ -482,6 +485,9 @@ export type ChannelSnapshot = {
// fifth gate: the real gate needs a live probe, and folding a guess into the
// hero figure would move the sidebar badge and /cleanup's Est. reclaim too.
reclaimableAtRiskBytes?: number;
+ // The Speakers lane over this channel (the speakers readout's per-channel
+ // row). Optional: snapshots written before it lack it.
+ speakers?: SpeakersWork;
// The audio audit's verdicts over the channel (release 32). Optional: older
// snapshots lack it; readers show nothing until the next regen.
audioIntegrity?: AudioIntegrityTally;
@@ -501,6 +507,35 @@ export type HeldAudio = {
diarizationNeverClears: number;
};
+export type SpeakersWork = {
+ // Audio seconds of the awaiting-diarization videos the lane will clear (the
+ // hold minus diarizationNeverClears), by recorded duration; and how many of
+ // them have no duration on disk.
+ workSeconds: number;
+ workUnmeasured: number;
+ // The engine's measured cost on this channel's sidecars: summed durationMs
+ // over summed audioSeconds, from `measured` sidecars.
+ engineMs: number;
+ engineAudioSeconds: number;
+ measured: number;
+ // Sidecars with complete voice fingerprints; and diarized videos without
+ // them whose audio is already gone — no fingerprint is possible for those.
+ voiceprinted: number;
+ noFingerprintPossible: number;
+};
+
+export function emptySpeakersWork(): SpeakersWork {
+ return {
+ workSeconds: 0,
+ workUnmeasured: 0,
+ engineMs: 0,
+ engineAudioSeconds: 0,
+ measured: 0,
+ voiceprinted: 0,
+ noFingerprintPossible: 0,
+ };
+}
+
export function emptyHeldAudio(): HeldAudio {
return {
noTranscript: 0,
@@ -1224,6 +1259,11 @@ export async function generateChannelSnapshot(
// once per snapshot rather than per video — this and the sweep's own guard key
// off the same setting, and they have to agree or the reclaim estimate lies.
const diarizationEnabled = getSettings().diarization.enabled;
+ // …and, with diarization.requireVoiceprints, until the sidecar carries voice
+ // fingerprints (cleanAudioFromTranscribed's audioCleanGate). Read only for a
+ // video that has BOTH a sidecar and audio — the one population it can hold.
+ const voiceprintGuardOn =
+ diarizationEnabled && getSettings().diarization.requireVoiceprints;
// Videos the user has opted out of the truncated/incomplete-transcript check
// (e.g. legitimately have no speech for the back half). Suppressed from the
@@ -1312,6 +1352,7 @@ export async function generateChannelSnapshot(
let totalClipsBytes = 0;
const heldAudioBytes = emptyHeldAudio();
const heldAudioCounts = emptyHeldAudio();
+ const speakers = emptySpeakersWork();
let reclaimableAtRiskBytes = 0;
// Is the lane that would release an awaiting-diarization video even running?
// allOperations drops a kind whose enabled() is false, so an ABSENT entry
@@ -1361,6 +1402,30 @@ export async function generateChannelSnapshot(
0,
);
totalAudioBytes += audioBytes;
+ // Diarized AS FAR AS THE SWEEP IS CONCERNED: a sidecar without voice
+ // fingerprints is held at the same gate as an absent one — what it waits
+ // for is the Speakers lane either way. Only a video that holds audio pays
+ // the read.
+ const diarRecord = files.hasDiarization
+ ? await loadDiarization(path.join(dataDir, id))
+ : null;
+ const diarVoiceprinted = hasVoiceprints(diarRecord);
+ if (diarRecord) {
+ if (diarVoiceprinted) speakers.voiceprinted++;
+ else if (files.audioFiles.length === 0 || !voiceprintsPossible(diarRecord)) {
+ speakers.noFingerprintPossible++;
+ }
+ // The engine's own clock, for the readout's rate: wall time over the
+ // audio it was given.
+ if ((diarRecord.durationMs ?? 0) > 0 && (diarRecord.audioSeconds ?? 0) > 0) {
+ speakers.engineMs += diarRecord.durationMs!;
+ speakers.engineAudioSeconds += diarRecord.audioSeconds!;
+ speakers.measured++;
+ }
+ }
+ const diarizedForCleanup =
+ files.hasDiarization &&
+ (!voiceprintGuardOn || files.audioFiles.length === 0 || diarVoiceprinted);
if (files.audioFiles.length > 0) {
const gate = attributeAudioHold({
// The sweep's own gate — entries.includes("transcript.json"). NOT
@@ -1376,7 +1441,7 @@ export async function generateChannelSnapshot(
inKeepLatestWindow: keptIds.has(id),
doNotClean: doNotCleanIds.has(id),
diarizationGuardOn: diarizationEnabled,
- hasDiarization: files.hasDiarization,
+ hasDiarization: diarizedForCleanup,
});
if (gate === "reclaimable") {
// What verifyBeforeClean is likely to refuse at sweep time, from the
@@ -1400,6 +1465,12 @@ export async function generateChannelSnapshot(
) {
heldAudioBytes.diarizationNeverClears += audioBytes;
heldAudioCounts.diarizationNeverClears += 1;
+ } else if (gate === "awaitingDiarization") {
+ // Work the Speakers lane WILL do, in audio seconds (the readout's
+ // "days left"). The recorded duration; a video without one counted.
+ const sec = coverage?.cov.duration ?? 0;
+ if (sec > 0) speakers.workSeconds += sec;
+ else speakers.workUnmeasured++;
}
}
}
@@ -1549,7 +1620,7 @@ export async function generateChannelSnapshot(
// Held back by the diarization guard in cleanAudioFromTranscribed. Kept
// out of the bucket AND its byte total so "Est. reclaim" never promises
// space the sweep is going to refuse to take.
- !(diarizationEnabled && !files.hasDiarization)
+ !(diarizationEnabled && !diarizedForCleanup)
) {
transcribedWithAudio.push(id);
for (const name of files.audioFiles) {
@@ -1583,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.
@@ -1921,6 +1994,7 @@ export async function generateChannelSnapshot(
totalClipsBytes,
heldAudioBytes,
heldAudioCounts,
+ speakers,
reclaimableAtRiskBytes,
audioIntegrity,
};
diff --git a/common/controller/cleanAfterCapture.test.ts b/common/controller/cleanAfterCapture.test.ts
@@ -0,0 +1,439 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { access, lstat, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { Operation } from "../lib/operations";
+import { cleanAudioForVideo, cleanAudioFromTranscribed } from "./cleanAudioFromTranscribed";
+import { runOperationUnit, type OperationRun } from "./operationBatch";
+import { readSpeakersLedger } from "../lib/speakersLedger-server";
+import { readAvailabilityVerdict, requestAvailabilityCheck, writeAvailabilityVerdict, type CheckRequestDeps } from "./availabilityVerdict";
+
+// Any test that reaches the request path without saying otherwise fails loudly.
+const NO_NETWORK: CheckRequestDeps = {
+ start: async () => {
+ throw new Error("a test asked for a real availability check");
+ },
+ platformRefusal: async () => null,
+ serviceAlert: async () => null,
+};
+import { defaultSiteSettings, getSettings } from "../lib/settings";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test common/controller/cleanAfterCapture.test.ts
+//
+// Temp corpus, temp settings.json. Nothing here probes the network: availability
+// is checked from availability.json (tier A) or switched off per test.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "clean-after-capture-"));
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+process.env.E2E_AVAILABILITY_PROBE_GAP_MS = "0";
+
+async function settings(diarization: Record<string, unknown>, over: Record<string, unknown> = {}) {
+ await writeFile(
+ process.env.SETTINGS_FILE!,
+ JSON.stringify({
+ verifyAvailabilityBeforeClean: false,
+ diarization: { enabled: true, segModel: "/m/seg.onnx", embModel: "/m/emb.onnx", ...diarization },
+ ...over,
+ }),
+ );
+}
+
+const VOICEPRINTS = [{ speaker: 0, seconds: 4, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "emb.onnx" }];
+
+function sidecar(voiceprints: boolean): string {
+ return JSON.stringify({
+ videoId: "v",
+ generatedAt: "2026-08-07T00:00:00.000Z",
+ speakers: 1,
+ turns: [{ start: 0, end: 4, speaker: 0 }],
+ engine: { engine: "sherpa-onnx", segmentationModel: "seg.onnx", embeddingModel: "emb.onnx", threshold: 0.9 },
+ ...(voiceprints ? { voiceprints: VOICEPRINTS } : {}),
+ });
+}
+
+let n = 0;
+async function corpus() {
+ const dir = path.join(ROOT, `c${n++}`);
+ const paths = {
+ channelsDir: path.join(dir, "channels"),
+ transcriptsDir: dir,
+ ytdlpBin: path.join(dir, "no-such-ytdlp"),
+ } as unknown as Paths;
+ await mkdir(path.join(paths.channelsDir, "ch", "data"), { recursive: true });
+ await writeFile(path.join(paths.channelsDir, "ch", "config.json"), JSON.stringify({ handling: "transcribe", name: "ch", url: "https://www.youtube.com/@ch" }));
+ const video = async (
+ id: string,
+ o: {
+ transcript?: boolean;
+ diarization?: "none" | "plain" | "voiceprints";
+ doNotClean?: boolean;
+ gone?: boolean;
+ bytes?: number;
+ // Named in a fresh availability listing of the channel (the verdict the
+ // automatic clean always reads). Default true; false = never listed.
+ listed?: boolean;
+ } = {},
+ ) => {
+ const v = path.join(paths.channelsDir, "ch", "data", id);
+ await mkdir(v, { recursive: true });
+ if (o.transcript !== false) await writeFile(path.join(v, "transcript.json"), "{}");
+ await writeFile(path.join(v, "audio.mp3"), Buffer.alloc(o.bytes ?? 1000));
+ if (o.diarization === "plain") await writeFile(path.join(v, "diarization.json"), sidecar(false));
+ if (o.diarization === "voiceprints") await writeFile(path.join(v, "diarization.json"), sidecar(true));
+ if (o.doNotClean) await writeFile(path.join(v, "do-not-clean.json"), JSON.stringify({ setAt: "now" }));
+ if (o.listed !== false) {
+ const cur = await readAvailabilityVerdict(paths, "ch");
+ await writeAvailabilityVerdict(paths, "ch", { checkedAt: new Date().toISOString(), ids: [...(cur?.ids ?? []), id] });
+ }
+ if (o.gone) {
+ await writeFile(path.join(v, "availability.json"), JSON.stringify({ checkedAt: new Date().toISOString(), availability: "deleted" }));
+ }
+ return v;
+ };
+ return { paths, video };
+}
+
+const exists = (f: string) => access(f).then(() => true, () => false);
+
+test("Clean audio holds a diarized video whose sidecar has no voice fingerprints, and says so", async () => {
+ await settings({});
+ const { paths, video } = await corpus();
+ const plain = await video("plain", { diarization: "plain" });
+ const done = await video("done", { diarization: "voiceprints", bytes: 4096 });
+ const logs: string[] = [];
+ const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: (m) => logs.push(m) });
+ assert.equal(await exists(path.join(plain, "audio.mp3")), true, "awaiting its fingerprint");
+ assert.equal(await exists(path.join(done, "audio.mp3")), false);
+ assert.equal(r.awaitingVoiceprint, 1);
+ assert.equal(r.bytesFreed, 4096);
+ assert.ok(logs.includes("Skipped plain (awaiting voice fingerprint)"));
+ assert.ok(
+ logs.some((l) => l.endsWith("Skipped 1 (0 protected, 0 gone-from-source pinned, 0 unverified, 1 awaiting voice fingerprint).")),
+ logs.join("\n"),
+ );
+});
+
+test("requireVoiceprints off: the old rule — a diarization.json is enough", async () => {
+ await settings({ requireVoiceprints: false });
+ const { paths, video } = await corpus();
+ const plain = await video("plain", { diarization: "plain" });
+ const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {} });
+ assert.equal(await exists(path.join(plain, "audio.mp3")), false);
+ assert.equal(r.awaitingVoiceprint, 0);
+});
+
+test("defaults: requireVoiceprints ON, cleanAfterCapture OFF", () => {
+ assert.equal(defaultSiteSettings().diarization.requireVoiceprints, true);
+ assert.equal(defaultSiteSettings().diarization.cleanAfterCapture, false);
+});
+
+test("cleanAudioForVideo keeps every gate of the channel sweep", async () => {
+ await settings({}, { verifyAvailabilityBeforeClean: true });
+ const { paths, video } = await corpus();
+ await video("untranscribed", { transcript: false, diarization: "voiceprints" });
+ await video("pinned", { diarization: "voiceprints", doNotClean: true });
+ await video("nodiar");
+ await video("plain", { diarization: "plain" });
+ const gone = await video("gone", { diarization: "voiceprints", gone: true });
+ const ok = await video("ok", { diarization: "voiceprints", bytes: 2048 });
+ await writeAvailabilityVerdict(paths, "ch", { checkedAt: new Date().toISOString(), ids: ["ok", "gone"] });
+ const one = (videoId: string) => cleanAudioForVideo({ channelSlug: "ch", paths, videoId, onLog: () => {}, checkDeps: NO_NETWORK });
+ assert.deepEqual(await one("untranscribed"), { outcome: "held", gate: "no-transcript", removedFiles: 0, bytesFreed: 0 });
+ assert.equal((await one("pinned")).gate, "do-not-clean");
+ assert.equal((await one("nodiar")).gate, "awaiting-diarization");
+ assert.equal((await one("plain")).gate, "awaiting-voiceprint");
+ // Gone upstream: pinned do-not-clean, audio kept.
+ assert.equal((await one("gone")).outcome, "pinned");
+ assert.equal(await exists(path.join(gone, "audio.mp3")), true);
+ assert.equal(await exists(path.join(gone, "do-not-clean.json")), true);
+ assert.deepEqual(await one("ok"), { outcome: "cleaned", removedFiles: 1, bytesFreed: 2048 });
+ assert.equal(await exists(path.join(ok, "audio.mp3")), false);
+});
+
+// ---- the hook: a diarization unit that returns done --------------------------
+
+function fakeDiarization(write: "voiceprints" | "plain"): Operation {
+ return {
+ id: "diarization",
+ lane: { queueKey: "backfill", contendsFor: "cpu" },
+ resolveTarget: () => ({}),
+ state: async () => "missing",
+ run: async ({ videoDir }: { videoDir: string }) => {
+ await writeFile(path.join(videoDir, "diarization.json"), sidecar(write === "voiceprints"));
+ return "done";
+ },
+ inputs: () => [],
+ outputs: ["diarization.json"],
+ } as unknown as Operation;
+}
+
+function fakeRun(paths: Paths): OperationRun {
+ return {
+ lane: "backfill",
+ paths,
+ settings: getSettings(),
+ force: false,
+ allowRedownload: false,
+ live: { llmActive: 0, unitActive: 0, costUsd: 0, diskFloorHit: false },
+ backfill: { targets: new Map(), llmFanout: null },
+ log: () => {},
+ } as unknown as OperationRun;
+}
+
+test("clean after capture: on, a captured video's audio goes at once, counted and ledgered", async () => {
+ await settings({ cleanAfterCapture: true });
+ const { paths, video } = await corpus();
+ const v = await video("v1", { bytes: 5000 });
+ const logs: string[] = [];
+ const report = await runOperationUnit(fakeRun(paths), { channelSlug: "ch", videoId: "v1", op: fakeDiarization("voiceprints") }, { onLog: (m) => logs.push(m) });
+ assert.equal(report.outcome, "done");
+ assert.equal(await exists(path.join(v, "audio.mp3")), false);
+ assert.equal(report.audioCleaned, 1);
+ assert.equal(report.audioFreedBytes, 5000);
+ const ledger = await readSpeakersLedger(paths);
+ // Runtime state, at a dot path beside the corpus root's others.
+ assert.equal(await exists(path.join(paths.transcriptsDir, ".speakers-run.json")), true);
+ assert.equal(ledger.freedBytes, 5000);
+ assert.equal(ledger.freedVideos, 1);
+ assert.ok(logs.some((l) => l.startsWith("Freed 4.9 KB of audio from v1")), logs.join("\n"));
+});
+
+test("clean after capture: never before the fingerprint exists", async () => {
+ await settings({ cleanAfterCapture: true, requireVoiceprints: false });
+ const { paths, video } = await corpus();
+ const v = await video("v1");
+ const report = await runOperationUnit(fakeRun(paths), { channelSlug: "ch", videoId: "v1", op: fakeDiarization("plain") }, { onLog: () => {} });
+ assert.equal(report.outcome, "done");
+ assert.equal(await exists(path.join(v, "audio.mp3")), true);
+ assert.equal(report.audioCleaned, 0);
+});
+
+test("clean after capture: off by default, and a protected video stays protected", async () => {
+ await settings({});
+ const { paths, video } = await corpus();
+ const a = await video("v1");
+ await runOperationUnit(fakeRun(paths), { channelSlug: "ch", videoId: "v1", op: fakeDiarization("voiceprints") }, { onLog: () => {} });
+ assert.equal(await exists(path.join(a, "audio.mp3")), true, "off by default");
+
+ await settings({ cleanAfterCapture: true });
+ const b = await video("v2", { doNotClean: true });
+ const report = await runOperationUnit(fakeRun(paths), { channelSlug: "ch", videoId: "v2", op: fakeDiarization("voiceprints") }, { onLog: () => {} });
+ assert.equal(await exists(path.join(b, "audio.mp3")), true, "do-not-clean holds");
+ assert.equal(report.audioCleaned, 0);
+});
+
+test("cleanAudioForVideo: an unmounted media drive keeps the audio link where it is", async () => {
+ await settings({});
+ const { paths, video } = await corpus();
+ const v = await video("v1", { diarization: "voiceprints" });
+ // Tier the audio by hand onto a "drive" that is not mounted: a dangling
+ // media link and a relative link into it, as mediaTier writes them.
+ await rm(path.join(v, "audio.mp3"));
+ const channelDir = path.join(paths.channelsDir, "ch");
+ const target = path.join(ROOT, "platter-not-mounted", "ch", "media");
+ await writeFile(path.join(channelDir, "config.json"), JSON.stringify({ handling: "transcribe", name: "ch", url: "https://www.youtube.com/@ch", mediaDir: target }));
+ await symlink(target, path.join(channelDir, "media"));
+ await symlink("../../media/v1/audio.mp3", path.join(v, "audio.mp3"));
+ const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "v1", onLog: () => {} });
+ assert.deepEqual(out, { outcome: "held", gate: "media-unreachable", removedFiles: 0, bytesFreed: 0 });
+ assert.ok((await lstat(path.join(v, "audio.mp3"))).isSymbolicLink(), "the link is untouched");
+});
+
+test("cleanAudioForVideo removes the audio and nothing else: no source media, clip, transcript, sidecar or saved-video pointer", async () => {
+ await settings({});
+ const { paths, video } = await corpus();
+ const v = await video("v1", { diarization: "voiceprints" });
+ const keep = ["source-media.mp4", "transcript.json", "transcript.cues.json", "diarization.json", "saved-video.json"];
+ for (const f of keep.filter((f) => !["transcript.json", "diarization.json"].includes(f))) await writeFile(path.join(v, f), "keep");
+ await mkdir(path.join(v, "clips"));
+ await writeFile(path.join(v, "clips", "10.00-20.00.m4a"), "clip");
+ const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "v1", onLog: () => {} });
+ assert.equal(out.outcome, "cleaned");
+ assert.equal(await exists(path.join(v, "audio.mp3")), false);
+ for (const f of keep) assert.equal(await exists(path.join(v, f)), true, f);
+ assert.equal(await readFile(path.join(v, "clips", "10.00-20.00.m4a"), "utf8"), "clip");
+});
+
+// ---- B1: the availability verdict cache, never a listing per video ------------
+
+test("no fresh listing: N captured videos of one channel are held, and at most ONE check is asked for", async () => {
+ await settings({}, { verifyAvailabilityBeforeClean: true });
+ const { paths, video } = await corpus();
+ const ids = ["a1", "a2", "a3", "a4", "a5"];
+ for (const id of ids) await video(id, { diarization: "voiceprints", listed: false });
+ const started: string[] = [];
+ const deps: CheckRequestDeps = {
+ start: async (_p, slug) => {
+ started.push(slug);
+ return { ok: true, jobId: "job-1" } as never;
+ },
+ platformRefusal: async () => null,
+ };
+ for (const id of ids) {
+ const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: id, onLog: () => {}, checkDeps: deps });
+ assert.equal(out.gate, "awaiting-availability", id);
+ }
+ assert.deepEqual(started, ["ch"], "one check, on the channel, for five videos");
+ for (const id of ids) assert.equal(await exists(path.join(paths.channelsDir, "ch", "data", id, "audio.mp3")), true);
+ assert.equal(typeof (await readAvailabilityVerdict(paths, "ch"))?.requestedAt, "string");
+
+ // An OLD listing is no listing: still held, and the request is not repeated
+ // inside the max age.
+ await writeAvailabilityVerdict(paths, "ch", { checkedAt: new Date(Date.now() - 48 * 3_600_000).toISOString(), ids });
+ assert.equal((await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "a1", onLog: () => {}, checkDeps: deps })).gate, "awaiting-availability");
+ assert.equal(started.length, 1);
+
+ // The check lands (a fresh listing naming them): cleaned, nothing asked.
+ await writeAvailabilityVerdict(paths, "ch", { checkedAt: new Date().toISOString(), ids: ["a1", "a2"] });
+ assert.equal((await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "a1", onLog: () => {}, checkDeps: deps })).outcome, "cleaned");
+ // A fresh listing that does NOT name a video holds it: maybe missing.
+ assert.equal((await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "a3", onLog: () => {}, checkDeps: deps })).gate, "maybe-missing");
+ assert.equal(started.length, 1);
+});
+
+test("a held platform: the video is held, nothing deleted, nothing requested", async () => {
+ await settings({}, { verifyAvailabilityBeforeClean: true });
+ const { paths, video } = await corpus();
+ const v = await video("v1", { diarization: "voiceprints", listed: false });
+ let started = 0;
+ const logs: string[] = [];
+ const out = await cleanAudioForVideo({
+ channelSlug: "ch",
+ paths,
+ videoId: "v1",
+ onLog: (m) => logs.push(m),
+ checkDeps: {
+ start: async () => {
+ started++;
+ return { ok: true, jobId: "x" } as never;
+ },
+ platformRefusal: async (platform) => `${platform} is held after a 429`,
+ },
+ });
+ assert.equal(out.gate, "awaiting-availability");
+ assert.equal(started, 0);
+ assert.equal(await exists(path.join(v, "audio.mp3")), true);
+ assert.equal((await readAvailabilityVerdict(paths, "ch"))?.requestedAt, undefined, "not even marked as asked");
+ assert.ok(logs.some((l) => l.includes("youtube is held after a 429")), logs.join("\n"));
+});
+
+// ---- B2: a channel with no source URL ---------------------------------------
+
+test("no source URL: the automatic clean holds; the channel's opt-in lets it through; the manual sweep is unchanged", async () => {
+ await settings({}, { verifyAvailabilityBeforeClean: true });
+ const { paths, video } = await corpus();
+ const cfg = path.join(paths.channelsDir, "ch", "config.json");
+ await writeFile(cfg, JSON.stringify({ handling: "transcribe", name: "ch" }));
+ const a = await video("a1", { diarization: "voiceprints" });
+ const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "a1", onLog: () => {}, checkDeps: NO_NETWORK });
+ assert.deepEqual(out, { outcome: "held", gate: "no-source-url", removedFiles: 0, bytesFreed: 0 });
+ assert.equal(await exists(path.join(a, "audio.mp3")), true);
+
+ await writeFile(cfg, JSON.stringify({ handling: "transcribe", name: "ch", cleanAfterCaptureUnverified: true }));
+ assert.equal((await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "a1", onLog: () => {}, checkDeps: NO_NETWORK })).outcome, "cleaned");
+
+ // The manual sweep: as today — a channel with no URL cannot be verified and
+ // is cleaned (verifyBeforeClean fails open), opt-in or not.
+ await writeFile(cfg, JSON.stringify({ handling: "transcribe", name: "ch" }));
+ const b = await video("b1", { diarization: "voiceprints" });
+ const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {} });
+ assert.equal(r.cleanedDirs, 1);
+ assert.equal(await exists(path.join(b, "audio.mp3")), false);
+});
+
+// ---- whole-recording platforms ------------------------------------------------
+
+test("a whole-recording channel (Rumble): clean after capture holds its audio — the recording clock's source — unless cleanWholeRecordingAudio", async () => {
+ await settings({}, { verifyAvailabilityBeforeClean: false });
+ const { paths, video } = await corpus();
+ await writeFile(
+ path.join(paths.channelsDir, "ch", "config.json"),
+ JSON.stringify({ handling: "transcribe", name: "ch", url: "https://rumble.com/c/ch" }),
+ );
+ const v = await video("v1", { diarization: "voiceprints" });
+ const held = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "v1", onLog: () => {}, checkDeps: NO_NETWORK });
+ assert.deepEqual(held, { outcome: "held", gate: "whole-recording", removedFiles: 0, bytesFreed: 0 });
+ assert.equal(await exists(path.join(v, "audio.mp3")), true);
+ assert.equal(defaultSiteSettings().diarization.cleanWholeRecordingAudio, false);
+
+ await settings({ cleanWholeRecordingAudio: true }, { verifyAvailabilityBeforeClean: false });
+ assert.equal((await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "v1", onLog: () => {}, checkDeps: NO_NETWORK })).outcome, "cleaned");
+});
+
+test("the automatic clean requires the verdict even with verifyAvailabilityBeforeClean off (that setting is the manual sweep's)", async () => {
+ await settings({}, { verifyAvailabilityBeforeClean: false });
+ const { paths, video } = await corpus();
+ const v = await video("v1", { diarization: "voiceprints", listed: false });
+ let started = 0;
+ const deps: CheckRequestDeps = {
+ start: async () => {
+ started++;
+ return { ok: true, jobId: "x" } as never;
+ },
+ platformRefusal: async () => null,
+ };
+ const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "v1", onLog: () => {}, checkDeps: deps });
+ assert.equal(out.gate, "awaiting-availability");
+ assert.equal(started, 1);
+ assert.equal(await exists(path.join(v, "audio.mp3")), true);
+ // …while the manual sweep, with the setting off, cleans without asking.
+ const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {} });
+ assert.equal(r.cleanedDirs, 1);
+});
+
+test("an open service alert for the platform: held \"awaiting an availability check (service alert open)\", nothing requested", async () => {
+ await settings({});
+ const { paths, video } = await corpus();
+ const v = await video("v1", { diarization: "voiceprints", listed: false });
+ let started = 0;
+ const logs: string[] = [];
+ const out = await cleanAudioForVideo({
+ channelSlug: "ch",
+ paths,
+ videoId: "v1",
+ onLog: (m) => logs.push(m),
+ checkDeps: {
+ start: async () => {
+ started++;
+ return { ok: true, jobId: "x" } as never;
+ },
+ platformRefusal: async () => null,
+ serviceAlert: async (platform) => (platform === "youtube" ? "Sign in to confirm you're not a bot" : null),
+ },
+ });
+ assert.equal(out.gate, "awaiting-availability");
+ assert.equal(started, 0);
+ assert.equal((await readAvailabilityVerdict(paths, "ch"))?.requestedAt, undefined);
+ assert.equal(await exists(path.join(v, "audio.mp3")), true);
+ assert.ok(logs.some((l) => l.includes("awaiting an availability check (service alert open: Sign in to confirm")), logs.join("\n"));
+});
+
+test("the real alert store: a raised yt-dlp service alert for the channel's platform is read", async () => {
+ await settings({});
+ const { paths, video } = await corpus();
+ await video("v1", { diarization: "voiceprints", listed: false });
+ await writeFile(
+ path.join(paths.transcriptsDir, ".service-cookies.json"),
+ JSON.stringify({ version: 1, services: { youtube: { since: new Date().toISOString(), raisedAt: new Date().toISOString(), kind: "challenge", evidence: { line: "bot check", at: new Date().toISOString() }, signals: 3 } } }),
+ );
+ const asked = await requestAvailabilityCheck(paths, "ch", 24, {
+ start: async () => {
+ throw new Error("must not start");
+ },
+ platformRefusal: async () => null,
+ });
+ assert.equal(asked.status, "service-alert");
+});
+
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+test("concurrency stays 1: one diarization at a time, one backfill unit at a time", () => {
+ // Load-bearing (plans/FACTS.md): two sherpa runs at once doubled the 11 GB
+ // transients that OOM-killed the box; the Speakers lane runs beside GPU
+ // transcription on four of eight threads.
+ assert.equal(defaultSiteSettings().diarization.concurrency, 1);
+ assert.equal(defaultSiteSettings().backfill.concurrency, 1);
+});
diff --git a/common/controller/cleanAudioFromTranscribed.ts b/common/controller/cleanAudioFromTranscribed.ts
@@ -1,17 +1,30 @@
import { removeMediaFile } from "../lib/mediaTier-server";
+import { isPermanentlyGone } from "../lib/availability";
+import { detectPlatform } from "../lib/platform";
+import { DEFAULT_CLIPS_SETTINGS } from "../lib/clipSettings";
+import { resolveEffectiveAvailability } from "../lib/availability-server";
+import { loadDoNotClean, setDoNotClean } from "../lib/doNotClean-server";
+import {
+ readAvailabilityVerdict,
+ requestAvailabilityCheck,
+ verdictFor,
+ type CheckRequestDeps,
+} from "./availabilityVerdict";
+import { assertChannelMediaReachable } from "../lib/channelMedia";
import path from "node:path";
import fs from "fs-extra";
import type { Paths } from "../lib/paths";
import { isDoNotClean } from "../lib/doNotClean-server";
-import { hasDiarization } from "../lib/diarization-server";
-import { getSettings } from "../lib/settings";
+import { loadDiarization } from "../lib/diarization-server";
+import { hasVoiceprints } from "../lib/diarization";
+import { getSettings, type DiarizationSettings } from "../lib/settings";
import { audioFilesToRemove } from "../lib/videoStatus";
import { readChannelConfig } from "./channels";
import { computeKeptVideoIds } from "./keptVideos";
import { pruneSavedVideos } from "./pruneSavedVideos";
import { excludedIds, verifyBeforeClean } from "./verifyBeforeClean";
-const { pathExists, readdir } = fs;
+const { pathExists, readdir, stat } = fs;
export type CleanAudioOptions = {
channelSlug: string;
@@ -42,6 +55,12 @@ export type CleanAudioResult = {
// catches up, and a number that only ever grows is the signal that the CPU
// lane has fallen behind the GPU.
awaitingDiarization: number;
+ // Left alone because the video IS diarized but its diarization.json has no
+ // voice fingerprints yet (diarization.requireVoiceprints). Transient like
+ // awaitingDiarization: the Speakers lane adds them while the audio is here.
+ awaitingVoiceprint: number;
+ // Bytes of audio removed (through tier links: the bytes on the media tier).
+ bytesFreed: number;
// Saved-store containers evicted because they rolled out of the keep-latest
// window (the retention prune runs alongside the audio sweep).
prunedSavedVideos: number;
@@ -54,6 +73,98 @@ type CleanCandidate = {
audioFiles: string[];
};
+// Where ONE video's audio leaves the sweep, or "candidate" when it passes every
+// gate that needs no network. The ONE rule both the channel sweep and the
+// per-video clean (cleanAudioForVideo) apply, in the same order, so the two can
+// never disagree about what is safe to delete. Availability (verifyBeforeClean)
+// is the last gate and is asked by the caller, for every candidate at once.
+export type AudioCleanGate =
+ | "candidate"
+ | "no-transcript"
+ | "no-audio"
+ | "keep-latest"
+ | "do-not-clean"
+ | "awaiting-diarization"
+ | "awaiting-voiceprint"
+ // cleanAudioForVideo only: the channel's media drive is not answering. The
+ // channel sweep is covered by its job kind's needsMedia guard instead.
+ | "media-unreachable"
+ // cleanAudioForVideo only, from the channel's availability verdict cache
+ // (controller/availabilityVerdict.ts): no listing within
+ // diarization.cleanVerdictMaxAgeHours (a check is requested), or a fresh
+ // listing that does not name the video (maybe deleted, maybe unlisted).
+ | "awaiting-availability"
+ | "maybe-missing"
+ // cleanAudioForVideo only (review B2): the channel has no source URL, so no
+ // check can vouch for anything — held unless its config sets
+ // cleanAfterCaptureUnverified. The manual sweep cleans these as before.
+ | "no-source-url"
+ // cleanAudioForVideo only: a channel on clips.wholeRecordingPlatforms
+ // (Rumble by default), whose audio.<ext> is the cue-clock source of the
+ // recording's time map (lib/recordingClock.mjs) — held unless
+ // diarization.cleanWholeRecordingAudio.
+ | "whole-recording";
+
+export async function audioCleanGate(
+ videoDir: string,
+ id: string,
+ ctx: { keptIds: Set<string>; diarization: DiarizationSettings },
+): Promise<{ gate: AudioCleanGate; audioFiles: string[] }> {
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ if (!entries.includes("transcript.json")) return { gate: "no-transcript", audioFiles: [] };
+ const audioFiles = audioFilesToRemove(entries);
+ if (audioFiles.length === 0) return { gate: "no-audio", audioFiles };
+ if (ctx.keptIds.has(id)) return { gate: "keep-latest", audioFiles };
+ if (await isDoNotClean(videoDir)) return { gate: "do-not-clean", audioFiles };
+ // While diarization is enabled, a transcribed video that still has audio but
+ // no diarization.json is NOT cleanable yet — its diarize job hasn't run.
+ //
+ // This guard is the whole reason deferring diarization to an async job is
+ // safe. Without it the sweep would delete the audio out from under a queued
+ // diarize job, silently and permanently: audio is the one input in this
+ // pipeline that cannot be regenerated, and the failure would leave no trace.
+ //
+ // A malformed sidecar reads as absent (loadDiarization), as it always has.
+ if (ctx.diarization.enabled) {
+ const record = entries.includes("diarization.json")
+ ? await loadDiarization(videoDir)
+ : null;
+ if (!record) return { gate: "awaiting-diarization", audioFiles };
+ // The voice fingerprint is the part of a diarization that cannot be made
+ // again without the audio, so it is waited for too.
+ if (ctx.diarization.requireVoiceprints && !hasVoiceprints(record)) {
+ return { gate: "awaiting-voiceprint", audioFiles };
+ }
+ }
+ return { gate: "candidate", audioFiles };
+}
+
+const SKIP_LOG: Partial<Record<AudioCleanGate, string>> = {
+ "keep-latest": "in keep-latest window",
+ "do-not-clean": "marked do not clean",
+ "awaiting-diarization": "awaiting diarization",
+ "awaiting-voiceprint": "awaiting voice fingerprint",
+};
+
+// Remove a candidate's audio files, through removeMediaFile (a tier link takes
+// its bytes on the media tier with it). Returns the bytes freed.
+async function removeCandidateAudio(
+ c: CleanCandidate,
+ log: (m: string) => void,
+): Promise<{ removed: number; bytes: number }> {
+ let removed = 0;
+ let bytes = 0;
+ for (const f of c.audioFiles) {
+ // stat follows a tier link to the bytes it frees.
+ const size = await stat(path.join(c.videoDir, f)).then((st) => st.size, () => 0);
+ await removeMediaFile(c.videoDir, f);
+ log(`Removed ${c.id}/${f}`);
+ removed++;
+ bytes += size;
+ }
+ return { removed, bytes };
+}
+
export async function cleanAudioFromTranscribed({
channelSlug,
paths,
@@ -73,6 +184,8 @@ export async function cleanAudioFromTranscribed({
pinned: 0,
unverified: 0,
awaitingDiarization: 0,
+ awaitingVoiceprint: 0,
+ bytesFreed: 0,
prunedSavedVideos: 0,
prunedBytes: 0,
};
@@ -90,16 +203,11 @@ export async function cleanAudioFromTranscribed({
let cleanedDirs = 0;
let removedFiles = 0;
+ let bytesFreed = 0;
let protectedCount = 0;
let awaitingDiarization = 0;
+ let awaitingVoiceprint = 0;
- // While diarization is enabled, a transcribed video that still has audio but
- // no diarization.json is NOT cleanable yet — its diarize job hasn't run.
- //
- // This guard is the whole reason deferring diarization to an async job is
- // safe. Without it the sweep would delete the audio out from under a queued
- // diarize job, silently and permanently: audio is the one input in this
- // pipeline that cannot be regenerated, and the failure would leave no trace.
const diarization = getSettings().diarization;
// --- Discover -------------------------------------------------------------
@@ -109,26 +217,13 @@ export async function cleanAudioFromTranscribed({
for (const id of dirs) {
if (signal?.aborted) break;
const videoDir = path.join(dataDir, id);
- const entries = await readdir(videoDir).catch(() => [] as string[]);
- if (!entries.includes("transcript.json")) continue;
- const audioFiles = audioFilesToRemove(entries);
- if (audioFiles.length === 0) continue;
- if (keptIds.has(id)) {
- log(`Skipped ${id} (in keep-latest window)`);
- protectedCount++;
- continue;
- }
- if (await isDoNotClean(videoDir)) {
- log(`Skipped ${id} (marked do not clean)`);
- protectedCount++;
- continue;
- }
- if (diarization.enabled && !(await hasDiarization(videoDir))) {
- log(`Skipped ${id} (awaiting diarization)`);
- awaitingDiarization++;
- continue;
- }
- candidates.push({ id, videoDir, audioFiles });
+ const { gate, audioFiles } = await audioCleanGate(videoDir, id, { keptIds, diarization });
+ if (gate === "no-transcript" || gate === "no-audio") continue;
+ if (gate !== "candidate") log(`Skipped ${id} (${SKIP_LOG[gate]})`);
+ if (gate === "keep-latest" || gate === "do-not-clean") protectedCount++;
+ else if (gate === "awaiting-diarization") awaitingDiarization++;
+ else if (gate === "awaiting-voiceprint") awaitingVoiceprint++;
+ else candidates.push({ id, videoDir, audioFiles });
}
// --- Verify ---------------------------------------------------------------
@@ -155,28 +250,28 @@ export async function cleanAudioFromTranscribed({
for (const candidate of candidates) {
if (signal?.aborted) break;
if (excluded.has(candidate.id)) continue;
- for (const f of candidate.audioFiles) {
- // Through its link when tiered (release 17): the bytes on the media tier go too.
- await removeMediaFile(candidate.videoDir, f);
- log(`Removed ${candidate.id}/${f}`);
- removedFiles++;
- }
+ const out = await removeCandidateAudio(candidate, log);
+ removedFiles += out.removed;
+ bytesFreed += out.bytes;
cleanedDirs++;
}
- const skipped = protectedCount + pinned + unverified + awaitingDiarization;
+ const skipped =
+ protectedCount + pinned + unverified + awaitingDiarization + awaitingVoiceprint;
// Keep the historical wording when the gate had nothing to report, and break
// the total down only when it would otherwise be misleading.
// The diarization clause is appended only when it is non-zero, so the message
// stays byte-identical for every install that doesn't use the capture lane —
// a "0 awaiting diarization" on a box with diarization off is noise, and this
// exact string is asserted in pre-clean-availability.spec.
+ // The voice-fingerprint clause follows the same rule.
const diarNote =
- awaitingDiarization > 0 ? `, ${awaitingDiarization} awaiting diarization` : "";
+ (awaitingDiarization > 0 ? `, ${awaitingDiarization} awaiting diarization` : "") +
+ (awaitingVoiceprint > 0 ? `, ${awaitingVoiceprint} awaiting voice fingerprint` : "");
const skippedNote =
skipped === 0
? ""
- : pinned === 0 && unverified === 0 && awaitingDiarization === 0
+ : pinned === 0 && unverified === 0 && awaitingDiarization === 0 && awaitingVoiceprint === 0
? ` Skipped ${skipped} (do not clean).`
: ` Skipped ${skipped} (${protectedCount} protected, ${pinned} gone-from-source pinned, ${unverified} unverified${diarNote}).`;
log(
@@ -195,7 +290,143 @@ export async function cleanAudioFromTranscribed({
pinned,
unverified,
awaitingDiarization,
+ awaitingVoiceprint,
+ bytesFreed,
prunedSavedVideos: prune.pruned,
prunedBytes: prune.bytesFreed,
};
}
+
+export type CleanOneOptions = {
+ channelSlug: string;
+ paths: Paths;
+ videoId: string;
+ onLog?: (msg: string) => void;
+ signal?: AbortSignal;
+ // Test seam: how a check is asked for (never run) — see availabilityVerdict.ts.
+ checkDeps?: CheckRequestDeps;
+};
+
+export type CleanOneResult = {
+ // cleaned: the audio is gone. held: a gate kept it (`gate` says which).
+ // pinned: its cached availability says it is gone upstream — now
+ // do-not-clean, kept.
+ outcome: "cleaned" | "held" | "pinned";
+ gate?: AudioCleanGate;
+ removedFiles: number;
+ bytesFreed: number;
+};
+
+// THE PER-VIDEO HALF of cleanAudioFromTranscribed, for clean-after-capture: the
+// same gates in the same order (audioCleanGate) and the same removeMediaFile.
+//
+// ITS AVAILABILITY CHECK ASKS NOTHING OF THE NETWORK (review B1). The channel
+// sweep's verifyBeforeClean lists the whole channel per call; called once per
+// captured video that is a full listing per video, outside every platform
+// queue, gap and hold. Here: a video whose cached per-video availability says
+// it is gone is pinned (verifyBeforeClean's tier A, no spawn); otherwise the
+// channel's verdict cache decides — listed in a fresh listing → clean; not named
+// → held (maybe missing); no fresh listing → held, and ONE quick check of the
+// channel is requested on its platform's queue, at most once per max age.
+// No saved-video prune: that is the channel sweep's retention pass.
+export async function cleanAudioForVideo({
+ channelSlug,
+ paths,
+ videoId,
+ onLog,
+ signal,
+ checkDeps,
+}: CleanOneOptions): Promise<CleanOneResult> {
+ const log = onLog ?? ((m: string) => console.log(m));
+ const held = (gate: AudioCleanGate): CleanOneResult => ({
+ outcome: "held",
+ gate,
+ removedFiles: 0,
+ bytesFreed: 0,
+ });
+ const videoDir = path.join(paths.channelsDir, channelSlug, "data", videoId);
+ const config = await readChannelConfig(paths, channelSlug);
+ const keptIds = await computeKeptVideoIds({
+ paths,
+ channelSlug,
+ keepLatest: config?.keepLatest ?? 0,
+ });
+ const diarization = getSettings().diarization;
+ const { gate, audioFiles } = await audioCleanGate(videoDir, videoId, { keptIds, diarization });
+ if (gate !== "candidate") {
+ if (SKIP_LOG[gate]) log(`Kept ${videoId}'s audio (${SKIP_LOG[gate]})`);
+ return held(gate);
+ }
+ if (signal?.aborted) return held(gate);
+ // THE CUE CLOCK (review). On a whole-recording platform the cues are the
+ // transcription of audio.<ext>, and every clip is cut from another file of
+ // the recording through a time map fitted against THAT audio
+ // (common/lib/recordingClock.mjs). Deleting it systematically leaves those
+ // recordings with no map to make later. Held by default; the operator rules.
+ const platform = config?.platform ?? detectPlatform(config?.url ?? "") ?? "";
+ const whole = getSettings().clips?.wholeRecordingPlatforms ?? DEFAULT_CLIPS_SETTINGS.wholeRecordingPlatforms;
+ if (whole.includes(platform) && !diarization.cleanWholeRecordingAudio) {
+ log(`Kept ${videoId}'s audio: ${platform} records whole — its audio is the recording clock's source (diarization.cleanWholeRecordingAudio).`);
+ return held("whole-recording");
+ }
+ // NO SOURCE, NO CHECK (review B2). verifyBeforeClean fails OPEN for a channel
+ // with no URL — right for a sweep the operator pressed, wrong for an
+ // automatic delete: an imported or hand-built channel's audio may be its only
+ // copy anywhere. Held unless the channel opts in.
+ const unverifiedOptIn = !config?.url && config?.cleanAfterCaptureUnverified === true;
+ if (!config?.url && !unverifiedOptIn) {
+ log(`Kept ${videoId}'s audio: no source to check — clean by hand (or set cleanAfterCaptureUnverified on the channel).`);
+ return held("no-source-url");
+ }
+ // AN UNMOUNTED DRIVE IS NOT AN EMPTY ONE. The audio here may be a tier link
+ // into a media/ that points at another disk; removing the link while that
+ // disk is away strands its bytes there. Asked fresh, per video: this runs
+ // from a unit hook, not from a job whose kind declares needsMedia.
+ try {
+ await assertChannelMediaReachable(paths, channelSlug);
+ } catch (err) {
+ log(`Kept ${videoId}'s audio: ${(err as Error).message}`);
+ return held("media-unreachable");
+ }
+ // ALWAYS, whatever verifyAvailabilityBeforeClean says: that setting governs
+ // the manual sweep the operator presses. An automatic delete is never
+ // unverified — only a URL-less channel's explicit opt-in skips this.
+ if (!unverifiedOptIn) {
+ const cached = await resolveEffectiveAvailability(videoDir);
+ if (isPermanentlyGone(cached)) {
+ if (!(await loadDoNotClean(videoDir))) {
+ await setDoNotClean(videoDir, true, `deleted from source (pre-clean check): ${cached}`);
+ log(`Pinned ${videoId} as do-not-clean (${cached}) — gone from source.`);
+ }
+ return { outcome: "pinned", removedFiles: 0, bytesFreed: 0 };
+ }
+ const maxAge = diarization.cleanVerdictMaxAgeHours;
+ const verdict = verdictFor(await readAvailabilityVerdict(paths, channelSlug), videoId, maxAge);
+ if (verdict === "absent") {
+ log(`Kept ${videoId}'s audio: the channel's last listing does not name it (maybe missing — Check maybe missing resolves it).`);
+ return held("maybe-missing");
+ }
+ if (verdict !== "listed") {
+ const asked = await requestAvailabilityCheck(paths, channelSlug, maxAge, checkDeps);
+ if (asked.status === "service-alert") {
+ log(`Kept ${videoId}'s audio: awaiting an availability check (service alert open: ${asked.why}).`);
+ return held("awaiting-availability");
+ }
+ const why =
+ asked.status === "requested"
+ ? "a quick availability check of the channel is queued"
+ : asked.status === "already-requested"
+ ? `a check was requested at ${asked.at}`
+ : asked.status === "platform-held"
+ ? `its platform is held, so no check is asked: ${asked.why}`
+ : asked.status === "refused"
+ ? `the check was refused: ${asked.why}`
+ : "the channel has no source URL to list";
+ log(`Kept ${videoId}'s audio: awaiting an availability check (${verdict === "none" ? "never listed" : `no listing in ${maxAge} h`}; ${why}).`);
+ return held("awaiting-availability");
+ }
+ }
+ if (signal?.aborted) return held(gate);
+ const out = await removeCandidateAudio({ id: videoId, videoDir, audioFiles }, log);
+ return { outcome: "cleaned", removedFiles: out.removed, bytesFreed: out.bytes };
+}
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/diarizeOne.test.ts b/common/controller/diarizeOne.test.ts
@@ -0,0 +1,186 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import path from "node:path";
+import os from "node:os";
+import { chmod, mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { diarizeOneVideo, voiceprintOneVideo } from "./diarizeOne";
+import { defaultSiteSettings } from "../lib/settings";
+import type { Paths } from "../lib/paths";
+import { hasVoiceprints, type DiarizationRecord } from "../lib/diarization";
+import { loadDiarization } from "../lib/diarization-server";
+import { loadAudioIntegrity } from "../lib/audioIntegrity-server";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test common/controller/diarizeOne.test.ts
+//
+// The engine is a fake DIARIZE_BIN: it logs its argv, and in --voiceprints-only
+// mode adds a voiceprint per speaker to the record it is given -- or exits 4
+// (diarize-sherpa.py's "ffmpeg failed") when FAKE_EXIT says so.
+
+const hasFfmpeg = spawnSync("ffmpeg", ["-version"], { stdio: "ignore" }).status === 0;
+
+const FAKE = `#!/usr/bin/env node
+const fs = require("node:fs");
+const argv = process.argv.slice(2);
+fs.appendFileSync(process.env.FAKE_LOG, JSON.stringify(argv) + "\\n");
+if (process.env.FAKE_STDERR) process.stderr.write(process.env.FAKE_STDERR + "\\n");
+if (process.env.FAKE_EXIT) process.exit(Number(process.env.FAKE_EXIT));
+const at = (f) => argv[argv.indexOf(f) + 1];
+const rec = JSON.parse(fs.readFileSync(at("--voiceprints-only"), "utf8"));
+const speakers = [...new Set(rec.turns.map((t) => t.speaker))];
+rec.voiceprints = speakers.map((s) => ({ speaker: s, seconds: 1, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "emb.onnx" }));
+rec.voiceprintsAt = "2026-11-11T00:00:00.000Z";
+fs.writeFileSync(at("--output"), JSON.stringify(rec) + "\\n");
+`;
+
+const EXISTING: DiarizationRecord = {
+ videoId: "vid1",
+ generatedAt: "2026-08-07T00:00:00.000Z",
+ speakers: 2,
+ turns: [
+ { start: 0, end: 4, speaker: 0 },
+ { start: 4, end: 9, speaker: 1 },
+ ],
+ engine: { engine: "sherpa-onnx", segmentationModel: "seg.onnx", embeddingModel: "emb.onnx", threshold: 0.9 },
+};
+
+async function setup(opts: { audio?: string | null } = {}) {
+ const root = await mkdtemp(path.join(os.tmpdir(), "diarize-one-"));
+ const bin = path.join(root, "fake-diarize.cjs");
+ await writeFile(bin, FAKE);
+ await chmod(bin, 0o755);
+ const log = path.join(root, "calls.log");
+ await writeFile(log, "");
+ const videoDir = path.join(root, "vid1");
+ await mkdir(videoDir);
+ await writeFile(path.join(videoDir, "diarization.json"), JSON.stringify(EXISTING) + "\n");
+ if (opts.audio !== null) await writeFile(path.join(videoDir, "audio.mp3"), opts.audio ?? "not really mp3");
+ const paths = { diarizeBin: bin, ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" } as unknown as Paths;
+ const settings = {
+ ...defaultSiteSettings().diarization,
+ enabled: true,
+ segModel: "/m/seg.onnx",
+ embModel: "/m/emb.onnx",
+ threshold: 0.9,
+ };
+ process.env.FAKE_LOG = log;
+ const calls = async () =>
+ (await readFile(log, "utf8")).split("\n").filter(Boolean).map((l) => JSON.parse(l) as string[]);
+ return { root, videoDir, paths, settings, calls, cleanup: () => rm(root, { recursive: true, force: true }) };
+}
+
+test("a fresh sidecar without voiceprints gets them from its own turns — no re-diarization, generatedAt kept", async () => {
+ const t = await setup();
+ try {
+ const out = await diarizeOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} });
+ assert.equal(out, "diarized");
+ const calls = await t.calls();
+ assert.equal(calls.length, 1);
+ assert.ok(calls[0].includes("--voiceprints-only"), "the voiceprint step, not a diarization");
+ assert.ok(!calls[0].includes("--seg"));
+ const rec = await loadDiarization(t.videoDir);
+ assert.equal(hasVoiceprints(rec), true);
+ assert.equal(rec?.generatedAt, EXISTING.generatedAt);
+ assert.deepEqual(rec?.turns, EXISTING.turns);
+ // A second pass has nothing to do.
+ assert.equal(await diarizeOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "already-exists");
+ assert.equal((await t.calls()).length, 1);
+ } finally {
+ await t.cleanup();
+ }
+});
+
+test("with the audio gone: no fingerprint is possible, and that is not a failure", async () => {
+ const t = await setup({ audio: null });
+ try {
+ assert.equal(await voiceprintOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "no-audio");
+ assert.equal(await diarizeOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "already-exists");
+ assert.equal((await t.calls()).length, 0);
+ assert.equal(hasVoiceprints(await loadDiarization(t.videoDir)), false);
+ } finally {
+ await t.cleanup();
+ }
+});
+
+test("a zero-byte audio is recorded as undecodable and skipped without running the engine", async () => {
+ const t = await setup({ audio: "" });
+ try {
+ assert.equal(await voiceprintOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "unreadable");
+ assert.equal((await t.calls()).length, 0);
+ const rec = await loadAudioIntegrity(t.videoDir);
+ assert.equal(rec?.verdict, "undecodable");
+ assert.equal(rec?.by, "speakers");
+ assert.equal(rec?.size, 0);
+ } finally {
+ await t.cleanup();
+ }
+});
+
+test("an engine that cannot decode the audio (exit 4): recorded as undecodable, the sidecar untouched", { skip: !hasFfmpeg && "needs ffmpeg" }, async () => {
+ const t = await setup({ audio: "garbage, not audio" });
+ process.env.FAKE_EXIT = "4";
+ try {
+ const before = await readFile(path.join(t.videoDir, "diarization.json"), "utf8");
+ assert.equal(await voiceprintOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "unreadable");
+ assert.equal(await readFile(path.join(t.videoDir, "diarization.json"), "utf8"), before);
+ assert.equal((await loadAudioIntegrity(t.videoDir))?.verdict, "undecodable");
+ } finally {
+ delete process.env.FAKE_EXIT;
+ await t.cleanup();
+ }
+});
+
+test("an engine failure for any other reason is a plain failure, and no verdict is written", async () => {
+ const t = await setup();
+ process.env.FAKE_EXIT = "1";
+ try {
+ assert.equal(await voiceprintOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "failed");
+ // diarizeOne keeps the diarization: the sidecar is fine, only without voiceprints.
+ assert.equal(await diarizeOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "already-exists");
+ assert.equal(await loadAudioIntegrity(t.videoDir), null);
+ } finally {
+ delete process.env.FAKE_EXIT;
+ await t.cleanup();
+ }
+});
+
+test("the voiceprint step never falls back to a source container: with no audio, no fingerprint is possible", async () => {
+ const t = await setup({ audio: null });
+ try {
+ await writeFile(path.join(t.videoDir, "source-media.mp4"), "a container of the same recording");
+ assert.equal(await voiceprintOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "no-audio");
+ assert.equal((await t.calls()).length, 0, "the engine is never given the container");
+ assert.equal(hasVoiceprints(await loadDiarization(t.videoDir)), false);
+ } finally {
+ await t.cleanup();
+ }
+});
+
+test("an exit-6 refusal is recorded against the file (voiceprintsRefused), turns and generatedAt kept, no voiceprints", async () => {
+ const t = await setup();
+ process.env.FAKE_EXIT = "6";
+ process.env.FAKE_STDERR = "diarize-sherpa: refused: the file is 99.000s, the record's audio 10s — not the audio these turns were made from";
+ try {
+ const logs: string[] = [];
+ assert.equal(
+ await voiceprintOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: (m) => logs.push(m) }),
+ "refused",
+ );
+ const rec = await loadDiarization(t.videoDir);
+ assert.equal(rec?.generatedAt, EXISTING.generatedAt);
+ assert.deepEqual(rec?.turns, EXISTING.turns);
+ assert.equal(hasVoiceprints(rec), false);
+ assert.equal(rec?.voiceprintsRefused?.file, "audio.mp3");
+ assert.equal(rec?.voiceprintsRefused?.size, "not really mp3".length);
+ assert.match(rec?.voiceprintsRefused?.reason ?? "", /^the file is 99\.000s/);
+ assert.ok(logs.some((l) => l.includes("no fingerprint possible from this file: the file is 99.000s")));
+ // Not an integrity verdict: the audio decodes, it is just not these turns'.
+ assert.equal(await loadAudioIntegrity(t.videoDir), null);
+ } finally {
+ delete process.env.FAKE_EXIT;
+ delete process.env.FAKE_STDERR;
+ await t.cleanup();
+ }
+});
+
diff --git a/common/controller/diarizeOne.ts b/common/controller/diarizeOne.ts
@@ -20,10 +20,18 @@ import {
DIARIZATION_FILENAME,
SORTFORMER_DIARIZATION_ENGINE,
diarizationTarget,
+ hasVoiceprints,
isDiarizationFresh,
} from "../lib/diarization";
-import { hasDiarization, loadDiarization } from "../lib/diarization-server";
+import { hasDiarization, loadDiarization, writeDiarization } from "../lib/diarization-server";
import { findSourceMedia, isRealAudioFile } from "../lib/videoStatus";
+import {
+ fileIdentity,
+ integrityRecord,
+ measureAndRecordIntegrity,
+ writeAudioIntegrity,
+} from "../lib/audioIntegrity-server";
+import type { AudioIntegrityVerdict } from "../lib/audioIntegrity";
import { pickPreferredAudio } from "../lib/mediaFiles";
import { resolveSavedVideo } from "../lib/savedVideo-server";
@@ -107,12 +115,23 @@ export async function diarizeOneVideo(
if (!opts.force) {
const existing = await loadDiarization(opts.videoDir);
if (existing && isDiarizationFresh(existing, diarizationTarget(cfg))) {
+ // Fresh turns from before voiceprints existed: add them from those same
+ // turns while the audio is still here. Never a reason to fail the
+ // diarization itself — the sidecar is good, it is only without them.
+ if (!hasVoiceprints(existing)) {
+ const vp = await voiceprintOneVideo({ ...opts, settings: cfg });
+ if (vp === "voiceprinted") return "diarized";
+ }
return "already-exists";
}
}
const media = await resolveDiarizableMedia(opts.videoDir);
if (!media) return "no-audio";
+ if (await isZeroByteAudio(opts.videoDir, media)) {
+ await recordUnreadableAudio(opts, media, log);
+ return "failed";
+ }
const start = Date.now();
log(`Diarize ${opts.videoId} start (${media})`);
@@ -176,6 +195,9 @@ export async function diarizeOneVideo(
await child;
} catch (err) {
log(`Diarize ${opts.videoId} failed: ${(err as Error).message}`);
+ if (!opts.signal?.aborted && isDecodeFailure(err)) {
+ await recordUnreadableAudio(opts, media, log);
+ }
return "failed";
}
@@ -193,3 +215,177 @@ export async function diarizeOneVideo(
);
return "diarized";
}
+
+// ---------------------------------------------------------------------------
+// Voiceprints for a sidecar that predates them.
+
+export type VoiceprintOneOutcome =
+ // diarization.json now carries a voiceprint per speaker.
+ | "voiceprinted"
+ // It already did.
+ | "already-present"
+ // No (valid) diarization.json: diarize it first.
+ | "no-diarization"
+ // The audio is gone: no fingerprint is possible any more. A fact to list,
+ // never an error.
+ | "no-audio"
+ // No embedding model configured.
+ | "not-configured"
+ // The audio is on disk but does not decode (recorded in audio-integrity.json).
+ | "unreadable"
+ // The engine refused this file for these turns (exit 6), recorded on the
+ // sidecar as voiceprintsRefused: no fingerprint possible from it.
+ | "refused"
+ | "failed";
+
+// Add voiceprints to an existing diarization.json from its own turns: the
+// embedder only (scripts/diarize.mjs --voiceprints-only), no segmentation and
+// no re-clustering, so the turns, the engine and `generatedAt` are kept as they
+// are (attribution-diarized's freshness names generatedAt). The same embedding
+// model the sherpa engine clusters with, so these are the numbers a fresh
+// diarization would have recorded.
+export async function voiceprintOneVideo(
+ opts: DiarizeOneOptions,
+): Promise<VoiceprintOneOutcome> {
+ const log = opts.onLog ?? ((m: string) => console.log(m));
+ const cfg = opts.settings ?? getSettings().diarization;
+ if (!cfg.embModel) return "not-configured";
+ const existing = await loadDiarization(opts.videoDir);
+ if (!existing) return "no-diarization";
+ if (hasVoiceprints(existing)) return "already-present";
+ // THE VIDEO'S OWN AUDIO, NEVER resolveDiarizableMedia's fallback (review B3).
+ // Turns made from audio.<ext> are seconds on that file's clock; a source
+ // container or a saved video of the same recording can run seconds apart
+ // (Rumble: measured up to 13 s), and centroids cut from it would be other
+ // stretches — other voices. Without the audio, no fingerprint is possible.
+ const entries = await readdir(opts.videoDir).catch(() => [] as string[]);
+ const media = pickPreferredAudio(entries.filter(isRealAudioFile));
+ if (!media) return "no-audio";
+ if (await isZeroByteAudio(opts.videoDir, media)) {
+ await recordUnreadableAudio(opts, media, log);
+ return "unreadable";
+ }
+ const start = Date.now();
+ log(`Voiceprints ${opts.videoId} start (${media})`);
+ const output: string[] = [];
+ try {
+ const child = execa(
+ opts.paths.diarizeBin,
+ [
+ "--voiceprints-only",
+ DIARIZATION_FILENAME,
+ "--output",
+ DIARIZATION_FILENAME,
+ "--python",
+ cfg.python,
+ "--emb",
+ cfg.embModel,
+ "--threads",
+ String(cfg.threads),
+ "--ffmpeg",
+ opts.paths.ffmpegBin,
+ "--ffprobe",
+ opts.paths.ffprobeBin,
+ media,
+ ],
+ { cwd: opts.videoDir, cancelSignal: opts.signal, all: true, buffer: false },
+ );
+ child.all?.on("data", (c: Buffer) => {
+ const text = c.toString("utf8").trimEnd();
+ output.push(text);
+ log(text);
+ });
+ await child;
+ } catch (err) {
+ log(`Voiceprints ${opts.videoId} failed: ${(err as Error).message}`);
+ if (!opts.signal?.aborted && (err as { exitCode?: number })?.exitCode === 6) {
+ const reason = refusalReason(output.join("\n"));
+ const id = await fileIdentity(path.join(opts.videoDir, media)).catch(() => null);
+ const current = await loadDiarization(opts.videoDir);
+ if (id && current) {
+ await writeDiarization(opts.videoDir, {
+ ...current,
+ voiceprintsRefused: { file: media, size: id.size, mtime: id.mtime, reason, at: new Date().toISOString() },
+ });
+ }
+ log(`${opts.videoId}: no fingerprint possible from this file: ${reason}`);
+ return "refused";
+ }
+ if (!opts.signal?.aborted && isDecodeFailure(err)) {
+ const verdict = await recordUnreadableAudio(opts, media, log);
+ if (verdict === "undecodable") return "unreadable";
+ }
+ return "failed";
+ }
+ // Trust the file: the same turns, the same generatedAt, voiceprints complete.
+ const after = await loadDiarization(opts.videoDir);
+ if (
+ !after ||
+ !hasVoiceprints(after) ||
+ after.generatedAt !== existing.generatedAt ||
+ after.turns.length !== existing.turns.length
+ ) {
+ log(`Voiceprints ${opts.videoId} produced no complete voiceprints — treating as failed.`);
+ return "failed";
+ }
+ log(
+ `Voiceprints ${opts.videoId} done in ${((Date.now() - start) / 1000).toFixed(1)}s`,
+ );
+ return "voiceprinted";
+}
+
+// The engine's own sentence for an exit-6 refusal ("diarize-sherpa: refused:
+// <why>"), or a generic one.
+function refusalReason(output: string): string {
+ const lines = output.split("\n").filter((l) => l.includes("refused:"));
+ const last = lines[lines.length - 1];
+ return last ? last.slice(last.indexOf("refused:") + "refused:".length).trim() : "the engine refused this file";
+}
+
+// The engine's "could not decode" exits: diarize-sherpa.py returns 4 when
+// ffmpeg fails and 5 when it decodes zero samples, and diarize.mjs passes the
+// code through.
+function isDecodeFailure(err: unknown): boolean {
+ const code = (err as { exitCode?: number })?.exitCode;
+ return code === 4 || code === 5;
+}
+
+async function isZeroByteAudio(videoDir: string, media: string): Promise<boolean> {
+ if (!isRealAudioFile(media)) return false;
+ const id = await fileIdentity(path.join(videoDir, media)).catch(() => null);
+ return id !== null && id.size === 0;
+}
+
+// RECORD, THEN SKIP. An audio file the engine cannot decode gets a verdict in
+// audio-integrity.json (keyed to the file's size and mtime), and the
+// diarization operation reports a video whose held audio is `undecodable` as
+// blocked — so the lane does not spend a pass on it every run, and a re-fetched
+// file (a new size or mtime) is work again. Only a real audio file: a source
+// container or a saved video is not this lane's to judge.
+async function recordUnreadableAudio(
+ opts: DiarizeOneOptions,
+ media: string,
+ log: (m: string) => void,
+): Promise<AudioIntegrityVerdict | null> {
+ if (!isRealAudioFile(media)) return null;
+ try {
+ const file = path.join(opts.videoDir, media);
+ const id = await fileIdentity(file);
+ const record =
+ id.size === 0
+ ? integrityRecord(media, id, { decodedSeconds: 0, totalSeconds: 0, gaps: [] }, { by: "speakers" })
+ : await measureAndRecordIntegrity(
+ opts.videoDir,
+ media,
+ { ffmpegBin: opts.paths.ffmpegBin, ffprobeBin: opts.paths.ffprobeBin, signal: opts.signal, lowPriority: true },
+ { by: "speakers" },
+ );
+ if (!record) return null;
+ if (id.size === 0) await writeAudioIntegrity(opts.videoDir, record);
+ log(`${opts.videoId}/${media}: ${record.verdict} (${id.size} bytes) — recorded in audio-integrity.json.`);
+ return record.verdict;
+ } catch (err) {
+ log(`${opts.videoId}/${media}: could not record its integrity: ${(err as Error).message}`);
+ return null;
+ }
+}
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
@@ -836,3 +836,18 @@ 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);
});
+
+// 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";
@@ -236,7 +237,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 +761,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);
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/operationBatch.ts b/common/controller/operationBatch.ts
@@ -50,6 +50,7 @@ import type { TaskTracker } from "../jobs/taskHooks";
import type { JobProgress } from "../jobs/registry";
import { readVideoFiles, CUES_JSON_FILENAME } from "../lib/videoStatus";
import {
+ DIARIZATION_OPERATION_ID,
DIGEST_OPERATION_ID,
addOperationState,
digestLaneFor,
@@ -73,6 +74,11 @@ import { TranscribeError } from "./transcribeError";
import { readDigestContext } from "../lib/digestContext-server";
import type { StartWorkerUnitInput } from "./workerServer";
import { reacquireMediaFor, type ReacquireOutcome } from "./backfillReacquire";
+import { cleanAudioForVideo } from "./cleanAudioFromTranscribed";
+import { hasVoiceprints } from "../lib/diarization";
+import { loadDiarization } from "../lib/diarization-server";
+import { recordSpeakersFreed } from "../lib/speakersLedger-server";
+import { formatBytes } from "../lib/format";
import { batchRecencyComparator } from "./batchRecency";
import {
digestGate,
@@ -335,7 +341,7 @@ function backfillLaneLimit(
hold: {
hold: true,
reason: "paused",
- message: "Backfill lane disabled in settings — holding.",
+ message: "The Speakers lane is paused — holding. Work through speakers (on its lane card) lifts it.",
},
};
}
@@ -915,6 +921,10 @@ export type OperationUnitReport = {
reacquireHandedOff: number;
reacquireFailed: number;
diskFloorHit: boolean;
+ // Clean-after-capture (diarization.cleanAfterCapture): audio removed right
+ // after this unit captured the video's speakers and voice fingerprints.
+ audioCleaned: number;
+ audioFreedBytes: number;
};
function emptyReport(
@@ -932,6 +942,8 @@ function emptyReport(
reacquireHandedOff: 0,
reacquireFailed: 0,
diskFloorHit: false,
+ audioCleaned: 0,
+ audioFreedBytes: 0,
};
}
@@ -1062,9 +1074,53 @@ export async function runOperationUnit(
}
}
}
+ // AFTER the finally: a re-acquired file has already been removed above, and
+ // this must never race that cleanup.
+ if (report.outcome === "done" && unit.op.id === DIARIZATION_OPERATION_ID && !aborted()) {
+ await cleanAfterCapture(run, unit, videoDir, report, log, signal);
+ }
return report;
}
+// CLEAN AFTER CAPTURE. The per-video half of Clean audio, run the moment a
+// diarization unit has captured a video's speakers — and only when its sidecar
+// carries the voice fingerprints, because those are the part a deleted audio
+// can never give back. Every gate of the channel sweep applies
+// (cleanAudioForVideo → audioCleanGate + verifyBeforeClean); a gone-upstream
+// video is pinned, not deleted. Live settings, read per unit, so switching it
+// off mid-run takes effect on the next video. Never fails the unit: the
+// capture succeeded whatever happens here.
+async function cleanAfterCapture(
+ run: OperationRun,
+ unit: OperationUnit,
+ videoDir: string,
+ report: OperationUnitReport,
+ log: (m: string) => void,
+ signal: AbortSignal,
+): Promise<void> {
+ if (!getSettings().diarization.cleanAfterCapture) return;
+ try {
+ if (!hasVoiceprints(await loadDiarization(videoDir))) {
+ log(`Kept ${unit.videoId}'s audio: its diarization has no voice fingerprints yet.`);
+ return;
+ }
+ const out = await cleanAudioForVideo({
+ channelSlug: unit.channelSlug,
+ paths: run.paths,
+ videoId: unit.videoId,
+ onLog: log,
+ signal,
+ });
+ if (out.outcome !== "cleaned") return;
+ report.audioCleaned = 1;
+ report.audioFreedBytes = out.bytesFreed;
+ await recordSpeakersFreed(run.paths, out.bytesFreed);
+ log(`Freed ${formatBytes(out.bytesFreed)} of audio from ${unit.videoId} (speakers captured).`);
+ } catch (err) {
+ log(`Clean after capture for ${unit.videoId} failed: ${(err as Error)?.message ?? String(err)}`);
+ }
+}
+
// The work itself: a tagged remote executor when one is free, else the llm
// fan-out for the call-bound operations, else the local run.
//
@@ -1511,6 +1567,9 @@ export type OperationBatchResult = {
reacquireHandedOff: number;
reacquireFailed: number;
diskFloorHit: boolean;
+ // Clean-after-capture: videos whose audio was removed, and the bytes.
+ audioCleaned: number;
+ audioFreedBytes: number;
// Digest: mirrors that received the canonical member's digest, and mirrors
// the alignment gate refused. A refusal is a normal outcome, not an error.
shared: number;
@@ -1541,6 +1600,8 @@ export function emptyOperationBatchResult(): OperationBatchResult {
reacquireHandedOff: 0,
reacquireFailed: 0,
diskFloorHit: false,
+ audioCleaned: 0,
+ audioFreedBytes: 0,
shared: 0,
misaligned: 0,
engineCalls: 0,
@@ -1939,6 +2000,9 @@ export async function runOperationBatch(
function laneOrderFor(run: OperationRun): AutoQueueOrder {
const order = run.settings.autoQueue[run.digest ? "digest" : "backfill"].order;
if (order === "cheapest") return run.digest ? "newest" : "listed";
+ // "space" orders ACROSS channels (corpus disk first); one channel's run has
+ // one disk, so it keeps the listed order.
+ if (order === "space") return "listed";
return order ?? "listed";
}
@@ -2028,6 +2092,8 @@ function foldUnitReport(
result.reacquireCleaned += report.reacquireCleaned;
result.reacquireHandedOff += report.reacquireHandedOff;
result.reacquireFailed += report.reacquireFailed;
+ result.audioCleaned += report.audioCleaned;
+ result.audioFreedBytes += report.audioFreedBytes;
if (report.diskFloorHit) result.diskFloorHit = true;
switch (report.outcome) {
case "done":
diff --git a/common/controller/operationJobs.ts b/common/controller/operationJobs.ts
@@ -25,6 +25,7 @@
// without this module knowing Next exists. The digest runner already had one.
import type { Paths } from "../lib/paths";
+import { formatBytes } from "../lib/format";
import { getSettings } from "../lib/settings";
import {
runManagedFunction,
@@ -143,6 +144,9 @@ export async function runBackfillChannelJob(
? `, ${batch.reacquireHandedOff} handed to auto-transcribe`
: "")
: "") +
+ (batch.audioCleaned > 0
+ ? `; freed ${formatBytes(batch.audioFreedBytes)} of audio from ${batch.audioCleaned} video(s) after capture`
+ : "") +
(batch.diskFloorHit ? " (stopped re-acquiring at the disk floor)" : "") +
(batch.stoppedForRelocation
? " (stopped: a relocation is in flight)"
diff --git a/common/controller/quickAvailabilityCheck.ts b/common/controller/quickAvailabilityCheck.ts
@@ -9,6 +9,7 @@ import {
seedRosterIfAbsent,
} from "./rosterStore";
import type { Paths } from "../lib/paths";
+import { writeAvailabilityVerdict } from "./availabilityVerdict";
// The record itself lives in the dependency-free ./maybeMissingStore so
// runYtdlp's full sweep can write it too (this module imports runYtdlp, so the
@@ -102,11 +103,15 @@ export async function runQuickAvailabilityCheck({
const maybeMissing = diffMaybeMissing(knownIds, freshIds);
+ const checkedAt = new Date().toISOString();
await writeMaybeMissing(paths, channelSlug, {
- checkedAt: new Date().toISOString(),
+ checkedAt,
freshPlaylistCount: freshIds.size,
ids: maybeMissing,
});
+ // What the listing NAMED, for clean-after-capture's verdict cache (an id is
+ // safe to clean only while a fresh listing names it).
+ await writeAvailabilityVerdict(paths, channelSlug, { checkedAt, ids: freshIds });
log(
`Quick availability: ${knownIds.length} known, ${freshIds.size} in fresh playlist, ${maybeMissing.length} maybe-missing.`,
diff --git a/common/controller/recencyIndex.ts b/common/controller/recencyIndex.ts
@@ -569,7 +569,7 @@ export function makeRecencyComparator(
keys: ReadonlyMap<string, RecencyKey>,
order: AutoQueueOrder,
): ((a: string, b: string) => number) | null {
- if (order === "listed" || order === "cheapest") return null;
+ if (order === "listed" || order === "cheapest" || order === "space") return null;
// Keys are YYYYMMDD strings, so lexicographic order IS chronological order.
// "newest" therefore sorts DESCENDING: a smaller (older) key must come later,
// which is a positive comparator result.
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/reportRefresh.ts b/common/controller/reportRefresh.ts
@@ -304,7 +304,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) => {
diff --git a/common/controller/speakersReadout.test.ts b/common/controller/speakersReadout.test.ts
@@ -0,0 +1,81 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { buildSpeakersReadout } from "./speakersReadout";
+import { emptySpeakersLedger } from "../lib/speakersLedger-server";
+import { speakersReadoutLine } from "../lib/speakersReadout";
+import { emptyHeldAudio, emptySpeakersWork } from "./channelSnapshot";
+
+const GB = 1024 ** 3;
+
+function brief(slug: string, o: {
+ external?: boolean;
+ awaitingBytes: number;
+ awaitingVideos: number;
+ neverBytes?: number;
+ neverVideos?: number;
+ workSeconds?: number;
+ unmeasured?: number;
+ engineMs?: number;
+ engineAudioSeconds?: number;
+ measured?: number;
+ speakers?: boolean;
+}) {
+ const heldAudioBytes = { ...emptyHeldAudio(), awaitingDiarization: o.awaitingBytes, diarizationNeverClears: o.neverBytes ?? 0 };
+ const heldAudioCounts = { ...emptyHeldAudio(), awaitingDiarization: o.awaitingVideos, diarizationNeverClears: o.neverVideos ?? 0 };
+ return {
+ slug,
+ config: (o.external ? { mediaDir: "/mnt/x" } : {}) as never,
+ snapshot: {
+ heldAudioBytes,
+ heldAudioCounts,
+ ...(o.speakers === false
+ ? {}
+ : {
+ speakers: {
+ ...emptySpeakersWork(),
+ workSeconds: o.workSeconds ?? 0,
+ workUnmeasured: o.unmeasured ?? 0,
+ engineMs: o.engineMs ?? 0,
+ engineAudioSeconds: o.engineAudioSeconds ?? 0,
+ measured: o.measured ?? 0,
+ },
+ }),
+ } as never,
+ };
+}
+
+test("the readout: waiting is the hold the lane WILL clear; rate from the sidecars; days at concurrency 1", () => {
+ const r = buildSpeakersReadout(
+ [
+ // 10 GB held, 2 GB of it never clears; 9 h of work measured, 1 video unmeasured.
+ brief("ext", { external: true, awaitingBytes: 10 * GB, awaitingVideos: 10, neverBytes: 2 * GB, neverVideos: 2, workSeconds: 7 * 3600, unmeasured: 1 }),
+ brief("int", { awaitingBytes: 1 * GB, awaitingVideos: 2, workSeconds: 2 * 3600, engineMs: 600_000, engineAudioSeconds: 3600, measured: 4 }),
+ brief("old", { awaitingBytes: GB, awaitingVideos: 1, speakers: false }),
+ ],
+ { ...emptySpeakersLedger(), freedBytes: 3 * GB, freedVideos: 5, startedAt: "2026-11-11T00:00:00.000Z" },
+ );
+ assert.equal(r.waitingBytes, 10 * GB);
+ assert.equal(r.waitingVideos, 11);
+ assert.equal(r.neverClearsVideos, 2);
+ assert.equal(r.secondsPerAudioHour, 600);
+ assert.equal(r.unmeasuredVideos, 1);
+ // 9 measured hours; the unmeasured video is estimated at the measured mean.
+ assert.ok(r.remainingAudioHours > 9 && r.remainingAudioHours < 11);
+ assert.equal(r.etaDays, Math.round(((r.remainingAudioHours * 600) / 86400) * 10) / 10);
+ assert.equal(r.staleSnapshots, 1);
+ // Corpus disk first.
+ assert.deepEqual(r.channels.map((c) => c.slug), ["int", "old", "ext"]);
+ assert.equal(r.freedBytes, 3 * GB);
+ assert.equal(
+ speakersReadoutLine(r),
+ `waiting: 10.00 GB in 11 videos · freed this run: 3.00 GB · about ${r.etaDays! < 1 ? "under a day" : `${r.etaDays} day${r.etaDays === 1 ? "" : "s"}`} left`,
+ );
+});
+
+test("the readout line with nothing measured and nothing waiting", () => {
+ const unmeasured = buildSpeakersReadout([brief("a", { awaitingBytes: GB, awaitingVideos: 1, workSeconds: 3600 })], emptySpeakersLedger());
+ assert.equal(unmeasured.etaDays, null);
+ assert.match(speakersReadoutLine(unmeasured), /time left not yet measured$/);
+ const none = buildSpeakersReadout([], emptySpeakersLedger());
+ assert.equal(speakersReadoutLine(none), "waiting: 0 B in 0 videos · freed this run: 0 B · nothing left");
+});
diff --git a/common/controller/speakersReadout.ts b/common/controller/speakersReadout.ts
@@ -0,0 +1,104 @@
+// The speakers readout, built (lib/speakersReadout.ts has the types and the
+// line). Everything comes from what is already on disk and cheap: each
+// channel's snapshot (heldAudioBytes / heldAudioCounts for the hold, the
+// `speakers` block for work seconds and the measured engine rate) and the
+// ledger for "freed this run". No per-video read here: the snapshot paid for
+// those when it was regenerated.
+
+import type { Paths } from "../lib/paths";
+import type { ChannelBrief } from "./channels";
+import { listChannelBriefs } from "./channels";
+import { readSpeakersLedger, type SpeakersLedger } from "../lib/speakersLedger-server";
+import type { SpeakersChannelRow, SpeakersReadout } from "../lib/speakersReadout";
+
+// PURE: the readout for these briefs and this ledger.
+export function buildSpeakersReadout(
+ briefs: ReadonlyArray<Pick<ChannelBrief, "slug" | "config" | "snapshot">>,
+ ledger: SpeakersLedger,
+): SpeakersReadout {
+ const channels: SpeakersChannelRow[] = [];
+ let engineMs = 0;
+ let engineAudioSeconds = 0;
+ let measured = 0;
+ let staleSnapshots = 0;
+ for (const b of briefs) {
+ const snap = b.snapshot;
+ const held = snap?.heldAudioBytes;
+ const count = snap?.heldAudioCounts;
+ const work = snap?.speakers;
+ if (!snap || !held || !count) continue;
+ if (!work) staleSnapshots++;
+ if (work) {
+ engineMs += work.engineMs;
+ engineAudioSeconds += work.engineAudioSeconds;
+ measured += work.measured;
+ }
+ const row: SpeakersChannelRow = {
+ slug: b.slug,
+ external: !!b.config?.mediaDir || !!b.config?.dataDir,
+ waitingBytes: Math.max(0, held.awaitingDiarization - held.diarizationNeverClears),
+ waitingVideos: Math.max(0, count.awaitingDiarization - count.diarizationNeverClears),
+ neverClearsBytes: held.diarizationNeverClears,
+ neverClearsVideos: count.diarizationNeverClears,
+ remainingAudioHours: (work?.workSeconds ?? 0) / 3600,
+ unmeasuredVideos: work?.workUnmeasured ?? 0,
+ voiceprinted: work?.voiceprinted ?? 0,
+ noFingerprintPossible: work?.noFingerprintPossible ?? 0,
+ };
+ if (
+ row.waitingVideos > 0 ||
+ row.neverClearsVideos > 0 ||
+ row.voiceprinted > 0 ||
+ row.noFingerprintPossible > 0
+ ) {
+ channels.push(row);
+ }
+ }
+ // The lane's own order: corpus disk first, then the biggest hold.
+ channels.sort(
+ (a, b) =>
+ Number(a.external) - Number(b.external) ||
+ b.waitingBytes - a.waitingBytes ||
+ a.slug.localeCompare(b.slug),
+ );
+ const sum = (f: (r: SpeakersChannelRow) => number) => channels.reduce((s, r) => s + f(r), 0);
+ const waitingVideos = sum((r) => r.waitingVideos);
+ const unmeasuredVideos = sum((r) => r.unmeasuredVideos);
+ const measuredHours = sum((r) => r.remainingAudioHours);
+ const measuredVideos = waitingVideos - unmeasuredVideos;
+ const meanHours = measuredVideos > 0 ? measuredHours / measuredVideos : 0;
+ const remainingAudioHours = measuredHours + unmeasuredVideos * meanHours;
+ const secondsPerAudioHour =
+ measured > 0 && engineAudioSeconds > 0 ? engineMs / 1000 / (engineAudioSeconds / 3600) : null;
+ const etaDays =
+ secondsPerAudioHour === null ? null : (remainingAudioHours * secondsPerAudioHour) / 86_400;
+ return {
+ waitingBytes: sum((r) => r.waitingBytes),
+ waitingVideos,
+ neverClearsBytes: sum((r) => r.neverClearsBytes),
+ neverClearsVideos: sum((r) => r.neverClearsVideos),
+ freedBytes: ledger.freedBytes,
+ freedVideos: ledger.freedVideos,
+ runStartedAt: ledger.startedAt,
+ secondsPerAudioHour: secondsPerAudioHour === null ? null : Math.round(secondsPerAudioHour),
+ measured,
+ remainingAudioHours: Math.round(remainingAudioHours * 10) / 10,
+ unmeasuredVideos,
+ etaDays: etaDays === null ? null : Math.round(etaDays * 10) / 10,
+ voiceprinted: sum((r) => r.voiceprinted),
+ noFingerprintPossible: sum((r) => r.noFingerprintPossible),
+ staleSnapshots,
+ channels,
+ };
+}
+
+export async function loadSpeakersReadout(
+ paths: Paths,
+ briefs?: ReadonlyArray<Pick<ChannelBrief, "slug" | "config" | "snapshot">>,
+): Promise<SpeakersReadout> {
+ const [list, ledger] = await Promise.all([
+ briefs ? Promise.resolve(briefs) : listChannelBriefs(paths),
+ readSpeakersLedger(paths),
+ ]);
+ return buildSpeakersReadout(list, ledger);
+}
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/jobs/autoQueuePolicy.test.ts b/common/jobs/autoQueuePolicy.test.ts
@@ -1440,3 +1440,14 @@ test("bucketIdsFrom knows undownloadedIds is a TOP-LEVEL field", () => {
assert.deepEqual([...bucketIdsFrom({}, "partialDownloads")], []);
assert.deepEqual([...bucketIdsFrom({}, "undownloadedIds")], []);
});
+
+test("sanitize: order \"space\" is kept; a lane's `operations` narrowing is kept, deduped and trimmed, and absent when empty", () => {
+ const s = sanitizeAutoQueue({
+ backfill: { enabled: true, order: "space", operations: [" diarization ", "diarization", 3, ""] },
+ digest: { enabled: true, operations: [] },
+ });
+ assert.equal(s.backfill.order, "space");
+ assert.deepEqual(s.backfill.operations, ["diarization"]);
+ assert.equal("operations" in s.digest, false);
+ assert.equal("operations" in s.transcription, false);
+});
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/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/audioIntegrity.ts b/common/lib/audioIntegrity.ts
@@ -51,8 +51,9 @@ export type AudioIntegrityRecord = {
verdict: AudioIntegrityVerdict;
// What measured it: the scan's own version and ffmpeg's `-version` line.
tool: { scan: string; ffmpeg?: string };
- // Who wrote it: the audit job, or the refetch that replaced the file.
- by: "audit" | "refetch";
+ // Who wrote it: the audit job, the refetch that replaced the file, or the
+ // speakers lane after its engine could not decode the file (diarizeOne).
+ by: "audit" | "refetch" | "speakers";
jobId?: string;
};
diff --git a/common/lib/autoQueueSchema.ts b/common/lib/autoQueueSchema.ts
@@ -48,6 +48,7 @@ export const AUTO_QUEUE_ORDERS: ReadonlyArray<AutoQueueOrder> = [
"newest",
"oldest",
"cheapest",
+ "space",
];
@@ -58,7 +59,10 @@ export const AUTO_QUEUE_ORDERS: ReadonlyArray<AutoQueueOrder> = [
// slice 1.3 folded digest.recencyOrder and backfill.order into them — and copies
// of this line would eventually disagree about what an absent field means.
export function sanitizeAutoQueueOrder(value: unknown): AutoQueueOrder {
- return value === "newest" || value === "oldest" || value === "cheapest"
+ return value === "newest" ||
+ value === "oldest" ||
+ value === "cheapest" ||
+ value === "space"
? value
: "listed";
}
@@ -267,6 +271,9 @@ function sanitizePolicy(value: unknown, lane: AutoQueueKind): AutoQueuePolicy {
// reading those fields gave a file that named no gate — free everywhere
// except backfill, whose field was inverted and defaulted to held.
held: typeof r.held === "boolean" ? r.held : defaultHeldFor(lane),
+ // Written only when it narrows: an absent key is every policy on disk
+ // today, and a default that wrote `[]` would change their bytes for nothing.
+ ...sanitizeLaneOperations(r.operations),
root:
r.root === undefined
? defaultRootFor(lane)
@@ -274,6 +281,19 @@ function sanitizePolicy(value: unknown, lane: AutoQueueKind): AutoQueuePolicy {
};
}
+function sanitizeLaneOperations(value: unknown): { operations?: string[] } {
+ if (!Array.isArray(value)) return {};
+ const ids = [
+ ...new Set(
+ value
+ .filter((v): v is string => typeof v === "string")
+ .map((v) => v.trim())
+ .filter(Boolean),
+ ),
+ ];
+ return ids.length > 0 ? { operations: ids } : {};
+}
+
export function sanitizeAutoQueue(value: unknown): AutoQueueSettings {
if (!value || typeof value !== "object") return defaultAutoQueue();
const r = value as Record<string, unknown>;
diff --git a/common/lib/autoQueueTypes.ts b/common/lib/autoQueueTypes.ts
@@ -33,7 +33,12 @@ export type AutoQueueMatchType = "channel" | "platform" | "all";
// SUPPLIED BY THE RUNNER (the engine never reads a duration off disk). A lane
// whose runner supplies no comparator for it falls back to today's order —
// which is what makes it safe to name here before anything computes it.
-export type AutoQueueOrder = "listed" | "newest" | "oldest" | "cheapest";
+//
+// "space" is the Speakers lane's free-the-disk order: channels whose media is
+// on the corpus disk (no `mediaDir`) first, then the videos holding the most
+// audio bytes per audio-hour of work — the space each hour of CPU frees.
+// Supplied by the runner for the backfill lane only; elsewhere it is "listed".
+export type AutoQueueOrder = "listed" | "newest" | "oldest" | "cheapest" | "space";
// Each field is documented in AUTO_QUEUE_MATCH_FIELD_DOCS below (rendered into SETTINGS.md).
export type AutoQueueMatch = {
@@ -128,6 +133,7 @@ export type AutoQueuePolicy = {
order?: AutoQueueOrder;
snoozeUntil?: number | null;
held?: boolean;
+ operations?: string[];
root: AutoQueueGroup;
};
@@ -176,6 +182,15 @@ export const AUTO_QUEUE_POLICY_FIELD_DOCS: FieldDocs<AutoQueuePolicy> = {
"It stays optional because a reader may be handed a PARTIAL settings " +
"object (laneGuards.test.ts casts one), and `isGateHeld` answers " +
"`false` for a lane that carries no key at all rather than throwing.",
+ operations:
+ "Narrow an OPERATION lane to these operation ids (e.g. [\"diarization\"] " +
+ "on the backfill lane: speakers only, no naming pass). Absent or empty = " +
+ "every enabled operation on the lane's queue, as before.\n\n" +
+ "On the POLICY rather than a leaf's `match.operation` because a channel-" +
+ "priority document compiles the lane's tree from its tiers and the stored " +
+ "leaves are not used while one exists; a lane-wide narrowing survives that " +
+ "and narrows the per-channel run, the counts and the runner alike " +
+ "(lib/operations.ts operationsForLane).",
root:
"The lane's rule tree: a group whose children are groups and leaves (see the node table). A missing root is the lane's default — empty for the runner lanes, one catch-all leaf for digest and backfill. While a channel-priority document exists, the four roots are compiled from it and not hand-edited.",
};
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";
@@ -245,6 +246,7 @@ export type ChannelConfig = {
lastFullSweepAt?: string;
excludeFromBuild?: boolean;
excludeFromCleanup?: boolean;
+ cleanAfterCaptureUnverified?: boolean;
syncIntervalMinutes?: number;
fullSweepIntervalMinutes?: number;
skipLiveDownloads?: boolean;
@@ -268,6 +270,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.
@@ -317,6 +321,8 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = {
excludeFromBuild: "Leave this channel out of every site build.",
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:
+ "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:
"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.",
fullSweepIntervalMinutes:
@@ -348,6 +354,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:
@@ -539,6 +547,7 @@ export const CHANNEL_CONFIG_COERCIONS: {
lastFullSweepAt: str,
excludeFromBuild: bool,
excludeFromCleanup: bool,
+ cleanAfterCaptureUnverified: bool,
syncIntervalMinutes: zeroOrClamped(SYNC_INTERVAL_MIN_MINUTES, SYNC_INTERVAL_MAX_MINUTES),
fullSweepIntervalMinutes: zeroOrClamped(
SYNC_INTERVAL_MIN_MINUTES,
@@ -561,6 +570,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, 42); // 2026-10-30: `skipShorts`
+ assert.equal(CHANNEL_CONFIG_KEYS.length, 44); // 2026-11-11: `cleanAfterCaptureUnverified`; lane/local-media: opt-in `localMedia`
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
@@ -69,6 +69,7 @@ export const channelConfigObjectSchema = z.object({
lastFullSweepAt: field("lastFullSweepAt"),
excludeFromBuild: field("excludeFromBuild"),
excludeFromCleanup: field("excludeFromCleanup"),
+ cleanAfterCaptureUnverified: field("cleanAfterCaptureUnverified"),
syncIntervalMinutes: field("syncIntervalMinutes"),
fullSweepIntervalMinutes: field("fullSweepIntervalMinutes"),
skipLiveDownloads: field("skipLiveDownloads"),
@@ -85,6 +86,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/diarization.test.ts b/common/lib/diarization.test.ts
@@ -7,6 +7,12 @@ import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";
import {
DIARIZATION_FILENAME,
diarizationSpeechSeconds,
+ diarizationTarget,
+ hasVoiceprints,
+ isDiarizationFresh,
+ VOICEPRINT_DIM,
+ voiceprintCount,
+ voiceprintsPossible,
type DiarizationRecord,
} from "./diarization";
import {
@@ -124,3 +130,82 @@ test("speech seconds sums turns, and overlapping turns are not clamped", () => {
});
assert.equal(diarizationSpeechSeconds(overlapping), 12);
});
+
+// ---- voiceprints ------------------------------------------------------------
+
+const REAL = Array.from({ length: VOICEPRINT_DIM }, (_, i) => (i === 0 ? 1 : 0));
+const vp = (speaker: number, centroid: number[] | null = REAL, embeddingModel = "titanet.onnx") => ({
+ speaker,
+ seconds: 4,
+ embedded: centroid ? 2 : 0,
+ centroid,
+ embeddingModel,
+});
+const withModel = (over: Partial<DiarizationRecord>) =>
+ record({ engine: { engine: "sherpa-onnx", embeddingModel: "titanet.onnx", threshold: 0.9 }, ...over });
+
+test("hasVoiceprints: every embeddable speaker has a REAL centroid (192 finite numbers, the record's model)", () => {
+ assert.equal(hasVoiceprints(null), false);
+ assert.equal(hasVoiceprints(record()), false, "a sidecar from before voiceprints has none");
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0)] })), false, "speaker 1 is missing");
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0), vp(1)] })), true);
+ // Both speakers have turns of 4 s and 6 s: a null is a fingerprint not made.
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0), vp(1, null)] })), false);
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0, null), vp(1, null)] })), false, "all null, from audio that decoded");
+ assert.equal(voiceprintCount(withModel({ voiceprints: [vp(0), vp(1, null)] })), 1);
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0), vp(1, [0.6, 0.8])] })), false, "not 192 floats");
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0), vp(1, REAL.map((x, i) => (i === 5 ? Number.NaN : x)))] })), false);
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0), vp(1, REAL, "other.onnx")] })), false, "another embedding model");
+ assert.equal(
+ hasVoiceprints(withModel({ voiceprints: [vp(0), { speaker: 1, seconds: 1, centroid: REAL } as never] })),
+ false,
+ "no embeddingModel",
+ );
+ // A null IS allowed for a speaker with no turn long enough to embed.
+ const blip = withModel({
+ turns: [
+ { start: 0, end: 4, speaker: 0 },
+ { start: 4, end: 4.3, speaker: 1 },
+ ],
+ voiceprints: [vp(0), vp(1, null)],
+ });
+ assert.equal(hasVoiceprints(blip), true);
+ assert.equal(voiceprintsPossible(blip), true);
+ // Zero turns, or none long enough: nothing was fingerprinted — not complete.
+ assert.equal(hasVoiceprints(withModel({ turns: [], speakers: 0, voiceprints: [] })), false);
+ const short = withModel({ turns: [{ start: 0, end: 0.3, speaker: 0 }], voiceprints: [vp(0, null)] });
+ assert.equal(hasVoiceprints(short), false);
+ assert.equal(voiceprintsPossible(short), false);
+});
+
+test("hasVoiceprints with no model on the record: each voiceprint names one, and they all agree", () => {
+ const noModel = (voiceprints: unknown[]) =>
+ record({ engine: { engine: "sortformer", model: "sf.gguf" }, voiceprints: voiceprints as never });
+ assert.equal(hasVoiceprints(noModel([vp(0, REAL, "titanet.onnx"), vp(1, REAL, "titanet.onnx")])), true);
+ assert.equal(hasVoiceprints(noModel([vp(0, REAL, "titanet.onnx"), vp(1, REAL, "ecapa.onnx")])), false, "two models");
+ assert.equal(hasVoiceprints(noModel([vp(0, REAL, "titanet.onnx"), vp(1, REAL, "")])), false, "an empty model");
+ assert.equal(
+ hasVoiceprints(noModel([vp(0, REAL, "titanet.onnx"), { speaker: 1, seconds: 4, centroid: REAL }])),
+ false,
+ "a missing model",
+ );
+});
+
+test("voiceprints are outside the freshness identity: a sidecar without them is not stale", () => {
+ const target = diarizationTarget({ segModel: "/m/model.onnx", embModel: "/m/titanet.onnx", threshold: 0.9 });
+ const engine = { engine: "sherpa-onnx", segmentationModel: "model.onnx", embeddingModel: "titanet.onnx", threshold: 0.9 };
+ assert.equal(isDiarizationFresh(record({ engine }), target), true);
+ assert.equal(isDiarizationFresh(record({ engine, voiceprints: [vp(0, REAL, "titanet.onnx"), vp(1)], voiceprintsAt: "2026-11-11T00:00:00.000Z" }), target), true);
+});
+
+test("a sidecar with voiceprints round-trips through the writer and the coercer", async () => {
+ const dir = await tmpDir();
+ try {
+ await writeDiarization(dir, withModel({ voiceprints: [vp(0), vp(1)] }));
+ const loaded = await loadDiarization(dir);
+ assert.equal(hasVoiceprints(loaded), true);
+ assert.deepEqual(loaded?.voiceprints?.[0].centroid, REAL);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/lib/diarization.ts b/common/lib/diarization.ts
@@ -78,8 +78,136 @@ export type DiarizationRecord = {
windowSeconds: number;
overlapSeconds: number;
};
+ // One voice fingerprint per speaker cluster: the TitaNet embedding the
+ // diarizer clustered with, kept rather than discarded (scripts/
+ // diarize-sherpa.py). It is the ONE part of a diarization that cannot be
+ // recomputed once the audio is gone, so the cleanup gate waits for it
+ // (hasVoiceprints) before deleting the audio.
+ //
+ // OUTSIDE `engine` AND OUTSIDE THE FRESHNESS IDENTITY, exactly as `windowing`
+ // is: a sidecar written before voiceprints existed is not stale — its turns
+ // are what the engine produces today — it is only without them, and the
+ // voiceprint step (diarizeOne's voiceprintOneVideo) adds them from the same
+ // turns without re-clustering and without touching `generatedAt` (which
+ // attribution-diarized's freshness names).
+ voiceprints?: DiarizationVoiceprint[];
+ // ISO 8601, when the voiceprints were computed. Equal to (about) generatedAt
+ // for a sidecar that was written with them; later for one that got them from
+ // the voiceprint step.
+ voiceprintsAt?: string;
+ // The file the fingerprints were cut from (basename, size, duration). The
+ // voiceprint step only ever uses the video's own extracted audio — never a
+ // source container or a saved video, whose clock can differ (review B3).
+ voiceprintsFrom?: { file: string; bytes?: number; durationSeconds?: number };
+ // The voiceprint step REFUSED this audio file (scripts/diarize-sherpa.py
+ // exit 6: its duration is not the record's, an excerpt came back short, or a
+ // speaker with long turns got no embedding). Keyed to the file as it was
+ // (name, size, floored mtime): while that file is the one on disk, no
+ // fingerprint is possible from it, and the diarization operation reports the
+ // video blocked rather than retrying it every runner session. A different
+ // file (a re-download) is work again. The audio stays held either way.
+ voiceprintsRefused?: { file: string; size: number; mtime: number; reason: string; at: string };
+};
+
+// PURE: does this refusal still speak for the file on disk?
+export function voiceprintsRefusedFor(
+ record: Pick<DiarizationRecord, "voiceprintsRefused"> | null,
+ file: { name: string; size: number; mtime: number },
+): boolean {
+ const r = record?.voiceprintsRefused;
+ return !!r && r.file === file.name && r.size === file.size && r.mtime === Math.floor(file.mtime);
+}
+
+// A speaker cluster's voice fingerprint. `centroid` is the L2-normalised mean
+// TitaNet-small embedding (VOICEPRINT_DIM floats, rounded to 4 decimals) of the
+// speaker's longest turns, outliers trimmed as voiceMatch's robustCentroid does;
+// null when none of the speaker's turns were long enough to embed — a recorded
+// "nothing to fingerprint", not a missing one.
+export type DiarizationVoiceprint = {
+ speaker: number;
+ // Talk time of this cluster in the record's turns.
+ seconds: number;
+ // How many excerpts the centroid was made from (0 with a null centroid).
+ embedded?: number;
+ centroid: number[] | null;
+ // Basename of the embedding model, so a comparison never mixes models.
+ embeddingModel: string;
};
+export const VOICEPRINT_DIM = 192;
+
+// The shortest turn the embedder is given (scripts/diarize-sherpa.py
+// EMB_MIN_SEC). A speaker with a turn at least this long CAN be fingerprinted,
+// so a null centroid for one is a fingerprint that was not made.
+export const VOICEPRINT_MIN_SPAN_SEC = 0.5;
+
+function isRealCentroid(c: unknown): c is number[] {
+ return (
+ Array.isArray(c) &&
+ c.length === VOICEPRINT_DIM &&
+ c.every((x) => typeof x === "number" && Number.isFinite(x))
+ );
+}
+
+// Speakers with at least one turn long enough to embed.
+function embeddableSpeakers(record: Pick<DiarizationRecord, "turns">): Set<number> {
+ const out = new Set<number>();
+ for (const t of record.turns ?? []) {
+ if (t.end - t.start >= VOICEPRINT_MIN_SPAN_SEC) out.add(t.speaker);
+ }
+ return out;
+}
+
+// Could this record's turns be fingerprinted at all? False for a record with no
+// turns, or none long enough to embed — "no fingerprint possible" from these
+// turns, which nothing the lane does will change.
+export function voiceprintsPossible(record: Pick<DiarizationRecord, "turns"> | null): boolean {
+ return !!record && embeddableSpeakers(record).size > 0;
+}
+
+// Has this record's voice capture REALLY been done (review B3)? True only when
+// every speaker its turns name has an entry, and every speaker with a turn of at
+// least VOICEPRINT_MIN_SPAN_SEC has a centroid of exactly VOICEPRINT_DIM finite
+// numbers made by the record's embedding model (null is allowed only for a
+// speaker with no turn that long). A record with no turns, or no speaker long
+// enough to embed, is NOT complete: nothing was fingerprinted, and this is the
+// predicate the cleanup gate keys off — anything short of a real fingerprint
+// keeps the only audio one could still be made from.
+export function hasVoiceprints(
+ record: Pick<DiarizationRecord, "turns" | "voiceprints" | "engine"> | null,
+): boolean {
+ if (!record || !Array.isArray(record.voiceprints)) return false;
+ if (!(record.turns ?? []).length) return false;
+ const embeddable = embeddableSpeakers(record);
+ if (embeddable.size === 0) return false;
+ const model = record.engine?.embeddingModel;
+ const bySpeaker = new Map<number, DiarizationVoiceprint>();
+ for (const v of record.voiceprints) {
+ if (!v || typeof v !== "object" || !Number.isInteger(v.speaker)) return false;
+ if (typeof v.embeddingModel !== "string" || !v.embeddingModel) return false;
+ if (model && v.embeddingModel !== model) return false;
+ bySpeaker.set(v.speaker, v);
+ }
+ // With no model on the record (a sortformer record, an engine replacement),
+ // the voiceprints still say which model made them, and they must all say the
+ // same one: a cosine between two models' vectors means nothing.
+ if (new Set(record.voiceprints.map((v) => v.embeddingModel)).size > 1) return false;
+ for (const t of record.turns) if (!bySpeaker.has(t.speaker)) return false;
+ for (const [speaker, v] of bySpeaker) {
+ if (embeddable.has(speaker) ? !isRealCentroid(v.centroid) : v.centroid !== null && !isRealCentroid(v.centroid)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+// How many clusters carry an actual centroid.
+export function voiceprintCount(
+ record: Pick<DiarizationRecord, "voiceprints"> | null,
+): number {
+ return (record?.voiceprints ?? []).filter((v) => isRealCentroid(v?.centroid)).length;
+}
+
export const DIARIZATION_FILENAME = "diarization.json";
// The engine id scripts/diarize.mjs records when it runs its own default
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
@@ -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/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/operations.test.ts b/common/lib/operations.test.ts
@@ -2,7 +2,8 @@ import { test } from "node:test";
import assert from "node:assert/strict";
import path from "node:path";
import os from "node:os";
-import { mkdtemp, mkdir, writeFile, rm, utimes } from "node:fs/promises";
+import { mkdtemp, mkdir, writeFile, rm, stat, utimes } from "node:fs/promises";
+import { AUDIO_INTEGRITY_FILENAME } from "./audioIntegrity";
import {
getOperation,
allOperations,
@@ -119,6 +120,8 @@ async function fixture(opts: {
// Written into metadata.info.json. Absent means NO metadata file at all,
// which is the "duration unknown" case the cap has to get right.
durationSec?: number;
+ // An audio-integrity.json verdict on audio.mp3.
+ integrity?: "undecodable" | "clean";
}): Promise<{ dir: string; cleanup: () => Promise<void> }> {
const root = await mkdtemp(path.join(os.tmpdir(), "backfill-kinds-"));
const dir = path.join(root, "vid1");
@@ -150,16 +153,41 @@ async function fixture(opts: {
JSON.stringify({ id: "vid1", duration: opts.durationSec }),
);
}
+ if (opts.integrity) {
+ // A verdict ON audio.mp3 as it is on disk (its size and mtime).
+ const st = await stat(path.join(dir, "audio.mp3"));
+ await writeFile(
+ path.join(dir, AUDIO_INTEGRITY_FILENAME),
+ JSON.stringify({
+ version: 1, checkedAt: "now", file: "audio.mp3", size: st.size, mtime: Math.floor(st.mtimeMs),
+ durationSeconds: opts.integrity === "undecodable" ? null : 1,
+ decodedSeconds: opts.integrity === "undecodable" ? 0 : 1,
+ gaps: [], verdict: opts.integrity, tool: { scan: "x" }, by: "speakers",
+ }),
+ );
+ }
return { dir, cleanup: () => rm(root, { recursive: true, force: true }) };
}
-function sidecar(engine: DiarizationRecord["engine"]): string {
+// A COMPLETE record by default — turns and the voice fingerprints a sidecar is
+// written with today. `voiceprints: false` is one written before they existed.
+function sidecar(
+ engine: DiarizationRecord["engine"],
+ { voiceprints = true }: { voiceprints?: boolean } = {},
+): string {
return JSON.stringify({
videoId: "vid1",
generatedAt: "2026-08-07T00:00:00.000Z",
speakers: 2,
turns: [{ start: 0, end: 4, speaker: 0 }],
engine,
+ ...(voiceprints
+ ? {
+ voiceprints: [
+ { speaker: 0, seconds: 4, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "emb-1.onnx" },
+ ],
+ }
+ : {}),
} satisfies DiarizationRecord);
}
@@ -201,6 +229,77 @@ test("present: the sidecar matches the identity we would produce now", async ()
assert.equal(await classify({ sidecar: sidecar(CURRENT) }), "present");
});
+test("partial: fresh turns without voice fingerprints, while the audio is still here", async () => {
+ assert.equal(
+ await classify({ audio: true, sidecar: sidecar(CURRENT, { voiceprints: false }) }),
+ "partial",
+ );
+ // A persisted container is NOT: the voiceprint step cuts only the video's
+ // own audio (another file of the recording runs on another clock, review
+ // B3), so with only a container there is no fingerprint to be had.
+ assert.equal(
+ await classify({ container: true, sidecar: sidecar(CURRENT, { voiceprints: false }) }),
+ "present",
+ );
+});
+
+test("present: without fingerprints once the audio is gone — none is possible, and it is not work", async () => {
+ assert.equal(await classify({ sidecar: sidecar(CURRENT, { voiceprints: false }) }), "present");
+});
+
+test("present: without fingerprints when no embedding model is configured (a sortformer setup)", async () => {
+ assert.equal(
+ await classify(
+ { audio: true, sidecar: sidecar({ engine: "sortformer", model: "sf.gguf" }, { voiceprints: false }) },
+ settingsWithDiarization({ engine: "sortformer", sortformerModel: "/m/sf.gguf", embModel: "" }),
+ ),
+ "present",
+ );
+});
+
+test("blocked: held audio the engine could not decode is recorded and skipped, not offered every pass", async () => {
+ assert.equal(await classify({ audio: true, integrity: "undecodable" }), "blocked");
+ assert.equal(
+ await classify({ audio: true, integrity: "undecodable", sidecar: sidecar(CURRENT, { voiceprints: false }) }),
+ "present",
+ );
+ // A clean verdict changes nothing.
+ assert.equal(await classify({ audio: true, integrity: "clean" }), "missing");
+});
+
+test("the diarization unit ships an existing sidecar, so a unit executor can add its voiceprints", async () => {
+ const { dir, cleanup } = await fixture({ audio: true, sidecar: sidecar(CURRENT, { voiceprints: false }), durationSec: 9 });
+ try {
+ const files = await readVideoFiles(dir, { checkUntranscribable: true });
+ assert.deepEqual(diarization.inputs(files), [META_FILENAME, DIARIZATION_FILENAME, "audio.mp3"]);
+ } finally {
+ await cleanup();
+ }
+});
+
+test("blocked: the voiceprint step refused THIS audio file (exit 6); a different file is work again", async () => {
+ const { dir, cleanup } = await fixture({ audio: true });
+ try {
+ const st = await stat(path.join(dir, "audio.mp3"));
+ const refused = (size: number) =>
+ JSON.stringify({
+ ...JSON.parse(sidecar(CURRENT, { voiceprints: false })),
+ voiceprintsRefused: { file: "audio.mp3", size, mtime: Math.floor(st.mtimeMs), reason: "duration differs", at: "now" },
+ });
+ const settings = settingsWithDiarization();
+ const target = await diarization.resolveTarget(targetCtx(settings));
+ const classifyHere = async () =>
+ diarization.state({ videoDir: dir, videoId: "vid1", files: await readVideoFiles(dir, { checkUntranscribable: true }), target, settings });
+ await writeFile(path.join(dir, DIARIZATION_FILENAME), refused(st.size));
+ assert.equal(await classifyHere(), "blocked");
+ // The file on disk is another one now (a re-download): partial again.
+ await writeFile(path.join(dir, DIARIZATION_FILENAME), refused(st.size + 100));
+ assert.equal(await classifyHere(), "partial");
+ } finally {
+ await cleanup();
+ }
+});
+
test("stale: a different threshold or model is work, not coverage", async () => {
// The threshold is the single most consequential knob (it decides how many
// speakers come out), so a change to it MUST show as work. Before the
@@ -1671,3 +1770,19 @@ test("operationsForLane: digest stays on the digest lane on BOTH its queues", ()
// And the backfill lane never picks it up on either engine.
assert.deepEqual(operationsForLane("backfill", remote).map((o) => o.id), []);
});
+
+test("operationsForLane: autoQueue.backfill.operations narrows the lane — speakers only — and absent is everything", () => {
+ const s = settingsWithBackfillLane();
+ const all = operationsForLane("backfill", s).map((k) => k.id);
+ assert.ok(all.length > 1 && all.includes("diarization"));
+ const narrowed = {
+ ...s,
+ autoQueue: {
+ ...s.autoQueue,
+ backfill: { ...s.autoQueue.backfill, operations: ["diarization"] },
+ },
+ };
+ assert.deepEqual(operationsForLane("backfill", narrowed).map((k) => k.id), ["diarization"]);
+ const empty = { ...s, autoQueue: { ...s.autoQueue, backfill: { ...s.autoQueue.backfill, operations: [] } } };
+ assert.deepEqual(operationsForLane("backfill", empty).map((k) => k.id), all);
+});
diff --git a/common/lib/operations.ts b/common/lib/operations.ts
@@ -72,6 +72,8 @@
// because it is what keeps them apart if they are ever added: `inline` folds
// into an existing pass and `lane` gets the concurrent queue and the share.
+import path from "node:path";
+import { stat } from "node:fs/promises";
import type { Paths } from "./paths";
import type {
AttributionSettings,
@@ -106,13 +108,18 @@ import type { DigestContext } from "./digestContext-server";
import {
SORTFORMER_DIARIZATION_ENGINE,
diarizationTarget,
+ hasVoiceprints,
isDiarizationFresh,
+ voiceprintsPossible,
+ voiceprintsRefusedFor,
type DiarizationBackend,
type DiarizationEngineId,
type DiarizationFreshnessTarget,
type DiarizationRecord,
} from "./diarization";
import { loadDiarization, writeDiarization } from "./diarization-server";
+import { AUDIO_INTEGRITY_FILENAME } from "./audioIntegrity";
+import { heldAudioDamage } from "./audioIntegrity-server";
import {
ATTRIBUTION_FILENAME,
isAttributionDowngrade,
@@ -702,11 +709,39 @@ const diarization: Operation = {
// diarization-server.ts treats it: a half-written sidecar must never be
// what convinces anything the work is done.
if (record) {
- return isDiarizationFresh(record, target as DiarizationFreshnessTarget)
- ? "present"
- : "stale";
+ if (!isDiarizationFresh(record, target as DiarizationFreshnessTarget)) {
+ return "stale";
+ }
+ if (
+ hasVoiceprints(record) ||
+ !voiceprintsPossible(record) ||
+ !settings.diarization.embModel
+ ) {
+ return "present";
+ }
+ // Fresh turns WITHOUT voice fingerprints: PARTIAL while the video's own
+ // AUDIO is still here (diarizeOneVideo's voiceprint step adds them from
+ // the same turns, seconds of work — and only from that audio, never a
+ // container or a saved video, review B3); present once it is gone — no
+ // fingerprint is possible then, which the speakers readout lists, and
+ // nothing this lane can do about it.
+ if (files.audioFiles.length === 0) return "present";
+ // The voiceprint step refused this very file (exit 6, recorded on the
+ // sidecar): "no fingerprint possible from this file: <reason>" —
+ // blocked until a different file is there, not retried every session.
+ if (record.voiceprintsRefused) {
+ const name = pickPreferredAudio(files.audioFiles);
+ const st = name ? await stat(path.join(videoDir, name)).catch(() => null) : null;
+ if (name && st && voiceprintsRefusedFor(record, { name, size: st.size, mtime: st.mtimeMs })) {
+ return "blocked";
+ }
+ }
+ return (await heldAudioUndecodable(videoDir, files)) ? "present" : "partial";
}
}
+ // Audio this lane's engine could not decode, recorded against the file
+ // (audio-integrity.json): not work until a different file is there.
+ if (await heldAudioUndecodable(videoDir, files)) return "blocked";
if (!(await hasDiarizableInput(videoDir, files))) {
// Read the cap here ONLY when this branch can dispatch a download: with
// re-download armed, missing-input is a fetch, and diarizeOneVideo does not
@@ -760,6 +795,9 @@ const diarization: Operation = {
inputs(files) {
const out: string[] = [];
if (files.entries.includes(META_FILENAME)) out.push(META_FILENAME);
+ // The existing sidecar travels too: a fresh one without voiceprints is a
+ // voiceprint step (its own turns, re-embedded), not a re-diarization.
+ if (files.hasDiarization) out.push(DIARIZATION_FILENAME);
const audio =
pickPreferredAudio(files.audioFiles) ?? findSourceMedia(files.entries);
if (audio) out.push(audio);
@@ -786,6 +824,19 @@ async function hasDiarizableInput(
return (await resolveSavedVideo(videoDir)) !== null;
}
+// Is the audio diarization would read known to be undecodable? Answered from
+// the listing first: only a dir holding audio-integrity.json pays a read.
+async function heldAudioUndecodable(
+ videoDir: string,
+ files: VideoFiles,
+): Promise<boolean> {
+ if (!files.entries.includes(AUDIO_INTEGRITY_FILENAME)) return false;
+ const preferred = pickPreferredAudio(files.audioFiles);
+ if (!preferred) return false;
+ const damage = await heldAudioDamage(videoDir, files.entries);
+ return damage?.file === preferred && damage.record.verdict === "undecodable";
+}
+
// Is this video longer than the diarization duration cap?
//
// THE CAP IS OFF BY DEFAULT NOW — windowed diarization removed the OOM it
@@ -1636,6 +1687,17 @@ export function backfillLaneOperations(settings: SiteSettings): Operation[] {
);
}
+// The backfill lane's kinds AS IT DISPATCHES THEM: backfillLaneOperations with
+// the lane's `operations` narrowing (autoQueue.backfill.operations) applied —
+// what operationsForLane("backfill") runs, for the surfaces that name and count
+// the lane (the deck, the Speakers stage, the /channels sections). Asks no
+// laneFor, so a partial settings object is safe here.
+export function backfillLaneDispatchOperations(settings: SiteSettings): Operation[] {
+ const only = settings.autoQueue?.backfill?.operations;
+ const lane = backfillLaneOperations(settings);
+ return only && only.length > 0 ? lane.filter((k) => only.includes(k.id)) : lane;
+}
+
// The READ-SIDE twin of backfillLaneOperations: given a snapshot's per-kind map,
// return only the entries belonging to the shared backfill lane — KEYED, so a
// surface can say WHICH kind a number came from. backfillLaneEntriesOf below is this
@@ -1721,9 +1783,15 @@ export function operationsForLane(
? [BACKFILL_QUEUE]
: [];
if (keys.length === 0) return [];
+ // The lane-wide narrowing (autoQueue.<lane>.operations): the one place every
+ // dispatch path, count and per-channel run asks, so "speakers only" is one
+ // setting rather than a leaf the channel-priority compiler would discard.
+ const only = settings.autoQueue?.[lane]?.operations;
return orderByDependencies(
- allOperations(settings).filter((op) =>
- keys.includes((op.laneFor?.(settings) ?? op.lane).queueKey),
+ allOperations(settings).filter(
+ (op) =>
+ keys.includes((op.laneFor?.(settings) ?? op.lane).queueKey) &&
+ (!only || only.length === 0 || only.includes(op.id)),
),
);
}
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/renderPriority.mjs b/common/lib/renderPriority.mjs
@@ -14,7 +14,7 @@
// subprocesses: RENDER_PRIORITY_TOKEN) is admitted, with the floor 4000 MB
// and the cap 10240 MB unless HEAVY_MIN_FREE_MB / HEAVY_CAP_MB say
// otherwise;
-// - holds the editor's transcription and download lanes, remembering which
+// - holds the editor's transcription, download and Speakers lanes, remembering which
// ones IT held (`lanesHeld`), so ending it releases only those — a lane
// someone else held before stays held.
//
@@ -52,8 +52,9 @@ import { tmpPathFor } from "./atomicFile.mjs";
export const RENDER_PRIORITY_FLOOR_MB = 4000;
/** The render's heavy cap (MemoryMax) in render mode, absent HEAVY_CAP_MB. */
export const RENDER_PRIORITY_CAP_MB = 10240;
-/** The editor lanes render mode holds. */
-export const RENDER_MODE_LANES = Object.freeze(["transcription", "download"]);
+/** The editor lanes render mode holds: the GPU transcription lane, downloads, and
+ * the Speakers (backfill) lane — CPU diarization, ~4 cores, which a render wants. */
+export const RENDER_MODE_LANES = Object.freeze(["transcription", "download", "backfill"]);
/** A manual window with no --for ends after this. */
export const DEFAULT_RENDER_MODE_WINDOW_MS = 2 * 60 * 60 * 1000;
/** The env var a render (and everything under it) carries the hold's token in. */
diff --git a/common/lib/renderPriority.test.ts b/common/lib/renderPriority.test.ts
@@ -36,7 +36,9 @@ function tmpFile() {
}
/** A fake editor's lanes: `held` is what it holds; `calls` what was asked. */
-function fakeLanes(held: Record<string, boolean> = {}, { failRelease = false } = {}) {
+// The Speakers (backfill) lane starts held, as it ships.
+function fakeLanes(initial: Record<string, boolean> = {}, { failRelease = false } = {}) {
+ const held: Record<string, boolean> = { backfill: true, ...initial };
const calls: string[] = [];
const lanes: RenderModeLanes = {
async isHeld(lane) {
@@ -139,13 +141,15 @@ test("describeRenderPriority and parseDurationMs", () => {
test("on holds only the lanes not held already, and off releases only those", async () => {
const file = tmpFile();
- const ed = fakeLanes({ download: true }); // someone else's hold
+ // Someone else's hold on download; the Speakers (backfill) lane running —
+ // a render takes its cores too (RENDER_MODE_LANES).
+ const ed = fakeLanes({ download: true, backfill: false });
const on = await renderModeOn({ file, holder: { pid: process.pid, cmd: "umtool take p --id t", project: "p", take: "t" }, lanes: ed.lanes, editor: "http://localhost:3001" });
assert.equal(on.ok, true);
- assert.deepEqual(on.state?.lanesHeld, ["transcription"]);
+ assert.deepEqual(on.state?.lanesHeld, ["transcription", "backfill"]);
assert.deepEqual(on.state?.lanesSkipped, ["download"]);
assert.equal(on.state?.until, null); // a take's hold ends with its process
- assert.deepEqual(ed.calls, ["hold transcription"]);
+ assert.deepEqual(ed.calls, ["hold transcription", "hold backfill"]);
const onDisk = readRenderPriorityState(file);
assert.equal(onDisk?.token, on.state?.token);
assert.equal(readRenderPriority(file).held, true);
@@ -161,8 +165,8 @@ test("on holds only the lanes not held already, and off releases only those", as
assert.equal(existsSync(file), true);
const off = await renderModeOff({ file, token: on.state?.token, lanes: ed.lanes });
- assert.deepEqual(off.released, ["transcription"]);
- assert.deepEqual(ed.calls, ["hold transcription", "release transcription"]);
+ assert.deepEqual(off.released, ["transcription", "backfill"]);
+ assert.deepEqual(ed.calls, ["hold transcription", "hold backfill", "release transcription", "release backfill"]);
assert.equal(ed.held.download, true, "the hold it found stays");
assert.equal(existsSync(file), 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/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/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -333,6 +333,10 @@ export type DiarizationSettings = {
sortformerModel: string;
concurrency: number;
maxAudioHours: number;
+ cleanAfterCapture: boolean;
+ requireVoiceprints: boolean;
+ cleanVerdictMaxAgeHours: number;
+ cleanWholeRecordingAudio: boolean;
};
export const DIARIZATION_SETTINGS_FIELD_DOCS: FieldDocs<DiarizationSettings> = {
@@ -435,6 +439,44 @@ export const DIARIZATION_SETTINGS_FIELD_DOCS: FieldDocs<DiarizationSettings> = {
"lands: windowing divides per-window n by the window count, so the " +
"matrix falls by its square, and the cap stops being needed rather than" +
" being tuned.",
+ cleanAfterCapture:
+ "Delete a video's audio as soon as the Speakers lane has captured it.\n\n" +
+ "When ON, a diarization unit that finishes with a complete set of voice " +
+ "fingerprints (diarization.json `voiceprints`) is followed at once by the " +
+ "per-video half of Clean audio, with every one of its gates: a " +
+ "transcript.json, outside the keep-latest window, not marked do-not-clean, " +
+ "and the availability check (a video gone upstream is pinned, not " +
+ "deleted). The bytes freed are logged and counted in the speakers " +
+ "readout. OFF by default: nothing deletes audio until the operator says " +
+ "so.",
+ requireVoiceprints:
+ "Hold a video's audio until its diarization.json carries voice " +
+ "fingerprints.\n\n" +
+ "A fingerprint is the one part of a diarization that cannot be made " +
+ "again once the audio is gone, so with this ON (the default) Clean audio " +
+ "skips a diarized video whose sidecar has none, saying \"awaiting voice " +
+ "fingerprint\", and the Speakers lane adds them from the existing turns. " +
+ "Applies only while diarization is enabled, like the diarization guard " +
+ "itself.",
+ cleanVerdictMaxAgeHours:
+ "How old the channel's last listing may be for clean-after-capture to " +
+ "trust it.\n\n" +
+ "Clean after capture asks NOTHING of the network: it reads the channel's " +
+ "availability verdict (availability-verdict.json, written by the quick " +
+ "availability check) — a video named in a listing younger than this is " +
+ "cleaned, one not named is held (maybe missing). With no fresh listing the " +
+ "video is held and ONE quick check of the channel is queued on its " +
+ "platform's queue, at most once per this many hours, never while the " +
+ "platform is held. The manual Clean audio sweep keeps its own live check.",
+ cleanWholeRecordingAudio:
+ "Let clean-after-capture delete the audio of channels on " +
+ "`clips.wholeRecordingPlatforms` (Rumble by default).\n\n" +
+ "OFF by default, and the reason is the recording clock: on those " +
+ "platforms the cues are the transcription of audio.<ext>, and every clip " +
+ "is cut from another file of the recording through a time map fitted " +
+ "against that audio (common/lib/recordingClock.mjs). Deleting it as each " +
+ "video is captured leaves those recordings with no map to make later. " +
+ "The manual Clean audio sweep is unaffected.",
};
// Configuration for the derived-corpus digest layer. Local-first by decision:
@@ -1558,6 +1600,10 @@ export function defaultDiarization(): DiarizationSettings {
// stays honest about what it does, for a machine smaller than this one or a
// recording longer than anything measured here.
maxAudioHours: 0,
+ cleanAfterCapture: false,
+ requireVoiceprints: true,
+ cleanVerdictMaxAgeHours: 24,
+ cleanWholeRecordingAudio: false,
};
}
@@ -1600,6 +1646,16 @@ export function sanitizeDiarization(value: unknown): DiarizationSettings {
r.maxAudioHours >= 0
? r.maxAudioHours
: d.maxAudioHours,
+ cleanAfterCapture: r.cleanAfterCapture === true,
+ // ON unless explicitly switched off: the safe direction is to keep audio.
+ requireVoiceprints: r.requireVoiceprints !== false,
+ cleanVerdictMaxAgeHours:
+ typeof r.cleanVerdictMaxAgeHours === "number" &&
+ Number.isFinite(r.cleanVerdictMaxAgeHours) &&
+ r.cleanVerdictMaxAgeHours > 0
+ ? r.cleanVerdictMaxAgeHours
+ : d.cleanVerdictMaxAgeHours,
+ cleanWholeRecordingAudio: r.cleanWholeRecordingAudio === true,
};
}
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/spaceOrder.test.ts b/common/lib/spaceOrder.test.ts
@@ -0,0 +1,17 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { audioBytesPerHour, spaceComparator } from "./spaceOrder";
+
+test("space order: corpus-disk channels first, then the most bytes freed per audio-hour; unknown last; ties stable", () => {
+ const external = new Set(["x1", "x2"]);
+ const rate: Record<string, number | null> = { a: 10, b: 50, c: null, d: 50, x1: 900, x2: null };
+ const cmp = spaceComparator({ external: (id) => external.has(id), bytesPerHour: (id) => rate[id] ?? null });
+ assert.deepEqual(["c", "x1", "a", "b", "x2", "d"].sort(cmp), ["b", "d", "a", "c", "x1", "x2"]);
+});
+
+test("audioBytesPerHour: bytes over hours; nothing to say without both", () => {
+ assert.equal(audioBytesPerHour(3_600_000, 1800), 7_200_000);
+ assert.equal(audioBytesPerHour(0, 1800), null);
+ assert.equal(audioBytesPerHour(100, null), null);
+ assert.equal(audioBytesPerHour(100, 0), null);
+});
diff --git a/common/lib/spaceOrder.ts b/common/lib/spaceOrder.ts
@@ -0,0 +1,38 @@
+// The Speakers lane's "space" order (AutoQueueOrder): which video to capture
+// next so the disk frees fastest.
+//
+// Two keys, in this order:
+// 1. a channel whose media is on the CORPUS disk (no `mediaDir`) before one
+// whose media lives on another drive — the operator's ruling: internal
+// disk first, because that is the disk that fills;
+// 2. bytes of held audio per audio-hour, descending — the space one hour of
+// diarization CPU frees (the CPU cost is ~proportional to duration, the
+// space to the file's size).
+// A video whose rate is unknown (no duration on disk) sorts after every known
+// one within its disk class. Equal keys compare 0, so the sort is stable and
+// keeps the listed order between them.
+//
+// Pure: the runner (controller/autoRunner.ts recencyOrdering) supplies the two
+// lookups; nothing here touches the disk.
+
+export function audioBytesPerHour(bytes: number, seconds: number | null): number | null {
+ if (!(bytes > 0) || seconds === null || !(seconds > 0)) return null;
+ return bytes / (seconds / 3600);
+}
+
+export function spaceComparator(look: {
+ external: (id: string) => boolean;
+ bytesPerHour: (id: string) => number | null;
+}): (a: string, b: string) => number {
+ return (a, b) => {
+ const ea = look.external(a) ? 1 : 0;
+ const eb = look.external(b) ? 1 : 0;
+ if (ea !== eb) return ea - eb;
+ const ra = look.bytesPerHour(a);
+ const rb = look.bytesPerHour(b);
+ if (ra === rb) return 0;
+ if (ra === null) return 1;
+ if (rb === null) return -1;
+ return rb - ra;
+ };
+}
diff --git a/common/lib/speakersLedger-server.ts b/common/lib/speakersLedger-server.ts
@@ -0,0 +1,102 @@
+// What the Speakers lane has freed since it was last started: the "freed this
+// run" half of the speakers readout (controller/speakersReadout.ts).
+//
+// A file, not a counter in the runner: the lane runs for weeks across editor
+// restarts, and a number that resets on every restart would say "freed 0 GB"
+// the morning after a night that freed forty. One small JSON at the corpus
+// root, read-modify-written under the in-process file lock; the lane runs at
+// concurrency 1 and the per-channel batch shares its queue, so there is one
+// writer at a time anyway.
+//
+// "This run" begins when the operator presses Work through speakers on a lane
+// that was paused or disarmed (startSpeakersRun); Pause does not reset it, so a
+// paused-then-resumed night is still one run.
+
+import path from "node:path";
+import type { Paths } from "./paths";
+import {
+ readJsonFile,
+ withJsonFileLock,
+ writeJsonAtomic,
+} from "./jsonFile-server";
+
+// A dot path, like the corpus root's other runtime state (.x-runs, .x-session,
+// .auto-queue): state, not corpus data.
+export const SPEAKERS_LEDGER_FILENAME = ".speakers-run.json";
+
+export type SpeakersLedger = {
+ version: 1;
+ // ISO 8601: when this run began (null before the first one).
+ startedAt: string | null;
+ // Audio removed by clean-after-capture this run.
+ freedBytes: number;
+ freedVideos: number;
+ // ISO 8601 of the last change.
+ updatedAt: string | null;
+};
+
+export function emptySpeakersLedger(): SpeakersLedger {
+ return { version: 1, startedAt: null, freedBytes: 0, freedVideos: 0, updatedAt: null };
+}
+
+export function speakersLedgerPath(paths: Pick<Paths, "transcriptsDir">): string {
+ return path.join(paths.transcriptsDir, SPEAKERS_LEDGER_FILENAME);
+}
+
+function coerce(value: unknown): SpeakersLedger {
+ const v = value as Partial<SpeakersLedger> | null;
+ const n = (x: unknown) => (typeof x === "number" && Number.isFinite(x) && x >= 0 ? x : 0);
+ const s = (x: unknown) => (typeof x === "string" ? x : null);
+ if (!v || typeof v !== "object") return emptySpeakersLedger();
+ return {
+ version: 1,
+ startedAt: s(v.startedAt),
+ freedBytes: n(v.freedBytes),
+ freedVideos: n(v.freedVideos),
+ updatedAt: s(v.updatedAt),
+ };
+}
+
+export async function readSpeakersLedger(
+ paths: Pick<Paths, "transcriptsDir">,
+): Promise<SpeakersLedger> {
+ const read = await readJsonFile(speakersLedgerPath(paths));
+ return read.ok ? coerce(read.value) : emptySpeakersLedger();
+}
+
+async function update(
+ paths: Pick<Paths, "transcriptsDir">,
+ fn: (l: SpeakersLedger) => SpeakersLedger,
+): Promise<SpeakersLedger> {
+ const file = speakersLedgerPath(paths);
+ return withJsonFileLock(file, async () => {
+ const next = fn(await readSpeakersLedger(paths));
+ await writeJsonAtomic(file, next, { indent: 2 });
+ return next;
+ });
+}
+
+// A new run: the freed tally starts again from zero.
+export function startSpeakersRun(
+ paths: Pick<Paths, "transcriptsDir">,
+ now: Date = new Date(),
+): Promise<SpeakersLedger> {
+ const at = now.toISOString();
+ return update(paths, () => ({ ...emptySpeakersLedger(), startedAt: at, updatedAt: at }));
+}
+
+// One video's audio freed by clean-after-capture.
+export function recordSpeakersFreed(
+ paths: Pick<Paths, "transcriptsDir">,
+ bytes: number,
+ now: Date = new Date(),
+): Promise<SpeakersLedger> {
+ const at = now.toISOString();
+ return update(paths, (l) => ({
+ ...l,
+ startedAt: l.startedAt ?? at,
+ freedBytes: l.freedBytes + Math.max(0, bytes),
+ freedVideos: l.freedVideos + 1,
+ updatedAt: at,
+ }));
+}
diff --git a/common/lib/speakersReadout.ts b/common/lib/speakersReadout.ts
@@ -0,0 +1,70 @@
+// The speakers readout — what the Speakers lane is holding, what it has freed,
+// how fast it goes and how long is left. Client-safe types and the one line
+// every surface prints (the lane deck, /cleanup, `pnpm ops get speakers`), so
+// the three can never word or round it differently. Built server-side by
+// controller/speakersReadout.ts from the channel snapshots and the ledger.
+
+import { formatBytes } from "./format";
+
+export type SpeakersChannelRow = {
+ slug: string;
+ // Media on another drive (the channel names a mediaDir).
+ external: boolean;
+ // Audio held for the lane that it WILL clear (the hold minus what it never
+ // clears), bytes and videos.
+ waitingBytes: number;
+ waitingVideos: number;
+ // Audio held at the speakers gate that the lane will never clear (over the
+ // duration cap, no input, the operation unconfigured).
+ neverClearsBytes: number;
+ neverClearsVideos: number;
+ remainingAudioHours: number;
+ unmeasuredVideos: number;
+ voiceprinted: number;
+ noFingerprintPossible: number;
+};
+
+export type SpeakersReadout = {
+ waitingBytes: number;
+ waitingVideos: number;
+ neverClearsBytes: number;
+ neverClearsVideos: number;
+ // This run (.speakers-run.json).
+ freedBytes: number;
+ freedVideos: number;
+ runStartedAt: string | null;
+ // Measured engine cost: wall seconds per audio-hour over `measured` sidecars.
+ secondsPerAudioHour: number | null;
+ measured: number;
+ // Remaining work. Videos with no recorded duration are estimated at the mean
+ // duration of the measured ones (and counted in unmeasuredVideos).
+ remainingAudioHours: number;
+ unmeasuredVideos: number;
+ // Wall-clock days at concurrency 1, or null when nothing measured the rate.
+ etaDays: number | null;
+ voiceprinted: number;
+ noFingerprintPossible: number;
+ // Channels whose snapshot predates the readout's fields: their numbers are
+ // missing until the next regeneration.
+ staleSnapshots: number;
+ channels: SpeakersChannelRow[];
+};
+
+function days(d: number): string {
+ if (d < 1) return "under a day";
+ const n = d < 10 ? Math.round(d * 10) / 10 : Math.round(d);
+ return `${n} day${n === 1 ? "" : "s"}`;
+}
+
+// "waiting: 368.78 GB in 3,634 videos · freed this run: 0 B · about 41 days left"
+export function speakersReadoutLine(r: SpeakersReadout): string {
+ const waiting = `waiting: ${formatBytes(r.waitingBytes)} in ${r.waitingVideos.toLocaleString("en-US")} video${r.waitingVideos === 1 ? "" : "s"}`;
+ const freed = `freed this run: ${formatBytes(r.freedBytes)}`;
+ const left =
+ r.waitingVideos === 0
+ ? "nothing left"
+ : r.etaDays === null
+ ? "time left not yet measured"
+ : `about ${days(r.etaDays)} left`;
+ return `${waiting} · ${freed} · ${left}`;
+}
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/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/channelGroupSections.ts b/common/views/channelGroupSections.ts
@@ -14,7 +14,7 @@ import {
import {
DIGEST_OPERATION_ID,
allOperations,
- backfillLaneOperations,
+ backfillLaneDispatchOperations,
backfillLaneEntriesOf,
operationsGroupLabel,
reachableOperationWork,
@@ -102,7 +102,7 @@ export function laneOffFor(
if (station === "digest") {
return !allOperations(settings).some((k) => k.id === DIGEST_OPERATION_ID);
}
- if (station === "speakers") return backfillLaneOperations(settings).length === 0;
+ if (station === "speakers") return backfillLaneDispatchOperations(settings).length === 0;
return false;
}
@@ -328,7 +328,7 @@ export function buildChannelGroupSections(
digest: station("digest"),
speakers: station("speakers"),
speakersLabel: operationsGroupLabel(
- backfillLaneOperations(settings).map((k) => k.id),
+ backfillLaneDispatchOperations(settings).map((k) => k.id),
),
};
});
diff --git a/common/views/channelRow.ts b/common/views/channelRow.ts
@@ -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
@@ -197,6 +199,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,
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
@@ -14,6 +14,7 @@ import {
// three client components (AttentionStrip, NextAction, OverviewPanel) for its
// types. A type import is erased, a value import would not be.
import type { ChannelMediaLocation } from "../../lib/channelMedia";
+import { formatBytes } from "../../lib/format";
export type SnapshotBuckets = ChannelSnapshot["buckets"];
@@ -249,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",
@@ -258,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");
@@ -272,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 }),
@@ -558,6 +566,16 @@ export function computeStageStatuses(
),
);
}
+ // Audio held for the Speakers lane. Not pending work for THIS stage (Clean
+ // audio cannot take it yet), but the reason the disk is not freed — the
+ // summary used to say "Nothing to clean." with gigabytes held.
+ const heldForSpeakers = snapshot.heldAudioBytes?.awaitingDiarization ?? 0;
+ const heldForSpeakersCount = snapshot.heldAudioCounts?.awaitingDiarization ?? 0;
+ if (heldForSpeakers > 0) {
+ cleanupParts.push(
+ `${formatBytes(heldForSpeakers)} held for speakers (${pluralize(heldForSpeakersCount, "video", "videos")})`,
+ );
+ }
const cleanup: StageStatus = {
id: "cleanup",
title: "Cleanup",
diff --git a/common/views/widgetSync.ts b/common/views/widgetSync.ts
@@ -1,10 +1,13 @@
import type { SiteSettings } from "../lib/settings";
import { digestCountOf, type ChannelBrief } from "../controller/channels";
import { digestWorkOf } from "../controller/channelSnapshot";
+import { buildSpeakersReadout } from "../controller/speakersReadout";
+import { emptySpeakersLedger, type SpeakersLedger } from "../lib/speakersLedger-server";
+import { speakersReadoutLine } from "../lib/speakersReadout";
import { isGateHeld } from "../lib/pauseGates";
import {
- backfillLaneOperations,
backfillLaneOperationEntriesOf,
+ backfillLaneDispatchOperations,
operationCostBasis,
operationLabel,
operationsGroupLabel,
@@ -114,6 +117,16 @@ export type WidgetSyncPayload = {
// word survives only on the controls that genuinely act on the shared queue,
// and even there the card now lists what is in it.
groupLabel: string;
+ // THE SPEAKERS READOUT, as the lane card prints it (lib/speakersReadout.ts):
+ // the one line, and the four numbers it leads with. Optional: a payload
+ // from before it reads as no readout.
+ speakers?: {
+ line: string;
+ waitingBytes: number;
+ waitingVideos: number;
+ freedBytes: number;
+ etaDays: number | null;
+ };
// The same numbers, kept apart by kind — which is the only form of them that
// means anything. Summed, this lane reads "77,952 reachable · 77,134 need
// media": both correct, and together a figure in no unit, since 99.5% of the
@@ -166,6 +179,9 @@ export type WidgetSyncInputs = {
// polls — which is why the briefs arrive as an argument rather than being
// read here: the caller already has them, memoized per request.
briefs: readonly ChannelBrief[];
+ // The Speakers lane's "freed this run" (lib/speakersLedger-server.ts). Absent
+ // reads as an empty run.
+ speakersLedger?: SpeakersLedger;
};
// Build the widget sync payload. Both the HTTP route and the dashboard cockpit's
@@ -240,6 +256,8 @@ export function buildWidgetSyncPayload(
// below — no extra read.
let digestBlocked = 0;
let digestDeferred = 0;
+ const narrowed = settings.autoQueue.backfill.operations;
+ const narrowedTo = narrowed && narrowed.length > 0 ? narrowed : null;
for (const c of channels) {
videos += c.snapshot?.totals.videos ?? 0;
const n = digestCountOf(c.snapshot);
@@ -259,6 +277,9 @@ export function buildWidgetSyncPayload(
// only ever meant diarization plus attribution — the digest coverage figure
// it shows beside this one is computed separately, from digestCountOf above.
for (const [id, entry] of backfillLaneOperationEntriesOf(c.snapshot?.backfill)) {
+ // A lane narrowed to some operations (autoQueue.backfill.operations)
+ // counts only those: the rest is not this lane's work while it is.
+ if (narrowedTo && !narrowedTo.includes(id)) continue;
backfillReachable += reachableOperationWork(entry);
backfillNeedsMedia += entry.missingInput;
const acc = backfillByKind.get(id) ?? {
@@ -310,14 +331,27 @@ export function buildWidgetSyncPayload(
armed: settings.autoQueue.digest.enabled,
},
backfill: {
+ speakers: (() => {
+ const r = buildSpeakersReadout(channels, inputs.speakersLedger ?? emptySpeakersLedger());
+ return {
+ line: speakersReadoutLine(r),
+ waitingBytes: r.waitingBytes,
+ waitingVideos: r.waitingVideos,
+ freedBytes: r.freedBytes,
+ etaDays: r.etaDays,
+ };
+ })(),
reachable: backfillReachable,
needsMedia: backfillNeedsMedia,
videos,
held: isGateHeld(settings, "backfill"),
armed: settings.autoQueue.backfill.enabled,
- anyKind: backfillLaneOperations(settings).length > 0,
+ // What the lane DISPATCHES (backfillLaneDispatchOperations: its `operations`
+ // narrowing applied), so a speakers-only lane is named and broken down as
+ // what it runs.
+ anyKind: backfillLaneDispatchOperations(settings).length > 0,
groupLabel: operationsGroupLabel(
- backfillLaneOperations(settings).map((k) => k.id),
+ backfillLaneDispatchOperations(settings).map((k) => k.id),
),
kinds: [...backfillByKind]
.map(([id, counts]) => ({
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/_renderMode.test.ts b/editor/app/api/ops/_renderMode.test.ts
@@ -19,18 +19,28 @@ const { getWorkerPool } = await import("yt-dlp-transcript-common/jobs/workerPool
const { renderModeReapTick } = await import("../../operations/renderMode");
test.after(() => corpus.cleanup());
-const held = (lane: "transcription" | "download") => getSettings().autoQueue[lane].held === true;
+const held = (lane: "transcription" | "download" | "backfill") => getSettings().autoQueue[lane].held === true;
test("on holds the lanes not already held (and says so), off releases only those", async () => {
- await corpus.writeSettings({ minFreeDiskGB: 0, autoQueue: { ...getSettings().autoQueue, download: { ...getSettings().autoQueue.download, held: true } } });
+ // The Speakers (backfill) lane running: a render takes its cores too.
+ await corpus.writeSettings({
+ minFreeDiskGB: 0,
+ autoQueue: {
+ ...getSettings().autoQueue,
+ download: { ...getSettings().autoQueue.download, held: true },
+ backfill: { ...getSettings().autoQueue.backfill, held: false },
+ },
+ });
assert.equal(held("download"), true);
assert.equal(held("transcription"), false);
+ assert.equal(held("backfill"), false);
const on = await callPost(POST!, { on: true, for: "90m", note: "the Ember cut" });
assert.equal(on.status, 200, JSON.stringify(on.body));
const state = on.body.state as { token: string; lanesHeld: string[]; lanesSkipped: string[]; until: string; editor: string };
- assert.deepEqual(state.lanesHeld, ["transcription"]);
+ assert.deepEqual(state.lanesHeld, ["transcription", "backfill"]);
assert.deepEqual(state.lanesSkipped, ["download"]);
+ assert.equal(held("backfill"), true);
assert.match(String(on.body.join), /^RENDER_PRIORITY_TOKEN=[0-9a-f]{16}$/);
assert.match(state.editor, /^http:\/\/localhost:\d+$/);
assert.equal(held("transcription"), true);
@@ -45,12 +55,13 @@ test("on holds the lanes not already held (and says so), off releases only those
assert.equal(got.status, 200);
assert.equal(got.body.held, true);
assert.equal(got.body.token, undefined, "the read side carries no token");
- assert.deepEqual(got.body.lanesHeld, ["transcription"]);
+ assert.deepEqual(got.body.lanesHeld, ["transcription", "backfill"]);
const off = await callPost(POST!, { on: false });
assert.equal(off.status, 200, JSON.stringify(off.body));
- assert.deepEqual(off.body.released, ["transcription"]);
+ assert.deepEqual(off.body.released, ["transcription", "backfill"]);
assert.equal(held("transcription"), false);
+ assert.equal(held("backfill"), false);
assert.equal(getWorkerPool().isPaused(), false);
assert.equal(held("download"), true, "someone else's hold stays");
assert.equal(existsSync(STATE), false);
diff --git a/editor/app/api/ops/_speakers.test.ts b/editor/app/api/ops/_speakers.test.ts
@@ -0,0 +1,104 @@
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_speakers.test.ts"
+//
+// `pnpm ops lane` for the Speakers lane — its `operations` narrowing, its
+// `order`, its one control (`speakers`: work | pause) — and `pnpm ops get
+// speakers`, against the route handlers over a temp corpus. Never the live
+// editor's settings.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { writeFileSync } from "node:fs";
+import path from "node:path";
+import { callGet, callPost, setupOpsCorpus } from "./_testCorpus";
+
+const corpus = await setupOpsCorpus(null);
+const RENDER_STATE = path.join(corpus.root, "render-priority.json");
+process.env.RENDER_PRIORITY_FILE = RENDER_STATE;
+const { POST } = await import("./lane/route");
+const { GET } = await import("./speakers/route");
+const { getSettings } = await import("yt-dlp-transcript-common/lib/settings");
+test.after(() => corpus.cleanup());
+
+const DIARIZATION = {
+ enabled: true,
+ segModel: "/m/seg.onnx",
+ embModel: "/m/emb.onnx",
+};
+
+test("lane: operations narrows the Speakers lane (and null widens it), order takes \"space\"; bad values are 400s", async () => {
+ await corpus.writeSettings({ minFreeDiskGB: 0, diarization: DIARIZATION, attribution: { enabled: true, textOnlyEnabled: true, diarizedEnabled: true } });
+ const ok = await callPost(POST!, { lane: "backfill", operations: ["diarization"], order: "space" });
+ assert.equal(ok.status, 200, JSON.stringify(ok.body));
+ assert.deepEqual(getSettings().autoQueue.backfill.operations, ["diarization"]);
+ assert.equal(getSettings().autoQueue.backfill.order, "space");
+
+ const unknown = await callPost(POST!, { lane: "backfill", operations: ["no-such-op"] });
+ assert.equal(unknown.status, 400);
+ assert.match(String(unknown.body.error), /Not an enabled operation on the backfill lane: no-such-op/);
+ assert.equal((await callPost(POST!, { lane: "backfill", order: "biggest" })).status, 400);
+ assert.equal((await callPost(POST!, { lane: "backfill", operations: "diarization" })).status, 400);
+ assert.equal((await callPost(POST!, { lane: "digest", speakers: "work" })).status, 400);
+
+ const widened = await callPost(POST!, { lane: "backfill", operations: null });
+ assert.equal(widened.status, 200, JSON.stringify(widened.body));
+ assert.equal(getSettings().autoQueue.backfill.operations, undefined);
+ assert.equal(getSettings().autoQueue.backfill.order, "space", "order untouched by an operations write");
+});
+
+// `speakers: "work" | "pause"` goes through the lane actions, which revalidate
+// pages and so need a request: the e2e suite drives them (speakers-run.spec,
+// backfill.spec). Here: what `get speakers` says about a held lane.
+test("get speakers: the line, the lane's state and the two capture settings", async () => {
+ await corpus.writeSettings({
+ minFreeDiskGB: 0,
+ diarization: { ...DIARIZATION, cleanAfterCapture: true },
+ autoQueue: { ...getSettings().autoQueue, backfill: { ...getSettings().autoQueue.backfill, enabled: false, held: true } },
+ });
+ const got = await callGet(GET!, "http://localhost/api/ops/speakers");
+ assert.equal(got.status, 200, JSON.stringify(got.body));
+ const lane = got.body.lane as { held: boolean; armed: boolean; cleanAfterCapture: boolean; requireVoiceprints: boolean };
+ assert.deepEqual(
+ { held: lane.held, armed: lane.armed, cleanAfterCapture: lane.cleanAfterCapture, requireVoiceprints: lane.requireVoiceprints },
+ { held: true, armed: false, cleanAfterCapture: true, requireVoiceprints: true },
+ );
+ assert.equal(got.body.line, "waiting: 0 B in 0 videos · freed this run: 0 B · nothing left");
+ assert.deepEqual(got.body.channels, []);
+});
+
+test("lane speakers:work refuses an un-narrowed lane, and a lane a render holds — writing nothing", async () => {
+ await corpus.writeSettings({
+ minFreeDiskGB: 0,
+ diarization: DIARIZATION,
+ attribution: { enabled: true, textOnlyEnabled: true, diarizedEnabled: true },
+ autoQueue: { ...getSettings().autoQueue, backfill: { ...getSettings().autoQueue.backfill, enabled: false, held: true, operations: undefined } },
+ });
+ const wide = await callPost(POST!, { lane: "backfill", speakers: "work" });
+ assert.equal(wide.status, 400);
+ assert.match(String(wide.body.error), /not narrowed to speaker diarization/);
+ assert.match(String(wide.body.error), /"operations":\["diarization"\]/);
+ assert.equal(getSettings().autoQueue.backfill.held, true);
+ assert.equal(getSettings().autoQueue.backfill.enabled, false);
+
+ await corpus.writeSettings({
+ minFreeDiskGB: 0,
+ diarization: DIARIZATION,
+ autoQueue: { ...getSettings().autoQueue, backfill: { ...getSettings().autoQueue.backfill, enabled: false, held: true, operations: ["diarization"] } },
+ });
+ writeFileSync(
+ RENDER_STATE,
+ JSON.stringify({
+ version: 1,
+ token: "tok",
+ since: new Date().toISOString(),
+ until: null,
+ holder: { pid: process.pid, cmd: "umtool take ember --id t1" },
+ lanesHeld: ["backfill"],
+ editor: "http://localhost:3001",
+ }),
+ );
+ const rendering = await callPost(POST!, { lane: "backfill", speakers: "work" });
+ assert.equal(rendering.status, 400);
+ assert.match(String(rendering.body.error), /A render holds the Speakers lane \(umtool take ember --id t1\)/);
+ assert.equal(getSettings().autoQueue.backfill.held, true, "the render's hold stands");
+});
+
diff --git a/editor/app/api/ops/diarize/route.ts b/editor/app/api/ops/diarize/route.ts
@@ -0,0 +1,18 @@
+import { diarizeChannelAction } from "../../../channels/[slug]/whisperActions";
+import { jobResponse, ops, reqSlug } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug } — the Cleanup stage's "Diarize speakers", as a job on the
+// channel's queue ({ ok, jobId }; --wait follows it): diarize every video of
+// the channel that still holds audio and has no current diarization.json, and
+// give an existing one its voice fingerprints from its own turns (no
+// re-clustering) — the voiceprint backfill, one channel at a time. Runs whether
+// or not the Speakers lane is paused; `lane {"lane":"backfill","speakers":"work"}`
+// is the whole-corpus way.
+export async function POST(request: Request) {
+ return ops(request, ["slug"], async (body) => {
+ const slug = reqSlug(body, "slug");
+ return jobResponse(await diarizeChannelAction(slug));
+ });
+}
diff --git a/editor/app/api/ops/lane/route.ts b/editor/app/api/ops/lane/route.ts
@@ -20,6 +20,13 @@ import {
stopPublishLaneAction,
} from "../../../sites/lib/publishActions";
import { OpsInputError, okResponse, ops, oneOf, optBool } from "../_lib";
+import {
+ pauseSpeakersAction,
+ workThroughSpeakersAction,
+} from "../../../jobs/actions";
+import { setLaneScopeAction } from "../../../operations/actions";
+import { AUTO_QUEUE_ORDERS } from "yt-dlp-transcript-common/lib/autoQueueSchema";
+import type { AutoQueueOrder } from "yt-dlp-transcript-common/lib/autoQueueTypes";
export const dynamic = "force-dynamic";
@@ -37,6 +44,17 @@ export const dynamic = "force-dynamic";
// `action` mirrors /api/auto-queue/control's body — same three verbs, same
// meanings — so a caller that already drives that route needs nothing new.
//
+// THE SPEAKERS LANE'S SCOPE AND ITS ONE CONTROL (the backfill lane):
+// operations: ["diarization"] | null narrow the lane to these operations
+// (null widens it again) — speakers only;
+// order: "listed"|"newest"|"oldest"|"space" its order ("space": corpus-disk
+// channels first, then the most audio
+// bytes per audio-hour);
+// speakers: "work" | "pause" the lane deck's Work through speakers
+// (arm + lift the hold + start a run) and
+// Pause (hold; stays armed).
+// `operations` and `order` apply first, then `speakers`, then the rest.
+//
// THE PUBLISH LANE (release 19, A4) is a pipeline lane, not a LANES entry: its
// switch is `settings.publish.enabled` (the /operations/publish form's, saved
// through that form's own action with every other field as stored), its gate
@@ -63,7 +81,7 @@ function publishForm(enabled: boolean): FormData {
}
export async function POST(request: Request) {
- return ops(request, ["lane", "held", "enabled", "action"], async (body) => {
+ return ops(request, ["lane", "held", "enabled", "action", "operations", "order", "speakers"], async (body) => {
const lane = oneOf(body, "lane", ALL_LANES);
const enabled = optBool(body, "enabled");
const held = optBool(body, "held");
@@ -76,9 +94,39 @@ export async function POST(request: Request) {
) {
throw new OpsInputError('"action" must be "start", "stop" or "drain"');
}
- if (enabled === undefined && held === undefined && action === undefined) {
+ const speakers = body.speakers;
+ if (speakers !== undefined && speakers !== "work" && speakers !== "pause") {
+ throw new OpsInputError('"speakers" must be "work" or "pause"');
+ }
+ const operations = body.operations;
+ if (
+ operations !== undefined &&
+ operations !== null &&
+ !(Array.isArray(operations) && operations.every((o) => typeof o === "string"))
+ ) {
+ throw new OpsInputError('"operations" must be an array of operation ids, or null');
+ }
+ const order = body.order;
+ if (order !== undefined && !AUTO_QUEUE_ORDERS.includes(order as AutoQueueOrder)) {
+ throw new OpsInputError(`"order" must be one of ${AUTO_QUEUE_ORDERS.join(", ")}`);
+ }
+ if ((speakers !== undefined || operations !== undefined || order !== undefined) &&
+ !(LANES as readonly string[]).includes(lane)) {
+ throw new OpsInputError('"speakers", "operations" and "order" are for an auto-queue lane');
+ }
+ if (speakers !== undefined && lane !== "backfill") {
+ throw new OpsInputError('"speakers" is the backfill (Speakers) lane\'s');
+ }
+ if (
+ enabled === undefined &&
+ held === undefined &&
+ action === undefined &&
+ speakers === undefined &&
+ operations === undefined &&
+ order === undefined
+ ) {
throw new OpsInputError(
- 'nothing to do — send at least one of "enabled", "held" or "action"',
+ 'nothing to do — send at least one of "enabled", "held", "action", "speakers", "operations" or "order"',
);
}
// THE RECURRING REPORTS' LANE (umtool R5) has a gate and nothing else: its
@@ -87,6 +135,17 @@ export async function POST(request: Request) {
if (lane === "report-schedule" && (enabled !== undefined || action !== undefined)) {
throw new OpsInputError('the report-schedule lane takes only "held" — pause a schedule with report-schedule {"action":"pause"}');
}
+ if (operations !== undefined || order !== undefined) {
+ const scoped = await setLaneScopeAction(lane as AutoQueueKind, {
+ ...(operations !== undefined ? { operations: operations as string[] | null } : {}),
+ ...(order !== undefined ? { order: order as AutoQueueOrder } : {}),
+ });
+ if (!scoped.ok) return okResponse(scoped);
+ }
+ if (speakers !== undefined) {
+ const done = speakers === "work" ? await workThroughSpeakersAction() : await pauseSpeakersAction();
+ if (!done.ok) return okResponse(done);
+ }
if (enabled !== undefined) {
if (lane === "publish") {
const saved = await savePublishSettingsAction(undefined, publishForm(enabled));
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/render-mode/route.ts b/editor/app/api/ops/render-mode/route.ts
@@ -14,7 +14,7 @@ export const dynamic = "force-dynamic";
// RENDER MODE (common/lib/renderPriority.mjs; AGENTS.md "Render mode"): a
// render the operator is waiting for gets the machine — every other heavy job
-// waits at the heavy slot's door, and this editor's transcription and download
+// waits at the heavy slot's door, and this editor's transcription, download and Speakers (backfill)
// lanes are held (only the ones not held already; only those are released).
// The same switch as `umtool render-mode`, for a session that has only `pnpm ops`.
//
diff --git a/editor/app/api/ops/speakers/route.ts b/editor/app/api/ops/speakers/route.ts
@@ -0,0 +1,42 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { isGateHeld } from "yt-dlp-transcript-common/lib/pauseGates";
+import { operationsForLane } from "yt-dlp-transcript-common/lib/operations";
+import { loadSpeakersReadout } from "yt-dlp-transcript-common/controller/speakersReadout";
+import { speakersReadoutLine } from "yt-dlp-transcript-common/lib/speakersReadout";
+import { readRoute } from "../_read";
+
+export const dynamic = "force-dynamic";
+
+// GET /api/ops/speakers — `pnpm ops get speakers`
+//
+// The speakers readout, as the lane deck and /cleanup print it: `line`
+// ("waiting: X GB in N videos · freed this run: Y GB · about D days left"),
+// then the numbers it is made of — waiting (the audio held for the Speakers
+// lane that it WILL clear), neverClears (held there and never cleared by it),
+// freed this run (.speakers-run.json), the measured rate (seconds of engine per
+// audio-hour, from the sidecars' durationMs/audioSeconds), the audio-hours
+// left and the days at concurrency 1, voiceprinted and noFingerprintPossible
+// (diarized, the audio already gone) — and per channel, corpus disk first.
+// `lane` is the backfill lane's state: armed, held, the operations it
+// dispatches, its order, and the two capture settings.
+export async function GET(request: Request) {
+ return readRoute(request, [], async () => {
+ const settings = getSettings();
+ const readout = await loadSpeakersReadout(getPaths());
+ const policy = settings.autoQueue.backfill;
+ return {
+ line: speakersReadoutLine(readout),
+ lane: {
+ armed: policy.enabled,
+ held: isGateHeld(settings, "backfill"),
+ operations: operationsForLane("backfill", settings).map((o) => o.id),
+ narrowedTo: policy.operations ?? null,
+ order: policy.order ?? "listed",
+ cleanAfterCapture: settings.diarization.cleanAfterCapture,
+ requireVoiceprints: settings.diarization.requireVoiceprints,
+ },
+ ...readout,
+ };
+ });
+}
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]/components/stages/CleanupStage.tsx b/editor/app/channels/[slug]/components/stages/CleanupStage.tsx
@@ -89,7 +89,7 @@ export function CleanupStage({
<div className="flex flex-col gap-2">
<Heading
title="Diarize speakers"
- desc="Capture who is speaking when, to diarization.json beside each transcript, for every video here that still has audio. This is the half of the decision that has a deadline: Clean audio below deletes the audio, and nothing can reconstruct it afterwards. While diarization is on, that sweep holds back any transcribed video without a sidecar — so running this is what releases the audio it is protecting."
+ desc="This channel, now — even while the Speakers lane is paused: who is speaking when (diarization.json) and each speaker's voice fingerprint, for every video here that still has audio; a video already diarized only gets its fingerprints. Clean audio below holds a transcribed video's audio until both exist, so running this is what releases it. The whole corpus, one video at a time, is Work through speakers on the Speakers lane."
/>
<StreamActionLog
trigger={() => diarizeChannelAction(slug, cleanQueue)}
@@ -112,7 +112,7 @@ export function CleanupStage({
<div className="flex flex-col gap-2">
<Heading
title="Clean audio for transcribed videos"
- desc="Delete audio.* files in any video directory that has a transcript.json (whisper output). YouTube videos with only auto-sub .vtt files have no audio and are skipped automatically."
+ desc="Delete audio.* files in any video directory that has a transcript.json (whisper output). YouTube videos with only auto-sub .vtt files have no audio and are skipped automatically. While diarization is on, a video awaiting its speakers or voice fingerprints keeps its audio."
/>
<ReclaimEstimate bytes={transcribedAudioBytes} />
<StreamActionLog
diff --git a/editor/app/channels/[slug]/components/stages/SpeakersStage.tsx b/editor/app/channels/[slug]/components/stages/SpeakersStage.tsx
@@ -26,6 +26,8 @@ import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActio
import { QueueControl } from "../../../../components/QueueControl";
import { cancelJobAction } from "../../../../jobs/actions";
import { backfillChannelAction } from "../../backfillActions";
+import { LaneActionButton } from "../../../../components/lanes/LaneActionButton";
+import { workThroughSpeakersAction } from "../../../../jobs/actions";
import { OperationWork } from "./OperationWork";
export type OperationRowView = {
@@ -78,6 +80,10 @@ type Props = {
// No backfill feature is switched on at all. The card still renders (the rail
// is fixed) but says so rather than reporting an empty work list as "done".
anyEnabled: boolean;
+ // The Speakers lane's gate is shut. A run here waits on it (backfillLaneLimit
+ // holds at zero), so the card says so and offers the lane's own control
+ // rather than leaving "Run speaker work" to idle at "holding".
+ laneHeld?: boolean;
};
export function SpeakersStage({
@@ -89,6 +95,7 @@ export function SpeakersStage({
anyEnabled,
groupLabel,
actionLabel,
+ laneHeld = false,
}: Props) {
// "speaker work" → "Speaker work". Sentence case, not title case: it is a
// phrase, and "Speaker Work" is a proper noun this system does not have.
@@ -152,6 +159,29 @@ export function SpeakersStage({
</>
),
},
+ ...(anyEnabled && laneHeld
+ ? [
+ {
+ key: "lane-paused",
+ ariaLabel: "speakers lane paused",
+ node: (
+ <span className="flex flex-wrap items-center gap-2">
+ <span>
+ The Speakers lane is paused, so {runLabel} waits for it.
+ </span>
+ <LaneActionButton
+ label="Work through speakers"
+ glyph="⟳"
+ ariaLabel="work through speakers"
+ title="Arm the Speakers lane and lift its hold: every channel's speakers and voice fingerprints, one video at a time."
+ variant="idle"
+ action={() => workThroughSpeakersAction()}
+ />
+ </span>
+ ),
+ },
+ ]
+ : []),
...(missingInput > 0
? [
{
@@ -252,6 +282,7 @@ export function SpeakersStage({
buttonLabel={runLabel}
runningLabel="Running…"
label={runLabel}
+ title={`This channel only, now: ${operations.map((k) => k.label.toLowerCase()).join(", ") || "nothing enabled"} for the videos listed below, one at a time on the Speakers lane's queue.`}
extraControls={
<QueueControl
value={queue}
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
@@ -67,6 +67,7 @@ import { countPlaylist } from "yt-dlp-transcript-common/controller/channels";
import { loadFailedTranscriptions } from "yt-dlp-transcript-common/controller/failedTranscriptions";
import { savedVideoTotals } from "yt-dlp-transcript-common/controller/savedVideoInventory";
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { isGateHeld } from "yt-dlp-transcript-common/lib/pauseGates";
import { locationLabelOfDataDir } from "yt-dlp-transcript-common/lib/storageLocations";
import { probeAllLocations } from "yt-dlp-transcript-common/controller/storageLocations";
import { STORAGE_STATUS_LABEL } from "yt-dlp-transcript-common/views/storage";
@@ -133,7 +134,7 @@ import { MirrorStage } from "./components/stages/MirrorStage";
import { readMirrorScan } from "yt-dlp-transcript-common/lib/mirrors/scanFile-server";
import {
getOperation,
- backfillLaneOperations,
+ backfillLaneDispatchOperations,
operationsActionLabel,
operationsGroupLabel,
OPERATION_GROUP_ORDER,
@@ -444,10 +445,11 @@ export default async function ChannelDetailPage({
buckets.downloadedNoTranscript.filter((id) => !excludedDownloadIds.has(id));
// Enabled lane backfills. A settings read, no I/O.
//
- // backfillLaneOperations, still: this is the BACKFILL lane's list, and the snapshot
- // now carries an entry for every catalog operation including digest, which has
- // its own station and its own queue key.
- const laneOperations = backfillLaneOperations(settings);
+ // The BACKFILL lane's list as it DISPATCHES (backfillLaneDispatchOperations): the snapshot
+ // carries an entry for every catalog operation including digest, which has its
+ // own station and queue key, and a lane narrowed by `autoQueue.backfill.
+ // operations` (speakers only) runs — and so names — only those.
+ const laneOperations = backfillLaneDispatchOperations(settings);
// A mirror channel's last scan (release 31, lane D): one small file, read
// only for a channel whose config has `mirror`.
const mirrorOf = config.mirror?.of ?? [];
@@ -734,6 +736,7 @@ export default async function ChannelDetailPage({
// The lane's name comes from what it HOLDS, not from its queue key.
groupLabel={operationsGroupLabel(laneOperations.map((k) => k.id))}
actionLabel={operationsActionLabel(laneOperations.map((k) => k.id))}
+ laneHeld={isGateHeld(settings, "backfill")}
/>
);
case "cleanup": {
@@ -993,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 />
@@ -1003,6 +1007,7 @@ export default async function ChannelDetailPage({
stageOrder={stageOrder}
stages={stages}
selected={selectedStage}
+ showLocalLibrary={!isSocialChannel(config) && !!config.localMedia}
/>
{selectedStage ? (
<section
@@ -1033,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,5 +1,6 @@
"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 { fetchPostsAction } from "./socialActions";
@@ -445,6 +446,8 @@ export async function runMetadataScanAction(
if (!channelConfig) {
return { ok: false, error: `Channel "${slug}" not found` };
}
+ 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";
@@ -216,6 +217,11 @@ async function planFetchWindows(
unresolved.push({ item, error: `Channel "${item.slug}" not found` });
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
// record's v<n> is data/<n>/ (release 23 F1). The item keeps its id.
const dirId = await resolveVideoDirId(paths.channelsDir, item.slug, item.id, {
diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts
@@ -1,5 +1,6 @@
"use server";
+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 +232,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 +245,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);
}
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/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: {
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/components/HoldSieve.tsx b/editor/app/cleanup/components/HoldSieve.tsx
@@ -97,7 +97,7 @@ export function HoldSieve({ summary }: { summary: CleanupSummary }) {
{
n: 4,
label: "awaiting diarization",
- clears: "run: Diarize",
+ clears: "run: Work through speakers",
bytes: heldBytes.awaitingDiarization,
count: heldCounts.awaitingDiarization,
neverClears: heldBytes.diarizationNeverClears,
diff --git a/editor/app/cleanup/lib/loadCleanup.ts b/editor/app/cleanup/lib/loadCleanup.ts
@@ -7,6 +7,8 @@ import {
type HeldAudio,
} from "yt-dlp-transcript-common/controller/channelSnapshot";
import { loadFailedTranscriptions } from "yt-dlp-transcript-common/controller/failedTranscriptions";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { isGateHeld } from "yt-dlp-transcript-common/lib/pauseGates";
// One channel's row in the cleanup ledger. The three reclaim estimates come
// straight from the snapshot's precomputed `cleanupBytes` (already net of
@@ -191,6 +193,17 @@ export async function loadCleanupSummary(
}
}
+ // A PAUSED SPEAKERS LANE CLEARS NOTHING ON ITS OWN. The snapshot's
+ // diarizationNeverClears is what the lane would never clear even when it
+ // runs; while it is held or disarmed, ALL of the awaiting-speakers hold is
+ // stuck until somebody presses Work through speakers. Applied here, at read
+ // time, because the lane's state is not in any snapshot.
+ const lane = getSettings();
+ if (!lane.autoQueue.backfill.enabled || isGateHeld(lane, "backfill")) {
+ heldBytes.diarizationNeverClears = heldBytes.awaitingDiarization;
+ heldCounts.diarizationNeverClears = heldCounts.awaitingDiarization;
+ }
+
return {
rows,
includedReclaimBytes,
diff --git a/editor/app/cleanup/page.tsx b/editor/app/cleanup/page.tsx
@@ -10,6 +10,13 @@ import { ReleaseLedger } from "./components/ReleaseLedger";
import { ChannelWorkTable } from "../components/channelWork/ChannelWorkTable";
import { sectionsFor } from "../components/channelWork/sections";
import { getActionableSummary } from "../lib/actionable/loadActionable";
+import { getChannelBriefs } from "../lib/requestCache";
+import { loadSpeakersReadout } from "yt-dlp-transcript-common/controller/speakersReadout";
+import { speakersReadoutLine } from "yt-dlp-transcript-common/lib/speakersReadout";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { isGateHeld } from "yt-dlp-transcript-common/lib/pauseGates";
+import { LaneActionButton } from "../components/lanes/LaneActionButton";
+import { workThroughSpeakersAction } from "../jobs/actions";
export const dynamic = "force-dynamic";
@@ -22,6 +29,12 @@ export default async function CleanupPage() {
// second way. The two cleanup sections are the only channel-work sections
// that belong to no operation: they are bytes, and bytes are this page.
const actionable = await getActionableSummary(paths);
+ // The Speakers lane's readout — the same line the lane card prints — beside
+ // the hold it is working down (the sieve's gate 4).
+ const speakers = await loadSpeakersReadout(paths, await getChannelBriefs(paths));
+ const settings = getSettings();
+ const speakersWorking =
+ settings.autoQueue.backfill.enabled && !isGateHeld(settings, "backfill");
const {
rows,
includedReclaimBytes,
@@ -120,6 +133,31 @@ export default async function CleanupPage() {
The hero answers "how much can I reclaim right now"; these two answer
the question an operator with weeks of queued GPU work actually has. */}
<HoldSieve summary={summary} />
+ <section
+ aria-label="speakers readout"
+ className="flex flex-wrap items-center gap-x-3 gap-y-2 rounded-xl border border-border bg-card px-5 py-3 text-sm"
+ >
+ <span className="font-medium">Speakers</span>
+ <span className="tabular-nums text-muted-foreground">
+ {speakersReadoutLine(speakers)}
+ </span>
+ {speakers.noFingerprintPossible > 0 && (
+ <span className="text-xs text-muted-foreground">
+ {speakers.noFingerprintPossible.toLocaleString("en-US")} diarized before
+ fingerprints, audio already gone: no fingerprint possible
+ </span>
+ )}
+ {!speakersWorking && speakers.waitingVideos > 0 && (
+ <LaneActionButton
+ label="Work through speakers"
+ glyph="⟳"
+ ariaLabel="work through speakers"
+ title="Arm the Speakers lane and lift its hold: every channel's speakers and voice fingerprints, one video at a time."
+ variant="idle"
+ action={workThroughSpeakersAction}
+ />
+ )}
+ </section>
<ReleaseLedger ledger={buildCleanupLedger(summary)} />
{!hasAnything ? (
diff --git a/editor/app/components/lanes/LaneDeck.tsx b/editor/app/components/lanes/LaneDeck.tsx
@@ -10,7 +10,12 @@ import { useSectionFrame } from "../../widget/components/WidgetSection";
import { LaneCard, type LaneControl } from "./LaneCard";
import { deriveLaneState, formatCount } from "yt-dlp-transcript-common/views/laneState";
import { pauseLaneControl } from "./pauseControl";
-import { armLaneAction, disarmLaneAction } from "../../jobs/actions";
+import {
+ armLaneAction,
+ disarmLaneAction,
+ pauseSpeakersAction,
+ workThroughSpeakersAction,
+} from "../../jobs/actions";
// The four lanes, and the ONLY place lane → server-action wiring lives. Rendered
// identically by the dashboard band and the monitor widget's controls section,
@@ -360,36 +365,40 @@ export function LaneDeck({
// queue key; it survives below only on the two controls that genuinely act on
// the shared queue, and the card now says what is in it.
const backfillGroup = backfill?.groupLabel ?? "Derived data";
+ // ONE CONTROL, for the operator's one decision about this lane: work through
+ // the speakers, or not now. It used to be a Run/Stop switch beside a
+ // Hold/Resume gate, and the two together had a state — armed and held — that
+ // read "running" while doing nothing, which is where "Run speaker work" went
+ // to idle at "holding". Work through speakers arms the lane AND lifts the
+ // hold; Pause holds it (the video in flight finishes) and leaves it armed, so
+ // pressing Work through speakers again — or a restart — resumes it. Disarming
+ // outright is the lane console's Stop, on its operation pages.
+ const backfillWorking = backfillArmed && !backfillHeld;
const backfillControls: LaneControl[] = backfillAvailable
? [
- backfillArmed
+ backfillWorking
? {
- key: "backfill-arm",
- label: "Stop the lane",
- glyph: "■",
- ariaLabel: "disarm backfill lane",
+ key: "speakers",
+ label: "Pause",
+ glyph: "❙❙",
+ ariaLabel: "pause speakers",
title:
- "Switch the backfill lane off and let its runner finish what it is holding. The video in flight completes; nothing already written is lost, and the lane's rules are left alone.",
+ "Hold the Speakers lane: the video in flight finishes and nothing new starts. It stays armed — Work through speakers picks up where it was.",
variant: "active",
- action: () => disarmLaneAction("backfill"),
+ action: () => pauseSpeakersAction(),
onChange: onSynced,
}
: {
- key: "backfill-arm",
- label: "Run the lane",
+ key: "speakers",
+ label: "Work through speakers",
glyph: "⟳",
- ariaLabel: "arm backfill lane",
+ ariaLabel: "work through speakers",
title:
- "Switch the backfill lane on and start its runner, on whatever its rules claim — every channel and every operation unless somebody has narrowed them. Survives a restart. The rules are on any of its operation pages.",
+ "Capture each video's speakers and voice fingerprints while its audio is still on disk, one video at a time beside transcription — and, with Clean after capture on, delete that audio once both are stored. Arms the lane and lifts its hold.",
variant: "idle",
- action: () => armLaneAction("backfill"),
+ action: () => workThroughSpeakersAction(),
onChange: onSynced,
},
- pauseLaneControl({
- lane: "backfill",
- held: backfillHeld,
- onChange: onSynced,
- }),
]
: [];
@@ -476,8 +485,19 @@ export function LaneDeck({
aria-label="backfill lane members"
className="block text-xs text-muted-foreground"
>
- {laneOperations.length} operations share one backfill queue and one
- pause: {laneOperations.map((k) => k.label).join(", ")}.
+ {laneOperations.length} operations share the Speakers lane and its
+ one control: {laneOperations.map((k) => k.label).join(", ")}.
+ </span>
+ )}
+ {backfillAvailable && backfill?.speakers && (
+ // THE READOUT, where the button is: what the lane is holding, what
+ // it has freed, how long is left (lib/speakersReadout.ts — the same
+ // line /cleanup and `pnpm ops get speakers` print).
+ <span
+ aria-label="speakers readout"
+ className="block text-xs tabular-nums text-muted-foreground"
+ >
+ {backfill.speakers.line}
</span>
)}
{backfillArmed && backfillHeld && (
diff --git a/editor/app/jobs/actions.ts b/editor/app/jobs/actions.ts
@@ -4,6 +4,10 @@ import { revalidatePath } from "next/cache";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
import { saveSettings } from "../settings/saveSettings";
+import { startSpeakersRun } from "yt-dlp-transcript-common/lib/speakersLedger-server";
+import { pauseLaneAction, resumeLaneAction } from "../operations/actions";
+import { readRenderPriority } from "yt-dlp-transcript-common/lib/renderPriority.mjs";
+import { renderModeFile } from "../operations/renderMode";
import { laneRootFromScope } from "yt-dlp-transcript-common/lib/laneMigration";
import { isDefaultChannelPriority } from "yt-dlp-transcript-common/lib/channelPriority";
import { operationsForLane } from "yt-dlp-transcript-common/lib/operations";
@@ -332,3 +336,61 @@ export async function endRenderModeAction(): Promise<{ ok: boolean; error?: stri
? { ok: false, error: `not released: ${r.failed.map((f) => `${f.lane} (${f.error})`).join(", ")}` }
: { ok: true };
}
+
+// THE SPEAKERS LANE'S ONE CONTROL (the lane deck's "Work through speakers").
+//
+// Arms the backfill lane AND lifts its hold, in that order of need — the two
+// switches the deck used to draw as a separate Run and Hold pair, which left a
+// lane that read "running" while held, and a "Run speaker work" that idled at
+// "holding". Pressed on a lane that was not already working (disarmed or held)
+// it also starts a new speakers run: the readout's "freed this run" counts from
+// here (lib/speakersLedger-server.ts).
+export async function workThroughSpeakersAction(): Promise<ArmLaneResult> {
+ try {
+ const refusal = speakersWorkRefusal();
+ if (refusal) return { ok: false, error: refusal };
+ const before = getSettings().autoQueue.backfill;
+ const wasWorking = before.enabled && before.held !== true;
+ if (before.held === true) {
+ const resumed = await resumeLaneAction("backfill");
+ if (!resumed.ok) return { ok: false, error: resumed.error };
+ }
+ const armed = await armLaneAction("backfill");
+ if (!armed.ok) return armed;
+ if (!wasWorking) await startSpeakersRun(getPaths());
+ revalidatePath("/cleanup");
+ return armed;
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+}
+
+// WHY THE ONE CONTROL MAY NOT START THE LANE, or null. Two refusals, both
+// one sentence (review): an un-narrowed backfill lane is every speaker
+// operation — the text-only naming pass over ~97,000 videos on the local model
+// among them — so "Work through speakers" must mean speakers only, and says how
+// to narrow it; and a lane render mode holds is the render's, released when the
+// render ends — lifting it here would take the cores back from the render.
+function speakersWorkRefusal(): string | null {
+ const ops = getSettings().autoQueue.backfill.operations ?? [];
+ if (!(ops.length === 1 && ops[0] === "diarization")) {
+ return (
+ "The Speakers lane is not narrowed to speaker diarization, so it would also run the naming passes — narrow it first: " +
+ `pnpm ops lane --json '{"lane":"backfill","operations":["diarization"]}' (autoQueue.backfill.operations).`
+ );
+ }
+ const render = readRenderPriority(renderModeFile());
+ if (render.held && render.state?.lanesHeld?.includes("backfill")) {
+ const by = render.state.holder?.cmd ?? render.state.note ?? "render mode";
+ return `A render holds the Speakers lane (${by}); it is released when the render ends — see umtool render-mode status.`;
+ }
+ return null;
+}
+
+// "Pause": the gate, not the switch. The video in flight finishes; the lane
+// stays armed, so Work through speakers (or a restart) resumes where it was.
+export async function pauseSpeakersAction(): Promise<ArmLaneResult> {
+ const out = await pauseLaneAction("backfill");
+ revalidatePath("/cleanup");
+ return out.ok ? { ok: true } : { ok: false, error: out.error };
+}
diff --git a/editor/app/operations/actions.ts b/editor/app/operations/actions.ts
@@ -23,6 +23,7 @@ import {
type AutoQueueOrder,
} from "yt-dlp-transcript-common/jobs/autoQueuePolicy";
import { isDefaultChannelPriority } from "yt-dlp-transcript-common/lib/channelPriority";
+import { operationsForLane } from "yt-dlp-transcript-common/lib/operations";
import { prioritizeChannelDownloadPriorityAction } from "../channels/actions";
// EVERY OPERATIONS SURFACE, not just the board. The console is a board plus one
@@ -105,6 +106,11 @@ export async function saveAutoQueueAction(
order: input.order,
snoozeUntil: current.autoQueue[kind].snoozeUntil ?? null,
held: current.autoQueue[kind].held,
+ // The lane-wide operation narrowing is set in settings (ops settings),
+ // not by this form: carried like `held`, never dropped by a save.
+ ...(current.autoQueue[kind].operations
+ ? { operations: current.autoQueue[kind].operations }
+ : {}),
root: compiled ? current.autoQueue[kind].root : input.root,
},
},
@@ -277,3 +283,62 @@ export async function prioritizeChannelDownloadAction(
revalidateOperations();
return { ok: true };
}
+
+// A lane's DISPATCH SCOPE outside its tree: the operation narrowing
+// (`autoQueue.<lane>.operations`, null clears it) and the `order`. Written
+// through the stored policy, every other field as stored — the tree is not
+// touched, so this works while a channel-priority document compiles the roots.
+// The narrowing names operations this lane dispatches, or it is refused: a
+// lane narrowed to nothing would hold at zero forever.
+export async function setLaneScopeAction(
+ kind: AutoQueueKind,
+ input: { operations?: string[] | null; order?: AutoQueueOrder },
+): Promise<{ ok: boolean; error?: string }> {
+ try {
+ const current = getSettings();
+ const policy = current.autoQueue[kind];
+ let operations = policy.operations;
+ if (input.operations !== undefined) {
+ if (input.operations === null || input.operations.length === 0) {
+ operations = undefined;
+ } else {
+ // Against the lane's operations WITHOUT the stored narrowing, so a
+ // narrowed lane can be widened again.
+ const known = new Set(
+ operationsForLane(kind, {
+ ...current,
+ autoQueue: { ...current.autoQueue, [kind]: { ...policy, operations: undefined } },
+ }).map((o) => o.id),
+ );
+ const unknown = input.operations.filter((id) => !known.has(id));
+ if (unknown.length > 0) {
+ return {
+ ok: false,
+ error: `Not an enabled operation on the ${kind} lane: ${unknown.join(", ")} (it has ${[...known].join(", ") || "none"}).`,
+ };
+ }
+ operations = [...new Set(input.operations)];
+ }
+ }
+ const { operations: _drop, ...rest } = policy;
+ void _drop;
+ await saveSettings({
+ autoQueue: {
+ ...current.autoQueue,
+ [kind]: {
+ ...rest,
+ ...(operations ? { operations } : {}),
+ ...(input.order !== undefined ? { order: input.order } : {}),
+ },
+ },
+ });
+ try {
+ revalidateOperations();
+ } catch {
+ /* outside a request (a unit test of the ops route): nothing to revalidate */
+ }
+ return { ok: true };
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+}
diff --git a/editor/app/operations/components/dispatch.ts b/editor/app/operations/components/dispatch.ts
@@ -76,6 +76,9 @@ export const ORDER_LABEL: Record<AutoQueueOrder, string> = {
// The digest lane's shortest-first. Named by DURATION, not by date, which is
// why it is not a third arm of the recency axis.
cheapest: "Shortest first",
+ // The Speakers lane's: corpus-disk channels first, then the most audio freed
+ // per hour of work.
+ space: "Most space freed first",
};
// THE ORDERS A DATE-KEYED LANE OFFERS — the three this control has always
@@ -104,7 +107,7 @@ export const LANE_ORDERS: Record<
transcription: RECENCY_ORDERS,
download: RECENCY_ORDERS,
digest: [...RECENCY_ORDERS, "cheapest"],
- backfill: RECENCY_ORDERS,
+ backfill: [...RECENCY_ORDERS, "space"],
};
// The runner console's heading, per lane. PINNED: the e2e suite scopes whole
@@ -123,7 +126,7 @@ export function orderTradeoff(
): string | null {
// Neither of these reorders by upload date, so neither costs a retry or a
// partial download its head start.
- if (order === "listed" || order === "cheapest") return null;
+ if (order === "listed" || order === "cheapest" || order === "space") return null;
// The trade-off named below is a DOWNLOAD/TRANSCRIPTION one — a retry or a
// partial losing its head start. The operation lanes have no retry bucket and
// no partial state to lose, so there is nothing to warn about.
diff --git a/editor/app/operations/components/settings/DiarizationSettingsForm.tsx b/editor/app/operations/components/settings/DiarizationSettingsForm.tsx
@@ -75,15 +75,57 @@ export function DiarizationSettingsForm({
</span>
<span className="text-xs text-muted-foreground">
Off by default, from measurement rather than caution. On this box
- transcription runs at ~221 s per audio-hour on the GPU (16× real
- time, over 3,602 videos); diarization runs on the CPU at roughly
- 500–680, because no diarization model has been ported to ggml and
- neither ONNX nor PyTorch has a Vulkan path on Linux. Inline
- therefore makes the whole pipeline ~3–4× slower and idles the GPU.
+ transcription runs at ~221 s per audio-hour on the GPU; the
+ sherpa-onnx engine diarizes on the CPU at roughly 500–680, so
+ inline makes the whole pipeline ~3–4× slower and idles the GPU.
For a large batch, leave this off, let transcription run at full
speed with the box above holding the audio, and catch up
- afterwards with <strong>Diarize speakers</strong> on each channel.
- Turn it on for steady state.
+ beside it with <strong>Work through speakers</strong> on the
+ Speakers lane. Turn it on for steady state.
+ </span>
+ </span>
+ </label>
+ <label className="flex items-start gap-2 text-sm">
+ <input
+ type="checkbox"
+ name="diarizationRequireVoiceprints"
+ defaultChecked={seedChecked(
+ state,
+ "diarizationRequireVoiceprints",
+ initial.requireVoiceprints,
+ )}
+ className="mt-1"
+ />
+ <span className="flex flex-col gap-1">
+ <span className="font-medium">
+ Keep the audio until its voice fingerprints are stored
+ </span>
+ <span className="text-xs text-muted-foreground">
+ A fingerprint (one per speaker, in <code>diarization.json</code>)
+ cannot be made once the audio is gone, so Clean audio skips a
+ diarized video without them — "awaiting voice
+ fingerprint" — until the Speakers lane adds them.
+ </span>
+ </span>
+ </label>
+ <label className="flex items-start gap-2 text-sm">
+ <input
+ type="checkbox"
+ name="diarizationCleanAfterCapture"
+ defaultChecked={seedChecked(
+ state,
+ "diarizationCleanAfterCapture",
+ initial.cleanAfterCapture,
+ )}
+ className="mt-1"
+ />
+ <span className="flex flex-col gap-1">
+ <span className="font-medium">Clean after capture</span>
+ <span className="text-xs text-muted-foreground">
+ Delete a video's audio as soon as the Speakers lane has stored
+ its speakers and fingerprints — through every Clean audio gate
+ (keep-latest, do not clean, the availability check). The bytes
+ freed show on the Speakers lane and on /cleanup.
</span>
</span>
</label>
diff --git a/editor/app/operations/renderMode.ts b/editor/app/operations/renderMode.ts
@@ -28,7 +28,7 @@ import { saveSettings } from "../settings/saveSettings";
// this checkout's git common dir (the editor runs from editor/), or
// RENDER_PRIORITY_FILE — the e2e servers set their own.
-type RenderLane = "transcription" | "download";
+type RenderLane = "transcription" | "download" | "backfill";
export function renderModeFile(): string {
return renderPriorityFile(process.env, { root: process.cwd() });
diff --git a/editor/app/operations/settingsActions.ts b/editor/app/operations/settingsActions.ts
@@ -155,6 +155,9 @@ export async function saveDiarizationSettingsAction(
enabled: formData.get("diarizationEnabled") === "on",
inlineAfterTranscribe:
formData.get("diarizationInlineAfterTranscribe") === "on",
+ requireVoiceprints:
+ formData.get("diarizationRequireVoiceprints") === "on",
+ cleanAfterCapture: formData.get("diarizationCleanAfterCapture") === "on",
threshold: num(formData, "diarizationThreshold", dDiar.threshold),
threads: num(formData, "diarizationThreads", dDiar.threads),
concurrency: num(formData, "diarizationConcurrency", dDiar.concurrency),
diff --git a/editor/app/widget/lib/syncInputs.ts b/editor/app/widget/lib/syncInputs.ts
@@ -3,6 +3,7 @@ import { getSettings } from "yt-dlp-transcript-common/lib/settings";
import { readSchedulerState } from "yt-dlp-transcript-common/jobs/syncSchedulerState";
import type { WidgetSyncInputs } from "yt-dlp-transcript-common/views/widgetSync";
import { getChannelBriefs } from "../../lib/requestCache";
+import { readSpeakersLedger } from "yt-dlp-transcript-common/lib/speakersLedger-server";
// THE READS BEHIND THE WIDGET'S SYNC STRIP.
//
@@ -18,9 +19,10 @@ import { getChannelBriefs } from "../../lib/requestCache";
// of the three.
export async function widgetSyncInputs(): Promise<WidgetSyncInputs> {
const paths = getPaths();
- const [state, briefs] = await Promise.all([
+ const [state, briefs, speakersLedger] = await Promise.all([
readSchedulerState(paths),
getChannelBriefs(paths),
+ readSpeakersLedger(paths),
]);
- return { settings: getSettings(), now: Date.now(), state, briefs };
+ return { settings: getSettings(), now: Date.now(), state, briefs, speakersLedger };
}
diff --git a/editor/e2e/backfill.spec.ts b/editor/e2e/backfill.spec.ts
@@ -97,6 +97,12 @@ function backfillSettings(over: {
};
}
+// The Speakers lane narrowed to diarization — what Work through speakers
+// requires before it will start the lane (it refuses an un-narrowed one).
+function speakersOnly<T extends { autoQueue: { backfill: Record<string, unknown> } }>(s: T): T {
+ return { ...s, autoQueue: { ...s.autoQueue, backfill: { ...s.autoQueue.backfill, operations: ["diarization"] } } };
+}
+
async function seedTranscript(videoId: string): Promise<void> {
await writeFile(
resolvePath(dataRel(videoId, "transcript.json")),
@@ -136,6 +142,22 @@ async function laneArmed(): Promise<boolean> {
return (await backfillLane()).enabled ?? false;
}
+async function laneHeldNow(): Promise<boolean> {
+ return ((await backfillLane()) as { held?: boolean }).held ?? false;
+}
+
+// Disarm through `pnpm ops lane`, so an armed lane does not bleed into the next
+// spec. The deck no longer draws a disarm: its one control is Work through
+// speakers / Pause, and switching the lane off is the console's (and ops').
+async function disarmLane(request: APIRequestContext): Promise<void> {
+ const res = await request.post(`${baseUrl}/api/ops/lane`, {
+ headers: { authorization: "Bearer test-worker-token" },
+ data: { lane: "backfill", enabled: false },
+ });
+ expect(res.status()).toBe(200);
+ await expect.poll(laneArmed, { timeout: 30_000 }).toBe(false);
+}
+
const SLOW = 120_000;
// (1) The stage card reports the two populations SEPARATELY.
@@ -396,40 +418,36 @@ test("the disk floor refuses to re-acquire anything", async ({ page }) => {
// in the same settings write as the switch — so what has to be pinned instead is
// the other half of that: disarming must NOT clear the tree, because an operator
// authored it and switching a lane off is not throwing it away.
-test("the lane arms from the dashboard and disarms without losing its rules", async ({
+test("Work through speakers arms the lane AND lifts its hold, keeping its rules", async ({
page,
+ request,
}) => {
test.setTimeout(SLOW);
await resetData("one-transcribe-channel-with-audio");
- await writeSettings(backfillSettings());
+ // Disarmed AND held — the state the live lane shipped in, two switches off.
+ await writeSettings({ ...backfillSettings(), autoQueue: { backfill: { held: true, operations: ["diarization"] } } });
await page.goto("/");
- const arm = page.getByRole("button", { name: "arm backfill lane" });
- await expect(arm).toBeEnabled({ timeout: 30_000 });
- await arm.click();
+ const work = page.getByRole("button", { name: "work through speakers" });
+ await expect(work).toBeEnabled({ timeout: 30_000 });
+ // ONE control: the Run/Hold pair is gone from the deck.
+ for (const name of ["arm backfill lane", "disarm backfill lane", "pause backfill", "resume backfill"]) {
+ await expect(page.getByRole("button", { name })).toHaveCount(0);
+ }
+ await work.click();
- await expect.poll(laneArmed, { timeout: 30_000 }).toBe(true);
- // An unscoped arm is one catch-all leaf — what an empty `sweepChannels` meant.
+ await expect
+ .poll(async () => ({ armed: await laneArmed(), held: await laneHeldNow() }), { timeout: 30_000 })
+ .toEqual({ armed: true, held: false });
+ // An unscoped arm keeps the one catch-all leaf — what an empty `sweepChannels` meant.
expect(
(await backfillLane()).root?.children?.map((c) => c.match),
).toEqual([{ type: "all" }]);
+ // And the control becomes its reverse.
+ await expect(page.getByRole("button", { name: "pause speakers" })).toBeEnabled({ timeout: 30_000 });
- const disarm = page.getByRole("button", { name: "disarm backfill lane" });
- await expect(disarm).toBeEnabled({ timeout: 30_000 });
- await disarm.click();
-
- await expect
- .poll(
- async () => {
- const lane = await backfillLane();
- return {
- enabled: lane.enabled ?? false,
- rules: lane.root?.children?.length ?? 0,
- };
- },
- { timeout: 30_000 },
- )
- .toEqual({ enabled: false, rules: 1 });
+ await disarmLane(request);
+ expect((await backfillLane()).root?.children?.length ?? 0).toBe(1);
// The sweep's own controls are gone from this surface, not merely relabelled
// — BOTH halves, and both aria-labels, because the deck drew whichever half
@@ -540,10 +558,10 @@ test("a lane can be scoped to one operation from its console, and the scope is a
test("an armed lane comes back after a restart", async ({ page, request }) => {
test.setTimeout(SLOW);
await resetData("one-transcribe-channel-with-audio");
- await writeSettings(backfillSettings());
+ await writeSettings(speakersOnly(backfillSettings()));
await page.goto("/");
- const arm = page.getByRole("button", { name: "arm backfill lane" });
+ const arm = page.getByRole("button", { name: "work through speakers" });
await expect(arm).toBeEnabled({ timeout: 30_000 });
await arm.click();
await expect.poll(laneArmed, { timeout: 30_000 }).toBe(true);
@@ -561,11 +579,7 @@ test("an armed lane comes back after a restart", async ({ page, request }) => {
expect(body.resumed).not.toBe(body.cancelled);
// Clean up, so an armed lane does not bleed into the next spec.
- await page.goto("/");
- const disarm = page.getByRole("button", { name: "disarm backfill lane" });
- await expect(disarm).toBeEnabled({ timeout: 30_000 });
- await disarm.click();
- await expect.poll(laneArmed, { timeout: 30_000 }).toBe(false);
+ await disarmLane(request);
});
// (9) THE WHOLE POINT OF THE SEPARATE QUEUE KEY: a backfill job and a
@@ -795,39 +809,33 @@ test("the diarization page shows the channel and both populations", async ({
// not just the label, for exactly that reason. It also asserts the button
// renders WITHOUT a sweep armed — an operator pauses a hand-clicked
// backfill-channel job too, not only an armed lane.
-test("the dashboard pauses and resumes the backfill lane", async ({ page }) => {
+test("the dashboard's one control: Pause holds the lane and leaves it armed; Work through speakers lifts the hold", async ({
+ page,
+ request,
+}) => {
test.setTimeout(SLOW);
await resetData("one-transcribe-channel-with-audio");
- await writeSettings(backfillSettings());
-
- // THE LANE'S GATE, on the lane. Slice 1.4 moved it off the inverted
- // `backfill.enabled` (deleted by S0-pause) and onto
- // `autoQueue.backfill.held`, so the polarity here is the plain one: held
- // means held.
- const laneHeld = async () =>
- (
- await readJson<{ autoQueue?: { backfill?: { held?: boolean } } }>(
- testPaths().settingsFile,
- ).catch(() => ({}) as { autoQueue?: { backfill?: { held?: boolean } } })
- ).autoQueue?.backfill?.held ?? false;
+ await writeSettings(speakersOnly(backfillSettings()));
await page.goto("/");
- const pause = page.getByRole("button", { name: "pause backfill" });
+ await page.getByRole("button", { name: "work through speakers" }).click();
+ await expect.poll(laneArmed, { timeout: 30_000 }).toBe(true);
+
+ const pause = page.getByRole("button", { name: "pause speakers" });
await expect(pause).toBeEnabled({ timeout: 30_000 });
await pause.click();
-
- await expect.poll(laneHeld, { timeout: 30_000 }).toBe(true);
-
- // THE LANE'S ARM SWITCH IS UNTOUCHED: pausing must not disarm the lane, or
- // "pause" would quietly become "stop" and days of queued work would need
- // re-arming. (The fixture leaves it disarmed, so `false` is what "unchanged"
- // looks like here.)
- expect(await laneArmed()).toBe(false);
-
- const resume = page.getByRole("button", { name: "resume backfill" });
- await expect(resume).toBeEnabled({ timeout: 30_000 });
- await resume.click();
- await expect.poll(laneHeld, { timeout: 30_000 }).toBe(false);
+ // THE LANE'S GATE (`autoQueue.backfill.held`), not its switch: a pause is
+ // not a stop, or days of queued work would need re-arming.
+ await expect.poll(laneHeldNow, { timeout: 30_000 }).toBe(true);
+ expect(await laneArmed()).toBe(true);
+
+ const work = page.getByRole("button", { name: "work through speakers" });
+ await expect(work).toBeEnabled({ timeout: 30_000 });
+ await work.click();
+ await expect.poll(laneHeldNow, { timeout: 30_000 }).toBe(false);
+ expect(await laneArmed()).toBe(true);
+
+ await disarmLane(request);
});
// ONE GATE, TWO SURFACES. /operations/diarization and the dashboard draw the
@@ -841,10 +849,11 @@ test("the dashboard pauses and resumes the backfill lane", async ({ page }) => {
// surfaces disagreeing about which lane they hold.
test("an operation page holds the same lane the dashboard does", async ({
page,
+ request,
}) => {
test.setTimeout(SLOW);
await resetData("one-transcribe-channel-with-audio");
- await writeSettings(backfillSettings());
+ await writeSettings(speakersOnly(backfillSettings()));
// THE LANE'S GATE, on the lane. Slice 1.4 moved it off the inverted
// `backfill.enabled` (deleted by S0-pause) and onto
@@ -870,14 +879,16 @@ test("an operation page holds the same lane the dashboard does", async ({
// A hold is not a stop: the lane's arm switch is untouched.
expect(await laneArmed()).toBe(false);
- // The dashboard shows the same lane held, and releases it.
+ // The dashboard shows the same lane NOT working, and its one control lifts
+ // the hold (and arms the lane: the deck has one switch for both).
await page.goto("/");
- const resumeOnDashboard = page.getByRole("button", {
- name: "resume backfill",
+ const workOnDashboard = page.getByRole("button", {
+ name: "work through speakers",
});
- await expect(resumeOnDashboard).toBeEnabled({ timeout: 30_000 });
- await resumeOnDashboard.click();
+ await expect(workOnDashboard).toBeEnabled({ timeout: 30_000 });
+ await workOnDashboard.click();
await expect.poll(laneHeld, { timeout: 30_000 }).toBe(false);
+ await disarmLane(request);
});
// (11) THE RE-DOWNLOAD ON A SUBTITLE CHANNEL: audio, not captions.
diff --git a/editor/e2e/cleanup-holds.spec.ts b/editor/e2e/cleanup-holds.spec.ts
@@ -90,7 +90,16 @@ test("the sieve attributes every held byte to exactly one gate, and names the ho
await seedTranscript("vidD");
await writeFile(
resolvePath(dataRel("vidD", "diarization.json")),
- JSON.stringify({ segments: [], engine: "test", createdAt: "2026-01-01" }),
+ // A COMPLETE sidecar — turns and voice fingerprints — which is what the
+ // sweep's gate (and so the snapshot's) needs to call a video diarized.
+ JSON.stringify({
+ videoId: "vidD",
+ generatedAt: "2026-01-01T00:00:00.000Z",
+ speakers: 1,
+ turns: [{ start: 0, end: 1, speaker: 0 }],
+ engine: { engine: "test" },
+ voiceprints: [{ speaker: 0, seconds: 1, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "t" }],
+ }),
);
await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
diff --git a/editor/e2e/diarization.spec.ts b/editor/e2e/diarization.spec.ts
@@ -34,7 +34,13 @@ async function seedTranscript(videoId: string): Promise<void> {
);
}
-async function seedDiarization(videoId: string): Promise<void> {
+// With voice fingerprints by default (what "diarized" means since
+// diarization.requireVoiceprints); `voiceprints: false` is a sidecar written
+// before they existed.
+async function seedDiarization(
+ videoId: string,
+ { voiceprints = true }: { voiceprints?: boolean } = {},
+): Promise<void> {
await writeFile(
resolvePath(dataRel(videoId, "diarization.json")),
JSON.stringify({
@@ -43,6 +49,13 @@ async function seedDiarization(videoId: string): Promise<void> {
speakers: 1,
turns: [{ start: 0, end: 10, speaker: 0 }],
engine: { engine: "fake-diarize", threshold: 0.5 },
+ ...(voiceprints
+ ? {
+ voiceprints: [
+ { speaker: 0, seconds: 10, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "null" },
+ ],
+ }
+ : {}),
}) + "\n",
);
}
diff --git a/editor/e2e/fixtures/bin/fake-diarize.mjs b/editor/e2e/fixtures/bin/fake-diarize.mjs
@@ -18,7 +18,14 @@
// vidC is the designated failing id because it is already in the shared
// one-transcribe-channel-with-audio fixture's archive; a spec can exercise the
// failure path without renaming dirs into ids the batch would never pick up.
-import { writeFile } from "node:fs/promises";
+//
+// VOICEPRINTS, as the real wrapper now writes them: one per speaker, with the
+// embedding model's basename. A dir containing "novoiceprint" gets a record
+// WITHOUT them (what every sidecar written before them looks like).
+// `--voiceprints-only <record>` is the wrapper's voiceprint step: it adds them
+// to the record it is given, keeping everything else, and writes --output (or
+// the record itself).
+import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { installFixtureWatchdog } from "./_watchdog.mjs";
@@ -31,7 +38,8 @@ function arg(flag) {
return i < 0 ? undefined : argv[i + 1];
}
-const out = arg("--output") ?? arg("-o");
+const voiceprintsOnly = arg("--voiceprints-only");
+const out = arg("--output") ?? arg("-o") ?? voiceprintsOnly;
const videoId = arg("--video-id") ?? path.basename(process.cwd());
const seg = arg("--seg");
const emb = arg("--emb");
@@ -52,6 +60,24 @@ if (
process.exit(3);
}
+const voiceprintsFor = (turns) =>
+ [...new Set(turns.map((t) => t.speaker))].sort((a, b) => a - b).map((speaker) => ({
+ speaker,
+ seconds: turns.filter((t) => t.speaker === speaker).reduce((s, t) => s + (t.end - t.start), 0),
+ embedded: 1,
+ centroid: Array.from({ length: 192 }, (_, i) => (i === speaker ? 1 : 0)),
+ embeddingModel: emb ? path.basename(emb) : "fake.onnx",
+ }));
+
+if (voiceprintsOnly) {
+ const record = JSON.parse(await readFile(voiceprintsOnly, "utf8"));
+ record.voiceprints = voiceprintsFor(record.turns ?? []);
+ record.voiceprintsAt = new Date().toISOString();
+ await writeFile(out, JSON.stringify(record) + "\n");
+ process.stderr.write(`[fake-diarize] voiceprints for ${record.voiceprints.length} speaker(s) -> ${out}\n`);
+ process.exit(0);
+}
+
const turns = [
{ start: 0, end: 4.5, speaker: 0 },
{ start: 4.5, end: 7.25, speaker: 1 },
@@ -74,6 +100,9 @@ await writeFile(
version: "e2e",
threshold,
},
+ ...(cwd.toLowerCase().includes("novoiceprint")
+ ? {}
+ : { voiceprints: voiceprintsFor(turns), voiceprintsAt: new Date().toISOString() }),
}) + "\n",
);
process.stderr.write(
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/maybe-missing.spec.ts b/editor/e2e/maybe-missing.spec.ts
@@ -124,6 +124,14 @@ test("quick check flags videos missing from the fresh playlist", async ({
`${channelRoot}/maybe-missing.json`,
);
expect(record.ids.sort()).toEqual(["viddeleted1", "vidunlisted1"].sort());
+ // …and what the listing NAMED, with when: the verdict cache
+ // clean-after-capture reads instead of listing the channel itself.
+ const verdict = await readJson<{ checkedAt: string; ids: string[] }>(
+ `${channelRoot}/availability-verdict.json`,
+ );
+ expect(verdict.ids).toContain(BASELINE_IDS.find((id) => id !== "viddeleted1")!);
+ expect(verdict.ids).not.toContain("viddeleted1");
+ expect(Date.now() - Date.parse(verdict.checkedAt)).toBeLessThan(10 * 60_000);
// The job arms a debounced (~1s) snapshot regen that re-surfaces the
// maybe-missing set into snapshot.json. Wait for it before reloading.
diff --git a/editor/e2e/speakers-run.spec.ts b/editor/e2e/speakers-run.spec.ts
@@ -0,0 +1,238 @@
+import { writeFile } from "node:fs/promises";
+import { test, expect } from "@playwright/test";
+import {
+ channelStage,
+ generateReport,
+ pathExists,
+ readJson,
+ resetData,
+ resolvePath,
+ writeSettings,
+ testPaths,
+} from "./helpers";
+import { baseUrl } from "./baseUrl";
+
+// "Work through speakers" (lane/speakers-run): the Speakers lane's one
+// control, the voice fingerprints a sidecar must carry before its audio may go,
+// clean-after-capture, and the readout on the lane card, the Cleanup stage and
+// /cleanup. The engine is the fake DIARIZE_BIN (e2e/fixtures/bin/
+// fake-diarize.mjs): voiceprints by default, `--voiceprints-only` as the
+// wrapper's voiceprint step.
+
+const SLUG = "test-transcribe";
+const AUTH = { authorization: "Bearer test-worker-token" };
+const SLOW = 120_000;
+
+function dataRel(videoId: string, file: string): string {
+ return `${testPaths().transcriptsDir}/channels/${SLUG}/data/${videoId}/${file}`;
+}
+
+// The channel's availability verdict (availability-verdict.json beside its
+// config) — what the Quick check writes after a listing, and the only thing
+// clean after capture trusts: `ids` named by a listing at `checkedAt`, and the
+// last check it asked for.
+async function seedVerdict(v: { checkedAt: string | null; ids: string[]; requestedAt?: string }): Promise<void> {
+ await writeFile(
+ resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}/availability-verdict.json`),
+ JSON.stringify({ version: 1, ...v }) + "\n",
+ );
+}
+
+async function seedTranscript(videoId: string): Promise<void> {
+ await writeFile(resolvePath(dataRel(videoId, "transcript.json")), '{"transcription":[{"text":"hi"}]}\n');
+}
+
+// A FRESH sidecar (the identity the settings below produce) from before
+// voiceprints existed.
+async function seedPlainDiarization(videoId: string): Promise<void> {
+ await writeFile(
+ resolvePath(dataRel(videoId, "diarization.json")),
+ JSON.stringify({
+ videoId,
+ generatedAt: "2026-08-07T00:00:00.000Z",
+ audioSeconds: 10,
+ durationMs: 1000,
+ speakers: 1,
+ turns: [{ start: 0, end: 10, speaker: 0 }],
+ engine: { engine: "fake-diarize", segmentationModel: "null", embeddingModel: "null", threshold: 0.5 },
+ }) + "\n",
+ );
+}
+
+function settings(over: { held?: boolean; narrowed?: boolean; diarization?: Record<string, unknown> } = {}) {
+ return {
+ adminTitle: "Test Admin",
+ maxTranscriptPageBytes: 8388608,
+ sleepBetweenDownloadsSeconds: 0,
+ minFreeDiskGB: 0,
+ verifyAvailabilityBeforeClean: false,
+ syncScheduler: { fullSweepIntervalMinutes: 0 },
+ diarization: {
+ enabled: true,
+ inlineAfterTranscribe: false,
+ threshold: 0.5,
+ threads: 1,
+ python: "python3",
+ segModel: "/dev/null",
+ embModel: "/dev/null",
+ concurrency: 1,
+ ...over.diarization,
+ },
+ backfill: { concurrency: 1, allowRedownload: false },
+ autoQueue: { backfill: { held: over.held ?? false, ...(over.narrowed === false ? {} : { operations: ["diarization"] }) } },
+ };
+}
+
+type Lane = { enabled?: boolean; held?: boolean };
+async function lane(): Promise<Lane> {
+ const s = await readJson<{ autoQueue?: { backfill?: Lane } }>(testPaths().settingsFile).catch(
+ () => ({}) as { autoQueue?: { backfill?: Lane } },
+ );
+ return s.autoQueue?.backfill ?? {};
+}
+
+test.afterEach(async ({ request }) => {
+ // Never leave an armed lane for the next spec.
+ await request.post(`${baseUrl}/api/ops/lane`, { headers: AUTH, data: { lane: "backfill", enabled: false } });
+});
+
+test("a paused Speakers lane: the stage says Run speaker work waits for it, and offers the lane's one control", async ({ page }) => {
+ test.setTimeout(SLOW);
+ await resetData("one-transcribe-channel-with-audio");
+ await writeSettings(settings({ held: true }));
+ await seedTranscript("vidA");
+ await generateReport(page, SLUG);
+
+ await page.goto(channelStage(SLUG, "speakers"));
+ const paused = page.getByLabel("speakers lane paused");
+ await expect(paused).toContainText("The Speakers lane is paused, so Run speaker work waits for it.", { timeout: 30_000 });
+ const work = paused.getByRole("button", { name: "work through speakers" });
+ await expect(work).toBeEnabled({ timeout: 30_000 });
+ await work.click();
+ await expect.poll(async () => ({ held: (await lane()).held, armed: (await lane()).enabled }), { timeout: 30_000 }).toEqual({ held: false, armed: true });
+});
+
+test("a sidecar without voice fingerprints keeps its audio until Diarize speakers adds them from its own turns", async ({ page }) => {
+ test.setTimeout(SLOW);
+ await resetData("one-transcribe-channel-with-audio");
+ await writeSettings(settings());
+ await seedTranscript("vidA");
+ await seedPlainDiarization("vidA");
+ await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
+ await generateReport(page, SLUG);
+
+ await page.goto(channelStage(SLUG, "cleanup"));
+ await page.getByRole("button", { name: "Clean audio", exact: true }).click();
+ await expect(page.getByLabel("Clean audio output")).toContainText("awaiting voice fingerprint", { timeout: 30_000 });
+ expect(await pathExists(dataRel("vidA", "audio.m4a"))).toBe(true);
+
+ await page.getByRole("button", { name: "Diarize speakers", exact: true }).click();
+ await expect
+ .poll(
+ async () => {
+ const r = await readJson<{ generatedAt: string; voiceprints?: unknown[] }>(dataRel("vidA", "diarization.json")).catch(() => null);
+ return r ? { generatedAt: r.generatedAt, voiceprints: r.voiceprints?.length ?? 0 } : null;
+ },
+ { timeout: 60_000 },
+ )
+ // The same turns' sidecar — generatedAt kept — now with its fingerprint.
+ .toEqual({ generatedAt: "2026-08-07T00:00:00.000Z", voiceprints: 1 });
+
+ await page.goto(channelStage(SLUG, "cleanup"));
+ await page.getByRole("button", { name: "Clean audio", exact: true }).click();
+ await expect(page.getByLabel("Clean audio output")).toContainText("Cleaned 1 audio file", { timeout: 30_000 });
+ expect(await pathExists(dataRel("vidA", "audio.m4a"))).toBe(false);
+});
+
+test("clean after capture: Run speaker work removes a captured video's audio at once, and the readout counts it", async ({ page, request }) => {
+ test.setTimeout(SLOW);
+ await resetData("one-transcribe-channel-with-audio");
+ await writeSettings(settings({ diarization: { cleanAfterCapture: true } }));
+ await seedTranscript("vidA");
+ // The channel was listed an hour ago by its Quick check, and the listing named
+ // vidA: the one verdict clean after capture deletes on.
+ await seedVerdict({ checkedAt: new Date(Date.now() - 3_600_000).toISOString(), ids: ["vidA", "vidB", "vidC"] });
+ await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
+ await generateReport(page, SLUG);
+
+ const before = await request.get(`${baseUrl}/api/ops/speakers`, { headers: AUTH });
+ expect(before.status()).toBe(200);
+ const freedBefore = ((await before.json()) as { freedVideos: number }).freedVideos;
+
+ await page.goto(channelStage(SLUG, "speakers"));
+ await page.getByRole("button", { name: "Run speaker work", exact: true }).click();
+ await expect.poll(async () => pathExists(dataRel("vidA", "diarization.json")), { timeout: 60_000 }).toBe(true);
+ await expect.poll(async () => pathExists(dataRel("vidA", "audio.m4a")), { timeout: 60_000 }).toBe(false);
+ await expect(page.getByLabel("Run speaker work output")).toContainText("after capture", { timeout: 30_000 });
+
+ const after = await request.get(`${baseUrl}/api/ops/speakers`, { headers: AUTH });
+ const body = (await after.json()) as { freedVideos: number; line: string; lane: { cleanAfterCapture: boolean } };
+ expect(body.freedVideos).toBe(freedBefore + 1);
+ expect(body.lane.cleanAfterCapture).toBe(true);
+ expect(body.line).toMatch(/^waiting: .* · freed this run: .* · /);
+});
+
+test("clean after capture with no fresh listing: the captured video keeps its audio, awaiting an availability check", async ({ page }) => {
+ test.setTimeout(SLOW);
+ await resetData("one-transcribe-channel-with-audio");
+ await writeSettings(settings({ diarization: { cleanAfterCapture: true } }));
+ await seedTranscript("vidA");
+ // The last listing is two days old (older than cleanVerdictMaxAgeHours, 24),
+ // and a check was asked for an hour ago — so nothing new is requested here,
+ // and nothing may be deleted on the old listing.
+ await seedVerdict({
+ checkedAt: new Date(Date.now() - 48 * 3_600_000).toISOString(),
+ ids: ["vidA", "vidB", "vidC"],
+ requestedAt: new Date(Date.now() - 3_600_000).toISOString(),
+ });
+ await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
+ await generateReport(page, SLUG);
+
+ await page.goto(channelStage(SLUG, "speakers"));
+ await page.getByRole("button", { name: "Run speaker work", exact: true }).click();
+ await expect.poll(async () => pathExists(dataRel("vidA", "diarization.json")), { timeout: 60_000 }).toBe(true);
+ const output = page.getByLabel("Run speaker work output");
+ await expect(output).toContainText("awaiting an availability check", { timeout: 60_000 });
+ await expect(output).toContainText("a check was requested at");
+ expect(await pathExists(dataRel("vidA", "audio.m4a"))).toBe(true);
+});
+
+test("the readout: the Cleanup stage names the audio held for speakers; /cleanup and the lane card print the line", async ({ page }) => {
+ test.setTimeout(SLOW);
+ await resetData("one-transcribe-channel-with-audio");
+ // Held: nothing is dispatched, and the paused lane is what /cleanup's gate 4
+ // must call a hold that will not clear on its own.
+ await writeSettings(settings({ held: true }));
+ await seedTranscript("vidA");
+ await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
+ await generateReport(page, SLUG);
+
+ await page.goto(`/channels/${SLUG}`);
+ await expect(page.getByText(/held for speakers \(1 video\)/).first()).toBeVisible({ timeout: 30_000 });
+
+ await page.goto("/cleanup");
+ const readout = page.getByLabel("speakers readout");
+ await expect(readout).toContainText("waiting:", { timeout: 30_000 });
+ await expect(readout).toContainText("in 1 video");
+ await expect(readout.getByRole("button", { name: "work through speakers" })).toBeVisible();
+ await expect(page.getByLabel("audio hold sieve").locator('li[data-gate="4"]')).toContainText("will not clear on its own");
+
+ await page.goto("/");
+ await expect(page.getByLabel("speakers readout")).toContainText("waiting:", { timeout: 30_000 });
+});
+
+test("Work through speakers refuses an un-narrowed lane, in one sentence naming the command", async ({ page }) => {
+ test.setTimeout(SLOW);
+ await resetData("one-transcribe-channel-with-audio");
+ await writeSettings(settings({ held: true, narrowed: false }));
+ await seedTranscript("vidA");
+ await generateReport(page, SLUG);
+ await page.goto(channelStage(SLUG, "speakers"));
+ const paused = page.getByLabel("speakers lane paused");
+ await paused.getByRole("button", { name: "work through speakers" }).click();
+ await expect(page.getByText(/is not narrowed to speaker diarization/).first()).toBeVisible({ timeout: 30_000 });
+ await expect(page.getByText(/"operations":\["diarization"\]/).first()).toBeVisible();
+ expect((await lane()).held).toBe(true);
+ expect((await lane()).enabled ?? false).toBe(false);
+});
+
diff --git a/editor/e2e/widget.spec.ts b/editor/e2e/widget.spec.ts
@@ -798,7 +798,12 @@ test("backfill=1 alone renders the Backfill strip", async ({ page }) => {
test("the widget's controls hold and release the backfill lane", async ({
page,
}) => {
- await writeSettings({ ...TWO_WORKERS, ...BACKFILL_SETTINGS });
+ // Narrowed to diarization: Work through speakers refuses an un-narrowed lane.
+ await writeSettings({
+ ...TWO_WORKERS,
+ ...BACKFILL_SETTINGS,
+ autoQueue: { backfill: { held: false, operations: ["diarization"] } },
+ });
// Assert the KEY, not just the label: the button writes the same
// `autoQueue.backfill.held` the "Run the backfill lane" checkbox does, and
@@ -813,16 +818,24 @@ test("the widget's controls hold and release the backfill lane", async ({
).autoQueue?.backfill?.held ?? false;
await page.goto("/widget?controls=1&backfill=1");
- const pause = page.getByRole("button", { name: "pause backfill" });
- await expect(pause).toBeEnabled({ timeout: 30_000 });
- await pause.click();
+ // The Speakers lane's one control (the deck's): Work through speakers arms
+ // the lane and lifts its hold; Pause holds it.
+ const work = page.getByRole("button", { name: "work through speakers" });
+ await expect(work).toBeEnabled({ timeout: 30_000 });
+ await work.click();
+ await expect.poll(laneHeld, { timeout: 30_000 }).toBe(false);
- await expect.poll(laneHeld, { timeout: 30_000 }).toBe(true);
// The label flips immediately, because the click refetches the payload it
// reads rather than waiting out the 15s poll floor.
- const resume = page.getByRole("button", { name: "resume backfill" });
- await expect(resume).toBeVisible({ timeout: 15_000 });
+ const pause = page.getByRole("button", { name: "pause speakers" });
+ await expect(pause).toBeVisible({ timeout: 15_000 });
+ await pause.click();
+ await expect.poll(laneHeld, { timeout: 30_000 }).toBe(true);
- await resume.click();
- await expect.poll(laneHeld, { timeout: 30_000 }).toBe(false);
+ // Disarm, so an armed lane does not bleed into the next spec.
+ const off = await page.request.post(`${baseUrl}/api/ops/lane`, {
+ headers: { authorization: "Bearer test-worker-token" },
+ data: { lane: "backfill", enabled: false },
+ });
+ expect(off.status()).toBe(200);
});
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";
@@ -1717,7 +1724,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 +1868,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 +2136,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 +2567,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}`
);
});
@@ -2987,7 +2994,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/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}}'
@@ -94,6 +99,11 @@
// pnpm ops channel-rank --json '{"slug":"x","after":"other-channel"}'
// pnpm ops channel-rank --json '{"slug":"x","rank":null}'
// pnpm ops lane --json '{"lane":"download","held":true}'
+// pnpm ops lane --json '{"lane":"backfill","operations":["diarization"],"order":"space"}'
+// pnpm ops lane --json '{"lane":"backfill","speakers":"work"}'
+// pnpm ops get speakers
+// pnpm ops diarize --json '{"slug":"x"}' --wait
+// pnpm ops settings --json '{"patch":{"diarization":{"cleanAfterCapture":true}}}'
// pnpm ops render-mode --json '{"on":true,"for":"90m","note":"the Ember cut"}'
// pnpm ops render-mode --json '{"on":false}'
// pnpm ops get render-mode
@@ -301,6 +311,8 @@ const GETTERS = {
"x-run": (run) => (run ? `/api/ops/x-run?run=${encodeURIComponent(run)}` : "/api/ops/x-run"),
// One channel's cleanup row: what each sweep would reclaim, what holds the rest.
cleanup: (slug) => `/api/ops/cleanup/${encodeURIComponent(slug)}`,
+ // The speakers readout: waiting, freed this run, rate, days left, per channel.
+ speakers: () => "/api/ops/speakers",
// 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)}`,
@@ -352,6 +364,7 @@ const GET_ARG_OPTIONAL = new Set([
"x-run",
"generation-usage",
"render-mode",
+ "speakers",
]);
// The flags each noun takes beyond the shared ones; any other is refused.
@@ -434,6 +447,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?,
@@ -561,6 +584,9 @@ const ACTIONS = [
"do-not-clean",
"drop-saved-alternate",
"cleanup",
+ // The Cleanup stage's "Diarize speakers" for one channel: diarization and
+ // voice fingerprints for the videos still holding audio.
+ "diarize",
// WEB READS (release 27 S3): a DuckDuckGo search ({query, n?}) and one
// page as text ({url, maxChars?}), read only, through the editor's one
// paced web queue. Synchronous; no job.
@@ -1057,6 +1083,7 @@ export function usage() {
" pnpm ops get x-session [<slug>]",
" pnpm ops get x-run [<run id>]",
" pnpm ops get cleanup <slug>",
+ " pnpm ops get speakers",
" pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]",
" pnpm ops get transcript <videoId> [--slug <slug>]",
" pnpm ops get coverage <slug>",
@@ -1142,6 +1169,14 @@ export function usage() {
" rank, slug), \"jar\" (its age, social.x.maxCookieAgeMinutes, staleAt:",
" when it passes the limit, and whether an X job would start now),",
" gapSeconds (X's queue gap) and maxPosts. Nothing is asked of X.",
+ "get speakers is the speakers readout the lane deck and /cleanup print",
+ " (\"line\": waiting: X GB in N videos · freed this run: Y GB · about D",
+ " days left) and its numbers: waiting (audio held for the Speakers lane",
+ " that it will clear), neverClears, freed this run, the measured seconds",
+ " of engine per audio-hour, audio-hours and days left, voiceprinted and",
+ " 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 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.",
@@ -1224,12 +1259,18 @@ export function usage() {
'lane takes {"lane": "transcription"|"download"|"digest"|"backfill"|',
' "publish", "enabled"?, "held"?, "action"?: "start"|"stop"|"drain"}, or',
' {"lane": "report-schedule", "held"}: the recurring reports\' gate, its only key.',
+ ' An auto-queue lane also takes "operations": [ids] | null (dispatch only',
+ ' these — ["diarization"] is speakers only; null widens it again) and',
+ ' "order" ("space" on backfill: corpus-disk channels first, then the most',
+ ' audio bytes per audio-hour). The backfill (Speakers) lane takes',
+ ' "speakers": "work" (the deck\'s Work through speakers: arm, lift the hold,',
+ ' start a run) | "pause" (hold; stays armed).',
"",
'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',
' stages, other renders — waits at the heavy slot\'s door, and holds the',
- ' transcription and download lanes (only the ones not already held; only',
+ ' transcription, download and Speakers lanes (only the ones not already held; only',
' those are released). The answer\'s "join" (RENDER_PRIORITY_TOKEN=…) lets a',
' render in, on the floor 4000 MB and the cap 10240 MB; every `umtool take`',
' joins by itself. {"on": false} ends it ("force": true ends a running',
@@ -1312,6 +1353,12 @@ export function usage() {
' gone is cleaned from the pointer ("existed": false). "dryRun": true',
' answers the same and changes nothing. No undo.',
"",
+ 'diarize runs a channel\'s "Diarize speakers" as a job: {"slug"}. Every video',
+ ' still holding audio with no current diarization.json is diarized, and a',
+ ' diarized one without voice fingerprints gets them from its own turns — the',
+ ' voiceprint backfill, one channel at a time. Runs while the Speakers lane',
+ ' is paused; nothing is deleted.',
+ "",
'cleanup runs one of a channel\'s cleanup sweeps as a job: {"slug", "sweep":',
' "transcribed" (audio of transcribed videos — the /cleanup total) |',
' "extra-formats" | "wrong-format" | "failed-transcriptions" (clears the',
@@ -1745,6 +1792,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',
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/diarize-sherpa.py b/scripts/diarize-sherpa.py
@@ -43,9 +43,25 @@ Usage:
[--threads N] [--ffmpeg PATH] [--ffprobe PATH]
[--window-minutes M] [--window-after-minutes M]
<audioFile>
+ diarize-sherpa.py --voiceprints-only <diarization.json> --emb <model.onnx>
+ [--threads N] [--ffmpeg PATH] <audioFile>
Output: {"turns":[{"start":s,"end":s,"speaker":i}], "audioSeconds":f,
- "version":"...", "sampleRate":n, "windowing":{...}|null}
+ "version":"...", "sampleRate":n, "windowing":{...}|null,
+ "voiceprints":[{"speaker":i,"seconds":f,"embedded":n,
+ "centroid":[192 floats]|null}]}
+ --voiceprints-only prints {"voiceprints":[...], "version":"..."} for the
+ turns of an EXISTING record: no segmentation, no clustering, the turns are
+ not touched.
+
+VOICEPRINTS, AND WHY THEY ARE KEPT
+----------------------------------
+A voiceprint is one TitaNet embedding per FINAL speaker: the robust mean of
+that speaker's longest turns (see speaker_voiceprints). It is the one thing a
+diarization cannot recompute once the audio is deleted, and the cleanup sweep
+deletes the audio, so it is captured here, while the samples are in memory.
+It is computed AFTER the turns are final and never feeds back into them: the
+turns a file produced before voiceprints existed are the turns it produces now.
"""
import argparse, json, subprocess, sys, time
@@ -60,6 +76,18 @@ EMB_MIN_SEC = 0.5
# does not leave a visible split that the same audio processed whole would not
# have had.
MERGE_GAP_SEC = 0.5
+# A voiceprint embeds a speaker's VP_MAX_SEGMENTS longest turns, each capped at
+# VP_MAX_SEC, and drops the ones more than VP_TRIM under the median similarity to
+# the first mean before taking the mean again -- the same robust centroid as
+# common/lib/montage/voiceMatch.mjs's robustCentroid (REFERENCE_TRIM 0.15), so a
+# voiceprint and a voice-match reference mean the same thing.
+VP_MAX_SEGMENTS = 8
+VP_MAX_SEC = 10.0
+VP_TRIM = 0.15
+# 4 decimals: a cosine between two rounded unit vectors moves by < 1e-3, far
+# under any threshold that reads them (0.30 / 0.42), and a 192-float centroid
+# stays ~1.5 KB on disk.
+VP_DECIMALS = 4
def decode_whole_file(np, ffmpeg, audio, sample_rate):
@@ -195,10 +223,140 @@ def speaker_centroid(np, extractor, samples, sample_rate, segments):
if norm > 0:
vecs.append(v / norm)
if not vecs:
- return None
+ return None, 0
mean = np.mean(np.stack(vecs), axis=0)
norm = float(np.linalg.norm(mean))
- return mean / norm if norm > 0 else None
+ return (mean / norm if norm > 0 else None), len(vecs)
+
+
+def unit(np, v):
+ n = float(np.linalg.norm(v))
+ return v / n if n > 0 else None
+
+
+def robust_centroid(np, vecs, trim=VP_TRIM):
+ """voiceMatch.mjs's robustCentroid: the mean, then every vector more than
+ `trim` under the median similarity to it dropped, then the mean of the rest.
+ Fewer than three vectors are simply averaged (no median worth trusting)."""
+ if not vecs:
+ return None
+ first = unit(np, np.mean(np.stack(vecs), axis=0))
+ if first is None or len(vecs) < 3:
+ return first
+ sims = [float(np.dot(v, first)) for v in vecs]
+ floor = float(np.median(sims)) - trim
+ kept = [v for v, s in zip(vecs, sims) if s >= floor]
+ return unit(np, np.mean(np.stack(kept), axis=0)) if kept else first
+
+
+def embed_samples(np, extractor, sample_rate, x):
+ """One L2-normalized embedding of a stretch of samples, or None."""
+ if x.size < int(EMB_MIN_SEC * sample_rate):
+ return None
+ stream = extractor.create_stream()
+ stream.accept_waveform(sample_rate, x)
+ stream.input_finished()
+ if not extractor.is_ready(stream):
+ return None
+ return unit(np, np.asarray(extractor.compute(stream), dtype=np.float32))
+
+
+def voiceprint_spans(turns):
+ """{speaker: [(start, end)]}: the excerpts a voiceprint embeds. A speaker's
+ longest turns, each cut to VP_MAX_SEC from its start; spans under
+ EMB_MIN_SEC are not worth an embedding and are left out here."""
+ by_speaker = {}
+ for t in turns:
+ by_speaker.setdefault(int(t["speaker"]), []).append((float(t["start"]), float(t["end"])))
+ out = {}
+ for spk, spans in by_speaker.items():
+ picked = sorted(spans, key=lambda s: (s[0] - s[1], s[0]))[:VP_MAX_SEGMENTS]
+ out[spk] = [(a, min(b, a + VP_MAX_SEC)) for a, b in picked
+ if min(b, a + VP_MAX_SEC) - a >= EMB_MIN_SEC]
+ return out
+
+
+def speaker_seconds(turns):
+ """{speaker: talk seconds}, from the FINAL turns."""
+ out = {}
+ for t in turns:
+ spk = int(t["speaker"])
+ out[spk] = out.get(spk, 0.0) + max(0.0, float(t["end"]) - float(t["start"]))
+ return out
+
+
+def voiceprint_records(turns, vectors):
+ """The `voiceprints` array: one entry per speaker in `turns`, in speaker
+ order. `vectors` is {speaker: (unit vector or None, excerpts embedded)}; a
+ speaker with nothing embeddable gets centroid null -- present and honest,
+ so "no voiceprint for this one" is a recorded fact, not a missing field."""
+ secs = speaker_seconds(turns)
+ out = []
+ for spk in sorted(secs):
+ vec, n = vectors.get(spk, (None, 0))
+ out.append({
+ "speaker": spk,
+ "seconds": round(secs[spk], 3),
+ "embedded": int(n),
+ "centroid": None if vec is None
+ else [round(float(e), VP_DECIMALS) for e in vec],
+ })
+ return out
+
+
+class VoiceprintRefused(Exception):
+ """The audio does not match the turns it is asked to fingerprint (exit 6):
+ nothing is written, so a fingerprint is never recorded from the wrong
+ stretches of a recording."""
+
+
+# An excerpt that comes back with less than this share of its samples was cut
+# from past the end of the file (or a truncated one): the turns were not made
+# from this audio.
+VP_MIN_FILL = 0.9
+
+
+def check_excerpt(x, a, b, sample_rate, strict):
+ if strict and x.size < VP_MIN_FILL * (b - a) * sample_rate:
+ raise VoiceprintRefused(
+ f"excerpt {a:.2f}-{b:.2f}s decoded {x.size / sample_rate:.2f}s of "
+ f"{b - a:.2f}s — the turns were not made from this file"
+ )
+
+
+def voiceprints_from_samples(np, extractor, samples, sample_rate, turns, strict=False):
+ """Voiceprints for a recording whose samples are in memory (the whole-file
+ path): each speaker's excerpts sliced out and embedded. `strict` (the
+ voiceprints-only mode) refuses a short excerpt."""
+ vectors = {}
+ for spk, spans in voiceprint_spans(turns).items():
+ vecs = []
+ for a, b in spans:
+ i, j = int(a * sample_rate), min(int(b * sample_rate), samples.size)
+ x = samples[i:j] if j > i else samples[0:0]
+ check_excerpt(x, a, b, sample_rate, strict)
+ v = embed_samples(np, extractor, sample_rate, x)
+ if v is not None:
+ vecs.append(v)
+ vectors[spk] = (robust_centroid(np, vecs), len(vecs))
+ return voiceprint_records(turns, vectors)
+
+
+def voiceprints_from_file(np, extractor, ffmpeg, audio, sample_rate, turns, strict=True):
+ """Voiceprints for an EXISTING record's turns, decoding only the excerpts
+ (an input seek per excerpt, as the windowed path does), so a nine-hour file
+ costs a few hundred seconds of audio, not nine hours of memory."""
+ vectors = {}
+ for spk, spans in voiceprint_spans(turns).items():
+ vecs = []
+ for a, b in spans:
+ x = decode_window(np, ffmpeg, audio, sample_rate, a, b - a)
+ check_excerpt(x, a, b, sample_rate, strict)
+ v = embed_samples(np, extractor, sample_rate, x)
+ if v is not None:
+ vecs.append(v)
+ vectors[spk] = (robust_centroid(np, vecs), len(vecs))
+ return voiceprint_records(turns, vectors)
def merge_and_renumber(turns):
@@ -246,7 +404,7 @@ def merge_and_renumber(turns):
merged.append({"start": cur_start, "end": cur_end, "speaker": speaker})
merged.sort(key=lambda t: (t["start"], t["end"], t["speaker"]))
- return merged
+ return merged, order
def run_windowed(np, sherpa_onnx, sd, args, total_sec, window_sec, overlap_sec):
@@ -268,6 +426,7 @@ def run_windowed(np, sherpa_onnx, sd, args, total_sec, window_sec, overlap_sec):
kept = [] # {"start","end","key"} in ABSOLUTE seconds
centroids = [] # parallel to keys
keys = [] # (window index, local speaker)
+ embedded = {} # key -> excerpts its centroid was made from
decoded_sec = 0.0
for wi, (ws, dur, own_s, own_e) in enumerate(windows):
@@ -296,11 +455,12 @@ def run_windowed(np, sherpa_onnx, sd, args, total_sec, window_sec, overlap_sec):
# every turn belongs to the neighbouring window would otherwise add a
# cluster that names nothing.
for spk, spk_segs in owned_by_speaker.items():
- c = speaker_centroid(np, extractor, samples, sample_rate, spk_segs)
+ c, n = speaker_centroid(np, extractor, samples, sample_rate, spk_segs)
if c is None:
continue
centroids.append(c)
keys.append((wi, spk))
+ embedded[(wi, spk)] = n
elapsed = time.time() - t0
print(
@@ -312,7 +472,7 @@ def run_windowed(np, sherpa_onnx, sd, args, total_sec, window_sec, overlap_sec):
del samples, result, segs
if not kept:
- return [], decoded_sec, len(windows)
+ return [], [], decoded_sec, len(windows)
# Cross-window identity. Same clusterer and same threshold as within a
# window, so "these two are the same person" means the same thing at both
@@ -338,13 +498,138 @@ def run_windowed(np, sherpa_onnx, sd, args, total_sec, window_sec, overlap_sec):
t["speaker"] = global_of[t["key"]]
del t["key"]
- return merge_and_renumber(kept), decoded_sec, len(windows)
+ merged, order = merge_and_renumber(kept)
+
+ # ONE voiceprint per FINAL speaker: the robust mean of the local centroids
+ # that clustered into it. Those centroids are what decided the identity
+ # across seams, so they are the voiceprint of exactly that identity. A
+ # spare (a local speaker with no usable centroid) has none.
+ by_label = {}
+ for key, c in zip(keys, centroids):
+ by_label.setdefault(global_of[key], []).append((c, embedded.get(key, 0)))
+ vectors = {}
+ for label, final in order.items():
+ members = by_label.get(label, [])
+ vectors[final] = (
+ robust_centroid(np, [c for c, _ in members]),
+ sum(n for _, n in members),
+ )
+ return merged, vectors, decoded_sec, len(windows)
+
+
+def print_voiceprint_line(voiceprints, elapsed):
+ # Not "window i/n": common/jobs/progressParsers.ts reads those lines as a bar.
+ have = sum(1 for v in voiceprints if v["centroid"] is not None)
+ print(
+ f"diarize-sherpa: voiceprints for {have} of {len(voiceprints)} speaker(s) "
+ f"in {elapsed:.1f}s",
+ file=sys.stderr, flush=True,
+ )
+
+
+def run_voiceprints_only(args):
+ """Voiceprints for an existing record's turns. No segmentation model, no
+ clustering: the turns are read, never changed."""
+ try:
+ import numpy as np
+ import sherpa_onnx
+ except ImportError as e:
+ print(f"diarize-sherpa: missing dependency: {e}", file=sys.stderr)
+ return 3
+ try:
+ with open(args.voiceprints_only, "r", encoding="utf8") as f:
+ record = json.load(f)
+ turns = record["turns"]
+ except Exception as e:
+ print(f"diarize-sherpa: cannot read turns from {args.voiceprints_only}: {e}",
+ file=sys.stderr)
+ return 2
+ cfg = sherpa_onnx.SpeakerEmbeddingExtractorConfig(
+ model=args.emb, num_threads=args.threads
+ )
+ if not cfg.validate():
+ print("diarize-sherpa: invalid embedding model config", file=sys.stderr)
+ return 2
+ extractor = sherpa_onnx.SpeakerEmbeddingExtractor(cfg)
+ t0 = time.time()
+ sample_rate = 16000
+ # A file the whole-file path would have taken is decoded whole here too, so
+ # its voiceprints are the very numbers a fresh diarization would record (an
+ # mp3 input seek is not sample-exact, and a short turn's embedding moves
+ # with a few ms of offset). Longer files seek per excerpt, as windowing does.
+ total_sec = probe_duration(args.ffprobe, args.audio)
+ # THE SAME RECORDING, OR NOTHING (review B3). A record's turns are seconds on
+ # the clock of the file they were made from; another file of the same video
+ # (a re-download, a container, a truncated copy) can run seconds apart, and
+ # centroids cut from it would be other people's voices.
+ recorded = record.get("audioSeconds")
+ if total_sec is not None and (
+ not isinstance(recorded, (int, float)) or abs(total_sec - recorded) > 1.0
+ ):
+ print(
+ f"diarize-sherpa: refused: the file is {total_sec:.3f}s, the record's audio "
+ f"{recorded if recorded is not None else 'unknown'}s — not the audio these "
+ "turns were made from",
+ file=sys.stderr,
+ )
+ return 6
+ whole = (
+ total_sec is not None
+ and total_sec <= args.window_after_minutes * 60.0
+ )
+ try:
+ if whole:
+ samples = decode_whole_file(np, args.ffmpeg, args.audio, sample_rate)
+ if samples is None or samples.size == 0:
+ print("diarize-sherpa: decoded zero samples", file=sys.stderr)
+ return 5 if samples is not None else 4
+ voiceprints = voiceprints_from_samples(
+ np, extractor, samples, sample_rate, turns, strict=True
+ )
+ del samples
+ elif total_sec is None:
+ # ffprobe cannot read it: neither can ffmpeg, and seeking into it
+ # would only produce silence to embed.
+ print("diarize-sherpa: cannot measure the audio (unreadable?)",
+ file=sys.stderr)
+ return 4
+ else:
+ voiceprints = voiceprints_from_file(
+ np, extractor, args.ffmpeg, args.audio, sample_rate, turns
+ )
+ except VoiceprintRefused as e:
+ print(f"diarize-sherpa: refused: {e}", file=sys.stderr)
+ return 6
+ except RuntimeError as e:
+ print(f"diarize-sherpa: {e}", file=sys.stderr)
+ return 4
+ # A speaker with a turn long enough to embed MUST come out with a centroid:
+ # a null there is a fingerprint that was not made, and recording it as done
+ # would let the audio go.
+ spans = voiceprint_spans(turns)
+ missing = [v["speaker"] for v in voiceprints if v["centroid"] is None and spans.get(v["speaker"])]
+ if missing:
+ print(
+ f"diarize-sherpa: refused: no embedding for speaker(s) {missing} "
+ "although their turns are long enough",
+ file=sys.stderr,
+ )
+ return 6
+ print_voiceprint_line(voiceprints, time.time() - t0)
+ json.dump(
+ {"voiceprints": voiceprints,
+ "probedSeconds": round(total_sec, 3) if total_sec is not None else None,
+ "version": getattr(sherpa_onnx, "__version__", None)},
+ sys.stdout,
+ )
+ return 0
def main():
ap = argparse.ArgumentParser()
ap.add_argument("audio")
- ap.add_argument("--seg", required=True)
+ ap.add_argument("--seg")
+ ap.add_argument("--voiceprints-only", metavar="DIARIZATION_JSON")
ap.add_argument("--emb", required=True)
ap.add_argument("--threshold", type=float, default=0.5)
ap.add_argument("--threads", type=int, default=4)
@@ -363,6 +648,11 @@ def main():
ap.add_argument("--window-overlap-seconds", type=float, default=30.0)
args = ap.parse_args()
+ if args.voiceprints_only:
+ return run_voiceprints_only(args)
+ if not args.seg:
+ ap.error("--seg is required")
+
try:
import numpy as np
import sherpa_onnx
@@ -409,7 +699,7 @@ def main():
# to separate them.
t0 = time.time()
try:
- turns, audio_seconds, window_count = run_windowed(
+ turns, vectors, audio_seconds, window_count = run_windowed(
np, sherpa_onnx, sd, args, total_sec, window_sec, overlap_sec
)
except RuntimeError as e:
@@ -448,6 +738,19 @@ def main():
for s in result
]
windowing = None
+ # After the turns are final and outside the engine timing above, so
+ # `elapsed` keeps meaning what plans/ recorded it as.
+ t1 = time.time()
+ extractor = sherpa_onnx.SpeakerEmbeddingExtractor(
+ sherpa_onnx.SpeakerEmbeddingExtractorConfig(
+ model=args.emb, num_threads=args.threads
+ )
+ )
+ voiceprints = voiceprints_from_samples(
+ np, extractor, samples, sd.sample_rate, turns
+ )
+ vp_elapsed = time.time() - t1
+ del samples
if windowed:
turns = [
@@ -455,6 +758,8 @@ def main():
"speaker": int(t["speaker"])}
for t in turns
]
+ voiceprints = voiceprint_records(turns, vectors)
+ vp_elapsed = 0.0
speakers = len({t["speaker"] for t in turns})
print(
@@ -463,6 +768,8 @@ def main():
file=sys.stderr, flush=True,
)
+ print_voiceprint_line(voiceprints, vp_elapsed)
+
json.dump(
{
"turns": turns,
@@ -470,6 +777,7 @@ def main():
"sampleRate": sd.sample_rate,
"version": getattr(sherpa_onnx, "__version__", None),
"windowing": windowing,
+ "voiceprints": voiceprints,
},
sys.stdout,
)
diff --git a/scripts/diarize-sherpa.test.mjs b/scripts/diarize-sherpa.test.mjs
@@ -0,0 +1,300 @@
+// scripts/diarize-sherpa.py's voiceprints, through scripts/diarize.mjs.
+//
+// Two engines run these tests. The STUB (scripts/fixtures/sherpa-stub, on the
+// system python with numpy) is the default: a "voice" is a pure tone, so the
+// test can say who speaks when, and every number is exact. The REAL engine
+// (sherpa-onnx + TitaNet-small) runs the last test when DIARIZE_PYTHON,
+// DIARIZE_SEG_MODEL and DIARIZE_EMB_MODEL name it, on two espeak-ng voices.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { execFileSync, spawnSync } from "node:child_process";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const HERE = import.meta.dirname;
+const SCRIPT = path.join(HERE, "diarize-sherpa.py");
+const WRAPPER = path.join(HERE, "diarize.mjs");
+const STUB = path.join(HERE, "fixtures", "sherpa-stub");
+
+function has(cmd, args) {
+ return spawnSync(cmd, args, { stdio: "ignore" }).status === 0;
+}
+const hasFfmpeg = has("ffmpeg", ["-version"]) && has("ffprobe", ["-version"]);
+const hasNumpy = has("python3", ["-c", "import numpy"]);
+const skip = !(hasFfmpeg && hasNumpy) && "needs ffmpeg, ffprobe and python3 with numpy";
+
+const SR = 16000;
+// [start, end, hz]: who is speaking when. 300 Hz and 1000 Hz are two voices;
+// the 2000 Hz blip is a third whose only turn is too short to embed.
+const PLAN = [
+ [0, 4, 300],
+ [4.5, 8, 1000],
+ [8.5, 11, 300],
+ [11.5, 13, 1000],
+ [13.5, 13.75, 2000],
+];
+
+function writeWav(file, plan, total = 14) {
+ const n = Math.round(total * SR);
+ const pcm = Buffer.alloc(n * 2);
+ for (const [a, b, hz] of plan) {
+ for (let i = Math.round(a * SR); i < Math.round(b * SR); i += 1) {
+ pcm.writeInt16LE(Math.round(0.5 * 32767 * Math.sin((2 * Math.PI * hz * i) / SR)), i * 2);
+ }
+ }
+ const h = Buffer.alloc(44);
+ h.write("RIFF", 0);
+ h.writeUInt32LE(36 + pcm.length, 4);
+ h.write("WAVEfmt ", 8);
+ h.writeUInt32LE(16, 16);
+ h.writeUInt16LE(1, 20);
+ h.writeUInt16LE(1, 22);
+ h.writeUInt32LE(SR, 24);
+ h.writeUInt32LE(SR * 2, 28);
+ h.writeUInt16LE(2, 32);
+ h.writeUInt16LE(16, 34);
+ h.write("data", 36);
+ h.writeUInt32LE(pcm.length, 40);
+ writeFileSync(file, Buffer.concat([h, pcm]));
+}
+
+const env = { ...process.env, PYTHONPATH: STUB, PYTHONDONTWRITEBYTECODE: "1" };
+
+function engine(args) {
+ return JSON.parse(execFileSync("python3", [SCRIPT, ...args], { env, stdio: ["ignore", "pipe", "pipe"] }).toString());
+}
+
+const dot = (a, b) => a.reduce((s, x, i) => s + x * b[i], 0);
+
+function withDir(fn) {
+ const dir = mkdtempSync(path.join(os.tmpdir(), "diarize-sherpa-test-"));
+ try {
+ return fn(dir);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+test("whole file: one voiceprint per speaker, unit length, voices apart; a too-short speaker is recorded with a null centroid", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN);
+ const out = engine(["--seg", "seg.onnx", "--emb", "emb.onnx", wav]);
+ // The turns are the engine's own, untouched by the voiceprint pass.
+ assert.deepEqual(
+ out.turns.map((t) => [t.start, t.end, t.speaker]),
+ [[0, 4, 0], [4.5, 8, 1], [8.5, 11, 0], [11.5, 13, 1], [13.5, 13.75, 2]],
+ );
+ assert.equal(out.windowing, null);
+ assert.deepEqual(out.voiceprints.map((v) => [v.speaker, v.seconds, v.embedded]), [[0, 6.5, 2], [1, 5, 2], [2, 0.25, 0]]);
+ const [a, b, c] = out.voiceprints;
+ assert.equal(a.centroid.length, 192);
+ assert.ok(Math.abs(dot(a.centroid, a.centroid) - 1) < 1e-3);
+ assert.ok(dot(a.centroid, b.centroid) < 0.2, "two voices are apart");
+ assert.equal(c.centroid, null);
+ // Rounded to 4 decimals, so the same input prints the same bytes.
+ assert.ok(a.centroid.every((x) => Math.round(x * 1e4) / 1e4 === x));
+ }));
+
+test("windowed: one voiceprint per FINAL cluster, and it is the same voice as the whole-file one", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN.slice(0, 4));
+ const whole = engine(["--seg", "s", "--emb", "e", wav]);
+ const win = engine(["--seg", "s", "--emb", "e", "--window-minutes", "0.1", "--window-after-minutes", "0", "--window-overlap-seconds", "1", wav]);
+ assert.equal(win.windowing.windows, 3);
+ const speakers = [...new Set(win.turns.map((t) => t.speaker))].sort();
+ assert.deepEqual(speakers, [0, 1]);
+ assert.deepEqual(win.voiceprints.map((v) => v.speaker), [0, 1]);
+ for (const v of win.voiceprints) {
+ assert.ok(v.embedded >= 2, `speaker ${v.speaker} was embedded from more than one window's turns`);
+ const same = whole.voiceprints.find((w) => w.speaker === v.speaker);
+ assert.ok(dot(v.centroid, same.centroid) > 0.99, `speaker ${v.speaker} matches its whole-file voiceprint`);
+ }
+ assert.equal(
+ win.voiceprints.find((v) => v.speaker === 0).seconds,
+ whole.voiceprints.find((v) => v.speaker === 0).seconds,
+ );
+ }));
+
+test("diarize.mjs records the voiceprints with the embedding model's basename, outside `engine`", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN);
+ const out = path.join(dir, "diarization.json");
+ execFileSync(process.execPath, [WRAPPER, "--python", "python3", "--seg", "/m/seg.onnx", "--emb", "/m/titanet.onnx", "--threshold", "0.9", "--output", out, "--video-id", "v1", wav], { env, stdio: "ignore" });
+ const rec = JSON.parse(readFileSync(out, "utf8"));
+ assert.equal(rec.voiceprints.length, 3);
+ assert.ok(rec.voiceprints.every((v) => v.embeddingModel === "titanet.onnx"));
+ assert.equal(typeof rec.voiceprintsAt, "string");
+ assert.deepEqual(Object.keys(rec.voiceprintsFrom).sort(), ["bytes", "durationSeconds", "file"]);
+ assert.equal(rec.voiceprintsFrom.file, "a.wav");
+ assert.equal(rec.engine.embeddingModel, "titanet.onnx");
+ assert.equal("voiceprints" in rec.engine, false);
+ }));
+
+test("--voiceprints-only adds voiceprints to an existing record from its own turns, keeping turns and generatedAt", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN);
+ const whole = engine(["--seg", "s", "--emb", "e", wav]);
+ const rec = path.join(dir, "diarization.json");
+ const before = {
+ videoId: "v1",
+ generatedAt: "2026-08-07T00:00:00.000Z",
+ audioSeconds: whole.audioSeconds,
+ speakers: 3,
+ turns: whole.turns,
+ engine: { engine: "sherpa-onnx", embeddingModel: "titanet.onnx", threshold: 0.9 },
+ };
+ writeFileSync(rec, JSON.stringify(before) + "\n");
+ execFileSync(process.execPath, [WRAPPER, "--voiceprints-only", rec, "--python", "python3", "--emb", "/m/titanet.onnx", wav], { env, stdio: "ignore" });
+ const after = JSON.parse(readFileSync(rec, "utf8"));
+ assert.equal(after.generatedAt, before.generatedAt);
+ assert.deepEqual(after.turns, before.turns);
+ assert.deepEqual(after.engine, before.engine);
+ assert.deepEqual(
+ after.voiceprints.map((v) => [v.speaker, v.seconds, v.embedded, v.embeddingModel]),
+ [[0, 6.5, 2, "titanet.onnx"], [1, 5, 2, "titanet.onnx"], [2, 0.25, 0, "titanet.onnx"]],
+ );
+ // Decoded per excerpt rather than whole, and the same voice either way.
+ for (const v of after.voiceprints.filter((x) => x.centroid)) {
+ assert.ok(dot(v.centroid, whole.voiceprints[v.speaker].centroid) > 0.999);
+ }
+ // Which file they were cut from.
+ assert.equal(after.voiceprintsFrom.file, "a.wav");
+ assert.equal(after.voiceprintsFrom.bytes, readFileSync(wav).length);
+ assert.ok(Math.abs(after.voiceprintsFrom.durationSeconds - 14) < 0.01);
+ }));
+
+test("--voiceprints-only on a zero-byte audio fails and leaves the record exactly as it was", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "empty.mp3");
+ writeFileSync(wav, "");
+ const rec = path.join(dir, "diarization.json");
+ const body = JSON.stringify({ videoId: "v1", generatedAt: "x", speakers: 1, turns: [{ start: 0, end: 3, speaker: 0 }], engine: { engine: "sherpa-onnx" } }) + "\n";
+ writeFileSync(rec, body);
+ const r = spawnSync(process.execPath, [WRAPPER, "--voiceprints-only", rec, "--python", "python3", "--emb", "/m/t.onnx", wav], { env, stdio: "ignore" });
+ assert.notEqual(r.status, 0);
+ assert.equal(readFileSync(rec, "utf8"), body);
+ }));
+
+const REAL = (() => {
+ const python = process.env.DIARIZE_PYTHON;
+ const seg = process.env.DIARIZE_SEG_MODEL;
+ const emb = process.env.DIARIZE_EMB_MODEL;
+ if (!python || !seg || !emb || ![python, seg, emb].every(existsSync)) return null;
+ if (!has("espeak-ng", ["--version"]) || !hasFfmpeg) return null;
+ return { python, seg, emb };
+})();
+
+test("the real engine (sherpa-onnx + TitaNet-small): two espeak voices, a 192-float voiceprint per speaker", { skip: !REAL && "set DIARIZE_PYTHON, DIARIZE_SEG_MODEL and DIARIZE_EMB_MODEL (and install espeak-ng) to run it" }, () =>
+ withDir((dir) => {
+ const parts = [
+ ["en-us", "The quick brown fox jumps over the lazy dog while the band plays on into the night."],
+ ["en+f4", "Nobody expected the committee to vote that way, but here we are again this morning."],
+ ["en-us", "Then the fox came back and asked whether anyone had seen his other shoe, which was red."],
+ ];
+ const files = parts.map(([voice, text], i) => {
+ const f = path.join(dir, `p${i}.wav`);
+ execFileSync("espeak-ng", ["-v", voice, "-s", "150", "-w", f, text]);
+ return f;
+ });
+ const list = path.join(dir, "list.txt");
+ writeFileSync(list, files.map((f) => `file '${f}'`).join("\n"));
+ const wav = path.join(dir, "talk.wav");
+ execFileSync("ffmpeg", ["-v", "error", "-f", "concat", "-safe", "0", "-i", list, "-ar", "16000", "-ac", "1", wav]);
+ const out = path.join(dir, "diarization.json");
+ execFileSync(process.execPath, [WRAPPER, "--python", REAL.python, "--seg", REAL.seg, "--emb", REAL.emb, "--threshold", "0.9", "--output", out, "--video-id", "real", wav], { stdio: "ignore" });
+ const rec = JSON.parse(readFileSync(out, "utf8"));
+ const speakers = new Set(rec.turns.map((t) => t.speaker));
+ assert.ok(speakers.size >= 1);
+ assert.equal(rec.voiceprints.length, speakers.size);
+ const real = rec.voiceprints.filter((v) => v.centroid);
+ assert.ok(real.length >= 1);
+ for (const v of real) {
+ assert.equal(v.centroid.length, 192);
+ assert.ok(Math.abs(dot(v.centroid, v.centroid) - 1) < 1e-2);
+ }
+ }));
+
+// ---- review B3: refuse rather than record a fingerprint from the wrong audio --
+
+function vpOnly(dir, wav, record, extraEnv = {}) {
+ const rec = path.join(dir, "diarization.json");
+ const body = JSON.stringify(record) + "\n";
+ writeFileSync(rec, body);
+ const r = spawnSync(process.execPath, [WRAPPER, "--voiceprints-only", rec, "--python", "python3", "--emb", "/m/t.onnx", wav], {
+ env: { ...env, ...extraEnv },
+ encoding: "utf8",
+ });
+ return { status: r.status, stderr: r.stderr, untouched: readFileSync(rec, "utf8") === body };
+}
+
+const base = (over) => ({
+ videoId: "v1",
+ generatedAt: "x",
+ audioSeconds: 14,
+ speakers: 2,
+ turns: [
+ { start: 0, end: 4, speaker: 0 },
+ { start: 4.5, end: 8, speaker: 1 },
+ ],
+ engine: { engine: "sherpa-onnx" },
+ ...over,
+});
+
+test("voiceprints-only refuses a file whose duration is not the record's (> 1 s apart), or a record with none", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN);
+ const off = vpOnly(dir, wav, base({ audioSeconds: 99 }));
+ assert.equal(off.status, 6);
+ assert.ok(off.untouched);
+ assert.match(off.stderr, /not the audio these turns were made from/);
+ const none = vpOnly(dir, wav, base({ audioSeconds: undefined }));
+ assert.equal(none.status, 6);
+ assert.ok(none.untouched);
+ assert.equal(vpOnly(dir, wav, base({ audioSeconds: 14.6 })).status, 0, "under a second apart is the same file");
+ }));
+
+test("voiceprints-only refuses when an excerpt comes back short (a turn past the file's end)", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN);
+ const r = vpOnly(dir, wav, base({ turns: [{ start: 0, end: 4, speaker: 0 }, { start: 12, end: 18, speaker: 1 }] }));
+ assert.equal(r.status, 6);
+ assert.ok(r.untouched);
+ assert.match(r.stderr, /were not made from this file/);
+ }));
+
+test("voiceprints-only refuses when a speaker with long turns gets no embedding, though the audio decodes", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN);
+ const r = vpOnly(dir, wav, base(), { STUB_NOT_READY: "1" });
+ assert.equal(r.status, 6);
+ assert.ok(r.untouched);
+ assert.match(r.stderr, /no embedding for speaker/);
+ // The full diarization still writes the record — with null centroids, which
+ // the cleanup gate (hasVoiceprints) reads as NOT fingerprinted.
+ const out = engine(["--seg", "s", "--emb", "e", wav].concat([]));
+ assert.ok(out.voiceprints.length > 0);
+ const notReady = JSON.parse(
+ execFileSync("python3", [SCRIPT, "--seg", "s", "--emb", "e", wav], { env: { ...env, STUB_NOT_READY: "1" }, stdio: ["ignore", "pipe", "pipe"] }).toString(),
+ );
+ assert.ok(notReady.voiceprints.every((v) => v.centroid === null));
+ }));
+
+test("a voiceprint step that succeeds drops a refusal recorded against an earlier file", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN);
+ const r = vpOnly(dir, wav, base({ voiceprintsRefused: { file: "audio.mp3", size: 1, mtime: 1, reason: "old", at: "x" } }));
+ assert.equal(r.status, 0);
+ const after = JSON.parse(readFileSync(path.join(dir, "diarization.json"), "utf8"));
+ assert.equal("voiceprintsRefused" in after, false);
+ assert.equal(after.voiceprints.length, 2);
+ }));
+
diff --git a/scripts/diarize.mjs b/scripts/diarize.mjs
@@ -58,8 +58,20 @@
// (DIARIZE_WINDOW_MINUTES, 45)
// --window-after-minutes <m> only window files longer than this
// (DIARIZE_WINDOW_AFTER_MINUTES, 90)
+// --voiceprints-only <record.json>
+// add voiceprints to an EXISTING record from its own
+// turns (sherpa's embedder; no segmentation, no
+// clustering) and write it to --output (default: back
+// over <record.json>). Turns, generatedAt and engine are
+// kept byte-for-byte; only voiceprints/voiceprintsAt land.
// -h, --help
//
+// VOICEPRINTS: the sherpa engine prints one TitaNet centroid per final speaker
+// (scripts/diarize-sherpa.py), and they land on the record as `voiceprints`,
+// each carrying the embedding model's basename. Like `windowing` they are
+// OUTSIDE `engine` and outside the freshness identity: a sidecar written before
+// they existed is not stale, it is merely without them (hasVoiceprints).
+//
// WINDOWING IS RECORDED BUT IS NOT PART OF THE FRESHNESS IDENTITY. It lands on
// the record as a top-level `windowing` field, deliberately OUTSIDE `engine` —
// isDiarizationFresh compares engine/models/threshold, and the target it
@@ -70,7 +82,7 @@
// See common/lib/diarization.ts, which says so in as many words.
import { spawn } from "node:child_process";
-import { rename, writeFile } from "node:fs/promises";
+import { readFile, rename, stat, writeFile } from "node:fs/promises";
import path from "node:path";
const HELP = `diarize.mjs [options] <audioFile>
@@ -126,6 +138,118 @@ const windowAfterMinutes = arg(
process.env.DIARIZE_WINDOW_AFTER_MINUTES ?? "90",
);
+const voiceprintsOnly = arg("--voiceprints-only", "");
+
+// The engine's voiceprints as the record stores them. Anything malformed is
+// dropped rather than written: a voiceprint is read by cosine, and a wrong
+// length or a NaN would make every comparison against it quietly meaningless.
+function recordVoiceprints(raw, embeddingModel) {
+ if (!Array.isArray(raw)) return undefined;
+ const out = [];
+ for (const v of raw) {
+ const speaker = Number(v?.speaker);
+ if (!Number.isInteger(speaker)) continue;
+ const centroid =
+ Array.isArray(v.centroid) &&
+ v.centroid.length > 0 &&
+ v.centroid.every((x) => Number.isFinite(x))
+ ? v.centroid.map(Number)
+ : null;
+ out.push({
+ speaker,
+ seconds: Number.isFinite(v.seconds) ? v.seconds : 0,
+ embedded: Number.isInteger(v.embedded) ? v.embedded : 0,
+ centroid,
+ embeddingModel,
+ });
+ }
+ return out;
+}
+
+// WHICH FILE the fingerprints were cut from: the cleanup gate and a later
+// voiceprint step can tell one recording's file from another's (review B3).
+async function voiceprintsFrom(file, durationSeconds) {
+ const bytes = await stat(file).then((st) => st.size, () => null);
+ return {
+ file: path.basename(file),
+ ...(bytes !== null ? { bytes } : {}),
+ ...(Number.isFinite(durationSeconds) ? { durationSeconds } : {}),
+ };
+}
+
+async function writeAtomic(file, json) {
+ // Atomic: a half-written sidecar must never be what convinces the cleanup
+ // sweep it is safe to delete the only copy of the audio.
+ const tmp = `${file}.tmp-${process.pid}`;
+ await writeFile(tmp, json);
+ await rename(tmp, file);
+}
+
+async function runVoiceprintsOnly() {
+ if (!emb) fail("missing --emb (or DIARIZE_EMB_MODEL)");
+ let existing;
+ try {
+ existing = JSON.parse(await readFile(voiceprintsOnly, "utf8"));
+ } catch (e) {
+ fail(`cannot read ${voiceprintsOnly}: ${e.message}`);
+ }
+ if (!Array.isArray(existing?.turns)) fail(`${voiceprintsOnly} has no \`turns\``);
+ const started = Date.now();
+ const child = spawn(
+ python,
+ [
+ path.join(import.meta.dirname, "diarize-sherpa.py"),
+ "--voiceprints-only", voiceprintsOnly,
+ "--emb", emb,
+ "--threads", String(threads),
+ "--ffmpeg", ffmpeg,
+ "--ffprobe", ffprobe,
+ "--window-after-minutes", String(windowAfterMinutes),
+ audio,
+ ],
+ { stdio: ["ignore", "pipe", "inherit"] },
+ );
+ let out = "";
+ child.stdout.setEncoding("utf8");
+ child.stdout.on("data", (d) => (out += d));
+ const code = await new Promise((resolve) => {
+ child.on("error", (err) => fail(`failed to run ${python}: ${err.message}`, 3));
+ child.on("close", resolve);
+ });
+ if (code !== 0) fail(`engine exited ${code}`, code ?? 1);
+ let raw;
+ try {
+ raw = JSON.parse(out);
+ } catch {
+ fail("engine produced no parseable JSON on stdout");
+ }
+ const voiceprints = recordVoiceprints(raw?.voiceprints, path.basename(emb));
+ if (!voiceprints) fail("engine output has no `voiceprints` array");
+ // Everything already on the record stays as it was -- generatedAt above
+ // all: attribution-diarized's freshness names it, so touching it would make
+ // every name already put to these clusters stale for no change in them.
+ // A refusal recorded against an earlier file is answered by these.
+ const { voiceprintsRefused: _refused, ...kept } = existing;
+ const record = {
+ ...kept,
+ voiceprints,
+ voiceprintsAt: new Date().toISOString(),
+ voiceprintsMs: Date.now() - started,
+ voiceprintsFrom: await voiceprintsFrom(audio, raw?.probedSeconds),
+ };
+ const target = output ?? voiceprintsOnly;
+ await writeAtomic(target, JSON.stringify(record) + "\n");
+ const have = voiceprints.filter((v) => v.centroid).length;
+ process.stderr.write(
+ `diarize: voiceprints for ${have} of ${voiceprints.length} speaker(s) -> ${target}\n`,
+ );
+}
+
+if (voiceprintsOnly) {
+ await runVoiceprintsOnly();
+ process.exit(0);
+}
+
const engineCmd = arg("--engine", process.env.DIARIZE_ENGINE_CMD ?? "");
const engineKind = arg(
"--engine-kind",
@@ -227,6 +351,14 @@ child.on("close", async (code) => {
: {}),
speakers: new Set(turns.map((t) => t.speaker)).size,
turns,
+ // Outside `engine`, like `windowing`. Only the sherpa engine embeds; a
+ // sortformer or `--engine` record has none, and says so by omission.
+ ...(() => {
+ const vp = usingSortformer
+ ? undefined
+ : recordVoiceprints(raw.voiceprints, emb ? path.basename(emb) : "");
+ return vp ? { voiceprints: vp, voiceprintsAt: new Date().toISOString() } : {};
+ })(),
// Provenance is per-engine, and the fields a given engine CANNOT have are
// left off rather than written empty. Recording sherpa's threshold on a
// sortformer record would be a lie that isDiarizationFresh then acts on: it
@@ -253,16 +385,15 @@ child.on("close", async (code) => {
},
};
+ if (record.voiceprints) {
+ record.voiceprintsFrom = await voiceprintsFrom(audio, raw.audioSeconds);
+ }
const json = JSON.stringify(record) + "\n";
if (!output) {
process.stdout.write(json);
return;
}
- // Atomic: a half-written sidecar must never be what convinces the cleanup
- // sweep it is safe to delete the only copy of the audio.
- const tmp = `${output}.tmp-${process.pid}`;
- await writeFile(tmp, json);
- await rename(tmp, output);
+ await writeAtomic(output, json);
process.stderr.write(
`diarize: ${record.turns.length} turns, ${record.speakers} speakers -> ${output}\n`,
);
diff --git a/scripts/fixtures/sherpa-stub/sherpa_onnx.py b/scripts/fixtures/sherpa-stub/sherpa_onnx.py
@@ -0,0 +1,132 @@
+"""A stand-in for sherpa_onnx, for scripts/diarize-sherpa.test.mjs.
+
+Same surface as the calls scripts/diarize-sherpa.py makes, none of the models:
+a "voice" is a pure tone, so a test can say who is speaking when by writing a
+wav. Segmentation labels each voiced 0.25 s frame by its dominant frequency;
+an embedding is a smooth bump on a 192-bin frequency axis, so two tones of one
+pitch embed alike and two pitches embed apart; clustering is greedy cosine.
+The real engine is tested by the same file when DIARIZE_PYTHON /
+DIARIZE_SEG_MODEL / DIARIZE_EMB_MODEL name it.
+"""
+import numpy as np
+
+__version__ = "stub-1"
+SR = 16000
+FRAME = 0.25
+
+
+class _Cfg:
+ def __init__(self, **kw):
+ self.__dict__.update(kw)
+
+ def validate(self):
+ return True
+
+
+OfflineSpeakerDiarizationConfig = _Cfg
+OfflineSpeakerSegmentationModelConfig = _Cfg
+OfflineSpeakerSegmentationPyannoteModelConfig = _Cfg
+SpeakerEmbeddingExtractorConfig = _Cfg
+FastClusteringConfig = _Cfg
+
+
+def _pitch(x):
+ if x.size == 0:
+ return 0.0
+ spec = np.abs(np.fft.rfft(x * np.hanning(x.size)))
+ return float(np.argmax(spec)) * SR / x.size
+
+
+class _Seg:
+ def __init__(self, start, end, speaker):
+ self.start, self.end, self.speaker = start, end, speaker
+
+
+class _Result(list):
+ def sort_by_start_time(self):
+ return _Result(sorted(self, key=lambda s: s.start))
+
+
+class OfflineSpeakerDiarization:
+ sample_rate = SR
+
+ def __init__(self, cfg):
+ self.cfg = cfg
+
+ def process(self, samples):
+ n = int(FRAME * SR)
+ labels = {}
+ segs = []
+ cur = None
+ for i in range(0, samples.size - n + 1, n):
+ x = samples[i:i + n]
+ if float(np.sqrt(np.mean(x * x))) < 0.01:
+ cur = None
+ continue
+ # Pitch to the nearest 100 Hz is the "speaker".
+ key = int(round(_pitch(x) / 100.0))
+ spk = labels.setdefault(key, len(labels))
+ t = i / SR
+ if cur is not None and cur.speaker == spk and abs(cur.end - t) < 1e-6:
+ cur.end = t + FRAME
+ else:
+ cur = _Seg(t, t + FRAME, spk)
+ segs.append(cur)
+ return _Result(segs)
+
+
+class _Stream:
+ def __init__(self):
+ self.x = np.zeros(0, dtype=np.float32)
+
+ def accept_waveform(self, sr, x):
+ self.x = np.concatenate([self.x, np.asarray(x, dtype=np.float32)])
+
+ def input_finished(self):
+ pass
+
+
+class SpeakerEmbeddingExtractor:
+ dim = 192
+
+ def __init__(self, cfg):
+ self.cfg = cfg
+
+ def create_stream(self):
+ return _Stream()
+
+ def is_ready(self, stream):
+ # STUB_NOT_READY: an embedder that never has enough (audio that decodes,
+ # and still no fingerprint).
+ import os
+ if os.environ.get("STUB_NOT_READY"):
+ return False
+ return stream.x.size >= int(0.5 * SR)
+
+ def compute(self, stream):
+ f = _pitch(stream.x)
+ axis = np.arange(self.dim, dtype=np.float64)
+ centre = min(self.dim - 1, f / 20.0)
+ v = np.exp(-((axis - centre) ** 2) / 18.0) + 0.01
+ return list(v)
+
+
+class FastClustering:
+ def __init__(self, cfg):
+ self.cfg = cfg
+
+ def __call__(self, arr):
+ cents = []
+ out = []
+ for v in np.asarray(arr, dtype=np.float64):
+ v = v / np.linalg.norm(v)
+ best = -1
+ for k, c in enumerate(cents):
+ if float(np.dot(v, c)) > 0.5:
+ best = k
+ break
+ if best < 0:
+ cents.append(v)
+ best = len(cents) - 1
+ out.append(best)
+ return out
diff --git a/settings.json.example b/settings.json.example
@@ -183,7 +183,11 @@
"sortformerBin": "",
"sortformerModel": "",
"concurrency": 1,
- "maxAudioHours": 0
+ "maxAudioHours": 0,
+ "cleanAfterCapture": false,
+ "requireVoiceprints": true,
+ "cleanVerdictMaxAgeHours": 24,
+ "cleanWholeRecordingAudio": false
},
"backfill": {
"concurrency": 1,
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -76,7 +76,7 @@ Inbox cannot disagree about what is wrong with one.
| `take <project> --id <id> --preview [--from <take>] [--at S --dur S \| --full] [--priority] [--json]` | the take's **preview**: the take as stored (a draft too, from its walked patch) composed exactly as its render is -- the same 1920×1080 layout, segments, chrome frames and sound -- with only its final picture encoded smaller and faster (`render.preview`: 1280×720, x264 veryfast, crf 26) into `takes/<id>/out/<slug>.preview.mp4`; its build, schedule and record (`render.json`, `render.log`) in `takes/<id>/out/preview/`. The full render (`preview.mp4`, `out/<slug>.mp4`, `out/sourced/`, `take.json`, `render.json`) is never touched. Reuses this take's own full render, and `--from`'s full render and preview ([report-video.md](report-video.md#fast-feedback-preview-and-changes-renders), [knobs.md](knobs.md#fast-feedback-a-preview-and-a-reel-of-the-changes)) |
| `take <project> --id <id> --changes [--from <take>] [--pad 3] [--no-preview] [--priority] [--json]` | the take's **changes reel**: only what changed against `--from` (default: the take's own `from`, or the take a draft was made from) -- each added, re-read, re-picked, re-voiced, trimmed, held, fx'd, … item with a neighbour either side, rendered in one build (`takes/<id>/out/changes/`), cut to the item ± `--pad` s, a label burned in (`21:19 · p-2116831815466193102 · re-voiced`: its time in the FULL cut), joined into `takes/<id>/out/<slug>.changes.mp4`; a removed item shows as the join it leaves. `takes/<id>/changes.json` lists the pieces with their full-cut times and how exact they are (`times.basis`: `measured` -- the base's measured schedule plus the changed items' measured lengths -- or `estimate`). Preview quality unless `--no-preview`. Nothing changed: no reel, and the list says so |
| `take <project> --id <id> --import-item <project>:<item>[,<item>…] [--import-item …] [--after <entry> \| --before <entry>] [--as <id>] [--dry-run] [--json]` | **items of another project into a take** -- deprecated, saying so in one line on stderr: edits land in the draft, so open the take there and use `timeline <p> import-item` (`takeImport.mjs`): each entry CLONED from the source's manifest as it is now (its card, context, knobs, narration with its takes and its pick) into the take's timeline -- one write, an undo point of the take's (`timeline <p> --take <id> undo`); the files it names (narration takes and their `take-<n>.*` sidecars, the parts' cache files, attachments, a context post's media, the picture of each author it draws that the take lacks, added to the take's `postAvatars`) **hard-linked** into this project's dir at the same path, so the render and the lint find them (copied across filesystems; the same file already there is left; ANOTHER file at the path: linked under `imports/<source>/<path>` and the clone names that). The source project and this project's manifest are only read. **Placed** `--after`/`--before` an entry of the take (several items in the order named, one after another), else by the post's date when the take's posts are in date order, else at the end. **Again**: updated in place from the source (moved only with `--after`/`--before`), `unchanged` with no write when nothing differs. `--as`: one item under another id (a second copy). `--dry-run`: the plan and the placement, nothing linked or written. `--json`: `items[] {id, action added\|updated\|unchanged\|moved, at {index, after, before}, narration {takes, pick, file}, files[], avatars[]}`, `revision`. Refused while the take renders. **Exit 0 · 1 refused (no such item, take or entry; a link out of the project) · 2 usage** |
-| `take … --priority` · `takes make … --priority` · `render-mode on [--for 90m] [--note T] [--json \| --print-token]` · `render-mode on [--for 90m] [--note T] [--print-token] -- <cmd …>` · `render-mode off [--force] [--json]` · `render-mode status [--json]` | **render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription and download lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints (`--print-token`: the token alone on stdout, the rest on stderr). **`on … -- <cmd …>` is the form for a script**: the command is spawned with the token in its environment, the hold is the command's pid, and it is released when the command exits — done, failed, or umtool signalled (the signal is passed on); umtool exits with the command's code, and inside a manual window the command joins it. A bare `on` in a script leaves the window behind (the chain trap). `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, "Render mode") |
+| `take … --priority` · `takes make … --priority` · `render-mode on [--for 90m] [--note T] [--json \| --print-token]` · `render-mode on [--for 90m] [--note T] [--print-token] -- <cmd …>` · `render-mode off [--force] [--json]` · `render-mode status [--json]` | **render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription, download and Speakers lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints (`--print-token`: the token alone on stdout, the rest on stderr). **`on … -- <cmd …>` is the form for a script**: the command is spawned with the token in its environment, the hold is the command's pid, and it is released when the command exits — done, failed, or umtool signalled (the signal is passed on); umtool exits with the command's code, and inside a manual window the command joins it. A bare `on` in a script leaves the window behind (the chain trap). `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, "Render mode") |
| `take status <project> [--id <take>] [--json] [--log] [--tail N]` | a take's **render record** (`takes/<take>/render.json`, written by every render whoever started it — a terminal, the Takes page, the queue): `state` (`running`, `waiting` at the heavy slot, `done`, `failed`, `cancelled`; `queued` or `blocked` while a queue step waits to render it), `stage` and a rough `percent`, the `error` (the first error line, not a bare "exited 1") and the log's last 40 lines (`tail`), on done the `mp4` and its measured `seconds`; `--log` prints the FULL `takes/<take>/render.log`. A "running" whose process is gone reads **failed** ("the render process is gone"); a done whose mp4 is missing or 0 bytes reads **failed**. **Exit 0 done · 3 queued, waiting or running · 1 failed, cancelled, blocked or none.** Without `--id`: every take with a record, the newest's exit ([queue and poll](#queue-and-poll-instead-of-scripting)); and its fast-feedback renders beside it, `preview` and `changes` (each one's state, mp4, seconds, log; a changes reel's piece count, its base and its list), a queued `--preview`/`--changes` step said as such -- never as the take's own render |
| `queue add [--after <qid>\|last] [--label T] [--timeout <minutes>] [--json] -- <umtool subcommand argv…>` | a **step** of the durable queue: the argv of a umtool command, one word per argument (no shell), stored under `<reports root>/.umtool-queue/` and run by the **umtool app** (its systemd unit), one step at a time, in order — so it survives the session that queued it, an app restart and a ship. Prints the qid (`q<N>`) alone on stdout. `--after` waits for that step to be **done**; when it fails or is cancelled this one is **blocked** (and so is whatever waits on it). `--timeout`: the step's limit (default 720 minutes). A step does not start while the app's own job runner is busy (a Takes-page job), and a heavy step still takes the machine's heavy slot and render mode by itself |
| `queue ls [--all] [--json]` · `queue status <qid> [--json]` · `queue wait <qid> [--timeout <s>]` · `queue log <qid> [--tail N]` · `queue cancel <qid>` · `queue retry <qid>` | the queue: `ls` the runner (is the app running it) and the steps not finished or finished in the last 24 h; `status` one step (**exit 0 done · 3 queued or running · 1 failed, blocked or cancelled**); `wait` the same after up to `<s>` seconds (default 90); `log` its FULL log (`logs/<qid>.log`; earlier attempts kept as `<qid>.<n>.log`); `cancel` a queued or blocked step at once, a running one stopped (its process group); `retry` a failed or cancelled step back in the queue with every step blocked behind it. A step that was running when the app died reads **failed** ("the step's process is gone"), its log kept — it is never re-run on its own |
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -2406,7 +2406,7 @@ render holds the machine.
While render mode is on, every other heavy job waits at the heavy slot's door (e2e suites,
`next build`s, the publish stages, other renders); the render is admitted on the floor
-4000 MB and the cap 10240 MB; the editor's transcription and download lanes are held — only
+4000 MB and the cap 10240 MB; the editor's transcription, download and Speakers lanes are held — only
the ones that were not held already, and only those are let go. A take's hold ends with the
take: done, failed, or stopped (Ctrl-C, the job's Stop). A window ends at its `until`
(2 h unless `--for`), or with `off`. A hold whose process died is no hold: the gate ignores
diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs
@@ -585,7 +585,7 @@ export const GROUPS = [
["`take <project> --id <id> --import-item <project>:<item>[,<item>…] [--import-item …] [--after <entry> \\| --before <entry>] [--as <id>] [--dry-run] [--json]`",
"**items of another project into a take** -- deprecated, saying so in one line on stderr: edits land in the draft, so open the take there and use `timeline <p> import-item` (`takeImport.mjs`): each entry CLONED from the source's manifest as it is now (its card, context, knobs, narration with its takes and its pick) into the take's timeline -- one write, an undo point of the take's (`timeline <p> --take <id> undo`); the files it names (narration takes and their `take-<n>.*` sidecars, the parts' cache files, attachments, a context post's media, the picture of each author it draws that the take lacks, added to the take's `postAvatars`) **hard-linked** into this project's dir at the same path, so the render and the lint find them (copied across filesystems; the same file already there is left; ANOTHER file at the path: linked under `imports/<source>/<path>` and the clone names that). The source project and this project's manifest are only read. **Placed** `--after`/`--before` an entry of the take (several items in the order named, one after another), else by the post's date when the take's posts are in date order, else at the end. **Again**: updated in place from the source (moved only with `--after`/`--before`), `unchanged` with no write when nothing differs. `--as`: one item under another id (a second copy). `--dry-run`: the plan and the placement, nothing linked or written. `--json`: `items[] {id, action added\\|updated\\|unchanged\\|moved, at {index, after, before}, narration {takes, pick, file}, files[], avatars[]}`, `revision`. Refused while the take renders. **Exit 0 · 1 refused (no such item, take or entry; a link out of the project) · 2 usage**"],
["`take … --priority` · `takes make … --priority` · `render-mode on [--for 90m] [--note T] [--json \\| --print-token]` · `render-mode on [--for 90m] [--note T] [--print-token] -- <cmd …>` · `render-mode off [--force] [--json]` · `render-mode status [--json]`",
- "**render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription and download lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints (`--print-token`: the token alone on stdout, the rest on stderr). **`on … -- <cmd …>` is the form for a script**: the command is spawned with the token in its environment, the hold is the command's pid, and it is released when the command exits — done, failed, or umtool signalled (the signal is passed on); umtool exits with the command's code, and inside a manual window the command joins it. A bare `on` in a script leaves the window behind (the chain trap). `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, \"Render mode\")"],
+ "**render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription, download and Speakers lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints (`--print-token`: the token alone on stdout, the rest on stderr). **`on … -- <cmd …>` is the form for a script**: the command is spawned with the token in its environment, the hold is the command's pid, and it is released when the command exits — done, failed, or umtool signalled (the signal is passed on); umtool exits with the command's code, and inside a manual window the command joins it. A bare `on` in a script leaves the window behind (the chain trap). `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, \"Render mode\")"],
["`take status <project> [--id <take>] [--json] [--log] [--tail N]`",
"a take's **render record** (`takes/<take>/render.json`, written by every render whoever started it — a terminal, the Takes page, the queue): `state` (`running`, `waiting` at the heavy slot, `done`, `failed`, `cancelled`; `queued` or `blocked` while a queue step waits to render it), `stage` and a rough `percent`, the `error` (the first error line, not a bare \"exited 1\") and the log's last 40 lines (`tail`), on done the `mp4` and its measured `seconds`; `--log` prints the FULL `takes/<take>/render.log`. A \"running\" whose process is gone reads **failed** (\"the render process is gone\"); a done whose mp4 is missing or 0 bytes reads **failed**. **Exit 0 done · 3 queued, waiting or running · 1 failed, cancelled, blocked or none.** Without `--id`: every take with a record, the newest's exit ([queue and poll](#queue-and-poll-instead-of-scripting)); and its fast-feedback renders beside it, `preview` and `changes` (each one's state, mp4, seconds, log; a changes reel's piece count, its base and its list), a queued `--preview`/`--changes` step said as such -- never as the take's own render"],
],
diff --git a/umtool/lib/report/renderMode.mjs b/umtool/lib/report/renderMode.mjs
@@ -11,7 +11,7 @@
// umtool render-mode status [--json]
//
// On: the state file (beside the heavy slot's lock), then the editor's
-// transcription and download lanes held through its ops — the `lane` action
+// transcription, download and Speakers lanes held through its ops — the `lane` action
// `pnpm ops lane` posts — each only if it was not held already, and recorded,
// so off releases only those. The editor is ARCHILYZER_EDITOR_URL with
// WORKER_TOKEN, read as `pnpm ops` reads them (fetchWindows.mjs editorConfig).
diff --git a/umtool/lib/report/renderMode.test.mjs b/umtool/lib/report/renderMode.test.mjs
@@ -21,8 +21,11 @@ function tmpFile() {
return path.join(mkdtempSync(path.join(tmpdir(), "render-mode-")), "heavy.lock.render.json");
}
-/** A fake editor's lanes: `held` what it holds, `calls` what was asked. */
-function fakeLanes(held = {}) {
+/** A fake editor's lanes: `held` what it holds, `calls` what was asked. The
+ * Speakers (backfill) lane starts held, as it ships — so these tests' calls are
+ * the two lanes a render actually takes from a fresh install. */
+function fakeLanes(initial = {}) {
+ const held = { backfill: true, ...initial };
const calls = [];
return {
held,
@@ -108,7 +111,7 @@ await withTakePriority({ priority: true, project: "p", take: "t", log: (l) => co
const code = await new Promise((r) => child.on("exit", (c) => r(c)));
assert.equal(code, 143);
assert.equal(existsSync(file), false);
- assert.equal(readFileSync(log, "utf8"), "hold transcription\nhold download\nrelease transcription\nrelease download\n");
+ assert.equal(readFileSync(log, "utf8"), "hold transcription\nhold download\nhold backfill\nrelease transcription\nrelease download\nrelease backfill\n");
});
test("a take inside a manual window joins it (flag or not) and leaves it on; beside another render it takes nothing", async () => {
@@ -159,7 +162,7 @@ test("umtool render-mode on | status | off, with --json; off of a running take's
assert.equal(out.at(-1), "render mode is off");
assert.equal(await renderModeCommand(["on", "--for", "soon"], io), 2);
assert.equal(await renderModeCommand(["on", "--for", "90m"], io), 0);
- assert.match(out.join("\n"), /render mode ON until \d\d:\d\d — lanes held: transcription \(download already held — left alone\)/);
+ assert.match(out.join("\n"), /render mode ON until \d\d:\d\d — lanes held: transcription \(download, backfill already held — left alone\)/);
assert.match(out.join("\n"), /export RENDER_PRIORITY_TOKEN=[0-9a-f]{16}/);
assert.equal(await renderModeCommand(["on"], io), 1, "already on");
out.length = 0;
@@ -362,7 +365,7 @@ process.exit(await renderModeCommand(["on", "--", process.execPath, "-e", child]
const code = await new Promise((r) => proc.on("exit", (c) => r(c)));
assert.equal(code, 143);
assert.equal(existsSync(file), false);
- assert.equal(readFileSync(log, "utf8"), "hold transcription\nhold download\nrelease transcription\nrelease download\n");
+ assert.equal(readFileSync(log, "utf8"), "hold transcription\nhold download\nhold backfill\nrelease transcription\nrelease download\nrelease backfill\n");
for (let i = 0; i < 100 && !readFileSync(childLog, "utf8").includes("TERM"); i += 1) await new Promise((r) => setTimeout(r, 20));
assert.equal(readFileSync(childLog, "utf8"), "ready\nTERM\n", "the command got the signal");
});
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/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/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/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",
};