Archilyzer · Source

archilyzer

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

commit fe72e5bc909f7c495241290ce767f6d23cc6587a
parent 507a04d310f2662c8304da32f6cf6c0c9edd8199
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 04:39:42 -0500

stored text, review fix F2: no pass fetches a chat on disk; one form after a re-fetch

The chat-only pass (a title-filter rejection on a chat-only channel) ran
`--sub-langs live_chat` with no look at the disk; yt-dlp's own skip sees only
the plain name, so over a stored chat it fetched the whole replay again and
landed a second, maybe trimmed, copy. It now asks for either form first and
normalizes what is here.

The rule for a re-fetched chat beside a stored one: no pass fetches a chat
on disk in either form; the one deliberate re-fetch is fetch-chat
`replace: true` over a chat stored compressed, and when its pass lands a
whole new plain file (no .part, not the file that was there) the older .zst
is removed through removeMediaFile, so exactly one form is left; a pass that
lands nothing keeps the stored chat. Over a plain chat `replace` is refused.
A pair left by any other path stays both-differ for a person.

The grep gate: no bare-identifier skip (multi-line imports are tracked
instead), an interpolation into a path is not a message, the sanctioned list
is readers and deleters only (other lines are allowed one by one with a
reason), scripts/ and editor/lib/ walked. A second gate pins every argv that
can write subtitles to a named builder, and every caller of a builder by
count, each with its guard and test. What they cannot see is in the file.

Docs: OPERATING.md (the rollback: restore before reverting), ops help,
COMMANDS.md, the editor changelog.

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

