commit 909d54e1d9c88e61d0fd40b43a3301cf4e935ca1
parent 28125b6354f8a111e46a4315b87e0697ca9fe277
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 05:22:28 -0500
Merge lane/text-compress: a raw live-chat capture may be stored zstd-compressed
Every reader, lister, mover and deleter of the raw chat treats `<name>` and `<name>.zst` as one file.
`compress-text` (person-started, one channel a job, dryRun, restore) writes, verifies by a fresh decode,
keeps the mtime and only then retires the original; a re-fetch sets the earlier capture aside and never
removes it. Captions and other sidecars are untouched.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
52 files changed, 5540 insertions(+), 73 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -161,6 +161,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": "<file>" 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"?, "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 read; the earlier content's stored copy is kept beside it. The dry run lists earlier chat captures a re-fetch kept (chat-capture-kept.\*.json.zst), which nothing removes automatically. "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 +203,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:<slug>:<id>), 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): only the named one goes, never the other, 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` |
@@ -241,7 +242,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `copies-reject` | copies-reject rejects pairs: the same body as copies-confirm. A rejected pair never holds or skips again, whatever its link; undo takes it back, and a later confirm replaces it. | |
| `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"}'` |
| `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)} -> {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 <platform>" (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 <platform>" (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). The stored capture is first kept as chat-capture-kept.<UTC stamp>.json.zst (no reader sees it; never removed automatically). A replay with messages becomes the chat; an empty one is kept too and, like no replay, leaves the stored capture the chat. The log gives both captures' bytes, message counts and first/last message times. 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/<id>/words.json), the chat replay (YouTube), diarization — each step skipped when its output exists, named in the log — then umtool's clip finder (POST UMTOOL\_URL/api/report/clips {mode: "new"}), followed to the end. "whilePaused": true runs this one video past the holds: the two transcriptions during a pause-all on a worker the pause alone switched off, and its diarization in the job when the backfill lane is held. "dryRun": true answers each step's plan and starts nothing. With --wait the result — {project, url, created, segments: \[{id, from, to, why}\], steps} — is printed on stdout. | `pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","segment":"s2","whilePaused":true}' --wait` |
| `fetch-chat-backlog` | fetch-chat-backlog fetches a channel's stream chats after its downloads: {"slug", "dryRun"?, "limit"?, "queueKey"?} — every held video whose metadata says it was a stream (live\_status was\_live / post\_live) and whose chat is not here, newest first, one at a time through fetch-chat's pass with the batch downloads' gap between two, as one fetch-chat-backlog job on the platform's download queue; a raw replay already here is only normalized. It stops on a rate limit, a held platform, three failures in a row, a drain or "limit" chats; a re-run skips the chats here and the streams known to have none (chat-backlog.json), and a restart resumes it. The download lane queues it by itself (25 a run) for a channel whose "chat" is "later" once it has nothing left to download. "dryRun": true counts from the disk and starts nothing: chats, normalizeOnly, have, settled, notStreams, ids (the first 50). | `pnpm ops fetch-chat-backlog --json '{"slug":"demo-yt","dryRun":true}'` |
| `x-run` | x-run fetches several X posts channels IN SEQUENCE as ONE job on X's queue: {"channels": \[slug, ...\]} in that order, each a fetch-posts sync new of at most 200 posts ("limit": N, 1-200, caps it lower), X's queue gap (pacing.jobGapSeconds.twitter) between two channels. Before EACH channel the jar is checked again: once it is past social.x.maxCookieAgeMinutes (or the X alert is up) the run stops and the rest are DEFERRED until the next refresh. It never refreshes the jar: Refresh cookies on /cookies, then {"resume": "<run id>"} runs the deferred channels (the console's Resume; a Retry of the job is the same). One run at a time; refused before a job on a stale jar (a new run's channels are kept, deferred). An interrupted run is not resumed on boot: it ends deferred. Answers {jobId, run}; get x-run follows it. The log ends with @@x-run {id, status, stopped?, counts, summary}. | `pnpm ops x-run --json '{"channels":["example-x","other-x"]}'`<br>`pnpm ops x-run --json '{"resume":"xr-01J…"}'` |
diff --git a/OPERATING.md b/OPERATING.md
@@ -1646,6 +1646,77 @@ pnpm wt prune --dry-run [--json] # w
- **Not done by it**: the clip-window cache (`evict-clips`: re-fetching is paced), a project's only preview, other
sessions' job directories, anything under `transcripts/`.
+### Compress the raw live chats
+
+```sh
+pnpm ops compress-text --json '{"dryRun":true}' # per channel: raw chats, bytes, the estimate after, free space; writes nothing
+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 (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. 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 read, and the stored copy of the earlier content is
+ kept beside it: two different captures are never settled by deleting one.
+- **One job per channel** with work, on one machine-wide queue, so a move of that channel's media refuses while it
+ runs, and a lock file in each video dir (`.stored-text.lock`) makes a second process (a second editor) wait its
+ turn instead of interleaving. **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}'`. The
+ stored capture is first **kept** as `chat-capture-kept.<UTC stamp>.json.zst` beside it (the same bytes; no reader of
+ the chat, the index, the compressor or the restore sees it; it is media, so it moves with the video, and deleting
+ the video removes it). The job log gives both captures' bytes, message counts and first/last message times. A
+ replay with messages then becomes the chat; an empty replay is kept the same way and, like no replay at all, leaves
+ the stored capture the chat. **Nothing removes a kept capture automatically** — a platform's replay is often
+ shorter than the live capture, which cannot be fetched again. The dry run lists them ("earlier captures kept");
+ delete one on the files card when you have looked at 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`. Only the file you
+ name goes, never its other form; the card says when the other is still there (with the same content, readers still
+ see the chat; with different content, the other is what readers read).
+- **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 (a hard link: the drive must support them — ext4 does; on exFAT or a CIFS mount the restore refuses each
+file and leaves it stored), looked at again (size and hash), 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. Kept earlier captures
+(`chat-capture-kept.*.json.zst`) are not restored: an older checkout ignores them, and they stay where they are.
+
### Compact saved videos
```sh
diff --git a/common/controller/archiveLiveChat.ts b/common/controller/archiveLiveChat.ts
@@ -18,7 +18,6 @@ import path from "node:path";
import {
access,
link,
- lstat,
mkdir,
readdir,
rm,
@@ -30,6 +29,7 @@ import { listChannelStatsFromDisk, type ChannelStat } from "./channels";
import { isLiveChatCuesFresh, normalizeLiveChat } from "./normalizeLiveChat";
import { inspectChannelMedia } from "../lib/channelMedia";
import { LIVE_CHAT_MEDIA_FILENAME } from "../lib/mediaTier";
+import { storedTextExists } from "../lib/storedText-server";
import {
archiveExtension,
archiveSidecarPath,
@@ -192,10 +192,8 @@ async function stageChannel(
() => false,
);
if (!have) {
- const hasRaw = await lstat(path.join(videoDir, LIVE_CHAT_MEDIA_FILENAME)).then(
- () => true,
- () => false,
- );
+ // Either form (lib/storedText.ts), by `lstat`.
+ const hasRaw = await storedTextExists(videoDir, LIVE_CHAT_MEDIA_FILENAME);
if (hasRaw) leftOut++;
return;
}
diff --git a/common/controller/buildIndex.test.ts b/common/controller/buildIndex.test.ts
@@ -895,6 +895,80 @@ test("(n) lane missing-source: an undated state with a channel held is re-read o
assert.ok(third.log.some((l) => l.startsWith("Shared transcript pages up to date")), third.log.join("\n"));
});
+test("(s) lane text-compress: a raw chat compressed in place changes NOTHING the index holds, and is still read", async () => {
+ resetCorpus();
+ seedVideo("c1");
+ seedDriveChannel();
+ const chat =
+ JSON.stringify({ replayChatItemAction: { actions: [{ addChatItemAction: { item: { liveChatTextMessageRenderer: { message: { runs: [{ text: "zst" }] }, authorName: { simpleText: "a" }, timestampUsec: "1000000" } } } }], videoOffsetTimeMsec: "1000" } }) + "\n";
+ // c1: a real raw replay on the corpus disk; d2: a tier link onto the drive.
+ // Both with sub-millisecond times — a `Date` would lose them.
+ const { utimesSync, lutimesSync } = await import("node:fs");
+ writeFileSync(path.join(videoDir("c1"), "transcript.live_chat.json"), chat);
+ utimesSync(path.join(videoDir("c1"), "transcript.live_chat.json"), 1763700000.123457, 1763700000.987653);
+ mkdirSync(path.join(DRIVE_MEDIA(), "d2"), { recursive: true });
+ writeFileSync(path.join(DRIVE_MEDIA(), "d2", "transcript.live_chat.json"), chat);
+ symlinkSync("../../media/d2/transcript.live_chat.json", path.join(videoDir("d2", DRIVE_CHANNEL), "transcript.live_chat.json"));
+ lutimesSync(path.join(videoDir("d2", DRIVE_CHANNEL), "transcript.live_chat.json"), 1763700001.5, 1763700001.000003);
+ const tracksOf = (id: string) =>
+ withIndex((db) =>
+ [...db("subs").getRange()]
+ .filter(({ key }) => (key as unknown as string[])[2] === id)
+ .flatMap(({ value }) => (value as { track: string }[]).map((t) => t.track)),
+ );
+ const mtimesOf = () => withIndex((db) => [...db("mtimes").getRange()].map(({ key, value }) => [key, value]));
+ await runIndex();
+ assert.ok(tracksOf("c1").includes("live_chat"));
+ assert.ok(tracksOf("d2").includes("live_chat"));
+ const before = mtimesOf();
+
+ const { storeFixture } = await import("../testing/storedTextFixture");
+ await storeFixture(videoDir("c1"), "transcript.live_chat.json");
+ await storeFixture(videoDir("d2", DRIVE_CHANNEL), "transcript.live_chat.json");
+ assert.equal(existsSync(path.join(videoDir("c1"), "transcript.live_chat.json")), false);
+
+ const after = await runIndex();
+ assert.equal(after.res.changed, 0, after.log.join("\n"));
+ assert.equal(after.res.added, 0);
+ assert.equal(after.res.removed, 0);
+ assert.deepEqual(mtimesOf(), before, "the stored mtimes are the same numbers");
+ assert.ok(tracksOf("c1").includes("live_chat"));
+
+ // A change elsewhere re-reads both records: the chat comes from the stored form.
+ seedVideo("c1", CHANNEL, { title: "Retitled" });
+ seedVideo("d2", DRIVE_CHANNEL, { title: "Retitled" });
+ const reread = await runIndex();
+ assert.equal(reread.res.changed, 2, reread.log.join("\n"));
+ assert.ok(tracksOf("c1").includes("live_chat"), "read from the real stored file");
+ assert.ok(tracksOf("d2").includes("live_chat"), "read through the stored form's tier link");
+});
+
+test("(t) lane text-compress: THE COMPRESSOR itself, over a real and a tiered chat — the index sees no change", async () => {
+ resetCorpus();
+ seedVideo("c1");
+ seedDriveChannel();
+ const chat =
+ JSON.stringify({ replayChatItemAction: { actions: [{ addChatItemAction: { item: { liveChatTextMessageRenderer: { message: { runs: [{ text: "real" }] }, authorName: { simpleText: "a" }, timestampUsec: "1000000" } } } }], videoOffsetTimeMsec: "1000" } }) + "\n";
+ const { utimesSync, lutimesSync } = await import("node:fs");
+ writeFileSync(path.join(videoDir("c1"), "transcript.live_chat.json"), chat);
+ utimesSync(path.join(videoDir("c1"), "transcript.live_chat.json"), 1763700000.123457, 1763700000.987653);
+ mkdirSync(path.join(DRIVE_MEDIA(), "d2"), { recursive: true });
+ writeFileSync(path.join(DRIVE_MEDIA(), "d2", "transcript.live_chat.json"), chat);
+ symlinkSync("../../media/d2/transcript.live_chat.json", path.join(videoDir("d2", DRIVE_CHANNEL), "transcript.live_chat.json"));
+ lutimesSync(path.join(videoDir("d2", DRIVE_CHANNEL), "transcript.live_chat.json"), 1763700001.5, 1763700001.000003);
+ const mtimesOf = () => withIndex((db) => [...db("mtimes").getRange()].map(({ key, value }) => [key, value]));
+ await runIndex();
+ const before = mtimesOf();
+ const { compressStoredText } = await import("../lib/storedText-write-server");
+ for (const dir of [videoDir("c1"), videoDir("d2", DRIVE_CHANNEL)]) {
+ const out = await compressStoredText(dir, "transcript.live_chat.json", { reserveBytes: 0 });
+ assert.equal(out.status, "compressed", JSON.stringify(out));
+ }
+ const after = await runIndex();
+ assert.equal(after.res.changed, 0, after.log.join("\n"));
+ assert.deepEqual(mtimesOf(), before);
+});
+
test("(z) no write this file caused landed outside its temp root", () => {
// LMDB writes natively, past the spy: its file must be under the root too.
assert.ok(paths.lmdbPath.startsWith(ROOT + path.sep), paths.lmdbPath);
diff --git a/common/controller/buildIndex.ts b/common/controller/buildIndex.ts
@@ -28,7 +28,6 @@
import path from "node:path";
import { createHash } from "node:crypto";
import {
- lstat,
mkdir,
readdir,
readFile,
@@ -101,6 +100,7 @@ import {
import { readChannelConfigFile } from "./channels";
import { inspectChannelMedia } from "../lib/channelMedia";
import { isTierable } from "../lib/mediaTier";
+import { readStoredText, statStoredText } from "../lib/storedText-server";
import { onDrive } from "../lib/storageHealth";
import {
HELD_WAYS_OUT,
@@ -591,8 +591,14 @@ async function scanSource(
// channels/<slug>/media, possibly on another drive. The link carries
// the file's times (the tier hook's `lutimes`), so this answers from
// the corpus disk and never reaches the media drive.
- const p = path.join(fullVideoDir, t.filename);
- const ms = (await (isTierable(t.filename) ? lstat(p) : stat(p))).mtimeMs;
+ //
+ // EITHER FORM (lib/storedText.ts): a chat stored compressed is asked
+ // under its stored name, whose times the compressor set to the plain
+ // file's exactly — the same `subsMs`, so a compression re-ingests
+ // nothing.
+ const ms = (
+ await statStoredText(fullVideoDir, t.filename, { link: isTierable(t.filename) })
+ ).stats.mtimeMs;
if (subsMs === null || ms > subsMs) subsMs = ms;
} catch {
// ignore
@@ -1290,16 +1296,24 @@ export async function buildIndex({
// Not read (unreachable, not answering, unreadable): the cues
// the last build held are kept; with none to keep, the record
// is written with no sub-track time, so the next build retries.
+ // Asked of the form present (lib/storedText.ts): a chat stored
+ // compressed is a link as `transcript.live_chat.json.zst`.
+ const rawDir = path.dirname(rawPath);
const tiered =
t.track === "live_chat" &&
- (await lstat(rawPath).then((l) => l.isSymbolicLink(), () => false));
+ (await statStoredText(rawDir, t.filename, { link: true }).then(
+ (l) => l.stats.isSymbolicLink(),
+ () => false,
+ ));
if (tiered) {
const access = mediaAccess.get(s.channelSlug);
let raw: string | null = null;
if (access?.readable) {
try {
- if (access.drive) await onDrive(access.drive, () => stat(rawPath));
- raw = await readFile(rawPath, "utf8");
+ if (access.drive) {
+ await onDrive(access.drive, () => statStoredText(rawDir, t.filename));
+ }
+ raw = await readStoredText(rawDir, t.filename, "utf8");
} catch {
raw = null;
}
@@ -1312,7 +1326,7 @@ export async function buildIndex({
}
trackCues = (await parseLiveChatOnRecordingClock(videoFullDir, raw)).cues;
} else {
- const raw = await readFile(rawPath, "utf8");
+ const raw = await readStoredText(rawDir, t.filename, "utf8");
// A stale chat's raw is parsed onto the recording's clock,
// as the normalizer does (lane chat-clock).
trackCues =
diff --git a/common/controller/channelSnapshot.test.ts b/common/controller/channelSnapshot.test.ts
@@ -628,6 +628,36 @@ test("a chat-only livestream is a corpus member, not a settled stub", async () =
}
});
+test("a chat-only livestream whose chat is STORED compressed is still a corpus member (lane text-compress)", async () => {
+ // Missed, the video would fall back to chatOnlyPending — download-lane work
+ // that fetches the whole chat again.
+ const { dir, paths, channelDir } = await filteredChannel({
+ filter: { include: "keep", rejectedLivestreams: "chat-only" },
+ listed: ["aaaa0000001", "cccc0000003"],
+ scanned: {
+ aaaa0000001: { title: "keep this one" },
+ cccc0000003: { title: "a long stream", liveStatus: "was_live" },
+ },
+ });
+ try {
+ const videoDir = path.join(channelDir, "data", "cccc0000003");
+ await mkdir(videoDir, { recursive: true });
+ await writeFile(
+ path.join(videoDir, "metadata.info.json"),
+ JSON.stringify({ id: "cccc0000003", title: "a long stream" }),
+ );
+ await writeFile(path.join(videoDir, "transcript.live_chat.json"), '{"action":{}}\n');
+ const { storeFixture } = await import("../testing/storedTextFixture");
+ await storeFixture(videoDir, "transcript.live_chat.json");
+ const snap = await generateChannelSnapshot(paths, "alpha");
+ assert.deepEqual(snap.buckets.chatOnly, ["cccc0000003"]);
+ assert.deepEqual(snap.buckets.chatOnlyPending, []);
+ assert.ok(!snap.undownloadedIds.includes("cccc0000003"));
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
test("before the chat lands it is chatOnlyPending — the download lane's bucket", async () => {
const { dir, paths } = await filteredChannel({
filter: { include: "keep", rejectedLivestreams: "chat-only" },
diff --git a/common/controller/channelSnapshot.ts b/common/controller/channelSnapshot.ts
@@ -25,6 +25,7 @@ import {
import { resolveCookiePolicy } from "../lib/cookiePolicy";
import { assertChannelTextReadable } from "../lib/channelMedia";
import { isTierable } from "../lib/mediaTier";
+import { listingHas } from "../lib/storedText";
import { isDriveNotAnswering, onDrive } from "../lib/storageHealth";
import { CLIPS_DIR_NAME } from "../lib/clipWindow";
import { getSettings } from "../lib/settings";
@@ -1547,7 +1548,8 @@ export async function generateChannelSnapshot(
// under this line classifies a video by what is MISSING, and nothing is
// missing from a chat-only video.
if (settledIds.has(id) && !videoHasAnyArtifact(files)) {
- if (files.entries.includes(LIVE_CHAT_FILENAME)) {
+ // Either form (lib/storedText.ts): a compressed chat is still on disk.
+ if (listingHas(files.entries, LIVE_CHAT_FILENAME)) {
chatOnly.push(id);
} else {
settledOnDisk.push(id);
@@ -1817,7 +1819,7 @@ export async function generateChannelSnapshot(
// store's `noLiveChat` flag is the other way out of this list: a stream
// we asked and got nothing from is not in `chatOnlyIds` at all, so it
// settles as an ordinary rejection instead of sitting here forever.
- if (!f?.entries.includes(LIVE_CHAT_FILENAME)) chatOnlyPending.push(dirId);
+ if (!f || !listingHas(f.entries, LIVE_CHAT_FILENAME)) chatOnlyPending.push(dirId);
continue;
}
// A settled video has no artifact and never will while the filter stands.
diff --git a/common/controller/compressText.test.ts b/common/controller/compressText.test.ts
@@ -0,0 +1,274 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { lstat, mkdir, mkdtemp, readdir, readFile, readlink, rm, symlink, utimes, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/compressText.test.ts
+//
+// THE MIGRATION (lane text-compress, slice 2): `compress-text` over a temp
+// corpus — a dry run that touches nothing, a real run, its limit, its check,
+// the render-mode wait and the slower pace while a recording runs.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "compress-text-"));
+process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts");
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await mkdir(process.env.TRANSCRIPTS_DIR, { recursive: true });
+await writeFile(process.env.SETTINGS_FILE, "{}");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { compressText, byteThrottle } = await import("./compressText");
+const { readStoredText } = await import("../lib/storedText-server");
+
+const paths = getPaths();
+const CHAT = "transcript.live_chat.json";
+const body = (seed: string, lines: number) =>
+ Array.from({ length: lines }, (_, i) =>
+ JSON.stringify({ replayChatItemAction: { actions: [{ text: `${seed} ${i} ${createHash("md5").update(seed + i).digest("hex")}` }], videoOffsetTimeMsec: String(i * 1000) } }),
+ ).join("\n") + "\n";
+
+async function channel(slug: string, videos: Record<string, string>, opts: { tiered?: boolean } = {}): Promise<void> {
+ const channelDir = path.join(paths.channelsDir, slug);
+ await mkdir(path.join(channelDir, "data"), { recursive: true });
+ await writeFile(path.join(channelDir, "config.json"), JSON.stringify({ handling: "youtube", url: `https://www.youtube.com/@${slug}` }));
+ if (opts.tiered) await mkdir(path.join(channelDir, "media"), { recursive: true });
+ for (const [id, chat] of Object.entries(videos)) {
+ const dir = path.join(channelDir, "data", id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id }));
+ if (opts.tiered) {
+ await mkdir(path.join(channelDir, "media", id), { recursive: true });
+ await writeFile(path.join(channelDir, "media", id, CHAT), chat);
+ await symlink(path.join("..", "..", "media", id, CHAT), path.join(dir, CHAT));
+ } else {
+ await writeFile(path.join(dir, CHAT), chat);
+ }
+ // Old enough for the quiet period.
+ await utimes(path.join(dir, CHAT), 1_700_000_000, 1_700_000_000.5);
+ }
+}
+
+async function tree(dir: string): Promise<string[]> {
+ const out: string[] = [];
+ async function walk(d: string): Promise<void> {
+ for (const e of (await readdir(d).catch(() => [] as string[])).sort()) {
+ const p = path.join(d, e);
+ const l = await lstat(p);
+ if (l.isSymbolicLink()) out.push(`${p} -> ${await readlink(p)} ${l.mtimeMs}`);
+ else if (l.isDirectory()) {
+ out.push(`${p}/ ${l.mtimeMs}`);
+ await walk(p);
+ } else out.push(`${p} ${l.size} ${l.mtimeMs} ${createHash("sha256").update(await readFile(p)).digest("hex")}`);
+ }
+ }
+ await walk(dir);
+ return out;
+}
+
+const A = { a1: body("a1", 4000), a2: body("a2", 2000) };
+const B = { b1: body("b1", 3000) };
+await channel("alpha", A);
+await channel("beta", B, { tiered: true });
+
+test("a dry run reports bytes before and the estimate after, per channel — and touches NOTHING", async () => {
+ const before = await tree(ROOT);
+ const lines: string[] = [];
+ const r = await compressText({ paths, dryRun: true, onLog: (l) => lines.push(l) });
+ assert.deepEqual(await tree(ROOT), before, "not one entry changed, not one mtime");
+ const alpha = r.channels.find((c) => c.slug === "alpha")!;
+ assert.equal(alpha.plainFiles, 2);
+ assert.equal(alpha.plainBytes, A.a1.length + A.a2.length);
+ assert.equal(alpha.estimateAfterBytes, Math.round(alpha.plainBytes * 0.05));
+ assert.ok(typeof alpha.free?.corpus === "number");
+ const beta = r.channels.find((c) => c.slug === "beta")!;
+ assert.equal(beta.plainFiles, 1, "a tier link's bytes are counted through the link");
+ assert.equal(beta.plainBytes, B.b1.length);
+ assert.match(lines.join(""), /Nothing was written/);
+});
+
+test("a real run with a limit compresses that many, smallest first; a re-run continues; the check passes", async () => {
+ const waits: number[] = [];
+ const first = await compressText({
+ paths,
+ quietMs: 0,
+ slugs: ["alpha"],
+ limit: 1,
+ onLog: () => {},
+ waitForRender: async () => (waits.push(1), 0),
+ });
+ assert.equal(first.stopped, "limit");
+ const alpha = first.channels[0];
+ assert.equal(alpha.compressed, 1);
+ // Smallest first: a2.
+ const a2 = path.join(paths.channelsDir, "alpha", "data", "a2");
+ assert.deepEqual((await readdir(a2)).sort(), ["metadata.info.json", `${CHAT}.zst`]);
+ assert.equal(await readStoredText(a2, CHAT, "utf8"), A.a2);
+ assert.equal(waits.length, 1, "render mode was asked before the file");
+
+ const rest = await compressText({ paths, quietMs: 0, slugs: ["alpha", "beta"], onLog: () => {} });
+ assert.equal(rest.stopped, undefined);
+ const byslug = Object.fromEntries(rest.channels.map((c) => [c.slug, c]));
+ assert.equal(byslug.alpha.compressed, 1);
+ assert.equal(byslug.alpha.already, 1);
+ assert.equal(byslug.beta.compressed, 1);
+ for (const [slug, vids] of [["alpha", A], ["beta", B]] as const) {
+ for (const [id, chat] of Object.entries(vids)) {
+ assert.equal(await readStoredText(path.join(paths.channelsDir, slug, "data", id), CHAT, "utf8"), chat, `${slug}/${id}`);
+ }
+ }
+ const again = await compressText({ paths, quietMs: 0, slugs: ["alpha", "beta"], onLog: () => {} });
+ assert.equal(again.channels.reduce((a, c) => a + (c.compressed ?? 0), 0), 0);
+
+ const check = await compressText({ paths, verify: true, slugs: ["alpha", "beta"], onLog: () => {} });
+ assert.deepEqual(
+ check.channels.map((c) => [c.slug, c.verified, c.problems?.length]),
+ [["alpha", 2, 0], ["beta", 1, 0]],
+ );
+});
+
+test("render mode ending the wait by a cancel stops the run before any file", async () => {
+ await channel("gamma", { g1: body("g1", 100) });
+ const r = await compressText({ paths, slugs: ["gamma"], onLog: () => {}, waitForRender: async () => null });
+ assert.equal(r.stopped, "cancelled");
+ assert.deepEqual((await readdir(path.join(paths.channelsDir, "gamma", "data", "g1"))).sort(), ["metadata.info.json", CHAT]);
+});
+
+test("the pace: a token bucket over bytes, at whatever rate is asked each time (slower while recording)", async () => {
+ let t = 0;
+ const slept: number[] = [];
+ let recording = false;
+ const throttle = byteThrottle(
+ () => (recording ? 8 : 40) * 1024 * 1024,
+ async (ms) => {
+ slept.push(Math.round(ms));
+ t += ms;
+ },
+ () => t,
+ );
+ await throttle(40 * 1024 * 1024); // the first second's worth: no wait
+ await throttle(40 * 1024 * 1024); // the next waits a second
+ recording = true;
+ await throttle(8 * 1024 * 1024); // queued behind the second; 8 MB at 8 MB/s is one more second
+ await throttle(8 * 1024 * 1024);
+ assert.deepEqual(slept, [1000, 1000, 1000]);
+});
+
+// REVIEW-1 F4(a): THE JOB VISITS EVERY DIR A STOPPED RUN LEFT, not only the
+// ones where the plain file opens. A kill after the original was set aside
+// leaves the name absent (the stored form only) beside the set-aside; a kill
+// inside the original's removal leaves a dangling tier link. Through the job
+// (compressText), each is finished: the stored form only, no leftover.
+const { CompressKill } = await import("../lib/storedText-write-server");
+const killAt = (point: string) => (p: string) => {
+ if (p === point) throw new CompressKill(p as never);
+};
+const leftovers = async (slug: string, id: string) =>
+ (await readdir(path.join(paths.channelsDir, slug, "data", id))).filter((e) => e.startsWith("."));
+
+test("the job finishes a run killed after the set-aside, and one killed inside the original's removal", async () => {
+ await channel("delta", { d1: body("d1", 500) });
+ await channel("epsilon", { e1: body("e1", 500) }, { tiered: true });
+ // A run killed at "retired" (a dead pid).
+ await assert.rejects(
+ compressText({ paths, slugs: ["delta"], quietMs: 0, onLog: () => {}, compressOpts: { pid: 999_999_997, crashAt: killAt("retired") } }),
+ CompressKill,
+ );
+ const d1 = path.join(paths.channelsDir, "delta", "data", "d1");
+ assert.ok(!(await readdir(d1)).includes(CHAT), "the name is absent: the stored form only");
+ assert.equal((await leftovers("delta", "d1")).length, 1, "the set-aside original");
+ // The dry run sees the dir as work (the action starts a job for it).
+ const plan = await compressText({ paths, slugs: ["delta"], dryRun: true, onLog: () => {} });
+ assert.equal(plan.channels[0].pending, 1);
+ assert.equal(plan.channels[0].plainFiles, 0);
+ const r = await compressText({ paths, slugs: ["delta"], quietMs: 0, onLog: () => {} });
+ assert.deepEqual(await leftovers("delta", "d1"), [], "finished by the job");
+ assert.deepEqual((await readdir(d1)).sort(), ["metadata.info.json", `${CHAT}.zst`]);
+ assert.equal(await readStoredText(d1, CHAT, "utf8"), body("d1", 500));
+ assert.ok((r.channels[0].compressed ?? 0) + (r.channels[0].already ?? 0) >= 1);
+
+ // Tiered: compressed, then the plain link put back dangling (what a kill
+ // between the bytes' removal and the link's leaves).
+ assert.equal((await compressText({ paths, slugs: ["epsilon"], quietMs: 0, onLog: () => {} })).channels[0].compressed, 1);
+ const e1 = path.join(paths.channelsDir, "epsilon", "data", "e1");
+ await symlink(path.join("..", "..", "media", "e1", CHAT), path.join(e1, CHAT));
+ const before = await compressText({ paths, slugs: ["epsilon"], dryRun: true, onLog: () => {} });
+ assert.equal(before.channels[0].pending, 1, "a dangling plain link is work");
+ await compressText({ paths, slugs: ["epsilon"], quietMs: 0, onLog: () => {} });
+ assert.deepEqual((await readdir(e1)).sort(), ["metadata.info.json", `${CHAT}.zst`], "the dangling link is gone");
+ assert.equal(await readStoredText(e1, CHAT, "utf8"), body("e1", 500));
+});
+
+// REVIEW-1 F4(b), through the job: this process's pid, an earlier start.
+test("the job treats this pid's leftovers from an earlier process start as dead: a set-aside and a temp", async () => {
+ await channel("zeta", { z1: body("z1", 400), z2: body("z2", 400) });
+ await assert.rejects(
+ compressText({ paths, slugs: ["zeta"], quietMs: 0, onLog: () => {}, compressOpts: { pid: process.pid, token: "earlier0", crashAt: killAt("retired") } }),
+ CompressKill,
+ );
+ // z2: a partial temp of this pid from an earlier start, beside its plain file.
+ const z2 = path.join(paths.channelsDir, "zeta", "data", "z2");
+ await writeFile(path.join(z2, `.${CHAT}.zst.compressing-${process.pid}-earlier0`), "partial");
+ await writeFile(path.join(z2, `.${CHAT}.zst.compressing-${process.pid}`), "partial, a name from before the token");
+ await compressText({ paths, slugs: ["zeta"], quietMs: 0, onLog: () => {} });
+ for (const id of ["z1", "z2"]) {
+ assert.deepEqual(await leftovers("zeta", id), [], id);
+ assert.equal(await readStoredText(path.join(paths.channelsDir, "zeta", "data", id), CHAT, "utf8"), body(id, 400), id);
+ }
+});
+
+// REVIEW-1 F3, through the job: the restore.
+test("restore through the job: a dry run touches nothing; a restore with a limit, killed, re-run — the plain files with their times", async () => {
+ const before: Record<string, number> = {};
+ await channel("eta", { h1: body("h1", 300), h2: body("h2", 600) });
+ await channel("theta", { t1: body("t1", 300) }, { tiered: true });
+ for (const [slug, id] of [["eta", "h1"], ["eta", "h2"], ["theta", "t1"]]) {
+ before[`${slug}/${id}`] = (await lstat(path.join(paths.channelsDir, slug, "data", id, CHAT))).mtimeMs;
+ }
+ await compressText({ paths, slugs: ["eta", "theta"], quietMs: 0, onLog: () => {} });
+
+ const tr = await tree(path.join(paths.channelsDir, "eta"));
+ const plan = await compressText({ paths, slugs: ["eta"], restore: true, dryRun: true, onLog: () => {} });
+ assert.deepEqual(await tree(path.join(paths.channelsDir, "eta")), tr, "the restore's dry run touches nothing");
+ assert.equal(plan.channels[0].storedFiles, 2);
+ assert.equal(plan.channels[0].estimateAfterBytes, body("h1", 300).length + body("h2", 600).length, "exact, from the headers");
+ assert.equal(plan.channels[0].pending, 2);
+
+ const one = await compressText({ paths, slugs: ["eta"], restore: true, limit: 1, onLog: () => {} });
+ assert.equal(one.stopped, "limit");
+ assert.equal(one.channels[0].restored, 1);
+ // A run killed mid-restore (after the plain copy is placed), then re-run.
+ await assert.rejects(
+ compressText({ paths, slugs: ["eta", "theta"], restore: true, onLog: () => {}, compressOpts: { pid: 999_999_996, crashAt: killAt("restore-placed") } }),
+ CompressKill,
+ );
+ await compressText({ paths, slugs: ["eta", "theta"], restore: true, onLog: () => {} });
+ for (const [slug, id, lines] of [["eta", "h1", 300], ["eta", "h2", 600], ["theta", "t1", 300]] as const) {
+ const d = path.join(paths.channelsDir, slug, "data", id);
+ assert.deepEqual((await readdir(d)).sort(), ["metadata.info.json", CHAT], `${slug}/${id}`);
+ assert.equal(await readFile(path.join(d, CHAT), "utf8"), body(id, lines), `${slug}/${id}`);
+ assert.equal((await lstat(path.join(d, CHAT))).mtimeMs, before[`${slug}/${id}`], `${slug}/${id}: the index key`);
+ }
+ assert.deepEqual(await readdir(path.join(paths.channelsDir, "theta", "media", "t1")), [CHAT]);
+});
+
+// REVIEW-2 R1: an earlier capture a re-fetch kept is listed by the dry run as
+// "earlier captures kept", with its bytes — and no run touches it.
+test("the dry run lists earlier captures kept; neither a compress nor a restore touches one", async () => {
+ await channel("iota", { i1: body("i1", 200) });
+ const d = path.join(paths.channelsDir, "iota", "data", "i1");
+ const keptName = "chat-capture-kept.20261121T040000Z.json.zst";
+ const { encodeStoredBytes } = await import("../lib/storedText-server");
+ const keptBytes = await encodeStoredBytes(Buffer.from(body("earlier", 300)));
+ await writeFile(path.join(d, keptName), keptBytes);
+ const lines: string[] = [];
+ const plan = await compressText({ paths, slugs: ["iota"], dryRun: true, onLog: (l) => lines.push(l) });
+ assert.equal(plan.channels[0].keptCaptures, 1);
+ assert.equal(plan.channels[0].keptCaptureBytes, keptBytes.length);
+ assert.match(lines.join(""), /earlier captures kept: 1 \(/);
+ await compressText({ paths, slugs: ["iota"], quietMs: 0, onLog: () => {} });
+ await compressText({ paths, slugs: ["iota"], restore: true, onLog: () => {} });
+ assert.deepEqual(await readFile(path.join(d, keptName)), keptBytes, "untouched");
+});
diff --git a/common/controller/compressText.ts b/common/controller/compressText.ts
@@ -0,0 +1,506 @@
+// COMPRESS TEXT — the migration that puts the existing raw live-chat replays
+// into their stored form (lib/storedText.ts): `transcript.live_chat.json` →
+// `transcript.live_chat.json.zst`, one file at a time, through the compressor
+// in lib/storedText-write-server.ts (write beside, fsync, read back and hash,
+// then the original removed through removeMediaFile). Lane text-compress,
+// slice 2; `pnpm ops compress-text` posts it.
+//
+// SAFE BY CONSTRUCTION, RESUMABLE BY RE-WALKING. Every file is "already",
+// "compressed", skipped with a reason, or repaired by the compressor's crash
+// rules; a re-run continues. `limit` counts files compressed this run.
+//
+// PACED, NEVER COMPETING: before each file it waits while render mode holds
+// the machine; the reads go through a token bucket (40 MB/s, 8 MB/s while a
+// live recording runs — the caller says which); a file written within the
+// quiet period (10 min), one with a `.part` beside it, one whose video is
+// recording or has a job running, one on a drive that does not answer, is
+// left alone and counted.
+//
+// `dryRun` WRITES NOTHING AND READS NO CONTENT: per channel, the plain files
+// and their bytes, the stored files and their logical bytes (from the frame
+// headers — 18 bytes each), the estimate after (labelled an estimate, at the
+// ratio measured on a sample) and the free space of the disks they are on.
+// `verify` decodes every stored file in full and writes nothing.
+//
+// THE WALK VISITS EVERY DIR A RUN MAY HAVE TO FINISH: one holding the plain
+// form (a dangling tier link too — an interrupted removal), or the stored form
+// (the restore), or a leftover of a stopped run (a temp, a set-aside original)
+// — so "the next run finishes it" is true through the job, not only of the
+// compressor.
+//
+// `restore: true` IS THE ROLLBACK: every stored chat put back into its plain
+// form (lib/storedText-write-server.ts restoreStoredText — decoded beside,
+// fsynced, read back against a fresh decode, the same times, and only then the
+// stored file removed). With `dryRun` it answers the stored files, the bytes
+// they will take, and the free space. Run it BEFORE reverting or running an
+// older checkout (OPERATING.md).
+
+import path from "node:path";
+import { open, readdir, stat, statfs } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import { LIVE_CHAT_FILENAME } from "../lib/videoStatus";
+import { storedFormsIn, storedNameOf } from "../lib/storedText";
+import { isKeptChatCapture } from "../lib/mediaTier";
+import { frameContentSize } from "../lib/storedText-server";
+import {
+ compressStoredText,
+ hasStoredTextLeftover,
+ restoreStoredText,
+ verifyStoredText,
+ type CompressOutcome,
+ type CompressSkipReason,
+ type RestoreOutcome,
+} from "../lib/storedText-write-server";
+import { inspectChannelMedia } from "../lib/channelMedia";
+import { onDrive } from "../lib/storageHealth";
+import { readChannelConfig, listChannelSlugs } from "./channels";
+
+export const COMPRESS_TEXT_KINDS = ["live-chat"] as const;
+export type CompressTextKind = (typeof COMPRESS_TEXT_KINDS)[number];
+
+// Measured on a sample (lane text-compress design §1): a raw chat at level 9
+// is ~5 % of its size. An estimate, and every line that uses it says so.
+export const CHAT_RATIO_ESTIMATE = 0.05;
+export const COMPRESS_QUIET_MS = 10 * 60_000;
+export const COMPRESS_RATE_BYTES = 40 * 1024 * 1024;
+export const COMPRESS_RATE_RECORDING_BYTES = 8 * 1024 * 1024;
+
+export type CompressTextOptions = {
+ paths: Paths;
+ // Default: every channel.
+ slugs?: string[];
+ dryRun?: boolean;
+ verify?: boolean;
+ // The rollback: stored → plain (with `dryRun`: the plan).
+ restore?: boolean;
+ limit?: number;
+ quietMs?: number;
+ onLog: (line: string) => void;
+ signal?: AbortSignal;
+ drainSignal?: AbortSignal;
+ // A job is running for this video (the editor's registry).
+ isBusy?: (slug: string, id: string) => boolean;
+ // The read rate now, bytes/s (the editor: slower while a recording runs).
+ rate?: () => number;
+ // Waits while render mode holds the machine; null when the wait was ended
+ // by the signal (lib/renderHold.ts waitWhileRenderHeld, injected).
+ waitForRender?: () => Promise<number | null>;
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
+ now?: () => number;
+ // Tests: the compressor's options passed through (a kill point, a pid).
+ compressOpts?: Parameters<typeof compressStoredText>[2];
+};
+
+export type ChannelLine = {
+ slug: string;
+ // Why the channel was not walked, when it was not.
+ refused?: string;
+ plainFiles: number;
+ plainBytes: number;
+ storedFiles: number;
+ storedLogicalBytes: number;
+ storedBytes: number;
+ // The dirs a run in this mode visits (a compress: the plain form or a
+ // stopped run's leftover; a restore: the stored form or a leftover) — a
+ // dir with only a leftover still has work.
+ pending?: number;
+ // Earlier chat captures kept by a re-fetch (`chat-capture-kept.*.json.zst`,
+ // lib/mediaTier.ts): never removed automatically — counted so a person sees
+ // them.
+ keptCaptures?: number;
+ keptCaptureBytes?: number;
+ // Dry run only: what the plain files would take at the estimated ratio
+ // (a restore's dry run: the stored files' logical bytes — exact).
+ estimateAfterBytes?: number;
+ // Dry run only: free space now on the disk(s) holding this channel's chats.
+ free?: { corpus?: number; media?: number };
+ // A real run.
+ compressed?: number;
+ bytesBefore?: number;
+ bytesAfter?: number;
+ already?: number;
+ changed?: number;
+ skipped?: Partial<Record<CompressSkipReason, number>>;
+ failed?: { id: string; error: string }[];
+ // A restore.
+ restored?: number;
+ // Verify.
+ verified?: number;
+ problems?: { id: string; status: string; detail?: string }[];
+};
+
+export type CompressTextResult = {
+ dryRun: boolean;
+ verify: boolean;
+ restore: boolean;
+ channels: ChannelLine[];
+ stopped?: "drained" | "cancelled" | "limit";
+ lines: string[];
+};
+
+// A dir with work for a run: `size` is the plain file's (0 when it does not
+// open — a dangling link, or only a leftover).
+type Candidate = { id: string; videoDir: string; size: number };
+
+function fmtBytes(n: number): string {
+ if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(2)} GB`;
+ if (n >= 1024 ** 2) return `${(n / 1024 ** 2).toFixed(1)} MB`;
+ if (n >= 1024) return `${(n / 1024).toFixed(1)} KB`;
+ return `${n} B`;
+}
+
+// A token bucket over bytes: each call waits until its bytes fit the rate.
+export function byteThrottle(
+ rate: () => number,
+ sleep: (ms: number, signal?: AbortSignal) => Promise<void>,
+ now: () => number = Date.now,
+ signal?: AbortSignal,
+): (bytes: number) => Promise<void> {
+ let nextFree = 0;
+ return async (bytes: number) => {
+ const r = rate();
+ if (!(r > 0) || !Number.isFinite(r)) return;
+ const t = now();
+ const start = Math.max(t, nextFree);
+ nextFree = start + (bytes / r) * 1000;
+ const wait = start - t;
+ if (wait > 1) await sleep(wait, signal);
+ };
+}
+
+const defaultSleep = (ms: number, signal?: AbortSignal) =>
+ new Promise<void>((resolve) => {
+ const t = setTimeout(resolve, ms);
+ signal?.addEventListener("abort", () => {
+ clearTimeout(t);
+ resolve();
+ }, { once: true });
+ });
+
+async function storedLogicalSize(file: string): Promise<number | null> {
+ try {
+ const fh = await open(file, "r");
+ try {
+ const head = Buffer.alloc(18);
+ const { bytesRead } = await fh.read(head, 0, 18, 0);
+ return frameContentSize(head.subarray(0, bytesRead));
+ } finally {
+ await fh.close();
+ }
+ } catch {
+ return null;
+ }
+}
+
+// One channel's chats, by what is on disk. Sizes are `stat`s (through a tier
+// link, under the drive's watchdog); no content is read.
+async function surveyChannel(
+ channelDir: string,
+ drive: string | undefined,
+): Promise<{
+ plain: Candidate[];
+ stored: { id: string; videoDir: string; bytes: number; logical: number }[];
+ // Every dir a compress run visits: the plain form, present at all (a
+ // dangling link included), or a stopped run's leftover.
+ work: Candidate[];
+ // Every dir a restore visits: the stored form, or a leftover.
+ restoreWork: Candidate[];
+ kept: { files: number; bytes: number };
+}> {
+ const dataDir = path.join(channelDir, "data");
+ const ids = (await readdir(dataDir).catch(() => [] as string[])).sort();
+ const plain: Candidate[] = [];
+ const stored: { id: string; videoDir: string; bytes: number; logical: number }[] = [];
+ const work: Candidate[] = [];
+ const restoreWork: Candidate[] = [];
+ const kept = { files: 0, bytes: 0 };
+ const sizeOf = (p: string) =>
+ (drive ? onDrive(drive, () => stat(p)) : stat(p)).then((s) => s.size, () => null);
+ for (const id of ids) {
+ const videoDir = path.join(dataDir, id);
+ const entries = await readdir(videoDir).catch(() => null);
+ if (!entries) continue;
+ const forms = storedFormsIn(entries, LIVE_CHAT_FILENAME);
+ const leftover = hasStoredTextLeftover(entries, LIVE_CHAT_FILENAME);
+ for (const k of entries.filter(isKeptChatCapture)) {
+ kept.files += 1;
+ kept.bytes += (await sizeOf(path.join(videoDir, k))) ?? 0;
+ }
+ let size: number | null = null;
+ if (forms === "plain" || forms === "both") {
+ size = await sizeOf(path.join(videoDir, LIVE_CHAT_FILENAME));
+ if (size !== null) plain.push({ id, videoDir, size });
+ }
+ if (forms === "plain" || forms === "both" || leftover) work.push({ id, videoDir, size: size ?? 0 });
+ if (forms === "zst" || forms === "both" || leftover) restoreWork.push({ id, videoDir, size: 0 });
+ if (forms === "zst" || forms === "both") {
+ const zp = path.join(videoDir, storedNameOf(LIVE_CHAT_FILENAME));
+ const bytes = await sizeOf(zp);
+ const logical = bytes === null ? null : await (drive
+ ? onDrive(drive, () => storedLogicalSize(zp))
+ : storedLogicalSize(zp)).catch(() => null);
+ if (bytes !== null) stored.push({ id, videoDir, bytes, logical: logical ?? 0 });
+ }
+ }
+ // Smallest first: the early files are the cheap ones (a dir to repair, 0).
+ const bySize = (a: Candidate, b: Candidate) => a.size - b.size || (a.id < b.id ? -1 : 1);
+ plain.sort(bySize);
+ work.sort(bySize);
+ return { plain, stored, work, restoreWork, kept };
+}
+
+export async function compressText(opts: CompressTextOptions): Promise<CompressTextResult> {
+ const dryRun = opts.dryRun === true;
+ const restore = opts.restore === true;
+ const verify = !dryRun && !restore && opts.verify === true;
+ const lines: string[] = [];
+ const say = (line: string) => {
+ lines.push(line);
+ opts.onLog(`${line}\n`);
+ };
+ const sleep = opts.sleep ?? defaultSleep;
+ const now = opts.now ?? Date.now;
+ const throttle = byteThrottle(opts.rate ?? (() => COMPRESS_RATE_BYTES), sleep, now, opts.signal);
+ const slugs = opts.slugs ?? (await listChannelSlugs(opts.paths)).sort();
+ const channels: ChannelLine[] = [];
+ // Files compressed (or restored) this run: what `limit` counts.
+ let doneThisRun = 0;
+ let stopped: CompressTextResult["stopped"];
+
+ for (const slug of slugs) {
+ if (stopped) break;
+ const channelDir = path.join(opts.paths.channelsDir, slug);
+ const line: ChannelLine = {
+ slug,
+ plainFiles: 0,
+ plainBytes: 0,
+ storedFiles: 0,
+ storedLogicalBytes: 0,
+ storedBytes: 0,
+ };
+ channels.push(line);
+ const config = await readChannelConfig(opts.paths, slug).catch(() => null);
+ if (!config) {
+ line.refused = "no config.json";
+ continue;
+ }
+ const media = await inspectChannelMedia(opts.paths, slug, config, { fresh: true });
+ if (media.status !== "ok" && media.status !== "in-place") {
+ line.refused = media.detail ?? media.status;
+ say(`${slug}: left alone — ${line.refused}`);
+ continue;
+ }
+ const drive = media.status === "ok" ? media.target : undefined;
+ const { plain, stored, work, restoreWork, kept } = await surveyChannel(channelDir, drive);
+ line.keptCaptures = kept.files;
+ line.keptCaptureBytes = kept.bytes;
+ const keptText = kept.files ? `; earlier captures kept: ${kept.files} (${fmtBytes(kept.bytes)})` : "";
+ line.plainFiles = plain.length;
+ line.plainBytes = plain.reduce((a, c) => a + c.size, 0);
+ line.storedFiles = stored.length;
+ line.storedBytes = stored.reduce((a, c) => a + c.bytes, 0);
+ line.storedLogicalBytes = stored.reduce((a, c) => a + c.logical, 0);
+ line.pending = (restore ? restoreWork : work).length;
+
+ if (dryRun && restore) {
+ // Exact, from the frame headers: what the plain files will take again.
+ line.estimateAfterBytes = line.storedLogicalBytes;
+ const freeOf = (p: string) =>
+ statfs(p).then((f) => f.bavail * f.bsize, () => undefined);
+ line.free = {
+ corpus: await freeOf(path.join(channelDir, "data")),
+ ...(drive ? { media: await onDrive(drive, () => freeOf(drive)).catch(() => undefined) } : {}),
+ };
+ if (line.storedFiles + kept.files > 0) {
+ say(
+ `${slug}: ${line.storedFiles} stored chat(s), ${fmtBytes(line.storedBytes)} → ${fmtBytes(line.storedLogicalBytes)} ` +
+ `as plain files; free on ${drive ? "the media drive" : "the corpus disk"} ` +
+ `${fmtBytes((drive ? line.free.media : line.free.corpus) ?? 0)}${keptText}`,
+ );
+ }
+ continue;
+ }
+
+ if (restore) {
+ line.restored = 0;
+ line.bytesBefore = 0;
+ line.bytesAfter = 0;
+ line.already = 0;
+ line.changed = 0;
+ line.skipped = {};
+ line.failed = [];
+ for (const c of restoreWork) {
+ if (opts.signal?.aborted) { stopped = "cancelled"; break; }
+ if (opts.drainSignal?.aborted) { stopped = "drained"; break; }
+ if (opts.limit !== undefined && doneThisRun >= opts.limit) { stopped = "limit"; break; }
+ if (opts.waitForRender) {
+ const waited = await opts.waitForRender();
+ if (waited === null) { stopped = "cancelled"; break; }
+ }
+ let out: RestoreOutcome;
+ try {
+ out = await restoreStoredText(c.videoDir, LIVE_CHAT_FILENAME, {
+ isBusy: opts.isBusy ? () => opts.isBusy!(slug, c.id) : undefined,
+ throttle,
+ ...(opts.signal ? { signal: opts.signal } : {}),
+ onLog: (l) => opts.onLog(`${l}\n`),
+ ...opts.compressOpts,
+ });
+ } catch (err) {
+ if ((err as Error).name === "CompressKill") throw err;
+ line.failed.push({ id: c.id, error: (err as Error).message });
+ say(`${slug}/${c.id}: failed — ${(err as Error).message} (the stored file is untouched)`);
+ continue;
+ }
+ if (out.status === "restored") {
+ doneThisRun += 1;
+ line.restored += 1;
+ line.bytesBefore += out.before;
+ line.bytesAfter += out.after;
+ opts.onLog(`${slug}/${c.id}: ${fmtBytes(out.before)} → ${fmtBytes(out.after)} (restored)${out.tiered ? " (media tier)" : ""}\n`);
+ } else if (out.status === "already") {
+ line.already += 1;
+ } else if (out.status === "changed") {
+ line.changed += 1;
+ } else if (out.status === "skipped") {
+ line.skipped[out.reason] = (line.skipped[out.reason] ?? 0) + 1;
+ if (out.reason === "both-differ" || out.reason === "stored-corrupt" || out.reason === "retired-kept") {
+ say(`${slug}/${c.id}: refused — ${out.reason}${out.detail ? ` (${out.detail})` : ""}; both files are kept`);
+ }
+ }
+ }
+ const skippedText = Object.entries(line.skipped).map(([r, n]) => `${n} ${r}`).join(", ");
+ if (restoreWork.length > 0) {
+ say(
+ `${slug}: restored ${line.restored} (${fmtBytes(line.bytesBefore)} → ${fmtBytes(line.bytesAfter)}), ` +
+ `already plain ${line.already}, changed ${line.changed}, skipped ${skippedText || "0"}, failed ${line.failed.length}`,
+ );
+ }
+ continue;
+ }
+
+ if (dryRun) {
+ line.estimateAfterBytes = Math.round(line.plainBytes * CHAT_RATIO_ESTIMATE);
+ const freeOf = (p: string) =>
+ statfs(p).then((f) => f.bavail * f.bsize, () => undefined);
+ line.free = {
+ corpus: await freeOf(path.join(channelDir, "data")),
+ ...(drive ? { media: await onDrive(drive, () => freeOf(drive)).catch(() => undefined) } : {}),
+ };
+ if (line.plainFiles + line.storedFiles + kept.files > 0) {
+ say(
+ `${slug}: ${line.plainFiles} raw chat(s), ${fmtBytes(line.plainBytes)} → ~${fmtBytes(line.estimateAfterBytes)} ` +
+ `(estimate, ${Math.round(CHAT_RATIO_ESTIMATE * 100)} %); already stored ${line.storedFiles} ` +
+ `(${fmtBytes(line.storedBytes)} holding ${fmtBytes(line.storedLogicalBytes)}); ` +
+ `free on ${drive ? "the media drive" : "the corpus disk"} ` +
+ `${fmtBytes((drive ? line.free.media : line.free.corpus) ?? 0)}${keptText}`,
+ );
+ }
+ continue;
+ }
+
+ if (verify) {
+ line.verified = 0;
+ line.problems = [];
+ for (const s of stored) {
+ if (opts.signal?.aborted) { stopped = "cancelled"; break; }
+ if (opts.drainSignal?.aborted) { stopped = "drained"; break; }
+ const v = await verifyStoredText(s.videoDir, LIVE_CHAT_FILENAME, { throttle });
+ if (v.status === "ok") line.verified += 1;
+ else {
+ line.problems.push({ id: s.id, status: v.status, ...("detail" in v ? { detail: v.detail } : {}) });
+ say(`${slug}/${s.id}: ${v.status}${"detail" in v ? ` — ${v.detail}` : ""}`);
+ }
+ }
+ say(`${slug}: verified ${line.verified} stored chat(s), ${line.problems.length} problem(s)`);
+ continue;
+ }
+
+ line.compressed = 0;
+ line.bytesBefore = 0;
+ line.bytesAfter = 0;
+ // A stored dir with nothing to finish is "already"; one in `work` says so
+ // itself.
+ const inWork = new Set(work.map((c) => c.id));
+ line.already = stored.filter((z) => !inWork.has(z.id)).length;
+ line.changed = 0;
+ line.skipped = {};
+ line.failed = [];
+ for (const c of work) {
+ if (opts.signal?.aborted) { stopped = "cancelled"; break; }
+ if (opts.drainSignal?.aborted) { stopped = "drained"; break; }
+ if (opts.limit !== undefined && doneThisRun >= opts.limit) { stopped = "limit"; break; }
+ if (opts.waitForRender) {
+ const waited = await opts.waitForRender();
+ if (waited === null) { stopped = "cancelled"; break; }
+ }
+ let out: CompressOutcome;
+ try {
+ out = await compressStoredText(c.videoDir, LIVE_CHAT_FILENAME, {
+ quietMs: opts.quietMs ?? COMPRESS_QUIET_MS,
+ now,
+ isBusy: opts.isBusy ? () => opts.isBusy!(slug, c.id) : undefined,
+ throttle,
+ ...(opts.signal ? { signal: opts.signal } : {}),
+ onLog: (l) => opts.onLog(`${l}\n`),
+ ...opts.compressOpts,
+ });
+ } catch (err) {
+ if ((err as Error).name === "CompressKill") throw err;
+ line.failed.push({ id: c.id, error: (err as Error).message });
+ say(`${slug}/${c.id}: failed — ${(err as Error).message} (the original is untouched)`);
+ continue;
+ }
+ if (out.status === "compressed") {
+ doneThisRun += 1;
+ line.compressed += 1;
+ line.bytesBefore += out.before;
+ line.bytesAfter += out.after;
+ opts.onLog(`${slug}/${c.id}: ${fmtBytes(out.before)} → ${fmtBytes(out.after)}${out.tiered ? " (media tier)" : ""}\n`);
+ } else if (out.status === "already") {
+ line.already += 1;
+ } else if (out.status === "changed") {
+ line.changed += 1;
+ } else if (out.status === "skipped") {
+ line.skipped[out.reason] = (line.skipped[out.reason] ?? 0) + 1;
+ if (out.reason === "both-differ" || out.reason === "stored-corrupt" || out.reason === "retired-kept") {
+ say(`${slug}/${c.id}: refused — ${out.reason}${out.detail ? ` (${out.detail})` : ""}; both files are kept`);
+ }
+ }
+ }
+ const skippedText = Object.entries(line.skipped)
+ .map(([r, n]) => `${n} ${r}`)
+ .join(", ");
+ if (work.length + line.storedFiles > 0) {
+ say(
+ `${slug}: compressed ${line.compressed} (${fmtBytes(line.bytesBefore)} → ${fmtBytes(line.bytesAfter)}), ` +
+ `already ${line.already}, changed ${line.changed}, skipped ${skippedText || "0"}, failed ${line.failed.length}`,
+ );
+ }
+ }
+
+ if (dryRun && restore) {
+ const tot = channels.reduce((a, c) => a + c.storedLogicalBytes, 0);
+ const n = channels.reduce((a, c) => a + c.storedFiles, 0);
+ say(`Dry run (restore): ${n} stored chat(s) → ${fmtBytes(tot)} as plain files. Nothing was written.`);
+ } else if (restore) {
+ const r = channels.reduce((a, l) => a + (l.restored ?? 0), 0);
+ const f = channels.reduce((a, l) => a + (l.bytesAfter ?? 0), 0);
+ say(`Restored ${r} raw chat(s) to their plain form (${fmtBytes(f)})${stopped ? ` — stopped (${stopped}); a re-run continues` : ""}.`);
+ } else if (dryRun) {
+ const tot = channels.reduce((a, c) => a + c.plainBytes, 0);
+ const n = channels.reduce((a, c) => a + c.plainFiles, 0);
+ const kf = channels.reduce((a, c) => a + (c.keptCaptures ?? 0), 0);
+ const kb = channels.reduce((a, c) => a + (c.keptCaptureBytes ?? 0), 0);
+ say(
+ `Dry run: ${n} raw chat(s), ${fmtBytes(tot)} → ~${fmtBytes(Math.round(tot * CHAT_RATIO_ESTIMATE))} (estimate)` +
+ `${kf ? `; earlier captures kept: ${kf} (${fmtBytes(kb)}), never removed automatically` : ""}. Nothing was written.`,
+ );
+ } else if (!verify) {
+ const c = channels.reduce((a, l) => a + (l.compressed ?? 0), 0);
+ const b = channels.reduce((a, l) => a + (l.bytesBefore ?? 0), 0);
+ const f = channels.reduce((a, l) => a + (l.bytesAfter ?? 0), 0);
+ say(`Compressed ${c} raw chat(s): ${fmtBytes(b)} → ${fmtBytes(f)}${stopped ? ` — stopped (${stopped}); a re-run continues` : ""}.`);
+ }
+ return { dryRun, verify, restore, channels, ...(stopped ? { stopped } : {}), lines };
+}
diff --git a/common/controller/fetchLiveChat.test.ts b/common/controller/fetchLiveChat.test.ts
@@ -428,3 +428,120 @@ test("renormalize: held by the media guard while the channel's media is moving",
await rm(marker, { force: true });
}
});
+
+// A DELIBERATE RE-FETCH OVER A STORED CAPTURE (lane text-compress, REVIEW-2
+// R1): fetch-chat `replace`. NOTHING EVER REMOVES A CAPTURE BECAUSE A
+// DIFFERENT ONE ARRIVED — a platform's replay is often shorter than the live
+// capture, and the capture cannot be fetched again. The stored capture is kept
+// as `chat-capture-kept.<stamp>.json.zst` (no reader sees it), both are
+// measured in the log and the result, and only then does the new replay
+// become the chat. An empty replay, no replay, a failed pass or a `.part`: the
+// stored capture stays THE chat. Over a plain chat, `replace` is refused.
+test("replace: a SHORTER replay over a longer stored capture — both survive, the longer one byte-identical", async () => {
+ const { storeFixture } = await import("../testing/storedTextFixture");
+ const { readStoredText, decodeStoredBytes, readdirLogical } = await import("../lib/storedText-server");
+ const { isKeptChatCapture } = await import("../lib/mediaTier");
+ const { readSubTracks } = await import("../lib/videoStatus");
+ const CHAT = "transcript.live_chat.json";
+ const LONG = [chatLine(1, "a", "live 1"), chatLine(2, "b", "live 2"), chatLine(3, "c", "live 3"), chatLine(900, "d", "live 4")].join("\n") + "\n";
+ const SHORT = chatLine(1, "a", "replay 1") + "\n";
+ for (const tiered of [false, true]) {
+ const id = tiered ? "rpt1" : "rp1";
+ const d = await video(id, { webpage_url: `https://www.youtube.com/watch?v=${id}`, was_live: true });
+ if (tiered) {
+ const media = path.join(CORPUS, "channels", SLUG, "media", id);
+ await mkdir(media, { recursive: true });
+ await writeFile(path.join(media, CHAT), LONG);
+ const { symlink } = await import("node:fs/promises");
+ await symlink(path.join("..", "..", "media", id, CHAT), path.join(d, CHAT));
+ } else {
+ await writeFile(path.join(d, CHAT), LONG);
+ }
+ await storeFixture(d, CHAT);
+ const ok = stubRunner({ writes: SHORT });
+ const l = log();
+ 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: ok.run, replace: true, paceSeconds: 0,
+ });
+ assert.equal(r.status, "fetched", JSON.stringify(r));
+ // The new replay is the chat…
+ assert.equal(await readStoredText(d, CHAT, "utf8"), SHORT, `${id}: the chat`);
+ // …and the earlier, longer capture is kept, byte-identical after decode.
+ const kept = (await readdir(d)).filter(isKeptChatCapture);
+ assert.equal(kept.length, 1, `${id}: ${(await readdir(d)).join(", ")}`);
+ assert.equal((await decodeStoredBytes(await readFile(path.join(d, kept[0])))).toString("utf8"), LONG, `${id}: kept whole`);
+ // No reader sees the kept capture as the chat.
+ assert.ok(!(await readdirLogical(d)).some((e) => e.startsWith("transcript.live_chat") && e !== CHAT), id);
+ const tracks = (await readSubTracks(d)).map((t) => JSON.stringify(t));
+ assert.equal(tracks.filter((t) => t.includes("live_chat")).length, 1, `${id}: one chat track (${tracks.join(" ")})`);
+ assert.ok(!tracks.some((t) => t.includes("chat-capture-kept")), `${id}: the kept capture is no track`);
+ // Both captures measured, in the result and the log.
+ assert.deepEqual(r.replace?.earlier, { bytes: LONG.length, messages: 4, firstSec: 1, lastSec: 900, keptAs: kept[0] });
+ assert.deepEqual(r.replace?.fetched, { bytes: SHORT.length, messages: 1, firstSec: 1, lastSec: 1, keptAs: null });
+ assert.match(l.lines.join(""), /Earlier capture \(chat-capture-kept\..*\): 4 message\(s\).*Replay fetched now: 1 message\(s\)/);
+ assert.match(l.lines.join(""), /3 fewer message/);
+ }
+});
+
+test("replace: an EMPTY replay, no replay, a failed pass or a .part — the stored capture stays the chat", async () => {
+ const { storeFixture } = await import("../testing/storedTextFixture");
+ const { readStoredText, decodeStoredBytes } = await import("../lib/storedText-server");
+ const { isKeptChatCapture } = await import("../lib/mediaTier");
+ const CHAT = "transcript.live_chat.json";
+ const OLD = [chatLine(1, "a", "old whole capture"), chatLine(2, "b", "more")].join("\n") + "\n";
+ const forms = async (d: string) =>
+ (await readdir(d)).filter((e) => (e.startsWith("transcript.live_chat") && !e.endsWith(".part")) || isKeptChatCapture(e)).sort();
+ const seeded = async (id: string) => {
+ 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);
+ return d;
+ };
+ const l = log();
+ const go = (id: string, run: Parameters<typeof fetchLiveChat>[0]["run"]) =>
+ 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, replace: true, paceSeconds: 0,
+ });
+
+ // An empty replay (a file with no message in it): the stored capture is the
+ // chat, the job says the replay was empty, and the empty replay is kept too.
+ const e = await seeded("rpe");
+ const out = await go("rpe", stubRunner({ writes: '{"replayChatItemAction":{"actions":[]}}\n' }).run);
+ assert.equal(out.status, "none");
+ assert.equal(await readStoredText(e, CHAT, "utf8"), OLD, "THE chat is the stored capture");
+ assert.match(l.lines.join(""), /The replay came back EMPTY \(0 messages\)/);
+ assert.equal(out.replace?.earlier.messages, 2);
+ assert.equal(out.replace?.fetched?.messages, 0);
+ const keptEmpty = (await forms(e)).filter(isKeptChatCapture);
+ assert.equal(keptEmpty.length, 1, (await forms(e)).join(", "));
+ assert.deepEqual((await forms(e)).filter((n) => !isKeptChatCapture(n)), [`${CHAT}.zst`]);
+ assert.equal((await decodeStoredBytes(await readFile(path.join(e, keptEmpty[0])))).toString("utf8"), '{"replayChatItemAction":{"actions":[]}}\n');
+
+ // Nothing landed; a failed pass; a .part.
+ for (const [id, run] of [
+ ["rp2", stubRunner({ writes: null }).run],
+ ["rp3", stubRunner({ exitCode: 1, stderr: "ERROR: [youtube] rp3: Video unavailable" }).run],
+ ["rp4", async (cwd: string) => {
+ await writeFile(path.join(cwd, "data", "rp4", `${CHAT}.part`), "half");
+ return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null };
+ }],
+ ] as const) {
+ const d = await seeded(id);
+ const r = await go(id, run).catch((err: Error) => ({ status: "failed", error: err.message }));
+ assert.notEqual(r.status, "fetched", id);
+ assert.deepEqual((await forms(d)), [`${CHAT}.zst`], `${id}: the stored chat is the chat, nothing kept aside`);
+ assert.equal(await readStoredText(d, CHAT, "utf8"), OLD, id);
+ }
+
+ // 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,6 +56,11 @@ 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, storedFormsIn } from "../lib/storedText";
+import { storedTextExists } from "../lib/storedText-server";
+import { keepPlainAsCapture, putBackKeptCapture, setAsideStoredText } from "../lib/storedText-write-server";
+import { decodeStoredBytes } from "../lib/storedText-server";
+import { parseLiveChat } from "../lib/liveChat";
import {
heldPlatformRefusal,
platformCooldownRemainingMs,
@@ -111,11 +116,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)` };
@@ -125,10 +133,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[]);
- if (entries.includes(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 {
@@ -170,11 +182,48 @@ 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`): the stored capture is KEPT under `chat-capture-kept.<stamp>.json.zst`
+ // and never removed (lib/storedText-write-server.ts). A new replay with
+ // messages becomes the chat; an empty one, or none, leaves the stored
+ // capture the chat.
+ replace?: boolean;
+};
+
+// One capture, measured: bytes, messages, and the first and last message's
+// time (seconds into the stream).
+export type CaptureMeasure = { bytes: number; messages: number; firstSec: number | null; lastSec: number | null };
+
+// What a `replace` did: the earlier capture (kept under `keptAs`, or put back
+// as the chat when `keptAs` is null) and the replay fetched (null: none).
+export type ReplaceReport = {
+ earlier: CaptureMeasure & { keptAs: string | null };
+ fetched: (CaptureMeasure & { keptAs: string | null }) | null;
};
export type FetchLiveChatResult =
- | { status: "fetched"; messages: number; cuesPath: string }
- | { status: "none" };
+ | { status: "fetched"; messages: number; cuesPath: string; replace?: ReplaceReport }
+ | { status: "none"; replace?: ReplaceReport };
+
+function measureChat(bytes: Buffer): CaptureMeasure {
+ let cues: { start: number }[] = [];
+ try {
+ cues = parseLiveChat(bytes.toString("utf8"));
+ } catch {
+ cues = [];
+ }
+ return {
+ bytes: bytes.length,
+ messages: cues.length,
+ firstSec: cues.length ? cues[0].start : null,
+ lastSec: cues.length ? cues[cues.length - 1].start : null,
+ };
+}
+
+function describe(m: CaptureMeasure): string {
+ const span = m.firstSec !== null && m.lastSec !== null ? `, ${m.firstSec.toFixed(0)}–${m.lastSec.toFixed(0)} s` : "";
+ return `${m.messages} message(s), ${m.bytes} bytes${span}`;
+}
/** The pass, then the normalize. Throws on a failed pass (the job ends `failed`). */
export async function fetchLiveChat(opts: FetchLiveChatOpts): Promise<FetchLiveChatResult> {
@@ -197,7 +246,70 @@ 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));
+ // A REPLACE keeps the stored capture first, under a name no reader sees.
+ let kept: string | null = null;
+ if (opts.replace) {
+ const set = await setAsideStoredText(videoDir, LIVE_CHAT_FILENAME);
+ if (set === "busy") throw new Error(`The chat of ${opts.videoId} is being compressed or restored right now; nothing was fetched. Try again in a moment.`);
+ kept = set.kept;
+ if (kept) opts.onLog(`The stored chat capture of ${opts.videoId} is kept as ${kept} while the replay is fetched.\n`);
+ }
+ try {
+ await passes();
+ } catch (err) {
+ if (kept) await putBack(kept);
+ throw err;
+ }
+ if (kept) return finishReplace(kept);
+ 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`);
+ return { status: "none" };
+ }
+ return normalizeChat(opts, videoDir);
+
+ async function putBack(k: string): Promise<void> {
+ const back = await putBackKeptCapture(videoDir, LIVE_CHAT_FILENAME, k);
+ opts.onLog(
+ back === true
+ ? `The kept capture ${k} is the chat again.\n`
+ : `The kept capture ${k} stays under that name (the chat's name is taken, or the file is busy); nothing was removed.\n`,
+ );
+ }
+
+ // After a clean pass over a kept capture: both measured, and the decision.
+ async function finishReplace(k: string): Promise<FetchLiveChatResult> {
+ const earlier = measureChat(await decodeStoredBytes(await readFile(path.join(videoDir, k)), k));
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ const partial = entries.some((e) => e.startsWith(`${LIVE_CHAT_FILENAME}.part`));
+ const landed = !partial && (await stat(path.join(videoDir, LIVE_CHAT_FILENAME)).then((st) => st.isFile(), () => false));
+ if (!landed) {
+ opts.onLog(`No new chat replay for ${opts.videoId} came back${partial ? " whole (a .part is here)" : ""}. Earlier capture: ${describe(earlier)}.\n`);
+ await putBack(k);
+ return { status: "none", replace: { earlier: { ...earlier, keptAs: null }, fetched: null } };
+ }
+ const fetched = measureChat(await readFile(path.join(videoDir, LIVE_CHAT_FILENAME)));
+ opts.onLog(`Earlier capture (${k}): ${describe(earlier)}. Replay fetched now: ${describe(fetched)}.\n`);
+ if (fetched.messages === 0) {
+ const empty = await keepPlainAsCapture(videoDir, LIVE_CHAT_FILENAME);
+ const emptyAs = empty !== "busy" ? empty.kept : null;
+ opts.onLog(
+ `The replay came back EMPTY (0 messages): the earlier capture stays the chat` +
+ (emptyAs ? `; the empty replay is kept as ${emptyAs}.\n` : `.\n`),
+ );
+ await putBack(k);
+ return { status: "none", replace: { earlier: { ...earlier, keptAs: null }, fetched: { ...fetched, keptAs: emptyAs } } };
+ }
+ opts.onLog(
+ `The replay fetched now is the chat; the earlier capture is KEPT as ${k} and is never removed automatically` +
+ (fetched.messages < earlier.messages ? ` (the replay has ${earlier.messages - fetched.messages} fewer message(s))` : "") +
+ `.\n`,
+ );
+ const out = await normalizeChat(opts, videoDir);
+ return { ...out, replace: { earlier: { ...earlier, keptAs: k }, fetched: { ...fetched, keptAs: null } } };
+ }
+ async function passes(): Promise<void> {
opts.onLog(
opts.capturingLive
? `Capturing the live chat of ${opts.videoId} from ${opts.videoUrl} while it is live (no media); ` +
@@ -242,12 +354,7 @@ export async function fetchLiveChat(opts: FetchLiveChatOpts): Promise<FetchLiveC
} catch {
/* shared-state write is best-effort */
}
- const entries = await readdir(videoDir).catch(() => [] as string[]);
- if (!entries.includes(LIVE_CHAT_FILENAME)) {
- opts.onLog(`No chat replay for ${opts.videoId}: the source has none (chat replay off, or never live). Nothing written.\n`);
- return { status: "none" };
}
- return normalizeChat(opts, videoDir);
}
// Best-effort: a failed write is logged, never the job's failure.
@@ -299,8 +406,29 @@ 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 (lib/storedText-write-server.ts): fetch the replay
+ // again over a chat stored compressed. The stored capture is kept as
+ // `chat-capture-kept.<stamp>.json.zst`, never removed; a replay with messages
+ // becomes the chat, an empty one (or none) leaves the stored capture the
+ // chat. 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,
@@ -311,7 +439,7 @@ export async function renormalizeChatRefusal(
const videoDir = path.join(paths.channelsDir, slug, "data", videoId);
if (!(await isDirectory(videoDir))) return notFetchedRefusal(videoId, slug);
const here = (name: string) => lstat(path.join(videoDir, name)).then(() => true, () => false);
- if (!(await here(LIVE_CHAT_FILENAME))) {
+ if (!(await storedTextExists(videoDir, LIVE_CHAT_FILENAME))) {
return (
`${videoId} has no raw chat on disk (${LIVE_CHAT_FILENAME}): "renormalize" reads only the file ` +
`already here and never fetches — fetch-chat without it fetches the chat`
@@ -329,13 +457,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 };
@@ -393,6 +528,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/controller/normalizeLiveChat.ts b/common/controller/normalizeLiveChat.ts
@@ -11,9 +11,11 @@
// `clock`. A chat fetched as a replay is already on that clock and is not moved.
import path from "node:path";
-import { lstat, readFile, stat } from "node:fs/promises";
+import { readFile, stat } from "node:fs/promises";
import { writeJsonAtomic } from "../lib/jsonFile-server";
import { tierMediaFile } from "../lib/mediaTier-server";
+import { LIVE_CHAT_STORED_FILENAME } from "../lib/mediaTier";
+import { readStoredText, storedTextMtimeMs } from "../lib/storedText-server";
import {
hasLiveCapturedLines,
liveChatClockOf,
@@ -73,12 +75,13 @@ async function mtimeMs(p: string): Promise<number | null> {
// the file's mtime onto the link (`lutimes`), so the link answers the same
// freshness question from the corpus disk — the index build asks it per video
// and must never reach the media drive to do so.
-async function rawMtimeMs(p: string): Promise<number | null> {
- try {
- return (await lstat(p)).mtimeMs;
- } catch {
- return null;
- }
+//
+// EITHER FORM (lib/storedText.ts): the plain name when present, else the
+// stored `transcript.live_chat.json.zst`, which the compressor gives the plain
+// file's times exactly — the same answer, so a compression re-normalizes
+// nothing.
+async function rawMtimeMs(videoDir: string): Promise<number | null> {
+ return storedTextMtimeMs(videoDir, LIVE_CHAT_FILENAME, { link: true });
}
/**
@@ -136,12 +139,11 @@ export async function normalizeLiveChat(
opts: NormalizeLiveChatOptions,
): Promise<NormalizeLiveChatOutcome> {
const metaPath = path.join(opts.videoDir, META_FILENAME);
- const rawPath = path.join(opts.videoDir, LIVE_CHAT_FILENAME);
const cuesPath = path.join(opts.videoDir, LIVE_CHAT_CUES_FILENAME);
const [metaStatMs, rawStatMs, cuesMs] = await Promise.all([
mtimeMs(metaPath),
- rawMtimeMs(rawPath),
+ rawMtimeMs(opts.videoDir),
mtimeMs(cuesPath),
]);
@@ -166,7 +168,7 @@ export async function normalizeLiveChat(
opts.configName,
);
- const rawLiveChat = await readFile(rawPath, "utf8");
+ const rawLiveChat = await readStoredText(opts.videoDir, LIVE_CHAT_FILENAME, "utf8");
let cues: Cue[];
let clock: LiveChatClock;
try {
@@ -198,9 +200,12 @@ export async function normalizeLiveChat(
// THE MEDIA TIER'S HOOK (release 17): the raw replay is read once, here, and
// every other reader uses the cues just written — so it moves into
// channels/<slug>/media now (a relative link stays). Never throws.
- if (opts.tier !== false) await tierMediaFile(opts.videoDir, LIVE_CHAT_FILENAME, {
- onLog: opts.log ? (line) => opts.log?.(line.trimEnd()) : undefined,
- });
+ // The stored form too, when that is what is here as a real file.
+ if (opts.tier !== false) {
+ const onLog = opts.log ? (line: string) => opts.log?.(line.trimEnd()) : undefined;
+ await tierMediaFile(opts.videoDir, LIVE_CHAT_FILENAME, { onLog });
+ await tierMediaFile(opts.videoDir, LIVE_CHAT_STORED_FILENAME, { onLog });
+ }
return { status: "wrote", cuesPath };
}
@@ -233,7 +238,7 @@ export async function readNormalizedLiveChat(
}
// Sidecar is fresh iff it exists and its mtime is >= both metadata.info.json
-// and transcript.live_chat.json. Used by buildIndex to decide whether to
+// and transcript.live_chat.json (either form). Used by buildIndex to decide whether to
// trust the cached cues without re-parsing the raw payload. Its version is
// not asked (LIVE_CHAT_FILE_VERSION above).
export async function isLiveChatCuesFresh(
@@ -241,11 +246,10 @@ export async function isLiveChatCuesFresh(
): Promise<{ fresh: boolean; cuesPath: string }> {
const cuesPath = path.join(videoDir, LIVE_CHAT_CUES_FILENAME);
const metaPath = path.join(videoDir, META_FILENAME);
- const rawPath = path.join(videoDir, LIVE_CHAT_FILENAME);
const [cuesMs, metaMs, rawMs] = await Promise.all([
mtimeMs(cuesPath),
mtimeMs(metaPath),
- rawMtimeMs(rawPath),
+ rawMtimeMs(videoDir),
]);
if (cuesMs === null || metaMs === null || rawMs === null) {
return { fresh: false, cuesPath };
diff --git a/common/controller/purgeSupersededAutoSubs.ts b/common/controller/purgeSupersededAutoSubs.ts
@@ -1,4 +1,4 @@
-import { removeMediaFile } from "../lib/mediaTier-server";
+import { removeStoredText } from "../lib/storedText-write-server";
import path from "node:path";
import fs from "fs-extra";
import type { Paths } from "../lib/paths";
@@ -89,7 +89,9 @@ export async function purgeSupersededAutoSubs({
skipped++;
continue;
}
- await removeMediaFile(videoDir, name); // the one rm of a video-dir entry (release 17)
+ // Both forms (lib/storedText-write-server.ts): a stored copy left behind
+ // would bring the captions back. Each through removeMediaFile.
+ await removeStoredText(videoDir, name);
log(`Removed ${id}/${name}`);
removedFiles++;
removedHere++;
diff --git a/common/controller/reconcileVideoDirs.test.ts b/common/controller/reconcileVideoDirs.test.ts
@@ -164,3 +164,52 @@ test("a dry run reports the same merge and moves nothing", async (t) => {
["20.00-30.00.mp4"],
);
});
+
+// ONE FILE, TWO NAMES (lane text-compress): a stored chat on one side and a
+// plain one on the other are the same file. Merged by name both would land,
+// the plain one would read as the truth, and the other side's copy would be
+// superseded with no trace. The loser's forms are stashed as `.dup-<src>`.
+test("a stored chat and a plain chat collide by their LOGICAL name; the loser is stashed, not superseded", async (t) => {
+ const channelDir = await makeChannel();
+ t.after(() => rm(channelDir, { recursive: true, force: true }));
+ await writeStrayDir(channelDir, "canonical01", {
+ "transcript.live_chat.json.zst": "destination stored chat",
+ });
+ await writeStrayDir(channelDir, "v-canonical01", {
+ "transcript.live_chat.json": "source plain chat",
+ });
+ await reconcileVideoDirs({ channelDir });
+ const dst = path.join(channelDir, "data", "canonical01");
+ const names = (await readdir(dst)).filter((n) => n.startsWith("transcript.")).sort();
+ assert.deepEqual(names, [
+ "transcript.live_chat.json",
+ "transcript.live_chat.json.zst.dup-v-canonical01",
+ ]);
+ // The source wins (yt-dlp's bytes, as for any transcript.*); the other is kept.
+ assert.equal(await readFile(path.join(dst, "transcript.live_chat.json"), "utf8"), "source plain chat");
+ assert.equal(
+ await readFile(path.join(dst, "transcript.live_chat.json.zst.dup-v-canonical01"), "utf8"),
+ "destination stored chat",
+ );
+});
+
+test("both forms on the source side move in together over a destination's stored chat", async (t) => {
+ const channelDir = await makeChannel();
+ t.after(() => rm(channelDir, { recursive: true, force: true }));
+ await writeStrayDir(channelDir, "canonical01", {
+ "transcript.live_chat.json.zst": "old stored",
+ });
+ await writeStrayDir(channelDir, "v-canonical01", {
+ "transcript.live_chat.json": "src plain",
+ "transcript.live_chat.json.zst": "src stored",
+ });
+ await reconcileVideoDirs({ channelDir });
+ const dst = path.join(channelDir, "data", "canonical01");
+ assert.deepEqual((await readdir(dst)).filter((n) => n.startsWith("transcript.")).sort(), [
+ "transcript.live_chat.json",
+ "transcript.live_chat.json.zst",
+ "transcript.live_chat.json.zst.dup-v-canonical01",
+ ]);
+ assert.equal(await readFile(path.join(dst, "transcript.live_chat.json.zst"), "utf8"), "src stored");
+ assert.equal(await readFile(path.join(dst, "transcript.live_chat.json.zst.dup-v-canonical01"), "utf8"), "old stored");
+});
diff --git a/common/controller/reconcileVideoDirs.ts b/common/controller/reconcileVideoDirs.ts
@@ -2,6 +2,7 @@ import path from "node:path";
import { readdir, readFile, rename, rmdir, stat } from "node:fs/promises";
import { extractVideoId } from "../ytdlp/runYtdlp";
import { CLIPS_DIR_NAME } from "../lib/clipWindow";
+import { isStoredTextName, logicalNameOf } from "../lib/storedText";
// The app keys every video by its canonical, URL-derived id
// (`extractVideoId(webpage_url)`) and expects its data under
@@ -83,6 +84,20 @@ async function mergeDir(
readdir(dstDir).catch(() => [] as string[]),
]);
const dstSet = new Set(dstEntries);
+ // ONE FILE, TWO NAMES (lib/storedText.ts): `transcript.live_chat.json` and
+ // its stored `transcript.live_chat.json.zst` collide although their names
+ // differ — merged by name, both would land and the plain one (the truth)
+ // would silently supersede the other side's copy. So a collision is by the
+ // LOGICAL name, and the loser's every form is stashed aside.
+ const dstForms = new Map<string, string[]>();
+ for (const d of dstEntries) {
+ const l = logicalNameOf(d);
+ if (!isStoredTextName(l)) continue;
+ dstForms.set(l, [...(dstForms.get(l) ?? []), d]);
+ }
+ // Logical names whose collision is settled: the destination's forms are
+ // stashed (the source won), so the source's other forms move in as they are.
+ const settled = new Set<string>();
for (const f of srcEntries) {
const src = path.join(srcDir, f);
// `clips/` IS A DIRECTORY, and the collision rule below is written for
@@ -103,6 +118,28 @@ async function mergeDir(
if (!dryRun) await rmdir(src).catch(() => {});
continue;
}
+ const logical = logicalNameOf(f);
+ const forms = dstForms.get(logical);
+ if (forms && !settled.has(logical)) {
+ settled.add(logical);
+ if (sourceWins(logical)) {
+ // Keep the source's; stash every destination form aside.
+ for (const d of forms) {
+ if (!dryRun) await rename(path.join(dstDir, d), path.join(dstDir, `${d}.dup-${srcName}`));
+ dstSet.delete(d);
+ }
+ } else {
+ // Keep the destination's; stash this and any other source form aside.
+ for (const g of srcEntries) {
+ if (logicalNameOf(g) !== logical) continue;
+ if (!dryRun) await rename(path.join(srcDir, g), path.join(dstDir, `${g}.dup-${srcName}`));
+ moved.push(`${g}.dup-${srcName}`);
+ }
+ continue;
+ }
+ } else if (forms && !sourceWins(logical)) {
+ continue; // stashed with its first form above
+ }
if (!dstSet.has(f)) {
if (!dryRun) await rename(src, path.join(dstDir, f));
moved.push(f);
diff --git a/common/controller/storedText.chat.test.ts b/common/controller/storedText.chat.test.ts
@@ -0,0 +1,142 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { ChannelConfig } from "../lib/channelConfig";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/storedText.chat.test.ts
+//
+// THE CHAT IS STILL FOUND BY EVERY READER AFTER IT IS COMPRESSED (lane
+// text-compress, slice 1). Each case builds a video dir whose raw replay is
+// `transcript.live_chat.json.zst` only — a real file, and a tier link into
+// the channel's `media/` — and asks every reader of the raw chat what it
+// sees. Before this slice the track vanished and the plan FETCHED the whole
+// replay again. Temp corpus, no network, no yt-dlp.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "stored-chat-"));
+const CORPUS = path.join(ROOT, "transcripts");
+process.env.TRANSCRIPTS_DIR = CORPUS;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await mkdir(CORPUS, { recursive: true });
+await writeFile(process.env.SETTINGS_FILE, "{}");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { liveChatPlan, renormalizeChatRefusal } = await import("./fetchLiveChat");
+const { normalizeLiveChat, isLiveChatCuesFresh } = await import("./normalizeLiveChat");
+const { readSubTracks } = await import("../lib/videoStatus");
+const { trackOnDisk, subLangsForVideo } = await import("../ytdlp/runYtdlp");
+const { youtubeHandlingArgs } = await import("../ytdlp/downloadOneManaged");
+const { storeFixture } = await import("../testing/storedTextFixture");
+
+const paths = getPaths();
+const SLUG = "synth-chat";
+const CONFIG = { handling: "youtube", url: "https://www.youtube.com/@synth/streams", name: "Synth" } as ChannelConfig;
+const CHAT = "transcript.live_chat.json";
+
+function chatLine(sec: number, author: string, text: string): string {
+ return JSON.stringify({
+ replayChatItemAction: {
+ actions: [
+ {
+ addChatItemAction: {
+ item: { liveChatTextMessageRenderer: { message: { runs: [{ text }] }, authorName: { simpleText: author } } },
+ },
+ },
+ ],
+ videoOffsetTimeMsec: String(sec * 1000),
+ },
+ });
+}
+const REPLAY = [chatLine(12, "viewer1", "lol"), chatLine(14, "viewer2", "LMAO"), chatLine(30, "viewer3", "W")].join("\n") + "\n";
+
+const channelDir = path.join(CORPUS, "channels", SLUG);
+
+async function video(id: string, opts: { tiered?: boolean } = {}): Promise<string> {
+ const dir = path.join(channelDir, "data", id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(channelDir, "config.json"), JSON.stringify(CONFIG));
+ await writeFile(
+ path.join(dir, "metadata.info.json"),
+ JSON.stringify({ id, title: "Synth stream", webpage_url: `https://www.youtube.com/watch?v=${id}`, was_live: true }),
+ );
+ if (opts.tiered) {
+ const media = path.join(channelDir, "media", id);
+ await mkdir(media, { recursive: true });
+ await writeFile(path.join(media, CHAT), REPLAY);
+ await symlink(path.join("..", "..", "media", id, CHAT), path.join(dir, CHAT));
+ } else {
+ await writeFile(path.join(dir, CHAT), REPLAY);
+ }
+ return dir;
+}
+
+const cuesOf = async (dir: string) =>
+ JSON.parse(await readFile(path.join(dir, "live_chat.cues.json"), "utf8")).cues;
+
+for (const tiered of [false, true]) {
+ const how = tiered ? "a tier link" : "a real file";
+
+ test(`compressed as ${how}: the live_chat track is listed under its plain name`, async () => {
+ const dir = await video(`list${tiered ? "t" : "r"}`, { tiered });
+ await storeFixture(dir, CHAT);
+ assert.deepEqual(
+ (await readSubTracks(dir)).map((t) => [t.track, t.filename]),
+ [["live_chat", CHAT]],
+ );
+ });
+
+ test(`compressed as ${how}: normalize reads it and writes the same cues`, async () => {
+ const id = `norm${tiered ? "t" : "r"}`;
+ const dir = await video(id, { tiered });
+ assert.equal((await normalizeLiveChat({ videoDir: dir, channelSlug: SLUG, force: true, tier: false })).status, "wrote");
+ const fromPlain = await cuesOf(dir);
+ await storeFixture(dir, CHAT);
+ // Fresh: the stored form carries the plain file's times exactly.
+ assert.equal((await isLiveChatCuesFresh(dir)).fresh, true);
+ assert.equal((await normalizeLiveChat({ videoDir: dir, channelSlug: SLUG, tier: false })).status, "fresh");
+ assert.equal((await normalizeLiveChat({ videoDir: dir, channelSlug: SLUG, force: true, tier: false })).status, "wrote");
+ assert.deepEqual(await cuesOf(dir), fromPlain);
+ assert.equal(fromPlain.length, 3);
+ });
+
+ test(`compressed as ${how}: the plan normalizes or says fresh — it NEVER fetches`, async () => {
+ const id = `plan${tiered ? "t" : "r"}`;
+ const dir = await video(id, { tiered });
+ await storeFixture(dir, CHAT);
+ // No cues yet: the raw on disk is normalized, not fetched again.
+ assert.deepEqual(await liveChatPlan(paths, SLUG, id, CONFIG), { kind: "normalize" });
+ await normalizeLiveChat({ videoDir: dir, channelSlug: SLUG, tier: false });
+ assert.equal((await liveChatPlan(paths, SLUG, id, CONFIG)).kind, "fresh");
+ // A re-normalize finds the raw chat on disk.
+ assert.equal(await renormalizeChatRefusal(paths, SLUG, id), null);
+ });
+
+ test(`compressed as ${how}: the missing-subs prefilter sees the chat on disk`, async () => {
+ const dir = await video(`subs${tiered ? "t" : "r"}`, { tiered });
+ await storeFixture(dir, CHAT);
+ const { readdir } = await import("node:fs/promises");
+ const entries = await readdir(dir);
+ assert.equal(trackOnDisk(entries, "live_chat"), true);
+ // And a fetch for another missing track leaves the chat out: yt-dlp's own
+ // skip would not see the stored form and would fetch the replay again.
+ assert.equal(subLangsForVideo(entries, "en.*,live_chat"), "en.*");
+ assert.equal(subLangsForVideo(["transcript.live_chat.json"], "en.*,live_chat"), "en.*,live_chat");
+ });
+}
+
+test("a download over a stored chat leaves the chat out of its sub-langs", () => {
+ const langs = (args: string[]) => args[args.indexOf("--sub-langs") + 1];
+ assert.equal(langs(youtubeHandlingArgs(CONFIG, false, false)), "en.*,live_chat");
+ assert.equal(langs(youtubeHandlingArgs(CONFIG, false, true)), "en.*");
+});
+
+test("with no chat in either form the plan still fetches (the control)", async () => {
+ const id = "nochat";
+ const dir = await video(id);
+ await rm(path.join(dir, CHAT));
+ assert.equal((await liveChatPlan(paths, SLUG, id, CONFIG)).kind, "fetch");
+ assert.notEqual(await renormalizeChatRefusal(paths, SLUG, id), null);
+});
diff --git a/common/controller/storedText.delete.test.ts b/common/controller/storedText.delete.test.ts
@@ -0,0 +1,159 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { lstat, mkdir, mkdtemp, readdir, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/storedText.delete.test.ts
+//
+// NO RESURRECTION (lane text-compress, slice 1). A plain file written again
+// beside an older stored copy, then deleted by a deleter that knows only the
+// plain name, would bring the older copy back as the file — silently and
+// wrongly. Every deleter of a declared name removes both forms
+// (`removeStoredText`), each through `removeMediaFile`. Temp dirs only.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "stored-delete-"));
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const { removeStoredText } = await import("../lib/storedText-write-server");
+const { purgeSupersededAutoSubs } = await import("./purgeSupersededAutoSubs");
+const { readStoredText } = await import("../lib/storedText-server");
+const { storeFixture } = await import("../testing/storedTextFixture");
+
+const CHAT = "transcript.live_chat.json";
+
+async function videoDir(slug: string, id: string): Promise<string> {
+ const d = path.join(ROOT, "channels", slug, "data", id);
+ await mkdir(d, { recursive: true });
+ return d;
+}
+
+const exists = (p: string) => lstat(p).then(() => true, () => false);
+
+test("removeStoredText: a plain chat re-written beside an older stored one — both go", async () => {
+ const d = await videoDir("c", "v1");
+ await writeFile(path.join(d, CHAT), "OLD\n");
+ await storeFixture(d, CHAT);
+ await writeFile(path.join(d, CHAT), "NEW\n");
+ assert.equal(await readStoredText(d, CHAT, "utf8"), "NEW\n");
+ await removeStoredText(d, CHAT);
+ await assert.rejects(readStoredText(d, CHAT, "utf8"), { code: "ENOENT" });
+ assert.deepEqual(await readdir(d), []);
+});
+
+test("removeStoredText through tier links: the bytes in media/<id>/ go too, never orphaned", async () => {
+ const d = await videoDir("t", "v2");
+ const media = path.join(ROOT, "channels", "t", "media", "v2");
+ await mkdir(media, { recursive: true });
+ await writeFile(path.join(media, CHAT), "CHAT\n");
+ await symlink(path.join("..", "..", "media", "v2", CHAT), path.join(d, CHAT));
+ await storeFixture(d, CHAT, { keepPlain: true });
+ assert.ok(await exists(path.join(media, `${CHAT}.zst`)));
+ await removeStoredText(d, CHAT);
+ assert.deepEqual(await readdir(d), []);
+ assert.equal(await exists(path.join(media, CHAT)), false);
+ assert.equal(await exists(path.join(media, `${CHAT}.zst`)), false);
+});
+
+// YouTube's rolling-caption shape: an ASR track (inline word timing).
+const ASR_VTT =
+ "WEBVTT\nKind: captions\nLanguage: en\n\n" +
+ "00:00:00.000 --> 00:00:05.000 align:start position:0%\n" +
+ "First<00:00:01.000><c> caption</c><00:00:02.000><c> line.</c>\n\n" +
+ "00:01:00.000 --> 00:01:50.000 align:start position:0%\n" +
+ "Second<00:01:10.000><c> caption</c><00:01:20.000><c> line.</c>\n";
+
+test("the superseded-auto-caption purge removes a caption's stored sibling too", async () => {
+ const d = await videoDir("p", "v3");
+ await writeFile(path.join(d, "transcript.json"), JSON.stringify({ transcription: [{ text: "x" }] }));
+ await writeFile(path.join(d, "transcript.en.vtt"), ASR_VTT);
+ // What a later stored-captions slice would leave: an older stored copy.
+ await writeFile(path.join(d, "transcript.en.vtt.zst"), "older stored copy");
+ const r = await purgeSupersededAutoSubs({
+ channelSlug: "p",
+ paths: { channelsDir: path.join(ROOT, "channels") } as never,
+ onLog: () => {},
+ });
+ assert.equal(r.removedFiles, 1);
+ assert.deepEqual((await readdir(d)).sort(), ["transcript.json"]);
+});
+
+// REVIEW-1 F5 / REVIEW-2 R2: THE FILES CARD'S DELETE OF ONE NAMED FORM
+// (`removeStoredTextForm`, what deleteVideoFileAction and `pnpm ops
+// delete-file` run). A person asked for ONE file: only that one goes, never the
+// other form — whether they hold the same content or not — and the answer
+// names the other and says which. (Before REVIEW-2: the same content took
+// both, so deleting a duplicate `.zst` beside its plain file left zero copies.)
+const { removeStoredTextForm } = await import("../lib/storedText-write-server");
+
+test("delete one named form: only the named one goes, whatever the other holds", async () => {
+ const ZST = `${CHAT}.zst`;
+ // Same content, either name clicked: the other stays, and is read.
+ for (const clicked of [CHAT, ZST]) {
+ const d = await videoDir("f5same", clicked);
+ await writeFile(path.join(d, CHAT), "SAME\n");
+ await storeFixture(d, CHAT, { keepPlain: true });
+ const out = await removeStoredTextForm(d, clicked);
+ const other = clicked === CHAT ? ZST : CHAT;
+ assert.deepEqual(out, { removed: [clicked], kept: { name: other, same: "same" } });
+ assert.deepEqual(await readdir(d), [other], `${clicked}: only it went`);
+ assert.equal(await readStoredText(d, CHAT, "utf8"), "SAME\n", `${clicked}: readers still see the chat`);
+ }
+ // Different content: the plain one clicked — the stored one is kept, and read.
+ {
+ const d = await videoDir("f5diff", "plain");
+ await writeFile(path.join(d, CHAT), "OLD WHOLE CAPTURE\n");
+ await storeFixture(d, CHAT);
+ await writeFile(path.join(d, CHAT), "NEWER, TRIMMED\n");
+ const out = await removeStoredTextForm(d, CHAT);
+ assert.deepEqual(out, { removed: [CHAT], kept: { name: ZST, same: "differs" } });
+ assert.deepEqual(await readdir(d), [ZST]);
+ assert.equal(await readStoredText(d, CHAT, "utf8"), "OLD WHOLE CAPTURE\n");
+ }
+ // Different content: the stored one clicked — the plain one is kept.
+ {
+ const d = await videoDir("f5diff", "stored");
+ await writeFile(path.join(d, CHAT), "OLD\n");
+ await storeFixture(d, CHAT);
+ await writeFile(path.join(d, CHAT), "NEW\n");
+ const out = await removeStoredTextForm(d, ZST);
+ assert.deepEqual(out, { removed: [ZST], kept: { name: CHAT, same: "differs" } });
+ assert.deepEqual(await readdir(d), [CHAT]);
+ }
+ // One form only: it goes.
+ {
+ const d = await videoDir("f5one", "v");
+ await writeFile(path.join(d, CHAT), "ONLY\n");
+ await storeFixture(d, CHAT);
+ assert.deepEqual(await removeStoredTextForm(d, ZST), { removed: [ZST] });
+ assert.deepEqual(await readdir(d), []);
+ }
+});
+
+test("delete one named form through tier links: the named form's bytes go, the other form's stay", async () => {
+ const ZST = `${CHAT}.zst`;
+ const d = await videoDir("f5t", "v5");
+ const media = path.join(ROOT, "channels", "f5t", "media", "v5");
+ await mkdir(media, { recursive: true });
+ await writeFile(path.join(media, CHAT), "TIERED\n");
+ await symlink(path.join("..", "..", "media", "v5", CHAT), path.join(d, CHAT));
+ await storeFixture(d, CHAT, { keepPlain: true });
+ assert.deepEqual(await removeStoredTextForm(d, ZST), { removed: [ZST], kept: { name: CHAT, same: "same" } });
+ assert.deepEqual(await readdir(d), [CHAT]);
+ assert.equal(await exists(path.join(media, ZST)), false, "its bytes went with it");
+ assert.equal(await readStoredText(d, CHAT, "utf8"), "TIERED\n");
+
+ // The plain link's bytes gone (an interrupted removal): clicking the plain
+ // name removes only that link; the stored copy stays, and is read.
+ const e = await videoDir("f5t", "v6");
+ const media6 = path.join(ROOT, "channels", "f5t", "media", "v6");
+ await mkdir(media6, { recursive: true });
+ await writeFile(path.join(media6, CHAT), "ONLY COPY\n");
+ await symlink(path.join("..", "..", "media", "v6", CHAT), path.join(e, CHAT));
+ await storeFixture(e, CHAT);
+ await symlink(path.join("..", "..", "media", "v6", CHAT), path.join(e, CHAT));
+ const out = await removeStoredTextForm(e, CHAT);
+ assert.deepEqual(out, { removed: [CHAT], kept: { name: ZST, same: "unreadable" } });
+ assert.equal(await readStoredText(e, CHAT, "utf8"), "ONLY COPY\n");
+});
diff --git a/common/jobs/bootQueuedJobs.test.ts b/common/jobs/bootQueuedJobs.test.ts
@@ -616,3 +616,40 @@ test("a queued x-run is cancelled as `person`, never re-queued", async () => {
await rm(f.root, { recursive: true, force: true });
}
});
+
+// Lane text-compress (REVIEW-1 F1): `compress-text` removes originals (or, a
+// restore, stored copies), so it starts ONLY on a person's word — in every
+// state a restart can leave it. A corpus-wide run is one job per channel on
+// one queue, so all but one are QUEUED: the queued pass closes each (never a
+// re-queue, though each has a fresh replayable spec); the one RUNNING is closed
+// as interrupted, and the resume pass does not resume it. Through the real
+// boot passes, in the order instrumentation.ts runs them.
+test("compress-text in any state a restart leaves is never started by the boot", async () => {
+ const { resumeInterruptedJobs } = await import("./resumeInterrupted");
+ const spec = (slug: string): JobSpec => ({ kind: "compress-text", slug, params: {} });
+ const f = await fixture([
+ { id: "C1", kind: "compress-text", queueKey: "compress-text", status: "running", channelSlug: "a", spec: spec("a"), pid: DEAD },
+ { id: "C2", kind: "compress-text", queueKey: "compress-text", channelSlug: "b", spec: spec("b") },
+ { id: "C3", kind: "compress-text", queueKey: "compress-text", channelSlug: "c", spec: { kind: "compress-text", slug: "c", params: { restore: true } } },
+ ]);
+ try {
+ const running = await settleRunningJobMetas({ paths: f.paths, bootedAt: BOOT, log: () => {}, ...check });
+ assert.deepEqual(running.interrupted.map((j) => j.id), ["C1"]);
+ const rq = recordingRequeue();
+ const queued = await settleQueuedJobMetas({ paths: f.paths, requeue: rq.fn, bootedAt: BOOT, log: () => {}, ...check });
+ assert.deepEqual(queued.requeued, []);
+ assert.deepEqual(queued.cancelled.map((c) => [c.id, c.category]).sort(), [["C2", "person"], ["C3", "person"]]);
+ for (const id of ["C2", "C3"]) assert.equal((await f.read(id)).cancelReason, PERSON_RESTART_REASON);
+ const resumed = await resumeInterruptedJobs({
+ paths: f.paths,
+ requeue: rq.fn,
+ ids: running.interrupted.map((j) => j.id),
+ now: BOOT,
+ });
+ assert.deepEqual(resumed.map((o) => [o.id, o.action]), [["C1", "not-resumed"]]);
+ assert.deepEqual(rq.calls, [], "nothing was re-queued, in any state");
+ assert.equal((await f.read("C1")).status, "cancelled");
+ } finally {
+ await rm(f.root, { recursive: true, force: true });
+ }
+});
diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts
@@ -301,7 +301,8 @@ test("release 18: every drainable kind but the lane runners and the clip-window
// fetch-windows writes only `data/<id>/clips/`, a cache the index never reads.
// wayback-scan writes only `wayback-scan.json`, which the index never reads.
// save-page-now-batch writes only its own state and evidence (.spn-batches/).
- const notIngest = new Set(["fetch-windows", "wayback-scan", "save-page-now-batch"]);
+ // compress-text changes how a raw chat is stored, never what the index reads.
+ const notIngest = new Set(["fetch-windows", "wayback-scan", "save-page-now-batch", "compress-text"]);
for (const kind of jobKindIds()) {
if (!isDrainableKind(kind) || runners.has(kind) || notIngest.has(kind)) continue;
assert.equal(isIngestKind(kind), true, `${kind} is drainable and per channel: an ingest kind`);
@@ -448,3 +449,25 @@ test("compact-saved-videos is a drainable, replayable media ingest kind the boot
assert.equal(isIngestKind("compact-saved-videos"), true);
assert.equal(kindIsNetwork("compact-saved-videos"), false);
});
+
+test("compress-text is a drainable, replayable media kind: not ingest, never resumed by the boot pass", () => {
+ const meta = getJobKind("compress-text");
+ assert.ok(meta, "registered");
+ assert.equal(jobKindLabel("compress-text"), "Compress text");
+ assert.equal(isDrainableKind("compress-text"), true);
+ assert.equal(meta.replayable, true);
+ assert.equal(meta.resumeOnBoot, undefined);
+ assert.equal(kindNeedsMedia("compress-text"), true);
+ assert.equal(isIngestKind("compress-text"), false);
+ assert.equal(kindIsNetwork("compress-text"), false);
+ // A queued one a restart left is closed, never re-queued (bootQueuedJobs.ts).
+ assert.equal(meta.startedByPerson, true);
+});
+
+// A kind a person starts is never started by a boot in ANY state: one that
+// says both would be resumed after an interruption.
+test("no kind is both startedByPerson and resumeOnBoot", () => {
+ for (const k of resumeOnBootKindIds()) {
+ assert.notEqual(getJobKind(k)?.startedByPerson, true, `${k}`);
+ }
+});
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -1639,6 +1639,24 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
queueKeyStrategy: "custom",
needsMedia: true,
},
+ // THE RAW LIVE CHATS PUT INTO THEIR STORED FORM (controller/compressText.ts,
+ // `pnpm ops compress-text`; lane text-compress): one file at a time on the
+ // machine-wide `compress-text` queue, one job per channel. It opens and
+ // removes the big file (media). NOT an ingest kind: the index reads the same
+ // cues and the same times after it (the stored form carries them). STARTED
+ // BY A PERSON ONLY, in every state: it removes originals (or, `restore`,
+ // stored copies), so a boot never runs one — a queued one is closed
+ // (`startedByPerson`), an interrupted one is not resumed (no
+ // `resumeOnBoot`); a person re-runs it, and a re-run continues.
+ "compress-text": {
+ kind: "compress-text",
+ label: "Compress text",
+ drainable: true,
+ replayable: true,
+ queueKeyStrategy: "custom",
+ needsMedia: true,
+ startedByPerson: true,
+ },
};
export function getJobKind(kind: string): JobKindMeta | undefined {
diff --git a/common/lib/mediaTier-server.test.ts b/common/lib/mediaTier-server.test.ts
@@ -277,6 +277,32 @@ test("the link carries the file's mtime, so an lstat answers freshness without t
await rm(f.root, { recursive: true, force: true });
});
+test("the link keeps a SUB-MILLISECOND mtime exactly (lane text-compress: numeric seconds, not Dates)", async () => {
+ // The index compares these with `!==`: a `Date` keeps whole milliseconds,
+ // so tiering a file with nanosecond times moved its key and re-ingested it.
+ const f = await fixture();
+ await mkdir(channelMediaLink(f.paths, f.slug));
+ const file = path.join(f.videoDir, "transcript.live_chat.json");
+ await utimes(file, 1763700000.123457, 1763700000.987653);
+ const before = (await stat(file)).mtimeMs;
+ assert.notEqual(before, Math.trunc(before), "the fixture has a sub-ms time");
+ assert.equal(await tierMediaFile(f.videoDir, "transcript.live_chat.json"), "tiered");
+ assert.equal((await lstat(file)).mtimeMs, before, "the link");
+ assert.equal((await stat(file)).mtimeMs, before, "the bytes");
+ await rm(f.root, { recursive: true, force: true });
+});
+
+test("the STORED chat (`.zst`) is tiered like the plain one", async () => {
+ const f = await fixture();
+ await mkdir(channelMediaLink(f.paths, f.slug));
+ await writeFile(path.join(f.videoDir, "transcript.live_chat.json.zst"), "ZST");
+ assert.equal(await tierMediaFile(f.videoDir, "transcript.live_chat.json.zst"), "tiered");
+ const link = path.join(f.videoDir, "transcript.live_chat.json.zst");
+ assert.ok((await lstat(link)).isSymbolicLink());
+ assert.equal(await readlink(link), tierLinkTarget("vid1", "transcript.live_chat.json.zst"));
+ await rm(f.root, { recursive: true, force: true });
+});
+
test("a move marker on the channel: the hook writes nothing into media/", async () => {
assert.equal(TIER_RELOCATION_MARKER, RELOCATION_MARKER_FILENAME);
const f = await fixture();
diff --git a/common/lib/mediaTier-server.ts b/common/lib/mediaTier-server.ts
@@ -220,7 +220,11 @@ export async function tierMediaFile(
// `stat` of the file did before it was tiered — the live-chat freshness
// check and the index's sub-track key read it there, on the corpus disk,
// instead of reaching the media drive.
- await lutimes(tmpLink, st.atime, st.mtime).catch(() => {});
+ //
+ // NUMERIC SECONDS, never the `Date`s: a `Date` holds whole milliseconds,
+ // so a file with sub-ms times came out with a different `mtimeMs` and the
+ // index — which compares it with `!==` — re-ingested the record once.
+ await lutimes(tmpLink, st.atimeMs / 1000, st.mtimeMs / 1000).catch(() => {});
await rm(destTmp, { force: true });
try {
await fsx.link(file, destTmp);
@@ -229,7 +233,7 @@ export async function tierMediaFile(
await rm(destTmp, { force: true }).catch(() => {});
if (!NO_HARD_LINK.has(errCode(err) ?? "")) throw err;
await fsx.copyFileAtomic(file, dest);
- await utimes(dest, st.atime, st.mtime).catch(() => {});
+ await utimes(dest, st.atimeMs / 1000, st.mtimeMs / 1000).catch(() => {});
}
placed = true;
if (await markerStands(mediaRoot)) {
@@ -427,7 +431,7 @@ export async function renameMediaFile(
const tmpLink = path.join(videoDir, `.${to}.tierlink-${process.pid}`);
await rm(tmpLink, { force: true });
await symlink(path.relative(videoDir, newTarget), tmpLink);
- await lutimes(tmpLink, st.atime, st.mtime).catch(() => {});
+ await lutimes(tmpLink, st.atimeMs / 1000, st.mtimeMs / 1000).catch(() => {});
await rename(tmpLink, path.join(videoDir, to));
await rm(file, { force: true });
return;
diff --git a/common/lib/mediaTier.test.ts b/common/lib/mediaTier.test.ts
@@ -96,3 +96,19 @@ test("every tierable name is media (tierable is narrower)", () => {
if (isTierable(name)) assert.equal(classifyEntry(name), "media", name);
}
});
+
+// Lane text-compress, REVIEW-2 R1: a kept earlier chat capture is media and
+// tierable (it travels with the video) and is never the chat's name.
+test("chat-capture-kept.<stamp>.json.zst: media, tierable, and not a chat name", async () => {
+ const { isKeptChatCapture, keptChatCaptureName, classifyEntry, isTierable } = await import("./mediaTier");
+ const k = keptChatCaptureName(new Date(Date.UTC(2026, 10, 21, 4, 5, 6, 789)));
+ assert.equal(k, "chat-capture-kept.20261121T040506Z.json.zst");
+ assert.equal(keptChatCaptureName(new Date(Date.UTC(2026, 10, 21, 4, 5, 6)), 2), "chat-capture-kept.20261121T040506Z-2.json.zst");
+ assert.ok(isKeptChatCapture(k));
+ assert.equal(classifyEntry(k), "media");
+ assert.equal(isTierable(k), true);
+ assert.ok(!k.startsWith("transcript.") && !k.startsWith("live_chat.") && !k.endsWith(".json"));
+ for (const t of [".transcript.live_chat.json.restoring-12-abc", ".x.stlink-12-abc", ".stored-text.lock", ".transcript.live_chat.json.retire-12-abc", ".transcript.live_chat.json.zst.compressing-12-abc"]) {
+ assert.equal(classifyEntry(t), "scratch", t);
+ }
+});
diff --git a/common/lib/mediaTier.ts b/common/lib/mediaTier.ts
@@ -33,6 +33,36 @@ import {
// pins that the two agree.
export const LIVE_CHAT_MEDIA_FILENAME = "transcript.live_chat.json";
+// The raw replay's STORED form (lib/storedText.ts): the same bytes, one zstd
+// frame. Media and tierable exactly like the plain name — without this the
+// tier hook would never move a compressed chat and the reclaim's "a tierable
+// file stays" rule would not cover it.
+export const LIVE_CHAT_STORED_FILENAME = `${LIVE_CHAT_MEDIA_FILENAME}.zst`;
+
+// AN EARLIER CHAT CAPTURE, KEPT (lane text-compress, REVIEW-2 R1): when
+// `fetch-chat {replace: true}` fetches a replay over a chat stored compressed,
+// the stored capture is first renamed `chat-capture-kept.<UTC stamp>.json.zst`
+// (the same bytes: one zstd frame). A platform's replay is often shorter than
+// the live capture, and the capture cannot be fetched again — so nothing ever
+// removes one of these automatically. The name is chosen so that NO reader of
+// the chat sees it: it does not start with `transcript.` or `live_chat.`, it
+// is not a declared stored-text name, and it does not end in `.json`. It is
+// MEDIA and TIERABLE like the chat itself, so it travels with the video: the
+// tier hook moves it, a relocation carries it, `removeVideoDirMedia` removes it
+// with the video, and the reclaim keeps it.
+export const KEPT_CHAT_CAPTURE_PREFIX = "chat-capture-kept.";
+const KEPT_CHAT_CAPTURE_RE = /^chat-capture-kept\.\d{8}T\d{6}Z(?:-\d+)?\.json\.zst$/;
+
+export function isKeptChatCapture(name: string): boolean {
+ return KEPT_CHAT_CAPTURE_RE.test(name);
+}
+
+// A kept capture's name for a moment (`n`: a second one in the same second).
+export function keptChatCaptureName(at: Date, n = 0): string {
+ const stamp = at.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
+ return `${KEPT_CHAT_CAPTURE_PREFIX}${stamp}${n ? `-${n}` : ""}.json.zst`;
+}
+
// The clip-window cache dir (`clipWindow.ts`'s `CLIPS_DIR_NAME`, pinned by the
// test for the same reason). Never tiered, never classified as media.
export const CLIPS_DIR = "clips";
@@ -81,6 +111,24 @@ const SCRATCH_PATTERNS: ReadonlyArray<RegExp> = [
// The salvage transcription's decoded WAV (`audio.salvage.wav`,
// lib/salvageAudio-server.ts): removed when the transcription ends.
/^audio\.salvage\.wav$/,
+ // The stored-text compressor's temp (`.transcript.live_chat.json.zst.compressing-<pid>`,
+ // lib/storedText-write-server.ts): never a copy anyone reads — the stored
+ // form appears only by a rename of a verified temp — and a dead pid's is
+ // discarded by the next run.
+ /\.compressing-\d+(?:-[0-9a-z]+)?$/,
+ // The restore's plain temp (`.transcript.live_chat.json.restoring-<pid>-<token>`)
+ // and the stored-text runs' own temp links (`.….stlink-<pid>-<token>`).
+ /\.restoring-\d+(?:-[0-9a-z]+)?$/,
+ /\.stlink-\d+(?:-[0-9a-z]+)?$/,
+ // A kept capture being written (`.chat-capture-kept.….json.zst.keeping-<pid>-<token>`).
+ /\.keeping-\d+(?:-[0-9a-z]+)?$/,
+ // The stored-text runs' per-directory lock (`.stored-text.lock`, and the
+ // temp a run links it from).
+ /^\.stored-text\.lock(?:\..+)?$/,
+ // The original the compressor set aside, between the stored form landing
+ // and the original's removal (`.transcript.live_chat.json.retire-<pid>`):
+ // the next run removes it, or renames it back when it is the only copy.
+ /\.retire-\d+(?:-[0-9a-z]+)?$/,
];
export function isScratchEntry(name: string): boolean {
@@ -98,7 +146,9 @@ export function classifyEntry(name: string): MediaTierKind {
if (
isRealAudioFile(name) ||
isSourceMediaFile(name) ||
- name === LIVE_CHAT_MEDIA_FILENAME
+ name === LIVE_CHAT_MEDIA_FILENAME ||
+ name === LIVE_CHAT_STORED_FILENAME ||
+ isKeptChatCapture(name)
) {
return "media";
}
@@ -114,7 +164,12 @@ export function classifyEntry(name: string): MediaTierKind {
// - `audio.*.part` stays real: it is yt-dlp's resumable partial, which yt-dlp
// appends to and renames.
export function isTierable(name: string): boolean {
- return isRealAudioFile(name) || name === LIVE_CHAT_MEDIA_FILENAME;
+ return (
+ isRealAudioFile(name) ||
+ name === LIVE_CHAT_MEDIA_FILENAME ||
+ name === LIVE_CHAT_STORED_FILENAME ||
+ isKeptChatCapture(name)
+ );
}
export type ClassifiedVideoDir = {
diff --git a/common/lib/sidecar-server.test.ts b/common/lib/sidecar-server.test.ts
@@ -87,6 +87,13 @@ test("sidecar() refuses a transcript.<x>.<y> name at declaration", () => {
assert.throws(() => sidecar("a/b.json", sidecarField((v) => v)), /bare filename/);
});
+test("sidecar() refuses a declared stored-text name's stored form (it would be read as the chat)", () => {
+ assert.throws(
+ () => sidecar("transcript.live_chat.json.zst", sidecarField((v) => v)),
+ /stored form of transcript\.live_chat\.json/,
+ );
+});
+
test("absent, unparseable and coercion-rejected all load as null", async () => {
const dir = await scratch();
assert.equal(await loadAvailability(dir), null);
diff --git a/common/lib/sidecar-server.ts b/common/lib/sidecar-server.ts
@@ -32,6 +32,7 @@ import path from "node:path";
import { rm } from "node:fs/promises";
import { z } from "zod";
import { SUB_FILE_RE } from "./videoStatus";
+import { plainNameOf } from "./storedText";
import {
readJsonFile,
writeJsonAtomic,
@@ -74,6 +75,13 @@ export function sidecar<T>(
`Sidecar "${filename}" matches SUB_FILE_RE (transcript.<x>.<y>) and would be read as a subtitle track — rename it`,
);
}
+ // A declared stored-text name's stored form (lib/storedText.ts) is read as
+ // that file: a sidecar so named would be read as the live chat.
+ if (plainNameOf(filename) !== null) {
+ throw new Error(
+ `Sidecar "${filename}" is the stored form of ${plainNameOf(filename)} and would be read as it — rename it`,
+ );
+ }
if (filename.includes("/") || filename.includes(path.sep)) {
throw new Error(`Sidecar "${filename}" must be a bare filename`);
}
diff --git a/common/lib/storedText-server.ts b/common/lib/storedText-server.ts
@@ -0,0 +1,292 @@
+// STORED TEXT ON DISK — THE READ PATH (lib/storedText.ts has the names and
+// the rules). Every reader of a declared name goes through here and accepts
+// either form: the plain file when it is present (the truth), else the stored
+// `<name>.zst`, decompressed. A reader that opens the plain name directly sees
+// a compressed file as ABSENT — which, for the live chat, makes the app fetch
+// it again — and storedText.grep.test.ts fails any such read added outside
+// this module.
+//
+// THE FORMAT: one zstd frame, the content size in its header (the logical size
+// is a few header bytes away) and the content checksum on (a corrupt file
+// throws instead of returning wrong text). Node's zstd does NOT throw on a
+// TRUNCATED frame — it returns what it decoded — so every read here also
+// requires the decoded length to equal the header's content size.
+//
+// SERVER-ONLY.
+
+import path from "node:path";
+import { lstat, open, readdir, readFile, stat } from "node:fs/promises";
+import type { Stats } from "node:fs";
+import zlib from "node:zlib";
+import type { Transform } from "node:stream";
+import {
+ isStoredTextName,
+ logicalEntries,
+ storedNameOf,
+ type StoredForms,
+} from "./storedText";
+
+// Node's zstd, typed here: the workspace's @types/node predates it.
+export type ZstdOptions = {
+ pledgedSrcSize?: number;
+ maxOutputLength?: number;
+ params?: Record<number, number>;
+};
+type ZstdZlib = {
+ zstdDecompress?: (buf: Buffer, opts: ZstdOptions, cb: (err: Error | null, out: Buffer) => void) => void;
+ createZstdCompress?: (opts: ZstdOptions) => Transform;
+ createZstdDecompress?: (opts?: ZstdOptions) => Transform;
+ constants: Record<string, number>;
+};
+const z = zlib as unknown as ZstdZlib;
+
+export function createStoredTextCompressor(size: number): Transform {
+ assertZstdAvailable();
+ return z.createZstdCompress!(storedTextCompressOptions(size));
+}
+
+export function createStoredTextDecompressor(): Transform {
+ assertZstdAvailable();
+ return z.createZstdDecompress!();
+}
+
+// Node's zstd: `zlib.zstdCompress` and friends from Node 22.15.0 (23.8.0).
+// Asked at first use, not at import: a process on an older Node that never
+// meets a stored file keeps working, and one that does gets this sentence.
+export function assertZstdAvailable(): void {
+ if (
+ typeof z.zstdDecompress !== "function" ||
+ typeof z.createZstdCompress !== "function" ||
+ typeof z.createZstdDecompress !== "function"
+ ) {
+ throw new Error(
+ `stored text needs node:zlib zstd — Node >= 22.15 (this is ${process.version})`,
+ );
+ }
+}
+
+export const STORED_TEXT_LEVEL = 9;
+
+// The compressor's options for a source of `size` bytes: level 9, checksum on,
+// the size pledged so it lands in the frame header.
+export function storedTextCompressOptions(size: number): ZstdOptions {
+ assertZstdAvailable();
+ const c = z.constants;
+ return {
+ pledgedSrcSize: size,
+ params: {
+ [c.ZSTD_c_compressionLevel]: STORED_TEXT_LEVEL,
+ [c.ZSTD_c_checksumFlag]: 1,
+ [c.ZSTD_c_contentSizeFlag]: 1,
+ },
+ };
+}
+
+const ZSTD_MAGIC = 0xfd2fb528;
+
+// The content size a zstd frame header declares, or null when the bytes are
+// not a frame header that carries one. `head` needs at most 18 bytes.
+export function frameContentSize(head: Uint8Array): number | null {
+ if (head.length < 5) return null;
+ const dv = new DataView(head.buffer, head.byteOffset, head.byteLength);
+ if (dv.getUint32(0, true) !== ZSTD_MAGIC) return null;
+ const fhd = head[4];
+ const fcsFlag = fhd >> 6;
+ const singleSegment = (fhd >> 5) & 1;
+ const dictFlag = fhd & 3;
+ if (fcsFlag === 0 && !singleSegment) return null; // size not recorded
+ let off = 5 + (singleSegment ? 0 : 1) + [0, 1, 2, 4][dictFlag];
+ const fcsBytes = fcsFlag === 0 ? 1 : [1, 2, 4, 8][fcsFlag];
+ if (head.length < off + fcsBytes) return null;
+ switch (fcsBytes) {
+ case 1:
+ return head[off];
+ case 2:
+ return dv.getUint16(off, true) + 256;
+ case 4:
+ return dv.getUint32(off, true);
+ default: {
+ const lo = dv.getUint32(off, true);
+ const hi = dv.getUint32(off + 4, true);
+ const n = hi * 2 ** 32 + lo;
+ return Number.isSafeInteger(n) ? n : null;
+ }
+ }
+}
+
+// One whole buffer as a stored frame (the compressor streams; this is for a
+// small file and for tests' fixtures).
+export async function encodeStoredBytes(bytes: Buffer): Promise<Buffer> {
+ const c = createStoredTextCompressor(bytes.length);
+ const out: Buffer[] = [];
+ c.on("data", (d: Buffer) => out.push(d));
+ const done = new Promise<void>((resolve, reject) => {
+ c.on("end", () => resolve());
+ c.on("error", reject);
+ });
+ c.end(bytes);
+ await done;
+ return Buffer.concat(out);
+}
+
+export class StoredTextCorruptError extends Error {
+ constructor(file: string, why: string) {
+ super(`${file}: not a whole stored-text frame (${why})`);
+ this.name = "StoredTextCorruptError";
+ }
+}
+
+// A stored file's bytes, decoded and checked: the frame's checksum (zstd
+// throws), and the decoded length against the header's content size (a
+// truncated frame decodes short without an error).
+export async function decodeStoredBytes(bytes: Buffer, label = "stored text"): Promise<Buffer> {
+ assertZstdAvailable();
+ const want = frameContentSize(bytes.subarray(0, 18));
+ if (want === null) throw new StoredTextCorruptError(label, "no content size in the frame header");
+ let out: Buffer;
+ try {
+ out = await new Promise<Buffer>((resolve, reject) =>
+ z.zstdDecompress!(bytes, { maxOutputLength: Math.max(1, want + 1) }, (err, res) =>
+ err ? reject(err) : resolve(res),
+ ),
+ );
+ } catch (err) {
+ throw new StoredTextCorruptError(label, (err as Error).message);
+ }
+ if (out.length !== want) {
+ throw new StoredTextCorruptError(label, `decoded ${out.length} bytes, header says ${want}`);
+ }
+ return out;
+}
+
+function isEnoent(err: unknown): boolean {
+ const code = (err as NodeJS.ErrnoException | null)?.code;
+ return code === "ENOENT" || code === "ENOTDIR";
+}
+
+function enoent(dir: string, name: string): NodeJS.ErrnoException {
+ const err = new Error(`ENOENT: no such file, '${path.join(dir, name)}' (nor its stored form)`) as NodeJS.ErrnoException;
+ err.code = "ENOENT";
+ return err;
+}
+
+// THE READ: the plain file's bytes when it opens; else (a declared name) the
+// stored form, decoded. A plain name that is a dangling link (an interrupted
+// removal, a drive not mounted) does not open, so the stored form is read;
+// when neither opens, ENOENT.
+export async function readStoredText(dir: string, name: string): Promise<Buffer>;
+export async function readStoredText(dir: string, name: string, encoding: "utf8"): Promise<string>;
+export async function readStoredText(
+ dir: string,
+ name: string,
+ encoding?: "utf8",
+): Promise<Buffer | string> {
+ try {
+ return encoding ? await readFile(path.join(dir, name), encoding) : await readFile(path.join(dir, name));
+ } catch (err) {
+ if (!isEnoent(err) || !isStoredTextName(name)) throw err;
+ }
+ const storedPath = path.join(dir, storedNameOf(name));
+ let bytes: Buffer;
+ try {
+ bytes = await readFile(storedPath);
+ } catch (err) {
+ if (isEnoent(err)) throw enoent(dir, name);
+ throw err;
+ }
+ const out = await decodeStoredBytes(bytes, storedPath);
+ return encoding ? out.toString(encoding) : out;
+}
+
+export type StoredTextStat = {
+ // Which form answered.
+ form: "plain" | "zst";
+ // The path that was stat'ed.
+ file: string;
+ stats: Stats;
+};
+
+// THE STAT a freshness or change check asks: of the plain name when it is
+// there, else of the stored form — which carries the plain file's times
+// exactly (the compressor sets them, numeric seconds), so the answer's
+// `mtimeMs` is the SAME number either way. `link: true` is `lstat` (a tiered
+// name is asked on the corpus disk, never on the media drive); otherwise
+// `stat`, where a dangling plain link falls through to the stored form.
+export async function statStoredText(
+ dir: string,
+ name: string,
+ opts: { link?: boolean } = {},
+): Promise<StoredTextStat> {
+ const ask = opts.link ? lstat : stat;
+ const plain = path.join(dir, name);
+ try {
+ return { form: "plain", file: plain, stats: await ask(plain) };
+ } catch (err) {
+ if (!isEnoent(err) || !isStoredTextName(name)) throw err;
+ }
+ const stored = path.join(dir, storedNameOf(name));
+ try {
+ return { form: "zst", file: stored, stats: await ask(stored) };
+ } catch (err) {
+ if (isEnoent(err)) throw enoent(dir, name);
+ throw err;
+ }
+}
+
+// The `mtimeMs` of `statStoredText`, or null when neither form answers.
+export async function storedTextMtimeMs(
+ dir: string,
+ name: string,
+ opts: { link?: boolean } = {},
+): Promise<number | null> {
+ try {
+ return (await statStoredText(dir, name, opts)).stats.mtimeMs;
+ } catch {
+ return null;
+ }
+}
+
+// Is `name` here in either form? An `lstat` — what a listing would say: a
+// dangling link is an entry (a drive that is not mounted is not an empty dir).
+export async function storedTextExists(dir: string, name: string): Promise<boolean> {
+ try {
+ await statStoredText(dir, name, { link: true });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// Which forms are present, by `lstat` of each.
+export async function storedTextForms(dir: string, name: string): Promise<StoredForms | null> {
+ const here = (n: string) => lstat(path.join(dir, n)).then(() => true, () => false);
+ const plain = await here(name);
+ const zst = isStoredTextName(name) ? await here(storedNameOf(name)) : false;
+ if (plain && zst) return "both";
+ if (plain) return "plain";
+ if (zst) return "zst";
+ return null;
+}
+
+// The LOGICAL size: the plain file's, or the content size the stored frame's
+// header declares (18 bytes read, nothing decompressed). Follows links.
+export async function storedTextLogicalSize(dir: string, name: string): Promise<number> {
+ const s = await statStoredText(dir, name);
+ if (s.form === "plain") return s.stats.size;
+ const fh = await open(s.file, "r");
+ try {
+ const head = Buffer.alloc(18);
+ const { bytesRead } = await fh.read(head, 0, 18, 0);
+ const n = frameContentSize(head.subarray(0, bytesRead));
+ if (n === null) throw new StoredTextCorruptError(s.file, "no content size in the frame header");
+ return n;
+ } finally {
+ await fh.close();
+ }
+}
+
+// A MATCHING listing of a dir: readdir, each declared `X.zst` reported as `X`.
+// A missing dir lists nothing.
+export async function readdirLogical(dir: string): Promise<string[]> {
+ return logicalEntries(await readdir(dir).catch(() => [] as string[]));
+}
diff --git a/common/lib/storedText-write-server.ts b/common/lib/storedText-write-server.ts
@@ -0,0 +1,1400 @@
+// STORED TEXT ON DISK — THE WRITE HALF: the one way to delete a declared name
+// (`removeStoredText`), the compressor (`compressStoredText`) and its checker
+// (`verifyStoredText`). The names and the rules are lib/storedText.ts; the
+// read path is lib/storedText-server.ts.
+//
+// THE ONE WAY TO DELETE A DECLARED NAME. A deleter that removed only the plain
+// `transcript.live_chat.json` would RESURRECT an older stored
+// `transcript.live_chat.json.zst` beside it — the one failure here that is
+// silent and wrong. So every deleter of a declared name calls
+// `removeStoredText`, which removes both forms, each through
+// `removeMediaFile` (a tier link's bytes go too). The stored form goes FIRST:
+// a process killed between the two leaves the plain file — the truth — never
+// the older stored copy alone.
+//
+// lib/, so no controller import (architecture.test.ts). SERVER-ONLY.
+
+import path from "node:path";
+import { createHash } from "node:crypto";
+import { createReadStream, readFileSync, type Stats } from "node:fs";
+import {
+ link,
+ lstat,
+ lutimes,
+ open,
+ readdir,
+ readFile,
+ readlink,
+ rename,
+ rm,
+ stat,
+ statfs,
+ symlink,
+ utimes,
+ writeFile,
+} from "node:fs/promises";
+import { Transform, Writable } from "node:stream";
+import { pipeline } from "node:stream/promises";
+import {
+ MEDIA_LINK_NAME,
+ TIER_RELOCATION_MARKER,
+ removeMediaFile,
+ renameMediaFile,
+ tierMediaFile,
+} from "./mediaTier-server";
+import { keptChatCaptureName } from "./mediaTier";
+import { onDrive, stalledLocationForPath } from "./storageHealth";
+import { LIVE_RECORDING_FILENAME } from "./liveCapture";
+import { isStoredTextName, plainNameOf, storedNameOf } from "./storedText";
+import {
+ StoredTextCorruptError,
+ createStoredTextCompressor,
+ createStoredTextDecompressor,
+ frameContentSize,
+} from "./storedText-server";
+
+// Remove `name` in both forms (any name: for one that is not declared, its
+// `.zst` sibling is not this module's and is removed only if it is there —
+// nothing else ever writes one). Missing is not an error.
+export async function removeStoredText(videoDir: string, name: string): Promise<void> {
+ await removeMediaFile(videoDir, storedNameOf(name));
+ await removeMediaFile(videoDir, name);
+}
+
+// ── THE COMPRESSOR ──────────────────────────────────────────────────────────
+//
+// `compressStoredText(videoDir, name)` puts ONE declared file into its stored
+// form, where its bytes are (never across disks): for a tier link
+// `data/<id>/<name> -> ../../media/<id>/<name>` the work happens in
+// `media/<id>/` and the stored form gets a tier link of its own; for a real
+// file, in `data/<id>/`. No `mkdir` anywhere: the work dir holds the file, so
+// a destination on an unmounted drive is never materialised.
+//
+// 1. S (the bytes) is streamed through sha256 and zstd (level 9, checksum,
+// the size pledged) into a temp T opened `wx`; T is fsynced.
+// 2. T is streamed back through the decompressor: sha256 and length must
+// equal S's, and S must be unchanged (inode, size, mtime) — else T goes.
+// 3. T is given S's times (numeric seconds) and renamed to Z (`<name>.zst`);
+// the dir is fsynced. Z ONLY EVER APPEARS BY THE RENAME OF A VERIFIED,
+// FSYNCED T: a partial stored file can only be a temp, never Z.
+// 4. Tiered: Z's link is placed (made beside, renamed in) with the plain
+// link's own times — what an `lstat` of the name answered before.
+// 5. P (the plain name) is set aside (`.<name>.retire-<pid>`), checked to be
+// the very file of step 1, and removed through `removeMediaFile`. A
+// writer that replaced P meanwhile is put back: outcome `changed`.
+// 6. A real Z on a channel with a media tier is tiered by the hook.
+//
+// A RUN AFTER A KILL AT ANY STEP finishes or undoes it: a dead run's temp is
+// discarded; a Z beside P is verified against P before P goes; a retired P
+// whose name is free is renamed back (and then verified like any P); a
+// dangling P beside a whole Z is removed. BOTH FORMS PRESENT WITH DIFFERENT
+// CONTENT is refused and reported — nothing is touched, and readers keep
+// reading the plain one.
+//
+// A LEFTOVER IS DEAD unless the process that named it is running NOW: its
+// name carries the pid and that process's START TOKEN (boot id + start time,
+// `processStartToken`), so a pid reused by a later process — an editor
+// container that comes back with the same pid — does not keep a dead run's
+// set-aside alive. A leftover named with THIS process's pid is dead too: the
+// per-file lock below means no run of ours is on this file at this moment.
+//
+// A WRITER THAT REPLACED P DURING A RUN (`changed`): the new P is the truth
+// and is read; the stored form beside it holds the earlier content and is
+// KEPT. Two captures with different content are never settled by deleting
+// one (REVIEW-2 R1): the pair is `both-differ`, for a person.
+
+export type CompressSkipReason =
+ | "not-declared"
+ | "relocating" // the channel's media is moving (its marker stands)
+ | "partial" // a `<name>.part…` beside it: a capture or download in progress
+ | "recording" // the video's live-recording.json says `recording` (or cannot be read)
+ | "busy" // a job is running for this video, or this file is being compressed
+ | "recent" // written within the quiet period
+ | "unreachable" // on a media drive that is not mounted or not answering
+ | "dangling" // a plain link whose bytes are gone, and no stored form
+ | "foreign-link" // a link that does not point into this channel's media/
+ | "not-a-file"
+ | "low-space" // the disk that holds it is too full for the temp
+ | "both-differ" // both forms present, different content: refused
+ | "stored-corrupt" // a stored form that does not decode
+ | "retired-kept"; // a set-aside original that is neither the stored content nor free to go back
+
+export type CompressOutcome =
+ | { status: "compressed"; before: number; after: number; tiered: boolean }
+ | { status: "already"; after: number }
+ | { status: "absent" }
+ | { status: "changed" }
+ | { status: "skipped"; reason: CompressSkipReason; detail?: string };
+
+// A test's kill point: `crashAt` throws a CompressKill there, and NOTHING
+// after it runs — no cleanup, no rollback — which is what a SIGKILL leaves.
+export type CompressKillPoint =
+ | "compressing" // T partly written
+ | "written" // T whole and fsynced, not verified
+ | "verified" // T verified, not renamed
+ | "placed" // Z in place (tiered: no link yet)
+ | "linked" // Z's tier link placed
+ | "retired" // P set aside, not removed
+ // The restore (`restoreStoredText`), in its order:
+ | "restoring" // R (the plain temp) partly written
+ | "restore-written" // R whole and fsynced, not verified
+ | "restore-verified" // R verified against a fresh decode of Z, not placed
+ | "restore-placed" // P in place (tiered: in media/<id>/, no link yet)
+ | "restore-linked"; // P's tier link placed; Z not yet removed
+
+export class CompressKill extends Error {
+ constructor(readonly point: CompressKillPoint) {
+ super(`killed at ${point}`);
+ this.name = "CompressKill";
+ }
+}
+
+export type CompressOptions = {
+ // Leave a file younger than this alone (the migration: 10 min). 0 = none.
+ quietMs?: number;
+ now?: () => number;
+ // A job is running for this video (the editor's registry).
+ isBusy?: () => boolean;
+ // Paced reads: awaited before each chunk read moves on.
+ throttle?: (bytes: number) => Promise<void>;
+ // Free space the disk must keep beyond the temp (default 2 GiB).
+ reserveBytes?: number;
+ // The pid and start token temps are named for (tests: a dead pid, to stand
+ // for a kill).
+ pid?: number;
+ token?: string;
+ crashAt?: (point: CompressKillPoint) => void;
+ signal?: AbortSignal;
+ onLog?: (line: string) => void;
+};
+
+type Ident = { dev: number; ino: number; size: number; mtimeMs: number };
+const identOf = (s: Stats): Ident => ({ dev: s.dev, ino: s.ino, size: s.size, mtimeMs: s.mtimeMs });
+const sameIdent = (a: Ident, b: Ident) =>
+ a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs;
+
+function errCode(err: unknown): string | undefined {
+ return (err as NodeJS.ErrnoException | null)?.code;
+}
+
+function processAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (err) {
+ return errCode(err) === "EPERM";
+ }
+}
+
+// ── WHO NAMED A LEFTOVER, AND IS IT STILL RUNNING ───────────────────────────
+//
+// A process's START TOKEN: the kernel's boot id (8 hex) and the process's
+// start time in clock ticks since boot (`/proc/<pid>/stat` field 22), base
+// 36. Two processes that ever had the same pid on this machine have different
+// tokens. Where there is no /proc, this process's token is its time origin and
+// another's is unknown (null).
+function bootIdPrefix(): string {
+ try {
+ return readFileSync("/proc/sys/kernel/random/boot_id", "utf8").replace(/[^0-9a-f]/g, "").slice(0, 8);
+ } catch {
+ return "";
+ }
+}
+
+export function processStartToken(pid: number = process.pid): string | null {
+ try {
+ const s = readFileSync(`/proc/${pid}/stat`, "utf8");
+ // After the command's ")" the fields start at field 3; field 22 is the
+ // start time.
+ const ticks = s.slice(s.lastIndexOf(")") + 2).split(" ")[19];
+ if (ticks && /^\d+$/.test(ticks)) return `${bootIdPrefix()}${Number(ticks).toString(36)}`;
+ } catch {
+ /* no /proc, or the process is gone */
+ }
+ return pid === process.pid ? `t${Math.floor(performance.timeOrigin).toString(36)}` : null;
+}
+
+let ownToken: string | undefined;
+function selfToken(): string {
+ return (ownToken ??= processStartToken(process.pid) ?? "t0");
+}
+
+// A leftover's suffix: `-<pid>-<token>` (a name from before the token,
+// `-<pid>`, is still read).
+const LEFTOVER_SUFFIX = "-(\\d+)(?:-([0-9a-z]+))?";
+
+type Owner = { pid: number; token?: string };
+
+// Is the run that named this leftover running now? Never this process's own
+// (`self`): the per-file lock means none of ours is on the file. Another pid:
+// alive AND (when the name carries a token) the same process start.
+function ownerRunning(owner: Owner, self: number): boolean {
+ if (owner.pid === self) return false;
+ if (!processAlive(owner.pid)) return false;
+ if (owner.token === undefined) return true; // a pid-only name: cannot tell, so alive
+ const now = processStartToken(owner.pid);
+ return now === null || now === owner.token;
+}
+
+function ownerOf(m: RegExpExecArray | null): Owner | null {
+ if (!m) return null;
+ return { pid: Number(m[1]), ...(m[2] ? { token: m[2] } : {}) };
+}
+
+const lstatOrNull = (p: string) => lstat(p).catch(() => null);
+
+async function fsyncDir(dir: string): Promise<void> {
+ const d = await open(dir, "r");
+ try {
+ await d.sync();
+ } finally {
+ await d.close();
+ }
+}
+
+function escapeRe(s: string): string {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+// A paced read: each chunk waits on the throttle before it moves on.
+function paced(throttle?: (bytes: number) => Promise<void>): Transform {
+ return new Transform({
+ transform(chunk: Buffer, _enc, cb) {
+ if (!throttle) return cb(null, chunk);
+ throttle(chunk.length).then(
+ () => cb(null, chunk),
+ (err: Error) => cb(err),
+ );
+ },
+ });
+}
+
+type Digest = { sha: string; bytes: number };
+
+function digestSink(): { sink: Writable; result: () => Digest } {
+ const h = createHash("sha256");
+ let n = 0;
+ const sink = new Writable({
+ write(chunk: Buffer, _enc, cb) {
+ h.update(chunk);
+ n += chunk.length;
+ cb();
+ },
+ });
+ return { sink, result: () => ({ sha: h.digest("hex"), bytes: n }) };
+}
+
+async function headContentSize(file: string): Promise<number | null> {
+ const fh = await open(file, "r");
+ try {
+ const head = Buffer.alloc(18);
+ const { bytesRead } = await fh.read(head, 0, 18, 0);
+ return frameContentSize(head.subarray(0, bytesRead));
+ } finally {
+ await fh.close();
+ }
+}
+
+// sha256 and length of a file's bytes — `decode`: of its stored content, the
+// frame's checksum checked by zstd and the length against the header's
+// content size (which a truncated frame would not reach).
+async function digestOf(
+ file: string,
+ opts: { decode?: boolean; throttle?: (bytes: number) => Promise<void> } = {},
+): Promise<Digest> {
+ const { sink, result } = digestSink();
+ if (!opts.decode) {
+ await pipeline(createReadStream(file), paced(opts.throttle), sink);
+ return result();
+ }
+ const want = await headContentSize(file);
+ if (want === null) throw new StoredTextCorruptError(file, "no content size in the frame header");
+ try {
+ await pipeline(createReadStream(file), paced(opts.throttle), createStoredTextDecompressor(), sink);
+ } catch (err) {
+ if (errCode(err) === "ENOENT") throw err;
+ throw new StoredTextCorruptError(file, (err as Error).message);
+ }
+ const d = result();
+ if (d.bytes !== want) throw new StoredTextCorruptError(file, `decoded ${d.bytes} bytes, header says ${want}`);
+ return d;
+}
+
+// What is at one name in the video dir.
+type Entry =
+ | { kind: "none" }
+ | { kind: "real"; path: string; l: Stats }
+ | { kind: "link"; path: string; l: Stats; target: string; inMedia: boolean }
+ | { kind: "other"; path: string; l: Stats };
+
+async function entryAt(videoDir: string, name: string): Promise<Entry> {
+ const p = path.join(videoDir, name);
+ const l = await lstatOrNull(p);
+ if (!l) return { kind: "none" };
+ if (l.isSymbolicLink()) {
+ let target = "";
+ try {
+ target = path.resolve(videoDir, await readlink(p));
+ } catch {
+ /* unreadable: not in media */
+ }
+ const mediaRoot = path.join(path.dirname(path.dirname(videoDir)), MEDIA_LINK_NAME);
+ return {
+ kind: "link",
+ path: p,
+ l,
+ target,
+ inMedia: !!target && path.dirname(path.dirname(target)) === mediaRoot,
+ };
+ }
+ if (l.isFile()) return { kind: "real", path: p, l };
+ return { kind: "other", path: p, l };
+}
+
+// Whether the channel's media tier answers: a real `media/` (the corpus disk),
+// or a link to a drive that is mounted and not stalled. "none": no `media`.
+async function mediaReachable(channelDir: string): Promise<"yes" | "no" | "none"> {
+ const root = path.join(channelDir, MEDIA_LINK_NAME);
+ const l = await lstatOrNull(root);
+ if (!l) return "none";
+ if (!l.isSymbolicLink()) return l.isDirectory() ? "yes" : "no";
+ let target: string;
+ try {
+ target = path.resolve(channelDir, await readlink(root));
+ } catch {
+ return "no";
+ }
+ if (stalledLocationForPath(target)) return "no";
+ try {
+ return (await onDrive(target, () => stat(root))).isDirectory() ? "yes" : "no";
+ } catch {
+ return "no";
+ }
+}
+
+// A live recording of this video in progress, by its own record — or a record
+// that cannot be read, which is no proof there is none.
+async function recordingNow(videoDir: string): Promise<boolean> {
+ let raw: string;
+ try {
+ raw = await readFile(path.join(videoDir, LIVE_RECORDING_FILENAME), "utf8");
+ } catch (err) {
+ return errCode(err) !== "ENOENT";
+ }
+ try {
+ return (JSON.parse(raw) as { status?: unknown })?.status === "recording";
+ } catch {
+ return true;
+ }
+}
+
+// Where the stored form's bytes are when they are on disk: the name in the
+// video dir as a real file, or the file its link resolves to.
+async function storedPathOf(videoDir: string, name: string): Promise<string | null> {
+ const z = await entryAt(videoDir, storedNameOf(name));
+ if (z.kind === "real") return z.path;
+ if (z.kind === "link" && z.target && (await stat(z.target).then((st) => st.isFile(), () => false))) {
+ return z.target;
+ }
+ return null;
+}
+
+// ONE RUN PER FILE AT A TIME — the compressor, the restore, the re-fetch's
+// set-aside and the files card's delete — in two layers:
+//
+// - IN THIS PROCESS, a set kept on `globalThis` (Next loads a module once
+// per bundle layer; a route and a server action must share it — the
+// storageHealth.ts pattern). Because of it, a leftover named with this
+// process's pid is never a run in progress.
+// - ACROSS PROCESSES, a lock file in the video dir, `.stored-text.lock`
+// (REVIEW-2 R3), made by a hard link of a temp that names its owner (pid
+// and start token), so it appears whole or not at all. A second process
+// honours it: held by a run that is running now, the run answers "busy";
+// held by a process that is gone (or this pid from an earlier start), it
+// is stale and is taken over. Two editors on one corpus are an operator's
+// mistake; this makes them wait for each other instead of interleaving.
+const g = globalThis as { __archilyzerStoredTextActive?: Set<string> };
+const active: Set<string> = (g.__archilyzerStoredTextActive ??= new Set<string>());
+
+export const STORED_TEXT_DIR_LOCK = ".stored-text.lock";
+
+// Is the run that holds a dir lock running now? This process: only when the
+// token is this start's (another of its runs holds the dir).
+function lockHolderRunning(owner: Owner): boolean {
+ if (owner.pid === process.pid) return owner.token === selfToken();
+ return ownerRunning(owner, process.pid);
+}
+
+// The dir lock, or null when a live run holds it. Returns its release.
+async function takeDirLock(videoDir: string): Promise<(() => Promise<void>) | null> {
+ const lock = path.join(videoDir, STORED_TEXT_DIR_LOCK);
+ const me = { pid: process.pid, token: selfToken() };
+ const tmp = path.join(videoDir, `${STORED_TEXT_DIR_LOCK}.${me.pid}-${me.token}-${Math.random().toString(36).slice(2, 8)}`);
+ try {
+ await writeFile(tmp, JSON.stringify(me), { flag: "wx" });
+ } catch (err) {
+ // No video dir: nothing to lock and nothing to do.
+ if (errCode(err) === "ENOENT") return async () => {};
+ throw err;
+ }
+ try {
+ for (let attempt = 0; attempt < 3; attempt++) {
+ try {
+ await link(tmp, lock);
+ const ino = (await lstat(lock)).ino;
+ return async () => {
+ const l = await lstatOrNull(lock);
+ if (l && l.ino === ino) await rm(lock, { force: true });
+ };
+ } catch (err) {
+ if (errCode(err) !== "EEXIST") throw err;
+ }
+ const held = await lstatOrNull(lock);
+ if (!held) continue;
+ let owner: Owner | null = null;
+ try {
+ const o = JSON.parse(await readFile(lock, "utf8")) as { pid?: unknown; token?: unknown };
+ if (typeof o.pid === "number") owner = { pid: o.pid, ...(typeof o.token === "string" ? { token: o.token } : {}) };
+ } catch {
+ /* unreadable: no owner to honour */
+ }
+ if (owner && lockHolderRunning(owner)) return null;
+ // Stale: moved aside, and removed only if it is the very file judged —
+ // another process's fresh lock that took its place goes back.
+ const aside = path.join(videoDir, `${STORED_TEXT_DIR_LOCK}.stale-${me.pid}-${me.token}`);
+ await rename(lock, aside).catch(() => {});
+ const a = await lstatOrNull(aside);
+ if (a && a.ino !== held.ino) {
+ await link(aside, lock).catch(() => {});
+ await rm(aside, { force: true });
+ return null;
+ }
+ await rm(aside, { force: true });
+ }
+ return null;
+ } finally {
+ await rm(tmp, { force: true });
+ }
+}
+
+async function withFileLock<T>(videoDir: string, name: string, busy: T, fn: () => Promise<T>): Promise<T> {
+ const key = path.resolve(videoDir, name);
+ if (active.has(key)) return busy;
+ active.add(key);
+ try {
+ const release = await takeDirLock(videoDir);
+ if (!release) return busy;
+ try {
+ return await fn();
+ } finally {
+ await release();
+ }
+ } finally {
+ active.delete(key);
+ }
+}
+
+export async function compressStoredText(
+ videoDir: string,
+ name: string,
+ opts: CompressOptions = {},
+): Promise<CompressOutcome> {
+ if (!isStoredTextName(name)) return { status: "skipped", reason: "not-declared" };
+ return withFileLock(videoDir, name, { status: "skipped", reason: "busy", detail: "being compressed" } as CompressOutcome, () =>
+ compressOne(videoDir, name, opts),
+ );
+}
+
+// The leftovers a run of the compressor or the restore leaves in a dir, by
+// name: temps (never a copy) and the compressor's set-aside original.
+function leftoverRes(name: string) {
+ const stored = storedNameOf(name);
+ return {
+ // `.X.zst.compressing-…`, `.X.zst.stlink-…`, `.X.restoring-…`, `.X.stlink-…`
+ // — never the tier hook's own `.X.tierlink-<pid>` (REVIEW-2 N2).
+ temp: new RegExp(
+ `^\\.(?:${escapeRe(stored)}\\.(?:compressing|stlink)|${escapeRe(name)}\\.(?:restoring|stlink))${LEFTOVER_SUFFIX}$`,
+ ),
+ retire: new RegExp(`^\\.${escapeRe(name)}\\.retire${LEFTOVER_SUFFIX}$`),
+ };
+}
+
+// Does this listing hold a leftover of a run on `name`? (What the job's
+// survey visits even when neither form is there.)
+export function hasStoredTextLeftover(entries: readonly string[], name: string): boolean {
+ const re = leftoverRes(name);
+ return entries.some((e) => re.temp.test(e) || re.retire.test(e));
+}
+
+type RunCtx = {
+ pid: number;
+ token: string;
+ log: (line: string) => void;
+ reachable: () => Promise<"yes" | "no" | "none">;
+};
+
+function runCtx(videoDir: string, opts: CompressOptions): RunCtx {
+ const channelDir = path.dirname(path.dirname(videoDir));
+ let reach: "yes" | "no" | "none" | undefined;
+ return {
+ pid: opts.pid ?? process.pid,
+ token: opts.token ?? selfToken(),
+ log: opts.onLog ?? (() => {}),
+ reachable: async () => (reach ??= await mediaReachable(channelDir)),
+ };
+}
+
+// Dead runs' temps in `dir` removed — scratch, never a copy.
+async function removeDeadTemps(dir: string, name: string, ctx: RunCtx): Promise<"ok" | "live"> {
+ const re = leftoverRes(name);
+ let live = false;
+ for (const e of await readdir(dir).catch(() => [] as string[])) {
+ const owner = ownerOf(re.temp.exec(e));
+ if (!owner) continue;
+ if (ownerRunning(owner, ctx.pid)) live = true;
+ else await rm(path.join(dir, e), { force: true });
+ }
+ return live ? "live" : "ok";
+}
+
+// REPAIR, BEFORE ANY RUN ON A FILE (the compressor's and the restore's): a dead
+// run's leftovers in the video dir, each finished or undone. A live one of
+// another process: "busy". Null: carry on.
+async function repairLeftovers(
+ videoDir: string,
+ name: string,
+ entries: readonly string[],
+ ctx: RunCtx,
+): Promise<CompressOutcome | null> {
+ const skip = (reason: CompressSkipReason, detail?: string): CompressOutcome => ({
+ status: "skipped",
+ reason,
+ ...(detail ? { detail } : {}),
+ });
+ if ((await removeDeadTemps(videoDir, name, ctx)) === "live") return skip("busy", "another process is on this file");
+ const re = leftoverRes(name);
+ for (const e of entries) {
+ const owner = ownerOf(re.retire.exec(e));
+ if (!owner) continue;
+ if (ownerRunning(owner, ctx.pid)) return skip("busy", "another process is on this file");
+ const r = await entryAt(videoDir, e);
+ if (r.kind === "none") continue;
+ if (r.kind === "link" && (await ctx.reachable()) !== "yes") return skip("unreachable");
+ const p = await entryAt(videoDir, name);
+ if (p.kind === "none") {
+ // The original was set aside and not removed: it is the file again,
+ // and is verified like any plain file.
+ await rename(path.join(videoDir, e), path.join(videoDir, name));
+ ctx.log(` restored ${e} as ${name}`);
+ continue;
+ }
+ if (r.kind === "link" && p.kind === "link" && r.target !== "" && r.target === p.target) {
+ // A second name for the plain file's own bytes (a newer file tiered
+ // over the same target): only the name goes, never the bytes.
+ await rm(path.join(videoDir, e));
+ continue;
+ }
+ // Removed only when it is the stored content exactly; otherwise kept for
+ // a person, with the file left as it is.
+ const z = await storedPathOf(videoDir, name);
+ let removable = false;
+ if (z) {
+ try {
+ const [rd, zd] = await Promise.all([digestOf(path.join(videoDir, e)), digestOf(z, { decode: true })]);
+ removable = rd.sha === zd.sha && rd.bytes === zd.bytes;
+ } catch {
+ removable = false;
+ }
+ }
+ if (!removable) return skip("retired-kept", e);
+ await removeMediaFile(videoDir, e);
+ }
+ return null;
+}
+
+// A plain file in media/<id>/ with no link to it, beside a stored form's
+// bytes there: what a restore killed between placing and linking leaves.
+// Removed when it is the stored content exactly (a copy; the stored form
+// stays whole), else kept for a person.
+async function leftoverPlainInMedia(
+ videoDir: string,
+ name: string,
+ zTarget: string,
+ ctx: RunCtx,
+): Promise<CompressOutcome | null> {
+ const mediaDir = path.dirname(zTarget);
+ if ((await removeDeadTemps(mediaDir, name, ctx)) === "live") {
+ return { status: "skipped", reason: "busy", detail: "another process is on this file" };
+ }
+ const beside = path.join(mediaDir, name);
+ if (!(await lstatOrNull(beside))?.isFile()) return null;
+ const [bd, zd] = await Promise.all([
+ digestOf(beside).catch(() => null),
+ digestOf(zTarget, { decode: true }).catch(() => null),
+ ]);
+ if (bd && zd && bd.sha === zd.sha && bd.bytes === zd.bytes) {
+ await rm(beside);
+ ctx.log(` removed an unlinked copy of ${name} in media/ (a restore that was stopped)`);
+ return null;
+ }
+ return { status: "skipped", reason: "retired-kept", detail: `media/${path.basename(mediaDir)}/${name}` };
+}
+
+async function compressOne(videoDir: string, name: string, opts: CompressOptions): Promise<CompressOutcome> {
+ const ctx = runCtx(videoDir, opts);
+ const { pid, token, log, reachable } = ctx;
+ const crash = (p: CompressKillPoint) => opts.crashAt?.(p);
+ const stored = storedNameOf(name);
+ const channelDir = path.dirname(path.dirname(videoDir));
+ const skip = (reason: CompressSkipReason, detail?: string): CompressOutcome => ({
+ status: "skipped",
+ reason,
+ ...(detail ? { detail } : {}),
+ });
+
+ // ── refusals: nothing is touched ──────────────────────────────────────────
+ if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating");
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ if (entries.some((e) => e.startsWith(`${name}.part`))) return skip("partial");
+ if (await recordingNow(videoDir)) return skip("recording");
+ if (opts.isBusy?.()) return skip("busy");
+
+ // ── repair: a dead run's leftovers in the video dir ───────────────────────
+ const repaired = await repairLeftovers(videoDir, name, entries, ctx);
+ if (repaired) return repaired;
+
+ // ── the plain file ────────────────────────────────────────────────────────
+ const p = await entryAt(videoDir, name);
+ const zEntry = await entryAt(videoDir, stored);
+ if (zEntry.kind === "other") return skip("not-a-file", stored);
+ if (p.kind === "none") {
+ if (zEntry.kind === "none") return { status: "absent" };
+ if (zEntry.kind === "link" && zEntry.inMedia) {
+ if ((await reachable()) !== "yes") return skip("unreachable");
+ // A restore killed after it placed the plain bytes in media/<id>/ and
+ // before their link: a copy of the stored content, which is kept.
+ const left = await leftoverPlainInMedia(videoDir, name, zEntry.target, ctx);
+ if (left) return left;
+ }
+ if (zEntry.kind === "real") await tierMediaFile(videoDir, stored, { onLog: log });
+ const z = await storedPathOf(videoDir, name);
+ return { status: "already", after: z ? ((await stat(z).catch(() => null))?.size ?? 0) : 0 };
+ }
+ if (p.kind === "other") return skip("not-a-file");
+ if (p.kind === "link" && !p.inMedia) return skip("foreign-link");
+ if ((p.kind === "link" || zEntry.kind === "link") && (await reachable()) !== "yes") {
+ return skip("unreachable");
+ }
+
+ let s: Stats;
+ try {
+ s = await stat(p.path);
+ } catch (err) {
+ if (p.kind !== "link" || (errCode(err) !== "ENOENT" && errCode(err) !== "ENOTDIR")) {
+ return skip("unreachable", (err as Error).message);
+ }
+ // A plain link whose bytes are gone, on a media tier that answers (an
+ // interrupted removal): with a whole stored form beside it, only the link
+ // is left to remove.
+ const z = await storedPathOf(videoDir, name);
+ if (!z) return skip("dangling");
+ try {
+ await digestOf(z, { decode: true, throttle: opts.throttle });
+ } catch (e) {
+ return skip("stored-corrupt", (e as Error).message);
+ }
+ await removeMediaFile(videoDir, name);
+ return { status: "already", after: (await stat(z)).size };
+ }
+ if (!s.isFile()) return skip("not-a-file");
+ const now = opts.now ?? Date.now;
+ // The later of mtime and ctime: a backdated mtime (`touch -d`, a copy
+ // that kept its times) is no proof the file is not being written.
+ if (opts.quietMs && now() - Math.max(s.mtimeMs, s.ctimeMs) < opts.quietMs) return skip("recent");
+
+ const tiered = p.kind === "link";
+ const workDir = tiered ? path.dirname(p.target) : videoDir;
+ const bytesPath = tiered ? p.target : p.path;
+ const first = identOf(s);
+
+ if (workDir !== videoDir && (await removeDeadTemps(workDir, name, ctx)) === "live") {
+ return skip("busy", "another process is on this file");
+ }
+
+ // ── the stored form: already there (a run killed after it landed), or made ─
+ let zKind: "none" | "real" | "link" = zEntry.kind;
+ let zPath = await storedPathOf(videoDir, name);
+ if (zKind === "link" && !zPath) {
+ // A stored link whose bytes are gone, on a tier that answers: no copy.
+ await removeMediaFile(videoDir, stored);
+ zKind = "none";
+ }
+ if (zKind === "none" && tiered) {
+ // Placed but not yet linked: the bytes beside the plain file's.
+ const beside = path.join(workDir, stored);
+ if ((await lstatOrNull(beside))?.isFile()) zPath = beside;
+ }
+
+ // The stored file's identity once it is verified (or made): what the
+ // last look before the original goes compares with.
+ let zIdent: Ident | null = null;
+ if (zPath) {
+ let zd: Digest;
+ try {
+ zd = await digestOf(zPath, { decode: true, throttle: opts.throttle });
+ } catch (e) {
+ return skip("stored-corrupt", (e as Error).message);
+ }
+ const sd = await digestOf(bytesPath, { throttle: opts.throttle });
+ if (zd.sha !== sd.sha || zd.bytes !== sd.bytes) {
+ return skip("both-differ", `${name} (${sd.bytes} bytes) and ${stored} (${zd.bytes} bytes) differ`);
+ }
+ // The same content: given the plain file's times, exactly.
+ await utimes(zPath, s.atimeMs / 1000, s.mtimeMs / 1000);
+ zIdent = identOf(await stat(zPath));
+ } else {
+ const free = await statfs(workDir).then(
+ (f) => f.bavail * f.bsize,
+ () => Infinity,
+ );
+ if (free < s.size * 0.3 + (opts.reserveBytes ?? 2 * 1024 ** 3)) return skip("low-space");
+ const made = await makeStored(bytesPath, workDir, stored, s, first, `${pid}-${token}`, opts);
+ if (made !== "ok") return made;
+ zPath = path.join(workDir, stored);
+ zIdent = identOf(await stat(zPath));
+ crash("placed");
+ }
+
+ // ── its tier link ─────────────────────────────────────────────────────────
+ if (tiered && zKind === "none") {
+ const tmpLink = path.join(videoDir, `.${stored}.stlink-${pid}-${token}`);
+ await rm(tmpLink, { force: true });
+ await symlink(path.relative(videoDir, zPath), tmpLink);
+ // The PLAIN LINK's times: what an `lstat` of the name answered.
+ await lutimes(tmpLink, p.l.atimeMs / 1000, p.l.mtimeMs / 1000);
+ await rename(tmpLink, path.join(videoDir, stored));
+ await fsyncDir(videoDir);
+ crash("linked");
+ } else if (tiered && zKind === "link") {
+ await lutimes(path.join(videoDir, stored), p.l.atimeMs / 1000, p.l.mtimeMs / 1000);
+ }
+
+ // ── the original goes: set aside, checked, removed ───────────────────────
+ // A move of this channel's media that began meanwhile (the tier hook's
+ // rule): the original stays — the stored form beside it is the same
+ // content, and the next run finishes.
+ if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating");
+ const retired = `.${name}.retire-${pid}-${token}`;
+ const retiredPath = path.join(videoDir, retired);
+ await rename(p.path, retiredPath);
+ crash("retired");
+ const nowL = await lstatOrNull(retiredPath);
+ const nowS = await stat(retiredPath).catch(() => null);
+ if (!(nowL && nowS && nowL.ino === p.l.ino && sameIdent(identOf(nowS), first))) {
+ // A writer replaced the file after it was read: it is the truth again.
+ let kept = false;
+ if (!(await lstatOrNull(p.path))) {
+ await rename(retiredPath, p.path);
+ } else {
+ // An even newer file is already under the name: what was set aside is
+ // a second name for its bytes (only the name goes), or the stored
+ // content (it goes), or neither — kept, for a person.
+ const r = await entryAt(videoDir, retired);
+ const q = await entryAt(videoDir, name);
+ if (r.kind === "link" && q.kind === "link" && r.target !== "" && r.target === q.target) {
+ await rm(retiredPath);
+ } else {
+ const zd = await digestOf(zPath, { decode: true }).catch(() => null);
+ const rd = await digestOf(retiredPath).catch(() => null);
+ if (zd && rd && zd.sha === rd.sha && zd.bytes === rd.bytes) await removeMediaFile(videoDir, retired);
+ else {
+ kept = true;
+ log(` kept ${retired} beside the newer ${name}: it is neither`);
+ }
+ }
+ }
+ // TWO DIFFERENT CAPTURES ARE NEVER SETTLED BY DELETING ONE (REVIEW-2
+ // R1): the new file under the name is what readers read; the stored form
+ // beside it holds the content it replaced and is KEPT — the pair is
+ // `both-differ` for a person (the files card deletes one named form).
+ void kept;
+ log(` ${name} changed while it was being compressed: the new file is kept and read; the stored copy of the earlier content is kept beside it (both-differ, for a person)`);
+ return { status: "changed" };
+ }
+ // THE STORED FORM, LOOKED AT AGAIN right before the original goes (REVIEW-2
+ // R3): still a regular file, and the very one verified (another process's
+ // run could have replaced or removed it). Otherwise the original goes back.
+ const zNow = await stat(path.join(videoDir, stored)).catch(() => null);
+ if (!zNow || !zNow.isFile() || !zIdent || zNow.ino !== zIdent.ino || zNow.size !== zIdent.size || zNow.dev !== zIdent.dev) {
+ if (!(await lstatOrNull(p.path))) await rename(retiredPath, p.path);
+ log(` ${stored} is not the file that was verified any more: ${name} is left as it was`);
+ return { status: "changed" };
+ }
+ await removeMediaFile(videoDir, retired);
+ await fsyncDir(videoDir);
+ // A writer that landed a new file under the name after the original was
+ // set aside: it is the truth, and the stored copy (the earlier content) is
+ // kept beside it — `changed`, both-differ for a person (REVIEW-2 R1).
+ if (await wholePlainAt(videoDir, name)) {
+ log(` ${name} was written again while it was being compressed: the new file is kept and read; the stored copy of the earlier content is kept beside it`);
+ return { status: "changed" };
+ }
+
+ // ── a real stored file on a channel with a media tier: the hook ───────────
+ let nowTiered = tiered && zKind !== "real";
+ if (!nowTiered) nowTiered = (await tierMediaFile(videoDir, stored, { onLog: log })) === "tiered";
+ const after = (await stat(path.join(videoDir, stored)).catch(() => null))?.size ?? 0;
+ return { status: "compressed", before: s.size, after, tiered: nowTiered };
+}
+
+class ChangedError extends Error {}
+
+// A plain file under the name that opens as a regular file (through its link).
+async function wholePlainAt(videoDir: string, name: string): Promise<boolean> {
+ return stat(path.join(videoDir, name)).then((st) => st.isFile(), () => false);
+}
+
+// Steps 1–3: S → T (verified) → Z. "ok", or the outcome that stops the file.
+async function makeStored(
+ bytesPath: string,
+ workDir: string,
+ stored: string,
+ s: Stats,
+ first: Ident,
+ owner: string, // `<pid>-<token>`
+ opts: CompressOptions,
+): Promise<"ok" | CompressOutcome> {
+ const tmp = path.join(workDir, `.${stored}.compressing-${owner}`);
+ const crash = (p: CompressKillPoint) => opts.crashAt?.(p);
+ try {
+ const fh = await open(tmp, "wx");
+ let written: Digest;
+ try {
+ const h = createHash("sha256");
+ let n = 0;
+ let chunks = 0;
+ const tap = new Transform({
+ transform(chunk: Buffer, _enc, cb) {
+ const go = () => {
+ h.update(chunk);
+ n += chunk.length;
+ cb(null, chunk);
+ };
+ if (!opts.throttle) return go();
+ opts.throttle(chunk.length).then(go, (err: Error) => cb(err));
+ },
+ });
+ const sink = new Writable({
+ write(chunk: Buffer, _enc, cb) {
+ fh.write(chunk).then(
+ () => {
+ chunks += 1;
+ try {
+ if (chunks === 1) crash("compressing");
+ cb();
+ } catch (err) {
+ cb(err as Error);
+ }
+ },
+ (err: Error) => cb(err),
+ );
+ },
+ });
+ await pipeline(
+ createReadStream(bytesPath),
+ tap,
+ createStoredTextCompressor(s.size),
+ sink,
+ ...(opts.signal ? [{ signal: opts.signal }] : []),
+ );
+ await fh.sync();
+ written = { sha: h.digest("hex"), bytes: n };
+ } finally {
+ await fh.close().catch(() => {});
+ }
+ crash("written");
+ if (written.bytes !== s.size) throw new ChangedError();
+ const back = await digestOf(tmp, { decode: true });
+ if (back.sha !== written.sha || back.bytes !== written.bytes) {
+ throw new Error(`the stored copy of ${path.basename(bytesPath)} did not read back the same`);
+ }
+ if (!sameIdent(identOf(await stat(bytesPath)), first)) throw new ChangedError();
+ crash("verified");
+ await utimes(tmp, s.atimeMs / 1000, s.mtimeMs / 1000);
+ await rename(tmp, path.join(workDir, stored));
+ await fsyncDir(workDir);
+ return "ok";
+ } catch (err) {
+ if (err instanceof CompressKill) throw err;
+ await rm(tmp, { force: true }).catch(() => {});
+ if (err instanceof ChangedError) return { status: "changed" };
+ // A writer meanwhile (zstd refuses a source whose size moved off the
+ // pledge) is a change, not a failure.
+ const again = await stat(bytesPath).catch(() => null);
+ if (!again || !sameIdent(identOf(again), first)) return { status: "changed" };
+ throw err;
+ }
+}
+
+// ── THE CHECK ───────────────────────────────────────────────────────────────
+// `compress-text {verify: true}`: every stored file decoded in full (its
+// checksum, its length), and against the plain file when both are present.
+// Writes nothing.
+export type VerifyOutcome =
+ | { status: "ok"; bytes: number }
+ | { status: "plain-only" }
+ | { status: "absent" }
+ | { status: "unreachable" }
+ | { status: "corrupt"; detail: string }
+ | { status: "differs" };
+
+export async function verifyStoredText(
+ videoDir: string,
+ name: string,
+ opts: { throttle?: (bytes: number) => Promise<void> } = {},
+): Promise<VerifyOutcome> {
+ const zEntry = await entryAt(videoDir, storedNameOf(name));
+ const plainHere = !!(await lstatOrNull(path.join(videoDir, name)));
+ if (zEntry.kind === "none") return { status: plainHere ? "plain-only" : "absent" };
+ const z = await storedPathOf(videoDir, name);
+ if (!z) return { status: "unreachable" };
+ let zd: Digest;
+ try {
+ zd = await digestOf(z, { decode: true, throttle: opts.throttle });
+ } catch (err) {
+ return { status: "corrupt", detail: (err as Error).message };
+ }
+ if (plainHere) {
+ const pd = await digestOf(path.join(videoDir, name), { throttle: opts.throttle }).catch(() => null);
+ if (pd && (pd.sha !== zd.sha || pd.bytes !== zd.bytes)) return { status: "differs" };
+ }
+ return { status: "ok", bytes: zd.bytes };
+}
+
+// ── THE RESTORE ─────────────────────────────────────────────────────────────
+//
+// `restoreStoredText(videoDir, name)` puts ONE stored file back into its plain
+// form — the compressor in reverse, for a rollback (OPERATING.md: restore
+// BEFORE reverting or running an older checkout, which cannot read a `.zst`).
+// Where the bytes are, never across disks, no `mkdir`:
+//
+// 1. Z is decoded into a temp R (`.<name>.restoring-<pid>-<token>`, `wx`,
+// in the dir that holds Z's bytes) through sha256; R is fsynced, and its
+// length must be the frame header's content size.
+// 2. R is read back from disk through sha256 and must equal a FRESH decode
+// of Z (a second read of Z, not the first stream), and Z must be
+// unchanged (inode, size, mtime).
+// 3. R is given Z's times (numeric seconds: Z carries the original's) and
+// linked to P with no clobber (`link`: a P that appeared meanwhile is
+// never replaced), R's name removed, the dir fsynced.
+// 4. Tiered: P's link is placed with Z's link's own times (the name's
+// `lstat` answers what it did), no clobber, the dir fsynced.
+// 5. Z goes, through `removeMediaFile` (its link and its bytes).
+//
+// A kill at any step leaves Z whole and untouched until step 5, and from step
+// 3 on a whole P beside it with the same content; the next run (a restore, or
+// a compress) finishes from either. Plain beside stored with the same content
+// is finished by removing Z; with different content it is refused.
+
+export type RestoreOutcome =
+ | { status: "restored"; before: number; after: number; tiered: boolean }
+ | { status: "already" } // the plain form only
+ | { status: "absent" }
+ | { status: "changed" }
+ | { status: "skipped"; reason: CompressSkipReason; detail?: string };
+
+export async function restoreStoredText(
+ videoDir: string,
+ name: string,
+ opts: CompressOptions = {},
+): Promise<RestoreOutcome> {
+ if (!isStoredTextName(name)) return { status: "skipped", reason: "not-declared" };
+ return withFileLock(videoDir, name, { status: "skipped", reason: "busy", detail: "being compressed or restored" } as RestoreOutcome, () =>
+ restoreOne(videoDir, name, opts),
+ );
+}
+
+async function restoreOne(videoDir: string, name: string, opts: CompressOptions): Promise<RestoreOutcome> {
+ const ctx = runCtx(videoDir, opts);
+ const { pid, token, log, reachable } = ctx;
+ const crash = (p: CompressKillPoint) => opts.crashAt?.(p);
+ const stored = storedNameOf(name);
+ const channelDir = path.dirname(path.dirname(videoDir));
+ const skip = (reason: CompressSkipReason, detail?: string): RestoreOutcome => ({
+ status: "skipped",
+ reason,
+ ...(detail ? { detail } : {}),
+ });
+
+ if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating");
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ if (entries.some((e) => e.startsWith(`${name}.part`))) return skip("partial");
+ if (await recordingNow(videoDir)) return skip("recording");
+ if (opts.isBusy?.()) return skip("busy");
+ const repaired = await repairLeftovers(videoDir, name, entries, ctx);
+ if (repaired) return repaired as RestoreOutcome;
+
+ const z = await entryAt(videoDir, stored);
+ let p = await entryAt(videoDir, name);
+ if (z.kind === "none") return p.kind === "none" ? { status: "absent" } : { status: "already" };
+ if (z.kind === "other") return skip("not-a-file", stored);
+ if (z.kind === "link" && !z.inMedia) return skip("foreign-link", stored);
+ if (p.kind === "other") return skip("not-a-file");
+ if ((z.kind === "link" || p.kind === "link") && (await reachable()) !== "yes") return skip("unreachable");
+ const zPath = await storedPathOf(videoDir, name);
+
+ // A plain link whose bytes are gone (a compress stopped inside the
+ // original's removal): with a whole stored form, the link goes and the
+ // restore proceeds.
+ if (p.kind === "link" && !(await stat(p.path).then((st) => st.isFile(), () => false))) {
+ if (!zPath) return skip("dangling");
+ try {
+ await digestOf(zPath, { decode: true });
+ } catch (e) {
+ return skip("stored-corrupt", (e as Error).message);
+ }
+ await removeMediaFile(videoDir, name);
+ p = { kind: "none" };
+ }
+ if (!zPath) {
+ // A stored link whose bytes are gone: with a plain file, only the link.
+ if (p.kind === "none") return skip("dangling", stored);
+ await removeMediaFile(videoDir, stored);
+ return { status: "already" };
+ }
+
+ let zd: Digest;
+ try {
+ zd = await digestOf(zPath, { decode: true, throttle: opts.throttle });
+ } catch (e) {
+ return skip("stored-corrupt", (e as Error).message);
+ }
+ const zStat = await stat(zPath);
+ const zFirst = identOf(zStat);
+ const tiered = z.kind === "link";
+ const workDir = tiered ? path.dirname(zPath) : videoDir;
+
+ // ── both forms: the plain one is a whole copy, or it is not ───────────────
+ if (p.kind !== "none") {
+ const pd = await digestOf(p.path, { throttle: opts.throttle }).catch(() => null);
+ if (!pd || pd.sha !== zd.sha || pd.bytes !== zd.bytes) {
+ return skip("both-differ", `${name} and ${stored} differ`);
+ }
+ if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating");
+ if (!(await plainStillWhole(videoDir, name, zd, null))) {
+ log(` ${name} is not a whole copy of ${stored} any more: the stored file is kept`);
+ return { status: "changed" };
+ }
+ await removeMediaFile(videoDir, stored);
+ await fsyncDir(videoDir);
+ return { status: "restored", before: zStat.size, after: zd.bytes, tiered: p.kind === "link" };
+ }
+
+ if (tiered && (await removeDeadTemps(workDir, name, ctx)) === "live") {
+ return skip("busy", "another process is on this file");
+ }
+ const placed = path.join(workDir, name);
+ const besideL = tiered ? await lstatOrNull(placed) : null;
+ if (besideL && !besideL.isFile()) return skip("not-a-file", `media/${path.basename(workDir)}/${name}`);
+ if (besideL) {
+ // Placed by a run that was stopped before its link: verified, then linked.
+ const bd = await digestOf(placed, { throttle: opts.throttle }).catch(() => null);
+ if (!bd || bd.sha !== zd.sha || bd.bytes !== zd.bytes) {
+ return skip("both-differ", `media/${path.basename(workDir)}/${name} and ${stored} differ`);
+ }
+ } else {
+ const free = await statfs(workDir).then(
+ (f) => f.bavail * f.bsize,
+ () => Infinity,
+ );
+ if (free < zd.bytes + (opts.reserveBytes ?? 2 * 1024 ** 3)) return skip("low-space");
+ const made = await makePlain(zPath, workDir, name, zStat, zFirst, zd, `${pid}-${token}`, opts);
+ if (made !== "ok") return made;
+ crash("restore-placed");
+ }
+
+ // ── its tier link ─────────────────────────────────────────────────────────
+ if (tiered) {
+ const tmpLink = path.join(videoDir, `.${name}.stlink-${pid}-${token}`);
+ await rm(tmpLink, { force: true });
+ await symlink(path.relative(videoDir, placed), tmpLink);
+ await lutimes(tmpLink, z.l.atimeMs / 1000, z.l.mtimeMs / 1000);
+ try {
+ // No clobber: a link to the symlink itself, then the temp name goes.
+ await link(tmpLink, path.join(videoDir, name));
+ } catch (err) {
+ await rm(tmpLink, { force: true });
+ if (errCode(err) !== "EEXIST") throw err;
+ // A writer put a plain file here meanwhile: it is the truth. The copy
+ // this run placed goes — unless the new name resolves to it (the tier
+ // hook moved the writer's bytes over that same target, REVIEW-2 N3);
+ // the stored form is the next run's to settle.
+ const [nowName, nowPlaced] = await Promise.all([
+ stat(path.join(videoDir, name)).catch(() => null),
+ stat(placed).catch(() => null),
+ ]);
+ if (!(nowName && nowPlaced && nowName.ino === nowPlaced.ino && nowName.dev === nowPlaced.dev)) {
+ await rm(placed, { force: true });
+ }
+ log(` ${name} appeared while it was being restored: the new file is kept`);
+ return { status: "changed" };
+ }
+ await rm(tmpLink, { force: true });
+ await fsyncDir(videoDir);
+ crash("restore-linked");
+ }
+
+ // ── the stored form goes ──────────────────────────────────────────────────
+ if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating");
+ // THE PLAIN FILE, LOOKED AT AGAIN right before (REVIEW-2 R3): there, a
+ // regular file (through the expected link), its size and hash those of a
+ // fresh decode. Otherwise the stored form stays.
+ if (!(await plainStillWhole(videoDir, name, zd, tiered ? placed : null))) {
+ log(` ${name} is not a whole copy of ${stored} any more: the stored file is kept`);
+ return { status: "changed" };
+ }
+ await removeMediaFile(videoDir, stored);
+ await fsyncDir(videoDir);
+ // A real plain file on a channel with a media tier: the hook, as the
+ // compressor does for its output (REVIEW-2 N6).
+ const nowTiered = tiered || (await tierMediaFile(videoDir, name, { onLog: log })) === "tiered";
+ return { status: "restored", before: zStat.size, after: zd.bytes, tiered: nowTiered };
+}
+
+// Is the plain file here a whole copy of the stored content `zd`? A regular
+// file (a link must resolve to `expected` when given), of its size, with its
+// hash. Read in full: this is the last look before a stored copy goes.
+async function plainStillWhole(videoDir: string, name: string, zd: Digest, expected: string | null): Promise<boolean> {
+ const file = path.join(videoDir, name);
+ const st = await stat(file).catch(() => null);
+ if (!st || !st.isFile() || st.size !== zd.bytes) return false;
+ if (expected) {
+ const ex = await stat(expected).catch(() => null);
+ if (!ex || ex.ino !== st.ino || ex.dev !== st.dev) return false;
+ }
+ const d = await digestOf(file).catch(() => null);
+ return !!d && d.sha === zd.sha && d.bytes === zd.bytes;
+}
+
+// Steps 1–3 of the restore: Z → R (verified) → P. "ok", or the outcome that
+// stops the file.
+async function makePlain(
+ zPath: string,
+ workDir: string,
+ name: string,
+ zStat: Stats,
+ zFirst: Ident,
+ zd: Digest,
+ owner: string,
+ opts: CompressOptions,
+): Promise<"ok" | RestoreOutcome> {
+ const tmp = path.join(workDir, `.${name}.restoring-${owner}`);
+ const crash = (p: CompressKillPoint) => opts.crashAt?.(p);
+ try {
+ const fh = await open(tmp, "wx");
+ const { sink: hashSink, result } = digestSink();
+ try {
+ let chunks = 0;
+ const sink = new Writable({
+ write(chunk: Buffer, _enc, cb) {
+ fh.write(chunk).then(
+ () => {
+ hashSink.write(chunk);
+ chunks += 1;
+ try {
+ if (chunks === 1) crash("restoring");
+ cb();
+ } catch (err) {
+ cb(err as Error);
+ }
+ },
+ (err: Error) => cb(err),
+ );
+ },
+ });
+ await pipeline(
+ createReadStream(zPath),
+ paced(opts.throttle),
+ createStoredTextDecompressor(),
+ sink,
+ ...(opts.signal ? [{ signal: opts.signal }] : []),
+ );
+ await fh.sync();
+ } finally {
+ await fh.close().catch(() => {});
+ }
+ const written = result();
+ crash("restore-written");
+ if (written.bytes !== zd.bytes || written.sha !== zd.sha) {
+ throw new Error(`the plain copy of ${name} did not decode the same as before`);
+ }
+ // R from disk against a FRESH decode of Z.
+ const [back, fresh] = await Promise.all([
+ digestOf(tmp, { throttle: opts.throttle }),
+ digestOf(zPath, { decode: true, throttle: opts.throttle }),
+ ]);
+ if (back.sha !== fresh.sha || back.bytes !== fresh.bytes || back.sha !== zd.sha) {
+ throw new Error(`the plain copy of ${name} did not read back the same as its stored form`);
+ }
+ if (!sameIdent(identOf(await stat(zPath)), zFirst)) throw new ChangedError();
+ crash("restore-verified");
+ await utimes(tmp, zStat.atimeMs / 1000, zStat.mtimeMs / 1000);
+ try {
+ await link(tmp, path.join(workDir, name));
+ } catch (err) {
+ if (errCode(err) === "EEXIST") throw new ChangedError();
+ throw err;
+ }
+ await rm(tmp, { force: true });
+ await fsyncDir(workDir);
+ return "ok";
+ } catch (err) {
+ if (err instanceof CompressKill) throw err;
+ await rm(tmp, { force: true }).catch(() => {});
+ if (err instanceof ChangedError) return { status: "changed" };
+ if (err instanceof StoredTextCorruptError) {
+ return { status: "skipped", reason: "stored-corrupt", detail: err.message };
+ }
+ throw err;
+ }
+}
+
+// ── A DELIBERATE RE-FETCH OVER A STORED CAPTURE: THE EARLIER ONE IS KEPT ──
+//
+// No pass fetches a declared file 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). The one pass that does
+// is a DELIBERATE re-fetch — `fetch-chat {replace: true}` over a chat stored
+// compressed. NOTHING EVER REMOVES A CAPTURE BECAUSE A DIFFERENT ONE ARRIVED
+// (REVIEW-2 R1): a platform's replay is often shorter than the live capture,
+// and the capture cannot be fetched again. So:
+//
+// 1. before the pass, the stored form is RENAMED to a kept name,
+// `chat-capture-kept.<UTC stamp>.json.zst` (lib/mediaTier.ts — no reader
+// of the chat sees it; it travels with the video as media), through
+// `renameMediaFile` (a tier link's bytes are renamed beside themselves);
+// 2. the pass runs; yt-dlp writes the plain name;
+// 3. the caller measures both and decides: a new replay with messages is the
+// chat, and the earlier capture stays kept; nothing landed, a `.part`, a
+// failed pass — the kept capture goes back under the stored name
+// (`putBackKeptCapture`); an EMPTY replay is itself kept under a kept
+// name (`keepPlainAsCapture`: compressed, verified, then its plain name
+// removed) and the earlier capture goes back.
+//
+// Nothing removes a kept capture automatically. `compress-text`'s dry run
+// lists them ("earlier captures kept"); a person deletes one on the files card.
+
+export type KeepOutcome = { kept: string } | { kept: null } | "busy";
+
+// A kept name free in both places it could be (data/<id>/ and, for a tier
+// link, beside its bytes in media/<id>/).
+async function freeKeptName(videoDir: string, besideDir: string | null, at: Date): Promise<string> {
+ for (let n = 0; ; n++) {
+ const k = keptChatCaptureName(at, n);
+ const here = await lstatOrNull(path.join(videoDir, k));
+ const there = besideDir ? await lstatOrNull(path.join(besideDir, k)) : null;
+ if (!here && !there) return k;
+ }
+}
+
+// Step 1: the stored form renamed to a kept name. `{kept: null}`: no stored
+// form here (nothing to keep).
+export async function setAsideStoredText(videoDir: string, name: string, at: Date = new Date()): Promise<KeepOutcome> {
+ if (!isStoredTextName(name)) return { kept: null };
+ return withFileLock<KeepOutcome>(videoDir, name, "busy", async () => {
+ const z = await entryAt(videoDir, storedNameOf(name));
+ if (z.kind === "none") return { kept: null };
+ const kept = await freeKeptName(videoDir, z.kind === "link" && z.inMedia ? path.dirname(z.target) : null, at);
+ await renameMediaFile(videoDir, storedNameOf(name), kept);
+ await fsyncDir(videoDir);
+ return { kept };
+ });
+}
+
+// The kept capture back under the stored name — only when neither form of the
+// name is here (it never replaces anything). False: left where it is.
+export async function putBackKeptCapture(videoDir: string, name: string, kept: string): Promise<boolean | "busy"> {
+ return withFileLock<boolean | "busy">(videoDir, name, "busy", async () => {
+ if ((await lstatOrNull(path.join(videoDir, name))) || (await lstatOrNull(path.join(videoDir, storedNameOf(name))))) {
+ return false;
+ }
+ const k = await entryAt(videoDir, kept);
+ if (k.kind === "none") return false;
+ if (k.kind === "link" && k.inMedia && (await lstatOrNull(path.join(path.dirname(k.target), storedNameOf(name))))) {
+ return false;
+ }
+ await renameMediaFile(videoDir, kept, storedNameOf(name));
+ await fsyncDir(videoDir);
+ return true;
+ });
+}
+
+// The plain file kept as a capture: compressed beside its bytes into a kept
+// name (written, fsynced, decoded back and hashed against it), linked when it
+// is tiered, and only then its plain name removed through removeMediaFile.
+export async function keepPlainAsCapture(
+ videoDir: string,
+ name: string,
+ at: Date = new Date(),
+ opts: CompressOptions = {},
+): Promise<KeepOutcome> {
+ return withFileLock<KeepOutcome>(videoDir, name, "busy", async () => {
+ const p = await entryAt(videoDir, name);
+ if (p.kind !== "real" && !(p.kind === "link" && p.inMedia)) return { kept: null };
+ const tiered = p.kind === "link";
+ const bytesPath = tiered ? p.target : p.path;
+ const workDir = path.dirname(bytesPath);
+ const s = await stat(bytesPath);
+ const kept = await freeKeptName(videoDir, tiered ? workDir : null, at);
+ const ctx = runCtx(videoDir, opts);
+ const made = await makeStored(bytesPath, workDir, kept, s, identOf(s), `${ctx.pid}-${ctx.token}`, opts);
+ if (made !== "ok") return { kept: null };
+ if (tiered) {
+ const tmpLink = path.join(videoDir, `.${kept}.stlink-${ctx.pid}-${ctx.token}`);
+ await rm(tmpLink, { force: true });
+ await symlink(path.relative(videoDir, path.join(workDir, kept)), tmpLink);
+ await rename(tmpLink, path.join(videoDir, kept));
+ await fsyncDir(videoDir);
+ }
+ await removeMediaFile(videoDir, name);
+ await fsyncDir(videoDir);
+ return { kept };
+ });
+}
+
+// ── THE FILES CARD'S DELETE OF ONE NAMED FORM ───────────────────────────────
+//
+// A person deleting `X` or `X.zst` on the files card asked for ONE file: only
+// that one goes, through `removeMediaFile` — never the other form (REVIEW-2
+// R2). When the other is there too, the answer says so and whether it holds
+// the same content (readers still see the chat) or different content (it is
+// what readers read now, or still).
+
+export type RemoveFormOutcome = {
+ removed: string[];
+ kept?: { name: string; same: "same" | "differs" | "unreadable" };
+};
+
+export async function removeStoredTextForm(videoDir: string, filename: string): Promise<RemoveFormOutcome | "busy"> {
+ const plain = plainNameOf(filename) ?? filename;
+ if (!isStoredTextName(plain)) {
+ await removeMediaFile(videoDir, filename);
+ return { removed: [filename] };
+ }
+ return withFileLock<RemoveFormOutcome | "busy">(videoDir, plain, "busy", async () => {
+ const other = filename === plain ? storedNameOf(plain) : plain;
+ if (!(await lstatOrNull(path.join(videoDir, other)))) {
+ await removeMediaFile(videoDir, filename);
+ return { removed: [filename] };
+ }
+ const z = await storedPathOf(videoDir, plain);
+ const [pd, zd] = await Promise.all([
+ digestOf(path.join(videoDir, plain)).catch(() => null),
+ z ? digestOf(z, { decode: true }).catch(() => null) : Promise.resolve(null),
+ ]);
+ const same = !pd || !zd ? "unreadable" : pd.sha === zd.sha && pd.bytes === zd.bytes ? "same" : "differs";
+ await removeMediaFile(videoDir, filename);
+ await fsyncDir(videoDir);
+ return { removed: [filename], kept: { name: other, same } };
+ });
+}
diff --git a/common/lib/storedText.compress.test.ts b/common/lib/storedText.compress.test.ts
@@ -0,0 +1,489 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import {
+ lstat,
+ mkdir,
+ mkdtemp,
+ readdir,
+ readFile,
+ readlink,
+ rename,
+ rm,
+ stat,
+ symlink,
+ utimes,
+ writeFile,
+} from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/storedText.compress.test.ts
+//
+// THE COMPRESSOR (lane text-compress, slice 2) — a DATA-LOSS-SENSITIVE path:
+// it removes originals. Every case is a temp channel tree. The kill points are
+// the compressor's `crashAt` seam: it throws there and nothing after it runs,
+// cleanup included — what a SIGKILL leaves — and the temps carry a pid that is
+// not alive. After each: a reader still gets ONE WHOLE COPY, a leftover
+// partial stored file never counts as the file, and the next run finishes.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "stored-compress-"));
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const {
+ compressStoredText,
+ CompressKill,
+ verifyStoredText,
+} = await import("./storedText-write-server");
+const { readStoredText, statStoredText, readdirLogical, encodeStoredBytes } = await import("./storedText-server");
+
+const CHAT = "transcript.live_chat.json";
+const ZST = `${CHAT}.zst`;
+const DEAD = 999_999_999; // never a live pid
+const KILL_POINTS = ["compressing", "written", "verified", "placed", "linked", "retired"] as const;
+
+// ~1.6 MB of chat lines, varied enough that the stored frame is written in
+// several chunks (so a kill at "compressing" leaves a PARTIAL temp).
+const ORIGINAL = Array.from({ length: 12_000 }, (_, i) =>
+ JSON.stringify({
+ replayChatItemAction: {
+ actions: [{ addChatItemAction: { item: { liveChatTextMessageRenderer: { message: { runs: [{ text: `msg ${i} ${createHash("md5").update(String(i)).digest("hex")}` }] }, authorName: { simpleText: `viewer${i % 97}` } } } } }],
+ videoOffsetTimeMsec: String(i * 1000),
+ },
+ }),
+).join("\n") + "\n";
+
+let n = 0;
+type Fixture = { channelDir: string; videoDir: string; mediaDir: string; tiered: boolean; plainMs: number; bytesMs: number };
+
+// A video with its raw chat — a real file, or a tier link into media/<id>/ —
+// with sub-millisecond times (as ext4 keeps them).
+async function fixture(tiered: boolean, opts: { mediaAway?: boolean } = {}): Promise<Fixture> {
+ const slug = `ch${++n}`;
+ const channelDir = path.join(ROOT, "channels", slug);
+ const id = "vid00000001";
+ const videoDir = path.join(channelDir, "data", id);
+ const mediaRoot = path.join(ROOT, "drive", slug, "media");
+ const mediaDir = path.join(mediaRoot, id);
+ await mkdir(videoDir, { recursive: true });
+ await writeFile(path.join(channelDir, "config.json"), JSON.stringify({ handling: "youtube" }));
+ await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify({ id }));
+ if (tiered) {
+ await mkdir(mediaDir, { recursive: true });
+ await symlink(mediaRoot, path.join(channelDir, "media"));
+ await writeFile(path.join(mediaDir, CHAT), ORIGINAL);
+ await utimes(path.join(mediaDir, CHAT), 1763700000.111111, 1763700000.222223);
+ await symlink(path.join("..", "..", "media", id, CHAT), path.join(videoDir, CHAT));
+ const { lutimes } = await import("node:fs/promises");
+ await lutimes(path.join(videoDir, CHAT), 1763700005.5, 1763700005.123457);
+ } else {
+ await writeFile(path.join(videoDir, CHAT), ORIGINAL);
+ await utimes(path.join(videoDir, CHAT), 1763700000.111111, 1763700000.987653);
+ }
+ const plainMs = (await lstat(path.join(videoDir, CHAT))).mtimeMs;
+ const bytesMs = (await stat(path.join(videoDir, CHAT))).mtimeMs;
+ return { channelDir, videoDir, mediaDir, tiered, plainMs, bytesMs };
+}
+
+const killAt = (point: string) => (p: string) => {
+ if (p === point) throw new CompressKill(p as never);
+};
+
+// A READER GETS ONE WHOLE COPY: the read path answers the original, the
+// logical listing has the chat, and a stored form that is there decodes whole.
+async function assertWhole(f: Fixture, why: string): Promise<void> {
+ assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ORIGINAL, `${why}: the read path`);
+ assert.ok((await readdirLogical(f.videoDir)).includes(CHAT), `${why}: listed`);
+ const z = await lstat(path.join(f.videoDir, ZST)).catch(() => null);
+ if (z) {
+ const v = await verifyStoredText(f.videoDir, CHAT);
+ assert.equal(v.status, "ok", `${why}: a stored form present is whole (${JSON.stringify(v)})`);
+ }
+}
+
+// THE END STATE: the stored form only, the same content, the same times, no
+// temp anywhere.
+async function assertFinal(f: Fixture, why: string): Promise<void> {
+ const data = (await readdir(f.videoDir)).sort();
+ assert.deepEqual(data, ["metadata.info.json", ZST], `${why}: data/<id>`);
+ if (f.tiered) {
+ assert.ok((await lstat(path.join(f.videoDir, ZST))).isSymbolicLink(), `${why}: a tier link`);
+ assert.equal(await readlink(path.join(f.videoDir, ZST)), path.join("..", "..", "media", "vid00000001", ZST));
+ assert.deepEqual((await readdir(f.mediaDir)).sort(), [ZST], `${why}: media/<id>`);
+ }
+ assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ORIGINAL, `${why}: content`);
+ assert.equal((await statStoredText(f.videoDir, CHAT, { link: true })).stats.mtimeMs, f.plainMs, `${why}: the lstat key`);
+ assert.equal((await statStoredText(f.videoDir, CHAT)).stats.mtimeMs, f.bytesMs, `${why}: the stat`);
+ assert.ok((await stat(path.join(f.videoDir, ZST))).size < ORIGINAL.length / 4, `${why}: compressed`);
+}
+
+const run = (f: Fixture, extra: Parameters<typeof compressStoredText>[2] = {}) =>
+ compressStoredText(f.videoDir, CHAT, { reserveBytes: 0, ...extra });
+
+for (const tiered of [false, true]) {
+ const how = tiered ? "tiered" : "real";
+
+ test(`${how}: compressed, then idempotent`, async () => {
+ const f = await fixture(tiered);
+ const out = await run(f);
+ assert.equal(out.status, "compressed", JSON.stringify(out));
+ assert.ok(out.status === "compressed" && out.before === ORIGINAL.length && out.tiered === tiered);
+ await assertFinal(f, "first run");
+ assert.equal((await run(f)).status, "already");
+ await assertFinal(f, "second run");
+ });
+
+ // A real file has no tier link to place.
+ for (const point of KILL_POINTS.filter((p) => tiered || p !== "linked")) {
+ test(`${how}: killed at "${point}" — one whole copy remains, a partial never counts, the next run finishes`, async () => {
+ const f = await fixture(tiered);
+ let partial = 0;
+ await assert.rejects(run(f, { pid: DEAD, crashAt: killAt(point) }), CompressKill);
+ await assertWhole(f, `after the kill at ${point}`);
+ if (point === "compressing" || point === "written" || point === "verified") {
+ // The temp is the only stored bytes, and no reader sees it.
+ const work = tiered ? f.mediaDir : f.videoDir;
+ const temps = (await readdir(work)).filter((e) => e.includes(".compressing-"));
+ assert.equal(temps.length, 1, `${point}: the temp is there`);
+ assert.equal(await lstat(path.join(work, ZST)).catch(() => null), null, `${point}: no stored file`);
+ partial = (await stat(path.join(work, temps[0]))).size;
+ }
+ const out = await run(f);
+ assert.equal(out.status, "compressed", `${point}: ${JSON.stringify(out)}`);
+ await assertFinal(f, `the run after ${point}`);
+ if (point === "compressing") {
+ assert.ok(partial < (await stat(path.join(f.videoDir, ZST))).size, "the temp the kill left was partial");
+ }
+ });
+ }
+
+ test(`${how}: both forms with DIFFERENT content are refused, and nothing is touched`, async () => {
+ const f = await fixture(tiered);
+ await run(f);
+ // A newer plain file beside the stored one (a re-fetch).
+ await writeFile(path.join(f.videoDir, CHAT), "NEWER\n");
+ const before = await tree(f.channelDir);
+ const out = await run(f);
+ assert.deepEqual(out.status === "skipped" && out.reason, "both-differ", JSON.stringify(out));
+ assert.deepEqual(await tree(f.channelDir), before);
+ assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), "NEWER\n", "the plain one is read");
+ });
+
+ test(`${how}: a writer that replaces the file mid-run wins — "changed", the new file read, the earlier content's stored copy KEPT`, async () => {
+ // The seam is synchronous: the new file lands by rename, as yt-dlp's do,
+ // between the stored form landing and the original being set aside.
+ const g = await fixture(tiered);
+ const { writeFileSync, renameSync } = await import("node:fs");
+ const r = await run(g, {
+ crashAt: (p) => {
+ if (p !== "placed") return;
+ writeFileSync(path.join(g.videoDir, ".new-chat"), "REWRITTEN\n");
+ renameSync(path.join(g.videoDir, ".new-chat"), path.join(g.videoDir, CHAT));
+ },
+ });
+ assert.equal(r.status, "changed", JSON.stringify(r));
+ assert.equal(await readFile(path.join(g.videoDir, CHAT), "utf8"), "REWRITTEN\n");
+ assert.equal(await readStoredText(g.videoDir, CHAT, "utf8"), "REWRITTEN\n");
+ assert.deepEqual((await readdir(g.videoDir)).filter((e) => e.includes(".retire-")), []);
+ // REVIEW-2 R1: two captures with different content are never settled by
+ // deleting one — the stored copy of the earlier content stays, whole.
+ assert.deepEqual((await readdir(g.videoDir)).sort(), ["metadata.info.json", CHAT, ZST]);
+ const zBytes = tiered ? path.join(g.mediaDir, ZST) : path.join(g.videoDir, ZST);
+ const { decodeStoredBytes } = await import("./storedText-server");
+ assert.equal((await decodeStoredBytes(await readFile(zBytes))).toString("utf8"), ORIGINAL, "the earlier capture, byte-identical");
+ // And the next run refuses the pair, for a person.
+ const again = await run(g);
+ assert.equal(again.status === "skipped" && again.reason, "both-differ", JSON.stringify(again));
+ });
+
+ test(`${how}: skipped, touching nothing — a .part, a recording, a move, a job, a recent write, a full disk`, async () => {
+ const cases: [string, (f: Fixture) => Promise<Parameters<typeof compressStoredText>[2]>][] = [
+ ["partial", async (f) => (await writeFile(path.join(f.videoDir, `${CHAT}.part`), "x"), {})],
+ ["recording", async (f) => (await writeFile(path.join(f.videoDir, "live-recording.json"), JSON.stringify({ status: "recording" })), {})],
+ ["relocating", async (f) => (await writeFile(path.join(f.channelDir, ".relocating.json"), "{}"), {})],
+ ["busy", async () => ({ isBusy: () => true })],
+ ["recent", async (f) => ({ quietMs: 600_000, now: () => f.bytesMs + 1000 })],
+ ["low-space", async () => ({ reserveBytes: Number.MAX_SAFE_INTEGER })],
+ ];
+ for (const [reason, arrange] of cases) {
+ const f = await fixture(tiered);
+ const extra = await arrange(f);
+ const before = await tree(path.dirname(path.dirname(f.channelDir)));
+ const out = await run(f, extra);
+ assert.equal(out.status === "skipped" && out.reason, reason, `${reason}: ${JSON.stringify(out)}`);
+ assert.deepEqual(await tree(path.dirname(path.dirname(f.channelDir))), before, `${reason}: nothing touched`);
+ }
+ });
+}
+
+for (const tiered of [false, true]) {
+ const how = tiered ? "tiered" : "real";
+
+ test(`${how}: a move of the channel's media that begins mid-run keeps the original (the tier hook's rule)`, async () => {
+ const f = await fixture(tiered);
+ const { writeFileSync } = await import("node:fs");
+ const out = await run(f, {
+ crashAt: (p) => {
+ if (p === "placed") writeFileSync(path.join(f.channelDir, ".relocating.json"), "{}");
+ },
+ });
+ assert.equal(out.status === "skipped" && out.reason, "relocating", JSON.stringify(out));
+ assert.equal(await readFile(path.join(f.videoDir, CHAT), "utf8"), ORIGINAL, "the original is untouched");
+ await assertWhole(f, "mid-move");
+ await rm(path.join(f.channelDir, ".relocating.json"));
+ assert.equal((await run(f)).status, "compressed");
+ await assertFinal(f, "after the move");
+ });
+
+ test(`${how}: a newer file written just after the original was set aside is kept, and read`, async () => {
+ const f = await fixture(tiered);
+ const { writeFileSync } = await import("node:fs");
+ const out = await run(f, {
+ crashAt: (p) => {
+ if (p === "retired") writeFileSync(path.join(f.videoDir, CHAT), "NEWEST\n");
+ },
+ });
+ assert.equal(out.status, "changed", JSON.stringify(out));
+ assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), "NEWEST\n", "the newer file is the truth");
+ assert.deepEqual((await readdir(f.videoDir)).filter((e) => e.includes(".retire-")), []);
+ // Both captures kept (REVIEW-2 R1): the newer file, and the earlier
+ // content's stored copy, whole.
+ assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", CHAT, ZST]);
+ assert.equal((await verifyStoredText(f.videoDir, CHAT)).status, "differs");
+ const again = await run(f);
+ assert.equal(again.status === "skipped" && again.reason, "both-differ", "refused, both kept");
+ });
+
+ test(`${how}: the stored form replaced by another process before the original goes — the original stays (REVIEW-2 R3)`, async () => {
+ const f = await fixture(tiered);
+ const { writeFileSync, renameSync } = await import("node:fs");
+ const zBytes = tiered ? path.join(f.mediaDir, ZST) : path.join(f.videoDir, ZST);
+ const out = await run(f, {
+ crashAt: (p) => {
+ // After the stored form is verified and in place: someone else's run
+ // swaps a different file in under its name.
+ if (p !== (tiered ? "linked" : "placed")) return;
+ writeFileSync(zBytes + ".other", "not the verified frame");
+ renameSync(zBytes + ".other", zBytes);
+ },
+ });
+ assert.equal(out.status, "changed", JSON.stringify(out));
+ assert.equal(await readFile(path.join(f.videoDir, CHAT), "utf8"), ORIGINAL, "the original is untouched");
+ });
+
+ test(`${how}: the tier hook's own temp link is not taken for a dead run's leftover (REVIEW-2 N2)`, async () => {
+ const f = await fixture(tiered);
+ const hookTemp = path.join(f.videoDir, `.${CHAT}.tierlink-${process.pid}`);
+ await writeFile(hookTemp, "the hook's");
+ assert.equal((await run(f)).status, "compressed");
+ assert.equal(await readFile(hookTemp, "utf8"), "the hook's");
+ await rm(hookTemp);
+ });
+}
+
+test("an unmounted media drive: skipped as unreachable, and nothing is created on the root filesystem", async () => {
+ const f = await fixture(true);
+ const drive = path.join(ROOT, "drive", path.basename(f.channelDir));
+ await rename(drive, `${drive}-unmounted`);
+ try {
+ const out = await run(f);
+ assert.equal(out.status === "skipped" && out.reason, "unreachable", JSON.stringify(out));
+ assert.equal(await lstat(drive).catch(() => null), null, "the mountpoint is not rebuilt");
+ assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", CHAT]);
+ } finally {
+ await rename(`${drive}-unmounted`, drive);
+ }
+ assert.equal((await run(f)).status, "compressed");
+});
+
+test("killed INSIDE the original's removal (its bytes gone, its link not): readers get the stored form; the next run removes the link", async () => {
+ const f = await fixture(true);
+ await run(f);
+ // What `removeMediaFile` leaves when killed between its two steps.
+ await symlink(path.join("..", "..", "media", "vid00000001", CHAT), path.join(f.videoDir, CHAT));
+ assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ORIGINAL);
+ const out = await run(f);
+ assert.equal(out.status, "already", JSON.stringify(out));
+ await assertFinal(f, "after the dangling link");
+});
+
+test("a dangling plain link with NO stored form is left alone (the bytes may be on a drive)", async () => {
+ const f = await fixture(true);
+ await rm(path.join(f.mediaDir, CHAT));
+ const out = await run(f);
+ assert.equal(out.status === "skipped" && out.reason, "dangling");
+ assert.ok((await lstat(path.join(f.videoDir, CHAT))).isSymbolicLink());
+});
+
+test("a corrupt stored form beside the plain file is refused; a truncated one never reads as the file", async () => {
+ const f = await fixture(false);
+ const good = await encodeStoredBytes(Buffer.from(ORIGINAL));
+ await writeFile(path.join(f.videoDir, ZST), good.subarray(0, Math.floor(good.length / 2)));
+ // The plain file is the truth while it is there.
+ assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ORIGINAL);
+ const out = await run(f);
+ assert.equal(out.status === "skipped" && out.reason, "stored-corrupt", JSON.stringify(out));
+ assert.ok((await lstat(path.join(f.videoDir, CHAT))).isFile(), "the original stays");
+ assert.equal((await verifyStoredText(f.videoDir, CHAT)).status, "corrupt");
+});
+
+test("a set-aside original of a dead run that is NOT the stored content is kept for a person", async () => {
+ const f = await fixture(false);
+ await run(f);
+ await writeFile(path.join(f.videoDir, CHAT), "NEWER\n");
+ await writeFile(path.join(f.videoDir, `.${CHAT}.retire-${DEAD}`), "SOMETHING ELSE\n");
+ const out = await run(f);
+ assert.equal(out.status === "skipped" && out.reason, "retired-kept", JSON.stringify(out));
+ assert.equal(await readFile(path.join(f.videoDir, `.${CHAT}.retire-${DEAD}`), "utf8"), "SOMETHING ELSE\n");
+});
+
+// REVIEW-1 F4(b): a leftover is dead unless the process that named it runs NOW
+// — the pid AND its start token. An editor that comes back with the same pid
+// (a container) finds its own earlier run's set-aside: dead, finished. A live
+// process of another pid with the same start: alive, nothing touched. A pid
+// reused by a later process (another start token): dead.
+for (const tiered of [false, true]) {
+ const how = tiered ? "tiered" : "real";
+ const { processStartToken } = await import("./storedText-write-server");
+ const killRetired = (p: string) => {
+ if (p === "retired") throw new CompressKill(p as never);
+ };
+
+ test(`${how}: this pid's leftover from an EARLIER process start is dead — the next run finishes`, async () => {
+ for (const token of ["oldstart1", undefined]) {
+ const f = await fixture(tiered);
+ await assert.rejects(run(f, { pid: process.pid, ...(token ? { token } : {}), crashAt: killRetired }), CompressKill);
+ const left = (await readdir(f.videoDir)).filter((e) => e.includes(".retire-"));
+ assert.equal(left.length, 1);
+ assert.match(left[0], new RegExp(`retire-${process.pid}-`));
+ await assertWhole(f, "after the kill");
+ const out = await run(f);
+ assert.equal(out.status, "compressed", JSON.stringify(out));
+ await assertFinal(f, `own pid, ${token ?? "this start"}`);
+ }
+ });
+
+ test(`${how}: a leftover of ANOTHER live process (same pid, same start) is left alone; a reused pid's is dead`, async () => {
+ const other = process.ppid;
+ const live = processStartToken(other);
+ assert.ok(live, "the parent's start token is readable");
+ const f = await fixture(tiered);
+ await assert.rejects(run(f, { pid: other, token: live!, crashAt: killRetired }), CompressKill);
+ const before = await tree(f.channelDir);
+ const out = await run(f);
+ assert.equal(out.status === "skipped" && out.reason, "busy", JSON.stringify(out));
+ assert.deepEqual(await tree(f.channelDir), before, "nothing touched");
+
+ const g = await fixture(tiered);
+ await assert.rejects(run(g, { pid: other, token: "reused0", crashAt: killRetired }), CompressKill);
+ const again = await run(g);
+ assert.equal(again.status, "compressed", JSON.stringify(again));
+ await assertFinal(g, "a reused pid");
+ });
+}
+
+test("the quiet period asks the later of mtime and ctime: a backdated mtime is still recent (REVIEW-1 N4)", async () => {
+ const f = await fixture(false);
+ // The fixture's mtime is days old; its ctime is now (the utimes itself).
+ const out = await run(f, { quietMs: 600_000 });
+ assert.equal(out.status === "skipped" && out.reason, "recent", JSON.stringify(out));
+ const later = await run(f, { quietMs: 600_000, now: () => Date.now() + 3_600_000 });
+ assert.equal(later.status, "compressed");
+});
+
+// A KERNEL-WRITTEN mtime has nanoseconds; `utimes` takes a double of seconds.
+// Measured (Node 22.23.5, ext4): `mtimeMs` round-trips EXACTLY — the number
+// the index compares (buildIndex: `mtimeMs !==`) — while `mtimeNs` may move by
+// a few hundred ns. Pinned both ways: the index sees no change; the
+// nanoseconds are not promised.
+test("a nanosecond kernel mtime: the stored form's mtimeMs equals the original's exactly (the index key)", async () => {
+ for (const tiered of [false, true]) {
+ const f = await fixture(tiered);
+ const bytes = tiered ? path.join(f.mediaDir, CHAT) : path.join(f.videoDir, CHAT);
+ // Rewrite in place so the kernel stamps the time (no utimes).
+ await writeFile(bytes, ORIGINAL);
+ const name = path.join(f.videoDir, CHAT);
+ const lBefore = await lstat(name, { bigint: true });
+ const sBefore = await stat(name, { bigint: true });
+ const msL = (await lstat(name)).mtimeMs;
+ const msS = (await stat(name)).mtimeMs;
+ assert.notEqual(sBefore.mtimeNs % 1_000_000n, 0n, "a sub-millisecond kernel time");
+ assert.equal((await run(f)).status, "compressed");
+ assert.equal((await statStoredText(f.videoDir, CHAT, { link: true })).stats.mtimeMs, msL, "lstat mtimeMs");
+ assert.equal((await statStoredText(f.videoDir, CHAT)).stats.mtimeMs, msS, "stat mtimeMs");
+ const zs = await stat(path.join(f.videoDir, ZST), { bigint: true });
+ const drift = zs.mtimeNs - sBefore.mtimeNs;
+ assert.ok(drift > -1000n && drift < 1000n, `mtimeNs within a microsecond (drift ${drift} ns)`);
+ void lBefore;
+ }
+});
+
+test("a stored file missing its last 1-4 bytes (the checksum) still decodes whole and right: pinned (REVIEW-1 N7)", async () => {
+ const f = await fixture(false);
+ assert.equal((await run(f)).status, "compressed");
+ const z = path.join(f.videoDir, ZST);
+ const whole = await readFile(z);
+ for (const cut of [1, 4]) {
+ await writeFile(z, whole.subarray(0, whole.length - cut));
+ // Without its checksum the frame is not checked, but every byte of the
+ // content is there, and the length matches the header: the text is right.
+ assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ORIGINAL, `cut ${cut}`);
+ assert.equal((await verifyStoredText(f.videoDir, CHAT)).status, "ok", `cut ${cut}`);
+ }
+ // One byte more and content is missing: never read as the file.
+ await writeFile(z, whole.subarray(0, whole.length - 5 - 100));
+ await assert.rejects(readStoredText(f.videoDir, CHAT, "utf8"));
+});
+
+test("a 0-byte chat compresses and reads back as 0 bytes", async () => {
+ const f = await fixture(false);
+ await writeFile(path.join(f.videoDir, CHAT), "");
+ assert.equal((await run(f)).status, "compressed");
+ assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), "");
+ assert.equal((await verifyStoredText(f.videoDir, CHAT)).status, "ok");
+});
+
+test("an abort mid-write and an appending writer: the original is untouched, no temp is left", async () => {
+ const f = await fixture(false);
+ const ac = new AbortController();
+ await assert.rejects(run(f, { signal: ac.signal, crashAt: (p) => { if (p === "compressing") ac.abort(); } }));
+ assert.equal(await readFile(path.join(f.videoDir, CHAT), "utf8"), ORIGINAL);
+ assert.deepEqual((await readdir(f.videoDir)).sort(), [CHAT, "metadata.info.json"].sort());
+
+ const g = await fixture(false);
+ const { appendFileSync } = await import("node:fs");
+ const out = await run(g, { crashAt: (p) => { if (p === "compressing") appendFileSync(path.join(g.videoDir, CHAT), "MORE\n"); } });
+ assert.equal(out.status, "changed", JSON.stringify(out));
+ assert.equal(await readFile(path.join(g.videoDir, CHAT), "utf8"), ORIGINAL + "MORE\n", "the writer's file is kept");
+ assert.deepEqual((await readdir(g.videoDir)).sort(), [CHAT, "metadata.info.json"].sort(), "no temp, no stored form");
+});
+
+test("not a declared name: refused", async () => {
+ const f = await fixture(false);
+ const out = await compressStoredText(f.videoDir, "transcript.en.vtt");
+ assert.equal(out.status === "skipped" && out.reason, "not-declared");
+});
+
+// Every entry under `dir`: its kind, size, times and content hash (a link:
+// its target and its own times) — what "nothing was touched" compares.
+async function tree(dir: string): Promise<string[]> {
+ const out: string[] = [];
+ async function walk(d: string): Promise<void> {
+ for (const e of (await readdir(d).catch(() => [] as string[])).sort()) {
+ const p = path.join(d, e);
+ const l = await lstat(p);
+ const rel = path.relative(ROOT, p);
+ if (l.isSymbolicLink()) out.push(`${rel} -> ${await readlink(p)} ${l.mtimeMs}`);
+ else if (l.isDirectory()) {
+ out.push(`${rel}/`);
+ await walk(p);
+ } else {
+ const h = createHash("sha256").update(await readFile(p)).digest("hex");
+ out.push(`${rel} ${l.size} ${l.mtimeMs} ${h}`);
+ }
+ }
+ }
+ await walk(dir);
+ return out;
+}
diff --git a/common/lib/storedText.grep.test.ts b/common/lib/storedText.grep.test.ts
@@ -0,0 +1,260 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readdir, readFile } from "node:fs/promises";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/storedText.grep.test.ts
+//
+// THE STORED-TEXT GATE (lane text-compress). The raw live chat may be on disk
+// as `transcript.live_chat.json.zst` (lib/storedText.ts). A reader that opens,
+// stats, lists or deletes the plain name directly sees that file as ABSENT —
+// for the chat that is a fetch of the whole replay again, or (a deleter) an
+// 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 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", "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
+// literal (but not its `.part`, its `.zst` spelled out in a comment, or the
+// derived `live_chat.cues.json`).
+const NAMES = /\bLIVE_CHAT_(?:MEDIA_|STORED_)?FILENAME\b|transcript\.live_chat\.json(?![.\w])/;
+
+// 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|removeStoredTextForm|compressStoredText|restoreStoredText|verifyStoredText|setAsideStoredText|putBackKeptCapture|keepPlainAsCapture|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: "common/controller/fetchLiveChat.ts",
+ code: /const landed = !partial && \(await stat\(path\.join\(videoDir, LIVE_CHAT_FILENAME\)\)|const fetched = measureChat\(await readFile\(path\.join\(videoDir, LIVE_CHAT_FILENAME\)\)\)/,
+ why: "the replace's look at what the pass wrote: the PLAIN file only (the stored capture was set aside first)",
+ },
+ {
+ 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([
+ "common/lib/videoStatus.ts",
+ "common/lib/mediaTier.ts",
+ "common/lib/storedText.ts",
+ "common/lib/storedText-server.ts",
+ "common/lib/storedText-write-server.ts",
+]);
+
+async function walk(dir: string, out: string[]): Promise<void> {
+ let entries;
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const e of entries) {
+ if (SKIP_DIRS.has(e.name)) continue;
+ const p = path.join(dir, e.name);
+ if (e.isDirectory()) await walk(p, out);
+ else if (/\.(?:ts|tsx|mjs|js)$/.test(e.name) && !/\.(?:test|spec|unit)\.|\.d\.m?ts$/.test(e.name)) out.push(p);
+ }
+}
+
+// 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 "";
+ // A trailing comment is not code.
+ return line.replace(/\s\/\/.*$/, "");
+}
+
+test("every app line naming the raw live chat goes through the stored-text helpers", async () => {
+ const files = await appFiles();
+ assert.ok(files.length > 200, `walked ${files.length} files`);
+ const offenders: string[] = [];
+ for (const { rel, lines } of files) {
+ if (DEFINITIONS.has(rel)) continue;
+ 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;
+ // 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");
+ if (SANCTIONED.test(statement)) continue;
+ offenders.push(`${rel}:${i + 1}: ${lines[i].trim()}`);
+ }
+ }
+ assert.deepEqual(
+ offenders,
+ [],
+ "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 stored capture kept first",
+ 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/lib/storedText.lock.test.ts b/common/lib/storedText.lock.test.ts
@@ -0,0 +1,125 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createHash } from "node:crypto";
+import { lstat, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/storedText.lock.test.ts
+//
+// TWO PROCESSES ON ONE VIDEO DIR (REVIEW-2 R3). Compress, restore and the files
+// card's delete take `.stored-text.lock` in the video dir; a second process
+// honours it ("busy", nothing touched) while its owner runs, and takes over a
+// stale one (its owner gone, or this pid from an earlier start). And the
+// restore looks at the plain file again right before the stored form goes.
+// Temp dirs only; the second process is a real child process.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "stored-lock-"));
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const W = await import("./storedText-write-server");
+const { readStoredText, decodeStoredBytes } = await import("./storedText-server");
+
+const CHAT = "transcript.live_chat.json";
+const ZST = `${CHAT}.zst`;
+const LOCK = ".stored-text.lock";
+const BODY = Array.from({ length: 30_000 }, (_, i) => `{"replayChatItemAction":{"n":${i},"h":"${createHash("md5").update(String(i)).digest("hex")}"}}`).join("\n") + "\n";
+
+let n = 0;
+async function videoDir(): Promise<string> {
+ const d = path.join(ROOT, "channels", `c${++n}`, "data", "v");
+ await mkdir(d, { recursive: true });
+ await writeFile(path.join(d, CHAT), BODY);
+ return d;
+}
+
+const exists = (p: string) => lstat(p).then(() => true, () => false);
+
+async function snapshot(d: string): Promise<string[]> {
+ const out: string[] = [];
+ for (const e of (await readdir(d)).sort()) out.push(`${e} ${createHash("sha256").update(await readFile(path.join(d, e))).digest("hex")}`);
+ return out;
+}
+
+test("a lock held by a live run of another process: compress, restore and delete answer busy, touching nothing", async () => {
+ const d = await videoDir();
+ const other = process.ppid;
+ const token = W.processStartToken(other);
+ assert.ok(token);
+ await writeFile(path.join(d, LOCK), JSON.stringify({ pid: other, token }));
+ const before = await snapshot(d);
+ const c = await W.compressStoredText(d, CHAT, { reserveBytes: 0 });
+ assert.equal(c.status === "skipped" && c.reason, "busy", JSON.stringify(c));
+ const r = await W.restoreStoredText(d, CHAT, { reserveBytes: 0 });
+ assert.equal(r.status === "skipped" && r.reason, "busy", JSON.stringify(r));
+ assert.equal(await W.removeStoredTextForm(d, CHAT), "busy");
+ assert.deepEqual(await snapshot(d), before, "nothing touched, the lock kept");
+});
+
+test("a stale lock (a reused pid's, a dead pid's, this pid's from an earlier start) is taken over and released", async () => {
+ for (const owner of [{ pid: process.ppid, token: "reused0" }, { pid: 999_999_995, token: "gone0" }, { pid: process.pid, token: "earlier0" }]) {
+ const d = await videoDir();
+ await writeFile(path.join(d, LOCK), JSON.stringify(owner));
+ const out = await W.compressStoredText(d, CHAT, { reserveBytes: 0 });
+ assert.equal(out.status, "compressed", `${JSON.stringify(owner)}: ${JSON.stringify(out)}`);
+ assert.equal(await exists(path.join(d, LOCK)), false, "released");
+ assert.deepEqual((await readdir(d)).sort(), [ZST]);
+ }
+});
+
+test("two processes at once: while a child process compresses, this one's restore and compress are refused; one whole copy throughout", async () => {
+ const d = await videoDir();
+ const child = spawn(process.execPath, [...process.execArgv, fileURLToPath(new URL("../testing/storedTextChild.ts", import.meta.url)), "compress", d, CHAT, "40"], {
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let out = "";
+ let err = "";
+ child.stdout.on("data", (b) => (out += b));
+ child.stderr.on("data", (b) => (err += b));
+ const done = new Promise<number | null>((resolve) => child.on("exit", resolve));
+ // Wait for the child to hold the dir.
+ for (let i = 0; i < 400 && !(await exists(path.join(d, LOCK))); i++) await new Promise((r) => setTimeout(r, 25));
+ assert.ok(await exists(path.join(d, LOCK)), `the child holds the lock (${err})`);
+ const r = await W.restoreStoredText(d, CHAT, { reserveBytes: 0 });
+ assert.equal(r.status === "skipped" && r.reason, "busy", JSON.stringify(r));
+ const c = await W.compressStoredText(d, CHAT, { reserveBytes: 0 });
+ assert.equal(c.status === "skipped" && c.reason, "busy", JSON.stringify(c));
+ assert.equal(await readStoredText(d, CHAT, "utf8"), BODY, "one whole copy while the child runs");
+ assert.equal(await done, 0, err);
+ assert.equal(JSON.parse(out).status, "compressed", out);
+ assert.equal(await exists(path.join(d, LOCK)), false);
+ assert.deepEqual((await readdir(d)).sort(), [ZST]);
+ // And the other way round: the child restores, this process is refused.
+ const back = spawn(process.execPath, [...process.execArgv, fileURLToPath(new URL("../testing/storedTextChild.ts", import.meta.url)), "restore", d, CHAT, "40"], {
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let out2 = "";
+ back.stdout.on("data", (b) => (out2 += b));
+ const done2 = new Promise<number | null>((resolve) => back.on("exit", resolve));
+ for (let i = 0; i < 400 && !(await exists(path.join(d, LOCK))); i++) await new Promise((r) => setTimeout(r, 25));
+ const c2 = await W.compressStoredText(d, CHAT, { reserveBytes: 0 });
+ assert.equal(c2.status === "skipped" && c2.reason, "busy", JSON.stringify(c2));
+ assert.equal(await done2, 0);
+ assert.equal(JSON.parse(out2).status, "restored", out2);
+ assert.equal(await readFile(path.join(d, CHAT), "utf8"), BODY);
+ assert.deepEqual((await readdir(d)).sort(), [CHAT]);
+});
+
+test("restore: the plain file is looked at again right before the stored form goes — a changed one keeps the stored form", async () => {
+ const { writeFileSync } = await import("node:fs");
+ const d = await videoDir();
+ assert.equal((await W.compressStoredText(d, CHAT, { reserveBytes: 0 })).status, "compressed");
+ const out = await W.restoreStoredText(d, CHAT, {
+ reserveBytes: 0,
+ // Another process's write lands in the placed plain file after it was verified.
+ crashAt: (p) => {
+ if (p === "restore-placed") writeFileSync(path.join(d, CHAT), BODY.replace("\"n\":7,", "\"n\":8,"));
+ },
+ });
+ assert.equal(out.status, "changed", JSON.stringify(out));
+ assert.ok(await exists(path.join(d, ZST)), "the stored form stays");
+ assert.equal((await decodeStoredBytes(await readFile(path.join(d, ZST)))).toString("utf8"), BODY, "whole");
+});
diff --git a/common/lib/storedText.restore.test.ts b/common/lib/storedText.restore.test.ts
@@ -0,0 +1,171 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { lstat, lutimes, mkdir, mkdtemp, readdir, readFile, readlink, rm, stat, symlink, utimes, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/storedText.restore.test.ts
+//
+// THE RESTORE (REVIEW-1 F3): a stored chat put back into its plain form, the
+// compressor in reverse — the rollback an older checkout needs. Every case is a
+// temp channel tree, real files and tier links. Kill points are the `crashAt`
+// seam (it throws and nothing after it runs, as a SIGKILL). After each: ONE
+// WHOLE COPY is always readable, and the next run finishes with the plain form
+// only, the same bytes and the same times (an `lstat` and a `stat` of the
+// name answer what they did before the file was ever compressed).
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "stored-restore-"));
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const { compressStoredText, restoreStoredText, CompressKill } = await import("./storedText-write-server");
+const { readStoredText, readdirLogical } = await import("./storedText-server");
+
+const CHAT = "transcript.live_chat.json";
+const ZST = `${CHAT}.zst`;
+const DEAD = 999_999_998;
+const KILLS = ["restoring", "restore-written", "restore-verified", "restore-placed", "restore-linked"] as const;
+
+const ORIGINAL = Array.from({ length: 9_000 }, (_, i) =>
+ JSON.stringify({ replayChatItemAction: { actions: [{ text: `m${i} ${createHash("md5").update(String(i)).digest("hex")}` }], videoOffsetTimeMsec: String(i * 1000) } }),
+).join("\n") + "\n";
+
+let n = 0;
+type F = { channelDir: string; videoDir: string; mediaDir: string; tiered: boolean; lstatMs: number; statMs: number };
+
+// A compressed chat, as the compressor leaves it (real or tiered), and the
+// times the plain name answered before.
+async function compressed(tiered: boolean): Promise<F> {
+ const slug = `r${++n}`;
+ const channelDir = path.join(ROOT, "channels", slug);
+ const id = "vid00000002";
+ const videoDir = path.join(channelDir, "data", id);
+ const mediaRoot = path.join(ROOT, "drive", slug, "media");
+ const mediaDir = path.join(mediaRoot, id);
+ await mkdir(videoDir, { recursive: true });
+ await writeFile(path.join(videoDir, "metadata.info.json"), "{}");
+ if (tiered) {
+ await mkdir(mediaDir, { recursive: true });
+ await symlink(mediaRoot, path.join(channelDir, "media"));
+ await writeFile(path.join(mediaDir, CHAT), ORIGINAL);
+ await utimes(path.join(mediaDir, CHAT), 1763700100.25, 1763700100.333337);
+ await symlink(path.join("..", "..", "media", id, CHAT), path.join(videoDir, CHAT));
+ await lutimes(path.join(videoDir, CHAT), 1763700200.5, 1763700200.777779);
+ } else {
+ await writeFile(path.join(videoDir, CHAT), ORIGINAL);
+ await utimes(path.join(videoDir, CHAT), 1763700100.25, 1763700100.987651);
+ }
+ const lstatMs = (await lstat(path.join(videoDir, CHAT))).mtimeMs;
+ const statMs = (await stat(path.join(videoDir, CHAT))).mtimeMs;
+ const out = await compressStoredText(videoDir, CHAT, { reserveBytes: 0 });
+ assert.equal(out.status, "compressed", JSON.stringify(out));
+ return { channelDir, videoDir, mediaDir, tiered, lstatMs, statMs };
+}
+
+async function assertWhole(f: F, why: string): Promise<void> {
+ assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ORIGINAL, `${why}: the read path`);
+ assert.ok((await readdirLogical(f.videoDir)).includes(CHAT), `${why}: listed`);
+}
+
+async function assertPlainFinal(f: F, why: string): Promise<void> {
+ assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", CHAT], `${why}: data/<id>`);
+ assert.equal(await readFile(path.join(f.videoDir, CHAT), "utf8"), ORIGINAL, `${why}: the plain bytes`);
+ assert.equal((await lstat(path.join(f.videoDir, CHAT))).mtimeMs, f.lstatMs, `${why}: the lstat key`);
+ assert.equal((await stat(path.join(f.videoDir, CHAT))).mtimeMs, f.statMs, `${why}: the stat`);
+ if (f.tiered) {
+ assert.ok((await lstat(path.join(f.videoDir, CHAT))).isSymbolicLink(), `${why}: a tier link`);
+ assert.equal(await readlink(path.join(f.videoDir, CHAT)), path.join("..", "..", "media", "vid00000002", CHAT));
+ assert.deepEqual(await readdir(f.mediaDir), [CHAT], `${why}: media/<id>`);
+ }
+}
+
+const run = (f: F, extra: Parameters<typeof restoreStoredText>[2] = {}) =>
+ restoreStoredText(f.videoDir, CHAT, { reserveBytes: 0, ...extra });
+
+for (const tiered of [false, true]) {
+ const how = tiered ? "tiered" : "real";
+
+ test(`${how}: restored with the same bytes and times, then idempotent; a compress after it is the same as before`, async () => {
+ const f = await compressed(tiered);
+ const out = await run(f);
+ assert.equal(out.status, "restored", JSON.stringify(out));
+ await assertPlainFinal(f, "restored");
+ assert.equal((await run(f)).status, "already");
+ // Round trip: compress again, restore again — the same plain file.
+ assert.equal((await compressStoredText(f.videoDir, CHAT, { reserveBytes: 0 })).status, "compressed");
+ assert.equal((await run(f)).status, "restored");
+ await assertPlainFinal(f, "second round trip");
+ });
+
+ for (const point of KILLS.filter((p) => tiered || p !== "restore-linked")) {
+ test(`${how}: killed at "${point}" — one whole copy remains, and the next run (a restore, or a compress) finishes`, async () => {
+ for (const next of ["restore", "compress"] as const) {
+ const f = await compressed(tiered);
+ await assert.rejects(
+ run(f, { pid: DEAD, crashAt: (p) => { if (p === point) throw new CompressKill(p); } }),
+ CompressKill,
+ );
+ await assertWhole(f, `after the kill at ${point}`);
+ if (next === "restore") {
+ const out = await run(f);
+ assert.equal(out.status, "restored", `${point}: ${JSON.stringify(out)}`);
+ await assertPlainFinal(f, `${point}, then restore`);
+ } else {
+ const out = await compressStoredText(f.videoDir, CHAT, { reserveBytes: 0 });
+ assert.ok(["already", "compressed"].includes(out.status), `${point}: ${JSON.stringify(out)}`);
+ await assertWhole(f, `${point}, then compress`);
+ assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", ZST], `${point}: stored form only`);
+ if (tiered) assert.deepEqual(await readdir(f.mediaDir), [ZST], `${point}: media/<id>`);
+ }
+ }
+ });
+ }
+
+ test(`${how}: a stored file that does not decode is refused and left as it is`, async () => {
+ const f = await compressed(tiered);
+ const zBytes = f.tiered ? path.join(f.mediaDir, ZST) : path.join(f.videoDir, ZST);
+ const whole = await readFile(zBytes);
+ await writeFile(zBytes, whole.subarray(0, Math.floor(whole.length / 2)));
+ const out = await run(f);
+ assert.equal(out.status === "skipped" && out.reason, "stored-corrupt", JSON.stringify(out));
+ assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", ZST]);
+ assert.equal((await readFile(zBytes)).length, Math.floor(whole.length / 2), "untouched");
+ });
+
+ test(`${how}: a plain file beside the stored one with DIFFERENT content is refused; with the same content the stored one goes`, async () => {
+ const f = await compressed(tiered);
+ await writeFile(path.join(f.videoDir, CHAT), "NEWER\n");
+ const out = await run(f);
+ assert.equal(out.status === "skipped" && out.reason, "both-differ", JSON.stringify(out));
+ assert.ok(await lstat(path.join(f.videoDir, ZST)));
+ await writeFile(path.join(f.videoDir, CHAT), ORIGINAL);
+ assert.equal((await run(f)).status, "restored");
+ assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", CHAT]);
+ });
+
+ test(`${how}: skipped, touching nothing — a move, a recording, a full disk`, async () => {
+ for (const [reason, arrange] of [
+ ["relocating", async (f: F) => (await writeFile(path.join(f.channelDir, ".relocating.json"), "{}"), {})],
+ ["recording", async (f: F) => (await writeFile(path.join(f.videoDir, "live-recording.json"), JSON.stringify({ status: "recording" })), {})],
+ ["low-space", async () => ({ reserveBytes: Number.MAX_SAFE_INTEGER })],
+ ] as const) {
+ const f = await compressed(tiered);
+ const extra = await arrange(f);
+ const before = (await readdir(f.videoDir)).sort();
+ const out = await restoreStoredText(f.videoDir, CHAT, extra);
+ assert.equal(out.status === "skipped" && out.reason, reason, `${reason}: ${JSON.stringify(out)}`);
+ assert.deepEqual((await readdir(f.videoDir)).sort(), before, `${reason}: nothing touched`);
+ await assertWhole(f, reason);
+ }
+ });
+}
+
+test("a plain chat that was never compressed is `already`; no chat at all is `absent`", async () => {
+ const d = path.join(ROOT, "channels", "plain-only", "data", "v");
+ await mkdir(d, { recursive: true });
+ assert.equal((await restoreStoredText(d, CHAT)).status, "absent");
+ await writeFile(path.join(d, CHAT), "x\n");
+ assert.equal((await restoreStoredText(d, CHAT)).status, "already");
+ assert.equal(await readFile(path.join(d, CHAT), "utf8"), "x\n");
+});
diff --git a/common/lib/storedText.test.ts b/common/lib/storedText.test.ts
@@ -0,0 +1,157 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { lstat, mkdir, mkdtemp, readFile, rm, stat, symlink, utimes, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/storedText.test.ts
+//
+// STORED TEXT (lane text-compress): the names, the classifier, and the one
+// read path that accepts either form. Temp dirs, synthetic names.
+
+import {
+ STORED_TEXT_NAMES,
+ isStoredTextName,
+ listingHas,
+ logicalEntries,
+ plainNameOf,
+ storedFormsIn,
+ storedNameOf,
+} from "./storedText";
+import {
+ decodeStoredBytes,
+ encodeStoredBytes,
+ frameContentSize,
+ readStoredText,
+ readdirLogical,
+ statStoredText,
+ storedTextExists,
+ storedTextForms,
+ storedTextLogicalSize,
+ storedTextMtimeMs,
+ StoredTextCorruptError,
+} from "./storedText-server";
+import { classifyEntry, isScratchEntry, isTierable, LIVE_CHAT_STORED_FILENAME } from "./mediaTier";
+import { LIVE_CHAT_FILENAME } from "./videoStatus";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "stored-text-"));
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const CHAT = LIVE_CHAT_FILENAME;
+const BODY = '{"replayChatItemAction":{"actions":[]}}\n'.repeat(500);
+
+async function dir(name: string): Promise<string> {
+ const d = path.join(ROOT, name);
+ await mkdir(d, { recursive: true });
+ return d;
+}
+
+test("the declared names: the live chat only, its stored form `.zst`", () => {
+ assert.deepEqual([...STORED_TEXT_NAMES], [CHAT]);
+ assert.equal(isStoredTextName(CHAT), true);
+ assert.equal(isStoredTextName("transcript.en.vtt"), false);
+ assert.equal(storedNameOf(CHAT), "transcript.live_chat.json.zst");
+ assert.equal(plainNameOf("transcript.live_chat.json.zst"), CHAT);
+ // Not declared: a `.zst` of another name stands for nothing here.
+ assert.equal(plainNameOf("transcript.en.vtt.zst"), null);
+ assert.equal(plainNameOf(CHAT), null);
+ assert.equal(LIVE_CHAT_STORED_FILENAME, storedNameOf(CHAT));
+});
+
+test("a logical listing reports the stored chat under its plain name, once", () => {
+ assert.deepEqual(
+ logicalEntries(["metadata.info.json", "transcript.live_chat.json.zst", CHAT, "x.zst"]),
+ ["metadata.info.json", CHAT, "x.zst"],
+ );
+ assert.equal(listingHas(["transcript.live_chat.json.zst"], CHAT), true);
+ assert.equal(listingHas(["transcript.en.vtt.zst"], "transcript.en.vtt"), false);
+ assert.equal(storedFormsIn([CHAT], CHAT), "plain");
+ assert.equal(storedFormsIn(["transcript.live_chat.json.zst"], CHAT), "zst");
+ assert.equal(storedFormsIn([CHAT, "transcript.live_chat.json.zst"], CHAT), "both");
+ assert.equal(storedFormsIn([], CHAT), null);
+});
+
+test("the classifier: the stored chat is media and tierable; the compressor's temps are scratch", () => {
+ assert.equal(classifyEntry("transcript.live_chat.json.zst"), "media");
+ assert.equal(isTierable("transcript.live_chat.json.zst"), true);
+ assert.equal(classifyEntry(".transcript.live_chat.json.zst.compressing-4242"), "scratch");
+ assert.equal(isScratchEntry(".transcript.live_chat.json.retire-4242"), true);
+ assert.equal(isTierable(".transcript.live_chat.json.zst.compressing-4242"), false);
+ // Not a declared stored form: text, as before.
+ assert.equal(classifyEntry("transcript.en.vtt.zst"), "text");
+});
+
+test("a frame carries its content size; the reader decodes and checks it", async () => {
+ const bytes = await encodeStoredBytes(Buffer.from(BODY));
+ assert.equal(frameContentSize(bytes.subarray(0, 18)), Buffer.byteLength(BODY));
+ assert.equal((await decodeStoredBytes(bytes)).toString(), BODY);
+ assert.equal(frameContentSize(Buffer.from("not a frame at all")), null);
+});
+
+test("a TRUNCATED or corrupt stored file throws — it never reads as shorter text", async () => {
+ const bytes = await encodeStoredBytes(Buffer.from(BODY));
+ await assert.rejects(decodeStoredBytes(bytes.subarray(0, bytes.length - 12)), StoredTextCorruptError);
+ for (const off of [10, Math.floor(bytes.length / 2), bytes.length - 2]) {
+ const bad = Buffer.from(bytes);
+ bad[off] ^= 0xff;
+ await assert.rejects(decodeStoredBytes(bad), StoredTextCorruptError, `flipped byte ${off}`);
+ }
+ await assert.rejects(decodeStoredBytes(Buffer.from("plain text")), StoredTextCorruptError);
+});
+
+test("readStoredText: plain first, else the stored form, else ENOENT", async () => {
+ const d = await dir("read");
+ await assert.rejects(readStoredText(d, CHAT, "utf8"), { code: "ENOENT" });
+ await writeFile(path.join(d, storedNameOf(CHAT)), await encodeStoredBytes(Buffer.from(BODY)));
+ assert.equal(await readStoredText(d, CHAT, "utf8"), BODY);
+ assert.ok((await readStoredText(d, CHAT)).equals(Buffer.from(BODY)));
+ // Both: the plain one is the truth.
+ await writeFile(path.join(d, CHAT), "NEWER\n");
+ assert.equal(await readStoredText(d, CHAT, "utf8"), "NEWER\n");
+ // A name that is not declared never reads a `.zst`.
+ await writeFile(path.join(d, "other.json.zst"), await encodeStoredBytes(Buffer.from("x")));
+ await assert.rejects(readStoredText(d, "other.json", "utf8"), { code: "ENOENT" });
+});
+
+test("a dangling plain link (an interrupted removal) reads the stored form", async () => {
+ const d = await dir("dangling");
+ await symlink("../nowhere/transcript.live_chat.json", path.join(d, CHAT));
+ await writeFile(path.join(d, storedNameOf(CHAT)), await encodeStoredBytes(Buffer.from(BODY)));
+ assert.equal(await readStoredText(d, CHAT, "utf8"), BODY);
+ // A listing (lstat) still has the plain name; a stat falls through.
+ assert.equal((await statStoredText(d, CHAT, { link: true })).form, "plain");
+ assert.equal((await statStoredText(d, CHAT)).form, "zst");
+});
+
+test("statStoredText answers the plain file's mtimeMs from the stored form, exactly", async () => {
+ const d = await dir("mtime");
+ const plain = path.join(d, CHAT);
+ await writeFile(plain, BODY);
+ // A nanosecond-precision time, as ext4 keeps them.
+ await utimes(plain, 1763700000.123456, 1763700000.987654);
+ const before = (await lstat(plain)).mtimeMs;
+ const { storeFixture } = await import("../testing/storedTextFixture");
+ await storeFixture(d, CHAT);
+ assert.equal(await storedTextMtimeMs(d, CHAT, { link: true }), before);
+ assert.equal(await storedTextMtimeMs(d, CHAT), before);
+ assert.equal(await storedTextMtimeMs(d, "transcript.de.vtt"), null);
+});
+
+test("existence, forms, logical size and the logical readdir", async () => {
+ const d = await dir("exists");
+ assert.equal(await storedTextExists(d, CHAT), false);
+ assert.equal(await storedTextForms(d, CHAT), null);
+ await writeFile(path.join(d, storedNameOf(CHAT)), await encodeStoredBytes(Buffer.from(BODY)));
+ await writeFile(path.join(d, "metadata.info.json"), "{}");
+ assert.equal(await storedTextExists(d, CHAT), true);
+ assert.equal(await storedTextForms(d, CHAT), "zst");
+ assert.equal(await storedTextLogicalSize(d, CHAT), Buffer.byteLength(BODY));
+ assert.ok((await stat(path.join(d, storedNameOf(CHAT)))).size < Buffer.byteLength(BODY) / 5);
+ assert.deepEqual((await readdirLogical(d)).sort(), ["metadata.info.json", CHAT]);
+ await writeFile(path.join(d, CHAT), BODY);
+ assert.equal(await storedTextForms(d, CHAT), "both");
+ assert.equal(await storedTextLogicalSize(d, CHAT), Buffer.byteLength(BODY));
+ assert.deepEqual(await readdirLogical(path.join(d, "missing")), []);
+ assert.equal((await readFile(path.join(d, CHAT), "utf8")).length, BODY.length);
+});
diff --git a/common/lib/storedText.ts b/common/lib/storedText.ts
@@ -0,0 +1,85 @@
+// STORED TEXT — a big, rarely read text file kept on disk as one zstd frame,
+// under its own name plus `.zst` (`transcript.live_chat.json.zst`), and read
+// back as if it were the plain file. Pure: names only, no fs (the read path is
+// lib/storedText-server.ts, the compressor and the one deleter
+// lib/storedText-write-server.ts).
+//
+// DECLARED NAMES ONLY. A name is stored compressed only when it is in
+// STORED_TEXT_NAMES; for every other name `<name>.zst` means nothing here. The
+// raw live-chat replay is the one declared name today (lane text-compress,
+// slices 1–2: the media drive's tens of GB of chat). Captions are a later
+// slice; `metadata.info.json` is out of scope.
+//
+// THE RULE: PLAIN, WHEN PRESENT, IS THE TRUTH. Every writer keeps writing the
+// plain name (yt-dlp, the chat fetch); none has to know about the stored form.
+// When both are present the plain one is either the latest write or a
+// compression that has not finished — reading it is right in both cases.
+//
+// TWO KINDS OF LISTING. One used to MATCH names (is the chat on disk, which
+// tracks are there, what to fetch) is LOGICAL: `logicalEntries` reports each
+// declared `X.zst` as `X`. One used to OPERATE on every entry as a file (the
+// files card, the movers, the byte walk) stays PHYSICAL: there the `.zst` is a
+// file with its own name and size.
+
+import { LIVE_CHAT_MEDIA_FILENAME } from "./mediaTier";
+
+export const STORED_TEXT_SUFFIX = ".zst";
+
+// The names stored compressed. One state per name, whatever its size: simpler
+// to test than "compressed when big".
+export const STORED_TEXT_NAMES: readonly string[] = Object.freeze([LIVE_CHAT_MEDIA_FILENAME]);
+
+const DECLARED = new Set(STORED_TEXT_NAMES);
+
+export function isStoredTextName(name: string): boolean {
+ return DECLARED.has(name);
+}
+
+export function storedNameOf(name: string): string {
+ return `${name}${STORED_TEXT_SUFFIX}`;
+}
+
+// The plain name a stored file stands for, or null when `name` is not the
+// stored form of a declared name.
+export function plainNameOf(name: string): string | null {
+ if (!name.endsWith(STORED_TEXT_SUFFIX)) return null;
+ const plain = name.slice(0, -STORED_TEXT_SUFFIX.length);
+ return DECLARED.has(plain) ? plain : null;
+}
+
+// The name a listing that MATCHES reports for this entry.
+export function logicalNameOf(name: string): string {
+ return plainNameOf(name) ?? name;
+}
+
+// A readdir's names as a matching listing: each declared `X.zst` reported as
+// `X`, deduped (both forms present are one file), first-seen order kept.
+export function logicalEntries(entries: Iterable<string>): string[] {
+ const out: string[] = [];
+ const seen = new Set<string>();
+ for (const e of entries) {
+ const n = logicalNameOf(e);
+ if (seen.has(n)) continue;
+ seen.add(n);
+ out.push(n);
+ }
+ return out;
+}
+
+// Does this PHYSICAL listing hold `name` in either form?
+export function listingHas(entries: readonly string[], name: string): boolean {
+ if (entries.includes(name)) return true;
+ return isStoredTextName(name) && entries.includes(storedNameOf(name));
+}
+
+export type StoredForms = "plain" | "zst" | "both";
+
+// Which forms of a declared `name` a physical listing holds, or null for none.
+export function storedFormsIn(entries: readonly string[], name: string): StoredForms | null {
+ const plain = entries.includes(name);
+ const zst = isStoredTextName(name) && entries.includes(storedNameOf(name));
+ if (plain && zst) return "both";
+ if (plain) return "plain";
+ if (zst) return "zst";
+ return null;
+}
diff --git a/common/lib/videoStatus.ts b/common/lib/videoStatus.ts
@@ -2,6 +2,7 @@ import path from "node:path";
import { readdir, readFile, stat } from "node:fs/promises";
import { isPartAudioFile, isRealAudioFile } from "./mediaFiles";
import { parseVtt, type Cue } from "./vtt";
+import { logicalEntries } from "./storedText";
export type VideoFiles = {
hasMeta: boolean;
@@ -272,8 +273,12 @@ export async function readVideoFiles(
};
}
+// A LOGICAL listing (lib/storedText.ts): a chat stored as
+// `transcript.live_chat.json.zst` is the `live_chat` track under its plain
+// name — the name every reader of the track's bytes opens through
+// lib/storedText-server.ts.
export async function readSubTracks(videoDir: string): Promise<SubTrack[]> {
- const entries = await readdir(videoDir).catch(() => [] as string[]);
+ const entries = logicalEntries(await readdir(videoDir).catch(() => [] as string[]));
const tracks: SubTrack[] = [];
for (const entry of entries) {
if (entry === WHISPER_FILENAME) continue;
diff --git a/common/testing/storedTextChild.ts b/common/testing/storedTextChild.ts
@@ -0,0 +1,13 @@
+// A SECOND PROCESS for the stored-text tests (lib/storedText.lock.test.ts): runs
+// one compress or restore on one file, slowly (each read chunk waits `delayMs`),
+// and prints its outcome as JSON. Temp dirs only.
+//
+// tsx testing/storedTextChild.ts <compress|restore> <videoDir> <name> <delayMs>
+
+import { compressStoredText, restoreStoredText } from "../lib/storedText-write-server";
+
+const [mode, videoDir, name, delay] = process.argv.slice(2);
+const throttle = () => new Promise<void>((resolve) => setTimeout(resolve, Number(delay)));
+const opts = { reserveBytes: 0, throttle };
+const out = mode === "restore" ? await restoreStoredText(videoDir, name, opts) : await compressStoredText(videoDir, name, opts);
+process.stdout.write(JSON.stringify(out));
diff --git a/common/testing/storedTextFixture.ts b/common/testing/storedTextFixture.ts
@@ -0,0 +1,40 @@
+// Tests' twin of the stored-text compressor (lib/storedText-write-server.ts):
+// a fixture file put into its stored form the way the compressor leaves it —
+// `<name>.zst` beside it with the plain file's times (numeric seconds), a
+// tier link's stored bytes beside its target in `media/<id>/` with a link of
+// the plain link's times — and the plain form removed (or kept, `keepPlain`).
+// Temp dirs only.
+
+import path from "node:path";
+import { lstat, lutimes, readFile, readlink, rm, stat, symlink, utimes, writeFile } from "node:fs/promises";
+import { encodeStoredBytes } from "../lib/storedText-server";
+import { storedNameOf } from "../lib/storedText";
+
+export async function storeFixture(
+ videoDir: string,
+ name: string,
+ opts: { keepPlain?: boolean } = {},
+): Promise<void> {
+ const plain = path.join(videoDir, name);
+ const l = await lstat(plain);
+ if (l.isSymbolicLink()) {
+ const rel = await readlink(plain);
+ const target = path.resolve(videoDir, rel);
+ const st = await stat(target);
+ const storedBytes = path.join(path.dirname(target), storedNameOf(name));
+ await writeFile(storedBytes, await encodeStoredBytes(await readFile(target)));
+ await utimes(storedBytes, st.atimeMs / 1000, st.mtimeMs / 1000);
+ const link = path.join(videoDir, storedNameOf(name));
+ await symlink(path.join(path.dirname(rel), storedNameOf(name)), link);
+ await lutimes(link, l.atimeMs / 1000, l.mtimeMs / 1000);
+ if (!opts.keepPlain) {
+ await rm(target);
+ await rm(plain);
+ }
+ return;
+ }
+ const stored = path.join(videoDir, storedNameOf(name));
+ await writeFile(stored, await encodeStoredBytes(await readFile(plain)));
+ await utimes(stored, l.atimeMs / 1000, l.mtimeMs / 1000);
+ if (!opts.keepPlain) await rm(plain);
+}
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
@@ -70,6 +70,7 @@ import { evaluateDownloadFilters } from "../lib/downloadFilters";
import { normalizeLiveChat } from "../controller/normalizeLiveChat";
import { writeCuesAfterDownload } from "../controller/normalizeTranscript";
import { LIVE_CHAT_FILENAME } from "../lib/videoStatus";
+import { listingHas, storedFormsIn } from "../lib/storedText";
import {
upsertMetadataScan,
type MetadataScanEntry,
@@ -291,9 +292,16 @@ export type ManagedDownloadOpts = {
// "no transcript" and fetches the media (attempt 3). Any other error is still
// an ERROR and a non-zero exit. `--sleep-subtitles` is the pace before each
// subtitle request — the request YouTube throttles — never below `-t sleep`'s 5.
-function youtubeHandlingArgs(
+//
+// A CHAT ALREADY STORED (`chatStored`, lib/storedText.ts): yt-dlp's own
+// "already present" skip looks for the plain `transcript.live_chat.json`, so
+// over a compressed one it would fetch the whole replay again. The chat is
+// left out of the sub-langs instead, as for a `later` channel. Exported for
+// its test.
+export function youtubeHandlingArgs(
config: ChannelConfig,
reuseInfoJson = false,
+ chatStored = false,
): string[] {
const args = [
"--write-auto-subs",
@@ -301,7 +309,7 @@ function youtubeHandlingArgs(
"--sub-langs",
// Without the live chat unless the channel fetches it with the download
// (ChannelConfig.chat).
- effectiveSubLangs(config),
+ effectiveSubLangs(chatStored ? { ...config, chat: "later" } : config),
];
if (!reuseInfoJson) args.push("--write-info-json");
args.push(
@@ -614,7 +622,8 @@ export function liveChatOnlyArgs(
// a metadata.info.json is the leftover this slice exists to stop creating.
async function hasLiveChatOnDisk(videoDir: string): Promise<boolean> {
const entries = await readdir(videoDir).catch(() => [] as string[]);
- return entries.includes(LIVE_CHAT_FILENAME);
+ // Either form (lib/storedText.ts).
+ return listingHas(entries, LIVE_CHAT_FILENAME);
}
function attemptSucceeded(exitCode: number | null): boolean {
@@ -1106,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`,
);
@@ -1292,11 +1323,18 @@ async function runManagedDownload(
// its own args; youtube handling downloads subtitles (the persistence plan only
// applies to the no-subs fallback below). For transcribe handling the plan
// chooses audio-only vs. keep-source-video and yt-dlp vs. app extraction.
+ const chatStored =
+ opts.channelConfig.handling === "youtube" && canonicalId
+ ? storedFormsIn(
+ await readdir(path.join(channelDir, "data", canonicalId)).catch(() => [] as string[]),
+ LIVE_CHAT_FILENAME,
+ ) === "zst"
+ : false;
const mediaArgs =
opts.channelConfig.handling === "youtube"
? [
...outputArgsForUrl(opts.videoUrl),
- ...youtubeHandlingArgs(opts.channelConfig, reuseInfoJson),
+ ...youtubeHandlingArgs(opts.channelConfig, reuseInfoJson, chatStored),
]
: transcribeMediaArgs(
opts.videoUrl,
diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts
@@ -2,6 +2,7 @@
// process's outward doors refuse before any request.
import "../lib/noNetwork.mjs";
import { tierChannelMedia } from "../lib/mediaTier-server";
+import { logicalEntries, storedFormsIn } from "../lib/storedText";
import path from "node:path";
import { mkdir, readdir, readFile } from "node:fs/promises";
import { writeFileAtomic } from "../lib/jsonFile-server";
@@ -26,7 +27,7 @@ import {
platformMinGapSeconds,
staticSleepRequestsSeconds,
} from "./channelArgs";
-import { isRealAudioFile } from "../lib/videoStatus";
+import { isRealAudioFile, LIVE_CHAT_FILENAME } from "../lib/videoStatus";
import { readVttProvenance } from "../lib/subtitleProvenance";
import { extractVideoId } from "../lib/videoId";
import type { Paths } from "../lib/paths";
@@ -1482,10 +1483,21 @@ function compileSubLangMatcher(spec: string): (track: string) => boolean {
const SUB_EXT_PATTERN = "(?:vtt|json|json3|srv1|srv2|srv3)";
-function trackOnDisk(entries: string[], track: string): boolean {
+// One video's `--sub-langs` for the missing-subs fetch. A chat stored
+// compressed (lib/storedText.ts) is on disk, but yt-dlp's own "already
+// present" skip looks for the plain name and would fetch the whole replay
+// again: it is left out, as for a `later` channel. Exported for its test.
+export function subLangsForVideo(entries: readonly string[], subLangs: string): string {
+ if (storedFormsIn(entries, LIVE_CHAT_FILENAME) !== "zst") return subLangs;
+ return effectiveSubLangs({ subLangs, chat: "later" });
+}
+
+// Over a LOGICAL listing (lib/storedText.ts): a chat stored as
+// `transcript.live_chat.json.zst` is on disk. Exported for its test.
+export function trackOnDisk(entries: string[], track: string): boolean {
const escaped = track.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
const re = new RegExp(`^transcript\\.${escaped}\\.${SUB_EXT_PATTERN}$`);
- return entries.some((e) => re.test(e));
+ return logicalEntries(entries).some((e) => re.test(e));
}
// Fetch only the missing subtitle tracks for one already-downloaded video.
@@ -1545,6 +1557,7 @@ async function downloadMissingSubs(opts: RunYtdlpOpts): Promise<void> {
const matchesSubLang = compileSubLangMatcher(subLangs);
const tofetch: string[] = [];
+ const subLangsFor = new Map<string, string>();
let upToDate = 0;
let unidentifiable = 0;
let noMetadata = 0;
@@ -1609,6 +1622,8 @@ async function downloadMissingSubs(opts: RunYtdlpOpts): Promise<void> {
continue;
}
tofetch.push(url);
+ const own = subLangsForVideo(entries, subLangs);
+ if (own !== subLangs) subLangsFor.set(url, own);
}
opts.onLog(
@@ -1678,7 +1693,7 @@ async function downloadMissingSubs(opts: RunYtdlpOpts): Promise<void> {
task ? { ...opts, onLog: task.onLog } : opts,
root,
url,
- subLangs,
+ subLangsFor.get(url) ?? subLangs,
);
// yt-dlp exited clean. A subtitle 429 it reported anyway (a WARNING)
// is still a deferral; otherwise the subtitles came down and the
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -63,6 +63,22 @@
- The copy that already has the work keeps it whatever the order, and a copy never waits behind one that is itself
held or skipped. Downloads, files, records and the published sites are unchanged, and no time is mapped between
copies. Removing the group, or a channel from it, restores the lanes at once.
+- **Raw live chats can be stored compressed: `pnpm ops compress-text`.**
+ - `transcript.live_chat.json` becomes `transcript.live_chat.json.zst` (zstd, about 5 % of the size). Every reader
+ of the raw chat reads either form, with the same times, so the index sees no change and no chat is fetched again.
+ - 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 auto-caption purge, the clear-transcript fix) removes both forms. On the video's files card
+ only the file named goes, never its other form, and the card says when 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 stored capture is kept as `chat-capture-kept.<stamp>.json.zst` and never
+ removed automatically; the log compares both. An empty replay leaves the stored capture the chat.
+ - Two different captures are never settled by deleting one. A second editor process waits for a video's lock.
- **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/compress-text/route.test.ts b/editor/app/api/ops/compress-text/route.test.ts
@@ -0,0 +1,76 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/compress-text/route.test.ts"
+//
+// The body's shape and the refusals that come before any job, then a dry run
+// that answers per channel and writes nothing. Nothing is compressed here.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "compress-text-route-"));
+process.env.WORKER_TOKEN = "test-token";
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+const { POST } = await import("./route");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const videoDir = path.join(ROOT, "channels", "synth", "data", "aaaaaaaaaaa");
+await mkdir(videoDir, { recursive: true });
+await writeFile(path.join(ROOT, "channels", "synth", "config.json"), JSON.stringify({ handling: "youtube" }));
+await writeFile(path.join(videoDir, "transcript.live_chat.json"), '{"replayChatItemAction":{}}\n'.repeat(100));
+
+async function post(body: Record<string, unknown>) {
+ const res = await POST(
+ new Request("http://localhost/api/ops/compress-text", {
+ method: "POST",
+ headers: { authorization: "Bearer test-token", "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+ return { status: res.status, json: (await res.json()) as Record<string, unknown> };
+}
+
+test("refusals before any job", async () => {
+ const cases: [Record<string, unknown>, RegExp][] = [
+ [{ force: true }, /unknown key\(s\): force/],
+ [{ slugs: ["../x"] }, /not a valid channel slug/],
+ [{ slugs: ["nope"], dryRun: true }, /Channel\(s\) not found: nope/],
+ [{ kinds: ["captions"] }, /"kinds" must be a list of: live-chat/],
+ [{ limit: 0 }, /limit/],
+ [{ limit: 5 }, /"limit" is per channel: name exactly one in "slugs"/],
+ [{ dryRun: true, verify: true }, /two different runs/],
+ [{ restore: true, verify: true }, /two different runs/],
+ [{ restore: "yes" }, /restore/],
+ ];
+ for (const [body, re] of cases) {
+ const r = await post(body);
+ assert.equal(r.status, 400, JSON.stringify(body));
+ assert.match(String(r.json.error), re, JSON.stringify(body));
+ }
+});
+
+test("a dry run answers per channel and writes nothing", async () => {
+ const before = (await stat(path.join(videoDir, "transcript.live_chat.json"))).mtimeMs;
+ const r = await post({ dryRun: true, kinds: ["live-chat"] });
+ assert.equal(r.status, 200, JSON.stringify(r.json));
+ const result = r.json.result as { channels: { slug: string; plainFiles: number; plainBytes: number }[] };
+ const synth = result.channels.find((c) => c.slug === "synth");
+ assert.equal(synth?.plainFiles, 1);
+ assert.equal(synth?.plainBytes, '{"replayChatItemAction":{}}\n'.length * 100);
+ assert.deepEqual(await readdir(videoDir), ["transcript.live_chat.json"]);
+ assert.equal((await stat(path.join(videoDir, "transcript.live_chat.json"))).mtimeMs, before);
+});
+
+test("a restore's dry run answers the stored files and writes nothing", async () => {
+ const r = await post({ dryRun: true, restore: true });
+ assert.equal(r.status, 200, JSON.stringify(r.json));
+ const result = r.json.result as { restore: boolean; channels: { slug: string; storedFiles: number; pending: number }[] };
+ assert.equal(result.restore, true);
+ const synth = result.channels.find((c) => c.slug === "synth");
+ assert.equal(synth?.storedFiles, 0, "nothing is stored here");
+ assert.equal(synth?.pending, 0);
+ assert.deepEqual(await readdir(videoDir), ["transcript.live_chat.json"]);
+});
diff --git a/editor/app/api/ops/compress-text/route.ts b/editor/app/api/ops/compress-text/route.ts
@@ -0,0 +1,61 @@
+import { NextResponse } from "next/server";
+import { compressTextAction } from "../../../storage/compressTextActions";
+import { OpsInputError, ops, opsFail, optBool, optPositiveInt, reqSlugs, type OpsBody } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slugs?, kinds?, dryRun?, limit?, verify?, restore? }
+// dryRun -> { ok: true, dryRun: true, result: { channels: [{ slug, plainFiles,
+// plainBytes, storedFiles, storedBytes, storedLogicalBytes,
+// estimateAfterBytes, free }], lines } }
+// else -> { ok: true, dryRun: false, verify, jobs: [{ slug, jobId }], jobIds,
+// jobId (one job only), skipped: [{ slug, reason }] }
+//
+// The raw live-chat replays put into their stored form, `transcript.live_chat.json`
+// → `transcript.live_chat.json.zst` (lib/storedText.ts; lane text-compress):
+// one file at a time — written beside, fsynced, read back and hashed against
+// the original, the original then removed through removeMediaFile. A crash at
+// any step leaves a whole copy and the next run finishes. Paced (render mode
+// waits it; slower while a live recording runs); a file written in the last
+// 10 minutes, with a `.part` beside it, whose video is recording or busy, or
+// on a drive that does not answer, is left alone and counted. Both forms with
+// different content are refused and both kept. `dryRun` writes nothing;
+// `verify` decodes every stored file and writes nothing; `limit` counts files
+// compressed by the job, 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); a re-run continues. Started by a person only: a restart never
+// re-queues or resumes one.
+// `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 stored file removed); with
+// `dryRun` it answers the stored files, their plain bytes and the free space.
+// Run it BEFORE reverting or running an older checkout (OPERATING.md).
+// `kinds`: what to compress. Only the raw live chat is a stored name today.
+function optKinds(body: OpsBody): void {
+ if (body.kinds === undefined) return;
+ if (!Array.isArray(body.kinds) || body.kinds.length === 0 || body.kinds.some((k) => k !== "live-chat")) {
+ throw new OpsInputError('"kinds" must be a list of: live-chat');
+ }
+}
+
+export async function POST(request: Request) {
+ return ops(request, ["slugs", "kinds", "dryRun", "limit", "verify", "restore"], async (body) => {
+ optKinds(body);
+ const dryRun = optBool(body, "dryRun") ?? false;
+ const verify = optBool(body, "verify") ?? false;
+ const restore = optBool(body, "restore") ?? false;
+ if (dryRun && verify) return opsFail('"dryRun" and "verify" are two different runs: ask one');
+ if (restore && verify) return opsFail('"restore" and "verify" are two different runs: ask one');
+ const limit = optPositiveInt(body, "limit");
+ const result = await compressTextAction({
+ ...(body.slugs !== undefined ? { slugs: reqSlugs(body, "slugs") } : {}),
+ dryRun,
+ verify,
+ restore,
+ ...(limit !== undefined ? { limit } : {}),
+ });
+ if (!result.ok) return opsFail(result.error);
+ if (result.dryRun) return NextResponse.json(result);
+ return NextResponse.json({ ...result, ...(result.jobIds.length === 1 ? { jobId: result.jobIds[0] } : {}) });
+ });
+}
diff --git a/editor/app/api/ops/delete-file/route.ts b/editor/app/api/ops/delete-file/route.ts
@@ -12,7 +12,10 @@ export const dynamic = "force-dynamic";
// the button refuses: a name that is not one entry of the directory, a file on
// a media drive that is not mounted or not answering (nothing is deleted), a
// channel whose drive is not answering, something that is not a regular file.
-// The channel's report is refreshed after. No undo.
+// The channel's report is refreshed after. No undo. A stored text file
+// (`transcript.live_chat.json` / `.zst`, lib/storedText.ts) named in one form
+// while the other is there: only the named one goes, never the other, and
+// `note` says the other is still there (same content or not).
export async function POST(request: Request) {
return ops(request, ["slug", "id", "file"], async (body) => {
const res = await deleteVideoFileAction(
@@ -21,6 +24,6 @@ export async function POST(request: Request) {
reqString(body, "file"),
);
if (!res.ok) return opsFail(res.error);
- return NextResponse.json({ ok: true });
+ return NextResponse.json({ ok: true, ...(res.note ? { note: res.note } : {}) });
});
}
diff --git a/editor/app/api/ops/fetch-chat/route.ts b/editor/app/api/ops/fetch-chat/route.ts
@@ -20,11 +20,21 @@ 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 stored capture is first KEPT as
+// `chat-capture-kept.<UTC stamp>.json.zst` (no reader of the chat sees it; it
+// is never removed automatically), then the replay is fetched. A replay with
+// messages becomes the chat; an empty one is kept too and, like no replay at
+// all, leaves the stored capture the chat. The job log gives both captures'
+// bytes, message counts and first/last message times. 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]/lib/fixIncompleteTranscript.ts b/editor/app/channels/[slug]/lib/fixIncompleteTranscript.ts
@@ -10,6 +10,7 @@
// short transcript. The fix MUST re-fetch the audio first.
import { removeMediaFile } from "yt-dlp-transcript-common/lib/mediaTier-server";
+import { removeStoredText } from "yt-dlp-transcript-common/lib/storedText-write-server";
import path from "node:path";
import { readdir } from "node:fs/promises";
import type { ChannelConfig } from "yt-dlp-transcript-common/lib/channelConfig";
@@ -151,8 +152,11 @@ export async function clearIncompleteTranscriptOne(opts: {
name === "transcript.cues.json",
);
for (const name of toRemove) {
- // Through its link when tiered (release 17): the bytes go too.
- await removeMediaFile(resolved, name);
+ // Through its link when tiered (release 17): the bytes go too. A caption
+ // track in both forms (lib/storedText-write-server.ts): a stored copy left
+ // behind would bring the cleared transcript back.
+ if (isTranscriptVtt(name)) await removeStoredText(resolved, name);
+ else await removeMediaFile(resolved, name);
}
return { removed: toRemove.length };
}
diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/FilesList.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/FilesList.tsx
@@ -76,6 +76,7 @@ function DeleteFileButton({
}) {
const [pending, startTransition] = useTransition();
const [error, setError] = useState<string | null>(null);
+ const [note, setNote] = useState<string | null>(null);
return (
<div className="flex items-center gap-2">
<button
@@ -85,9 +86,11 @@ function DeleteFileButton({
onClick={() => {
if (!confirm(`Delete ${filename}?`)) return;
setError(null);
+ setNote(null);
startTransition(async () => {
const res = await deleteVideoFileAction(slug, videoId, filename);
if (!res.ok) setError(res.error);
+ else if (res.note) setNote(res.note);
});
}}
className="self-start px-2 py-1 rounded border border-destructive/30 text-destructive text-xs hover:bg-destructive-soft disabled:opacity-50"
@@ -102,6 +105,11 @@ function DeleteFileButton({
{error}
</span>
)}
+ {note && (
+ <span className="text-xs text-muted-foreground" aria-label={`delete note ${filename}`}>
+ {note}
+ </span>
+ )}
</div>
);
}
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/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -60,6 +60,7 @@ import {
} from "yt-dlp-transcript-common/lib/channelMedia";
import { onDrive } from "yt-dlp-transcript-common/lib/storageHealth";
import { isTierable } from "yt-dlp-transcript-common/lib/mediaTier";
+import { removeStoredTextForm } from "yt-dlp-transcript-common/lib/storedText-write-server";
import { setExcludedFromTruncatedCheck } from "yt-dlp-transcript-common/lib/excludeTruncatedCheck-server";
import { pinTranscript } from "yt-dlp-transcript-common/lib/transcriptPin-server";
import { readVideoTracks } from "yt-dlp-transcript-common/lib/captionTracks-server";
@@ -1012,7 +1013,7 @@ export async function deleteVideoFileAction(
slug: string,
videoId: string,
filename: string,
-): Promise<{ ok: true } | { ok: false; error: string }> {
+): Promise<{ ok: true; note?: string } | { ok: false; error: string }> {
const videoDir = videoDirOf(slug, videoId);
const target = safeJoinUnderDir(videoDir, filename);
if (!target) {
@@ -1072,10 +1073,27 @@ export async function deleteVideoFileAction(
return { ok: false, error: `Not a regular file: ${filename}` };
}
// Through its link when the file is tiered (release 17): the bytes on the
- // media tier go too, never orphaned behind a removed link.
- await removeMediaFile(videoDir, path.basename(target));
+ // media tier go too, never orphaned behind a removed link. A declared stored
+ // name (lib/storedText.ts) is one file in two forms: only the one named goes,
+ // never the other; the answer says when the other is still here.
+ const out = await removeStoredTextForm(videoDir, path.basename(target));
+ if (out === "busy") {
+ return { ok: false, error: `${filename} not deleted: it is being compressed or restored right now. Try again in a moment.` };
+ }
revalidatePath(`/channels/${slug}/videos/${videoId}`);
requestChannelSnapshot(getPaths(), slug);
+ if (out.kept) {
+ const k = out.kept;
+ return {
+ ok: true,
+ note:
+ k.same === "same"
+ ? `Deleted ${filename} only. ${k.name} is still here with the same content: readers still see the chat.`
+ : k.same === "differs"
+ ? `Deleted ${filename} only. ${k.name} is still here with different content, and is the file readers read.`
+ : `Deleted ${filename} only. ${k.name} is still here (it could not be read whole to compare).`,
+ };
+ }
return { ok: true };
}
diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts
@@ -19,6 +19,7 @@ import type { AudioFormat } from "yt-dlp-transcript-common/lib/channelConfig";
import { isSourceVideoQuality } from "yt-dlp-transcript-common/ytdlp/downloadFormat";
import { isPersistReplacePolicy } from "yt-dlp-transcript-common/controller/persistVideos";
import { compactChannelVideosAction } from "../saved-videos/compactActions";
+import { compressTextJobAction } from "../storage/compressTextActions";
import {
downloadAction,
downloadMissingAction,
@@ -625,6 +626,17 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = {
},
// The same list, mode and overrides: a replay (a person's Retry) resumes at
// the first chunk not encoded and skips what is already compacted.
+ // The same channel, limit and mode: a replay (a person's Retry) re-walks
+ // and continues — every file already stored is skipped.
+ "compress-text": (spec) => {
+ const { p } = params(spec);
+ const limit = num(p.limit);
+ return compressTextJobAction(spec.slug, {
+ ...(limit !== undefined ? { limit } : {}),
+ ...(p.verify === true ? { verify: true } : {}),
+ ...(p.restore === true ? { restore: true } : {}),
+ });
+ },
"compact-saved-videos": (spec) => {
const { p } = params(spec);
return compactChannelVideosAction(spec.slug, strings(p.ids) ?? [], {
diff --git a/editor/app/storage/compressTextActions.ts b/editor/app/storage/compressTextActions.ts
@@ -0,0 +1,168 @@
+"use server";
+
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { listChannelSlugs } from "yt-dlp-transcript-common/controller/channels";
+import {
+ COMPRESS_RATE_BYTES,
+ COMPRESS_RATE_RECORDING_BYTES,
+ compressText,
+ type CompressTextResult,
+} from "yt-dlp-transcript-common/controller/compressText";
+import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
+import {
+ runManagedFunction,
+ type StreamActionResult,
+} from "yt-dlp-transcript-common/jobs/streamCommand";
+import { waitWhileRenderHeld } from "yt-dlp-transcript-common/lib/renderHold";
+
+// COMPRESS TEXT: the `compress-text` job, as `pnpm ops compress-text` posts it
+// (`/api/ops/compress-text`). The work and its rules are
+// common/controller/compressText.ts and lib/storedText-write-server.ts.
+//
+// ONE QUEUE MACHINE-WIDE, ONE JOB PER CHANNEL: one file at a time across every
+// channel. Per channel because the job is a media writer of THAT channel —
+// the media guard asks it before the job starts, and a move of the channel's
+// media refuses while it runs (`channelMediaWriters` finds it by its slug).
+// So `limit` is per job, and is taken only with one channel named. STARTED BY
+// A PERSON ONLY (jobKinds.ts `startedByPerson`): a restart closes a queued one
+// and resumes no interrupted one — it removes originals (a restore: stored
+// copies); the job's Retry (a person) re-runs it, and a re-run continues.
+const COMPRESS_QUEUE = "compress-text";
+
+export type CompressTextActionResult =
+ | { ok: false; error: string }
+ | { ok: true; dryRun: true; result: CompressTextResult }
+ | {
+ ok: true;
+ dryRun: false;
+ verify: boolean;
+ restore: boolean;
+ jobs: { slug: string; jobId: string }[];
+ jobIds: string[];
+ skipped: { slug: string; reason: string }[];
+ };
+
+// A job running for this video: one of its own, or a batch with a task on it.
+// The compress job itself is not counted.
+function videoBusy(slug: string, id: string, self: string): boolean {
+ return getRegistry()
+ .list()
+ .some(
+ (j) =>
+ j.id !== self &&
+ j.status === "running" &&
+ j.channelSlug === slug &&
+ (j.videoId === id || (j.tasks ?? []).some((t) => t.id === id)),
+ );
+}
+
+// A live recording in progress anywhere: the reads go slower.
+function recordingRunning(): boolean {
+ return getRegistry()
+ .list()
+ .some((j) => j.kind === "record-live" && j.status === "running");
+}
+
+const sleep = (ms: number, signal?: AbortSignal) =>
+ new Promise<void>((resolve) => {
+ const t = setTimeout(resolve, ms);
+ signal?.addEventListener(
+ "abort",
+ () => {
+ clearTimeout(t);
+ resolve();
+ },
+ { once: true },
+ );
+ });
+
+export async function compressTextJobAction(
+ slug: string,
+ opts: { limit?: number; verify?: boolean; restore?: boolean } = {},
+): Promise<StreamActionResult> {
+ const paths = getPaths();
+ return runManagedFunction({
+ kind: "compress-text",
+ queueKey: COMPRESS_QUEUE,
+ paths,
+ channelSlug: slug,
+ spec: {
+ kind: "compress-text",
+ slug,
+ params: {
+ ...(opts.limit !== undefined ? { limit: opts.limit } : {}),
+ ...(opts.verify ? { verify: true } : {}),
+ ...(opts.restore ? { restore: true } : {}),
+ },
+ },
+ fn: async (onLog, signal, _progress, ctx) => {
+ const result = await compressText({
+ paths,
+ slugs: [slug],
+ ...(opts.limit !== undefined ? { limit: opts.limit } : {}),
+ ...(opts.verify ? { verify: true } : {}),
+ ...(opts.restore ? { restore: true } : {}),
+ onLog,
+ signal,
+ drainSignal: ctx.drainSignal,
+ isBusy: (s, id) => videoBusy(s, id, ctx.jobId),
+ rate: () => (recordingRunning() ? COMPRESS_RATE_RECORDING_BYTES : COMPRESS_RATE_BYTES),
+ waitForRender: () =>
+ waitWhileRenderHeld({ sleep, onLog: (l) => onLog(`${l}\n`), what: "compress-text", signal }),
+ sleep,
+ });
+ const failed = result.channels.reduce((a, c) => a + (c.failed?.length ?? 0) + (c.problems?.length ?? 0), 0);
+ if (result.stopped === "cancelled") throw new Error("Stopped: cancelled. A re-run continues.");
+ if (failed > 0) throw new Error(`${failed} file(s) failed or did not verify — see the lines above.`);
+ },
+ });
+}
+
+// `slugs` (default: every channel). A dry run answers with the plan and
+// writes nothing; a real run (a check, a restore) starts one job per channel
+// that has a raw chat to compress or a stopped run to finish (a stored one to
+// check, or to restore).
+export async function compressTextAction(input: {
+ slugs?: string[];
+ dryRun?: boolean;
+ verify?: boolean;
+ restore?: boolean;
+ limit?: number;
+}): Promise<CompressTextActionResult> {
+ const paths = getPaths();
+ const all = (await listChannelSlugs(paths)).sort();
+ const missing = (input.slugs ?? []).filter((s) => !all.includes(s));
+ if (missing.length) return { ok: false, error: `Channel(s) not found: ${missing.join(", ")}` };
+ if (input.limit !== undefined && input.slugs?.length !== 1) {
+ return { ok: false, error: '"limit" is per channel: name exactly one in "slugs"' };
+ }
+ const slugs = input.slugs ?? all;
+ const plan = await compressText({ paths, slugs, dryRun: true, ...(input.restore ? { restore: true } : {}), onLog: () => {} });
+ if (input.dryRun) return { ok: true, dryRun: true, result: plan };
+ const jobs: { slug: string; jobId: string }[] = [];
+ const skipped: { slug: string; reason: string }[] = [];
+ for (const line of plan.channels) {
+ if (line.refused) {
+ skipped.push({ slug: line.slug, reason: line.refused });
+ continue;
+ }
+ const work = input.verify ? line.storedFiles : (line.pending ?? 0);
+ if (work === 0) continue;
+ const r = await compressTextJobAction(line.slug, {
+ ...(input.limit !== undefined ? { limit: input.limit } : {}),
+ ...(input.verify ? { verify: true } : {}),
+ ...(input.restore ? { restore: true } : {}),
+ });
+ if (r.ok) jobs.push({ slug: line.slug, jobId: r.jobId });
+ else skipped.push({ slug: line.slug, reason: r.error });
+ }
+ return {
+ ok: true,
+ dryRun: false,
+ verify: input.verify === true,
+ restore: input.restore === true,
+ jobs,
+ jobIds: jobs.map((j) => j.jobId),
+ skipped,
+ };
+}
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -587,6 +587,9 @@ const ACTIONS = [
"compaction-markers",
// 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?, restore?}).
+ "compress-text",
// Write transcript.cues.json from each video's raw transcript ({slug, ids?,
// force?}) — what a reader with no index build wants.
"build-cues",
@@ -1783,7 +1786,9 @@ 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): only the named one goes,',
+ ' never the other, 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.)',
@@ -2076,6 +2081,14 @@ 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). The stored capture is first kept as chat-capture-kept.<UTC",
+ " stamp>.json.zst (no reader sees it; never removed automatically). A",
+ " replay with messages becomes the chat; an empty one is kept too and, like",
+ " no replay, leaves the stored capture the chat. The log gives both",
+ " captures' bytes, message counts and first/last message times. 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',
@@ -2482,6 +2495,37 @@ export function usage() {
' while its compaction runs). compact-saved-videos "reverify": true re-checks',
" one without encoding.",
"",
+ '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 read; the earlier content's stored copy is",
+ " kept beside it. The dry run lists earlier chat captures a re-fetch kept",
+ " (chat-capture-kept.*.json.zst), which nothing removes automatically.",
+ ' "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).",
+ "",
'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",