commit aae8e05d0e3432826eb9bbd4eca6079f4568cd03 parent c4332c83170a81226cc8457303eed73ea0637c73 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Sat, 17 Oct 2026 01:26:11 -0400 common, editor, mcp: full audio before a salvage (operator ruling 2026-10-17) — a corrupt full source whose record stores a trusted media URL is downloaded from it FULL_AUDIO_ATTEMPTS (2) times (R7's ranged reader, gap and audio check) before a salvage transcript: the refetch reads the stored URL by itself while attempts are owed, transcribeOne refuses an early automatic salvage (no-audio; salvage: true still forces), the editor's Transcribe and transcribe-one make the owed downloads first (controller/fullAudioFirst.ts); the snapshot's fullAudio and the flow's 'awaiting full audio' / 'salvaged — full audio attempts: n'; the partial mark on the video page notice, the video list and MCP get_transcripts; ops help (transcribe-one, retry-bucket, bench-verdicts dedupe), COMMANDS.md; e2e full-audio-first.spec.ts Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
23 files changed, 758 insertions(+), 20 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md @@ -37,7 +37,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer reports iterations` | `<articleId> [--json]` | an article's iterations (transcripts/reports/<id>/iterations/): each one's kind, model, status, cost, lineage and what it revised or copied, the current article and current video marked (exit 1 when an iteration.json is unsound; 2 for no such article) | | `archilyzer reports delete` | `<articleId> [--iteration <n>] [--apply] [--force] [--json]` | delete an article — its directory (report, video, history, notes, iterations), its iterations' video projects under settings.generation.projectsRoot and its staged exports — or, with --iteration, one iteration and its project, through the article registry. A dry run printing the plan (every path with its size, what is kept and why, what refuses) unless --apply. Refused: a published article, or a site page naming it with no report of its own (--force unpublishes it and drops the page first); a queued or running iteration; an iteration that is current (article, its report's source, video) or that another revises or copies (exit 1 when refused; 2 for no such article or iteration) | | `archilyzer reports respell` | `<articleId> --heard <form,…> --reads <word> [--bracket] [--note <text>] [--iteration <n>] [--apply] [--json]` | correct what the transcripts mishear across an article's quotes: each heard form (words, case-insensitive, a plural s carried) reads as --reads in the quotes of iteration n's report.json (default: the iteration the current report came from), the article's report.json when it is that report, and the iteration's video manifest (burned-in quotes, flip cards) — plainly, or bracketed (\[K-Cup\]) with --bracket; the report's own words plainly. Each file gains `respellings`, which every quote check (compose, verify-quotes, the video's cut-to-quote) applies to the transcript before comparing, so a corrected quote verifies as its original did. A dry run printing every change as before → after unless --apply, which backs each file up to the project's revisions/ first (exit 1 when nothing would change; 2 for usage, or no such article or iteration) | -| `archilyzer reports bench-verdicts` | `--models <a,b,…> [--report <id,…>] [--window <s>] [--window-mode seconds\|turn] [--max-usd <n>] [--limit <n>] [--items-from <run>] [--run <id>] [--dry] [--here] [--wait] [--json]` | the verdict bench (release 28; release 29 V1): every claim of the registry's fact-checks (or of --report) with the operator's verdict and a citation with cues, asked of each model one claim per call — the report's title, the claim's section, the claim, its quotes (their speaker and the recording's date) and the transcript within --window seconds (default 60) of each cited span, or with --window-mode turn the cited speaker's turn bounded by --window, never the findings or the verdict — and scored against the rulings (agreement, the confusion matrix, CONTRADICTED and NOT\_FOUND recall, not-CORROBORATED precision and recall, against an always-CORROBORATED baseline). --limit takes a stratified sample (by the operator's verdict: every verdict kept); --items-from takes an earlier run's exact items (no --report, --window, --window-mode or --limit with it). The run records its prompt version and its items' hash. --dry lists the items, the skipped claims and the dropped citations and estimates the cost, asking nothing. Otherwise through the editor (`pnpm ops bench-verdicts`; a local model through the GPU arbiter; --wait follows the job), or --here in this process for API models only. The run stops at --max-usd (default 5, the whole run); a --run that exists continues with this invocation's --models only (refused under another prompt version). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /tools/bench) (exit 1 when the run stopped early or was refused; 2 for usage) | +| `archilyzer reports bench-verdicts` | `--models <a,b,…> [--report <id,…>] [--window <s>] [--window-mode seconds\|turn] [--max-usd <n>] [--limit <n>] [--items-from <run>] [--dedupe] [--run <id>] [--dry] [--here] [--wait] [--json]` | the verdict bench (release 28; release 29 V1): every claim of the registry's fact-checks (or of --report) with the operator's verdict and a citation with cues, asked of each model one claim per call — the report's title, the claim's section, the claim, its quotes (their speaker and the recording's date) and the transcript within --window seconds (default 60) of each cited span, or with --window-mode turn the cited speaker's turn bounded by --window, never the findings or the verdict — and scored against the rulings (agreement, the confusion matrix, CONTRADICTED and NOT\_FOUND recall, not-CORROBORATED precision and recall, against an always-CORROBORATED baseline). --limit takes a stratified sample (by the operator's verdict: every verdict kept); --items-from takes an earlier run's exact items (no --report, --window, --window-mode, --limit or --dedupe with it); --dedupe asks a claim that repeats an earlier one (the same text over the same cited spans) once — without it every claim is asked. The run records its prompt version and its items' hash. --dry lists the items, the skipped claims and the dropped citations and estimates the cost, asking nothing. Otherwise through the editor (`pnpm ops bench-verdicts`; a local model through the GPU arbiter; --wait follows the job), or --here in this process for API models only. The run stops at --max-usd (default 5, the whole run); a --run that exists continues with this invocation's --models only (refused under another prompt version). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /tools/bench) (exit 1 when the run stopped early or was refused; 2 for usage) | | `archilyzer reports import-local-runs` | `[--apply] [--runs <dir>] [--only <run,…>] [--move-projects] [--generation <file>]` | ONE-OFF (release 27): the stopgap's kept runs (--runs: its directory, default ~/reports/local-reports; --only: those runs, default piratesoftware-ai-friends and api-shondo-recent) become i1 of their article through the iterations store — made current only when the run's report.json is the article's; a run with no article becomes an article in the making — and each video project is copied (--move-projects: moved) to the generation projects root; ~/.config/archilyzer/generation.json, when there is one, becomes settings.generation's routes and models. Lists the stopgap's test runs, projects and drafts to delete after the operator's OK (deletes nothing). A dry run printing the plan unless --apply (exit 1 when a run is refused) | | `archilyzer frames rederive` | `<slug>/<id> [--profile poker] [--hero <name>] [--dry] [--json]` | work a frame scan's derived timeline (tournaments, series, events, flags) out again from the readings frame-scan.<profile>.json already holds and the video's cues — no model, no frame, no editor — and write it back (--dry: print what would change, write nothing). Not while a scan of the video is running (it writes the same file): with an editor up, `pnpm ops frame-scan --json '{"slug","id","rederive":true}'` checks that (exit 1 when there is no sidecar; 2 for usage) | | `archilyzer gen policy` | `[--json]` | the generation policy: where each task runs (code = Claude Code, api = the Claude API, local = the local model), the models, the caps and the day's Claude API spend — from the editor, or settings.json when none answers | @@ -118,7 +118,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `refresh-report` | refresh-report regenerates a channel's report (the buckets and counts its page shows) on the one serial report queue: {"slug"} answers the job queued, or the one already waiting ("started": false); {"all": true} queues every channel and answers {queued, jobIds, skipped}. | `pnpm ops refresh-report --json '{"all":true}'` | | `sync` | sync lists a channel and downloads what is new, as its Sync button does: {"slug"}. "full": true runs the periodic whole-listing sweep now (else the configured cadence decides); "queueKey" picks another queue. On the channel's platform queue, paced like its downloads. | `pnpm ops sync --json '{"slug":"the-quartering"}' --wait` | | `download-missing` | download-missing downloads every listed video the channel does not hold: {"slug"}. "ignoreArchive": true drops the download archive so listed videos it names are fetched again (recovery from a stale archive); "abortOnError": false carries on past a failure (default: stop at the first that is not one video's own). Paced on the platform's queue. "storedUrl": "fallback" \| "only" reads each video from the media URL its record stores when the page is rate-limited (or always), one file per 20 min; with one, a held platform's run goes ahead as "only". | | -| `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. "storedUrl": "fallback" \| "only" reads each from the media URL its record stores, as on download-missing (a held platform's retry runs as "only"). "corruptHeldAudio" (held audio the audio audit found damaged) is refetched the same way, with the audio check on; the new file is audited again. | `pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait` | +| `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. A record that stores an Odysee media URL is read from that URL (as "only") until 2 such downloads are on record, then from the page. "storedUrl": "fallback" \| "only" reads each from the media URL its record stores, as on download-missing (a held platform's retry runs as "only"). "corruptHeldAudio" (held audio the audio audit found damaged) is refetched the same way, with the audio check on; the new file is audited again. | `pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait` | | `transcribe-bucket` | transcribe-bucket transcribes a channel's "downloaded, not transcribed" bucket on the transcription queue, as the channel page's Transcribe button does: {"slug"}. "ids": \[...\] narrows it the same way as on retry-bucket. | | | `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"}. "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). "full" and "older" together are refused. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. A drained fetch stops at its next resume point and the next run resumes. | | | `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/<id>/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. Paced like a post fetch, on its queue. | | @@ -144,7 +144,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `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}}'` | | `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. | | | `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` | -| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. A job; --wait follows it. "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. | | +| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. A job; --wait follows it. "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. | | | `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. | | | `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.) | | | `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` | @@ -158,7 +158,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "research" \| a media draft, "article", ...} -> {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). "seed" (a new sweep's, on a Claude model) is cited markdown in the /sweep shape — umtool's research board: kept as the iteration's seed.md, the report starts from it, and the sweep verifies and extends it. "ids" (a sweep's) restricts it to those recordings: an enumeration reads only their pages and answers only their rows, a read of another is refused. A "refresh" re-fetches an iteration's scope and folds in what changed: "iteration" (default: the current report's) — its question, its recorded enumerations and every channel its citations touch. One job on draft:refresh: the editor's own sync / refresh-report / transcribe-bucket (what landed) per video channel and fetch-posts per posts channel (a platform held or cooling down is skipped; transcribe-bucket is skipped, and said, while transcription is paused or no worker is enabled), then a local build of the site holding them (never a deploy); the enumerations again (new and changed recordings) and every cited quote read again (changed words, en vs en-orig, a source gone); nothing changed ends no-change, $0 — or partial, naming what a capped search did not reach. Else, within the caps ("model", "maxUsd", "extractorModel"; past one it ends held-by-cap with the delta and the estimate), a sweep restricted to the new recordings and a revision of the report: a new refresh iteration, refresh.json beside it. "fetch": false skips the fetch and the build; "dryRun": true answers {plan} and writes nothing. Its log ends with @@report-draft {…, refresh: {status, newIds, changed, drifted, deleted, summary}}. "verdicts" proposes a verdict for each UNRULED claim of a fact-check ("article"; "claims"? only those; "model"?, "maxUsd"?): the verdict bench's prompt, one claim per call, on a model in settings.generation.verdicts.models only (refused otherwise; none named: the first of them on the verdicts route). No iteration (iteration 0): the proposals go to the article's verdicts.proposed.json, never report.json; a claim the operator ruled, or whose proposal was reviewed, is not asked. Its log ends with @@report-draft {…, verdicts: {proposed, failed, skipped, promptVersion}}. | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article"}' --wait`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'`<br>`pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait`<br>`pnpm ops report-draft --json '{"task":"verdicts","article":"demo-factcheck"}' --wait` | | `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -> {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. An `auto` run is continued by the editor itself once ready; autoContinue says how (continued by, held for a build, refused by a cap, and why). Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` | | `verdict-review` | verdict-review settles one verdict proposal: {"article", "claim", "decision": "approve" \| "reject", "verdict", "at", "note"?} -> {proposal}. "verdict" and "at" are the proposal you were shown (its verdicts.proposed.json entry): a compare-and-set, refused (409) when the proposal was replaced or reviewed since, its claim changed (the proposal is stale) or was ruled meanwhile. approve sets the claim's verdict to it (through the registry); reject leaves the claim unruled. Synchronous. | `pnpm ops verdict-review --json '{"article":"demo-factcheck","claim":"c04","decision":"approve","verdict":"PARTLY","at":"2026-10-15T10:00:00.000Z"}'` | -| `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["<article>"\], "window"? (seconds, default 60), "windowMode"? ("seconds" \| "turn": the cited speaker's turn, bounded by the window), "maxUsd"? (default 5), "limit"? (a stratified sample, by the operator's verdict), "itemsFrom"? (an earlier run's exact items; no reports, window, windowMode or limit with it)} -> {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the report's title, the claim's section, the claim, its quotes, the transcript in the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues with this call's models only (answered pairs are skipped; refused under another prompt version). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /tools/bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` | +| `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["<article>"\], "window"? (seconds, default 60), "windowMode"? ("seconds" \| "turn": the cited speaker's turn, bounded by the window), "maxUsd"? (default 5), "limit"? (a stratified sample, by the operator's verdict), "itemsFrom"? (an earlier run's exact items; no reports, window, windowMode, limit or dedupe with it), "dedupe"? (true: a claim repeating an earlier one, the same text over the same cited spans, is asked once; default: every claim is asked)} -> {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the report's title, the claim's section, the claim, its quotes, the transcript in the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues with this call's models only (answered pairs are skipped; refused under another prompt version). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /tools/bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` | | `frame-scan` | frame-scan reads a saved stream's frames for a profile's progress: {"slug", "id", "profile"? ("poker", the default), "everySeconds"? (default settings.generation.frames.everySeconds, 10), "from"?, "to"? (source seconds), "maxFrames"? (5000), "model"? (default the `frames` route's model), "maxUsd"? (default frames.maxUsd, at most caps.max), "hero"? (the hero's screen name, a hint), "framesPerAsk"? (1-8), "crop"? (\[x, y, w, h\] as fractions of the picture: the part read and hashed, e.g. the poker client beside a webcam), "fresh"? (read every frame again: another model or prompt), "evict"?, "rederive"?} -> {jobId, model, queueKey}. The video's saved container is sampled (keyframes, one ffmpeg a half hour) into a frame cache on the channel's media side; near-duplicate frames are skipped; the rest are read by the vision model and the numbers the streamer said are read from the transcript; frame-scan.<profile>.json beside the video gets the readings and the derived series, events, segments and flags (a frame and a spoken number that disagree). On `frames` (API) or draft:local (a local vision model, through the GPU arbiter). The same body again resumes: read frames are never asked again. Refused when the video is not saved (persist-videos first) or past caps.daily; the run stops before an ask that would pass maxUsd. {"evict": true} removes the frame cache and answers at once; {"rederive": true} works the derived timeline out again from the readings the sidecar holds (no model, no frame; refused while a scan of the video runs) and answers {rederived: {before, after, tournaments, eventsByKind}}. The log ends with @@frame-scan {slug, id, profile, file, frames, kept, read, failed, readings, spentUsd, totalUsd, events, tournaments, flags, stopped?}. | `pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","profile":"poker","maxUsd":2}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","hero":"DemoHero","crop":[0.02,0.1,0.7,0.68],"from":3000,"to":3600}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","evict":true}'`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","rederive":true}'` | | `mirror-scan` | mirror-scan pairs a mirror channel with the creator it copies: {"slug", "dryRun"?} -> {jobId}. The channel's config names the creator's channels (mirror.of; channel-config's "mirrorOf"); refused without them. Each of the mirror's videos, dated by its recorded date (else its upload date), is matched with the creator's videos uploaded one day before to two after, by title words and duration (the index's records; no media, no network); per video the matches and a status: only-copy (no creator platform has it public), creator-deleted (removed on one platform, public on another), never-uploaded (missing on one platform, public on the rest) or creator-public. The other way: the creator's removed (deleted or private) uploads dated inside the mirror's window, and which the mirror holds. Written to transcripts/mirrors/<slug>.json (private: never published); the channel page's Mirror stage shows it. dryRun writes nothing. The log ends with @@mirror-scan {slug, dryRun, file?, of, missing?, window, videos, matched, byStatus, byPlatform, creatorRemoved: {inWindow, held, byChannel}}. | `pnpm ops mirror-scan --json '{"slug":"demo-vod-archive","dryRun":true}' --wait`<br>`pnpm ops mirror-scan --json '{"slug":"demo-vod-archive"}' --wait` | | `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage" \| "learn" \| "unlearn" \| "promote-alias" \| "add-spelling", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. add-spelling {"id", "spelling", "means"} adds a spelling by hand (no model): "means" is one of the names the terms watch; it is counted in scope and its proving line found by code, and kept (source hand) only when it occurs; a removed spelling added by hand is no longer blocked. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'`<br>`pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'` | diff --git a/common/controller/channelSnapshot.test.ts b/common/controller/channelSnapshot.test.ts @@ -910,3 +910,53 @@ test("a salvage transcript is salvagedTranscript; its corrupt full source stays await rm(dir, { recursive: true, force: true }); } }); + +// Release 32 R8: on a channel whose platform serves stored media URLs, the +// snapshot's `fullAudio` counts each corrupt full source's stored-URL download +// attempts, and lists the untranscribed ones still owed one (`awaiting`). +test("fullAudio: a stored-URL channel's corrupt full sources, their attempts, the ones awaiting full audio", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "ttb-snap-fullaudio-")); + try { + const paths = { channelsDir: path.join(dir, "channels") } as Paths; + const make = async (slug: string, url: string, extra: object = {}) => { + const channelDir = path.join(paths.channelsDir, slug); + const ids = ["aaaa0000001", "bbbb0000002", "cccc0000003"]; + for (const id of ids) await mkdir(path.join(channelDir, "data", id), { recursive: true }); + await writeFile(path.join(channelDir, "config.json"), JSON.stringify({ handling: "transcribe", url, ...extra })); + await writeFile(path.join(channelDir, "playlist"), ids.map((id) => `https://odysee.com/v:${id}`).join("\n")); + const put = (id: string, name: string, body: unknown) => + writeFile(path.join(channelDir, "data", id, name), typeof body === "string" ? body : JSON.stringify(body)); + const stored = { n: 1, kind: "stored-url-ranged", handling: "transcribe", usedCookies: false, ytdlpExitCode: 1 }; + const cfs = (id: string, n: number) => ({ + videoId: id, + status: "corrupt-full-source", + startedAt: "2026-10-01T00:00:00.000Z", + finishedAt: "2026-10-01T00:01:00.000Z", + attempts: Array.from({ length: n }, () => stored), + }); + const salvaged = { source: "audio.mp4", decodedSeconds: 100, totalSeconds: 600, gaps: [[100, 600]] }; + for (const id of ids) { + await put(id, "metadata.info.json", { id, duration: 600 }); + await put(id, "audio.mp4", "x"); + } + await put("aaaa0000001", "download-outcome.json", cfs("aaaa0000001", 0)); + await put("bbbb0000002", "download-outcome.json", cfs("bbbb0000002", 2)); + await put("cccc0000003", "download-outcome.json", cfs("cccc0000003", 1)); + await put("cccc0000003", "transcript.json", "{}"); + await put("cccc0000003", "transcribe-outcome.json", { videoId: "cccc0000003", transcribedAt: "2026-10-15T00:00:00.000Z", salvaged }); + }; + await make("ody", "https://odysee.com/@synth:1"); + await make("yt", "https://www.youtube.com/@synth/videos"); + await make("never", "https://odysee.com/@synth:2", { storedUrlDownloads: "never" }); + const ody = await generateChannelSnapshot(paths, "ody"); + assert.deepEqual(ody.fullAudio, { + of: 2, + attempts: { aaaa0000001: 0, bbbb0000002: 2, cccc0000003: 1 }, + awaiting: ["aaaa0000001"], + }); + assert.equal((await generateChannelSnapshot(paths, "yt")).fullAudio, undefined, "not a stored-URL platform"); + assert.equal((await generateChannelSnapshot(paths, "never")).fullAudio, undefined, "the channel says never"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/common/controller/channelSnapshot.ts b/common/controller/channelSnapshot.ts @@ -87,6 +87,9 @@ import { deriveChannelSets } from "./channelSets"; import { readTranscriptCoverage } from "./normalizeTranscript"; import { resolveCaptionsProvenance } from "../lib/subtitleProvenance"; import { isIncompleteTranscript } from "../lib/transcriptCoverage"; +import { detectPlatform } from "../lib/platform"; +import { isStoredUrlPlatform } from "../lib/storedMediaUrl"; +import { FULL_AUDIO_ATTEMPTS, fullAudioAttemptsOf } from "../lib/fullAudioFirst"; // THE PER-OPERATION WORK LISTS, keyed by operation id. // @@ -182,6 +185,14 @@ export type ChannelSnapshot = { // reason: no live snapshot is regenerated by the slice that added them, so // every reader falls back to the bucket fold until a channel's next regen. backfill?: ChannelSnapshotOperations; + // FULL AUDIO BEFORE A SALVAGE (release 32 R8, lib/fullAudioFirst.ts), on a + // channel whose platform serves stored media URLs (STORED_URL_PLATFORMS) and + // whose stored-URL mode is not "never": every corrupt full source's + // stored-URL download attempts so far (`attempts`, by id), of `of`, and the + // untranscribed ones still owed one (`awaiting` — no salvage until then). + // The channel's platform stands in for each record's trusted URL (no + // metadata read per video). Omitted when there are none. + fullAudio?: { of: number; attempts: Record<string, number>; awaiting: string[] }; buckets: { noTranscript: string[]; downloadedNoTranscript: string[]; @@ -1251,6 +1262,13 @@ export async function generateChannelSnapshot( const incompleteTranscript: string[] = []; const salvagedTranscript: string[] = []; const corruptHeldAudio: string[] = []; + // Release 32 R8: full audio before a salvage (the snapshot's `fullAudio`). + const fullAudioChannel = + config?.handling === "transcribe" && + config.storedUrlDownloads !== "never" && + isStoredUrlPlatform(config.platform ?? detectPlatform(config.url)); + const fullAudioAttempts: Record<string, number> = {}; + const fullAudioAwaiting: string[] = []; // The audio audit's verdicts over the channel (release 32): every // audio-integrity.json, by the rule in force. const audioIntegrity: AudioIntegrityTally = { clean: 0, damaged: 0, undecodable: 0, stale: 0 }; @@ -1381,6 +1399,11 @@ export async function generateChannelSnapshot( if (salvaged) salvagedTranscript.push(id); if (outcome?.status === "corrupt-full-source") { corruptFullSource.push(id); + if (fullAudioChannel) { + const n = fullAudioAttemptsOf(outcome); + fullAudioAttempts[id] = n; + if (n < FULL_AUDIO_ATTEMPTS && !salvaged && !isVideoTranscribed(files)) fullAudioAwaiting.push(id); + } continue; } // Held audio the audit found damaged (release 31, lane A). Untranscribed, @@ -1823,6 +1846,9 @@ export async function generateChannelSnapshot( : {}), }, digestEngines, + ...(Object.keys(fullAudioAttempts).length + ? { fullAudio: { of: FULL_AUDIO_ATTEMPTS, attempts: fullAudioAttempts, awaiting: fullAudioAwaiting.sort() } } + : {}), backfill: { ...backfillCounts, ...bucketLaneEntries }, undownloadedIds, excludedFromDownload, diff --git a/common/controller/fullAudioFirst.test.ts b/common/controller/fullAudioFirst.test.ts @@ -0,0 +1,153 @@ +// Full audio before a salvage (release 32 R8): the rule (pure), the reader, the +// controller's loop, and transcribeOne's refusal of an early automatic salvage. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fullAudioFirst.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import path from "node:path"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import type { DownloadAttempt, DownloadOutcomeRecord } from "../lib/downloadOutcome"; +import { FULL_AUDIO_ATTEMPTS, fullAudioAttemptsOf, fullAudioFirstRefusal, fullAudioLine, fullAudioState } from "../lib/fullAudioFirst"; +import { fullAudioGate } from "../lib/fullAudioFirst-server"; +import { fullAudioFirst } from "./fullAudioFirst"; +import { transcribeOneVideo } from "./transcribeOne"; +import { TranscribeError } from "./transcribeError"; +import type { Paths } from "../lib/paths"; +import type { Worker } from "../lib/workers"; + +const CLAIM = "FAKE-TEST-VALUEFAKE-TEST-VALUE01234567"; +const stored = (n: number): DownloadAttempt[] => + Array.from({ length: n }, () => ({ n: 1, kind: "stored-url-ranged" as const, handling: "transcribe" as const, usedCookies: false, ytdlpExitCode: 1 })); +const cfs = (storedAttempts: number, status: DownloadOutcomeRecord["status"] = "corrupt-full-source"): DownloadOutcomeRecord => ({ + videoId: CLAIM, + status, + startedAt: "2026-10-15T00:00:00.000Z", + finishedAt: "2026-10-15T01:00:00.000Z", + attempts: [{ n: 1, kind: "audio-checked-primary", handling: "transcribe", usedCookies: false, ytdlpExitCode: 0 }, ...stored(storedAttempts)], +}); + +test("the rule: stored-URL attempts counted; owed until FULL_AUDIO_ATTEMPTS; not applicable off the allowlist, never, or another handling", () => { + assert.equal(FULL_AUDIO_ATTEMPTS, 2); + assert.equal(fullAudioAttemptsOf(cfs(0)), 0); + assert.equal(fullAudioAttemptsOf(cfs(3)), 3); + assert.equal(fullAudioAttemptsOf(null), 0); + assert.deepEqual(fullAudioState(cfs(0), { storedUrlTrusted: true }), { attempts: 0, of: 2, exhausted: false }); + assert.deepEqual(fullAudioState(cfs(1), { storedUrlTrusted: true, handling: "transcribe" }), { attempts: 1, of: 2, exhausted: false }); + assert.deepEqual(fullAudioState(cfs(2), { storedUrlTrusted: true }), { attempts: 2, of: 2, exhausted: true }); + assert.equal(fullAudioState(cfs(0), { storedUrlTrusted: false }), null, "no trusted stored URL"); + assert.equal(fullAudioState(cfs(0), { storedUrlTrusted: true, mode: "never" }), null, "an explicit never"); + assert.equal(fullAudioState(cfs(0), { storedUrlTrusted: true, handling: "youtube" }), null); + assert.equal(fullAudioState(cfs(0, "ok"), { storedUrlTrusted: true }), null, "not a corrupt full source"); + assert.equal(fullAudioLine({ attempts: 1, of: 2 }), "full audio attempts: 1 of 2"); + assert.match(fullAudioFirstRefusal({ attempts: 0, of: 2, exhausted: false }), /^Full audio first \(full audio attempts: 0 of 2\)/); +}); + +async function videoDir(o: { record?: DownloadOutcomeRecord; formats?: unknown[]; config?: object } = {}) { + const root = await mkdtemp(path.join(tmpdir(), "full-audio-")); + const channel = path.join(root, "channels", "c"); + const dir = path.join(channel, "data", CLAIM); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(channel, "config.json"), JSON.stringify(o.config ?? { handling: "transcribe", url: "https://odysee.com/@synth:1" })); + await writeFile( + path.join(dir, "metadata.info.json"), + JSON.stringify({ + id: CLAIM, + webpage_url: `https://odysee.com/synthetic-stream:${CLAIM}`, + formats: o.formats ?? [{ url: "https://player.odycdn.com/v6/streams/x/y.mp4", protocol: "https", ext: "mp4" }], + }), + ); + if (o.record) await writeFile(path.join(dir, "download-outcome.json"), JSON.stringify(o.record)); + await writeFile(path.join(dir, "audio.mp4"), "kept malformed"); + return { root, dir, done: () => rm(root, { recursive: true, force: true }) }; +} + +test("the reader: the record's status and its trusted stored URL", async () => { + const a = await videoDir({ record: cfs(1) }); + const b = await videoDir({ record: cfs(0), formats: [{ url: "https://cdn.example/x.mp4", protocol: "https" }] }); + const c = await videoDir({ record: cfs(0, "ok") }); + try { + assert.deepEqual(await fullAudioGate(a.dir), { attempts: 1, of: 2, exhausted: false }); + assert.deepEqual(await fullAudioGate(a.dir, { mode: "never" }), null); + assert.equal(await fullAudioGate(b.dir), null, "a host off the CDN list is not trusted"); + assert.equal(await fullAudioGate(c.dir), null); + } finally { + await Promise.all([a.done(), b.done(), c.done()]); + } +}); + +test("the loop: downloads the owed attempts — clean stops it; exhausted lets the salvage follow; a refusal with attempts owed stops with an error; not applicable downloads nothing", async () => { + const states = (seq: (number | null)[]) => { + let i = 0; + return async () => { + const n = seq[Math.min(i++, seq.length - 1)]; + return n === null ? null : { attempts: n, of: 2, exhausted: n >= 2 }; + }; + }; + const rec = (status: DownloadOutcomeRecord["status"], failureClass?: DownloadOutcomeRecord["failureClass"]) => ({ ...cfs(0, status), ...(failureClass ? { failureClass } : {}) }); + const log: string[] = []; + let calls = 0; + const base = { videoDir: "/x", onLog: (l: string) => log.push(l) }; + + calls = 0; + assert.equal(await fullAudioFirst({ ...base, gate: states([null]), download: async () => (calls++, rec("ok")) }), "not-needed"); + assert.equal(calls, 0); + + calls = 0; + assert.equal(await fullAudioFirst({ ...base, gate: states([0, 1]), download: async () => (calls++, rec("ok-audio-checked")) }), "clean"); + assert.equal(calls, 1); + + calls = 0; + assert.equal(await fullAudioFirst({ ...base, gate: states([0, 1, 2]), download: async () => (calls++, rec("corrupt-full-source")) }), "exhausted"); + assert.equal(calls, 2, "both owed attempts, then the salvage"); + + calls = 0; + assert.equal(await fullAudioFirst({ ...base, gate: states([2]), download: async () => (calls++, rec("ok")) }), "exhausted"); + assert.equal(calls, 0, "attempts already made: nothing downloaded"); + + calls = 0; + await assert.rejects( + fullAudioFirst({ ...base, gate: states([0, 1]), download: async () => (calls++, rec("failed", "rate_limit")) }), + /refused the download \(rate limited; full audio attempts: 1 of 2\)/, + ); + assert.equal(calls, 1, "a refusal is not hammered"); + + // A refusal that made the last owed attempt: the salvage may follow. + assert.equal(await fullAudioFirst({ ...base, gate: states([1, 2]), download: async () => rec("failed", "rate_limit") }), "exhausted"); + assert.ok(log.some((l) => l.startsWith("Full audio first (full audio attempts: 0 of 2)"))); +}); + +const worker: Worker = { id: "w1", name: "fake", kind: "local", enabled: true, priority: 0, appId: "whisper-cpp", config: { bin: "/bin/false", model: "m.bin" } }; + +test("transcribeOne: an automatic salvage of a corrupt full source with attempts owed is refused (no-audio); salvage: true still forces one", async () => { + const v = await videoDir({ record: cfs(1) }); + try { + const err = await transcribeOneVideo({ paths: {} as Paths, videoDir: v.dir, videoId: CLAIM, audioFilename: "audio.mp4", worker, onLog: () => {} }).then( + (x) => x, + (e) => e, + ); + assert.ok(err instanceof TranscribeError, String(err)); + assert.equal(err.failureClass, "no-audio"); + assert.match(err.message, /Full audio first \(full audio attempts: 1 of 2\)/); + // Forced: the gate is not asked (the engine here is /bin/false — some other failure, never the refusal). + const forced = await transcribeOneVideo({ paths: { ffmpegBin: "/bin/false", ffprobeBin: "/bin/false" } as Paths, videoDir: v.dir, videoId: CLAIM, audioFilename: "audio.mp4", worker, salvage: true, onLog: () => {} }).then( + (x) => x, + (e) => e, + ); + assert.doesNotMatch(String((forced as Error)?.message ?? forced), /Full audio first/); + } finally { + await v.done(); + } + // The channel says never: release 30's automatic salvage (not refused by the gate). + const n = await videoDir({ record: cfs(0), config: { handling: "transcribe", url: "https://odysee.com/@synth:1", storedUrlDownloads: "never" } }); + try { + const r = await transcribeOneVideo({ paths: { ffmpegBin: "/bin/false", ffprobeBin: "/bin/false" } as Paths, videoDir: n.dir, videoId: CLAIM, audioFilename: "audio.mp4", worker, onLog: () => {} }).then( + (x) => x, + (e) => e, + ); + assert.doesNotMatch(String((r as Error)?.message ?? r), /Full audio first/); + } finally { + await n.done(); + } +}); diff --git a/common/controller/fullAudioFirst.ts b/common/controller/fullAudioFirst.ts @@ -0,0 +1,74 @@ +// FULL AUDIO BEFORE A SALVAGE, for a transcription that would salvage +// (operator ruling 2026-10-17, release 32 R8; the rule: lib/fullAudioFirst.ts). +// +// The editor's Transcribe (and `pnpm ops transcribe-one`) on a corrupt full +// source whose record stores a trusted media URL first makes the full-audio +// attempts that are still owed: each a managed download (`download`, the +// caller's downloadOneManaged with `storedUrl: "only"` — the corrupt-source +// refetch around R7's ranged reader, its audio check and its 20-minute gap), +// until one comes back clean or FULL_AUDIO_ATTEMPTS are on record. Then the +// transcription runs: in full after a clean download, as a salvage once the +// attempts are exhausted. +// +// not-needed the rule does not apply (not a corrupt full source, no trusted +// stored URL, a stored-URL mode of never): transcribe as before +// clean a download came back clean: the audio is whole +// exhausted every attempt made, none clean: the salvage may follow +// +// A refusal (rate limit) with attempts still owed stops here with an error that +// says so — the next Transcribe tries again; nothing is hammered. A cancel +// stops at once. + +import type { DownloadOutcomeRecord } from "../lib/downloadOutcome"; +import { FULL_AUDIO_ATTEMPTS, fullAudioLine, type FullAudioState } from "../lib/fullAudioFirst"; +import { fullAudioGate } from "../lib/fullAudioFirst-server"; +import type { StoredUrlMode } from "../lib/storedMediaUrl"; + +export type FullAudioFirstResult = "not-needed" | "clean" | "exhausted"; + +export async function fullAudioFirst(o: { + videoDir: string; + handling?: string; + mode?: StoredUrlMode; + onLog: (line: string) => void; + signal?: AbortSignal; + download: () => Promise<DownloadOutcomeRecord>; + // Tests: the gate's reading (default: the video dir's). + gate?: (videoDir: string) => Promise<FullAudioState | null>; +}): Promise<FullAudioFirstResult> { + const gate = + o.gate ?? + ((dir: string) => + fullAudioGate(dir, { ...(o.handling ? { handling: o.handling } : {}), ...(o.mode ? { mode: o.mode } : {}) })); + let state = await gate(o.videoDir); + if (!state) return "not-needed"; + // At most the owed attempts: a download that records no stored-URL attempt + // (it should not happen) cannot loop. + for (let i = 0; i < FULL_AUDIO_ATTEMPTS && !state.exhausted; i++) { + if (o.signal?.aborted) throw abortError(); + o.onLog(`Full audio first (${fullAudioLine(state)}): downloading from the stored media URL before any salvage.`); + const record = await o.download(); + if (record.status.startsWith("ok")) { + o.onLog("The stored media URL's download is clean: the audio is transcribed in full."); + return "clean"; + } + if (o.signal?.aborted) throw abortError(); + const next = await gate(o.videoDir); + if (!next) return "not-needed"; + state = next; + if (record.failureClass === "rate_limit" && !state.exhausted) { + throw new Error( + `The stored media URL refused the download (rate limited; ${fullAudioLine(state)}). ` + + `The salvage waits for the full-audio attempts: transcribe again later.`, + ); + } + o.onLog(`The download ended ${record.status}${record.failureClass ? ` (${record.failureClass})` : ""}; ${fullAudioLine(state)}.`); + } + return state.exhausted ? "exhausted" : "not-needed"; +} + +function abortError(): Error { + const err = new Error("full-audio download aborted"); + err.name = "AbortError"; + return err; +} diff --git a/common/controller/transcribeOne.ts b/common/controller/transcribeOne.ts @@ -24,6 +24,9 @@ import { resolveSavedVideo } from "../lib/savedVideo-server"; import { writeTranscribeOutcome } from "../lib/transcribeOutcome-server"; import type { TranscriptSalvage } from "../lib/transcribeOutcome"; import { loadDownloadOutcome } from "../lib/downloadOutcome-server"; +import { fullAudioGate } from "../lib/fullAudioFirst-server"; +import { fullAudioFirstRefusal } from "../lib/fullAudioFirst"; +import { readChannelConfigFile } from "./channels"; import { SALVAGE_WAV_FILENAME, describeSalvage, @@ -174,8 +177,9 @@ export type TranscribeOneOptions = { // what is missing in transcribe-outcome.json's `salvaged`. Asked for by // `transcribe-one {"salvage": true}`; AUTOMATIC for a video whose download // outcome is corrupt-full-source (its file is known to be malformed, and a - // plain run fails at the first bad window), or whose held audio the audio - // audit found damaged (release 31). False forces a plain run. + // plain run fails at the first bad window) — once its full-audio attempts + // are made (release 32 R8, lib/fullAudioFirst.ts) — or whose held audio the + // audio audit found damaged (release 31). False forces a plain run. salvage?: boolean; }; @@ -235,10 +239,26 @@ export async function transcribeOneVideo( // said not to — or when the file about to be read is held audio the audio // audit found damaged (release 31, lane A: its audio-integrity.json still // speaks for this very file). +// +// FULL AUDIO FIRST (operator ruling 2026-10-17, release 32 R8): a corrupt full +// source whose record stores a trusted media URL is not salvaged automatically +// until FULL_AUDIO_ATTEMPTS stored-URL downloads were made +// (lib/fullAudioFirst.ts) — the run is refused as "no-audio" (a batch skips +// it, no failure recorded). `salvage: true` still forces one. async function salvageWanted(opts: TranscribeOneOptions, resolvedAudio: string): Promise<boolean> { if (opts.salvage !== undefined) return opts.salvage; const outcome = await loadDownloadOutcome(opts.videoDir).catch(() => null); - if (outcome?.status === "corrupt-full-source") return true; + if (outcome?.status === "corrupt-full-source") { + // The channel's config.json, beside data/<id>/: its handling and its + // stored-URL mode (an explicit "never" keeps the old behaviour). + const config = await readChannelConfigFile(path.join(path.dirname(path.dirname(opts.videoDir)), "config.json")).catch(() => null); + const gate = await fullAudioGate(opts.videoDir, { + ...(config?.handling ? { handling: config.handling } : {}), + ...(config?.storedUrlDownloads ? { mode: config.storedUrlDownloads } : {}), + }); + if (gate && !gate.exhausted) throw new TranscribeError(fullAudioFirstRefusal(gate), "no-audio"); + return true; + } const damage = await heldAudioDamage(opts.videoDir).catch(() => null); return damage !== null && damage.file === resolvedAudio; } diff --git a/common/lib/fullAudioFirst-server.ts b/common/lib/fullAudioFirst-server.ts @@ -0,0 +1,17 @@ +// The reader of a video's full-audio state (lib/fullAudioFirst.ts): its +// download record and whether its record stores a trusted media URL. + +import { loadDownloadOutcome } from "./downloadOutcome-server"; +import { fullAudioState, type FullAudioState } from "./fullAudioFirst"; +import { storedMediaUrl } from "./storedMediaUrl-server"; +import type { StoredUrlMode } from "./storedMediaUrl"; + +export async function fullAudioGate( + videoDir: string, + o: { handling?: string; mode?: StoredUrlMode } = {}, +): Promise<FullAudioState | null> { + const record = await loadDownloadOutcome(videoDir).catch(() => null); + if (record?.status !== "corrupt-full-source") return null; + const stored = await storedMediaUrl(videoDir); + return fullAudioState(record, { storedUrlTrusted: stored !== null, ...o }); +} diff --git a/common/lib/fullAudioFirst.ts b/common/lib/fullAudioFirst.ts @@ -0,0 +1,67 @@ +// FULL AUDIO BEFORE A SALVAGE (operator ruling 2026-10-17; release 32 R8). +// +// A corrupt-full-source video (release 30, lane Q: the download completed, its +// audio stayed malformed) used to be salvage-transcribed as soon as anyone +// transcribed it. The ruling: a partial transcript is fine and stays marked, +// but only once the full audio has been tried. For a record whose platform +// serves its stored media URL (lib/storedMediaUrl.ts, STORED_URL_PLATFORMS), +// the corrupt-source path first downloads from that URL — R7's ranged reader +// with the audio check (ytdlp/storedUrlDownload.ts) — FULL_AUDIO_ATTEMPTS +// times, paced by R7's gap (STORED_URL_NEW_FILE_GAP_MS), and only then may a +// salvage transcript be made. A clean download retires a salvage already made +// (corruptRefetch.ts, release 30's rule). +// +// AN ATTEMPT is a `stored-url-ranged` attempt in the video's download record: +// a refetch appends its attempts to the corrupt-full-source record, so the +// count is the video's whole stored-URL history. A refusal (429) counts: the +// ruling is a number of attempts, not of successes. +// +// NOT APPLICABLE (null): a video that is not a corrupt full source, a record +// with no trusted stored URL, a channel that is not transcribe handling, or a +// stored-URL mode of "never" (the request's, else the channel's +// `storedUrlDownloads` — an explicit never keeps release 30's behaviour). +// +// Pure: the reader is fullAudioFirst-server.ts. + +import type { DownloadOutcomeRecord } from "./downloadOutcome"; +import type { StoredUrlMode } from "./storedMediaUrl"; + +export const FULL_AUDIO_ATTEMPTS = 2; + +export type FullAudioState = { + // Stored-URL full-download attempts made so far. + attempts: number; + of: number; + // Every attempt made: a salvage may follow. + exhausted: boolean; +}; + +export function fullAudioAttemptsOf(record: Pick<DownloadOutcomeRecord, "attempts"> | null | undefined): number { + return (record?.attempts ?? []).filter((a) => a.kind === "stored-url-ranged").length; +} + +export function fullAudioState( + record: Pick<DownloadOutcomeRecord, "status" | "attempts"> | null | undefined, + o: { storedUrlTrusted: boolean; handling?: string; mode?: StoredUrlMode }, +): FullAudioState | null { + if (record?.status !== "corrupt-full-source") return null; + if (!o.storedUrlTrusted || o.mode === "never") return null; + if (o.handling !== undefined && o.handling !== "transcribe") return null; + const attempts = fullAudioAttemptsOf(record); + return { attempts, of: FULL_AUDIO_ATTEMPTS, exhausted: attempts >= FULL_AUDIO_ATTEMPTS }; +} + +// "full audio attempts: 1 of 2" +export function fullAudioLine(s: Pick<FullAudioState, "attempts" | "of">): string { + return `full audio attempts: ${s.attempts} of ${s.of}`; +} + +// What a transcription that would salvage too early says (transcribeOne's +// refusal; the editor's Transcribe downloads the attempts first). +export function fullAudioFirstRefusal(s: FullAudioState): string { + return ( + `Full audio first (${fullAudioLine(s)}): a salvage transcript waits until the stored media URL ` + + `has been tried ${s.of} times. Transcribe from the video page downloads them first; ` + + `transcribe with salvage to make the partial transcript now.` + ); +} diff --git a/common/views/pipeline/channelFlow.test.ts b/common/views/pipeline/channelFlow.test.ts @@ -337,3 +337,21 @@ test("every optional snapshot field survives being absent", () => { for (const sd of g.sidings) assert.ok(Number.isFinite(sd.count)); } }); + +// Release 32 R8: the full-audio state in the flow — corrupt full sources still +// owed a stored-URL download, and the salvaged siding's attempts. +test("the flow says which corrupt full sources await full audio, and the salvaged siding's attempts", () => { + const buckets = { ...normalizeBuckets(undefined), corruptFullSource: ["a", "b", "c"], salvagedTranscript: ["c"] }; + const flow = flowOf( + snapshotOf({ buckets, fullAudio: { of: 2, attempts: { a: 0, b: 1, c: 2 }, awaiting: ["a", "b"] } }), + ); + const all = flow.gaps.flatMap((g) => g.sidings); + const awaiting = all.find((s) => s.label === "awaiting full audio"); + assert.equal(awaiting?.count, 2); + assert.match(awaiting?.hint ?? "", /tried 2 times before a salvage transcript is made; full audio attempts so far: 0–1 of 2/); + assert.equal(all.find((s) => s.label.startsWith("salvaged"))?.label, "salvaged — full audio attempts: 2"); + // Without the snapshot's fullAudio (another platform), the old label. + const plain = flowOf(snapshotOf({ buckets })).gaps.flatMap((g) => g.sidings); + assert.ok(plain.some((s) => s.label === "salvaged transcript")); + assert.ok(!plain.some((s) => s.label === "awaiting full audio")); +}); diff --git a/common/views/pipeline/channelFlow.ts b/common/views/pipeline/channelFlow.ts @@ -164,6 +164,29 @@ function ratio(through: number | null, denominator: number | null): number | nul return Math.min(1, through / denominator); } +// THE FULL-AUDIO STATE IN THE FLOW (release 32 R8). The salvaged siding reads +// "salvaged — full audio attempts: n" on a channel that tries the stored media +// URL first (the snapshot's `fullAudio`); n is a range when the videos differ. +type FullAudioSnapshot = ChannelSnapshot["fullAudio"]; + +function attemptsRange(fullAudio: FullAudioSnapshot, ids: readonly string[]): string | null { + const ns = ids.map((id) => fullAudio?.attempts[id]).filter((n): n is number => n !== undefined); + if (ns.length === 0) return null; + const lo = Math.min(...ns); + const hi = Math.max(...ns); + return lo === hi ? `${lo}` : `${lo}–${hi}`; +} + +export function salvagedLabel(fullAudio: FullAudioSnapshot, salvaged: readonly string[]): string { + const n = attemptsRange(fullAudio, salvaged); + return n === null ? "salvaged transcript" : `salvaged — full audio attempts: ${n}`; +} + +function attemptsSummary(fullAudio: FullAudioSnapshot, ids: readonly string[]): string { + const n = attemptsRange(fullAudio, ids); + return `full audio attempts so far: ${n ?? "0"} of ${fullAudio?.of ?? 0}`; +} + function siding( label: string, count: number, @@ -233,6 +256,7 @@ export function computeChannelFlow( const totals = snapshot.totals ?? { videos: 0, transcribed: 0, downloaded: 0 }; const undownloadedIds = snapshot.undownloadedIds ?? []; const excluded = snapshot.excludedFromDownload; + const fullAudio = snapshot.fullAudio; const excludedIds = excludedDownloadIdSet(snapshot); const actionableDownloadedNoTranscript = buckets.downloadedNoTranscript.filter( (id) => !excludedIds.has(id), @@ -450,6 +474,15 @@ export function computeChannelFlow( "download", "The audio audit found part of the held file will not decode; it is kept. A retry downloads again with the audio check.", ), + // Release 32 R8: corrupt full sources still owed a stored-URL download + // before any salvage transcript (lib/fullAudioFirst.ts). + ...siding( + "awaiting full audio", + fullAudio?.awaiting.length ?? 0, + "download", + `Corrupt full sources whose stored media URL is tried ${fullAudio?.of ?? 0} times before a salvage transcript is made; ` + + `${attemptsSummary(fullAudio, fullAudio?.awaiting ?? [])}. A retry or Transcribe downloads the next one.`, + ), ], transcribe: [ ...siding("failed", failedVideoIds.length, "transcribe"), @@ -466,10 +499,10 @@ export function computeChannelFlow( "The transcript covers a fraction of the runtime — the audio download truncated silently.", ), ...siding( - "salvaged transcript", + salvagedLabel(fullAudio, buckets.salvagedTranscript), buckets.salvagedTranscript.length, "transcribe", - "Transcribed from a damaged file: the parts that would not decode are gaps. A retry of the corrupt full source can bring a clean copy.", + "Transcribed from a damaged file: the parts that would not decode are gaps, and the transcript is marked partial wherever it shows. A retry of the corrupt full source can bring a clean copy.", ), ...siding( "short audio", diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts @@ -114,6 +114,7 @@ import { type StoredUrlWhy, } from "../lib/storedMediaUrl"; import { storedMediaUrl } from "../lib/storedMediaUrl-server"; +import { fullAudioLine, fullAudioState } from "../lib/fullAudioFirst"; import type { DownloadFailureClass } from "../lib/availability"; import { notePlatformGap, platformGapRemainingMs, waitForPlatformGap } from "../jobs/platformGap"; import { @@ -734,6 +735,28 @@ export async function downloadOneManaged( }, }; } + // FULL AUDIO FIRST (operator ruling 2026-10-17, release 32 R8): the refetch + // of a corrupt full source whose record stores a trusted media URL reads + // that URL (R7's ranged reader, its audio check and its gap) until + // FULL_AUDIO_ATTEMPTS such downloads are on record — unless the request or + // the channel names a stored-URL mode of its own (lib/fullAudioFirst.ts). + if ( + refetch?.trigger === "corrupt-full-source" && + canonicalId && + opts.storedUrl === undefined && + opts.channelConfig.storedUrlDownloads === undefined + ) { + const state = fullAudioState(refetch.previous, { + storedUrlTrusted: (await storedMediaUrl(path.join(channelDir, "data", canonicalId))) !== null, + ...(opts.channelConfig.handling ? { handling: opts.channelConfig.handling } : {}), + }); + if (state && !state.exhausted) { + opts.onLog( + `Full audio first (${fullAudioLine(state)}): this refetch reads the stored media URL before any salvage transcript.\n`, + ); + opts = { ...opts, storedUrl: "only" }; + } + } let outcome = await runManagedDownload(opts, channelDir, startedAt, canonicalId); if (refetch) outcome = await settleCorruptRefetch(refetch, outcome, refetchCtx); await recordWaybackProvenance(opts, channelDir, canonicalId); diff --git a/common/ytdlp/storedUrlManaged.test.ts b/common/ytdlp/storedUrlManaged.test.ts @@ -308,3 +308,80 @@ test("the managed download opens the player's page (the injected opener) and rec await done(f); } }); + +// Release 32 R8 — FULL AUDIO BEFORE A SALVAGE: a corrupt full source's refetch +// reads the stored URL by itself (no storedUrl asked, none on the channel) +// until FULL_AUDIO_ATTEMPTS stored-URL downloads are on record; then the page, +// as before. An explicit mode (request or channel) is left alone. +async function corruptPrevious(f: Fixture, storedAttempts: number): Promise<void> { + await writeFile(path.join(f.videoDir, "audio.mp4"), "OLD-MALFORMED"); + const previous: DownloadOutcomeRecord = { + videoId: CLAIM, + webpageUrl: PAGE, + status: "corrupt-full-source", + startedAt: "2026-10-15T00:00:00.000Z", + finishedAt: "2026-10-15T01:00:00.000Z", + attempts: [ + { n: 1, kind: "audio-checked-primary", handling: "transcribe", usedCookies: false, ytdlpExitCode: 0 }, + ...Array.from({ length: storedAttempts }, () => ({ n: 1, kind: "stored-url-ranged" as const, handling: "transcribe" as const, usedCookies: false, ytdlpExitCode: 1 })), + ], + }; + await writeFile(path.join(f.videoDir, "download-outcome.json"), JSON.stringify(previous)); +} + +test("full audio first: a corrupt full source's refetch reads the stored URL by itself while attempts are owed", { skip: !FF }, async () => { + const f = await fixture(); + try { + await corruptPrevious(f, 0); + const log = { s: "" }; + const record = await run(f, { corruptRefetchDeps: { measure: async () => null } }, log); + assert.equal(record.status, "ok-audio-checked", log.s); + assert.deepEqual(await ytdlpCalls(f), [], "no page request"); + assert.match(log.s, /Full audio first \(full audio attempts: 0 of 2\): this refetch reads the stored media URL/); + assert.equal(storedUrlAttemptOf(record)?.why, "only"); + } finally { + await done(f); + } +}); + +test("full audio first: a refused attempt is counted on the corrupt record; once the attempts are made the refetch asks the page", { skip: !FF }, async () => { + const f = await fixture({ cdn: { refuseAfterBytes: 0 } }); + try { + await corruptPrevious(f, 1); + const record = await run(f, { corruptRefetchDeps: { measure: async () => null } }); + assert.equal(record.status, "failed"); + const disk = await readOutcome(f.videoDir); + assert.equal(disk.status, "corrupt-full-source", "the bucket stays"); + assert.equal(disk.attempts.filter((a) => a.kind === "stored-url-ranged").length, 2, "the attempt is on record"); + assert.deepEqual(await ytdlpCalls(f), []); + // Two on record: the next refetch is the page's, as before R8. + const cdnBefore = f.cdn.requests.length; + await run(f, { corruptRefetchDeps: { measure: async () => null } }); + assert.ok((await ytdlpCalls(f)).length > 0, "the page is asked"); + assert.equal(f.cdn.requests.length, cdnBefore, "the stored URL is not read again"); + } finally { + await done(f); + } +}); + +test("full audio first: an explicit mode (the request's never, the channel's) is left alone", { skip: !FF }, async () => { + const f = await fixture(); + try { + await corruptPrevious(f, 0); + await run(f, { storedUrl: "never", corruptRefetchDeps: { measure: async () => null } }); + assert.ok((await ytdlpCalls(f)).length > 0, "never: the page"); + assert.equal(f.cdn.requests.length, 0); + } finally { + await done(f); + } + const g = await fixture(); + try { + await corruptPrevious(g, 0); + const cfg = { handling: "transcribe", url: "https://odysee.com/@synth:1", storedUrlDownloads: "never" } as ChannelConfig; + await run(g, { channelConfig: cfg, corruptRefetchDeps: { measure: async () => null } }); + assert.ok((await ytdlpCalls(g)).length > 0, "the channel's never: the page"); + assert.equal(g.cdn.requests.length, 0); + } finally { + await done(g); + } +}); diff --git a/editor/app/api/ops/transcribe-one/route.ts b/editor/app/api/ops/transcribe-one/route.ts @@ -21,7 +21,9 @@ export const dynamic = "force-dynamic"; // "salvage" (release 30, lane Q): true decodes the audio with error tolerance // and transcribes what decodes, its gaps recorded (transcribeOne's salvage); // false forbids it; absent, a corrupt-full-source video is salvaged and any -// other is not. +// other is not — release 32 R8: once its full audio was tried (a record that +// stores a trusted media URL is downloaded from it FULL_AUDIO_ATTEMPTS times +// first; controller/fullAudioFirst.ts). // "storedUrl" (release 32 R7): "never" | "fallback" | "only" — with no audio on // disk, the download reads the media URL the record stores, the way the // platform's player does (the managed path: the audio check, the outcome diff --git a/editor/app/channels/[slug]/components/VideoListPane.tsx b/editor/app/channels/[slug]/components/VideoListPane.tsx @@ -863,7 +863,7 @@ function StatusGlyphs({ row }: { row: VideoRow }) { : "bg-muted"; const trColor = row.untranscribable ? "bg-muted-foreground" - : row.incompleteTranscript + : row.incompleteTranscript || row.salvagedTranscript ? "bg-warning" : row.transcribed ? "bg-success" @@ -890,7 +890,9 @@ function StatusGlyphs({ row }: { row: VideoRow }) { title={ row.incompleteTranscript ? "transcript truncated (covers a fraction of the video — re-download)" - : "transcribed" + : row.salvagedTranscript + ? "salvaged transcript (partial — the parts of the audio that would not decode are gaps)" + : "transcribed" } className={`w-2 h-2 rounded-full ${trColor}`} /> diff --git a/editor/app/channels/[slug]/lib/videoRows.ts b/editor/app/channels/[slug]/lib/videoRows.ts @@ -33,6 +33,9 @@ export type VideoRow = { // (snapshot `corruptHeldAudio` minus its salvage transcripts — release 31, // lane A). Kept on disk; a retry refetches it. corruptHeldAudio?: boolean; + // The transcript is a SALVAGE (snapshot `salvagedTranscript`, release 30 + // lane Q): partial, marked as such (release 32 R8). + salvagedTranscript?: boolean; failedTranscription: boolean; // Has at least one finalized audio file not in the channel's target format — // the failed-extract orphans (audio.m4a with no audio.mp3) plus dirs with the diff --git a/editor/app/channels/[slug]/lib/videoRowsServer.ts b/editor/app/channels/[slug]/lib/videoRowsServer.ts @@ -112,6 +112,7 @@ export function computeVideoRows(input: ComputeRowsInput): VideoRow[] { corruptSource: isCorruptSource, corruptFullSource: isCorruptFullSource, ...(isCorruptHeldAudio ? { corruptHeldAudio: true } : {}), + ...(salvagedSet.has(id) ? { salvagedTranscript: true } : {}), failedTranscription: isFailedT, wrongFormatAudio: wrongFormatAudio.has(id) || multipleAudioFormats.has(id), diff --git a/editor/app/channels/[slug]/videos/[id]/components/SalvagedTranscriptNotice.tsx b/editor/app/channels/[slug]/videos/[id]/components/SalvagedTranscriptNotice.tsx @@ -7,7 +7,15 @@ import { formatDuration } from "yt-dlp-transcript-common/lib/format"; const clock = (s: number) => formatDuration(s) || "0:00"; const MAX_LISTED = 8; -export function SalvagedTranscriptNotice({ salvaged }: { salvaged: TranscriptSalvage }) { +// `fullAudio`: the stored-URL download attempts made before the salvage +// (release 32 R8, lib/fullAudioFirst.ts), when the record stores one. +export function SalvagedTranscriptNotice({ + salvaged, + fullAudio, +}: { + salvaged: TranscriptSalvage; + fullAudio?: { attempts: number; of: number } | null; +}) { const listed = salvaged.gaps.slice(0, MAX_LISTED); const more = salvaged.gaps.length - listed.length; return ( @@ -26,6 +34,7 @@ export function SalvagedTranscriptNotice({ salvaged }: { salvaged: TranscriptSal {more > 0 ? ` and ${more} more` : ""}. </> )} + {fullAudio && <> Full audio attempts: {fullAudio.attempts} of {fullAudio.of}.</>} </div> ); } diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx @@ -8,6 +8,7 @@ // The registry-driven operation panels (digest, diarization, attribution) render // after this component, in page.tsx. +import { FULL_AUDIO_ATTEMPTS, fullAudioAttemptsOf } from "yt-dlp-transcript-common/lib/fullAudioFirst"; import type { AudioFormat, ChannelHandling, @@ -207,7 +208,16 @@ export function VideoPanel({ downloadFailed={downloadFailed} /> {downloadOutcome && <DownloadOutcomeBadge outcome={downloadOutcome} />} - {salvageShown && salvaged && <SalvagedTranscriptNotice salvaged={salvaged} />} + {salvageShown && salvaged && ( + <SalvagedTranscriptNotice + salvaged={salvaged} + fullAudio={ + storedMediaHost && downloadOutcome + ? { attempts: fullAudioAttemptsOf(downloadOutcome), of: FULL_AUDIO_ATTEMPTS } + : null + } + /> + )} {/* BOTH BANNERS ARE RENDERED UNCONDITIONALLY, and each decides for itself whether to draw anything. THE RULE (plans/FACTS.md, fae99f1): a component carrying a StreamActionLog must not be UNMOUNTED when the diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -64,6 +64,7 @@ import { transcriptionContainer, } from "yt-dlp-transcript-common/controller/transcribeOne"; import { findVideoSourceUrl } from "yt-dlp-transcript-common/controller/undownloadedVideos"; +import { fullAudioFirst } from "yt-dlp-transcript-common/controller/fullAudioFirst"; import { loadSavedVideo, unpersistSavedVideo, @@ -118,7 +119,6 @@ import { runYtdlp } from "yt-dlp-transcript-common/ytdlp/runYtdlp"; import { isStoredUrlMode, resolveStoredUrlMode, - type StoredUrlMode, } from "yt-dlp-transcript-common/lib/storedMediaUrl"; import { storedUrlAttemptOf, @@ -219,6 +219,9 @@ export async function transcribeOneAction( channelSlug: slug, videoId, fn: async (onLog, signal, _setProgress, ctx) => { + if (salvage === undefined) { + await fullAudioBeforeSalvage({ slug, videoId, config: r.config, paths, onLog, signal }); + } await transcribeWithWorker({ paths, videoDir, @@ -307,6 +310,52 @@ export async function downloadVideoPipelineAction( }); } +// FULL AUDIO BEFORE A SALVAGE (operator ruling 2026-10-17, release 32 R8): +// a Transcribe that would salvage a corrupt full source whose record stores a +// trusted media URL first makes the stored-URL downloads still owed +// (controller/fullAudioFirst.ts) — the corrupt-source refetch, `storedUrl: +// "only"`. Nothing happens for any other video. `storedUrl` is the request's +// mode (an explicit "never" keeps the old behaviour), else the channel's. +async function fullAudioBeforeSalvage(o: { + slug: string; + videoId: string; + config: ChannelConfig; + paths: Paths; + onLog: (line: string) => void; + signal: AbortSignal; + storedUrl?: StoredUrlMode; +}): Promise<void> { + const videoDir = videoDirOf(o.slug, o.videoId); + const mode = o.storedUrl ?? o.config.storedUrlDownloads; + await fullAudioFirst({ + videoDir, + handling: o.config.handling, + ...(mode ? { mode } : {}), + onLog: o.onLog, + signal: o.signal, + download: async () => { + const url = await findVideoSourceUrl(o.paths, o.slug, o.videoId, o.config); + if (!url) throw new Error("Could not determine the video URL for the full-audio download."); + const settings = getSettings(); + const record = await downloadOneManaged({ + channelSlug: o.slug, + channelConfig: o.config, + paths: o.paths, + videoUrl: url, + onLog: o.onLog, + signal: o.signal, + cookiePolicy: resolveCookiePolicy(settings, o.config), + globalSkipLiveDownloads: settings.skipLiveDownloads, + audioFormatOverride: o.config.audioFormat ?? "mp3", + appendArchive: true, + storedUrl: "only", + }); + await recordStoredUrlBackoff(record, url, o.paths); + return record; + }, + }); +} + // A single-video download that read the stored media URL (release 32 R7) // backs the platform off on a refusal — its CDN's, or the page lookup's before // it — as a batch does. Best-effort. @@ -602,6 +651,9 @@ export async function whisperVideoAction( } } else { onLog(`Audio already on disk for ${videoId}; skipping download.`); + if (salvage === undefined) { + await fullAudioBeforeSalvage({ slug, videoId, config: r.config, paths, onLog, signal, storedUrl }); + } } await transcribeWithWorker({ paths, diff --git a/editor/e2e/full-audio-first.spec.ts b/editor/e2e/full-audio-first.spec.ts @@ -0,0 +1,80 @@ +import { mkdir, writeFile } from "node:fs/promises"; +import { test, expect } from "@playwright/test"; +import { baseUrl } from "./baseUrl"; +import { generateReport, resetData, resolvePath, testPaths } from "./helpers"; + +// Release 32 R8, the operator's ruling of 2026-10-17: a partial transcript is +// marked, but the full audio comes first. A corrupt full source whose record +// stores a trusted media URL is downloaded from it FULL_AUDIO_ATTEMPTS times +// before a salvage transcript is made; the channel's line says which are still +// waiting ("awaiting full audio") and how many attempts the salvaged ones had +// ("salvaged — full audio attempts: n"), and the video page's salvaged +// transcript notice says the same. Nothing here starts a download: the stored +// URL's host is a real CDN and no test asks it anything (the downloads are +// covered by common's unit tests against a fake CDN). + +const CHANNEL = "test-transcribe"; +const FIXTURE = "one-transcribe-channel"; +const ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; +const WAITING = "1111111111111111111111111111111111111111"; +const SALVAGED = "2222222222222222222222222222222222222222"; + +const stored = { n: 1, kind: "stored-url-ranged", handling: "transcribe", usedCookies: false, ytdlpExitCode: 1 }; + +async function video(id: string, storedAttempts: number, salvaged: boolean) { + const dir = resolvePath(`${ROOT}/data/${id}`); + await mkdir(dir, { recursive: true }); + const put = (name: string, body: unknown) => + writeFile(`${dir}/${name}`, typeof body === "string" ? body : JSON.stringify(body)); + await put("metadata.info.json", { + id, + extractor: "lbry", + title: `A synthetic stream ${id.slice(0, 4)}`, + webpage_url: `https://odysee.com/synthetic-stream:${id}`, + duration: 600, + formats: [{ url: `https://player.odycdn.com/v6/streams/${id}/a1b2c3.mp4`, protocol: "https", ext: "mp4" }], + }); + await put("audio.mp4", "kept malformed bytes"); + await put("download-outcome.json", { + videoId: id, + status: "corrupt-full-source", + startedAt: "2026-10-16T00:00:00.000Z", + finishedAt: "2026-10-16T00:10:00.000Z", + attempts: [ + { n: 1, kind: "audio-checked-primary", handling: "transcribe", usedCookies: false, ytdlpExitCode: 0 }, + ...Array.from({ length: storedAttempts }, () => stored), + ], + }); + if (salvaged) { + await put("transcript.json", { transcription: [{ offsets: { from: 0, to: 2000 }, text: " hello there" }] }); + await put("transcribe-outcome.json", { + videoId: id, + transcribedAt: "2026-10-16T01:00:00.000Z", + salvaged: { source: "audio.mp4", decodedSeconds: 300, totalSeconds: 600, gaps: [[300, 600]] }, + }); + } +} + +test("the line names the corrupt full sources awaiting full audio, and the salvaged ones' attempts; the video page says it too", async ({ page }) => { + await resetData(FIXTURE); + await video(WAITING, 0, false); + await video(SALVAGED, 1, true); + await writeFile( + resolvePath(`${ROOT}/playlist`), + [WAITING, SALVAGED].map((id) => `https://odysee.com/synthetic-stream:${id}`).join("\n") + "\n", + ); + await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {}); + await generateReport(page, CHANNEL); + await page.goto(`/channels/${CHANNEL}`); + + const line = page.getByLabel("channel line"); + await expect(line.getByLabel("awaiting full audio siding")).toContainText("1 awaiting full audio"); + await expect(line.getByLabel("salvaged — full audio attempts: 1 siding")).toContainText( + "1 salvaged — full audio attempts: 1", + ); + + await page.goto(`/channels/${CHANNEL}/videos/${SALVAGED}`); + const notice = page.getByRole("status", { name: "salvaged transcript" }); + await expect(notice).toContainText("Salvaged transcript — 5:00 of 10:00 of audio.mp4 decoded."); + await expect(notice).toContainText("Full audio attempts: 1 of 2."); +}); diff --git a/mcp/src/search.test.ts b/mcp/src/search.test.ts @@ -1790,5 +1790,13 @@ test("server: a salvage transcript is marked partial by get_transcript and get_v await client.callTool({ name: "get_transcript", arguments: { video_id: "b2" } }), ); assert.doesNotMatch(other, /PARTIAL TRANSCRIPT/); + // Release 32 R8: the batch reader marks it too — whole transcripts and windowed. + const batch = firstText(await client.callTool({ name: "get_transcripts", arguments: { video_ids: ["a1"] } })); + assert.match(batch, /Video ID: a1\n[\s\S]*PARTIAL TRANSCRIPT — made from a damaged recording: 39 of 100 min decoded/); + // Windowed (a query): the block's head carries it. + const windowed = firstText( + await client.callTool({ name: "get_transcripts", arguments: { video_ids: ["a1"], query: "coffee" } }), + ); + assert.match(windowed, /PARTIAL TRANSCRIPT — made from a damaged recording/); await client.close(); }); diff --git a/mcp/src/server.ts b/mcp/src/server.ts @@ -2109,7 +2109,9 @@ async function handleGetTranscripts( (ch.siteTitle ? ` | site: ${ch.siteTitle}` : "") + ` | uploaded: ${formatDate(record.uploadDate)}` + (record.webpageUrl ? `\n- source: ${record.webpageUrl}` : "") + - (baseUrl ? `\n- moment_base: ${baseUrl}` : ""); + (baseUrl ? `\n- moment_base: ${baseUrl}` : "") + + // A salvage transcript (release 30, lane Q) is marked here too (release 32 R8). + (record.salvaged ? `\n- ${salvageCaveat(record.salvaged)}` : ""); if (matcher) { const { lines, matchCount } = getWindowedTranscript(record, matcher.match, { @@ -2164,6 +2166,9 @@ async function handleGetTranscripts( ].join("\n\n"); blocks.push(`${head}\n\n${body}`); } else { + // A salvage transcript (release 30, lane Q) is marked here too (release 32 R8). + const salvageMeta = record.salvaged ? [salvageCaveat(record.salvaged)] : []; + const extraMeta = [...(base && baseUrl ? [`moment_base: ${baseUrl}`] : []), ...salvageMeta]; const md = transcriptToMarkdown( record, base @@ -2171,12 +2176,13 @@ async function handleGetTranscripts( timestamps, includeTags: true, stampForCue: baseStamp, - extraMeta: baseUrl ? [`moment_base: ${baseUrl}`] : undefined, + extraMeta: extraMeta.length ? extraMeta : undefined, } : { timestamps, includeTags: true, linkForCue: (seconds) => momentLinkFor(source, link, seconds), + ...(extraMeta.length ? { extraMeta } : {}), }, ); blocks.push(md.trim()); diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -456,7 +456,7 @@ const ACTIONS = [ "verdict-review", // THE VERDICT BENCH (release 28 M7): ruled fact-check claims asked of each // model, one per call ({models, run?, reports?, window?, windowMode?, - // maxUsd?, limit?, itemsFrom?}), + // maxUsd?, limit?, itemsFrom?, dedupe?}), // as a bench-verdicts job on draft:local (any local model) or draft:api. "bench-verdicts", // THE FRAME SCAN (release 30): a saved stream's frames read by a vision @@ -953,7 +953,10 @@ export function usage() { ' managed path. A job; --wait follows it. "salvage": true decodes a damaged', ' file with error tolerance and transcribes what decodes, on the', ' recording\'s clock, its gaps recorded (the transcript is listed as', - ' salvaged); a corrupt-full-source video is salvaged unless "salvage": false.', + ' salvaged); a corrupt-full-source video is salvaged unless "salvage": false', + ' — once its full audio was tried: when its record stores an Odysee media', + ' URL, that URL is downloaded first, up to 2 times (20 min apart), and the', + ' salvage follows only if neither download is clean.', ' "storedUrl": "only" | "fallback" | "never" downloads missing audio from the', ' media URL the record stores (Odysee\'s CDN), read in ranges as its player', ' reads it — no page request with "only", the page first with "fallback" —', @@ -1132,6 +1135,8 @@ export function usage() { " with ids is not replayable, as a checkbox selection in the UI is not.", ' "corruptFullSource" downloads again: the kept file is set aside, and comes', " back if the download fails; malformed again, the longer decode stays.", + " A record that stores an Odysee media URL is read from that URL (as", + ' "only") until 2 such downloads are on record, then from the page.', ' "storedUrl": "fallback" | "only" reads each from the media URL its record', ' stores, as on download-missing (a held platform\'s retry runs as "only").', ' "corruptHeldAudio" (held audio the audio audit found damaged) is refetched', @@ -1475,7 +1480,9 @@ export function usage() { ' "windowMode"? ("seconds" | "turn": the cited speaker\'s turn, bounded by', ' the window), "maxUsd"? (default 5), "limit"? (a stratified sample, by the', ' operator\'s verdict), "itemsFrom"? (an earlier run\'s exact items; no', - ' reports, window, windowMode or limit with it)} -> {jobId, run}. Every claim', + ' reports, window, windowMode, limit or dedupe with it), "dedupe"? (true: a', + ' claim repeating an earlier one, the same text over the same cited spans, is', + ' asked once; default: every claim is asked)} -> {jobId, run}. Every claim', " of the registry's fact-checks (or of \"reports\") with the operator's verdict", " and a citation with cues is asked of each model, one claim per call (the", " report's title, the claim's section, the claim, its quotes, the transcript",