Diffstat:
MCOMMANDS.md | 6+++---
MOPERATING.md | 55++++++++++++++++++++++++++++++++++++++++++++-----------
Mcommon/controller/fetchLiveChat.test.ts | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/fetchLiveChat.ts | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mcommon/lib/storedText.grep.test.ts | 191++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Acommon/ytdlp/chatOnlyStored.test.ts | 146+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/ytdlp/downloadOneManaged.ts | 24+++++++++++++++++++++++-
Meditor/CHANGELOG.md | 10+++++++++-
Meditor/app/api/ops/fetch-chat/route.ts | 9++++++++-
Meditor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts | 3++-
Mscripts/archilyzer-ops.mjs | 39++++++++++++++++++++++++++++-----------
11 files changed, 573 insertions(+), 53 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -160,7 +160,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `review-compacted-original` | review-compacted-original records a person's review of one compacted copy (watch it first: get compaction-review's "watch"): {"slug", "id", "note"?}. It names the copy it is for ("watched", its sha256) and counts for that copy only; it changes nothing on disk. It is what lets drop-saved-alternate ("confirmOriginal": true) drop the original of a video not freshly checked on its platform. "formerOriginal": "&lt;file&gt;" reviews the active copy that replaced a former original instead. | | | `compaction-markers` | compaction-markers lists the "being compacted" markers (.compacting.json), each live or stale and why: {}. {"clear": {"slug", "id"}} removes a stale one; a live one is refused (cancel its job). Stale ones are also swept at editor boot and at the start of every compaction run. | | | `kept-failed-encodes` | kept-failed-encodes lists the encodes kept after a failed check (in each video's .compact-scratch, never active: chunks and the joined copy, their size, what failed): {}. {"clear": {"slug", "id"}} removes one (refused while its compaction runs). compact-saved-videos "reverify": true re-checks one without encoding. | | -| `compress-text` | compress-text stores the raw live-chat replays compressed (zstd, level 9): transcript.live\_chat.json becomes transcript.live\_chat.json.zst, read back by every reader as the same file, with the same times (the index sees no change): {"slugs"?: \[...\], "kinds"?: \["live-chat"\], "dryRun"?, "limit"?, "verify"?}. One file at a time: written beside the original, fsynced, read back and hashed against it, and only then the original removed; a crash at any step leaves a whole copy, and the next run finishes it. Left alone and counted: a file written in the last 10 minutes, one with a .part beside it, a video recording or with a job running, a drive that does not answer, a channel whose media is moving. Both forms present with different content are refused and both kept. "dryRun": true answers per channel the raw chats, their bytes, the stored ones, the estimate after (about 5 %, an estimate) and the free space, and writes nothing; "verify": true decodes every stored file in full and writes nothing; "limit" counts files compressed and takes exactly one channel in "slugs". One job per channel with work, on the machine-wide compress-text queue (one file at a time), waiting while render mode holds the machine and slower while a live recording runs; never resumed at boot (it removes originals) -- a re-run continues. | | +| `compress-text` | compress-text stores the raw live-chat replays compressed (zstd, level 9): transcript.live\_chat.json becomes transcript.live\_chat.json.zst, read back by every reader as the same file, with the same times (the index sees no change): {"slugs"?: \[...\], "kinds"?: \["live-chat"\], "dryRun"?, "limit"?, "verify"?, "restore"?}. One file at a time: written beside the original, fsynced, read back and hashed against it, and only then the original removed; a crash at any step leaves a whole copy, and the next run finishes it (it visits every dir a stopped run left). Left alone and counted: a file written (mtime or ctime) in the last 10 minutes, one with a .part beside it, a video recording or with a job running, a drive that does not answer, a channel whose media is moving. Both forms present with different content are refused and both kept. A file a writer replaces during the run is kept, and the older stored copy removed. "dryRun": true answers per channel the raw chats, their bytes, the stored ones, the estimate after (about 5 %, an estimate) and the free space, and writes nothing; "verify": true decodes every stored file in full and writes nothing; "limit" counts files compressed and takes exactly one channel in "slugs". One job per channel with work, on the machine-wide compress-text queue (one file at a time), waiting while render mode holds the machine and slower while a live recording runs. Started by a person only: a restart closes a queued one and resumes no interrupted one (it removes originals) -- a re-run continues. "restore": true is the rollback: every stored chat put back into its plain form, verified the same way in reverse (decoded beside, fsynced, read back against a fresh decode, the same times, then the .zst removed); with "dryRun" it answers the stored files, their plain bytes and the free space. Run it BEFORE reverting or running an older checkout, which cannot read a stored chat (OPERATING.md). | | | `build-cues` | build-cues writes each video's transcript.cues.json from its raw transcript (the caption-track rule for VTTs), as the digest card's Normalize button does: {"slug"}, "ids": \[...\] for those videos only (every one held), "force": true to rewrite a fresh one. A job on the channel's queue. The file every reader without an index build wants. | `pnpm ops build-cues --json '{"slug":"demo-yt","ids":["<videoId>"]}' --wait` | | `feed-metadata` | feed-metadata completes a podcast channel's records from its RSS feed: one fetch of the channel's url, then title, date, description and duration into each record that lacks them: {"slug"}. "dryRun": true counts matched, unmatched and already complete, and writes nothing. | `pnpm ops feed-metadata --json '{"slug":"demo-podcast","dryRun":true}' --wait` | | `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}'` | @@ -202,7 +202,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `rerun-service-jobs` | — | | | `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. Only a download waits on the platform's queue: the transcription runs as a transcribe-one job on the video's own queue (transcribe-one:&lt;slug&gt;:&lt;id&gt;), at once when nothing is downloaded, else handed off by the whisper-video once the audio is down. A job; --wait follows it through the hand-off to the end of the transcription. "queueKey" names another queue. A youtube-handling video with no audio whose metadata lists English captions has those fetched instead ({"instead": "captions", "message"}, the job the caption download), one with an English caption track on disk is refused; "asr": true transcribes it anyway (no "file"). "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. "whilePaused": true runs this one transcription during a pause-all on a worker the pause alone switched off; the pause stays on (the video page's "Transcribe now (workers paused)"). A video its record says is live, scheduled or still processing its VOD (live\_status is\_live, is\_upcoming, post\_live) is refused before anything is queued — a download would read the stream at 1x and hold the platform queue: record it with record-live, or wait for the VOD (refresh-metadata re-reads the record once it has ended). With its audio on disk it transcribes. | | -| `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. | | +| `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. A raw live chat named in one form while the other is there (transcript.live\_chat.json and its .zst): both go when they hold the same content; only the named one when they differ, and "note" says the other is still there. | | | `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. An ORIGINAL ("keptAs": "original", the source of a compacted copy) needs "confirmOriginal": true; the compacted copy is read back from disk (size, sha256, container, length) before it goes; a video not freshly checked on its platform needs a review of this copy recorded first; and nothing goes while a download or persist of the video is queued or running, or while it is being compacted. A FORMER original ("former-original") needs its own "confirmFormerOriginal": true, and the same gone/review rule. | | | `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` | @@ -237,7 +237,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `mirror-scan` | mirror-scan pairs a mirror channel with the creator it copies: {"slug", "dryRun"?} -&gt; {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/&lt;slug&gt;.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"?} -&gt; {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 &lt;series&gt;-&lt;date&gt; over the window since the last edition ("&lt;topic&gt; · week of &lt;date&gt;"); 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"} -&gt; {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"}'` | | `audio-audit` | audio-audit decodes every audio file a channel holds, with error tolerance, and writes the verdict beside it in audio-integrity.json: {"slug" \| "platform" (every channel on it, e.g. "odysee"), "scope"? ("untranscribed", the default: videos with no transcript yet; "all": every video holding audio), "max"? (files decoded across the run), "force"? (decode again a file whose record is still its own)} -&gt; {jobIds, channels, refused}. One audio-audit job per channel on the audio-audit queue: one file at a time machine-wide, at idle I/O priority and nice 19. The verdict is clean, damaged (a gap, or under 98% of the container's duration decodes) or undecodable, with the decoded seconds, the gaps, the file's size and mtime and ffmpeg's version. The same body again resumes (a file whose record matches is skipped). A channel whose media is unreachable is refused; a drive that stops answering mid-run ends that channel's job with the sentence (failed), as do two decodes in a row past their deadline (a minute plus a tenth of the audio's length). Corrupt full sources are left to their retry. Damaged untranscribed files (and their salvage transcripts) are the report's corruptHeldAudio bucket, held out of the transcription lane: retry-bucket {"bucket": "corruptHeldAudio"} refetches them; a transcription of one salvages automatically. Each log ends with @@audio-audit {slug, scope, held, fresh, planned, checked, clean, damaged, undecodable, unmeasured, timedOut, corruptFullSource, stopped?}. | `pnpm ops audio-audit --json '{"platform":"odysee","scope":"untranscribed"}' --wait`<br>`pnpm ops audio-audit --json '{"slug":"demo-odysee","scope":"all","max":50}'` | -| `fetch-chat` | fetch-chat fetches ONE video's live chat replay and nothing else: {"slug", "id"} — the chat-only yt-dlp pass (the channel's cookies, the platform's pace) on the platform's download queue, then live\_chat.cues.json. YouTube only: another platform answers "no chat fetcher for &lt;platform&gt;" (info, no job), as do a chat already here and fresh and a video never live. A pass that finds no replay ends done and says so. A pass the source refuses for the video as members-only or private records that in its availability.json (source fetch); a removal is recorded only by the channel's Check availability. A chat captured while the stream was live is put on the recording's clock (the broadcast's start, or a recording begun "from now" its own start) and its cues say which in "clock". "renormalize": true parses the raw chat already on disk again, fresh or not, with no network — for a chat normalized before that; refused when no raw is here (it never fetches). | `pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait`<br>`pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>","renormalize":true}' --wait` | +| `fetch-chat` | fetch-chat fetches ONE video's live chat replay and nothing else: {"slug", "id"} — the chat-only yt-dlp pass (the channel's cookies, the platform's pace) on the platform's download queue, then live\_chat.cues.json. YouTube only: another platform answers "no chat fetcher for &lt;platform&gt;" (info, no job), as do a chat already here and fresh and a video never live. A pass that finds no replay ends done and says so. A pass the source refuses for the video as members-only or private records that in its availability.json (source fetch); a removal is recorded only by the channel's Check availability. A chat captured while the stream was live is put on the recording's clock (the broadcast's start, or a recording begun "from now" its own start) and its cues say which in "clock". "renormalize": true parses the raw chat already on disk again, fresh or not, with no network — for a chat normalized before that; refused when no raw is here (it never fetches). "replace": true fetches the replay again over a chat stored compressed (.zst): when a whole new plain chat lands, the stored one is removed -- one form is left; a pass that lands nothing keeps the stored chat. Refused over a plain chat (delete it on the files card first) and with "renormalize". | `pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait`<br>`pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>","renormalize":true}' --wait` | | `find-clips` | find-clips runs the clip finder's chain for ONE video as one job: {"slug", "id", "target"? (the cut's seconds), "segment"? (one umtool found, "s2"), "project"? (the umtool project a run makes), "whilePaused"?, "dryRun"?}. Persist the source video, the corpus transcript, word timings (data/&lt;id&gt;/words.json), the chat replay (YouTube), diarization — each step skipped when its output exists, named in the log — then umtool's clip finder (POST UMTOOL\_URL/api/report/clips {mode: "new"}), followed to the end. "whilePaused": true runs this one video past the holds: the two transcriptions during a pause-all on a worker the pause alone switched off, and its diarization in the job when the backfill lane is held. "dryRun": true answers each step's plan and starts nothing. With --wait the result — {project, url, created, segments: \[{id, from, to, why}\], steps} — is printed on stdout. | `pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","segment":"s2","whilePaused":true}' --wait` | | `fetch-chat-backlog` | fetch-chat-backlog fetches a channel's stream chats after its downloads: {"slug", "dryRun"?, "limit"?, "queueKey"?} — every held video whose metadata says it was a stream (live\_status was\_live / post\_live) and whose chat is not here, newest first, one at a time through fetch-chat's pass with the batch downloads' gap between two, as one fetch-chat-backlog job on the platform's download queue; a raw replay already here is only normalized. It stops on a rate limit, a held platform, three failures in a row, a drain or "limit" chats; a re-run skips the chats here and the streams known to have none (chat-backlog.json), and a restart resumes it. The download lane queues it by itself (25 a run) for a channel whose "chat" is "later" once it has nothing left to download. "dryRun": true counts from the disk and starts nothing: chats, normalizeOnly, have, settled, notStreams, ids (the first 50). | `pnpm ops fetch-chat-backlog --json '{"slug":"demo-yt","dryRun":true}'` | | `x-run` | x-run fetches several X posts channels IN SEQUENCE as ONE job on X's queue: {"channels": \[slug, ...\]} in that order, each a fetch-posts sync new of at most 200 posts ("limit": N, 1-200, caps it lower), X's queue gap (pacing.jobGapSeconds.twitter) between two channels. Before EACH channel the jar is checked again: once it is past social.x.maxCookieAgeMinutes (or the X alert is up) the run stops and the rest are DEFERRED until the next refresh. It never refreshes the jar: Refresh cookies on /cookies, then {"resume": "&lt;run id&gt;"} runs the deferred channels (the console's Resume; a Retry of the job is the same). One run at a time; refused before a job on a stale jar (a new run's channels are kept, deferred). An interrupted run is not resumed on boot: it ends deferred. Answers {jobId, run}; get x-run follows it. The log ends with @@x-run {id, status, stopped?, counts, summary}. | `pnpm ops x-run --json '{"channels":["example-x","other-x"]}'`<br>`pnpm ops x-run --json '{"resume":"xr-01J…"}'` | diff --git a/OPERATING.md b/OPERATING.md @@ -1587,25 +1587,58 @@ pnpm ops compress-text --json '{"dryRun":true}' # per chan pnpm ops compress-text --json '{"slugs":["example"],"limit":20}' --wait # a first batch (limit: one channel) pnpm ops compress-text --json '{"verify":true}' --wait # decode every stored chat in full; writes nothing pnpm ops compress-text --json '{}' --wait # the rest; a re-run continues +pnpm ops compress-text --json '{"restore":true,"dryRun":true}' # the rollback's plan: stored chats, their plain bytes, free space +pnpm ops compress-text --json '{"restore":true}' --wait # the rollback: every stored chat back to its plain form ``` - **What it does.** A raw live-chat replay, `transcript.live_chat.json`, is stored as `transcript.live_chat.json.zst` (one zstd frame, level 9, its content size and checksum in the frame): about 5 % of its size. Every reader — the index, normalize, the chat plan, the snapshot, the archive build, the missing-subs fetch — reads either form as the - same file (`common/lib/storedText-server.ts`). The stored file carries the original's times exactly, so the index - sees no change and nothing is re-normalized. + same file (`common/lib/storedText-server.ts`). The stored file carries the original's times (its `mtimeMs` + exactly; the nanoseconds may move by under a microsecond), so the index sees no change and nothing is + re-normalized. - **Safe at every step.** One file at a time: the stored form is written beside the original (in `media/<id>/` for a tiered chat, on the same drive), fsynced, read back and hashed against the original, and only then is the original - removed, through `removeMediaFile`. A kill at any step leaves a whole copy, and the next run finishes it. -- **Left alone and counted:** a file written in the last 10 minutes; one with a `.part` beside it (a capture or a - download in progress); a video whose `live-recording.json` says `recording`, or with a job running; a drive that - is not mounted or not answering; a channel whose media is moving. **Both forms present with different content - are refused, and both kept**: the plain one is what readers read; look at the pair by hand. + removed, through `removeMediaFile`. A kill at any step leaves a whole copy. The next run visits every directory a + stopped run left (a temp, a set-aside original, a dangling link) and finishes it; a leftover is a stopped run's + unless the process that named it (its pid and start time) is running now. +- **Left alone and counted:** a file written (mtime or ctime) in the last 10 minutes; one with a `.part` beside it (a + capture or a download in progress); a video whose `live-recording.json` says `recording`, or with a job running; a + drive that is not mounted or not answering; a channel whose media is moving. **Both forms present with different + content are refused, and both kept**: the plain one is what readers read; look at the pair on the video's files + card. A file a writer replaces during the run is kept, and the older stored copy removed. - **One job per channel** with work, on one machine-wide queue, so a move of that channel's media refuses while it - runs. **Paced.** It waits while render mode holds the machine, reads at 40 MB/s (8 MB/s while a live recording runs), - and is never resumed by the boot pass: it removes originals, so a person re-runs it. Drain stops it between files. -- **By hand:** `zstdcat transcript.live_chat.json.zst` reads one. Delete a chat through the video page or the app, - never with `rm`: a plain file deleted beside an older stored one would bring that one back (the app removes both). + runs. **Paced.** It waits while render mode holds the machine, reads at 40 MB/s (8 MB/s while a live recording runs). + **Started by a person only**: a restart closes a queued one and resumes no interrupted one (it removes originals); + a person re-runs it, and a re-run continues. Drain stops it between files. +- **One form of a chat, always.** No download fetches a chat that is on disk in either form: the chat-only pass is + skipped, the caption passes leave the chat out of `--sub-langs`, `fetch-chat` normalizes what is here. To fetch a + stored chat again on purpose: `pnpm ops fetch-chat --json '{"slug":"<slug>","id":"<id>","replace":true}'` — when a + whole new plain chat lands, the stored one is removed; a pass that lands nothing (a stream since deleted) keeps it. + Over a plain chat `replace` is refused: delete it on the files card first, then fetch-chat. +- **Deleting a chat**: through the video's files card (or `pnpm ops delete-file`), never with `rm`. With both forms + there and the same content, both go (otherwise the other would come back as the file); with different content + only the one named goes, and the card says the other is still there. +- **By hand:** `zstdcat transcript.live_chat.json.zst` reads one. + +#### Rollback: restore BEFORE reverting + +An older checkout, an image built before this, or a revert of the lane cannot read a `.zst`: to it, every stored +chat is absent — the index drops the track from the next publish, and the download lane fetches every stored +chat-only video's replay again (a burst at YouTube, and nothing at all for a stream since deleted). So **restore +first, then revert or run the older code**: + +```sh +pnpm ops compress-text --json '{"restore":true,"dryRun":true}' # the plain bytes it needs, and the free space per disk +pnpm ops compress-text --json '{"restore":true}' --wait # every channel; "slugs" and "limit" as for a compress +pnpm ops compress-text --json '{"verify":true}' --wait # afterwards: "verified 0 stored chat(s)" on every channel +``` + +The restore is the compressor in reverse: each stored chat is decoded beside itself (on the same drive), fsynced, +read back and hashed against a fresh decode of the `.zst`, given the same times, put in place without replacing +anything, and only then is the `.zst` removed through `removeMediaFile`. A kill at any step leaves a whole copy; a +re-run finishes. The raw chats then take their plain size again (the dry run says how much): about 20 times the +stored size. ### Compact saved videos diff --git a/common/controller/fetchLiveChat.test.ts b/common/controller/fetchLiveChat.test.ts @@ -428,3 +428,77 @@ test("renormalize: held by the media guard while the channel's media is moving", await rm(marker, { force: true }); } }); + +// THE ONE-FORM RULE FOR A DELIBERATE RE-FETCH (lane text-compress, REVIEW-1 +// F2): fetch-chat `replace` over a chat stored compressed. yt-dlp does not see +// the `.zst` and writes the plain name; when that lands whole, the older +// stored form goes — exactly one form is left, the new one, and readers read +// it. A pass that lands nothing (a deleted stream), fails, or leaves a `.part` +// keeps the stored chat as it was. Over a plain chat, `replace` is refused. +test("replace: over a stored chat the new plain file wins and the stored one goes; nothing landed keeps it", async () => { + const { storeFixture } = await import("../testing/storedTextFixture"); + const { readStoredText } = await import("../lib/storedText-server"); + const CHAT = "transcript.live_chat.json"; + const OLD = [chatLine(1, "a", "old whole capture"), chatLine(2, "b", "more")].join("\n") + "\n"; + const NEW = chatLine(1, "a", "re-fetched") + "\n"; + const forms = async (d: string) => (await readdir(d)).filter((e) => e.startsWith("transcript.live_chat")).sort(); + + // Landed: one form, the new one. + const d1 = await video("rp1", { webpage_url: "https://www.youtube.com/watch?v=rp1", was_live: true }); + await writeFile(path.join(d1, CHAT), OLD); + await storeFixture(d1, CHAT); + const ok = stubRunner({ writes: NEW }); + const l = log(); + const job = await runFetchChatJob({ paths, slug: SLUG, videoId: "rp1", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run: ok.run, replace: true }); + assert.ok(job.ok, JSON.stringify(job)); + void job.stream.cancel(); + assert.equal((await job.done).status, "done"); + assert.equal(ok.calls.length, 1, "a deliberate re-fetch spawns"); + assert.deepEqual(await forms(d1), [CHAT], "exactly one form: the new plain file"); + assert.equal(await readStoredText(d1, CHAT, "utf8"), NEW); + assert.equal(JSON.parse(await readFile(path.join(d1, "live_chat.cues.json"), "utf8")).cues.length, 1, "normalized from the new file"); + + // Nothing landed (the source has no replay any more): the stored chat stays. + for (const [id, runner] of [ + ["rp2", stubRunner({ writes: null })], + ["rp3", stubRunner({ exitCode: 1, stderr: "ERROR: [youtube] rp3: Video unavailable" })], + ] as const) { + const d = await video(id, { webpage_url: `https://www.youtube.com/watch?v=${id}`, was_live: true }); + await writeFile(path.join(d, CHAT), OLD); + await storeFixture(d, CHAT); + const r = await fetchLiveChat({ + paths, slug: SLUG, videoId: id, videoUrl: `https://www.youtube.com/watch?v=${id}`, channelConfig: CONFIG, + cookiePolicy: NO_COOKIES, onLog: l.onLog, signal: new AbortController().signal, run: runner.run, replace: true, paceSeconds: 0, + }).catch((e: Error) => ({ status: "failed", error: e.message })); + assert.notEqual(r.status, "fetched", id); + assert.deepEqual(await forms(d), [`${CHAT}.zst`], `${id}: the stored chat is kept`); + assert.equal(await readStoredText(d, CHAT, "utf8"), OLD, id); + } + // A pass that left a `.part` (a capture not finished): the stored chat stays. + { + const d = await video("rp4", { webpage_url: "https://www.youtube.com/watch?v=rp4", was_live: true }); + await writeFile(path.join(d, CHAT), OLD); + await storeFixture(d, CHAT); + const partial = async (cwd: string, args: string[]) => { + void args; + await writeFile(path.join(cwd, "data", "rp4", `${CHAT}.part`), "half"); + return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null }; + }; + const r = await fetchLiveChat({ + paths, slug: SLUG, videoId: "rp4", videoUrl: "https://www.youtube.com/watch?v=rp4", channelConfig: CONFIG, + cookiePolicy: NO_COOKIES, onLog: l.onLog, signal: new AbortController().signal, run: partial, replace: true, + }); + assert.deepEqual(r, { status: "none" }); + assert.ok((await readdir(d)).includes(`${CHAT}.zst`)); + } + + // Over a plain chat: refused before any job, nothing spawned. + const d5 = await video("rp5", { webpage_url: "https://www.youtube.com/watch?v=rp5", was_live: true }); + await writeFile(path.join(d5, CHAT), OLD); + const spawn = stubRunner(); + const refused = await runFetchChatJob({ paths, slug: SLUG, videoId: "rp5", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run: spawn.run, replace: true }); + assert.ok(!refused.ok && /re-fetches over a chat stored compressed only/.test(refused.error), JSON.stringify(refused)); + assert.equal(spawn.calls.length, 0); + const both = await runFetchChatJob({ paths, slug: SLUG, videoId: "rp5", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run: spawn.run, replace: true, renormalize: true }); + assert.ok(!both.ok && /ask one/.test(both.error)); +}); diff --git a/common/controller/fetchLiveChat.ts b/common/controller/fetchLiveChat.ts @@ -56,8 +56,9 @@ import { detectPlatform } from "../lib/platform"; import type { Paths } from "../lib/paths"; import { downloadQueueKey, resolveQueueKey } from "../lib/queueKeys"; import { LIVE_CHAT_CUES_FILENAME, LIVE_CHAT_FILENAME, META_FILENAME } from "../lib/videoStatus"; -import { listingHas } from "../lib/storedText"; +import { listingHas, storedFormsIn } from "../lib/storedText"; import { storedTextExists } from "../lib/storedText-server"; +import { plainIdentity, settleStoredTextAfterWrite } from "../lib/storedText-write-server"; import { heldPlatformRefusal, platformCooldownRemainingMs, @@ -113,11 +114,14 @@ export function noChatFetcherSentence(platform: string): string { return `no chat fetcher for ${platform}: only YouTube's chat replay is fetched`; } +// `replace` (fetch-chat's deliberate re-fetch over a STORED chat): what is on +// disk does not answer — the plan is the fetch, or why there is none. export async function liveChatPlan( paths: Paths, slug: string, videoId: string, config: ChannelConfig, + opts: { replace?: boolean } = {}, ): Promise<LiveChatPlan> { if (!isVideoIdSegment(videoId)) { return { kind: "refused", error: `"${videoId}" is not a video id (one path segment)` }; @@ -127,12 +131,14 @@ export async function liveChatPlan( // 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[]); - // Either form of the raw (lib/storedText.ts): a compressed chat is ON DISK — - // missing it here is a fetch of the whole replay again. - if (listingHas(entries, LIVE_CHAT_FILENAME) && entries.includes(META_FILENAME)) return { kind: "normalize" }; + if (!opts.replace) { + const fresh = await isLiveChatCuesFresh(videoDir); + if (fresh.fresh) return { kind: "fresh", cuesPath: fresh.cuesPath }; + const entries = await readdir(videoDir).catch(() => [] as string[]); + // Either form of the raw (lib/storedText.ts): a compressed chat is ON DISK — + // missing it here is a fetch of the whole replay again. + if (listingHas(entries, LIVE_CHAT_FILENAME) && entries.includes(META_FILENAME)) return { kind: "normalize" }; + } const url = await findVideoSourceUrl(paths, slug, videoId, config); if (!url) { return { @@ -174,6 +180,11 @@ export type FetchLiveChatOpts = { // Test seams: the spawn, and the platform pace in the argv. run?: ChatRunner; paceSeconds?: number; + // THE DELIBERATE RE-FETCH over a chat stored compressed (fetch-chat + // `replace`): when the pass lands a whole new plain chat, the older stored + // form goes — one form is left (lib/storedText-write-server.ts, the one-form + // rule). A pass that lands nothing leaves the stored chat as it was. + replace?: boolean; }; export type FetchLiveChatResult = @@ -201,6 +212,9 @@ export async function fetchLiveChat(opts: FetchLiveChatOpts): Promise<FetchLiveC if (!(await isDirectory(videoDir))) throw new Error(notFetchedRefusal(opts.videoId, opts.slug)); const pass = (cookies: string | undefined) => run(channelDir, liveChatOnlyArgs(opts.channelConfig, cookies, opts.videoUrl, opts.paceSeconds)); + // The plain file before the pass: what tells a file this pass wrote from one + // that was there (the one-form rule asks). + const before = opts.replace ? await plainIdentity(videoDir, LIVE_CHAT_FILENAME) : null; opts.onLog( opts.capturingLive @@ -246,6 +260,17 @@ export async function fetchLiveChat(opts: FetchLiveChatOpts): Promise<FetchLiveC } catch { /* shared-state write is best-effort */ } + if (opts.replace) { + const settled = await settleStoredTextAfterWrite(videoDir, LIVE_CHAT_FILENAME, before, (l) => opts.onLog(`${l}\n`)); + if (settled !== "one-form") { + opts.onLog( + settled === "busy" + ? `The chat of ${opts.videoId} is being compressed or restored right now; nothing was replaced. Try again in a moment.\n` + : `No new chat replay for ${opts.videoId} came back; the chat on disk is kept as it was.\n`, + ); + return { status: "none" }; + } + } const entries = await readdir(videoDir).catch(() => [] as string[]); if (!listingHas(entries, LIVE_CHAT_FILENAME)) { opts.onLog(`No chat replay for ${opts.videoId}: the source has none (chat replay off, or never live). Nothing written.\n`); @@ -303,8 +328,28 @@ export type FetchChatJobOpts = { // `needsMedia`, so a raw that is a tier link onto an unreachable drive is // refused by runManagedFunction's guard like any other media reader. renormalize?: boolean; + // THE DELIBERATE RE-FETCH (the one-form rule, lib/storedText-write-server.ts): + // fetch the replay again over a chat stored compressed; the new plain file + // replaces the stored one when it lands whole. Refused over a PLAIN chat + // (yt-dlp would keep it and fetch nothing). + replace?: boolean; }; +/** Why a re-fetch over the chat on disk cannot run, or null. Reads the disk only. */ +export async function replaceChatRefusal(paths: Paths, slug: string, videoId: string): Promise<string | null> { + if (!isVideoIdSegment(videoId)) return `"${videoId}" is not a video id (one path segment)`; + const videoDir = path.join(paths.channelsDir, slug, "data", videoId); + if (!(await isDirectory(videoDir))) return notFetchedRefusal(videoId, slug); + const forms = storedFormsIn(await readdir(videoDir).catch(() => [] as string[]), LIVE_CHAT_FILENAME); + if (forms === "plain" || forms === "both") { + return ( + `${videoId}'s raw chat is a plain ${LIVE_CHAT_FILENAME} here: "replace" re-fetches over a chat stored ` + + `compressed only (yt-dlp keeps a plain file and fetches nothing) — delete it on the video's files card first` + ); + } + return null; +} + /** Why a re-normalize cannot run for this video, or null. Reads the disk only. */ export async function renormalizeChatRefusal( paths: Paths, @@ -333,13 +378,20 @@ export async function runFetchChatJob(opts: FetchChatJobOpts): Promise<StreamAct } catch (err) { return { ok: false, error: (err as Error).message }; } + if (opts.renormalize && opts.replace) { + return { ok: false, error: `"renormalize" reads the raw chat here and "replace" fetches it again: ask one` }; + } if (opts.renormalize) { const refusal = await renormalizeChatRefusal(paths, slug, videoId); if (refusal) return { ok: false, error: refusal }; } + if (opts.replace) { + const refusal = await replaceChatRefusal(paths, slug, videoId); + if (refusal) return { ok: false, error: refusal }; + } const plan: LiveChatPlan = opts.renormalize ? { kind: "normalize" } - : await liveChatPlan(paths, slug, videoId, channelConfig); + : await liveChatPlan(paths, slug, videoId, channelConfig, { replace: opts.replace === true }); switch (plan.kind) { case "refused": return { ok: false, error: plan.error }; @@ -397,6 +449,7 @@ export async function runFetchChatJob(opts: FetchChatJobOpts): Promise<StreamAct onPlatformClean: () => recordPlatformClean(plan.platform, paths), ...(plan.live ? { capturingLive: true } : {}), ...(opts.run ? { run: opts.run } : {}), + ...(opts.replace ? { replace: true } : {}), }); } await opts.afterRun?.(); diff --git a/common/lib/storedText.grep.test.ts b/common/lib/storedText.grep.test.ts @@ -14,14 +14,26 @@ import { fileURLToPath } from "node:url"; // older stored copy brought back as the file. So every line of app code that // names the raw chat must go through the stored-text helpers. A context-blind // grep, like architecture.test.ts: each line naming it (by its constant or the -// literal) must also name a sanctioned helper within the same statement (the -// line or the two before it), or interpolate the name into a message, or be -// an import, or be one of the definitions below. +// literal) must also name a sanctioned READER or DELETER within the same +// statement (the line or the two before it), or interpolate the name into a +// message (a log line, an error), or be inside an import, or be one of the +// definitions below, or be an ALLOWED line (each with its reason). +// +// The second gate below is the one REVIEW-1 F2 asked for: every yt-dlp argv +// that can WRITE the chat, and every caller of its builder, is pinned — a new +// one fails until it asks the disk for the stored form first and says so here. +// +// WHAT THESE GATES CANNOT SEE: a channel's own `ytdlpExtraArgs` (appended to +// every spawn; a `--sub-langs` there would win over the narrowing — no channel +// sets one today); a flag spelled at run time (built from a variable, or inside +// one shell string); a spawn in a language they do not read (shell, Python); +// yt-dlp's own config files (the builders pass `--ignore-config`); and a read +// of the chat through a path built from a variable that holds the name. const COMMON = path.dirname(path.dirname(fileURLToPath(import.meta.url))); const REPO = path.dirname(COMMON); -const ROOTS = ["common", "editor/app", "mcp/src", "umtool", "export/scripts", "export/lib", "export/app"]; +const ROOTS = ["common", "editor/app", "editor/lib", "mcp/src", "umtool", "export/scripts", "export/lib", "export/app", "scripts", "docker"]; const SKIP_DIRS = new Set(["node_modules", ".next", "out", "public", "e2e", "dist", ".turbo"]); // The names of the raw chat in code: the two constants, the stored one, the @@ -29,10 +41,36 @@ const SKIP_DIRS = new Set(["node_modules", ".next", "out", "public", "e2e", "dis // derived `live_chat.cues.json`). const NAMES = /\bLIVE_CHAT_(?:MEDIA_|STORED_)?FILENAME\b|transcript\.live_chat\.json(?![.\w])/; -// The read path, the existence checks, the one deleter, and the tier hook -// (which moves whichever form it is given and never reads it). +// The read path, the existence checks, and the writers that know both forms. +// Readers and deleters only: a name helper (`storedNameOf`) or the tier hook +// (`tierMediaFile`) makes no read safe — those lines are in ALLOWED. const SANCTIONED = - /\b(?:listingHas|storedFormsIn|logicalEntries|readdirLogical|storedTextExists|storedTextForms|storedTextMtimeMs|statStoredText|readStoredText|storedTextLogicalSize|removeStoredText|compressStoredText|verifyStoredText|storedNameOf|tierMediaFile|isStoredTextName)\b/; + /\b(?:listingHas|storedFormsIn|logicalEntries|readdirLogical|storedTextExists|storedTextForms|storedTextMtimeMs|statStoredText|readStoredText|storedTextLogicalSize|removeStoredText|removeStoredTextForm|compressStoredText|restoreStoredText|verifyStoredText|settleStoredTextAfterWrite|plainIdentity|hasStoredTextLeftover)\b/; + +// Lines that name the raw chat for a reason that is neither a read nor a +// delete, each with it: `file` and a pattern of the code on the line. +const ALLOWED: { file: string; code: RegExp; why: string }[] = [ + { + file: "common/controller/compressText.ts", + code: /sizeOf\(path\.join\(videoDir, (?:LIVE_CHAT_FILENAME|storedNameOf\(LIVE_CHAT_FILENAME\))\)\)|const zp = path\.join\(videoDir, storedNameOf\(LIVE_CHAT_FILENAME\)\)/, + why: "the migration's own survey: each form's PHYSICAL size, after storedFormsIn said which are there", + }, + { + file: "common/controller/normalizeLiveChat.ts", + code: /^\s*`Failed to parse \$\{LIVE_CHAT_FILENAME\} for /, + why: "a message (its path.basename is the video id, not a path to the chat)", + }, + { + file: "common/controller/normalizeLiveChat.ts", + code: /await tierMediaFile\(opts\.videoDir, LIVE_CHAT_(?:STORED_)?FILENAME, \{ onLog \}\)/, + why: "the tier hook moves whichever form it is given and never reads it", + }, + { + file: "scripts/archilyzer-ops.mjs", + code: /^\s*['"`][^'"`]*transcript\.live_chat\.json[^'"`]*['"`],?\s*$/, + why: "a line of the ops help text (a string literal alone on its line)", + }, +]; // Where the names are DEFINED or are the rules themselves. const DEFINITIONS = new Set([ @@ -58,6 +96,18 @@ async function walk(dir: string, out: string[]): Promise<void> { } } +// Every walked file's lines, read once for both gates. +let corpusOnce: Promise<{ rel: string; lines: string[] }[]> | undefined; +function appFiles(): Promise<{ rel: string; lines: string[] }[]> { + return (corpusOnce ??= (async () => { + const files: string[] = []; + for (const r of ROOTS) await walk(path.join(REPO, r), files); + return Promise.all( + files.map(async (f) => ({ rel: path.relative(REPO, f), lines: (await readFile(f, "utf8")).split("\n") })), + ); + })()); +} + function codeOnly(line: string): string { const t = line.trim(); if (t.startsWith("//") || t.startsWith("*") || t.startsWith("/*")) return ""; @@ -66,21 +116,37 @@ function codeOnly(line: string): string { } test("every app line naming the raw live chat goes through the stored-text helpers", async () => { - const files: string[] = []; - for (const r of ROOTS) await walk(path.join(REPO, r), files); + const files = await appFiles(); assert.ok(files.length > 200, `walked ${files.length} files`); const offenders: string[] = []; - for (const file of files) { - const rel = path.relative(REPO, file); + for (const { rel, lines } of files) { if (DEFINITIONS.has(rel)) continue; - const lines = (await readFile(file, "utf8")).split("\n"); + let inImport = false; for (let i = 0; i < lines.length; i++) { const code = codeOnly(lines[i]); + // Inside a multi-line `import { … } from` / `export { … } from` list — + // and only there: a bare constant on a line of its own elsewhere (a + // prettier-wrapped `rm(path.join(\n dir,\n NAME,\n))`) is a use. + if (/^\s*(?:import|export)\b[^;]*\{[^}]*$/.test(code)) { + inImport = true; + continue; + } + if (inImport) { + if (/\}/.test(code)) inImport = false; + continue; + } if (!NAMES.test(code)) continue; - // An import or an import/export list member. - if (/^\s*(?:import\b|export\s*\{)/.test(code) || /^\s*[A-Z_]+,?\s*$/.test(code)) continue; - // Interpolated into a message (a log line, an error). - if (/\$\{LIVE_CHAT_(?:MEDIA_|STORED_)?FILENAME\}/.test(code)) continue; + // A one-line import or re-export. + if (/^\s*(?:import\b|export\s*\{)/.test(code)) continue; + // Interpolated into a MESSAGE — a log line, an error, a refusal — and + // never into a path (a template with a "/" or a path.* call is a path). + if ( + /\$\{LIVE_CHAT_(?:MEDIA_|STORED_)?FILENAME\}/.test(code) && + !/\/\$\{LIVE_CHAT|\$\{LIVE_CHAT_(?:MEDIA_|STORED_)?FILENAME\}\/|path\.|join\(/.test(code) + ) { + continue; + } + if (ALLOWED.some((a) => a.file === rel && a.code.test(code))) continue; // UI copy naming the file. if (/<code>transcript\.live_chat\.json<\/code>/.test(code)) continue; const statement = [lines[i - 2] ?? "", lines[i - 1] ?? "", code].map(codeOnly).join("\n"); @@ -94,3 +160,96 @@ test("every app line naming the raw live chat goes through the stored-text helpe "read, list, stat or delete the raw live chat through lib/storedText(-server|-write-server).ts — it may be stored as .zst", ); }); + +// ── THE SECOND GATE: EVERY yt-dlp ARGV THAT CAN WRITE THE CHAT (REVIEW-1 F2) ── +// +// yt-dlp's own "already present" skip sees only the plain +// `transcript.live_chat.json`: a pass that may write subtitles over a chat +// stored as `.zst` fetches the whole replay again and lands a second copy +// beside it. The first gate cannot see such a site — it names no file, only a +// flag. So every code line carrying a subtitle-writing flag (or `live_chat` +// as an argv value) must be inside a builder pinned here, and every builder's +// callers are pinned by count, each with the guard that asks the disk first +// and the behavioural test that proves it. A new site, or a new caller of a +// builder, fails until it is listed — with its guard and its test. + +// A flag as an argv element: `"--write-subs"`, `'--sub-langs'`, or a joined +// `--sub-langs=…` in any quote; or `"live_chat"` alone as an argv value. +// (Prose that names a flag in backticks is not an argv.) +const SUB_FLAGS = + /(["'])--(?:sub-langs?|all-subs|write-subs|write-auto-subs|write-automatic-subs)\1|["'`]--(?:sub-langs?)=|^\s*["'`]live_chat["'`],?\s*$/; + +const CHAT_WRITERS: Record<string, { file: string; guard: string; test: string }> = { + youtubeHandlingArgs: { + file: "common/ytdlp/downloadOneManaged.ts", + guard: "chatStored (storedFormsIn === \"zst\"): the chat left out of --sub-langs", + test: "controller/storedText.chat.test.ts (youtubeHandlingArgs)", + }, + liveChatOnlyArgs: { + file: "common/ytdlp/downloadOneManaged.ts", + guard: "the chat-only pass: hasLiveChatOnDisk first; fetch-chat: liveChatPlan, or `replace` with the one-form settle", + test: "ytdlp/chatOnlyStored.test.ts; controller/fetchLiveChat.test.ts (replace)", + }, + downloadSubsForUrl: { + file: "common/ytdlp/runYtdlp.ts", + guard: "subLangsForVideo: the chat left out of --sub-langs for a stored chat", + test: "controller/storedText.chat.test.ts (subLangsForVideo)", + }, +}; + +// Every call of each builder, by file (the definition not counted). A caller +// is where the guard has to be. +const CALLERS: Record<string, Record<string, number>> = { + youtubeHandlingArgs: { "common/ytdlp/downloadOneManaged.ts": 1 }, + liveChatOnlyArgs: { "common/ytdlp/downloadOneManaged.ts": 1, "common/controller/fetchLiveChat.ts": 1 }, + downloadSubsForUrl: { "common/ytdlp/runYtdlp.ts": 1 }, +}; + +const BUILDER_RES = Object.keys(CHAT_WRITERS).map((name) => ({ + name, + call: new RegExp(`\\b${name}\\s*\\(`, "g"), + def: new RegExp(`\\bfunction\\s+${name}\\s*\\(`), +})); + +// The enclosing named function of line `i`: the nearest `function NAME(` +// above it. Good enough for argv builders, which are named functions. +function enclosingFunction(lines: string[], i: number): string | null { + for (let j = i; j >= 0; j--) { + const m = /\bfunction\s+([A-Za-z0-9_$]+)\s*[(<]/.exec(codeOnly(lines[j])); + if (m) return m[1]; + } + return null; +} + +test("every yt-dlp argv that can write the raw chat is a pinned builder, and every caller of one is pinned", async () => { + const sites: string[] = []; + const calls: Record<string, Record<string, number>> = {}; + for (const { rel, lines } of await appFiles()) { + for (let i = 0; i < lines.length; i++) { + const code = codeOnly(lines[i]); + if (SUB_FLAGS.test(code)) { + const fn = enclosingFunction(lines, i); + const pinned = fn ? CHAT_WRITERS[fn] : undefined; + if (!pinned || pinned.file !== rel) sites.push(`${rel}:${i + 1} (in ${fn ?? "no function"}): ${lines[i].trim()}`); + } + for (const { name, call, def } of BUILDER_RES) { + if (!code.includes(name)) continue; + const n = (code.match(call) ?? []).length - (def.test(code) ? 1 : 0); + if (n > 0) (calls[name] ??= {})[rel] = (calls[name]?.[rel] ?? 0) + n; + } + } + } + assert.deepEqual( + sites, + [], + "a yt-dlp argv that can write subtitles (the chat among them) outside a pinned builder: it must ask the disk " + + "for the stored chat first (listingHas / storedFormsIn), have a test that the fake yt-dlp is not asked for it, " + + "and be listed in CHAT_WRITERS", + ); + assert.deepEqual( + calls, + CALLERS, + "a new caller of a chat-writing argv builder: it must guard against a stored chat (see CHAT_WRITERS' guards), " + + "be tested, and be counted in CALLERS", + ); +}); diff --git a/common/ytdlp/chatOnlyStored.test.ts b/common/ytdlp/chatOnlyStored.test.ts @@ -0,0 +1,146 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { chmod, mkdir, mkdtemp, readFile, readdir, 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 { downloadOneManaged } from "./downloadOneManaged"; +import { storeFixture } from "../testing/storedTextFixture"; +import { readStoredText } from "../lib/storedText-server"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/chatOnlyStored.test.ts +// +// REVIEW-1 F2: THE CHAT-ONLY PASS OVER A CHAT ALREADY ON DISK. A title-filter +// rejection of a livestream on a `chat-only` channel runs a yt-dlp pass with +// `--sub-langs live_chat`. yt-dlp's own "already present" skip sees only the +// plain `transcript.live_chat.json`, so over a chat stored compressed the pass +// fetched the whole replay again and landed a second copy beside it. Now the +// pass asks the disk first (either form) and normalizes what is here. The +// yt-dlp is a temp node script that logs every argv; no network. + +const ID = "Zz0chatonly"; +const VIDEO = `https://www.youtube.com/watch?v=${ID}`; +const CHAT = "transcript.live_chat.json"; + +// The fake: the metadata prefetch writes meta.json as the info json; a chat +// pass writes a NEW plain chat (what yt-dlp would, not seeing a .zst). +const FAKE_YTDLP = `#!/usr/bin/env node +const fs = require("node:fs"); +const path = require("node:path"); +const argv = process.argv.slice(2); +const root = process.env.FAKE_ROOT; +fs.appendFileSync(path.join(root, "argv.log"), JSON.stringify(argv) + "\\n"); +const has = (f) => argv.includes(f); +const arg = (f) => { const i = argv.indexOf(f); return i < 0 ? undefined : argv[i + 1]; }; +const dir = path.join("data", "${ID}"); +fs.mkdirSync(dir, { recursive: true }); +if (has("--skip-download") && has("--write-info-json") && has("--no-write-subs")) { + fs.copyFileSync(path.join(root, "meta.json"), path.join(dir, "metadata.info.json")); + process.exit(0); +} +if (arg("--sub-langs") === "live_chat") { + fs.writeFileSync(path.join(dir, "${CHAT}"), fs.readFileSync(path.join(root, "refetched.json"))); + process.exit(0); +} +console.error("fake: unknown invocation " + argv.join(" ")); +process.exit(2); +`; + +function chatLine(sec: number, text: string): string { + return JSON.stringify({ + replayChatItemAction: { + actions: [{ addChatItemAction: { item: { liveChatTextMessageRenderer: { message: { runs: [{ text }] }, authorName: { simpleText: "v" } } } } }], + videoOffsetTimeMsec: String(sec * 1000), + }, + }); +} +const WHOLE = [chatLine(5, "first"), chatLine(9, "second"), chatLine(20, "third")].join("\n") + "\n"; +const TRIMMED = chatLine(5, "first") + "\n"; + +const META = { id: ID, title: "A stream", live_status: "was_live", was_live: true, duration: 3600, webpage_url: VIDEO }; + +async function runWith(seed: "stored" | "plain" | "none") { + const root = await mkdtemp(path.join(tmpdir(), "chat-only-stored-")); + const ytdlp = path.join(root, "fake-ytdlp.cjs"); + await writeFile(ytdlp, FAKE_YTDLP); + await chmod(ytdlp, 0o755); + await writeFile(path.join(root, "meta.json"), JSON.stringify(META)); + await writeFile(path.join(root, "refetched.json"), TRIMMED); + process.env.FAKE_ROOT = root; + const paths = { + transcriptsDir: root, + channelsDir: path.join(root, "channels"), + savedVideosDir: path.join(root, "saved-videos"), + ytdlpBin: ytdlp, + ffmpegBin: path.join(root, "no-ffmpeg"), + ffprobeBin: path.join(root, "no-ffprobe"), + } as Paths; + const videoDir = path.join(paths.channelsDir, "c", "data", ID); + await mkdir(videoDir, { recursive: true }); + await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify(META)); + if (seed !== "none") { + await writeFile(path.join(videoDir, CHAT), WHOLE); + if (seed === "stored") await storeFixture(videoDir, CHAT); + } + let log = ""; + const record = await downloadOneManaged({ + channelSlug: "c", + channelConfig: { + handling: "youtube", + url: "https://www.youtube.com/@c/streams", + downloadFilter: { include: "^nothing matches this$", rejectedLivestreams: "chat-only" }, + } as ChannelConfig, + paths, + videoUrl: VIDEO, + onLog: (s) => { + log += s; + }, + signal: new AbortController().signal, + }); + const argvs = (await readFile(path.join(root, "argv.log"), "utf8").catch(() => "")) + .split("\n") + .filter(Boolean) + .map((l) => JSON.parse(l) as string[]); + return { + record, + log, + videoDir, + argvs, + chatPasses: argvs.filter((a) => a.includes("live_chat")), + files: (await readdir(videoDir)).sort(), + cleanup: () => rm(root, { recursive: true, force: true }), + }; +} + +for (const seed of ["stored", "plain"] as const) { + test(`a chat-only video whose chat is on disk (${seed}) is not fetched again: normalized from what is here`, async () => { + const r = await runWith(seed); + try { + assert.deepEqual(r.chatPasses, [], `no --sub-langs live_chat pass: ${JSON.stringify(r.argvs)}`); + assert.equal(r.record.status, "chat-only", r.log); + assert.match(r.log, /already on disk; not fetched again/); + assert.equal(await readStoredText(r.videoDir, CHAT, "utf8"), WHOLE, "the whole capture, not a re-fetch"); + assert.ok(r.files.includes("live_chat.cues.json"), `normalized: ${r.files.join(", ")}`); + // Exactly the form that was there. + assert.deepEqual( + r.files.filter((f) => f.startsWith("transcript.live_chat")), + seed === "stored" ? [`${CHAT}.zst`] : [CHAT], + ); + } finally { + await r.cleanup(); + } + }); +} + +test("a chat-only video with no chat on disk still runs the chat pass (the control)", async () => { + const r = await runWith("none"); + try { + assert.equal(r.chatPasses.length, 1, JSON.stringify(r.argvs)); + assert.equal(r.record.status, "chat-only", r.log); + assert.equal(await readStoredText(r.videoDir, CHAT, "utf8"), TRIMMED); + } finally { + await r.cleanup(); + } +}); diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts @@ -1115,7 +1115,29 @@ async function runManagedDownload( // it and re-runs a pass that will never return anything. let chatOnlyFetched = false; let chatOnlyUnavailable = false; - if (decision.chatOnly && !opts.signal.aborted) { + // A CHAT ALREADY ON DISK, IN EITHER FORM (lib/storedText.ts), is not + // fetched again: yt-dlp's own "already present" skip sees only the + // plain name, so over a compressed chat this pass would fetch the whole + // replay and land a second, maybe trimmed, copy beside it (REVIEW-1 F2). + // It is normalized from what is here instead. + const chatHere = decision.chatOnly && (await hasLiveChatOnDisk(videoDir)); + if (chatHere) { + opts.onLog( + `The live chat of ${canonicalId} is already on disk; not fetched again (media skipped by the download filter).\n`, + ); + chatOnlyFetched = true; + try { + await normalizeLiveChat({ + videoDir, + channelSlug: opts.channelSlug, + ...(opts.channelConfig.name ? { configName: opts.channelConfig.name } : {}), + log: (m: string) => opts.onLog(`${m}\n`), + }); + } catch (err) { + opts.onLog(`Could not normalize the live chat: ${(err as Error).message}\n`); + } + } + if (decision.chatOnly && !chatHere && !opts.signal.aborted) { opts.onLog( `Fetching the live chat for ${canonicalId} (media skipped by the download filter).\n`, ); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -7,7 +7,15 @@ - One file at a time, verified by reading it back before the original is removed; a crash at any step leaves a whole copy and the next run finishes. `dryRun` reports bytes per channel and writes nothing; `verify` decodes every stored chat; `limit` caps a run. It waits for render mode and goes slower while a live recording runs. - - Deleting a chat (the video page, the auto-caption purge, the clear-transcript fix) removes both forms. + - Deleting a chat (the auto-caption purge, the clear-transcript fix) removes both forms. On the video's files card, + one form named while the other is there: both go when they hold the same content; with different content only + the named one, and the card says the other is still there. + - `"restore": true` is the rollback: every stored chat back to its plain form, verified the same way in reverse. + Restore before reverting or running an older checkout, which cannot read a stored chat. + - Started by a person only: a restart closes a queued compress-text job and resumes no interrupted one. A re-run + finishes whatever a stopped run left, whichever process it was. + - No download fetches a chat that is on disk in either form. `pnpm ops fetch-chat` `"replace": true` fetches a + stored chat again on purpose; the new chat replaces the stored one only when it lands whole. - **umtool: the gap mark's border is the deck's accent colour.** - The operator picked variant B. The border is drawn in the deck's accent, the colour of the deck's accent rule and the dots in its source line, at full opacity. The box behind the text is near-black at 90 %, and the text diff --git a/editor/app/api/ops/fetch-chat/route.ts b/editor/app/api/ops/fetch-chat/route.ts @@ -20,11 +20,18 @@ export const dynamic = "force-dynamic"; // `renormalize: true` parses the raw chat already on disk again (fresh or // not) onto the recording's clock, with no network: refused when no raw is // here — it never fetches. +// +// `replace: true` is the DELIBERATE RE-FETCH over a chat stored compressed +// (`transcript.live_chat.json.zst`): the replay is fetched again, and when a +// whole new plain chat lands the stored one is removed — one form is left. A +// pass that lands nothing keeps the stored chat as it was. Refused over a +// plain chat (delete it on the files card first) and with `renormalize`. export async function POST(request: Request) { - return ops(request, ["slug", "id", "queueKey", "renormalize"], async (body) => + return ops(request, ["slug", "id", "queueKey", "renormalize", "replace"], async (body) => jobResponse( await fetchChatAction(reqSlug(body, "slug"), reqVideoId(body, "id"), optString(body, "queueKey"), { renormalize: optBool(body, "renormalize") === true, + replace: optBool(body, "replace") === true, }), ), ); diff --git a/editor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts b/editor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts @@ -57,7 +57,7 @@ export async function fetchChatAction( slug: string, videoId: string, queueKey?: string, - opts: { renormalize?: boolean } = {}, + opts: { renormalize?: boolean; replace?: boolean } = {}, ): Promise<StreamActionResult> { if (!isValidChannelSlug(slug)) return { ok: false, error: `"${slug}" is not a channel slug` }; const paths = getPaths(); @@ -71,6 +71,7 @@ export async function fetchChatAction( cookiePolicy: resolveCookiePolicy(getSettings(), config), ...(queueKey !== undefined ? { queueKey } : {}), ...(opts.renormalize ? { renormalize: true } : {}), + ...(opts.replace ? { replace: true } : {}), afterRun: () => safeRevalidate([`/channels/${slug}/videos/${videoId}`]), }); } diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -559,7 +559,7 @@ const ACTIONS = [ // The failed encodes kept for a re-verify, and clearing one ({} | {clear: {slug, id}}). "kept-failed-encodes", // The raw live chats stored zstd-compressed, one file at a time, verified - // before each original goes ({slugs?, kinds?, dryRun?, limit? (one slug), verify?}). + // before each original goes ({slugs?, kinds?, dryRun?, limit? (one slug), verify?, restore?}). "compress-text", // Write transcript.cues.json from each video's raw transcript ({slug, ids?, // force?}) — what a reader with no index build wants. @@ -1595,7 +1595,10 @@ export function usage() { '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.', + ' answering. No undo. A raw live chat named in one form while the other is', + ' there (transcript.live_chat.json and its .zst): both go when they hold the', + ' same content; only the named one when they differ, and "note" says the', + ' other is still there.', "", '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.)', @@ -1888,6 +1891,11 @@ export function usage() { ' "renormalize": true parses the raw chat already on disk again, fresh or', " not, with no network — for a chat normalized before that; refused when no", " raw is here (it never fetches).", + ' "replace": true fetches the replay again over a chat stored compressed', + " (.zst): when a whole new plain chat lands, the stored one is removed --", + " one form is left; a pass that lands nothing keeps the stored chat. Refused", + ' over a plain chat (delete it on the files card first) and with', + ' "renormalize".', "", 'fetch-chat-backlog fetches a channel\'s stream chats after its downloads:', ' {"slug", "dryRun"?, "limit"?, "queueKey"?} — every held video whose', @@ -2298,21 +2306,30 @@ export function usage() { ' transcript.live_chat.json becomes transcript.live_chat.json.zst, read', " back by every reader as the same file, with the same times (the index", ' sees no change): {"slugs"?: [...], "kinds"?: ["live-chat"], "dryRun"?,', - ' "limit"?, "verify"?}. One file at a time: written beside the original,', - " fsynced, read back and hashed against it, and only then the original", - " removed; a crash at any step leaves a whole copy, and the next run", - " finishes it. Left alone and counted: a file written in the last 10", - " minutes, one with a .part beside it, a video recording or with a job", - " running, a drive that does not answer, a channel whose media is moving.", - " Both forms present with different content are refused and both kept.", + ' "limit"?, "verify"?, "restore"?}. One file at a time: written beside the', + " original, fsynced, read back and hashed against it, and only then the", + " original removed; a crash at any step leaves a whole copy, and the next", + " run finishes it (it visits every dir a stopped run left). Left alone and", + " counted: a file written (mtime or ctime) in the last 10 minutes, one with", + " a .part beside it, a video recording or with a job running, a drive that", + " does not answer, a channel whose media is moving. Both forms present with", + " different content are refused and both kept. A file a writer replaces", + " during the run is kept, and the older stored copy removed.", ' "dryRun": true answers per channel the raw chats, their bytes, the', " stored ones, the estimate after (about 5 %, an estimate) and the free", ' space, and writes nothing; "verify": true decodes every stored file in', ' full and writes nothing; "limit" counts files compressed and takes', ' exactly one channel in "slugs". One job per channel with work, on the', " machine-wide compress-text queue (one file at a time), waiting while", - " render mode holds the machine and slower while a live recording runs;", - " never resumed at boot (it removes originals) -- a re-run continues.", + " render mode holds the machine and slower while a live recording runs.", + " Started by a person only: a restart closes a queued one and resumes no", + " interrupted one (it removes originals) -- a re-run continues.", + ' "restore": true is the rollback: every stored chat put back into its', + " plain form, verified the same way in reverse (decoded beside, fsynced,", + " read back against a fresh decode, the same times, then the .zst removed);", + ' with "dryRun" it answers the stored files, their plain bytes and the free', + " space. Run it BEFORE reverting or running an older checkout, which cannot", + " read a stored chat (OPERATING.md).", "", 'compaction-markers lists the "being compacted" markers (.compacting.json),', ' each live or stale and why: {}. {"clear": {"slug", "id"}} removes a stale',